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
|
---|---|---|---|---|---|---|---|---|---|---|---|
8,400 | luci/luci-go | logdog/client/butlerproto/proto.go | WriteWith | func (w *Writer) WriteWith(fw recordio.Writer, b *logpb.ButlerLogBundle) error {
data, err := proto.Marshal(b)
if err != nil {
entries := b.GetEntries()
// TODO(tandrii, hinoka): leave just error after crbug.com/859995 is fixed.
if len(entries) > 100 {
return fmt.Errorf("butlerproto: failed to marshal Bundle of len %d with first 100 entries %s: %s",
len(entries), entries[:100], err)
} else {
return fmt.Errorf("butlerproto: failed to marshal Bundle %s: %s", entries, err)
}
}
return w.writeData(fw, logpb.ButlerMetadata_ButlerLogBundle, data)
} | go | func (w *Writer) WriteWith(fw recordio.Writer, b *logpb.ButlerLogBundle) error {
data, err := proto.Marshal(b)
if err != nil {
entries := b.GetEntries()
// TODO(tandrii, hinoka): leave just error after crbug.com/859995 is fixed.
if len(entries) > 100 {
return fmt.Errorf("butlerproto: failed to marshal Bundle of len %d with first 100 entries %s: %s",
len(entries), entries[:100], err)
} else {
return fmt.Errorf("butlerproto: failed to marshal Bundle %s: %s", entries, err)
}
}
return w.writeData(fw, logpb.ButlerMetadata_ButlerLogBundle, data)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"WriteWith",
"(",
"fw",
"recordio",
".",
"Writer",
",",
"b",
"*",
"logpb",
".",
"ButlerLogBundle",
")",
"error",
"{",
"data",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"entries",
":=",
"b",
".",
"GetEntries",
"(",
")",
"\n",
"// TODO(tandrii, hinoka): leave just error after crbug.com/859995 is fixed.",
"if",
"len",
"(",
"entries",
")",
">",
"100",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"entries",
")",
",",
"entries",
"[",
":",
"100",
"]",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"entries",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"writeData",
"(",
"fw",
",",
"logpb",
".",
"ButlerMetadata_ButlerLogBundle",
",",
"data",
")",
"\n",
"}"
] | // WriteWith writes a ButlerLogBundle to the supplied recordio.Writer. | [
"WriteWith",
"writes",
"a",
"ButlerLogBundle",
"to",
"the",
"supplied",
"recordio",
".",
"Writer",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerproto/proto.go#L261-L275 |
8,401 | luci/luci-go | gce/cmd/agent/connect.go | validateFlags | func (cmd *connectCmd) validateFlags(c context.Context) error {
switch {
case cmd.dir == "":
return errors.New("-dir is required")
// TODO(crbug/945063): Remove -server.
case cmd.provider == "" && cmd.server == "":
return errors.New("-provider or -server is required")
case cmd.user == "":
return errors.New("-user is required")
}
return nil
} | go | func (cmd *connectCmd) validateFlags(c context.Context) error {
switch {
case cmd.dir == "":
return errors.New("-dir is required")
// TODO(crbug/945063): Remove -server.
case cmd.provider == "" && cmd.server == "":
return errors.New("-provider or -server is required")
case cmd.user == "":
return errors.New("-user is required")
}
return nil
} | [
"func",
"(",
"cmd",
"*",
"connectCmd",
")",
"validateFlags",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"switch",
"{",
"case",
"cmd",
".",
"dir",
"==",
"\"",
"\"",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"// TODO(crbug/945063): Remove -server.",
"case",
"cmd",
".",
"provider",
"==",
"\"",
"\"",
"&&",
"cmd",
".",
"server",
"==",
"\"",
"\"",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"cmd",
".",
"user",
"==",
"\"",
"\"",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateFlags validates parsed command line flags. | [
"validateFlags",
"validates",
"parsed",
"command",
"line",
"flags",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/connect.go#L43-L54 |
8,402 | luci/luci-go | gce/cmd/agent/connect.go | Run | func (cmd *connectCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
c := cli.GetContext(app, cmd, env)
if err := cmd.validateFlags(c); err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
if cmd.server == ":metadata" {
meta := getMetadata(c)
srv, err := meta.Get("instance/attributes/swarming-server")
if err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
cmd.server = srv
}
if cmd.provider != "" {
meta := getMetadata(c)
name, err := meta.InstanceName()
if err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
if cmd.provider == ":metadata" {
cmd.provider, err = meta.Get("instance/attributes/provider")
if err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
}
prov := newInstances(c, cmd.serviceAccount, cmd.provider)
inst, err := prov.Get(c, &instances.GetRequest{
Hostname: name,
})
if err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
cmd.server = inst.Swarming
}
swr := getSwarming(c)
swr.server = cmd.server
if err := swr.Configure(c, cmd.dir, cmd.user); err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
return 0
} | go | func (cmd *connectCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
c := cli.GetContext(app, cmd, env)
if err := cmd.validateFlags(c); err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
if cmd.server == ":metadata" {
meta := getMetadata(c)
srv, err := meta.Get("instance/attributes/swarming-server")
if err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
cmd.server = srv
}
if cmd.provider != "" {
meta := getMetadata(c)
name, err := meta.InstanceName()
if err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
if cmd.provider == ":metadata" {
cmd.provider, err = meta.Get("instance/attributes/provider")
if err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
}
prov := newInstances(c, cmd.serviceAccount, cmd.provider)
inst, err := prov.Get(c, &instances.GetRequest{
Hostname: name,
})
if err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
cmd.server = inst.Swarming
}
swr := getSwarming(c)
swr.server = cmd.server
if err := swr.Configure(c, cmd.dir, cmd.user); err != nil {
logging.Errorf(c, "%s", err.Error())
return 1
}
return 0
} | [
"func",
"(",
"cmd",
"*",
"connectCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"c",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"cmd",
",",
"env",
")",
"\n",
"if",
"err",
":=",
"cmd",
".",
"validateFlags",
"(",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"if",
"cmd",
".",
"server",
"==",
"\"",
"\"",
"{",
"meta",
":=",
"getMetadata",
"(",
"c",
")",
"\n",
"srv",
",",
"err",
":=",
"meta",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"cmd",
".",
"server",
"=",
"srv",
"\n",
"}",
"\n",
"if",
"cmd",
".",
"provider",
"!=",
"\"",
"\"",
"{",
"meta",
":=",
"getMetadata",
"(",
"c",
")",
"\n",
"name",
",",
"err",
":=",
"meta",
".",
"InstanceName",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"if",
"cmd",
".",
"provider",
"==",
"\"",
"\"",
"{",
"cmd",
".",
"provider",
",",
"err",
"=",
"meta",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"}",
"\n",
"prov",
":=",
"newInstances",
"(",
"c",
",",
"cmd",
".",
"serviceAccount",
",",
"cmd",
".",
"provider",
")",
"\n",
"inst",
",",
"err",
":=",
"prov",
".",
"Get",
"(",
"c",
",",
"&",
"instances",
".",
"GetRequest",
"{",
"Hostname",
":",
"name",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"cmd",
".",
"server",
"=",
"inst",
".",
"Swarming",
"\n",
"}",
"\n\n",
"swr",
":=",
"getSwarming",
"(",
"c",
")",
"\n",
"swr",
".",
"server",
"=",
"cmd",
".",
"server",
"\n",
"if",
"err",
":=",
"swr",
".",
"Configure",
"(",
"c",
",",
"cmd",
".",
"dir",
",",
"cmd",
".",
"user",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"return",
"0",
"\n",
"}"
] | // Run runs the command to connect to a Swarming server. | [
"Run",
"runs",
"the",
"command",
"to",
"connect",
"to",
"a",
"Swarming",
"server",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/connect.go#L57-L104 |
8,403 | luci/luci-go | gce/cmd/agent/connect.go | newConnectCmd | func newConnectCmd() *subcommands.Command {
return &subcommands.Command{
UsageLine: "connect -dir <path> -server <server> -user <name>",
ShortDesc: "connects to a swarming server",
LongDesc: "Connects to a Swarming server.",
CommandRun: func() subcommands.CommandRun {
cmd := &connectCmd{}
cmd.Initialize()
cmd.Flags.StringVar(&cmd.dir, "dir", "", "Path to use as the Swarming bot directory.")
cmd.Flags.StringVar(&cmd.provider, "provider", "", "Provider server URL to retrieve Swarming server URL from.")
cmd.Flags.StringVar(&cmd.server, "server", "", "Deprecated. Use -provider.")
cmd.Flags.StringVar(&cmd.user, "user", "", "Name of the local user to start the Swarming bot process as.")
return cmd
},
}
} | go | func newConnectCmd() *subcommands.Command {
return &subcommands.Command{
UsageLine: "connect -dir <path> -server <server> -user <name>",
ShortDesc: "connects to a swarming server",
LongDesc: "Connects to a Swarming server.",
CommandRun: func() subcommands.CommandRun {
cmd := &connectCmd{}
cmd.Initialize()
cmd.Flags.StringVar(&cmd.dir, "dir", "", "Path to use as the Swarming bot directory.")
cmd.Flags.StringVar(&cmd.provider, "provider", "", "Provider server URL to retrieve Swarming server URL from.")
cmd.Flags.StringVar(&cmd.server, "server", "", "Deprecated. Use -provider.")
cmd.Flags.StringVar(&cmd.user, "user", "", "Name of the local user to start the Swarming bot process as.")
return cmd
},
}
} | [
"func",
"newConnectCmd",
"(",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\"",
",",
"CommandRun",
":",
"func",
"(",
")",
"subcommands",
".",
"CommandRun",
"{",
"cmd",
":=",
"&",
"connectCmd",
"{",
"}",
"\n",
"cmd",
".",
"Initialize",
"(",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"dir",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"provider",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"server",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"user",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"cmd",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // newConnectCmd returns a new command to connect to a Swarming server. | [
"newConnectCmd",
"returns",
"a",
"new",
"command",
"to",
"connect",
"to",
"a",
"Swarming",
"server",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/connect.go#L107-L122 |
8,404 | luci/luci-go | tokenserver/appengine/impl/utils/zip.go | ZlibCompress | func ZlibCompress(in []byte) ([]byte, error) {
out := bytes.Buffer{}
w := zlib.NewWriter(&out)
_, writeErr := w.Write(in)
closeErr := w.Close()
if writeErr != nil {
return nil, writeErr
}
if closeErr != nil {
return nil, closeErr
}
return out.Bytes(), nil
} | go | func ZlibCompress(in []byte) ([]byte, error) {
out := bytes.Buffer{}
w := zlib.NewWriter(&out)
_, writeErr := w.Write(in)
closeErr := w.Close()
if writeErr != nil {
return nil, writeErr
}
if closeErr != nil {
return nil, closeErr
}
return out.Bytes(), nil
} | [
"func",
"ZlibCompress",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"out",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"w",
":=",
"zlib",
".",
"NewWriter",
"(",
"&",
"out",
")",
"\n",
"_",
",",
"writeErr",
":=",
"w",
".",
"Write",
"(",
"in",
")",
"\n",
"closeErr",
":=",
"w",
".",
"Close",
"(",
")",
"\n",
"if",
"writeErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"writeErr",
"\n",
"}",
"\n",
"if",
"closeErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"closeErr",
"\n",
"}",
"\n",
"return",
"out",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // ZlibCompress zips a blob using zlib. | [
"ZlibCompress",
"zips",
"a",
"blob",
"using",
"zlib",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/zip.go#L24-L36 |
8,405 | luci/luci-go | tokenserver/appengine/impl/utils/zip.go | ZlibDecompress | func ZlibDecompress(in []byte) ([]byte, error) {
out := bytes.Buffer{}
r, err := zlib.NewReader(bytes.NewReader(in))
if err != nil {
return nil, err
}
_, readErr := io.Copy(&out, r)
closeErr := r.Close()
if readErr != nil {
return nil, readErr
}
if closeErr != nil {
return nil, closeErr
}
return out.Bytes(), nil
} | go | func ZlibDecompress(in []byte) ([]byte, error) {
out := bytes.Buffer{}
r, err := zlib.NewReader(bytes.NewReader(in))
if err != nil {
return nil, err
}
_, readErr := io.Copy(&out, r)
closeErr := r.Close()
if readErr != nil {
return nil, readErr
}
if closeErr != nil {
return nil, closeErr
}
return out.Bytes(), nil
} | [
"func",
"ZlibDecompress",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"out",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"r",
",",
"err",
":=",
"zlib",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"in",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"_",
",",
"readErr",
":=",
"io",
".",
"Copy",
"(",
"&",
"out",
",",
"r",
")",
"\n",
"closeErr",
":=",
"r",
".",
"Close",
"(",
")",
"\n",
"if",
"readErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"readErr",
"\n",
"}",
"\n",
"if",
"closeErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"closeErr",
"\n",
"}",
"\n",
"return",
"out",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // ZlibDecompress unzips a blob using zlib. | [
"ZlibDecompress",
"unzips",
"a",
"blob",
"using",
"zlib",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/zip.go#L39-L54 |
8,406 | luci/luci-go | server/auth/cache.go | newTokenCache | func newTokenCache(cfg tokenCacheConfig) *tokenCache {
return &tokenCache{
cfg: cfg,
lc: layered.Cache{
ProcessLRUCache: cfg.ProcessLRUCache,
GlobalNamespace: globalCacheNamespace,
Marshal: json.Marshal, // marshals *cachedToken
Unmarshal: func(blob []byte) (interface{}, error) {
out := &cachedToken{}
err := json.Unmarshal(blob, out)
return out, err
},
},
}
} | go | func newTokenCache(cfg tokenCacheConfig) *tokenCache {
return &tokenCache{
cfg: cfg,
lc: layered.Cache{
ProcessLRUCache: cfg.ProcessLRUCache,
GlobalNamespace: globalCacheNamespace,
Marshal: json.Marshal, // marshals *cachedToken
Unmarshal: func(blob []byte) (interface{}, error) {
out := &cachedToken{}
err := json.Unmarshal(blob, out)
return out, err
},
},
}
} | [
"func",
"newTokenCache",
"(",
"cfg",
"tokenCacheConfig",
")",
"*",
"tokenCache",
"{",
"return",
"&",
"tokenCache",
"{",
"cfg",
":",
"cfg",
",",
"lc",
":",
"layered",
".",
"Cache",
"{",
"ProcessLRUCache",
":",
"cfg",
".",
"ProcessLRUCache",
",",
"GlobalNamespace",
":",
"globalCacheNamespace",
",",
"Marshal",
":",
"json",
".",
"Marshal",
",",
"// marshals *cachedToken",
"Unmarshal",
":",
"func",
"(",
"blob",
"[",
"]",
"byte",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"out",
":=",
"&",
"cachedToken",
"{",
"}",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"blob",
",",
"out",
")",
"\n",
"return",
"out",
",",
"err",
"\n",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // newTokenCache configures tokenCache based on given parameters. | [
"newTokenCache",
"configures",
"tokenCache",
"based",
"on",
"given",
"parameters",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/cache.go#L70-L84 |
8,407 | luci/luci-go | logdog/client/butler/bundler/bundler.go | New | func New(c Config) *Bundler {
b := Bundler{
c: &c,
finishedC: make(chan struct{}),
bundleC: make(chan *logpb.ButlerLogBundle),
streams: map[string]bundlerStream{},
}
b.streamsCond = cancelcond.New(&b.streamsLock)
go b.makeBundles()
return &b
} | go | func New(c Config) *Bundler {
b := Bundler{
c: &c,
finishedC: make(chan struct{}),
bundleC: make(chan *logpb.ButlerLogBundle),
streams: map[string]bundlerStream{},
}
b.streamsCond = cancelcond.New(&b.streamsLock)
go b.makeBundles()
return &b
} | [
"func",
"New",
"(",
"c",
"Config",
")",
"*",
"Bundler",
"{",
"b",
":=",
"Bundler",
"{",
"c",
":",
"&",
"c",
",",
"finishedC",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"bundleC",
":",
"make",
"(",
"chan",
"*",
"logpb",
".",
"ButlerLogBundle",
")",
",",
"streams",
":",
"map",
"[",
"string",
"]",
"bundlerStream",
"{",
"}",
",",
"}",
"\n",
"b",
".",
"streamsCond",
"=",
"cancelcond",
".",
"New",
"(",
"&",
"b",
".",
"streamsLock",
")",
"\n\n",
"go",
"b",
".",
"makeBundles",
"(",
")",
"\n",
"return",
"&",
"b",
"\n",
"}"
] | // New instantiates a new Bundler instance. | [
"New",
"instantiates",
"a",
"new",
"Bundler",
"instance",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/bundler/bundler.go#L97-L108 |
8,408 | luci/luci-go | logdog/client/butler/bundler/bundler.go | Register | func (b *Bundler) Register(p *streamproto.Properties) (Stream, error) {
// Our Properties must validate.
if err := p.Validate(); err != nil {
return nil, err
}
// Enforce that the log stream descriptor's Prefix is empty.
p.Prefix = ""
// Construct a parser for this stream.
c := streamConfig{
name: p.Name,
template: logpb.ButlerLogBundle_Entry{
Desc: p.LogStreamDescriptor,
},
maximumBufferDuration: b.c.MaxBufferDelay,
maximumBufferedBytes: b.c.MaxBufferedBytes,
onAppend: func(appended bool) {
if appended {
b.signalStreamUpdate()
}
},
}
if b.c.StreamRegistrationCallback != nil {
c.nextBundleEntryCallback = b.c.StreamRegistrationCallback(p.LogStreamDescriptor)
}
err := error(nil)
c.parser, err = newParser(p, &b.prefixCounter)
if err != nil {
return nil, fmt.Errorf("failed to create stream parser: %s", err)
}
b.streamsLock.Lock()
defer b.streamsLock.Unlock()
// Ensure that this is not a duplicate stream name.
if s := b.streams[p.Name]; s != nil {
return nil, fmt.Errorf("a Stream is already registered for %q", p.Name)
}
// Create a new stream. This will kick off its processing goroutine, which
// will not stop until it is closed.
s := newStream(c)
b.registerStreamLocked(s)
return s, nil
} | go | func (b *Bundler) Register(p *streamproto.Properties) (Stream, error) {
// Our Properties must validate.
if err := p.Validate(); err != nil {
return nil, err
}
// Enforce that the log stream descriptor's Prefix is empty.
p.Prefix = ""
// Construct a parser for this stream.
c := streamConfig{
name: p.Name,
template: logpb.ButlerLogBundle_Entry{
Desc: p.LogStreamDescriptor,
},
maximumBufferDuration: b.c.MaxBufferDelay,
maximumBufferedBytes: b.c.MaxBufferedBytes,
onAppend: func(appended bool) {
if appended {
b.signalStreamUpdate()
}
},
}
if b.c.StreamRegistrationCallback != nil {
c.nextBundleEntryCallback = b.c.StreamRegistrationCallback(p.LogStreamDescriptor)
}
err := error(nil)
c.parser, err = newParser(p, &b.prefixCounter)
if err != nil {
return nil, fmt.Errorf("failed to create stream parser: %s", err)
}
b.streamsLock.Lock()
defer b.streamsLock.Unlock()
// Ensure that this is not a duplicate stream name.
if s := b.streams[p.Name]; s != nil {
return nil, fmt.Errorf("a Stream is already registered for %q", p.Name)
}
// Create a new stream. This will kick off its processing goroutine, which
// will not stop until it is closed.
s := newStream(c)
b.registerStreamLocked(s)
return s, nil
} | [
"func",
"(",
"b",
"*",
"Bundler",
")",
"Register",
"(",
"p",
"*",
"streamproto",
".",
"Properties",
")",
"(",
"Stream",
",",
"error",
")",
"{",
"// Our Properties must validate.",
"if",
"err",
":=",
"p",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Enforce that the log stream descriptor's Prefix is empty.",
"p",
".",
"Prefix",
"=",
"\"",
"\"",
"\n\n",
"// Construct a parser for this stream.",
"c",
":=",
"streamConfig",
"{",
"name",
":",
"p",
".",
"Name",
",",
"template",
":",
"logpb",
".",
"ButlerLogBundle_Entry",
"{",
"Desc",
":",
"p",
".",
"LogStreamDescriptor",
",",
"}",
",",
"maximumBufferDuration",
":",
"b",
".",
"c",
".",
"MaxBufferDelay",
",",
"maximumBufferedBytes",
":",
"b",
".",
"c",
".",
"MaxBufferedBytes",
",",
"onAppend",
":",
"func",
"(",
"appended",
"bool",
")",
"{",
"if",
"appended",
"{",
"b",
".",
"signalStreamUpdate",
"(",
")",
"\n",
"}",
"\n",
"}",
",",
"}",
"\n",
"if",
"b",
".",
"c",
".",
"StreamRegistrationCallback",
"!=",
"nil",
"{",
"c",
".",
"nextBundleEntryCallback",
"=",
"b",
".",
"c",
".",
"StreamRegistrationCallback",
"(",
"p",
".",
"LogStreamDescriptor",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"error",
"(",
"nil",
")",
"\n",
"c",
".",
"parser",
",",
"err",
"=",
"newParser",
"(",
"p",
",",
"&",
"b",
".",
"prefixCounter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"b",
".",
"streamsLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"streamsLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// Ensure that this is not a duplicate stream name.",
"if",
"s",
":=",
"b",
".",
"streams",
"[",
"p",
".",
"Name",
"]",
";",
"s",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
".",
"Name",
")",
"\n",
"}",
"\n\n",
"// Create a new stream. This will kick off its processing goroutine, which",
"// will not stop until it is closed.",
"s",
":=",
"newStream",
"(",
"c",
")",
"\n",
"b",
".",
"registerStreamLocked",
"(",
"s",
")",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // Register adds a new stream to the Bundler, returning a reference to the
// registered stream.
//
// The Bundler takes ownership of the supplied Properties, and may modify them
// as needed. | [
"Register",
"adds",
"a",
"new",
"stream",
"to",
"the",
"Bundler",
"returning",
"a",
"reference",
"to",
"the",
"registered",
"stream",
".",
"The",
"Bundler",
"takes",
"ownership",
"of",
"the",
"supplied",
"Properties",
"and",
"may",
"modify",
"them",
"as",
"needed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/bundler/bundler.go#L115-L161 |
8,409 | luci/luci-go | logdog/client/butler/bundler/bundler.go | GetStreamDescs | func (b *Bundler) GetStreamDescs() map[string]*logpb.LogStreamDescriptor {
b.streamsLock.Lock()
defer b.streamsLock.Unlock()
if len(b.streams) == 0 {
return nil
}
streams := make(map[string]*logpb.LogStreamDescriptor, len(b.streams))
for k, s := range b.streams {
streams[k] = s.streamDesc()
}
return streams
} | go | func (b *Bundler) GetStreamDescs() map[string]*logpb.LogStreamDescriptor {
b.streamsLock.Lock()
defer b.streamsLock.Unlock()
if len(b.streams) == 0 {
return nil
}
streams := make(map[string]*logpb.LogStreamDescriptor, len(b.streams))
for k, s := range b.streams {
streams[k] = s.streamDesc()
}
return streams
} | [
"func",
"(",
"b",
"*",
"Bundler",
")",
"GetStreamDescs",
"(",
")",
"map",
"[",
"string",
"]",
"*",
"logpb",
".",
"LogStreamDescriptor",
"{",
"b",
".",
"streamsLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"streamsLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"len",
"(",
"b",
".",
"streams",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"streams",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"logpb",
".",
"LogStreamDescriptor",
",",
"len",
"(",
"b",
".",
"streams",
")",
")",
"\n",
"for",
"k",
",",
"s",
":=",
"range",
"b",
".",
"streams",
"{",
"streams",
"[",
"k",
"]",
"=",
"s",
".",
"streamDesc",
"(",
")",
"\n",
"}",
"\n",
"return",
"streams",
"\n",
"}"
] | // GetStreamDescs returns the set of registered stream names mapped to their
// descriptors.
//
// This is intended for testing purposes. DO NOT modify the resulting
// descriptors. | [
"GetStreamDescs",
"returns",
"the",
"set",
"of",
"registered",
"stream",
"names",
"mapped",
"to",
"their",
"descriptors",
".",
"This",
"is",
"intended",
"for",
"testing",
"purposes",
".",
"DO",
"NOT",
"modify",
"the",
"resulting",
"descriptors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/bundler/bundler.go#L168-L181 |
8,410 | luci/luci-go | logdog/client/butler/bundler/bundler.go | makeBundles | func (b *Bundler) makeBundles() {
defer close(b.finishedC)
defer close(b.bundleC)
b.streamsLock.Lock()
defer b.streamsLock.Unlock()
var bb *builder
defer func() {
if bb != nil && bb.hasContent() {
b.bundleC <- bb.bundle()
}
}()
for {
bb = &builder{
size: b.c.MaxBundleSize,
template: logpb.ButlerLogBundle{
Timestamp: google.NewTimestamp(b.getClock().Now()),
Project: string(b.c.Project),
Prefix: string(b.c.Prefix),
},
}
var oldestContentTime time.Time
for {
state := b.getStreamStateLocked()
// Attempt to create more bundles.
sendNow := b.bundleRoundLocked(bb, state)
// Prune and unregister any drained streams.
state.forEachStream(func(s bundlerStream) bool {
if s.isDrained() {
state.removeStream(s.name())
b.unregisterStreamLocked(s)
}
return true
})
if b.flushing && len(state.streams) == 0 {
// We're flushing, and there are no more streams, so we're completely
// finished.
//
// If we have any content in our builder, it will be exported via defer.
return
}
// If we have content, consider emitting this bundle.
if bb.hasContent() && (b.c.MaxBufferDelay == 0 || sendNow || bb.ready()) {
break
}
// Mark the first time this round where we actually saw data.
if oldestContentTime.IsZero() && bb.hasContent() {
oldestContentTime = state.now
}
// We will yield our stream lock and sleep, waiting for either:
// 1) The earliest expiration time.
// 2) A streams channel signal.
//
// We use a Cond here because we want Streams to be able to be added
// while we're waiting for stream data.
nextExpire, has := state.nextExpire()
// If we have an oldest content time, that also means that we have
// content. Factor this constraint in.
if !oldestContentTime.IsZero() {
roundExpire := oldestContentTime.Add(b.c.MaxBufferDelay)
if !roundExpire.After(state.now) {
break
}
if !has || roundExpire.Before(nextExpire) {
nextExpire = roundExpire
has = true
}
}
// If we had no data or expire constraints, wait indefinitely for
// something to change.
//
// This will release our state lock during switch execution. The lock will
// be held after the switch statement has finished.
condC := context.Background()
switch {
case has && nextExpire.After(state.now):
// No immediate data, so block until the next known data expiration
// time.
condC, _ = context.WithDeadline(condC, nextExpire)
b.streamsCond.Wait(condC)
case has:
// There is more data, and it has already expired, so go immediately.
break
default:
// No data, and no enqueued stream data, so block indefinitely until we
// get a signal.
b.streamsCond.Wait(condC)
}
}
// If our bundler has contents, send them.
if bb.hasContent() {
b.bundleC <- bb.bundle()
}
}
} | go | func (b *Bundler) makeBundles() {
defer close(b.finishedC)
defer close(b.bundleC)
b.streamsLock.Lock()
defer b.streamsLock.Unlock()
var bb *builder
defer func() {
if bb != nil && bb.hasContent() {
b.bundleC <- bb.bundle()
}
}()
for {
bb = &builder{
size: b.c.MaxBundleSize,
template: logpb.ButlerLogBundle{
Timestamp: google.NewTimestamp(b.getClock().Now()),
Project: string(b.c.Project),
Prefix: string(b.c.Prefix),
},
}
var oldestContentTime time.Time
for {
state := b.getStreamStateLocked()
// Attempt to create more bundles.
sendNow := b.bundleRoundLocked(bb, state)
// Prune and unregister any drained streams.
state.forEachStream(func(s bundlerStream) bool {
if s.isDrained() {
state.removeStream(s.name())
b.unregisterStreamLocked(s)
}
return true
})
if b.flushing && len(state.streams) == 0 {
// We're flushing, and there are no more streams, so we're completely
// finished.
//
// If we have any content in our builder, it will be exported via defer.
return
}
// If we have content, consider emitting this bundle.
if bb.hasContent() && (b.c.MaxBufferDelay == 0 || sendNow || bb.ready()) {
break
}
// Mark the first time this round where we actually saw data.
if oldestContentTime.IsZero() && bb.hasContent() {
oldestContentTime = state.now
}
// We will yield our stream lock and sleep, waiting for either:
// 1) The earliest expiration time.
// 2) A streams channel signal.
//
// We use a Cond here because we want Streams to be able to be added
// while we're waiting for stream data.
nextExpire, has := state.nextExpire()
// If we have an oldest content time, that also means that we have
// content. Factor this constraint in.
if !oldestContentTime.IsZero() {
roundExpire := oldestContentTime.Add(b.c.MaxBufferDelay)
if !roundExpire.After(state.now) {
break
}
if !has || roundExpire.Before(nextExpire) {
nextExpire = roundExpire
has = true
}
}
// If we had no data or expire constraints, wait indefinitely for
// something to change.
//
// This will release our state lock during switch execution. The lock will
// be held after the switch statement has finished.
condC := context.Background()
switch {
case has && nextExpire.After(state.now):
// No immediate data, so block until the next known data expiration
// time.
condC, _ = context.WithDeadline(condC, nextExpire)
b.streamsCond.Wait(condC)
case has:
// There is more data, and it has already expired, so go immediately.
break
default:
// No data, and no enqueued stream data, so block indefinitely until we
// get a signal.
b.streamsCond.Wait(condC)
}
}
// If our bundler has contents, send them.
if bb.hasContent() {
b.bundleC <- bb.bundle()
}
}
} | [
"func",
"(",
"b",
"*",
"Bundler",
")",
"makeBundles",
"(",
")",
"{",
"defer",
"close",
"(",
"b",
".",
"finishedC",
")",
"\n",
"defer",
"close",
"(",
"b",
".",
"bundleC",
")",
"\n\n",
"b",
".",
"streamsLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"streamsLock",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"bb",
"*",
"builder",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"bb",
"!=",
"nil",
"&&",
"bb",
".",
"hasContent",
"(",
")",
"{",
"b",
".",
"bundleC",
"<-",
"bb",
".",
"bundle",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"for",
"{",
"bb",
"=",
"&",
"builder",
"{",
"size",
":",
"b",
".",
"c",
".",
"MaxBundleSize",
",",
"template",
":",
"logpb",
".",
"ButlerLogBundle",
"{",
"Timestamp",
":",
"google",
".",
"NewTimestamp",
"(",
"b",
".",
"getClock",
"(",
")",
".",
"Now",
"(",
")",
")",
",",
"Project",
":",
"string",
"(",
"b",
".",
"c",
".",
"Project",
")",
",",
"Prefix",
":",
"string",
"(",
"b",
".",
"c",
".",
"Prefix",
")",
",",
"}",
",",
"}",
"\n",
"var",
"oldestContentTime",
"time",
".",
"Time",
"\n\n",
"for",
"{",
"state",
":=",
"b",
".",
"getStreamStateLocked",
"(",
")",
"\n\n",
"// Attempt to create more bundles.",
"sendNow",
":=",
"b",
".",
"bundleRoundLocked",
"(",
"bb",
",",
"state",
")",
"\n\n",
"// Prune and unregister any drained streams.",
"state",
".",
"forEachStream",
"(",
"func",
"(",
"s",
"bundlerStream",
")",
"bool",
"{",
"if",
"s",
".",
"isDrained",
"(",
")",
"{",
"state",
".",
"removeStream",
"(",
"s",
".",
"name",
"(",
")",
")",
"\n",
"b",
".",
"unregisterStreamLocked",
"(",
"s",
")",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}",
")",
"\n\n",
"if",
"b",
".",
"flushing",
"&&",
"len",
"(",
"state",
".",
"streams",
")",
"==",
"0",
"{",
"// We're flushing, and there are no more streams, so we're completely",
"// finished.",
"//",
"// If we have any content in our builder, it will be exported via defer.",
"return",
"\n",
"}",
"\n\n",
"// If we have content, consider emitting this bundle.",
"if",
"bb",
".",
"hasContent",
"(",
")",
"&&",
"(",
"b",
".",
"c",
".",
"MaxBufferDelay",
"==",
"0",
"||",
"sendNow",
"||",
"bb",
".",
"ready",
"(",
")",
")",
"{",
"break",
"\n",
"}",
"\n\n",
"// Mark the first time this round where we actually saw data.",
"if",
"oldestContentTime",
".",
"IsZero",
"(",
")",
"&&",
"bb",
".",
"hasContent",
"(",
")",
"{",
"oldestContentTime",
"=",
"state",
".",
"now",
"\n",
"}",
"\n\n",
"// We will yield our stream lock and sleep, waiting for either:",
"// 1) The earliest expiration time.",
"// 2) A streams channel signal.",
"//",
"// We use a Cond here because we want Streams to be able to be added",
"// while we're waiting for stream data.",
"nextExpire",
",",
"has",
":=",
"state",
".",
"nextExpire",
"(",
")",
"\n\n",
"// If we have an oldest content time, that also means that we have",
"// content. Factor this constraint in.",
"if",
"!",
"oldestContentTime",
".",
"IsZero",
"(",
")",
"{",
"roundExpire",
":=",
"oldestContentTime",
".",
"Add",
"(",
"b",
".",
"c",
".",
"MaxBufferDelay",
")",
"\n",
"if",
"!",
"roundExpire",
".",
"After",
"(",
"state",
".",
"now",
")",
"{",
"break",
"\n",
"}",
"\n\n",
"if",
"!",
"has",
"||",
"roundExpire",
".",
"Before",
"(",
"nextExpire",
")",
"{",
"nextExpire",
"=",
"roundExpire",
"\n",
"has",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If we had no data or expire constraints, wait indefinitely for",
"// something to change.",
"//",
"// This will release our state lock during switch execution. The lock will",
"// be held after the switch statement has finished.",
"condC",
":=",
"context",
".",
"Background",
"(",
")",
"\n",
"switch",
"{",
"case",
"has",
"&&",
"nextExpire",
".",
"After",
"(",
"state",
".",
"now",
")",
":",
"// No immediate data, so block until the next known data expiration",
"// time.",
"condC",
",",
"_",
"=",
"context",
".",
"WithDeadline",
"(",
"condC",
",",
"nextExpire",
")",
"\n",
"b",
".",
"streamsCond",
".",
"Wait",
"(",
"condC",
")",
"\n\n",
"case",
"has",
":",
"// There is more data, and it has already expired, so go immediately.",
"break",
"\n\n",
"default",
":",
"// No data, and no enqueued stream data, so block indefinitely until we",
"// get a signal.",
"b",
".",
"streamsCond",
".",
"Wait",
"(",
"condC",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If our bundler has contents, send them.",
"if",
"bb",
".",
"hasContent",
"(",
")",
"{",
"b",
".",
"bundleC",
"<-",
"bb",
".",
"bundle",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // makeBundles is run in its own goroutine. It runs continuously, responding
// to Stream constraints and availability and sending ButlerLogBundles through
// bundleC when available.
//
// makeBundles will terminate when closeC is closed and all streams are drained. | [
"makeBundles",
"is",
"run",
"in",
"its",
"own",
"goroutine",
".",
"It",
"runs",
"continuously",
"responding",
"to",
"Stream",
"constraints",
"and",
"availability",
"and",
"sending",
"ButlerLogBundles",
"through",
"bundleC",
"when",
"available",
".",
"makeBundles",
"will",
"terminate",
"when",
"closeC",
"is",
"closed",
"and",
"all",
"streams",
"are",
"drained",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/bundler/bundler.go#L214-L324 |
8,411 | luci/luci-go | logdog/client/butler/bundler/bundler.go | removeStream | func (s *streamState) removeStream(name string) bundlerStream {
if si, idx := s.streamIndex(name); si != nil {
heap.Remove(s, idx)
return si
}
return nil
} | go | func (s *streamState) removeStream(name string) bundlerStream {
if si, idx := s.streamIndex(name); si != nil {
heap.Remove(s, idx)
return si
}
return nil
} | [
"func",
"(",
"s",
"*",
"streamState",
")",
"removeStream",
"(",
"name",
"string",
")",
"bundlerStream",
"{",
"if",
"si",
",",
"idx",
":=",
"s",
".",
"streamIndex",
"(",
"name",
")",
";",
"si",
"!=",
"nil",
"{",
"heap",
".",
"Remove",
"(",
"s",
",",
"idx",
")",
"\n",
"return",
"si",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // removeStream removes a stream from the stream state. | [
"removeStream",
"removes",
"a",
"stream",
"from",
"the",
"stream",
"state",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/bundler/bundler.go#L492-L498 |
8,412 | luci/luci-go | appengine/gaeauth/server/cookies.go | LoginURL | func (m UsersAPIAuthMethod) LoginURL(c context.Context, dest string) (string, error) {
url, err := user.LoginURL(c, dest)
if err != nil {
return "", err
}
if !strings.HasPrefix(url, serviceLoginURL) {
if !info.IsDevAppServer(c) {
logging.Warningf(c, "Unexpected login URL: %q", url)
}
return url, nil
}
// Give the user a choice of existing accounts in their session or the option
// to add an account, even if they are currently signed in to exactly one
// account.
return accountChooserURL + url[len(serviceLoginURL):], nil
} | go | func (m UsersAPIAuthMethod) LoginURL(c context.Context, dest string) (string, error) {
url, err := user.LoginURL(c, dest)
if err != nil {
return "", err
}
if !strings.HasPrefix(url, serviceLoginURL) {
if !info.IsDevAppServer(c) {
logging.Warningf(c, "Unexpected login URL: %q", url)
}
return url, nil
}
// Give the user a choice of existing accounts in their session or the option
// to add an account, even if they are currently signed in to exactly one
// account.
return accountChooserURL + url[len(serviceLoginURL):], nil
} | [
"func",
"(",
"m",
"UsersAPIAuthMethod",
")",
"LoginURL",
"(",
"c",
"context",
".",
"Context",
",",
"dest",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"url",
",",
"err",
":=",
"user",
".",
"LoginURL",
"(",
"c",
",",
"dest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"url",
",",
"serviceLoginURL",
")",
"{",
"if",
"!",
"info",
".",
"IsDevAppServer",
"(",
"c",
")",
"{",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"url",
")",
"\n",
"}",
"\n",
"return",
"url",
",",
"nil",
"\n",
"}",
"\n",
"// Give the user a choice of existing accounts in their session or the option",
"// to add an account, even if they are currently signed in to exactly one",
"// account.",
"return",
"accountChooserURL",
"+",
"url",
"[",
"len",
"(",
"serviceLoginURL",
")",
":",
"]",
",",
"nil",
"\n",
"}"
] | // LoginURL returns a URL that, when visited, prompts the user to sign in,
// then redirects the user to the URL specified by dest. | [
"LoginURL",
"returns",
"a",
"URL",
"that",
"when",
"visited",
"prompts",
"the",
"user",
"to",
"sign",
"in",
"then",
"redirects",
"the",
"user",
"to",
"the",
"URL",
"specified",
"by",
"dest",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/cookies.go#L59-L74 |
8,413 | luci/luci-go | appengine/gaeauth/server/cookies.go | LogoutURL | func (m UsersAPIAuthMethod) LogoutURL(c context.Context, dest string) (string, error) {
return user.LogoutURL(c, dest)
} | go | func (m UsersAPIAuthMethod) LogoutURL(c context.Context, dest string) (string, error) {
return user.LogoutURL(c, dest)
} | [
"func",
"(",
"m",
"UsersAPIAuthMethod",
")",
"LogoutURL",
"(",
"c",
"context",
".",
"Context",
",",
"dest",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"user",
".",
"LogoutURL",
"(",
"c",
",",
"dest",
")",
"\n",
"}"
] | // LogoutURL returns a URL that, when visited, signs the user out,
// then redirects the user to the URL specified by dest. | [
"LogoutURL",
"returns",
"a",
"URL",
"that",
"when",
"visited",
"signs",
"the",
"user",
"out",
"then",
"redirects",
"the",
"user",
"to",
"the",
"URL",
"specified",
"by",
"dest",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/cookies.go#L78-L80 |
8,414 | luci/luci-go | milo/buildsource/rawpresentation/logDogBuild.go | SubStepsToUI | func SubStepsToUI(c context.Context, ub URLBuilder, substeps []*miloProto.Step_Substep) ([]*ui.BuildComponent, []*ui.PropertyGroup) {
components := make([]*ui.BuildComponent, 0, len(substeps))
propGroups := make([]*ui.PropertyGroup, 0, len(substeps)+1) // This is the max number or property groups.
for _, substepContainer := range substeps {
anno := substepContainer.GetStep()
if anno == nil {
// TODO: We ignore non-embedded substeps for now.
continue
}
bs := miloBuildStep(c, ub, anno, true)
components = append(components, &bs)
addPropGroups(&propGroups, &bs, anno)
}
return components, propGroups
} | go | func SubStepsToUI(c context.Context, ub URLBuilder, substeps []*miloProto.Step_Substep) ([]*ui.BuildComponent, []*ui.PropertyGroup) {
components := make([]*ui.BuildComponent, 0, len(substeps))
propGroups := make([]*ui.PropertyGroup, 0, len(substeps)+1) // This is the max number or property groups.
for _, substepContainer := range substeps {
anno := substepContainer.GetStep()
if anno == nil {
// TODO: We ignore non-embedded substeps for now.
continue
}
bs := miloBuildStep(c, ub, anno, true)
components = append(components, &bs)
addPropGroups(&propGroups, &bs, anno)
}
return components, propGroups
} | [
"func",
"SubStepsToUI",
"(",
"c",
"context",
".",
"Context",
",",
"ub",
"URLBuilder",
",",
"substeps",
"[",
"]",
"*",
"miloProto",
".",
"Step_Substep",
")",
"(",
"[",
"]",
"*",
"ui",
".",
"BuildComponent",
",",
"[",
"]",
"*",
"ui",
".",
"PropertyGroup",
")",
"{",
"components",
":=",
"make",
"(",
"[",
"]",
"*",
"ui",
".",
"BuildComponent",
",",
"0",
",",
"len",
"(",
"substeps",
")",
")",
"\n",
"propGroups",
":=",
"make",
"(",
"[",
"]",
"*",
"ui",
".",
"PropertyGroup",
",",
"0",
",",
"len",
"(",
"substeps",
")",
"+",
"1",
")",
"// This is the max number or property groups.",
"\n",
"for",
"_",
",",
"substepContainer",
":=",
"range",
"substeps",
"{",
"anno",
":=",
"substepContainer",
".",
"GetStep",
"(",
")",
"\n",
"if",
"anno",
"==",
"nil",
"{",
"// TODO: We ignore non-embedded substeps for now.",
"continue",
"\n",
"}",
"\n\n",
"bs",
":=",
"miloBuildStep",
"(",
"c",
",",
"ub",
",",
"anno",
",",
"true",
")",
"\n",
"components",
"=",
"append",
"(",
"components",
",",
"&",
"bs",
")",
"\n",
"addPropGroups",
"(",
"&",
"propGroups",
",",
"&",
"bs",
",",
"anno",
")",
"\n",
"}",
"\n\n",
"return",
"components",
",",
"propGroups",
"\n",
"}"
] | // SubStepsToUI converts a slice of annotation substeps to ui.BuildComponent and
// slice of ui.PropertyGroups. | [
"SubStepsToUI",
"converts",
"a",
"slice",
"of",
"annotation",
"substeps",
"to",
"ui",
".",
"BuildComponent",
"and",
"slice",
"of",
"ui",
".",
"PropertyGroups",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/rawpresentation/logDogBuild.go#L177-L193 |
8,415 | luci/luci-go | milo/buildsource/rawpresentation/logDogBuild.go | AddLogDogToBuild | func AddLogDogToBuild(
c context.Context, ub URLBuilder, mainAnno *miloProto.Step, build *ui.MiloBuildLegacy) {
// Now fill in each of the step components.
// TODO(hinoka): This is totes cachable.
build.Summary = miloBuildStep(c, ub, mainAnno, false)
build.Components, build.PropertyGroup = SubStepsToUI(c, ub, mainAnno.Substep)
// Take care of properties
propGroup := &ui.PropertyGroup{GroupName: "Main"}
for _, prop := range mainAnno.Property {
propGroup.Property = append(propGroup.Property, &ui.Property{
Key: prop.Name,
Value: prop.Value,
})
}
build.PropertyGroup = append(build.PropertyGroup, propGroup)
// Build a property map so we can extract revision properties.
propMap := map[string]string{}
for _, pg := range build.PropertyGroup {
for _, p := range pg.Property {
propMap[p.Key] = p.Value
}
}
// HACK(hinoka,iannucci): Extract revision out of properties. This should use
// source manifests instead.
jrev, ok := propMap["got_revision"]
if !ok {
jrev, ok = propMap["revision"]
}
if ok {
// got_revision/revision are json strings, so it looks like "aaaaaabbcc123..."
var rev string
err := json.Unmarshal([]byte(jrev), &rev)
if err == nil {
if build.Trigger == nil {
build.Trigger = &ui.Trigger{}
}
build.Trigger.Revision = ui.NewLink(
rev, fmt.Sprintf("https://crrev.com/%s", rev), fmt.Sprintf("revision %s", rev))
}
}
return
} | go | func AddLogDogToBuild(
c context.Context, ub URLBuilder, mainAnno *miloProto.Step, build *ui.MiloBuildLegacy) {
// Now fill in each of the step components.
// TODO(hinoka): This is totes cachable.
build.Summary = miloBuildStep(c, ub, mainAnno, false)
build.Components, build.PropertyGroup = SubStepsToUI(c, ub, mainAnno.Substep)
// Take care of properties
propGroup := &ui.PropertyGroup{GroupName: "Main"}
for _, prop := range mainAnno.Property {
propGroup.Property = append(propGroup.Property, &ui.Property{
Key: prop.Name,
Value: prop.Value,
})
}
build.PropertyGroup = append(build.PropertyGroup, propGroup)
// Build a property map so we can extract revision properties.
propMap := map[string]string{}
for _, pg := range build.PropertyGroup {
for _, p := range pg.Property {
propMap[p.Key] = p.Value
}
}
// HACK(hinoka,iannucci): Extract revision out of properties. This should use
// source manifests instead.
jrev, ok := propMap["got_revision"]
if !ok {
jrev, ok = propMap["revision"]
}
if ok {
// got_revision/revision are json strings, so it looks like "aaaaaabbcc123..."
var rev string
err := json.Unmarshal([]byte(jrev), &rev)
if err == nil {
if build.Trigger == nil {
build.Trigger = &ui.Trigger{}
}
build.Trigger.Revision = ui.NewLink(
rev, fmt.Sprintf("https://crrev.com/%s", rev), fmt.Sprintf("revision %s", rev))
}
}
return
} | [
"func",
"AddLogDogToBuild",
"(",
"c",
"context",
".",
"Context",
",",
"ub",
"URLBuilder",
",",
"mainAnno",
"*",
"miloProto",
".",
"Step",
",",
"build",
"*",
"ui",
".",
"MiloBuildLegacy",
")",
"{",
"// Now fill in each of the step components.",
"// TODO(hinoka): This is totes cachable.",
"build",
".",
"Summary",
"=",
"miloBuildStep",
"(",
"c",
",",
"ub",
",",
"mainAnno",
",",
"false",
")",
"\n",
"build",
".",
"Components",
",",
"build",
".",
"PropertyGroup",
"=",
"SubStepsToUI",
"(",
"c",
",",
"ub",
",",
"mainAnno",
".",
"Substep",
")",
"\n\n",
"// Take care of properties",
"propGroup",
":=",
"&",
"ui",
".",
"PropertyGroup",
"{",
"GroupName",
":",
"\"",
"\"",
"}",
"\n",
"for",
"_",
",",
"prop",
":=",
"range",
"mainAnno",
".",
"Property",
"{",
"propGroup",
".",
"Property",
"=",
"append",
"(",
"propGroup",
".",
"Property",
",",
"&",
"ui",
".",
"Property",
"{",
"Key",
":",
"prop",
".",
"Name",
",",
"Value",
":",
"prop",
".",
"Value",
",",
"}",
")",
"\n",
"}",
"\n",
"build",
".",
"PropertyGroup",
"=",
"append",
"(",
"build",
".",
"PropertyGroup",
",",
"propGroup",
")",
"\n\n",
"// Build a property map so we can extract revision properties.",
"propMap",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"pg",
":=",
"range",
"build",
".",
"PropertyGroup",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"pg",
".",
"Property",
"{",
"propMap",
"[",
"p",
".",
"Key",
"]",
"=",
"p",
".",
"Value",
"\n",
"}",
"\n",
"}",
"\n",
"// HACK(hinoka,iannucci): Extract revision out of properties. This should use",
"// source manifests instead.",
"jrev",
",",
"ok",
":=",
"propMap",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"jrev",
",",
"ok",
"=",
"propMap",
"[",
"\"",
"\"",
"]",
"\n",
"}",
"\n",
"if",
"ok",
"{",
"// got_revision/revision are json strings, so it looks like \"aaaaaabbcc123...\"",
"var",
"rev",
"string",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"jrev",
")",
",",
"&",
"rev",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"build",
".",
"Trigger",
"==",
"nil",
"{",
"build",
".",
"Trigger",
"=",
"&",
"ui",
".",
"Trigger",
"{",
"}",
"\n",
"}",
"\n",
"build",
".",
"Trigger",
".",
"Revision",
"=",
"ui",
".",
"NewLink",
"(",
"rev",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rev",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rev",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // AddLogDogToBuild takes a set of logdog streams and populate a milo build.
// build.Summary.Finished must be set. | [
"AddLogDogToBuild",
"takes",
"a",
"set",
"of",
"logdog",
"streams",
"and",
"populate",
"a",
"milo",
"build",
".",
"build",
".",
"Summary",
".",
"Finished",
"must",
"be",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/rawpresentation/logDogBuild.go#L197-L242 |
8,416 | luci/luci-go | common/tsmon/metric/standard_metrics.go | UpdateHTTPMetrics | func UpdateHTTPMetrics(ctx context.Context, name string, client string,
code int, duration time.Duration, requestBytes int64, responseBytes int64) {
requestBytesMetric.Add(ctx, float64(requestBytes), name, client)
responseBytesMetric.Add(ctx, float64(responseBytes), name, client)
requestDurationsMetric.Add(ctx, float64(int64(duration)/int64(time.Millisecond)), name, client)
responseStatusMetric.Add(ctx, 1, code, name, client)
} | go | func UpdateHTTPMetrics(ctx context.Context, name string, client string,
code int, duration time.Duration, requestBytes int64, responseBytes int64) {
requestBytesMetric.Add(ctx, float64(requestBytes), name, client)
responseBytesMetric.Add(ctx, float64(responseBytes), name, client)
requestDurationsMetric.Add(ctx, float64(int64(duration)/int64(time.Millisecond)), name, client)
responseStatusMetric.Add(ctx, 1, code, name, client)
} | [
"func",
"UpdateHTTPMetrics",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"client",
"string",
",",
"code",
"int",
",",
"duration",
"time",
".",
"Duration",
",",
"requestBytes",
"int64",
",",
"responseBytes",
"int64",
")",
"{",
"requestBytesMetric",
".",
"Add",
"(",
"ctx",
",",
"float64",
"(",
"requestBytes",
")",
",",
"name",
",",
"client",
")",
"\n",
"responseBytesMetric",
".",
"Add",
"(",
"ctx",
",",
"float64",
"(",
"responseBytes",
")",
",",
"name",
",",
"client",
")",
"\n",
"requestDurationsMetric",
".",
"Add",
"(",
"ctx",
",",
"float64",
"(",
"int64",
"(",
"duration",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
")",
",",
"name",
",",
"client",
")",
"\n",
"responseStatusMetric",
".",
"Add",
"(",
"ctx",
",",
"1",
",",
"code",
",",
"name",
",",
"client",
")",
"\n",
"}"
] | // UpdateHTTPMetrics updates the metrics for a request to a remote server. | [
"UpdateHTTPMetrics",
"updates",
"the",
"metrics",
"for",
"a",
"request",
"to",
"a",
"remote",
"server",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/metric/standard_metrics.go#L124-L130 |
8,417 | luci/luci-go | common/tsmon/metric/standard_metrics.go | UpdateServerMetrics | func UpdateServerMetrics(ctx context.Context, name string, code int,
duration time.Duration, requestBytes int64, responseBytes int64,
userAgent string) {
isRobot := (strings.Contains(userAgent, "GoogleBot") ||
strings.Contains(userAgent, "GoogleSecurityScanner") ||
userAgent == "B3M/prober")
serverDurationsMetric.Add(ctx, float64(int64(duration)/int64(time.Millisecond)), code, name, isRobot)
serverResponseStatusMetric.Add(ctx, 1, code, name, isRobot)
serverRequestBytesMetric.Add(ctx, float64(requestBytes), code, name, isRobot)
serverResponseBytesMetric.Add(ctx, float64(responseBytes), code, name, isRobot)
} | go | func UpdateServerMetrics(ctx context.Context, name string, code int,
duration time.Duration, requestBytes int64, responseBytes int64,
userAgent string) {
isRobot := (strings.Contains(userAgent, "GoogleBot") ||
strings.Contains(userAgent, "GoogleSecurityScanner") ||
userAgent == "B3M/prober")
serverDurationsMetric.Add(ctx, float64(int64(duration)/int64(time.Millisecond)), code, name, isRobot)
serverResponseStatusMetric.Add(ctx, 1, code, name, isRobot)
serverRequestBytesMetric.Add(ctx, float64(requestBytes), code, name, isRobot)
serverResponseBytesMetric.Add(ctx, float64(responseBytes), code, name, isRobot)
} | [
"func",
"UpdateServerMetrics",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"code",
"int",
",",
"duration",
"time",
".",
"Duration",
",",
"requestBytes",
"int64",
",",
"responseBytes",
"int64",
",",
"userAgent",
"string",
")",
"{",
"isRobot",
":=",
"(",
"strings",
".",
"Contains",
"(",
"userAgent",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"userAgent",
",",
"\"",
"\"",
")",
"||",
"userAgent",
"==",
"\"",
"\"",
")",
"\n",
"serverDurationsMetric",
".",
"Add",
"(",
"ctx",
",",
"float64",
"(",
"int64",
"(",
"duration",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
")",
",",
"code",
",",
"name",
",",
"isRobot",
")",
"\n",
"serverResponseStatusMetric",
".",
"Add",
"(",
"ctx",
",",
"1",
",",
"code",
",",
"name",
",",
"isRobot",
")",
"\n",
"serverRequestBytesMetric",
".",
"Add",
"(",
"ctx",
",",
"float64",
"(",
"requestBytes",
")",
",",
"code",
",",
"name",
",",
"isRobot",
")",
"\n",
"serverResponseBytesMetric",
".",
"Add",
"(",
"ctx",
",",
"float64",
"(",
"responseBytes",
")",
",",
"code",
",",
"name",
",",
"isRobot",
")",
"\n",
"}"
] | // UpdateServerMetrics updates the metrics for a handled request. | [
"UpdateServerMetrics",
"updates",
"the",
"metrics",
"for",
"a",
"handled",
"request",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/metric/standard_metrics.go#L133-L143 |
8,418 | luci/luci-go | tokenserver/appengine/impl/delegation/config.go | NewRulesCache | func NewRulesCache() *RulesCache {
return &RulesCache{
policy: policy.Policy{
Name: delegationCfg, // used as part of datastore keys
Fetch: fetchConfigs, // see below
Validate: validateConfigBundle, // see config_validation.go
Prepare: prepareRules, // see below
},
}
} | go | func NewRulesCache() *RulesCache {
return &RulesCache{
policy: policy.Policy{
Name: delegationCfg, // used as part of datastore keys
Fetch: fetchConfigs, // see below
Validate: validateConfigBundle, // see config_validation.go
Prepare: prepareRules, // see below
},
}
} | [
"func",
"NewRulesCache",
"(",
")",
"*",
"RulesCache",
"{",
"return",
"&",
"RulesCache",
"{",
"policy",
":",
"policy",
".",
"Policy",
"{",
"Name",
":",
"delegationCfg",
",",
"// used as part of datastore keys",
"Fetch",
":",
"fetchConfigs",
",",
"// see below",
"Validate",
":",
"validateConfigBundle",
",",
"// see config_validation.go",
"Prepare",
":",
"prepareRules",
",",
"// see below",
"}",
",",
"}",
"\n",
"}"
] | // NewRulesCache properly initializes RulesCache instance. | [
"NewRulesCache",
"properly",
"initializes",
"RulesCache",
"instance",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/config.go#L104-L113 |
8,419 | luci/luci-go | tokenserver/appengine/impl/delegation/config.go | ImportConfigs | func (rc *RulesCache) ImportConfigs(c context.Context) (rev string, err error) {
return rc.policy.ImportConfigs(c)
} | go | func (rc *RulesCache) ImportConfigs(c context.Context) (rev string, err error) {
return rc.policy.ImportConfigs(c)
} | [
"func",
"(",
"rc",
"*",
"RulesCache",
")",
"ImportConfigs",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"rev",
"string",
",",
"err",
"error",
")",
"{",
"return",
"rc",
".",
"policy",
".",
"ImportConfigs",
"(",
"c",
")",
"\n",
"}"
] | // ImportConfigs refetches delegation.cfg and updates datastore copy of it.
//
// Called from cron. | [
"ImportConfigs",
"refetches",
"delegation",
".",
"cfg",
"and",
"updates",
"datastore",
"copy",
"of",
"it",
".",
"Called",
"from",
"cron",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/config.go#L118-L120 |
8,420 | luci/luci-go | tokenserver/appengine/impl/delegation/config.go | Rules | func (rc *RulesCache) Rules(c context.Context) (*Rules, error) {
q, err := rc.policy.Queryable(c)
if err != nil {
return nil, err
}
return q.(*Rules), nil
} | go | func (rc *RulesCache) Rules(c context.Context) (*Rules, error) {
q, err := rc.policy.Queryable(c)
if err != nil {
return nil, err
}
return q.(*Rules), nil
} | [
"func",
"(",
"rc",
"*",
"RulesCache",
")",
"Rules",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"*",
"Rules",
",",
"error",
")",
"{",
"q",
",",
"err",
":=",
"rc",
".",
"policy",
".",
"Queryable",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"q",
".",
"(",
"*",
"Rules",
")",
",",
"nil",
"\n",
"}"
] | // Rules returns in-memory copy of delegation rules, ready for querying. | [
"Rules",
"returns",
"in",
"-",
"memory",
"copy",
"of",
"delegation",
"rules",
"ready",
"for",
"querying",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/config.go#L136-L142 |
8,421 | luci/luci-go | tokenserver/appengine/impl/delegation/config.go | makeDelegationRule | func makeDelegationRule(c context.Context, rule *admin.DelegationRule) (*delegationRule, error) {
ctx := &validation.Context{Context: c}
validateRule(ctx, rule.Name, rule)
if err := ctx.Finalize(); err != nil {
return nil, err
}
// The main validation step has been done above. Here we just assert that
// everything looks sane (it should). See corresponding chunks of
// 'ValidateRule' code.
requestors, err := identityset.FromStrings(rule.Requestor, nil)
if err != nil {
panic(err)
}
delegators, err := identityset.FromStrings(rule.AllowedToImpersonate, skipRequestorOrProjects)
if err != nil {
panic(err)
}
audience, err := identityset.FromStrings(rule.AllowedAudience, skipRequestor)
if err != nil {
panic(err)
}
services, err := identityset.FromStrings(rule.TargetService, nil)
if err != nil {
panic(err)
}
return &delegationRule{
rule: rule,
requestors: requestors,
delegators: delegators,
audience: audience,
services: services,
addRequestorAsDelegator: sliceHasString(rule.AllowedToImpersonate, Requestor),
addRequestorToAudience: sliceHasString(rule.AllowedAudience, Requestor),
addProjectsAsDelegators: sliceHasString(rule.AllowedToImpersonate, Projects),
}, nil
} | go | func makeDelegationRule(c context.Context, rule *admin.DelegationRule) (*delegationRule, error) {
ctx := &validation.Context{Context: c}
validateRule(ctx, rule.Name, rule)
if err := ctx.Finalize(); err != nil {
return nil, err
}
// The main validation step has been done above. Here we just assert that
// everything looks sane (it should). See corresponding chunks of
// 'ValidateRule' code.
requestors, err := identityset.FromStrings(rule.Requestor, nil)
if err != nil {
panic(err)
}
delegators, err := identityset.FromStrings(rule.AllowedToImpersonate, skipRequestorOrProjects)
if err != nil {
panic(err)
}
audience, err := identityset.FromStrings(rule.AllowedAudience, skipRequestor)
if err != nil {
panic(err)
}
services, err := identityset.FromStrings(rule.TargetService, nil)
if err != nil {
panic(err)
}
return &delegationRule{
rule: rule,
requestors: requestors,
delegators: delegators,
audience: audience,
services: services,
addRequestorAsDelegator: sliceHasString(rule.AllowedToImpersonate, Requestor),
addRequestorToAudience: sliceHasString(rule.AllowedAudience, Requestor),
addProjectsAsDelegators: sliceHasString(rule.AllowedToImpersonate, Projects),
}, nil
} | [
"func",
"makeDelegationRule",
"(",
"c",
"context",
".",
"Context",
",",
"rule",
"*",
"admin",
".",
"DelegationRule",
")",
"(",
"*",
"delegationRule",
",",
"error",
")",
"{",
"ctx",
":=",
"&",
"validation",
".",
"Context",
"{",
"Context",
":",
"c",
"}",
"\n",
"validateRule",
"(",
"ctx",
",",
"rule",
".",
"Name",
",",
"rule",
")",
"\n",
"if",
"err",
":=",
"ctx",
".",
"Finalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// The main validation step has been done above. Here we just assert that",
"// everything looks sane (it should). See corresponding chunks of",
"// 'ValidateRule' code.",
"requestors",
",",
"err",
":=",
"identityset",
".",
"FromStrings",
"(",
"rule",
".",
"Requestor",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"delegators",
",",
"err",
":=",
"identityset",
".",
"FromStrings",
"(",
"rule",
".",
"AllowedToImpersonate",
",",
"skipRequestorOrProjects",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"audience",
",",
"err",
":=",
"identityset",
".",
"FromStrings",
"(",
"rule",
".",
"AllowedAudience",
",",
"skipRequestor",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"services",
",",
"err",
":=",
"identityset",
".",
"FromStrings",
"(",
"rule",
".",
"TargetService",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"delegationRule",
"{",
"rule",
":",
"rule",
",",
"requestors",
":",
"requestors",
",",
"delegators",
":",
"delegators",
",",
"audience",
":",
"audience",
",",
"services",
":",
"services",
",",
"addRequestorAsDelegator",
":",
"sliceHasString",
"(",
"rule",
".",
"AllowedToImpersonate",
",",
"Requestor",
")",
",",
"addRequestorToAudience",
":",
"sliceHasString",
"(",
"rule",
".",
"AllowedAudience",
",",
"Requestor",
")",
",",
"addProjectsAsDelegators",
":",
"sliceHasString",
"(",
"rule",
".",
"AllowedToImpersonate",
",",
"Projects",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // makeDelegationRule preprocesses admin.DelegationRule proto.
//
// It also double checks that the rule is passing validation. The check may
// fail if new code uses old configs, still stored in the datastore. | [
"makeDelegationRule",
"preprocesses",
"admin",
".",
"DelegationRule",
"proto",
".",
"It",
"also",
"double",
"checks",
"that",
"the",
"rule",
"is",
"passing",
"validation",
".",
"The",
"check",
"may",
"fail",
"if",
"new",
"code",
"uses",
"old",
"configs",
"still",
"stored",
"in",
"the",
"datastore",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/config.go#L207-L244 |
8,422 | luci/luci-go | tokenserver/appengine/impl/delegation/config.go | IsAuthorizedRequestor | func (r *Rules) IsAuthorizedRequestor(c context.Context, id identity.Identity) (bool, error) {
return r.requestors.IsMember(c, id)
} | go | func (r *Rules) IsAuthorizedRequestor(c context.Context, id identity.Identity) (bool, error) {
return r.requestors.IsMember(c, id)
} | [
"func",
"(",
"r",
"*",
"Rules",
")",
"IsAuthorizedRequestor",
"(",
"c",
"context",
".",
"Context",
",",
"id",
"identity",
".",
"Identity",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"r",
".",
"requestors",
".",
"IsMember",
"(",
"c",
",",
"id",
")",
"\n",
"}"
] | // IsAuthorizedRequestor returns true if the caller belongs to 'requestor' set
// of at least one rule. | [
"IsAuthorizedRequestor",
"returns",
"true",
"if",
"the",
"caller",
"belongs",
"to",
"requestor",
"set",
"of",
"at",
"least",
"one",
"rule",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/config.go#L270-L272 |
8,423 | luci/luci-go | tokenserver/appengine/impl/delegation/config.go | FindMatchingRule | func (r *Rules) FindMatchingRule(c context.Context, q *RulesQuery) (*admin.DelegationRule, error) {
var matches []*admin.DelegationRule
for _, rule := range r.rules {
switch yes, err := rule.matchesQuery(c, q); {
case err != nil:
return nil, err // usually transient
case yes:
matches = append(matches, rule.rule)
}
}
if len(matches) == 0 {
return nil, fmt.Errorf("no matching delegation rules in the config")
}
if len(matches) > 1 {
names := make([]string, len(matches))
for i, m := range matches {
names[i] = fmt.Sprintf("%q", m.Name)
}
return nil, fmt.Errorf(
"ambiguous request, multiple delegation rules match (%s)",
strings.Join(names, ", "))
}
return matches[0], nil
} | go | func (r *Rules) FindMatchingRule(c context.Context, q *RulesQuery) (*admin.DelegationRule, error) {
var matches []*admin.DelegationRule
for _, rule := range r.rules {
switch yes, err := rule.matchesQuery(c, q); {
case err != nil:
return nil, err // usually transient
case yes:
matches = append(matches, rule.rule)
}
}
if len(matches) == 0 {
return nil, fmt.Errorf("no matching delegation rules in the config")
}
if len(matches) > 1 {
names := make([]string, len(matches))
for i, m := range matches {
names[i] = fmt.Sprintf("%q", m.Name)
}
return nil, fmt.Errorf(
"ambiguous request, multiple delegation rules match (%s)",
strings.Join(names, ", "))
}
return matches[0], nil
} | [
"func",
"(",
"r",
"*",
"Rules",
")",
"FindMatchingRule",
"(",
"c",
"context",
".",
"Context",
",",
"q",
"*",
"RulesQuery",
")",
"(",
"*",
"admin",
".",
"DelegationRule",
",",
"error",
")",
"{",
"var",
"matches",
"[",
"]",
"*",
"admin",
".",
"DelegationRule",
"\n",
"for",
"_",
",",
"rule",
":=",
"range",
"r",
".",
"rules",
"{",
"switch",
"yes",
",",
"err",
":=",
"rule",
".",
"matchesQuery",
"(",
"c",
",",
"q",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"nil",
",",
"err",
"// usually transient",
"\n",
"case",
"yes",
":",
"matches",
"=",
"append",
"(",
"matches",
",",
"rule",
".",
"rule",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"matches",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"matches",
")",
">",
"1",
"{",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"matches",
")",
")",
"\n",
"for",
"i",
",",
"m",
":=",
"range",
"matches",
"{",
"names",
"[",
"i",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"m",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"names",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"return",
"matches",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] | // FindMatchingRule finds one and only one rule matching the query.
//
// If multiple rules match or none rules match, an error is returned. | [
"FindMatchingRule",
"finds",
"one",
"and",
"only",
"one",
"rule",
"matching",
"the",
"query",
".",
"If",
"multiple",
"rules",
"match",
"or",
"none",
"rules",
"match",
"an",
"error",
"is",
"returned",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/config.go#L277-L303 |
8,424 | luci/luci-go | tokenserver/appengine/impl/delegation/config.go | matchesQuery | func (rule *delegationRule) matchesQuery(c context.Context, q *RulesQuery) (bool, error) {
// Rule's 'requestor' set contains the requestor?
switch found, err := rule.requestors.IsMember(c, q.Requestor); {
case err != nil:
return false, err
case !found:
return false, nil
}
// Rule's 'delegators' set contains the identity being delegated/impersonated?
switch yes, err := rule.matchesDelegator(c, q); {
case err != nil:
return false, err
case !yes:
return false, nil
}
// Rule's 'audience' is superset of requested audience?
allowedAudience := rule.audience
if rule.addRequestorToAudience {
allowedAudience = identityset.Extend(allowedAudience, q.Requestor)
}
if !allowedAudience.IsSuperset(q.Audience) {
return false, nil
}
// Rule's allowed targets is superset of requested targets?
if !rule.services.IsSuperset(q.Services) {
return false, nil
}
return true, nil
} | go | func (rule *delegationRule) matchesQuery(c context.Context, q *RulesQuery) (bool, error) {
// Rule's 'requestor' set contains the requestor?
switch found, err := rule.requestors.IsMember(c, q.Requestor); {
case err != nil:
return false, err
case !found:
return false, nil
}
// Rule's 'delegators' set contains the identity being delegated/impersonated?
switch yes, err := rule.matchesDelegator(c, q); {
case err != nil:
return false, err
case !yes:
return false, nil
}
// Rule's 'audience' is superset of requested audience?
allowedAudience := rule.audience
if rule.addRequestorToAudience {
allowedAudience = identityset.Extend(allowedAudience, q.Requestor)
}
if !allowedAudience.IsSuperset(q.Audience) {
return false, nil
}
// Rule's allowed targets is superset of requested targets?
if !rule.services.IsSuperset(q.Services) {
return false, nil
}
return true, nil
} | [
"func",
"(",
"rule",
"*",
"delegationRule",
")",
"matchesQuery",
"(",
"c",
"context",
".",
"Context",
",",
"q",
"*",
"RulesQuery",
")",
"(",
"bool",
",",
"error",
")",
"{",
"// Rule's 'requestor' set contains the requestor?",
"switch",
"found",
",",
"err",
":=",
"rule",
".",
"requestors",
".",
"IsMember",
"(",
"c",
",",
"q",
".",
"Requestor",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"false",
",",
"err",
"\n",
"case",
"!",
"found",
":",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"// Rule's 'delegators' set contains the identity being delegated/impersonated?",
"switch",
"yes",
",",
"err",
":=",
"rule",
".",
"matchesDelegator",
"(",
"c",
",",
"q",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"false",
",",
"err",
"\n",
"case",
"!",
"yes",
":",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"// Rule's 'audience' is superset of requested audience?",
"allowedAudience",
":=",
"rule",
".",
"audience",
"\n",
"if",
"rule",
".",
"addRequestorToAudience",
"{",
"allowedAudience",
"=",
"identityset",
".",
"Extend",
"(",
"allowedAudience",
",",
"q",
".",
"Requestor",
")",
"\n",
"}",
"\n",
"if",
"!",
"allowedAudience",
".",
"IsSuperset",
"(",
"q",
".",
"Audience",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"// Rule's allowed targets is superset of requested targets?",
"if",
"!",
"rule",
".",
"services",
".",
"IsSuperset",
"(",
"q",
".",
"Services",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // matchesQuery returns true if this rule matches the query.
//
// See doc in config.proto, DelegationRule for exact description of when this
// happens. Basically, all sets in rule must be supersets of corresponding sets
// in RulesQuery.
//
// May return transient errors. | [
"matchesQuery",
"returns",
"true",
"if",
"this",
"rule",
"matches",
"the",
"query",
".",
"See",
"doc",
"in",
"config",
".",
"proto",
"DelegationRule",
"for",
"exact",
"description",
"of",
"when",
"this",
"happens",
".",
"Basically",
"all",
"sets",
"in",
"rule",
"must",
"be",
"supersets",
"of",
"corresponding",
"sets",
"in",
"RulesQuery",
".",
"May",
"return",
"transient",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/config.go#L312-L344 |
8,425 | luci/luci-go | cipd/appengine/impl/gs/uploader.go | Write | func (u *Uploader) Write(p []byte) (n int, err error) {
if len(p) == 0 {
return 0, nil
}
bufStart := u.Offset
bufEnd := u.Offset + int64(len(p))
if bufEnd > u.FileSize {
return 0, fmt.Errorf("attempting to write past the declared file size (%d > %d)", bufEnd, u.FileSize)
}
for u.Offset != bufEnd && err == nil {
resuming := false
err = withRetry(u.Context, func() error {
// When resuming, we upload 0 bytes chunk to grab the last known offset.
// Otherwise, just upload the next chunk of data.
var chunk []byte
if !resuming {
chunk = p[int(u.Offset-bufStart):]
}
resumeOffset, err := u.uploadChunk(chunk)
// On transient errors, try to resume right away once.
if apiErr, _ := err.(*googleapi.Error); apiErr != nil && apiErr.Code >= 500 {
logging.WithError(err).Warningf(u.Context, "Transient error, querying for last uploaded offset")
resuming = true
resumeOffset, err = u.uploadChunk(nil)
}
switch {
case err != nil:
// Either a fatal error during the upload or a transient or fatal error
// trying to resume. Let 'withRetry' handle it by retrying or failing.
return err
case resumeOffset < bufStart || resumeOffset > bufEnd:
// Resuming requires data we don't have? Escalate to the caller.
return &RestartUploadError{Offset: resumeOffset}
default:
// Resume the upload from the last acknowledged offset.
u.Offset = resumeOffset
resuming = false
return nil
}
})
}
return int(u.Offset - bufStart), err
} | go | func (u *Uploader) Write(p []byte) (n int, err error) {
if len(p) == 0 {
return 0, nil
}
bufStart := u.Offset
bufEnd := u.Offset + int64(len(p))
if bufEnd > u.FileSize {
return 0, fmt.Errorf("attempting to write past the declared file size (%d > %d)", bufEnd, u.FileSize)
}
for u.Offset != bufEnd && err == nil {
resuming := false
err = withRetry(u.Context, func() error {
// When resuming, we upload 0 bytes chunk to grab the last known offset.
// Otherwise, just upload the next chunk of data.
var chunk []byte
if !resuming {
chunk = p[int(u.Offset-bufStart):]
}
resumeOffset, err := u.uploadChunk(chunk)
// On transient errors, try to resume right away once.
if apiErr, _ := err.(*googleapi.Error); apiErr != nil && apiErr.Code >= 500 {
logging.WithError(err).Warningf(u.Context, "Transient error, querying for last uploaded offset")
resuming = true
resumeOffset, err = u.uploadChunk(nil)
}
switch {
case err != nil:
// Either a fatal error during the upload or a transient or fatal error
// trying to resume. Let 'withRetry' handle it by retrying or failing.
return err
case resumeOffset < bufStart || resumeOffset > bufEnd:
// Resuming requires data we don't have? Escalate to the caller.
return &RestartUploadError{Offset: resumeOffset}
default:
// Resume the upload from the last acknowledged offset.
u.Offset = resumeOffset
resuming = false
return nil
}
})
}
return int(u.Offset - bufStart), err
} | [
"func",
"(",
"u",
"*",
"Uploader",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n\n",
"bufStart",
":=",
"u",
".",
"Offset",
"\n",
"bufEnd",
":=",
"u",
".",
"Offset",
"+",
"int64",
"(",
"len",
"(",
"p",
")",
")",
"\n",
"if",
"bufEnd",
">",
"u",
".",
"FileSize",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"bufEnd",
",",
"u",
".",
"FileSize",
")",
"\n",
"}",
"\n\n",
"for",
"u",
".",
"Offset",
"!=",
"bufEnd",
"&&",
"err",
"==",
"nil",
"{",
"resuming",
":=",
"false",
"\n",
"err",
"=",
"withRetry",
"(",
"u",
".",
"Context",
",",
"func",
"(",
")",
"error",
"{",
"// When resuming, we upload 0 bytes chunk to grab the last known offset.",
"// Otherwise, just upload the next chunk of data.",
"var",
"chunk",
"[",
"]",
"byte",
"\n",
"if",
"!",
"resuming",
"{",
"chunk",
"=",
"p",
"[",
"int",
"(",
"u",
".",
"Offset",
"-",
"bufStart",
")",
":",
"]",
"\n",
"}",
"\n",
"resumeOffset",
",",
"err",
":=",
"u",
".",
"uploadChunk",
"(",
"chunk",
")",
"\n\n",
"// On transient errors, try to resume right away once.",
"if",
"apiErr",
",",
"_",
":=",
"err",
".",
"(",
"*",
"googleapi",
".",
"Error",
")",
";",
"apiErr",
"!=",
"nil",
"&&",
"apiErr",
".",
"Code",
">=",
"500",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Warningf",
"(",
"u",
".",
"Context",
",",
"\"",
"\"",
")",
"\n",
"resuming",
"=",
"true",
"\n",
"resumeOffset",
",",
"err",
"=",
"u",
".",
"uploadChunk",
"(",
"nil",
")",
"\n",
"}",
"\n\n",
"switch",
"{",
"case",
"err",
"!=",
"nil",
":",
"// Either a fatal error during the upload or a transient or fatal error",
"// trying to resume. Let 'withRetry' handle it by retrying or failing.",
"return",
"err",
"\n",
"case",
"resumeOffset",
"<",
"bufStart",
"||",
"resumeOffset",
">",
"bufEnd",
":",
"// Resuming requires data we don't have? Escalate to the caller.",
"return",
"&",
"RestartUploadError",
"{",
"Offset",
":",
"resumeOffset",
"}",
"\n",
"default",
":",
"// Resume the upload from the last acknowledged offset.",
"u",
".",
"Offset",
"=",
"resumeOffset",
"\n",
"resuming",
"=",
"false",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"int",
"(",
"u",
".",
"Offset",
"-",
"bufStart",
")",
",",
"err",
"\n",
"}"
] | // Write is part of io.Writer interface. | [
"Write",
"is",
"part",
"of",
"io",
".",
"Writer",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/gs/uploader.go#L74-L121 |
8,426 | luci/luci-go | milo/common/model/status.go | Terminal | func (s Status) Terminal() bool {
switch s {
case Success, Failure, InfraFailure, Warning, Expired, Exception, Cancelled:
return true
default:
return false
}
} | go | func (s Status) Terminal() bool {
switch s {
case Success, Failure, InfraFailure, Warning, Expired, Exception, Cancelled:
return true
default:
return false
}
} | [
"func",
"(",
"s",
"Status",
")",
"Terminal",
"(",
")",
"bool",
"{",
"switch",
"s",
"{",
"case",
"Success",
",",
"Failure",
",",
"InfraFailure",
",",
"Warning",
",",
"Expired",
",",
"Exception",
",",
"Cancelled",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // Terminal returns true if the step status won't change. | [
"Terminal",
"returns",
"true",
"if",
"the",
"step",
"status",
"won",
"t",
"change",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/status.go#L71-L78 |
8,427 | luci/luci-go | logdog/client/annotee/annotation/execution.go | ProbeExecution | func ProbeExecution(argv, env []string, cwd string) *Execution {
if env == nil {
env = os.Environ()
}
if cwd == "" {
cwd, _ = os.Getwd()
}
return probeExecutionImpl(argv, env, cwd)
} | go | func ProbeExecution(argv, env []string, cwd string) *Execution {
if env == nil {
env = os.Environ()
}
if cwd == "" {
cwd, _ = os.Getwd()
}
return probeExecutionImpl(argv, env, cwd)
} | [
"func",
"ProbeExecution",
"(",
"argv",
",",
"env",
"[",
"]",
"string",
",",
"cwd",
"string",
")",
"*",
"Execution",
"{",
"if",
"env",
"==",
"nil",
"{",
"env",
"=",
"os",
".",
"Environ",
"(",
")",
"\n",
"}",
"\n",
"if",
"cwd",
"==",
"\"",
"\"",
"{",
"cwd",
",",
"_",
"=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"}",
"\n",
"return",
"probeExecutionImpl",
"(",
"argv",
",",
"env",
",",
"cwd",
")",
"\n",
"}"
] | // ProbeExecution loads Execution parameters by probing the current runtime
// environment. | [
"ProbeExecution",
"loads",
"Execution",
"parameters",
"by",
"probing",
"the",
"current",
"runtime",
"environment",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/execution.go#L33-L41 |
8,428 | luci/luci-go | common/proto/git/changetype.go | UnmarshalJSON | func (c *Commit_TreeDiff_ChangeType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
change, ok := Commit_TreeDiff_ChangeType_value[strings.ToUpper(s)]
if !ok {
return fmt.Errorf("unexpected change type %q", s)
}
*c = Commit_TreeDiff_ChangeType(change)
return nil
} | go | func (c *Commit_TreeDiff_ChangeType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
change, ok := Commit_TreeDiff_ChangeType_value[strings.ToUpper(s)]
if !ok {
return fmt.Errorf("unexpected change type %q", s)
}
*c = Commit_TreeDiff_ChangeType(change)
return nil
} | [
"func",
"(",
"c",
"*",
"Commit_TreeDiff_ChangeType",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"s",
"string",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"change",
",",
"ok",
":=",
"Commit_TreeDiff_ChangeType_value",
"[",
"strings",
".",
"ToUpper",
"(",
"s",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"}",
"\n\n",
"*",
"c",
"=",
"Commit_TreeDiff_ChangeType",
"(",
"change",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON parses a string representation of the change. | [
"UnmarshalJSON",
"parses",
"a",
"string",
"representation",
"of",
"the",
"change",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/git/changetype.go#L15-L28 |
8,429 | luci/luci-go | machine-db/appengine/config/oses.go | importOSes | func importOSes(c context.Context, configSet config.Set) error {
os := &configPB.OSes{}
metadata := &config.Meta{}
if err := cfgclient.Get(c, cfgclient.AsService, configSet, osesFilename, textproto.Message(os), metadata); err != nil {
return errors.Annotate(err, "failed to load %s", osesFilename).Err()
}
logging.Infof(c, "Found %s revision %q", osesFilename, metadata.Revision)
ctx := &validation.Context{Context: c}
ctx.SetFile(osesFilename)
validateOSes(ctx, os)
if err := ctx.Finalize(); err != nil {
return errors.Annotate(err, "invalid config").Err()
}
if err := model.EnsureOSes(c, os.OperatingSystem); err != nil {
return errors.Annotate(err, "failed to ensure operating systems").Err()
}
return nil
} | go | func importOSes(c context.Context, configSet config.Set) error {
os := &configPB.OSes{}
metadata := &config.Meta{}
if err := cfgclient.Get(c, cfgclient.AsService, configSet, osesFilename, textproto.Message(os), metadata); err != nil {
return errors.Annotate(err, "failed to load %s", osesFilename).Err()
}
logging.Infof(c, "Found %s revision %q", osesFilename, metadata.Revision)
ctx := &validation.Context{Context: c}
ctx.SetFile(osesFilename)
validateOSes(ctx, os)
if err := ctx.Finalize(); err != nil {
return errors.Annotate(err, "invalid config").Err()
}
if err := model.EnsureOSes(c, os.OperatingSystem); err != nil {
return errors.Annotate(err, "failed to ensure operating systems").Err()
}
return nil
} | [
"func",
"importOSes",
"(",
"c",
"context",
".",
"Context",
",",
"configSet",
"config",
".",
"Set",
")",
"error",
"{",
"os",
":=",
"&",
"configPB",
".",
"OSes",
"{",
"}",
"\n",
"metadata",
":=",
"&",
"config",
".",
"Meta",
"{",
"}",
"\n",
"if",
"err",
":=",
"cfgclient",
".",
"Get",
"(",
"c",
",",
"cfgclient",
".",
"AsService",
",",
"configSet",
",",
"osesFilename",
",",
"textproto",
".",
"Message",
"(",
"os",
")",
",",
"metadata",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"osesFilename",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"logging",
".",
"Infof",
"(",
"c",
",",
"\"",
"\"",
",",
"osesFilename",
",",
"metadata",
".",
"Revision",
")",
"\n\n",
"ctx",
":=",
"&",
"validation",
".",
"Context",
"{",
"Context",
":",
"c",
"}",
"\n",
"ctx",
".",
"SetFile",
"(",
"osesFilename",
")",
"\n",
"validateOSes",
"(",
"ctx",
",",
"os",
")",
"\n",
"if",
"err",
":=",
"ctx",
".",
"Finalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"model",
".",
"EnsureOSes",
"(",
"c",
",",
"os",
".",
"OperatingSystem",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // importOSes fetches, validates, and applies operating system configs. | [
"importOSes",
"fetches",
"validates",
"and",
"applies",
"operating",
"system",
"configs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/config/oses.go#L36-L55 |
8,430 | luci/luci-go | machine-db/appengine/config/oses.go | validateOSes | func validateOSes(c *validation.Context, cfg *configPB.OSes) {
// Operating system names must be unique.
// Keep records of ones we've already seen.
names := stringset.New(len(cfg.OperatingSystem))
for _, os := range cfg.OperatingSystem {
switch {
case os.Name == "":
c.Errorf("operating system names are required and must be non-empty")
case !names.Add(os.Name):
c.Errorf("duplicate operating system %q", os.Name)
}
}
} | go | func validateOSes(c *validation.Context, cfg *configPB.OSes) {
// Operating system names must be unique.
// Keep records of ones we've already seen.
names := stringset.New(len(cfg.OperatingSystem))
for _, os := range cfg.OperatingSystem {
switch {
case os.Name == "":
c.Errorf("operating system names are required and must be non-empty")
case !names.Add(os.Name):
c.Errorf("duplicate operating system %q", os.Name)
}
}
} | [
"func",
"validateOSes",
"(",
"c",
"*",
"validation",
".",
"Context",
",",
"cfg",
"*",
"configPB",
".",
"OSes",
")",
"{",
"// Operating system names must be unique.",
"// Keep records of ones we've already seen.",
"names",
":=",
"stringset",
".",
"New",
"(",
"len",
"(",
"cfg",
".",
"OperatingSystem",
")",
")",
"\n",
"for",
"_",
",",
"os",
":=",
"range",
"cfg",
".",
"OperatingSystem",
"{",
"switch",
"{",
"case",
"os",
".",
"Name",
"==",
"\"",
"\"",
":",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"case",
"!",
"names",
".",
"Add",
"(",
"os",
".",
"Name",
")",
":",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"os",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // validateOSes validates oses.cfg. | [
"validateOSes",
"validates",
"oses",
".",
"cfg",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/config/oses.go#L58-L70 |
8,431 | luci/luci-go | logdog/common/types/streamsecret.go | NewPrefixSecret | func NewPrefixSecret() (PrefixSecret, error) {
buf := make([]byte, PrefixSecretLength)
if _, err := rand.Read(buf); err != nil {
return nil, err
}
value := PrefixSecret(buf)
if err := value.Validate(); err != nil {
panic(err)
}
return value, nil
} | go | func NewPrefixSecret() (PrefixSecret, error) {
buf := make([]byte, PrefixSecretLength)
if _, err := rand.Read(buf); err != nil {
return nil, err
}
value := PrefixSecret(buf)
if err := value.Validate(); err != nil {
panic(err)
}
return value, nil
} | [
"func",
"NewPrefixSecret",
"(",
")",
"(",
"PrefixSecret",
",",
"error",
")",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"PrefixSecretLength",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"value",
":=",
"PrefixSecret",
"(",
"buf",
")",
"\n",
"if",
"err",
":=",
"value",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"value",
",",
"nil",
"\n",
"}"
] | // NewPrefixSecret generates a new, default-length secret parameter. | [
"NewPrefixSecret",
"generates",
"a",
"new",
"default",
"-",
"length",
"secret",
"parameter",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamsecret.go#L44-L55 |
8,432 | luci/luci-go | logdog/common/types/streamsecret.go | Validate | func (s PrefixSecret) Validate() error {
if len(s) != PrefixSecretLength {
return fmt.Errorf("invalid prefix secret length (%d != %d)", len(s), PrefixSecretLength)
}
return nil
} | go | func (s PrefixSecret) Validate() error {
if len(s) != PrefixSecretLength {
return fmt.Errorf("invalid prefix secret length (%d != %d)", len(s), PrefixSecretLength)
}
return nil
} | [
"func",
"(",
"s",
"PrefixSecret",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"len",
"(",
"s",
")",
"!=",
"PrefixSecretLength",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"s",
")",
",",
"PrefixSecretLength",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate confirms that this prefix secret is conformant.
//
// Note that this does not scan the byte contents of the secret for any
// security-related parameters. | [
"Validate",
"confirms",
"that",
"this",
"prefix",
"secret",
"is",
"conformant",
".",
"Note",
"that",
"this",
"does",
"not",
"scan",
"the",
"byte",
"contents",
"of",
"the",
"secret",
"for",
"any",
"security",
"-",
"related",
"parameters",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamsecret.go#L61-L66 |
8,433 | luci/luci-go | common/system/environ/environment.go | normalizeKey | func (e *Env) normalizeKey(k string) string {
if e.CaseInsensitive {
return strings.ToUpper(k)
}
return k
} | go | func (e *Env) normalizeKey(k string) string {
if e.CaseInsensitive {
return strings.ToUpper(k)
}
return k
} | [
"func",
"(",
"e",
"*",
"Env",
")",
"normalizeKey",
"(",
"k",
"string",
")",
"string",
"{",
"if",
"e",
".",
"CaseInsensitive",
"{",
"return",
"strings",
".",
"ToUpper",
"(",
"k",
")",
"\n",
"}",
"\n",
"return",
"k",
"\n",
"}"
] | // normalizeKey normalizes the map key, ensuring that it is handled
// case-insensitive. | [
"normalizeKey",
"normalizes",
"the",
"map",
"key",
"ensuring",
"that",
"it",
"is",
"handled",
"case",
"-",
"insensitive",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/environ/environment.go#L52-L57 |
8,434 | luci/luci-go | common/system/environ/environment.go | New | func New(s []string) Env {
e := Env{
CaseInsensitive: SystemIsCaseInsensitive(),
}
e.LoadSlice(s)
return e
} | go | func New(s []string) Env {
e := Env{
CaseInsensitive: SystemIsCaseInsensitive(),
}
e.LoadSlice(s)
return e
} | [
"func",
"New",
"(",
"s",
"[",
"]",
"string",
")",
"Env",
"{",
"e",
":=",
"Env",
"{",
"CaseInsensitive",
":",
"SystemIsCaseInsensitive",
"(",
")",
",",
"}",
"\n",
"e",
".",
"LoadSlice",
"(",
"s",
")",
"\n",
"return",
"e",
"\n",
"}"
] | // New instantiates a new Env instance from the supplied set of environment
// KEY=VALUE strings using LoadSlice.
//
// The environment is automatically configured with the local system's case
// insensitivity. | [
"New",
"instantiates",
"a",
"new",
"Env",
"instance",
"from",
"the",
"supplied",
"set",
"of",
"environment",
"KEY",
"=",
"VALUE",
"strings",
"using",
"LoadSlice",
".",
"The",
"environment",
"is",
"automatically",
"configured",
"with",
"the",
"local",
"system",
"s",
"case",
"insensitivity",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/environ/environment.go#L73-L79 |
8,435 | luci/luci-go | common/system/environ/environment.go | GetEmpty | func (e Env) GetEmpty(k string) string {
v, _ := e.Get(k)
return v
} | go | func (e Env) GetEmpty(k string) string {
v, _ := e.Get(k)
return v
} | [
"func",
"(",
"e",
"Env",
")",
"GetEmpty",
"(",
"k",
"string",
")",
"string",
"{",
"v",
",",
"_",
":=",
"e",
".",
"Get",
"(",
"k",
")",
"\n",
"return",
"v",
"\n",
"}"
] | // GetEmpty is the same as Get, except that instead of returning a separate
// boolean indicating the presence of a key, it will return an empty string if
// the key is missing. | [
"GetEmpty",
"is",
"the",
"same",
"as",
"Get",
"except",
"that",
"instead",
"of",
"returning",
"a",
"separate",
"boolean",
"indicating",
"the",
"presence",
"of",
"a",
"key",
"it",
"will",
"return",
"an",
"empty",
"string",
"if",
"the",
"key",
"is",
"missing",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/environ/environment.go#L195-L198 |
8,436 | luci/luci-go | common/system/environ/environment.go | Sorted | func (e Env) Sorted() []string {
var r []string
if len(e.env) > 0 {
r = make([]string, 0, len(e.env))
for _, v := range e.env {
r = append(r, v)
}
sort.Strings(r)
}
return r
} | go | func (e Env) Sorted() []string {
var r []string
if len(e.env) > 0 {
r = make([]string, 0, len(e.env))
for _, v := range e.env {
r = append(r, v)
}
sort.Strings(r)
}
return r
} | [
"func",
"(",
"e",
"Env",
")",
"Sorted",
"(",
")",
"[",
"]",
"string",
"{",
"var",
"r",
"[",
"]",
"string",
"\n",
"if",
"len",
"(",
"e",
".",
"env",
")",
">",
"0",
"{",
"r",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"e",
".",
"env",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"e",
".",
"env",
"{",
"r",
"=",
"append",
"(",
"r",
",",
"v",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"r",
")",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] | // Sorted returns the contents of the environment, sorted by key. | [
"Sorted",
"returns",
"the",
"contents",
"of",
"the",
"environment",
"sorted",
"by",
"key",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/environ/environment.go#L201-L211 |
8,437 | luci/luci-go | common/system/environ/environment.go | Clone | func (e Env) Clone() Env {
clone := e
clone.env = nil
if len(e.env) > 0 {
clone.env = make(map[string]string, len(e.env))
for k, v := range e.env {
clone.env[k] = v
}
}
return clone
} | go | func (e Env) Clone() Env {
clone := e
clone.env = nil
if len(e.env) > 0 {
clone.env = make(map[string]string, len(e.env))
for k, v := range e.env {
clone.env[k] = v
}
}
return clone
} | [
"func",
"(",
"e",
"Env",
")",
"Clone",
"(",
")",
"Env",
"{",
"clone",
":=",
"e",
"\n",
"clone",
".",
"env",
"=",
"nil",
"\n\n",
"if",
"len",
"(",
"e",
".",
"env",
")",
">",
"0",
"{",
"clone",
".",
"env",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"len",
"(",
"e",
".",
"env",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"e",
".",
"env",
"{",
"clone",
".",
"env",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"clone",
"\n",
"}"
] | // Clone creates a new Env instance that is identical to, but independent from,
// e. | [
"Clone",
"creates",
"a",
"new",
"Env",
"instance",
"that",
"is",
"identical",
"to",
"but",
"independent",
"from",
"e",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/environ/environment.go#L235-L246 |
8,438 | luci/luci-go | common/system/environ/environment.go | iterate | func (e *Env) iterate(cb func(realKey, envKey, envValue string) bool) {
for k, v := range e.env {
envKey, envValue := Split(v)
if !cb(k, envKey, envValue) {
break
}
}
} | go | func (e *Env) iterate(cb func(realKey, envKey, envValue string) bool) {
for k, v := range e.env {
envKey, envValue := Split(v)
if !cb(k, envKey, envValue) {
break
}
}
} | [
"func",
"(",
"e",
"*",
"Env",
")",
"iterate",
"(",
"cb",
"func",
"(",
"realKey",
",",
"envKey",
",",
"envValue",
"string",
")",
"bool",
")",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"e",
".",
"env",
"{",
"envKey",
",",
"envValue",
":=",
"Split",
"(",
"v",
")",
"\n",
"if",
"!",
"cb",
"(",
"k",
",",
"envKey",
",",
"envValue",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Internal iteration function. Invokes cb for every entry in the environment.
// If the callback returns false, iteration stops.
//
// It is safe to mutate the environment map during iteration.
//
// realKey is the real, normalized map key. envKey and envValue are the split
// map value. | [
"Internal",
"iteration",
"function",
".",
"Invokes",
"cb",
"for",
"every",
"entry",
"in",
"the",
"environment",
".",
"If",
"the",
"callback",
"returns",
"false",
"iteration",
"stops",
".",
"It",
"is",
"safe",
"to",
"mutate",
"the",
"environment",
"map",
"during",
"iteration",
".",
"realKey",
"is",
"the",
"real",
"normalized",
"map",
"key",
".",
"envKey",
"and",
"envValue",
"are",
"the",
"split",
"map",
"value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/environ/environment.go#L255-L262 |
8,439 | luci/luci-go | common/lhttp/client.go | NewRequest | func NewRequest(ctx context.Context, c *http.Client, rFn retry.Factory, rgen RequestGen,
handler Handler, errorHandler ErrorHandler) func() (int, error) {
if rFn == nil {
rFn = transient.Only(retry.Default)
}
if errorHandler == nil {
errorHandler = func(resp *http.Response, err error) error {
if resp != nil {
// Drain and close the resp.Body.
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}
return err
}
}
return func() (int, error) {
status, attempts := 0, 0
err := retry.Retry(ctx, rFn, func() error {
attempts++
req, err := rgen()
if err != nil {
return err
}
resp, err := c.Do(req)
if err != nil {
// Retry every error. This is sad when you specify an invalid hostname but
// it's better than failing when DNS resolution is flaky.
return errorHandler(nil, transient.Tag.Apply(err))
}
status = resp.StatusCode
switch {
case status == 408, status == 429, status >= 500:
// The HTTP status code means the request should be retried.
err = errors.Reason("http request failed: %s (HTTP %d)", http.StatusText(status), status).
Tag(transient.Tag).Err()
case status == 404 && strings.HasPrefix(req.URL.Path, "/_ah/api/"):
// Endpoints occasionally return 404 on valid requests!
logging.Infof(ctx, "lhttp.Do() got a Cloud Endpoints 404: %#v", resp.Header)
err = errors.Reason("http request failed (endpoints): %s (HTTP %d)", http.StatusText(status), status).
Tag(transient.Tag).Err()
case status >= 400:
// Any other failure code is a hard failure.
err = fmt.Errorf("http request failed: %s (HTTP %d)", http.StatusText(status), status)
default:
// The handler may still return a retry.Error to indicate that the request
// should be retried even on successful status code.
return handler(resp)
}
err = applyHTTPTag(err, status)
return errorHandler(resp, err)
}, nil)
if err != nil {
err = errors.Annotate(err, "gave up after %d attempts", attempts).Err()
}
return status, err
}
} | go | func NewRequest(ctx context.Context, c *http.Client, rFn retry.Factory, rgen RequestGen,
handler Handler, errorHandler ErrorHandler) func() (int, error) {
if rFn == nil {
rFn = transient.Only(retry.Default)
}
if errorHandler == nil {
errorHandler = func(resp *http.Response, err error) error {
if resp != nil {
// Drain and close the resp.Body.
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}
return err
}
}
return func() (int, error) {
status, attempts := 0, 0
err := retry.Retry(ctx, rFn, func() error {
attempts++
req, err := rgen()
if err != nil {
return err
}
resp, err := c.Do(req)
if err != nil {
// Retry every error. This is sad when you specify an invalid hostname but
// it's better than failing when DNS resolution is flaky.
return errorHandler(nil, transient.Tag.Apply(err))
}
status = resp.StatusCode
switch {
case status == 408, status == 429, status >= 500:
// The HTTP status code means the request should be retried.
err = errors.Reason("http request failed: %s (HTTP %d)", http.StatusText(status), status).
Tag(transient.Tag).Err()
case status == 404 && strings.HasPrefix(req.URL.Path, "/_ah/api/"):
// Endpoints occasionally return 404 on valid requests!
logging.Infof(ctx, "lhttp.Do() got a Cloud Endpoints 404: %#v", resp.Header)
err = errors.Reason("http request failed (endpoints): %s (HTTP %d)", http.StatusText(status), status).
Tag(transient.Tag).Err()
case status >= 400:
// Any other failure code is a hard failure.
err = fmt.Errorf("http request failed: %s (HTTP %d)", http.StatusText(status), status)
default:
// The handler may still return a retry.Error to indicate that the request
// should be retried even on successful status code.
return handler(resp)
}
err = applyHTTPTag(err, status)
return errorHandler(resp, err)
}, nil)
if err != nil {
err = errors.Annotate(err, "gave up after %d attempts", attempts).Err()
}
return status, err
}
} | [
"func",
"NewRequest",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"http",
".",
"Client",
",",
"rFn",
"retry",
".",
"Factory",
",",
"rgen",
"RequestGen",
",",
"handler",
"Handler",
",",
"errorHandler",
"ErrorHandler",
")",
"func",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"rFn",
"==",
"nil",
"{",
"rFn",
"=",
"transient",
".",
"Only",
"(",
"retry",
".",
"Default",
")",
"\n",
"}",
"\n",
"if",
"errorHandler",
"==",
"nil",
"{",
"errorHandler",
"=",
"func",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"error",
"{",
"if",
"resp",
"!=",
"nil",
"{",
"// Drain and close the resp.Body.",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"resp",
".",
"Body",
")",
"\n",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"func",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"status",
",",
"attempts",
":=",
"0",
",",
"0",
"\n",
"err",
":=",
"retry",
".",
"Retry",
"(",
"ctx",
",",
"rFn",
",",
"func",
"(",
")",
"error",
"{",
"attempts",
"++",
"\n",
"req",
",",
"err",
":=",
"rgen",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Retry every error. This is sad when you specify an invalid hostname but",
"// it's better than failing when DNS resolution is flaky.",
"return",
"errorHandler",
"(",
"nil",
",",
"transient",
".",
"Tag",
".",
"Apply",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"status",
"=",
"resp",
".",
"StatusCode",
"\n\n",
"switch",
"{",
"case",
"status",
"==",
"408",
",",
"status",
"==",
"429",
",",
"status",
">=",
"500",
":",
"// The HTTP status code means the request should be retried.",
"err",
"=",
"errors",
".",
"Reason",
"(",
"\"",
"\"",
",",
"http",
".",
"StatusText",
"(",
"status",
")",
",",
"status",
")",
".",
"Tag",
"(",
"transient",
".",
"Tag",
")",
".",
"Err",
"(",
")",
"\n",
"case",
"status",
"==",
"404",
"&&",
"strings",
".",
"HasPrefix",
"(",
"req",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
":",
"// Endpoints occasionally return 404 on valid requests!",
"logging",
".",
"Infof",
"(",
"ctx",
",",
"\"",
"\"",
",",
"resp",
".",
"Header",
")",
"\n",
"err",
"=",
"errors",
".",
"Reason",
"(",
"\"",
"\"",
",",
"http",
".",
"StatusText",
"(",
"status",
")",
",",
"status",
")",
".",
"Tag",
"(",
"transient",
".",
"Tag",
")",
".",
"Err",
"(",
")",
"\n",
"case",
"status",
">=",
"400",
":",
"// Any other failure code is a hard failure.",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"http",
".",
"StatusText",
"(",
"status",
")",
",",
"status",
")",
"\n",
"default",
":",
"// The handler may still return a retry.Error to indicate that the request",
"// should be retried even on successful status code.",
"return",
"handler",
"(",
"resp",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"applyHTTPTag",
"(",
"err",
",",
"status",
")",
"\n",
"return",
"errorHandler",
"(",
"resp",
",",
"err",
")",
"\n",
"}",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"attempts",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"status",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // NewRequest returns a retriable request.
//
// The handler func is responsible for closing the response Body before
// returning. It should return retry.Error in case of retriable error, for
// example if a TCP connection is terminated while receiving the content.
//
// If rFn is nil, NewRequest will use a default exponential backoff strategy
// only for transient errors.
//
// If errorHandler is nil, the default error handler will drain and close the
// response body. | [
"NewRequest",
"returns",
"a",
"retriable",
"request",
".",
"The",
"handler",
"func",
"is",
"responsible",
"for",
"closing",
"the",
"response",
"Body",
"before",
"returning",
".",
"It",
"should",
"return",
"retry",
".",
"Error",
"in",
"case",
"of",
"retriable",
"error",
"for",
"example",
"if",
"a",
"TCP",
"connection",
"is",
"terminated",
"while",
"receiving",
"the",
"content",
".",
"If",
"rFn",
"is",
"nil",
"NewRequest",
"will",
"use",
"a",
"default",
"exponential",
"backoff",
"strategy",
"only",
"for",
"transient",
"errors",
".",
"If",
"errorHandler",
"is",
"nil",
"the",
"default",
"error",
"handler",
"will",
"drain",
"and",
"close",
"the",
"response",
"body",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/lhttp/client.go#L81-L141 |
8,440 | luci/luci-go | common/lhttp/client.go | NewRequestJSON | func NewRequestJSON(ctx context.Context, c *http.Client, rFn retry.Factory, url, method string, headers map[string]string, in, out interface{}) (func() (int, error), error) {
var encoded []byte
if in != nil {
var err error
if encoded, err = json.Marshal(in); err != nil {
return nil, err
}
}
return NewRequest(ctx, c, rFn, func() (*http.Request, error) {
var body io.Reader
if encoded != nil {
body = bytes.NewReader(encoded)
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
if encoded != nil {
req.Header.Set("Content-Type", jsonContentTypeForPOST)
}
if headers != nil {
for k, v := range headers {
req.Header.Add(k, v)
}
}
return req, nil
}, func(resp *http.Response) error {
defer resp.Body.Close()
if ct := strings.ToLower(resp.Header.Get("Content-Type")); !strings.HasPrefix(ct, jsonContentType) {
// Non-retriable.
return fmt.Errorf("unexpected Content-Type, expected \"%s\", got \"%s\"", jsonContentType, ct)
}
if out == nil {
// The client doesn't care about the response. Still ensure the response
// is valid json.
out = &map[string]interface{}{}
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
// Retriable.
return errors.Annotate(err, "bad response %s", url).Tag(transient.Tag).Err()
}
return nil
}, nil), nil
} | go | func NewRequestJSON(ctx context.Context, c *http.Client, rFn retry.Factory, url, method string, headers map[string]string, in, out interface{}) (func() (int, error), error) {
var encoded []byte
if in != nil {
var err error
if encoded, err = json.Marshal(in); err != nil {
return nil, err
}
}
return NewRequest(ctx, c, rFn, func() (*http.Request, error) {
var body io.Reader
if encoded != nil {
body = bytes.NewReader(encoded)
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
if encoded != nil {
req.Header.Set("Content-Type", jsonContentTypeForPOST)
}
if headers != nil {
for k, v := range headers {
req.Header.Add(k, v)
}
}
return req, nil
}, func(resp *http.Response) error {
defer resp.Body.Close()
if ct := strings.ToLower(resp.Header.Get("Content-Type")); !strings.HasPrefix(ct, jsonContentType) {
// Non-retriable.
return fmt.Errorf("unexpected Content-Type, expected \"%s\", got \"%s\"", jsonContentType, ct)
}
if out == nil {
// The client doesn't care about the response. Still ensure the response
// is valid json.
out = &map[string]interface{}{}
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
// Retriable.
return errors.Annotate(err, "bad response %s", url).Tag(transient.Tag).Err()
}
return nil
}, nil), nil
} | [
"func",
"NewRequestJSON",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"http",
".",
"Client",
",",
"rFn",
"retry",
".",
"Factory",
",",
"url",
",",
"method",
"string",
",",
"headers",
"map",
"[",
"string",
"]",
"string",
",",
"in",
",",
"out",
"interface",
"{",
"}",
")",
"(",
"func",
"(",
")",
"(",
"int",
",",
"error",
")",
",",
"error",
")",
"{",
"var",
"encoded",
"[",
"]",
"byte",
"\n",
"if",
"in",
"!=",
"nil",
"{",
"var",
"err",
"error",
"\n",
"if",
"encoded",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"in",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"NewRequest",
"(",
"ctx",
",",
"c",
",",
"rFn",
",",
"func",
"(",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"var",
"body",
"io",
".",
"Reader",
"\n",
"if",
"encoded",
"!=",
"nil",
"{",
"body",
"=",
"bytes",
".",
"NewReader",
"(",
"encoded",
")",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"url",
",",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"encoded",
"!=",
"nil",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"jsonContentTypeForPOST",
")",
"\n",
"}",
"\n",
"if",
"headers",
"!=",
"nil",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"headers",
"{",
"req",
".",
"Header",
".",
"Add",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"req",
",",
"nil",
"\n",
"}",
",",
"func",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"error",
"{",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"ct",
":=",
"strings",
".",
"ToLower",
"(",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
";",
"!",
"strings",
".",
"HasPrefix",
"(",
"ct",
",",
"jsonContentType",
")",
"{",
"// Non-retriable.",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
",",
"jsonContentType",
",",
"ct",
")",
"\n",
"}",
"\n",
"if",
"out",
"==",
"nil",
"{",
"// The client doesn't care about the response. Still ensure the response",
"// is valid json.",
"out",
"=",
"&",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"out",
")",
";",
"err",
"!=",
"nil",
"{",
"// Retriable.",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"url",
")",
".",
"Tag",
"(",
"transient",
".",
"Tag",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
",",
"nil",
")",
",",
"nil",
"\n",
"}"
] | // NewRequestJSON returns a retriable request calling a JSON endpoint. | [
"NewRequestJSON",
"returns",
"a",
"retriable",
"request",
"calling",
"a",
"JSON",
"endpoint",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/lhttp/client.go#L144-L189 |
8,441 | luci/luci-go | common/lhttp/client.go | PostJSON | func PostJSON(ctx context.Context, rFn retry.Factory, c *http.Client, url string, headers map[string]string, in, out interface{}) (int, error) {
req, err := NewRequestJSON(ctx, c, rFn, url, "POST", headers, in, out)
if err != nil {
return 0, err
}
return req()
} | go | func PostJSON(ctx context.Context, rFn retry.Factory, c *http.Client, url string, headers map[string]string, in, out interface{}) (int, error) {
req, err := NewRequestJSON(ctx, c, rFn, url, "POST", headers, in, out)
if err != nil {
return 0, err
}
return req()
} | [
"func",
"PostJSON",
"(",
"ctx",
"context",
".",
"Context",
",",
"rFn",
"retry",
".",
"Factory",
",",
"c",
"*",
"http",
".",
"Client",
",",
"url",
"string",
",",
"headers",
"map",
"[",
"string",
"]",
"string",
",",
"in",
",",
"out",
"interface",
"{",
"}",
")",
"(",
"int",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"NewRequestJSON",
"(",
"ctx",
",",
"c",
",",
"rFn",
",",
"url",
",",
"\"",
"\"",
",",
"headers",
",",
"in",
",",
"out",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"req",
"(",
")",
"\n",
"}"
] | // PostJSON is a shorthand. It returns the HTTP status code and error if any. | [
"PostJSON",
"is",
"a",
"shorthand",
".",
"It",
"returns",
"the",
"HTTP",
"status",
"code",
"and",
"error",
"if",
"any",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/lhttp/client.go#L201-L207 |
8,442 | luci/luci-go | machine-db/client/cli/machines.go | printMachines | func printMachines(tsv bool, machines ...*crimson.Machine) {
if len(machines) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Platform", "Rack", "Datacenter", "Description", "Asset Tag", "Service Tag", "Deployment Ticket", "DRAC Password", "State")
}
for _, m := range machines {
p.Row(m.Name, m.Platform, m.Rack, m.Datacenter, m.Description, m.AssetTag, m.ServiceTag, m.DeploymentTicket, m.DracPassword, m.State)
}
}
} | go | func printMachines(tsv bool, machines ...*crimson.Machine) {
if len(machines) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Platform", "Rack", "Datacenter", "Description", "Asset Tag", "Service Tag", "Deployment Ticket", "DRAC Password", "State")
}
for _, m := range machines {
p.Row(m.Name, m.Platform, m.Rack, m.Datacenter, m.Description, m.AssetTag, m.ServiceTag, m.DeploymentTicket, m.DracPassword, m.State)
}
}
} | [
"func",
"printMachines",
"(",
"tsv",
"bool",
",",
"machines",
"...",
"*",
"crimson",
".",
"Machine",
")",
"{",
"if",
"len",
"(",
"machines",
")",
">",
"0",
"{",
"p",
":=",
"newStdoutPrinter",
"(",
"tsv",
")",
"\n",
"defer",
"p",
".",
"Flush",
"(",
")",
"\n",
"if",
"!",
"tsv",
"{",
"p",
".",
"Row",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"machines",
"{",
"p",
".",
"Row",
"(",
"m",
".",
"Name",
",",
"m",
".",
"Platform",
",",
"m",
".",
"Rack",
",",
"m",
".",
"Datacenter",
",",
"m",
".",
"Description",
",",
"m",
".",
"AssetTag",
",",
"m",
".",
"ServiceTag",
",",
"m",
".",
"DeploymentTicket",
",",
"m",
".",
"DracPassword",
",",
"m",
".",
"State",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // printMachines prints machine data to stdout in tab-separated columns. | [
"printMachines",
"prints",
"machine",
"data",
"to",
"stdout",
"in",
"tab",
"-",
"separated",
"columns",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/machines.go#L28-L39 |
8,443 | luci/luci-go | machine-db/client/cli/machines.go | Run | func (c *AddMachineCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
// TODO(smut): Validate required fields client-side.
req := &crimson.CreateMachineRequest{
Machine: &c.machine,
}
client := getClient(ctx)
resp, err := client.CreateMachine(ctx, req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printMachines(c.f.tsv, resp)
return 0
} | go | func (c *AddMachineCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
// TODO(smut): Validate required fields client-side.
req := &crimson.CreateMachineRequest{
Machine: &c.machine,
}
client := getClient(ctx)
resp, err := client.CreateMachine(ctx, req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printMachines(c.f.tsv, resp)
return 0
} | [
"func",
"(",
"c",
"*",
"AddMachineCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"c",
",",
"env",
")",
"\n",
"// TODO(smut): Validate required fields client-side.",
"req",
":=",
"&",
"crimson",
".",
"CreateMachineRequest",
"{",
"Machine",
":",
"&",
"c",
".",
"machine",
",",
"}",
"\n",
"client",
":=",
"getClient",
"(",
"ctx",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"CreateMachine",
"(",
"ctx",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Log",
"(",
"ctx",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"printMachines",
"(",
"c",
".",
"f",
".",
"tsv",
",",
"resp",
")",
"\n",
"return",
"0",
"\n",
"}"
] | // Run runs the command to add a machine. | [
"Run",
"runs",
"the",
"command",
"to",
"add",
"a",
"machine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/machines.go#L48-L62 |
8,444 | luci/luci-go | machine-db/client/cli/machines.go | addMachineCmd | func addMachineCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "add-machine -name <name> -plat <platform> -rack <rack> -state <state> [-desc <description>] [-atag <asset tag>] [-stag <service tag>] [-tick <deployment ticket>] [-dracpass <DRAC password>]",
ShortDesc: "adds a machine",
LongDesc: "Adds a machine to the database.\n\nExample:\ncrimson add-machine -name xx11-11-720 -plat 'Apple Mac Pro' -rack xx1 -state test -stag BC0001",
CommandRun: func() subcommands.CommandRun {
cmd := &AddMachineCmd{}
cmd.Initialize(params)
cmd.Flags.StringVar(&cmd.machine.Name, "name", "", "The name of the machine. Required and must be unique within the database.")
cmd.Flags.StringVar(&cmd.machine.Platform, "plat", "", "The platform type this machine is. Required and must be the name of a platform returned by get-platforms.")
cmd.Flags.StringVar(&cmd.machine.Rack, "rack", "", "The rack this machine belongs to. Required and must be the name of a rack returned by get-racks.")
cmd.Flags.Var(StateFlag(&cmd.machine.State), "state", "The state of this machine. Required and must be a state returned by get-states.")
cmd.Flags.StringVar(&cmd.machine.Description, "desc", "", "A description of this machine.")
cmd.Flags.StringVar(&cmd.machine.AssetTag, "atag", "", "The asset tag associated with this machine.")
cmd.Flags.StringVar(&cmd.machine.ServiceTag, "stag", "", "The service tag associated with this machine.")
cmd.Flags.StringVar(&cmd.machine.DeploymentTicket, "tick", "", "The deployment ticket associated with this machine.")
cmd.Flags.StringVar(&cmd.machine.DracPassword, "dracpass", "", "The initial DRAC password associated with this machine.")
return cmd
},
}
} | go | func addMachineCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "add-machine -name <name> -plat <platform> -rack <rack> -state <state> [-desc <description>] [-atag <asset tag>] [-stag <service tag>] [-tick <deployment ticket>] [-dracpass <DRAC password>]",
ShortDesc: "adds a machine",
LongDesc: "Adds a machine to the database.\n\nExample:\ncrimson add-machine -name xx11-11-720 -plat 'Apple Mac Pro' -rack xx1 -state test -stag BC0001",
CommandRun: func() subcommands.CommandRun {
cmd := &AddMachineCmd{}
cmd.Initialize(params)
cmd.Flags.StringVar(&cmd.machine.Name, "name", "", "The name of the machine. Required and must be unique within the database.")
cmd.Flags.StringVar(&cmd.machine.Platform, "plat", "", "The platform type this machine is. Required and must be the name of a platform returned by get-platforms.")
cmd.Flags.StringVar(&cmd.machine.Rack, "rack", "", "The rack this machine belongs to. Required and must be the name of a rack returned by get-racks.")
cmd.Flags.Var(StateFlag(&cmd.machine.State), "state", "The state of this machine. Required and must be a state returned by get-states.")
cmd.Flags.StringVar(&cmd.machine.Description, "desc", "", "A description of this machine.")
cmd.Flags.StringVar(&cmd.machine.AssetTag, "atag", "", "The asset tag associated with this machine.")
cmd.Flags.StringVar(&cmd.machine.ServiceTag, "stag", "", "The service tag associated with this machine.")
cmd.Flags.StringVar(&cmd.machine.DeploymentTicket, "tick", "", "The deployment ticket associated with this machine.")
cmd.Flags.StringVar(&cmd.machine.DracPassword, "dracpass", "", "The initial DRAC password associated with this machine.")
return cmd
},
}
} | [
"func",
"addMachineCmd",
"(",
"params",
"*",
"Parameters",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
",",
"CommandRun",
":",
"func",
"(",
")",
"subcommands",
".",
"CommandRun",
"{",
"cmd",
":=",
"&",
"AddMachineCmd",
"{",
"}",
"\n",
"cmd",
".",
"Initialize",
"(",
"params",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"machine",
".",
"Name",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"machine",
".",
"Platform",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"machine",
".",
"Rack",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"StateFlag",
"(",
"&",
"cmd",
".",
"machine",
".",
"State",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"machine",
".",
"Description",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"machine",
".",
"AssetTag",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"machine",
".",
"ServiceTag",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"machine",
".",
"DeploymentTicket",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"machine",
".",
"DracPassword",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"cmd",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // addMachineCmd returns a command to add a machine. | [
"addMachineCmd",
"returns",
"a",
"command",
"to",
"add",
"a",
"machine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/machines.go#L65-L85 |
8,445 | luci/luci-go | machine-db/client/cli/machines.go | deleteMachineCmd | func deleteMachineCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "del-machine -name <name>",
ShortDesc: "deletes a machine",
LongDesc: "Deletes a machine from the database.\n\nExample:\ncrimson del-machine -name xx11-11-720",
CommandRun: func() subcommands.CommandRun {
cmd := &DeleteMachineCmd{}
cmd.Initialize(params)
cmd.Flags.StringVar(&cmd.req.Name, "name", "", "The name of the machine to delete.")
return cmd
},
}
} | go | func deleteMachineCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "del-machine -name <name>",
ShortDesc: "deletes a machine",
LongDesc: "Deletes a machine from the database.\n\nExample:\ncrimson del-machine -name xx11-11-720",
CommandRun: func() subcommands.CommandRun {
cmd := &DeleteMachineCmd{}
cmd.Initialize(params)
cmd.Flags.StringVar(&cmd.req.Name, "name", "", "The name of the machine to delete.")
return cmd
},
}
} | [
"func",
"deleteMachineCmd",
"(",
"params",
"*",
"Parameters",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
",",
"CommandRun",
":",
"func",
"(",
")",
"subcommands",
".",
"CommandRun",
"{",
"cmd",
":=",
"&",
"DeleteMachineCmd",
"{",
"}",
"\n",
"cmd",
".",
"Initialize",
"(",
"params",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"req",
".",
"Name",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"cmd",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // deleteMachineCmd returns a command to delete a machine. | [
"deleteMachineCmd",
"returns",
"a",
"command",
"to",
"delete",
"a",
"machine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/machines.go#L107-L119 |
8,446 | luci/luci-go | machine-db/client/cli/machines.go | Run | func (c *EditMachineCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
// TODO(smut): Validate required fields client-side.
req := &crimson.UpdateMachineRequest{
Machine: &c.machine,
UpdateMask: getUpdateMask(&c.Flags, map[string]string{
"plat": "platform",
"rack": "rack",
"state": "state",
"desc": "description",
"atag": "asset_tag",
"stag": "service_tag",
"tick": "deployment_ticket",
"dracpass": "drac_password",
}),
}
client := getClient(ctx)
resp, err := client.UpdateMachine(ctx, req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printMachines(c.f.tsv, resp)
return 0
} | go | func (c *EditMachineCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
// TODO(smut): Validate required fields client-side.
req := &crimson.UpdateMachineRequest{
Machine: &c.machine,
UpdateMask: getUpdateMask(&c.Flags, map[string]string{
"plat": "platform",
"rack": "rack",
"state": "state",
"desc": "description",
"atag": "asset_tag",
"stag": "service_tag",
"tick": "deployment_ticket",
"dracpass": "drac_password",
}),
}
client := getClient(ctx)
resp, err := client.UpdateMachine(ctx, req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printMachines(c.f.tsv, resp)
return 0
} | [
"func",
"(",
"c",
"*",
"EditMachineCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"c",
",",
"env",
")",
"\n",
"// TODO(smut): Validate required fields client-side.",
"req",
":=",
"&",
"crimson",
".",
"UpdateMachineRequest",
"{",
"Machine",
":",
"&",
"c",
".",
"machine",
",",
"UpdateMask",
":",
"getUpdateMask",
"(",
"&",
"c",
".",
"Flags",
",",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"}",
")",
",",
"}",
"\n",
"client",
":=",
"getClient",
"(",
"ctx",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"UpdateMachine",
"(",
"ctx",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Log",
"(",
"ctx",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"printMachines",
"(",
"c",
".",
"f",
".",
"tsv",
",",
"resp",
")",
"\n",
"return",
"0",
"\n",
"}"
] | // Run runs the command to edit a machine. | [
"Run",
"runs",
"the",
"command",
"to",
"edit",
"a",
"machine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/machines.go#L128-L152 |
8,447 | luci/luci-go | machine-db/client/cli/machines.go | Run | func (c *GetMachinesCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListMachines(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printMachines(c.f.tsv, resp.Machines...)
return 0
} | go | func (c *GetMachinesCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListMachines(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printMachines(c.f.tsv, resp.Machines...)
return 0
} | [
"func",
"(",
"c",
"*",
"GetMachinesCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"c",
",",
"env",
")",
"\n",
"client",
":=",
"getClient",
"(",
"ctx",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"ListMachines",
"(",
"ctx",
",",
"&",
"c",
".",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Log",
"(",
"ctx",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"printMachines",
"(",
"c",
".",
"f",
".",
"tsv",
",",
"resp",
".",
"Machines",
"...",
")",
"\n",
"return",
"0",
"\n",
"}"
] | // Run runs the command to get machines. | [
"Run",
"runs",
"the",
"command",
"to",
"get",
"machines",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/machines.go#L184-L194 |
8,448 | luci/luci-go | machine-db/client/cli/machines.go | getMachinesCmd | func getMachinesCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-machines [-name <name>]... [-plat <plat>]... [-rack <rack>]... [-dc <dc>]... [-state <state>]...",
ShortDesc: "retrieves machines",
LongDesc: "Retrieves machines matching the given names, platforms, racks, and states, or all machines if names are omitted.\n\nExample to get all machines:\ncrimson get-machines\nExample to get all machines in rack xx1 that are in repair state:\ncrimson get-machines -rack xx1 -state repair",
CommandRun: func() subcommands.CommandRun {
cmd := &GetMachinesCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a machine 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(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.")
return cmd
},
}
} | go | func getMachinesCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-machines [-name <name>]... [-plat <plat>]... [-rack <rack>]... [-dc <dc>]... [-state <state>]...",
ShortDesc: "retrieves machines",
LongDesc: "Retrieves machines matching the given names, platforms, racks, and states, or all machines if names are omitted.\n\nExample to get all machines:\ncrimson get-machines\nExample to get all machines in rack xx1 that are in repair state:\ncrimson get-machines -rack xx1 -state repair",
CommandRun: func() subcommands.CommandRun {
cmd := &GetMachinesCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a machine 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(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.")
return cmd
},
}
} | [
"func",
"getMachinesCmd",
"(",
"params",
"*",
"Parameters",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\\n",
"\\n",
"\\n",
"\\n",
"\\n",
"\"",
",",
"CommandRun",
":",
"func",
"(",
")",
"subcommands",
".",
"CommandRun",
"{",
"cmd",
":=",
"&",
"GetMachinesCmd",
"{",
"}",
"\n",
"cmd",
".",
"Initialize",
"(",
"params",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Names",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\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",
"(",
"StateSliceFlag",
"(",
"&",
"cmd",
".",
"req",
".",
"States",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"cmd",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // getMachinesCmd returns a command to get machines. | [
"getMachinesCmd",
"returns",
"a",
"command",
"to",
"get",
"machines",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/machines.go#L197-L213 |
8,449 | luci/luci-go | machine-db/client/cli/machines.go | renameMachineCmd | func renameMachineCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "name-machine -old <name> -new <name>",
ShortDesc: "renames a machine",
LongDesc: "Renames a machine in the database.\n\nExample:\ncrimson name-machine -old xx01-07-720 -new yy01-07-720",
CommandRun: func() subcommands.CommandRun {
cmd := &RenameMachineCmd{}
cmd.Initialize(params)
cmd.Flags.StringVar(&cmd.req.Name, "old", "", "The name of the machine. Required and must be the name of a machine returned by get-machines.")
cmd.Flags.StringVar(&cmd.req.NewName, "new", "", "The new name of the machine. Required and must be unique within the database.")
return cmd
},
}
} | go | func renameMachineCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "name-machine -old <name> -new <name>",
ShortDesc: "renames a machine",
LongDesc: "Renames a machine in the database.\n\nExample:\ncrimson name-machine -old xx01-07-720 -new yy01-07-720",
CommandRun: func() subcommands.CommandRun {
cmd := &RenameMachineCmd{}
cmd.Initialize(params)
cmd.Flags.StringVar(&cmd.req.Name, "old", "", "The name of the machine. Required and must be the name of a machine returned by get-machines.")
cmd.Flags.StringVar(&cmd.req.NewName, "new", "", "The new name of the machine. Required and must be unique within the database.")
return cmd
},
}
} | [
"func",
"renameMachineCmd",
"(",
"params",
"*",
"Parameters",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
",",
"CommandRun",
":",
"func",
"(",
")",
"subcommands",
".",
"CommandRun",
"{",
"cmd",
":=",
"&",
"RenameMachineCmd",
"{",
"}",
"\n",
"cmd",
".",
"Initialize",
"(",
"params",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"req",
".",
"Name",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"StringVar",
"(",
"&",
"cmd",
".",
"req",
".",
"NewName",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"cmd",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // renameMachineCmd returns a command to rename a machine. | [
"renameMachineCmd",
"returns",
"a",
"command",
"to",
"rename",
"a",
"machine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/machines.go#L236-L249 |
8,450 | luci/luci-go | appengine/tsmon/tasknum.go | NotifyTaskIsAlive | func (DatastoreTaskNumAllocator) NotifyTaskIsAlive(c context.Context, task *target.Task, instanceID string) (taskNum int, err error) {
c = dsContext(c)
// Exact values here are not important. Important properties are:
// * 'entityID' is unique, and depends on both 'task' and 'instanceID'.
// * All instances from same task have same 'target' value.
//
// The cron ('AssignTaskNumbers') will fetch all entities and will group them
// by 'target' value before assigning task numbers.
target := fmt.Sprintf("%s|%s|%s|%s", task.DataCenter, task.ServiceName, task.JobName, task.HostName)
entityID := fmt.Sprintf("%s|%s", target, instanceID)
err = datastore.RunInTransaction(c, func(c context.Context) error {
entity := instance{ID: entityID}
switch err := datastore.Get(c, &entity); {
case err == datastore.ErrNoSuchEntity:
entity.Target = target
entity.TaskNum = -1
case err != nil:
return err
}
entity.LastUpdated = clock.Now(c).UTC()
taskNum = entity.TaskNum
return datastore.Put(c, &entity)
}, nil)
if err == nil && taskNum == -1 {
err = tsmon.ErrNoTaskNumber
}
return
} | go | func (DatastoreTaskNumAllocator) NotifyTaskIsAlive(c context.Context, task *target.Task, instanceID string) (taskNum int, err error) {
c = dsContext(c)
// Exact values here are not important. Important properties are:
// * 'entityID' is unique, and depends on both 'task' and 'instanceID'.
// * All instances from same task have same 'target' value.
//
// The cron ('AssignTaskNumbers') will fetch all entities and will group them
// by 'target' value before assigning task numbers.
target := fmt.Sprintf("%s|%s|%s|%s", task.DataCenter, task.ServiceName, task.JobName, task.HostName)
entityID := fmt.Sprintf("%s|%s", target, instanceID)
err = datastore.RunInTransaction(c, func(c context.Context) error {
entity := instance{ID: entityID}
switch err := datastore.Get(c, &entity); {
case err == datastore.ErrNoSuchEntity:
entity.Target = target
entity.TaskNum = -1
case err != nil:
return err
}
entity.LastUpdated = clock.Now(c).UTC()
taskNum = entity.TaskNum
return datastore.Put(c, &entity)
}, nil)
if err == nil && taskNum == -1 {
err = tsmon.ErrNoTaskNumber
}
return
} | [
"func",
"(",
"DatastoreTaskNumAllocator",
")",
"NotifyTaskIsAlive",
"(",
"c",
"context",
".",
"Context",
",",
"task",
"*",
"target",
".",
"Task",
",",
"instanceID",
"string",
")",
"(",
"taskNum",
"int",
",",
"err",
"error",
")",
"{",
"c",
"=",
"dsContext",
"(",
"c",
")",
"\n\n",
"// Exact values here are not important. Important properties are:",
"// * 'entityID' is unique, and depends on both 'task' and 'instanceID'.",
"// * All instances from same task have same 'target' value.",
"//",
"// The cron ('AssignTaskNumbers') will fetch all entities and will group them",
"// by 'target' value before assigning task numbers.",
"target",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"task",
".",
"DataCenter",
",",
"task",
".",
"ServiceName",
",",
"task",
".",
"JobName",
",",
"task",
".",
"HostName",
")",
"\n",
"entityID",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"target",
",",
"instanceID",
")",
"\n\n",
"err",
"=",
"datastore",
".",
"RunInTransaction",
"(",
"c",
",",
"func",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"entity",
":=",
"instance",
"{",
"ID",
":",
"entityID",
"}",
"\n",
"switch",
"err",
":=",
"datastore",
".",
"Get",
"(",
"c",
",",
"&",
"entity",
")",
";",
"{",
"case",
"err",
"==",
"datastore",
".",
"ErrNoSuchEntity",
":",
"entity",
".",
"Target",
"=",
"target",
"\n",
"entity",
".",
"TaskNum",
"=",
"-",
"1",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"\n",
"}",
"\n",
"entity",
".",
"LastUpdated",
"=",
"clock",
".",
"Now",
"(",
"c",
")",
".",
"UTC",
"(",
")",
"\n",
"taskNum",
"=",
"entity",
".",
"TaskNum",
"\n",
"return",
"datastore",
".",
"Put",
"(",
"c",
",",
"&",
"entity",
")",
"\n",
"}",
",",
"nil",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"taskNum",
"==",
"-",
"1",
"{",
"err",
"=",
"tsmon",
".",
"ErrNoTaskNumber",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NotifyTaskIsAlive is part of TaskNumAllocator interface. | [
"NotifyTaskIsAlive",
"is",
"part",
"of",
"TaskNumAllocator",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/tsmon/tasknum.go#L45-L74 |
8,451 | luci/luci-go | appengine/tsmon/tasknum.go | dsContext | func dsContext(c context.Context) context.Context {
c = info.MustNamespace(c, DatastoreNamespace)
return dscache.AddShardFunctions(c, func(*datastore.Key) (shards int, ok bool) {
return 0, true
})
} | go | func dsContext(c context.Context) context.Context {
c = info.MustNamespace(c, DatastoreNamespace)
return dscache.AddShardFunctions(c, func(*datastore.Key) (shards int, ok bool) {
return 0, true
})
} | [
"func",
"dsContext",
"(",
"c",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"c",
"=",
"info",
".",
"MustNamespace",
"(",
"c",
",",
"DatastoreNamespace",
")",
"\n",
"return",
"dscache",
".",
"AddShardFunctions",
"(",
"c",
",",
"func",
"(",
"*",
"datastore",
".",
"Key",
")",
"(",
"shards",
"int",
",",
"ok",
"bool",
")",
"{",
"return",
"0",
",",
"true",
"\n",
"}",
")",
"\n",
"}"
] | // dsContext is used for all datastore accesses that touch 'instance' entities.
//
// It switches the namespace and disables dscache, since these entities are
// updated from Flex, which doesn't work with dscache. Besides, all reads happen
// either in transactions or through queries - dscache is useless anyhow. | [
"dsContext",
"is",
"used",
"for",
"all",
"datastore",
"accesses",
"that",
"touch",
"instance",
"entities",
".",
"It",
"switches",
"the",
"namespace",
"and",
"disables",
"dscache",
"since",
"these",
"entities",
"are",
"updated",
"from",
"Flex",
"which",
"doesn",
"t",
"work",
"with",
"dscache",
".",
"Besides",
"all",
"reads",
"happen",
"either",
"in",
"transactions",
"or",
"through",
"queries",
"-",
"dscache",
"is",
"useless",
"anyhow",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/tsmon/tasknum.go#L149-L154 |
8,452 | luci/luci-go | common/logging/gologger/logger.go | formatWithFields | func formatWithFields(format string, fields logging.Fields, args []interface{}) string {
fieldString := fields.String()
buf := bytes.Buffer{}
buf.Grow(len(format) + logMessageFieldPadding + len(fieldString))
fmt.Fprintf(&buf, format, args...)
padding := 44 - buf.Len()
if padding < 1 {
padding = 1
}
for i := 0; i < padding; i++ {
buf.WriteString(" ")
}
buf.WriteString(fieldString)
return buf.String()
} | go | func formatWithFields(format string, fields logging.Fields, args []interface{}) string {
fieldString := fields.String()
buf := bytes.Buffer{}
buf.Grow(len(format) + logMessageFieldPadding + len(fieldString))
fmt.Fprintf(&buf, format, args...)
padding := 44 - buf.Len()
if padding < 1 {
padding = 1
}
for i := 0; i < padding; i++ {
buf.WriteString(" ")
}
buf.WriteString(fieldString)
return buf.String()
} | [
"func",
"formatWithFields",
"(",
"format",
"string",
",",
"fields",
"logging",
".",
"Fields",
",",
"args",
"[",
"]",
"interface",
"{",
"}",
")",
"string",
"{",
"fieldString",
":=",
"fields",
".",
"String",
"(",
")",
"\n\n",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"buf",
".",
"Grow",
"(",
"len",
"(",
"format",
")",
"+",
"logMessageFieldPadding",
"+",
"len",
"(",
"fieldString",
")",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"format",
",",
"args",
"...",
")",
"\n\n",
"padding",
":=",
"44",
"-",
"buf",
".",
"Len",
"(",
")",
"\n",
"if",
"padding",
"<",
"1",
"{",
"padding",
"=",
"1",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"padding",
";",
"i",
"++",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"fieldString",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // formatWithFields renders the supplied format string, adding fields. | [
"formatWithFields",
"renders",
"the",
"supplied",
"format",
"string",
"adding",
"fields",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/gologger/logger.go#L91-L107 |
8,453 | luci/luci-go | client/downloader/downloader.go | normalizePathSeparator | func normalizePathSeparator(p string) string {
if filepath.Separator == '/' {
return strings.Replace(p, `\`, string(filepath.Separator), -1)
}
return strings.Replace(p, "/", string(filepath.Separator), -1)
} | go | func normalizePathSeparator(p string) string {
if filepath.Separator == '/' {
return strings.Replace(p, `\`, string(filepath.Separator), -1)
}
return strings.Replace(p, "/", string(filepath.Separator), -1)
} | [
"func",
"normalizePathSeparator",
"(",
"p",
"string",
")",
"string",
"{",
"if",
"filepath",
".",
"Separator",
"==",
"'/'",
"{",
"return",
"strings",
".",
"Replace",
"(",
"p",
",",
"`\\`",
",",
"string",
"(",
"filepath",
".",
"Separator",
")",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Replace",
"(",
"p",
",",
"\"",
"\"",
",",
"string",
"(",
"filepath",
".",
"Separator",
")",
",",
"-",
"1",
")",
"\n",
"}"
] | // normalizePathSeparator returns path having os native path separator. | [
"normalizePathSeparator",
"returns",
"path",
"having",
"os",
"native",
"path",
"separator",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/downloader/downloader.go#L123-L128 |
8,454 | luci/luci-go | client/downloader/downloader.go | New | func New(ctx context.Context, c *isolatedclient.Client, hash isolated.HexDigest,
outputDir string, options *Options) *Downloader {
var opt Options
if options != nil {
opt = *options
}
if opt.MaxConcurrentJobs == 0 {
opt.MaxConcurrentJobs = 8
}
if opt.MaxFileStatsInterval == 0 {
opt.MaxFileStatsInterval = time.Second * 5
}
interval := 100 * time.Millisecond
if interval > opt.MaxFileStatsInterval {
interval = opt.MaxFileStatsInterval
}
ctx2, cancel := context.WithCancel(ctx)
ret := &Downloader{
ctx: ctx2,
cancel: cancel,
c: c,
options: opt,
interval: interval,
dirCache: stringset.New(0),
rootHash: hash,
outputDir: normalizePathSeparator(outputDir),
isoMap: map[isolated.HexDigest]*isolated.Isolated{},
}
return ret
} | go | func New(ctx context.Context, c *isolatedclient.Client, hash isolated.HexDigest,
outputDir string, options *Options) *Downloader {
var opt Options
if options != nil {
opt = *options
}
if opt.MaxConcurrentJobs == 0 {
opt.MaxConcurrentJobs = 8
}
if opt.MaxFileStatsInterval == 0 {
opt.MaxFileStatsInterval = time.Second * 5
}
interval := 100 * time.Millisecond
if interval > opt.MaxFileStatsInterval {
interval = opt.MaxFileStatsInterval
}
ctx2, cancel := context.WithCancel(ctx)
ret := &Downloader{
ctx: ctx2,
cancel: cancel,
c: c,
options: opt,
interval: interval,
dirCache: stringset.New(0),
rootHash: hash,
outputDir: normalizePathSeparator(outputDir),
isoMap: map[isolated.HexDigest]*isolated.Isolated{},
}
return ret
} | [
"func",
"New",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"isolatedclient",
".",
"Client",
",",
"hash",
"isolated",
".",
"HexDigest",
",",
"outputDir",
"string",
",",
"options",
"*",
"Options",
")",
"*",
"Downloader",
"{",
"var",
"opt",
"Options",
"\n",
"if",
"options",
"!=",
"nil",
"{",
"opt",
"=",
"*",
"options",
"\n",
"}",
"\n",
"if",
"opt",
".",
"MaxConcurrentJobs",
"==",
"0",
"{",
"opt",
".",
"MaxConcurrentJobs",
"=",
"8",
"\n",
"}",
"\n",
"if",
"opt",
".",
"MaxFileStatsInterval",
"==",
"0",
"{",
"opt",
".",
"MaxFileStatsInterval",
"=",
"time",
".",
"Second",
"*",
"5",
"\n",
"}",
"\n\n",
"interval",
":=",
"100",
"*",
"time",
".",
"Millisecond",
"\n",
"if",
"interval",
">",
"opt",
".",
"MaxFileStatsInterval",
"{",
"interval",
"=",
"opt",
".",
"MaxFileStatsInterval",
"\n",
"}",
"\n\n",
"ctx2",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n",
"ret",
":=",
"&",
"Downloader",
"{",
"ctx",
":",
"ctx2",
",",
"cancel",
":",
"cancel",
",",
"c",
":",
"c",
",",
"options",
":",
"opt",
",",
"interval",
":",
"interval",
",",
"dirCache",
":",
"stringset",
".",
"New",
"(",
"0",
")",
",",
"rootHash",
":",
"hash",
",",
"outputDir",
":",
"normalizePathSeparator",
"(",
"outputDir",
")",
",",
"isoMap",
":",
"map",
"[",
"isolated",
".",
"HexDigest",
"]",
"*",
"isolated",
".",
"Isolated",
"{",
"}",
",",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // New returns a Downloader instance, good to download one isolated.
//
// ctx will be used for logging and clock.
//
// The Client, hash and outputDir must be specified.
//
// If options is nil, this will use defaults as described in the Options struct. | [
"New",
"returns",
"a",
"Downloader",
"instance",
"good",
"to",
"download",
"one",
"isolated",
".",
"ctx",
"will",
"be",
"used",
"for",
"logging",
"and",
"clock",
".",
"The",
"Client",
"hash",
"and",
"outputDir",
"must",
"be",
"specified",
".",
"If",
"options",
"is",
"nil",
"this",
"will",
"use",
"defaults",
"as",
"described",
"in",
"the",
"Options",
"struct",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/downloader/downloader.go#L137-L169 |
8,455 | luci/luci-go | client/downloader/downloader.go | Start | func (d *Downloader) Start() {
d.mu.Lock()
defer d.mu.Unlock()
if d.started {
return
}
d.started = true
d.pool = common.NewGoroutinePriorityPool(d.ctx, d.options.MaxConcurrentJobs)
if err := d.ensureDir(d.outputDir); err != nil {
d.addError(isolatedType, "<isolated setup>", err)
d.cancel()
return
}
// Start downloading the isolated tree in the work pool.
d.scheduleIsolatedJob(d.rootHash)
} | go | func (d *Downloader) Start() {
d.mu.Lock()
defer d.mu.Unlock()
if d.started {
return
}
d.started = true
d.pool = common.NewGoroutinePriorityPool(d.ctx, d.options.MaxConcurrentJobs)
if err := d.ensureDir(d.outputDir); err != nil {
d.addError(isolatedType, "<isolated setup>", err)
d.cancel()
return
}
// Start downloading the isolated tree in the work pool.
d.scheduleIsolatedJob(d.rootHash)
} | [
"func",
"(",
"d",
"*",
"Downloader",
")",
"Start",
"(",
")",
"{",
"d",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"d",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"d",
".",
"started",
"{",
"return",
"\n",
"}",
"\n",
"d",
".",
"started",
"=",
"true",
"\n\n",
"d",
".",
"pool",
"=",
"common",
".",
"NewGoroutinePriorityPool",
"(",
"d",
".",
"ctx",
",",
"d",
".",
"options",
".",
"MaxConcurrentJobs",
")",
"\n\n",
"if",
"err",
":=",
"d",
".",
"ensureDir",
"(",
"d",
".",
"outputDir",
")",
";",
"err",
"!=",
"nil",
"{",
"d",
".",
"addError",
"(",
"isolatedType",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"d",
".",
"cancel",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Start downloading the isolated tree in the work pool.",
"d",
".",
"scheduleIsolatedJob",
"(",
"d",
".",
"rootHash",
")",
"\n",
"}"
] | // Start begins downloading the isolated. | [
"Start",
"begins",
"downloading",
"the",
"isolated",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/downloader/downloader.go#L172-L190 |
8,456 | luci/luci-go | client/downloader/downloader.go | CmdAndCwd | func (d *Downloader) CmdAndCwd() ([]string, string, error) {
d.mu.Lock()
finished := d.finished
d.mu.Unlock()
if !finished {
return nil, "", errors.New(
"can only call CumulativeIsolated on a finished Downloader")
}
if d.err != nil {
return nil, "", d.err
}
queue := []*isolated.Isolated{d.isoMap[d.rootHash]}
for len(queue) > 0 {
iso := queue[0]
if len(iso.Command) > 0 {
return iso.Command, iso.RelativeCwd, nil
}
toPrepend := []*isolated.Isolated{}
for _, inc := range iso.Includes {
toPrepend = append(toPrepend, d.isoMap[inc])
}
queue = append(toPrepend, queue[1:]...)
}
return nil, "", nil
} | go | func (d *Downloader) CmdAndCwd() ([]string, string, error) {
d.mu.Lock()
finished := d.finished
d.mu.Unlock()
if !finished {
return nil, "", errors.New(
"can only call CumulativeIsolated on a finished Downloader")
}
if d.err != nil {
return nil, "", d.err
}
queue := []*isolated.Isolated{d.isoMap[d.rootHash]}
for len(queue) > 0 {
iso := queue[0]
if len(iso.Command) > 0 {
return iso.Command, iso.RelativeCwd, nil
}
toPrepend := []*isolated.Isolated{}
for _, inc := range iso.Includes {
toPrepend = append(toPrepend, d.isoMap[inc])
}
queue = append(toPrepend, queue[1:]...)
}
return nil, "", nil
} | [
"func",
"(",
"d",
"*",
"Downloader",
")",
"CmdAndCwd",
"(",
")",
"(",
"[",
"]",
"string",
",",
"string",
",",
"error",
")",
"{",
"d",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"finished",
":=",
"d",
".",
"finished",
"\n",
"d",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"finished",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"d",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"d",
".",
"err",
"\n",
"}",
"\n\n",
"queue",
":=",
"[",
"]",
"*",
"isolated",
".",
"Isolated",
"{",
"d",
".",
"isoMap",
"[",
"d",
".",
"rootHash",
"]",
"}",
"\n\n",
"for",
"len",
"(",
"queue",
")",
">",
"0",
"{",
"iso",
":=",
"queue",
"[",
"0",
"]",
"\n\n",
"if",
"len",
"(",
"iso",
".",
"Command",
")",
">",
"0",
"{",
"return",
"iso",
".",
"Command",
",",
"iso",
".",
"RelativeCwd",
",",
"nil",
"\n",
"}",
"\n\n",
"toPrepend",
":=",
"[",
"]",
"*",
"isolated",
".",
"Isolated",
"{",
"}",
"\n",
"for",
"_",
",",
"inc",
":=",
"range",
"iso",
".",
"Includes",
"{",
"toPrepend",
"=",
"append",
"(",
"toPrepend",
",",
"d",
".",
"isoMap",
"[",
"inc",
"]",
")",
"\n",
"}",
"\n",
"queue",
"=",
"append",
"(",
"toPrepend",
",",
"queue",
"[",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}"
] | // CmdAndCwd returns the effective command and relative_cwd entries
// from the fetched isolated.
//
// Must be called after the Downloader is completed.
//
// Note that new uses of isolated should NOT use cmd or relative_cwd! | [
"CmdAndCwd",
"returns",
"the",
"effective",
"command",
"and",
"relative_cwd",
"entries",
"from",
"the",
"fetched",
"isolated",
".",
"Must",
"be",
"called",
"after",
"the",
"Downloader",
"is",
"completed",
".",
"Note",
"that",
"new",
"uses",
"of",
"isolated",
"should",
"NOT",
"use",
"cmd",
"or",
"relative_cwd!"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/downloader/downloader.go#L218-L248 |
8,457 | luci/luci-go | client/downloader/downloader.go | ensureDir | func (d *Downloader) ensureDir(dir string) error {
dir = normalizePathSeparator(dir)
// Fast path: if the cache has the directory, we're done.
d.muCache.RLock()
cached := d.dirCache.Has(dir)
d.muCache.RUnlock()
if cached {
return nil
}
// Slow path: collect the directory and its parents, then create
// them and add them to the cache.
d.muCache.Lock()
defer d.muCache.Unlock()
parents := make([]string, 0, 1)
for i := dir; i != "" && !d.dirCache.Has(i); i = filepath.Dir(i) {
if i == d.outputDir {
break
}
parents = append(parents, i)
}
for i := len(parents) - 1; i >= 0; i-- {
if err := os.Mkdir(parents[i], os.ModePerm); err != nil && !os.IsExist(err) {
return err
}
d.dirCache.Add(parents[i])
}
return nil
} | go | func (d *Downloader) ensureDir(dir string) error {
dir = normalizePathSeparator(dir)
// Fast path: if the cache has the directory, we're done.
d.muCache.RLock()
cached := d.dirCache.Has(dir)
d.muCache.RUnlock()
if cached {
return nil
}
// Slow path: collect the directory and its parents, then create
// them and add them to the cache.
d.muCache.Lock()
defer d.muCache.Unlock()
parents := make([]string, 0, 1)
for i := dir; i != "" && !d.dirCache.Has(i); i = filepath.Dir(i) {
if i == d.outputDir {
break
}
parents = append(parents, i)
}
for i := len(parents) - 1; i >= 0; i-- {
if err := os.Mkdir(parents[i], os.ModePerm); err != nil && !os.IsExist(err) {
return err
}
d.dirCache.Add(parents[i])
}
return nil
} | [
"func",
"(",
"d",
"*",
"Downloader",
")",
"ensureDir",
"(",
"dir",
"string",
")",
"error",
"{",
"dir",
"=",
"normalizePathSeparator",
"(",
"dir",
")",
"\n",
"// Fast path: if the cache has the directory, we're done.",
"d",
".",
"muCache",
".",
"RLock",
"(",
")",
"\n",
"cached",
":=",
"d",
".",
"dirCache",
".",
"Has",
"(",
"dir",
")",
"\n",
"d",
".",
"muCache",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"cached",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Slow path: collect the directory and its parents, then create",
"// them and add them to the cache.",
"d",
".",
"muCache",
".",
"Lock",
"(",
")",
"\n",
"defer",
"d",
".",
"muCache",
".",
"Unlock",
"(",
")",
"\n",
"parents",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"1",
")",
"\n",
"for",
"i",
":=",
"dir",
";",
"i",
"!=",
"\"",
"\"",
"&&",
"!",
"d",
".",
"dirCache",
".",
"Has",
"(",
"i",
")",
";",
"i",
"=",
"filepath",
".",
"Dir",
"(",
"i",
")",
"{",
"if",
"i",
"==",
"d",
".",
"outputDir",
"{",
"break",
"\n",
"}",
"\n",
"parents",
"=",
"append",
"(",
"parents",
",",
"i",
")",
"\n",
"}",
"\n",
"for",
"i",
":=",
"len",
"(",
"parents",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"if",
"err",
":=",
"os",
".",
"Mkdir",
"(",
"parents",
"[",
"i",
"]",
",",
"os",
".",
"ModePerm",
")",
";",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n",
"d",
".",
"dirCache",
".",
"Add",
"(",
"parents",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ensureDir ensures that the directory dir exists. | [
"ensureDir",
"ensures",
"that",
"the",
"directory",
"dir",
"exists",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/downloader/downloader.go#L332-L360 |
8,458 | luci/luci-go | client/downloader/downloader.go | StatLine | func (f *FileStats) StatLine(previous *FileStats, span time.Duration) string {
var bytesDownloaded uint64
if previous != nil {
bytesDownloaded = f.BytesCompleted - previous.BytesCompleted
}
return fmt.Sprintf("Files (%d/%d) - %s / %s - %0.1f%% - %s/s",
f.CountCompleted, f.CountScheduled,
humanize.Bytes(f.BytesCompleted), humanize.Bytes(f.BytesScheduled),
100*float64(f.BytesCompleted)/float64(f.BytesScheduled),
humanize.Bytes(uint64(float64(bytesDownloaded)/span.Seconds())),
)
} | go | func (f *FileStats) StatLine(previous *FileStats, span time.Duration) string {
var bytesDownloaded uint64
if previous != nil {
bytesDownloaded = f.BytesCompleted - previous.BytesCompleted
}
return fmt.Sprintf("Files (%d/%d) - %s / %s - %0.1f%% - %s/s",
f.CountCompleted, f.CountScheduled,
humanize.Bytes(f.BytesCompleted), humanize.Bytes(f.BytesScheduled),
100*float64(f.BytesCompleted)/float64(f.BytesScheduled),
humanize.Bytes(uint64(float64(bytesDownloaded)/span.Seconds())),
)
} | [
"func",
"(",
"f",
"*",
"FileStats",
")",
"StatLine",
"(",
"previous",
"*",
"FileStats",
",",
"span",
"time",
".",
"Duration",
")",
"string",
"{",
"var",
"bytesDownloaded",
"uint64",
"\n",
"if",
"previous",
"!=",
"nil",
"{",
"bytesDownloaded",
"=",
"f",
".",
"BytesCompleted",
"-",
"previous",
".",
"BytesCompleted",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"f",
".",
"CountCompleted",
",",
"f",
".",
"CountScheduled",
",",
"humanize",
".",
"Bytes",
"(",
"f",
".",
"BytesCompleted",
")",
",",
"humanize",
".",
"Bytes",
"(",
"f",
".",
"BytesScheduled",
")",
",",
"100",
"*",
"float64",
"(",
"f",
".",
"BytesCompleted",
")",
"/",
"float64",
"(",
"f",
".",
"BytesScheduled",
")",
",",
"humanize",
".",
"Bytes",
"(",
"uint64",
"(",
"float64",
"(",
"bytesDownloaded",
")",
"/",
"span",
".",
"Seconds",
"(",
")",
")",
")",
",",
")",
"\n",
"}"
] | // StatLine calculates a simple statistics line suitable for logging. | [
"StatLine",
"calculates",
"a",
"simple",
"statistics",
"line",
"suitable",
"for",
"logging",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/downloader/downloader.go#L539-L551 |
8,459 | luci/luci-go | gce/appengine/backend/internal/metrics/metrics.go | UpdateFailures | func UpdateFailures(c context.Context, creations int, vm *model.VM) {
creationFailures.Add(c, int64(creations), vm.Prefix, vm.Attributes.GetProject(), vm.Attributes.GetZone())
} | go | func UpdateFailures(c context.Context, creations int, vm *model.VM) {
creationFailures.Add(c, int64(creations), vm.Prefix, vm.Attributes.GetProject(), vm.Attributes.GetZone())
} | [
"func",
"UpdateFailures",
"(",
"c",
"context",
".",
"Context",
",",
"creations",
"int",
",",
"vm",
"*",
"model",
".",
"VM",
")",
"{",
"creationFailures",
".",
"Add",
"(",
"c",
",",
"int64",
"(",
"creations",
")",
",",
"vm",
".",
"Prefix",
",",
"vm",
".",
"Attributes",
".",
"GetProject",
"(",
")",
",",
"vm",
".",
"Attributes",
".",
"GetZone",
"(",
")",
")",
"\n",
"}"
] | // UpdateFailures increments failure counters. | [
"UpdateFailures",
"increments",
"failure",
"counters",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/internal/metrics/metrics.go#L45-L47 |
8,460 | luci/luci-go | gce/appengine/backend/internal/metrics/metrics.go | AddConfigured | func (ic *InstanceCount) AddConfigured(n int, project string) {
for i, c := range ic.Configured {
if c.Project == project {
ic.Configured[i].Count += n
return
}
}
ic.Configured = append(ic.Configured, configuredCount{
Count: n,
Project: project,
})
} | go | func (ic *InstanceCount) AddConfigured(n int, project string) {
for i, c := range ic.Configured {
if c.Project == project {
ic.Configured[i].Count += n
return
}
}
ic.Configured = append(ic.Configured, configuredCount{
Count: n,
Project: project,
})
} | [
"func",
"(",
"ic",
"*",
"InstanceCount",
")",
"AddConfigured",
"(",
"n",
"int",
",",
"project",
"string",
")",
"{",
"for",
"i",
",",
"c",
":=",
"range",
"ic",
".",
"Configured",
"{",
"if",
"c",
".",
"Project",
"==",
"project",
"{",
"ic",
".",
"Configured",
"[",
"i",
"]",
".",
"Count",
"+=",
"n",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"ic",
".",
"Configured",
"=",
"append",
"(",
"ic",
".",
"Configured",
",",
"configuredCount",
"{",
"Count",
":",
"n",
",",
"Project",
":",
"project",
",",
"}",
")",
"\n",
"}"
] | // AddConfigured increments the count of configured VMs for the given project. | [
"AddConfigured",
"increments",
"the",
"count",
"of",
"configured",
"VMs",
"for",
"the",
"given",
"project",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/internal/metrics/metrics.go#L122-L133 |
8,461 | luci/luci-go | gce/appengine/backend/internal/metrics/metrics.go | AddCreated | func (ic *InstanceCount) AddCreated(n int, project, zone string) {
for i, c := range ic.Created {
if c.Project == project && c.Zone == zone {
ic.Created[i].Count += n
return
}
}
ic.Created = append(ic.Created, createdCount{
Count: n,
Project: project,
Zone: zone,
})
} | go | func (ic *InstanceCount) AddCreated(n int, project, zone string) {
for i, c := range ic.Created {
if c.Project == project && c.Zone == zone {
ic.Created[i].Count += n
return
}
}
ic.Created = append(ic.Created, createdCount{
Count: n,
Project: project,
Zone: zone,
})
} | [
"func",
"(",
"ic",
"*",
"InstanceCount",
")",
"AddCreated",
"(",
"n",
"int",
",",
"project",
",",
"zone",
"string",
")",
"{",
"for",
"i",
",",
"c",
":=",
"range",
"ic",
".",
"Created",
"{",
"if",
"c",
".",
"Project",
"==",
"project",
"&&",
"c",
".",
"Zone",
"==",
"zone",
"{",
"ic",
".",
"Created",
"[",
"i",
"]",
".",
"Count",
"+=",
"n",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"ic",
".",
"Created",
"=",
"append",
"(",
"ic",
".",
"Created",
",",
"createdCount",
"{",
"Count",
":",
"n",
",",
"Project",
":",
"project",
",",
"Zone",
":",
"zone",
",",
"}",
")",
"\n",
"}"
] | // AddCreated increments the count of created VMs for the given project and
// zone. | [
"AddCreated",
"increments",
"the",
"count",
"of",
"created",
"VMs",
"for",
"the",
"given",
"project",
"and",
"zone",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/internal/metrics/metrics.go#L137-L149 |
8,462 | luci/luci-go | gce/appengine/backend/internal/metrics/metrics.go | AddConnected | func (ic *InstanceCount) AddConnected(n int, project, server, zone string) {
for i, c := range ic.Connected {
if c.Project == project && c.Server == server && c.Zone == zone {
ic.Connected[i].Count += n
return
}
}
ic.Connected = append(ic.Connected, connectedCount{
Count: n,
Project: project,
Server: server,
Zone: zone,
})
} | go | func (ic *InstanceCount) AddConnected(n int, project, server, zone string) {
for i, c := range ic.Connected {
if c.Project == project && c.Server == server && c.Zone == zone {
ic.Connected[i].Count += n
return
}
}
ic.Connected = append(ic.Connected, connectedCount{
Count: n,
Project: project,
Server: server,
Zone: zone,
})
} | [
"func",
"(",
"ic",
"*",
"InstanceCount",
")",
"AddConnected",
"(",
"n",
"int",
",",
"project",
",",
"server",
",",
"zone",
"string",
")",
"{",
"for",
"i",
",",
"c",
":=",
"range",
"ic",
".",
"Connected",
"{",
"if",
"c",
".",
"Project",
"==",
"project",
"&&",
"c",
".",
"Server",
"==",
"server",
"&&",
"c",
".",
"Zone",
"==",
"zone",
"{",
"ic",
".",
"Connected",
"[",
"i",
"]",
".",
"Count",
"+=",
"n",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"ic",
".",
"Connected",
"=",
"append",
"(",
"ic",
".",
"Connected",
",",
"connectedCount",
"{",
"Count",
":",
"n",
",",
"Project",
":",
"project",
",",
"Server",
":",
"server",
",",
"Zone",
":",
"zone",
",",
"}",
")",
"\n",
"}"
] | // AddConnected increments the count of connected VMs for the given project,
// server, and zone. | [
"AddConnected",
"increments",
"the",
"count",
"of",
"connected",
"VMs",
"for",
"the",
"given",
"project",
"server",
"and",
"zone",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/internal/metrics/metrics.go#L153-L166 |
8,463 | luci/luci-go | gce/appengine/backend/internal/metrics/metrics.go | Update | func (ic *InstanceCount) Update(c context.Context, prefix string) error {
// Prefixes are globally unique, so we can use them as IDs.
ic.ID = prefix
ic.Computed = clock.Now(c).UTC()
ic.Prefix = prefix
if err := datastore.Put(c, ic); err != nil {
return errors.Annotate(err, "failed to store count").Err()
}
return nil
} | go | func (ic *InstanceCount) Update(c context.Context, prefix string) error {
// Prefixes are globally unique, so we can use them as IDs.
ic.ID = prefix
ic.Computed = clock.Now(c).UTC()
ic.Prefix = prefix
if err := datastore.Put(c, ic); err != nil {
return errors.Annotate(err, "failed to store count").Err()
}
return nil
} | [
"func",
"(",
"ic",
"*",
"InstanceCount",
")",
"Update",
"(",
"c",
"context",
".",
"Context",
",",
"prefix",
"string",
")",
"error",
"{",
"// Prefixes are globally unique, so we can use them as IDs.",
"ic",
".",
"ID",
"=",
"prefix",
"\n",
"ic",
".",
"Computed",
"=",
"clock",
".",
"Now",
"(",
"c",
")",
".",
"UTC",
"(",
")",
"\n",
"ic",
".",
"Prefix",
"=",
"prefix",
"\n",
"if",
"err",
":=",
"datastore",
".",
"Put",
"(",
"c",
",",
"ic",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Update updates metrics for all known counts of VMs for the given prefix. | [
"Update",
"updates",
"metrics",
"for",
"all",
"known",
"counts",
"of",
"VMs",
"for",
"the",
"given",
"prefix",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/internal/metrics/metrics.go#L169-L178 |
8,464 | luci/luci-go | gce/appengine/backend/internal/metrics/metrics.go | updateInstances | func updateInstances(c context.Context) {
now := clock.Now(c)
q := datastore.NewQuery("InstanceCount").Order("computed")
if err := datastore.Run(c, q, func(ic *InstanceCount) {
if now.Sub(ic.Computed) > 10*time.Minute {
logging.Debugf(c, "deleting outdated count %q", ic.Prefix)
if err := datastore.Delete(c, ic); err != nil {
logging.Errorf(c, "%s", err)
}
return
}
for _, conf := range ic.Configured {
configuredInstances.Set(c, int64(conf.Count), ic.Prefix, conf.Project)
}
for _, crea := range ic.Created {
createdInstances.Set(c, int64(crea.Count), ic.Prefix, crea.Project, crea.Zone)
}
for _, conn := range ic.Connected {
connectedInstances.Set(c, int64(conn.Count), ic.Prefix, conn.Project, conn.Server, conn.Zone)
}
}); err != nil {
errors.Log(c, errors.Annotate(err, "failed to fetch counts").Err())
}
} | go | func updateInstances(c context.Context) {
now := clock.Now(c)
q := datastore.NewQuery("InstanceCount").Order("computed")
if err := datastore.Run(c, q, func(ic *InstanceCount) {
if now.Sub(ic.Computed) > 10*time.Minute {
logging.Debugf(c, "deleting outdated count %q", ic.Prefix)
if err := datastore.Delete(c, ic); err != nil {
logging.Errorf(c, "%s", err)
}
return
}
for _, conf := range ic.Configured {
configuredInstances.Set(c, int64(conf.Count), ic.Prefix, conf.Project)
}
for _, crea := range ic.Created {
createdInstances.Set(c, int64(crea.Count), ic.Prefix, crea.Project, crea.Zone)
}
for _, conn := range ic.Connected {
connectedInstances.Set(c, int64(conn.Count), ic.Prefix, conn.Project, conn.Server, conn.Zone)
}
}); err != nil {
errors.Log(c, errors.Annotate(err, "failed to fetch counts").Err())
}
} | [
"func",
"updateInstances",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"now",
":=",
"clock",
".",
"Now",
"(",
"c",
")",
"\n",
"q",
":=",
"datastore",
".",
"NewQuery",
"(",
"\"",
"\"",
")",
".",
"Order",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"datastore",
".",
"Run",
"(",
"c",
",",
"q",
",",
"func",
"(",
"ic",
"*",
"InstanceCount",
")",
"{",
"if",
"now",
".",
"Sub",
"(",
"ic",
".",
"Computed",
")",
">",
"10",
"*",
"time",
".",
"Minute",
"{",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"ic",
".",
"Prefix",
")",
"\n",
"if",
"err",
":=",
"datastore",
".",
"Delete",
"(",
"c",
",",
"ic",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"conf",
":=",
"range",
"ic",
".",
"Configured",
"{",
"configuredInstances",
".",
"Set",
"(",
"c",
",",
"int64",
"(",
"conf",
".",
"Count",
")",
",",
"ic",
".",
"Prefix",
",",
"conf",
".",
"Project",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"crea",
":=",
"range",
"ic",
".",
"Created",
"{",
"createdInstances",
".",
"Set",
"(",
"c",
",",
"int64",
"(",
"crea",
".",
"Count",
")",
",",
"ic",
".",
"Prefix",
",",
"crea",
".",
"Project",
",",
"crea",
".",
"Zone",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"conn",
":=",
"range",
"ic",
".",
"Connected",
"{",
"connectedInstances",
".",
"Set",
"(",
"c",
",",
"int64",
"(",
"conn",
".",
"Count",
")",
",",
"ic",
".",
"Prefix",
",",
"conn",
".",
"Project",
",",
"conn",
".",
"Server",
",",
"conn",
".",
"Zone",
")",
"\n",
"}",
"\n",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Log",
"(",
"c",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] | // updateInstances sets GCE instance metrics. | [
"updateInstances",
"sets",
"GCE",
"instance",
"metrics",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/internal/metrics/metrics.go#L181-L204 |
8,465 | luci/luci-go | gce/appengine/backend/internal/metrics/metrics.go | UpdateQuota | func UpdateQuota(c context.Context, limit, usage float64, metric, project, region string) {
quotaLimit.Set(c, limit, metric, project, region)
quotaRemaining.Set(c, limit-usage, metric, project, region)
quotaUsage.Set(c, usage, metric, project, region)
} | go | func UpdateQuota(c context.Context, limit, usage float64, metric, project, region string) {
quotaLimit.Set(c, limit, metric, project, region)
quotaRemaining.Set(c, limit-usage, metric, project, region)
quotaUsage.Set(c, usage, metric, project, region)
} | [
"func",
"UpdateQuota",
"(",
"c",
"context",
".",
"Context",
",",
"limit",
",",
"usage",
"float64",
",",
"metric",
",",
"project",
",",
"region",
"string",
")",
"{",
"quotaLimit",
".",
"Set",
"(",
"c",
",",
"limit",
",",
"metric",
",",
"project",
",",
"region",
")",
"\n",
"quotaRemaining",
".",
"Set",
"(",
"c",
",",
"limit",
"-",
"usage",
",",
"metric",
",",
"project",
",",
"region",
")",
"\n",
"quotaUsage",
".",
"Set",
"(",
"c",
",",
"usage",
",",
"metric",
",",
"project",
",",
"region",
")",
"\n",
"}"
] | // UpdateQuota sets GCE quota metrics. | [
"UpdateQuota",
"sets",
"GCE",
"quota",
"metrics",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/internal/metrics/metrics.go#L240-L244 |
8,466 | luci/luci-go | luci_notify/notify/commits.go | commitIndex | func commitIndex(commits []*gitpb.Commit, revision string) int {
for i, commit := range commits {
if commit.Id == revision {
return i
}
}
return -1
} | go | func commitIndex(commits []*gitpb.Commit, revision string) int {
for i, commit := range commits {
if commit.Id == revision {
return i
}
}
return -1
} | [
"func",
"commitIndex",
"(",
"commits",
"[",
"]",
"*",
"gitpb",
".",
"Commit",
",",
"revision",
"string",
")",
"int",
"{",
"for",
"i",
",",
"commit",
":=",
"range",
"commits",
"{",
"if",
"commit",
".",
"Id",
"==",
"revision",
"{",
"return",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] | // commitIndex finds the index of the given revision inside the list of
// Git commits, or -1 if the revision is not found. | [
"commitIndex",
"finds",
"the",
"index",
"of",
"the",
"given",
"revision",
"inside",
"the",
"list",
"of",
"Git",
"commits",
"or",
"-",
"1",
"if",
"the",
"revision",
"is",
"not",
"found",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/commits.go#L35-L42 |
8,467 | luci/luci-go | luci_notify/notify/commits.go | NewCheckout | func NewCheckout(commits notifypb.GitilesCommits) Checkout {
results := make(Checkout, len(commits.GetCommits()))
for _, gitilesCommit := range commits.GetCommits() {
results[protoutil.GitilesRepoURL(gitilesCommit)] = gitilesCommit.Id
}
return results
} | go | func NewCheckout(commits notifypb.GitilesCommits) Checkout {
results := make(Checkout, len(commits.GetCommits()))
for _, gitilesCommit := range commits.GetCommits() {
results[protoutil.GitilesRepoURL(gitilesCommit)] = gitilesCommit.Id
}
return results
} | [
"func",
"NewCheckout",
"(",
"commits",
"notifypb",
".",
"GitilesCommits",
")",
"Checkout",
"{",
"results",
":=",
"make",
"(",
"Checkout",
",",
"len",
"(",
"commits",
".",
"GetCommits",
"(",
")",
")",
")",
"\n",
"for",
"_",
",",
"gitilesCommit",
":=",
"range",
"commits",
".",
"GetCommits",
"(",
")",
"{",
"results",
"[",
"protoutil",
".",
"GitilesRepoURL",
"(",
"gitilesCommit",
")",
"]",
"=",
"gitilesCommit",
".",
"Id",
"\n",
"}",
"\n",
"return",
"results",
"\n",
"}"
] | // NewCheckout creates a new Checkout populated with the repositories and revision
// found in the GitilesCommits object. | [
"NewCheckout",
"creates",
"a",
"new",
"Checkout",
"populated",
"with",
"the",
"repositories",
"and",
"revision",
"found",
"in",
"the",
"GitilesCommits",
"object",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/commits.go#L68-L74 |
8,468 | luci/luci-go | luci_notify/notify/commits.go | ToGitilesCommits | func (c Checkout) ToGitilesCommits() notifypb.GitilesCommits {
result := notifypb.GitilesCommits{
Commits: make([]*buildbucketpb.GitilesCommit, 0, len(c)),
}
for repo, commit := range c {
host, project, _ := gitiles.ParseRepoURL(repo)
result.Commits = append(result.Commits, &buildbucketpb.GitilesCommit{
Host: host,
Project: project,
Id: commit,
})
}
// Sort commits, first by host, then by project.
sort.Slice(result.Commits, func(i, j int) bool {
first := result.Commits[i]
second := result.Commits[j]
hostResult := strings.Compare(first.Host, second.Host)
if hostResult == 0 {
return strings.Compare(first.Project, second.Project) < 0
}
return hostResult < 0
})
return result
} | go | func (c Checkout) ToGitilesCommits() notifypb.GitilesCommits {
result := notifypb.GitilesCommits{
Commits: make([]*buildbucketpb.GitilesCommit, 0, len(c)),
}
for repo, commit := range c {
host, project, _ := gitiles.ParseRepoURL(repo)
result.Commits = append(result.Commits, &buildbucketpb.GitilesCommit{
Host: host,
Project: project,
Id: commit,
})
}
// Sort commits, first by host, then by project.
sort.Slice(result.Commits, func(i, j int) bool {
first := result.Commits[i]
second := result.Commits[j]
hostResult := strings.Compare(first.Host, second.Host)
if hostResult == 0 {
return strings.Compare(first.Project, second.Project) < 0
}
return hostResult < 0
})
return result
} | [
"func",
"(",
"c",
"Checkout",
")",
"ToGitilesCommits",
"(",
")",
"notifypb",
".",
"GitilesCommits",
"{",
"result",
":=",
"notifypb",
".",
"GitilesCommits",
"{",
"Commits",
":",
"make",
"(",
"[",
"]",
"*",
"buildbucketpb",
".",
"GitilesCommit",
",",
"0",
",",
"len",
"(",
"c",
")",
")",
",",
"}",
"\n",
"for",
"repo",
",",
"commit",
":=",
"range",
"c",
"{",
"host",
",",
"project",
",",
"_",
":=",
"gitiles",
".",
"ParseRepoURL",
"(",
"repo",
")",
"\n",
"result",
".",
"Commits",
"=",
"append",
"(",
"result",
".",
"Commits",
",",
"&",
"buildbucketpb",
".",
"GitilesCommit",
"{",
"Host",
":",
"host",
",",
"Project",
":",
"project",
",",
"Id",
":",
"commit",
",",
"}",
")",
"\n",
"}",
"\n",
"// Sort commits, first by host, then by project.",
"sort",
".",
"Slice",
"(",
"result",
".",
"Commits",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"first",
":=",
"result",
".",
"Commits",
"[",
"i",
"]",
"\n",
"second",
":=",
"result",
".",
"Commits",
"[",
"j",
"]",
"\n",
"hostResult",
":=",
"strings",
".",
"Compare",
"(",
"first",
".",
"Host",
",",
"second",
".",
"Host",
")",
"\n",
"if",
"hostResult",
"==",
"0",
"{",
"return",
"strings",
".",
"Compare",
"(",
"first",
".",
"Project",
",",
"second",
".",
"Project",
")",
"<",
"0",
"\n",
"}",
"\n",
"return",
"hostResult",
"<",
"0",
"\n",
"}",
")",
"\n",
"return",
"result",
"\n",
"}"
] | // ToGitilesCommits converts the Checkout into a set of GitilesCommits which may
// be stored as part of a config.Builder. | [
"ToGitilesCommits",
"converts",
"the",
"Checkout",
"into",
"a",
"set",
"of",
"GitilesCommits",
"which",
"may",
"be",
"stored",
"as",
"part",
"of",
"a",
"config",
".",
"Builder",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/commits.go#L78-L101 |
8,469 | luci/luci-go | luci_notify/notify/commits.go | Filter | func (c Checkout) Filter(whiteset stringset.Set) Checkout {
newCheckout := make(Checkout)
for repo, commit := range c {
if whiteset.Has(repo) {
newCheckout[repo] = commit
}
}
return newCheckout
} | go | func (c Checkout) Filter(whiteset stringset.Set) Checkout {
newCheckout := make(Checkout)
for repo, commit := range c {
if whiteset.Has(repo) {
newCheckout[repo] = commit
}
}
return newCheckout
} | [
"func",
"(",
"c",
"Checkout",
")",
"Filter",
"(",
"whiteset",
"stringset",
".",
"Set",
")",
"Checkout",
"{",
"newCheckout",
":=",
"make",
"(",
"Checkout",
")",
"\n",
"for",
"repo",
",",
"commit",
":=",
"range",
"c",
"{",
"if",
"whiteset",
".",
"Has",
"(",
"repo",
")",
"{",
"newCheckout",
"[",
"repo",
"]",
"=",
"commit",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"newCheckout",
"\n",
"}"
] | // Filter filters out repositories from the Checkout which are not in the whitelist
// and returns a new Checkout. | [
"Filter",
"filters",
"out",
"repositories",
"from",
"the",
"Checkout",
"which",
"are",
"not",
"in",
"the",
"whitelist",
"and",
"returns",
"a",
"new",
"Checkout",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/commits.go#L105-L113 |
8,470 | luci/luci-go | luci_notify/notify/commits.go | ComputeLogs | func ComputeLogs(c context.Context, oldCheckout, newCheckout Checkout, history HistoryFunc) (Logs, error) {
var resultMu sync.Mutex
result := make(Logs)
err := parallel.WorkPool(8, func(ch chan<- func() error) {
for repo, revision := range newCheckout {
repo := repo
newRev := revision
oldRev, ok := oldCheckout[repo]
if !ok {
continue
}
host, project, _ := gitiles.ParseRepoURL(repo)
ch <- func() error {
log, err := history(c, host, project, oldRev, newRev)
if err != nil {
return err
}
if len(log) <= 1 {
return nil
}
resultMu.Lock()
result[repo] = log[:len(log)-1]
resultMu.Unlock()
return nil
}
}
})
return result, err
} | go | func ComputeLogs(c context.Context, oldCheckout, newCheckout Checkout, history HistoryFunc) (Logs, error) {
var resultMu sync.Mutex
result := make(Logs)
err := parallel.WorkPool(8, func(ch chan<- func() error) {
for repo, revision := range newCheckout {
repo := repo
newRev := revision
oldRev, ok := oldCheckout[repo]
if !ok {
continue
}
host, project, _ := gitiles.ParseRepoURL(repo)
ch <- func() error {
log, err := history(c, host, project, oldRev, newRev)
if err != nil {
return err
}
if len(log) <= 1 {
return nil
}
resultMu.Lock()
result[repo] = log[:len(log)-1]
resultMu.Unlock()
return nil
}
}
})
return result, err
} | [
"func",
"ComputeLogs",
"(",
"c",
"context",
".",
"Context",
",",
"oldCheckout",
",",
"newCheckout",
"Checkout",
",",
"history",
"HistoryFunc",
")",
"(",
"Logs",
",",
"error",
")",
"{",
"var",
"resultMu",
"sync",
".",
"Mutex",
"\n",
"result",
":=",
"make",
"(",
"Logs",
")",
"\n",
"err",
":=",
"parallel",
".",
"WorkPool",
"(",
"8",
",",
"func",
"(",
"ch",
"chan",
"<-",
"func",
"(",
")",
"error",
")",
"{",
"for",
"repo",
",",
"revision",
":=",
"range",
"newCheckout",
"{",
"repo",
":=",
"repo",
"\n",
"newRev",
":=",
"revision",
"\n",
"oldRev",
",",
"ok",
":=",
"oldCheckout",
"[",
"repo",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"host",
",",
"project",
",",
"_",
":=",
"gitiles",
".",
"ParseRepoURL",
"(",
"repo",
")",
"\n",
"ch",
"<-",
"func",
"(",
")",
"error",
"{",
"log",
",",
"err",
":=",
"history",
"(",
"c",
",",
"host",
",",
"project",
",",
"oldRev",
",",
"newRev",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"log",
")",
"<=",
"1",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"resultMu",
".",
"Lock",
"(",
")",
"\n",
"result",
"[",
"repo",
"]",
"=",
"log",
"[",
":",
"len",
"(",
"log",
")",
"-",
"1",
"]",
"\n",
"resultMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"result",
",",
"err",
"\n",
"}"
] | // ComputeLogs produces a set of Git diffs between oldCheckout and newCheckout, using the
// repositories in the newCheckout. historyFunc is used to grab the Git history. | [
"ComputeLogs",
"produces",
"a",
"set",
"of",
"Git",
"diffs",
"between",
"oldCheckout",
"and",
"newCheckout",
"using",
"the",
"repositories",
"in",
"the",
"newCheckout",
".",
"historyFunc",
"is",
"used",
"to",
"grab",
"the",
"Git",
"history",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/commits.go#L123-L151 |
8,471 | luci/luci-go | luci_notify/notify/commits.go | Filter | func (l Logs) Filter(whiteset stringset.Set) Logs {
newLogs := make(Logs)
for repo, commits := range l {
if whiteset.Has(repo) {
newLogs[repo] = commits
}
}
return newLogs
} | go | func (l Logs) Filter(whiteset stringset.Set) Logs {
newLogs := make(Logs)
for repo, commits := range l {
if whiteset.Has(repo) {
newLogs[repo] = commits
}
}
return newLogs
} | [
"func",
"(",
"l",
"Logs",
")",
"Filter",
"(",
"whiteset",
"stringset",
".",
"Set",
")",
"Logs",
"{",
"newLogs",
":=",
"make",
"(",
"Logs",
")",
"\n",
"for",
"repo",
",",
"commits",
":=",
"range",
"l",
"{",
"if",
"whiteset",
".",
"Has",
"(",
"repo",
")",
"{",
"newLogs",
"[",
"repo",
"]",
"=",
"commits",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"newLogs",
"\n",
"}"
] | // Filter filters out repositories from the Logs which are not in the whitelist
// and returns a new Logs. | [
"Filter",
"filters",
"out",
"repositories",
"from",
"the",
"Logs",
"which",
"are",
"not",
"in",
"the",
"whitelist",
"and",
"returns",
"a",
"new",
"Logs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/commits.go#L155-L163 |
8,472 | luci/luci-go | luci_notify/notify/commits.go | Blamelist | func (l Logs) Blamelist(template string) []EmailNotify {
blamelist := stringset.New(0)
for _, log := range l {
for _, commit := range log {
blamelist.Add(commit.Author.Email)
}
}
recipients := make([]EmailNotify, 0, len(blamelist))
for recipient := range blamelist {
recipients = append(recipients, EmailNotify{
Email: recipient,
Template: template,
})
}
sortEmailNotify(recipients)
return recipients
} | go | func (l Logs) Blamelist(template string) []EmailNotify {
blamelist := stringset.New(0)
for _, log := range l {
for _, commit := range log {
blamelist.Add(commit.Author.Email)
}
}
recipients := make([]EmailNotify, 0, len(blamelist))
for recipient := range blamelist {
recipients = append(recipients, EmailNotify{
Email: recipient,
Template: template,
})
}
sortEmailNotify(recipients)
return recipients
} | [
"func",
"(",
"l",
"Logs",
")",
"Blamelist",
"(",
"template",
"string",
")",
"[",
"]",
"EmailNotify",
"{",
"blamelist",
":=",
"stringset",
".",
"New",
"(",
"0",
")",
"\n",
"for",
"_",
",",
"log",
":=",
"range",
"l",
"{",
"for",
"_",
",",
"commit",
":=",
"range",
"log",
"{",
"blamelist",
".",
"Add",
"(",
"commit",
".",
"Author",
".",
"Email",
")",
"\n",
"}",
"\n",
"}",
"\n",
"recipients",
":=",
"make",
"(",
"[",
"]",
"EmailNotify",
",",
"0",
",",
"len",
"(",
"blamelist",
")",
")",
"\n",
"for",
"recipient",
":=",
"range",
"blamelist",
"{",
"recipients",
"=",
"append",
"(",
"recipients",
",",
"EmailNotify",
"{",
"Email",
":",
"recipient",
",",
"Template",
":",
"template",
",",
"}",
")",
"\n",
"}",
"\n",
"sortEmailNotify",
"(",
"recipients",
")",
"\n",
"return",
"recipients",
"\n",
"}"
] | // Blamelist computes a set of email notifications from the Logs. | [
"Blamelist",
"computes",
"a",
"set",
"of",
"email",
"notifications",
"from",
"the",
"Logs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/commits.go#L166-L182 |
8,473 | luci/luci-go | logdog/common/storage/archive/storage.go | New | func New(o Options) (storage.Storage, error) {
s := storageImpl{
Options: &o,
}
if !s.Stream.IsFullPath() {
return nil, fmt.Errorf("invalid stream URL: %q", s.Stream)
}
if s.Index != "" && !s.Index.IsFullPath() {
return nil, fmt.Errorf("invalid index URL: %v", s.Index)
}
return &s, nil
} | go | func New(o Options) (storage.Storage, error) {
s := storageImpl{
Options: &o,
}
if !s.Stream.IsFullPath() {
return nil, fmt.Errorf("invalid stream URL: %q", s.Stream)
}
if s.Index != "" && !s.Index.IsFullPath() {
return nil, fmt.Errorf("invalid index URL: %v", s.Index)
}
return &s, nil
} | [
"func",
"New",
"(",
"o",
"Options",
")",
"(",
"storage",
".",
"Storage",
",",
"error",
")",
"{",
"s",
":=",
"storageImpl",
"{",
"Options",
":",
"&",
"o",
",",
"}",
"\n\n",
"if",
"!",
"s",
".",
"Stream",
".",
"IsFullPath",
"(",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"Stream",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"Index",
"!=",
"\"",
"\"",
"&&",
"!",
"s",
".",
"Index",
".",
"IsFullPath",
"(",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"Index",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"s",
",",
"nil",
"\n",
"}"
] | // New instantiates a new Storage instance, bound to the supplied Options. | [
"New",
"instantiates",
"a",
"new",
"Storage",
"instance",
"bound",
"to",
"the",
"supplied",
"Options",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/archive/storage.go#L83-L96 |
8,474 | luci/luci-go | logdog/common/storage/archive/storage.go | getIndex | func (s *storageImpl) getIndex(c context.Context) (*logpb.LogIndex, error) {
idx := s.index.Load()
if idx != nil {
return idx.(*logpb.LogIndex), nil
}
index, err := loadIndex(c, s.Client, s.Index, s.Cache)
switch errors.Unwrap(err) {
case nil:
break
case cloudStorage.ErrBucketNotExist, cloudStorage.ErrObjectNotExist:
// Treat a missing index the same as an empty index.
log.WithError(err).Warningf(c, "Index is invalid, using empty index.")
index = &logpb.LogIndex{}
default:
return nil, err
}
s.index.Store(index)
return index, nil
} | go | func (s *storageImpl) getIndex(c context.Context) (*logpb.LogIndex, error) {
idx := s.index.Load()
if idx != nil {
return idx.(*logpb.LogIndex), nil
}
index, err := loadIndex(c, s.Client, s.Index, s.Cache)
switch errors.Unwrap(err) {
case nil:
break
case cloudStorage.ErrBucketNotExist, cloudStorage.ErrObjectNotExist:
// Treat a missing index the same as an empty index.
log.WithError(err).Warningf(c, "Index is invalid, using empty index.")
index = &logpb.LogIndex{}
default:
return nil, err
}
s.index.Store(index)
return index, nil
} | [
"func",
"(",
"s",
"*",
"storageImpl",
")",
"getIndex",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"*",
"logpb",
".",
"LogIndex",
",",
"error",
")",
"{",
"idx",
":=",
"s",
".",
"index",
".",
"Load",
"(",
")",
"\n",
"if",
"idx",
"!=",
"nil",
"{",
"return",
"idx",
".",
"(",
"*",
"logpb",
".",
"LogIndex",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"index",
",",
"err",
":=",
"loadIndex",
"(",
"c",
",",
"s",
".",
"Client",
",",
"s",
".",
"Index",
",",
"s",
".",
"Cache",
")",
"\n",
"switch",
"errors",
".",
"Unwrap",
"(",
"err",
")",
"{",
"case",
"nil",
":",
"break",
"\n\n",
"case",
"cloudStorage",
".",
"ErrBucketNotExist",
",",
"cloudStorage",
".",
"ErrObjectNotExist",
":",
"// Treat a missing index the same as an empty index.",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"index",
"=",
"&",
"logpb",
".",
"LogIndex",
"{",
"}",
"\n\n",
"default",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"index",
".",
"Store",
"(",
"index",
")",
"\n",
"return",
"index",
",",
"nil",
"\n",
"}"
] | // getIndex returns the cached log stream index, fetching it if necessary. | [
"getIndex",
"returns",
"the",
"cached",
"log",
"stream",
"index",
"fetching",
"it",
"if",
"necessary",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/archive/storage.go#L289-L311 |
8,475 | luci/luci-go | logdog/common/storage/archive/storage.go | setCount | func (gs *getStrategy) setCount(v uint64) {
if gs.count == 0 || gs.count > v {
gs.count = v
}
} | go | func (gs *getStrategy) setCount(v uint64) {
if gs.count == 0 || gs.count > v {
gs.count = v
}
} | [
"func",
"(",
"gs",
"*",
"getStrategy",
")",
"setCount",
"(",
"v",
"uint64",
")",
"{",
"if",
"gs",
".",
"count",
"==",
"0",
"||",
"gs",
".",
"count",
">",
"v",
"{",
"gs",
".",
"count",
"=",
"v",
"\n",
"}",
"\n",
"}"
] | // setCount sets the `count` field. If called multiple times, the smallest
// assigned value will be retained. | [
"setCount",
"sets",
"the",
"count",
"field",
".",
"If",
"called",
"multiple",
"times",
"the",
"smallest",
"assigned",
"value",
"will",
"be",
"retained",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/archive/storage.go#L391-L395 |
8,476 | luci/luci-go | common/tsmon/monitor/serialize.go | SerializeCells | func SerializeCells(cells []types.Cell, now time.Time) []*pb.MetricsCollection {
collections := map[uint64]*pb.MetricsCollection{}
dataSets := map[dataSetKey]*pb.MetricsDataSet{}
for _, c := range cells {
// Find the collection, add it if it doesn't exist.
targetHash := c.Target.Hash()
collection, ok := collections[targetHash]
if !ok {
collection = &pb.MetricsCollection{}
collections[targetHash] = collection
c.Target.PopulateProto(collection)
}
// Find the data set, add it if it doesn't exist.
key := dataSetKey{targetHash, c.Name}
dataSet, ok := dataSets[key]
if !ok {
dataSet = SerializeDataSet(c)
dataSets[key] = dataSet
collection.MetricsDataSet = append(collection.MetricsDataSet, dataSet)
}
// Add the data to the data set.
dataSet.Data = append(dataSet.Data, SerializeValue(c, now))
}
// Turn the hash into a list and return it.
ret := make([]*pb.MetricsCollection, 0, len(collections))
for _, collection := range collections {
ret = append(ret, collection)
}
return ret
} | go | func SerializeCells(cells []types.Cell, now time.Time) []*pb.MetricsCollection {
collections := map[uint64]*pb.MetricsCollection{}
dataSets := map[dataSetKey]*pb.MetricsDataSet{}
for _, c := range cells {
// Find the collection, add it if it doesn't exist.
targetHash := c.Target.Hash()
collection, ok := collections[targetHash]
if !ok {
collection = &pb.MetricsCollection{}
collections[targetHash] = collection
c.Target.PopulateProto(collection)
}
// Find the data set, add it if it doesn't exist.
key := dataSetKey{targetHash, c.Name}
dataSet, ok := dataSets[key]
if !ok {
dataSet = SerializeDataSet(c)
dataSets[key] = dataSet
collection.MetricsDataSet = append(collection.MetricsDataSet, dataSet)
}
// Add the data to the data set.
dataSet.Data = append(dataSet.Data, SerializeValue(c, now))
}
// Turn the hash into a list and return it.
ret := make([]*pb.MetricsCollection, 0, len(collections))
for _, collection := range collections {
ret = append(ret, collection)
}
return ret
} | [
"func",
"SerializeCells",
"(",
"cells",
"[",
"]",
"types",
".",
"Cell",
",",
"now",
"time",
".",
"Time",
")",
"[",
"]",
"*",
"pb",
".",
"MetricsCollection",
"{",
"collections",
":=",
"map",
"[",
"uint64",
"]",
"*",
"pb",
".",
"MetricsCollection",
"{",
"}",
"\n",
"dataSets",
":=",
"map",
"[",
"dataSetKey",
"]",
"*",
"pb",
".",
"MetricsDataSet",
"{",
"}",
"\n\n",
"for",
"_",
",",
"c",
":=",
"range",
"cells",
"{",
"// Find the collection, add it if it doesn't exist.",
"targetHash",
":=",
"c",
".",
"Target",
".",
"Hash",
"(",
")",
"\n",
"collection",
",",
"ok",
":=",
"collections",
"[",
"targetHash",
"]",
"\n",
"if",
"!",
"ok",
"{",
"collection",
"=",
"&",
"pb",
".",
"MetricsCollection",
"{",
"}",
"\n",
"collections",
"[",
"targetHash",
"]",
"=",
"collection",
"\n",
"c",
".",
"Target",
".",
"PopulateProto",
"(",
"collection",
")",
"\n",
"}",
"\n\n",
"// Find the data set, add it if it doesn't exist.",
"key",
":=",
"dataSetKey",
"{",
"targetHash",
",",
"c",
".",
"Name",
"}",
"\n",
"dataSet",
",",
"ok",
":=",
"dataSets",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"dataSet",
"=",
"SerializeDataSet",
"(",
"c",
")",
"\n",
"dataSets",
"[",
"key",
"]",
"=",
"dataSet",
"\n",
"collection",
".",
"MetricsDataSet",
"=",
"append",
"(",
"collection",
".",
"MetricsDataSet",
",",
"dataSet",
")",
"\n",
"}",
"\n\n",
"// Add the data to the data set.",
"dataSet",
".",
"Data",
"=",
"append",
"(",
"dataSet",
".",
"Data",
",",
"SerializeValue",
"(",
"c",
",",
"now",
")",
")",
"\n",
"}",
"\n\n",
"// Turn the hash into a list and return it.",
"ret",
":=",
"make",
"(",
"[",
"]",
"*",
"pb",
".",
"MetricsCollection",
",",
"0",
",",
"len",
"(",
"collections",
")",
")",
"\n",
"for",
"_",
",",
"collection",
":=",
"range",
"collections",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"collection",
")",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // SerializeCells creates a MetricsCollection message from a slice of cells. | [
"SerializeCells",
"creates",
"a",
"MetricsCollection",
"message",
"from",
"a",
"slice",
"of",
"cells",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/monitor/serialize.go#L34-L67 |
8,477 | luci/luci-go | common/tsmon/monitor/serialize.go | SerializeDataSet | func SerializeDataSet(c types.Cell) *pb.MetricsDataSet {
d := pb.MetricsDataSet{}
d.MetricName = proto.String(metricNamePrefix + c.Name)
d.FieldDescriptor = field.SerializeDescriptor(c.Fields)
d.Description = proto.String(c.Description)
if c.ValueType.IsCumulative() {
d.StreamKind = pb.StreamKind_CUMULATIVE.Enum()
} else {
d.StreamKind = pb.StreamKind_GAUGE.Enum()
}
switch c.ValueType {
case types.NonCumulativeIntType, types.CumulativeIntType:
d.ValueType = pb.ValueType_INT64.Enum()
case types.NonCumulativeFloatType, types.CumulativeFloatType:
d.ValueType = pb.ValueType_DOUBLE.Enum()
case types.NonCumulativeDistributionType, types.CumulativeDistributionType:
d.ValueType = pb.ValueType_DISTRIBUTION.Enum()
case types.StringType:
d.ValueType = pb.ValueType_STRING.Enum()
case types.BoolType:
d.ValueType = pb.ValueType_BOOL.Enum()
}
if c.Units.IsSpecified() {
d.Annotations.Unit = proto.String(string(c.Units))
}
return &d
} | go | func SerializeDataSet(c types.Cell) *pb.MetricsDataSet {
d := pb.MetricsDataSet{}
d.MetricName = proto.String(metricNamePrefix + c.Name)
d.FieldDescriptor = field.SerializeDescriptor(c.Fields)
d.Description = proto.String(c.Description)
if c.ValueType.IsCumulative() {
d.StreamKind = pb.StreamKind_CUMULATIVE.Enum()
} else {
d.StreamKind = pb.StreamKind_GAUGE.Enum()
}
switch c.ValueType {
case types.NonCumulativeIntType, types.CumulativeIntType:
d.ValueType = pb.ValueType_INT64.Enum()
case types.NonCumulativeFloatType, types.CumulativeFloatType:
d.ValueType = pb.ValueType_DOUBLE.Enum()
case types.NonCumulativeDistributionType, types.CumulativeDistributionType:
d.ValueType = pb.ValueType_DISTRIBUTION.Enum()
case types.StringType:
d.ValueType = pb.ValueType_STRING.Enum()
case types.BoolType:
d.ValueType = pb.ValueType_BOOL.Enum()
}
if c.Units.IsSpecified() {
d.Annotations.Unit = proto.String(string(c.Units))
}
return &d
} | [
"func",
"SerializeDataSet",
"(",
"c",
"types",
".",
"Cell",
")",
"*",
"pb",
".",
"MetricsDataSet",
"{",
"d",
":=",
"pb",
".",
"MetricsDataSet",
"{",
"}",
"\n",
"d",
".",
"MetricName",
"=",
"proto",
".",
"String",
"(",
"metricNamePrefix",
"+",
"c",
".",
"Name",
")",
"\n",
"d",
".",
"FieldDescriptor",
"=",
"field",
".",
"SerializeDescriptor",
"(",
"c",
".",
"Fields",
")",
"\n",
"d",
".",
"Description",
"=",
"proto",
".",
"String",
"(",
"c",
".",
"Description",
")",
"\n\n",
"if",
"c",
".",
"ValueType",
".",
"IsCumulative",
"(",
")",
"{",
"d",
".",
"StreamKind",
"=",
"pb",
".",
"StreamKind_CUMULATIVE",
".",
"Enum",
"(",
")",
"\n",
"}",
"else",
"{",
"d",
".",
"StreamKind",
"=",
"pb",
".",
"StreamKind_GAUGE",
".",
"Enum",
"(",
")",
"\n",
"}",
"\n\n",
"switch",
"c",
".",
"ValueType",
"{",
"case",
"types",
".",
"NonCumulativeIntType",
",",
"types",
".",
"CumulativeIntType",
":",
"d",
".",
"ValueType",
"=",
"pb",
".",
"ValueType_INT64",
".",
"Enum",
"(",
")",
"\n",
"case",
"types",
".",
"NonCumulativeFloatType",
",",
"types",
".",
"CumulativeFloatType",
":",
"d",
".",
"ValueType",
"=",
"pb",
".",
"ValueType_DOUBLE",
".",
"Enum",
"(",
")",
"\n",
"case",
"types",
".",
"NonCumulativeDistributionType",
",",
"types",
".",
"CumulativeDistributionType",
":",
"d",
".",
"ValueType",
"=",
"pb",
".",
"ValueType_DISTRIBUTION",
".",
"Enum",
"(",
")",
"\n",
"case",
"types",
".",
"StringType",
":",
"d",
".",
"ValueType",
"=",
"pb",
".",
"ValueType_STRING",
".",
"Enum",
"(",
")",
"\n",
"case",
"types",
".",
"BoolType",
":",
"d",
".",
"ValueType",
"=",
"pb",
".",
"ValueType_BOOL",
".",
"Enum",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"Units",
".",
"IsSpecified",
"(",
")",
"{",
"d",
".",
"Annotations",
".",
"Unit",
"=",
"proto",
".",
"String",
"(",
"string",
"(",
"c",
".",
"Units",
")",
")",
"\n",
"}",
"\n",
"return",
"&",
"d",
"\n",
"}"
] | // SerializeDataSet creates a new MetricsDataSet without any data, but just with
// the metric metadata fields populated. | [
"SerializeDataSet",
"creates",
"a",
"new",
"MetricsDataSet",
"without",
"any",
"data",
"but",
"just",
"with",
"the",
"metric",
"metadata",
"fields",
"populated",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/monitor/serialize.go#L71-L100 |
8,478 | luci/luci-go | common/tsmon/monitor/serialize.go | SerializeValue | func SerializeValue(c types.Cell, now time.Time) *pb.MetricsData {
d := pb.MetricsData{}
d.Field = field.Serialize(c.Fields, c.FieldVals)
if c.ValueType.IsCumulative() {
d.StartTimestamp = toTimestamp(c.ResetTime)
} else {
d.StartTimestamp = toTimestamp(now)
}
d.EndTimestamp = toTimestamp(now)
switch c.ValueType {
case types.NonCumulativeIntType, types.CumulativeIntType:
d.Value = &pb.MetricsData_Int64Value{c.Value.(int64)}
case types.NonCumulativeFloatType, types.CumulativeFloatType:
d.Value = &pb.MetricsData_DoubleValue{c.Value.(float64)}
case types.CumulativeDistributionType, types.NonCumulativeDistributionType:
d.Value = &pb.MetricsData_DistributionValue{serializeDistribution(c.Value.(*distribution.Distribution))}
case types.StringType:
d.Value = &pb.MetricsData_StringValue{c.Value.(string)}
case types.BoolType:
d.Value = &pb.MetricsData_BoolValue{c.Value.(bool)}
}
return &d
} | go | func SerializeValue(c types.Cell, now time.Time) *pb.MetricsData {
d := pb.MetricsData{}
d.Field = field.Serialize(c.Fields, c.FieldVals)
if c.ValueType.IsCumulative() {
d.StartTimestamp = toTimestamp(c.ResetTime)
} else {
d.StartTimestamp = toTimestamp(now)
}
d.EndTimestamp = toTimestamp(now)
switch c.ValueType {
case types.NonCumulativeIntType, types.CumulativeIntType:
d.Value = &pb.MetricsData_Int64Value{c.Value.(int64)}
case types.NonCumulativeFloatType, types.CumulativeFloatType:
d.Value = &pb.MetricsData_DoubleValue{c.Value.(float64)}
case types.CumulativeDistributionType, types.NonCumulativeDistributionType:
d.Value = &pb.MetricsData_DistributionValue{serializeDistribution(c.Value.(*distribution.Distribution))}
case types.StringType:
d.Value = &pb.MetricsData_StringValue{c.Value.(string)}
case types.BoolType:
d.Value = &pb.MetricsData_BoolValue{c.Value.(bool)}
}
return &d
} | [
"func",
"SerializeValue",
"(",
"c",
"types",
".",
"Cell",
",",
"now",
"time",
".",
"Time",
")",
"*",
"pb",
".",
"MetricsData",
"{",
"d",
":=",
"pb",
".",
"MetricsData",
"{",
"}",
"\n",
"d",
".",
"Field",
"=",
"field",
".",
"Serialize",
"(",
"c",
".",
"Fields",
",",
"c",
".",
"FieldVals",
")",
"\n\n",
"if",
"c",
".",
"ValueType",
".",
"IsCumulative",
"(",
")",
"{",
"d",
".",
"StartTimestamp",
"=",
"toTimestamp",
"(",
"c",
".",
"ResetTime",
")",
"\n",
"}",
"else",
"{",
"d",
".",
"StartTimestamp",
"=",
"toTimestamp",
"(",
"now",
")",
"\n",
"}",
"\n",
"d",
".",
"EndTimestamp",
"=",
"toTimestamp",
"(",
"now",
")",
"\n\n",
"switch",
"c",
".",
"ValueType",
"{",
"case",
"types",
".",
"NonCumulativeIntType",
",",
"types",
".",
"CumulativeIntType",
":",
"d",
".",
"Value",
"=",
"&",
"pb",
".",
"MetricsData_Int64Value",
"{",
"c",
".",
"Value",
".",
"(",
"int64",
")",
"}",
"\n",
"case",
"types",
".",
"NonCumulativeFloatType",
",",
"types",
".",
"CumulativeFloatType",
":",
"d",
".",
"Value",
"=",
"&",
"pb",
".",
"MetricsData_DoubleValue",
"{",
"c",
".",
"Value",
".",
"(",
"float64",
")",
"}",
"\n",
"case",
"types",
".",
"CumulativeDistributionType",
",",
"types",
".",
"NonCumulativeDistributionType",
":",
"d",
".",
"Value",
"=",
"&",
"pb",
".",
"MetricsData_DistributionValue",
"{",
"serializeDistribution",
"(",
"c",
".",
"Value",
".",
"(",
"*",
"distribution",
".",
"Distribution",
")",
")",
"}",
"\n",
"case",
"types",
".",
"StringType",
":",
"d",
".",
"Value",
"=",
"&",
"pb",
".",
"MetricsData_StringValue",
"{",
"c",
".",
"Value",
".",
"(",
"string",
")",
"}",
"\n",
"case",
"types",
".",
"BoolType",
":",
"d",
".",
"Value",
"=",
"&",
"pb",
".",
"MetricsData_BoolValue",
"{",
"c",
".",
"Value",
".",
"(",
"bool",
")",
"}",
"\n",
"}",
"\n",
"return",
"&",
"d",
"\n",
"}"
] | // SerializeValue creates a new MetricsData representing this cell's value. | [
"SerializeValue",
"creates",
"a",
"new",
"MetricsData",
"representing",
"this",
"cell",
"s",
"value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/monitor/serialize.go#L110-L134 |
8,479 | luci/luci-go | buildbucket/deprecated/v1.go | builderToV2 | func builderToV2(msg *v1.ApiCommonBuildMessage, tags strpair.Map, params *v1Params) (ret *pb.BuilderID, err error) {
ret = &pb.BuilderID{Builder: params.Builder}
if ret.Builder == "" {
ret.Builder = tags.Get(v1.TagBuilder) // Fallback: Grab builder name from tags.
}
ret.Project, ret.Bucket = BucketNameToV2(msg.Bucket)
if msg.Project != "" && ret.Project != "" && ret.Project != msg.Project {
err = errors.Reason(
"message project %q does not match bucket project %q", msg.Project, ret.Project).Tag(MalformedBuild).Err()
}
return
} | go | func builderToV2(msg *v1.ApiCommonBuildMessage, tags strpair.Map, params *v1Params) (ret *pb.BuilderID, err error) {
ret = &pb.BuilderID{Builder: params.Builder}
if ret.Builder == "" {
ret.Builder = tags.Get(v1.TagBuilder) // Fallback: Grab builder name from tags.
}
ret.Project, ret.Bucket = BucketNameToV2(msg.Bucket)
if msg.Project != "" && ret.Project != "" && ret.Project != msg.Project {
err = errors.Reason(
"message project %q does not match bucket project %q", msg.Project, ret.Project).Tag(MalformedBuild).Err()
}
return
} | [
"func",
"builderToV2",
"(",
"msg",
"*",
"v1",
".",
"ApiCommonBuildMessage",
",",
"tags",
"strpair",
".",
"Map",
",",
"params",
"*",
"v1Params",
")",
"(",
"ret",
"*",
"pb",
".",
"BuilderID",
",",
"err",
"error",
")",
"{",
"ret",
"=",
"&",
"pb",
".",
"BuilderID",
"{",
"Builder",
":",
"params",
".",
"Builder",
"}",
"\n",
"if",
"ret",
".",
"Builder",
"==",
"\"",
"\"",
"{",
"ret",
".",
"Builder",
"=",
"tags",
".",
"Get",
"(",
"v1",
".",
"TagBuilder",
")",
"// Fallback: Grab builder name from tags.",
"\n",
"}",
"\n\n",
"ret",
".",
"Project",
",",
"ret",
".",
"Bucket",
"=",
"BucketNameToV2",
"(",
"msg",
".",
"Bucket",
")",
"\n",
"if",
"msg",
".",
"Project",
"!=",
"\"",
"\"",
"&&",
"ret",
".",
"Project",
"!=",
"\"",
"\"",
"&&",
"ret",
".",
"Project",
"!=",
"msg",
".",
"Project",
"{",
"err",
"=",
"errors",
".",
"Reason",
"(",
"\"",
"\"",
",",
"msg",
".",
"Project",
",",
"ret",
".",
"Project",
")",
".",
"Tag",
"(",
"MalformedBuild",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // builderToV2 attempts to parse as many fields into bucket and project as possible,
// and do project name validation if the project is available. | [
"builderToV2",
"attempts",
"to",
"parse",
"as",
"many",
"fields",
"into",
"bucket",
"and",
"project",
"as",
"possible",
"and",
"do",
"project",
"name",
"validation",
"if",
"the",
"project",
"is",
"available",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/deprecated/v1.go#L265-L277 |
8,480 | luci/luci-go | common/sync/bufferpool/buffer_pool.go | Get | func (p *P) Get() *Buffer {
buf, ok := p.pool.Get().(*bytes.Buffer)
if !ok {
buf = &bytes.Buffer{}
}
return &Buffer{
Buffer: buf,
p: p,
}
} | go | func (p *P) Get() *Buffer {
buf, ok := p.pool.Get().(*bytes.Buffer)
if !ok {
buf = &bytes.Buffer{}
}
return &Buffer{
Buffer: buf,
p: p,
}
} | [
"func",
"(",
"p",
"*",
"P",
")",
"Get",
"(",
")",
"*",
"Buffer",
"{",
"buf",
",",
"ok",
":=",
"p",
".",
"pool",
".",
"Get",
"(",
")",
".",
"(",
"*",
"bytes",
".",
"Buffer",
")",
"\n",
"if",
"!",
"ok",
"{",
"buf",
"=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"Buffer",
"{",
"Buffer",
":",
"buf",
",",
"p",
":",
"p",
",",
"}",
"\n",
"}"
] | // Get returns a Buffer. When the caller is finished with the Buffer, they
// should call Release to return it to its pool. | [
"Get",
"returns",
"a",
"Buffer",
".",
"When",
"the",
"caller",
"is",
"finished",
"with",
"the",
"Buffer",
"they",
"should",
"call",
"Release",
"to",
"return",
"it",
"to",
"its",
"pool",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/bufferpool/buffer_pool.go#L45-L55 |
8,481 | luci/luci-go | server/router/router.go | NewWithRootContext | func NewWithRootContext(root context.Context) *Router {
return &Router{
hrouter: httprouter.New(),
middleware: NewMiddlewareChain(),
rootCtx: root,
BasePath: "/",
}
} | go | func NewWithRootContext(root context.Context) *Router {
return &Router{
hrouter: httprouter.New(),
middleware: NewMiddlewareChain(),
rootCtx: root,
BasePath: "/",
}
} | [
"func",
"NewWithRootContext",
"(",
"root",
"context",
".",
"Context",
")",
"*",
"Router",
"{",
"return",
"&",
"Router",
"{",
"hrouter",
":",
"httprouter",
".",
"New",
"(",
")",
",",
"middleware",
":",
"NewMiddlewareChain",
"(",
")",
",",
"rootCtx",
":",
"root",
",",
"BasePath",
":",
"\"",
"\"",
",",
"}",
"\n",
"}"
] | // NewWithRootContext creates a router whose request contexts all inherit from
// the given context. | [
"NewWithRootContext",
"creates",
"a",
"router",
"whose",
"request",
"contexts",
"all",
"inherit",
"from",
"the",
"given",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/router.go#L55-L62 |
8,482 | luci/luci-go | server/router/router.go | Subrouter | func (r *Router) Subrouter(relativePath string) *Router {
newRouter := &Router{
hrouter: r.hrouter,
middleware: r.middleware,
rootCtx: r.rootCtx,
BasePath: makeBasePath(r.BasePath, relativePath),
}
return newRouter
} | go | func (r *Router) Subrouter(relativePath string) *Router {
newRouter := &Router{
hrouter: r.hrouter,
middleware: r.middleware,
rootCtx: r.rootCtx,
BasePath: makeBasePath(r.BasePath, relativePath),
}
return newRouter
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Subrouter",
"(",
"relativePath",
"string",
")",
"*",
"Router",
"{",
"newRouter",
":=",
"&",
"Router",
"{",
"hrouter",
":",
"r",
".",
"hrouter",
",",
"middleware",
":",
"r",
".",
"middleware",
",",
"rootCtx",
":",
"r",
".",
"rootCtx",
",",
"BasePath",
":",
"makeBasePath",
"(",
"r",
".",
"BasePath",
",",
"relativePath",
")",
",",
"}",
"\n",
"return",
"newRouter",
"\n",
"}"
] | // Subrouter creates a new router with an updated base path.
// The new router copies middleware and configuration from the
// router it derives from. | [
"Subrouter",
"creates",
"a",
"new",
"router",
"with",
"an",
"updated",
"base",
"path",
".",
"The",
"new",
"router",
"copies",
"middleware",
"and",
"configuration",
"from",
"the",
"router",
"it",
"derives",
"from",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/router.go#L74-L82 |
8,483 | luci/luci-go | server/router/router.go | ServeHTTP | func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
r.hrouter.ServeHTTP(rw, req)
} | go | func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
r.hrouter.ServeHTTP(rw, req)
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"ServeHTTP",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"r",
".",
"hrouter",
".",
"ServeHTTP",
"(",
"rw",
",",
"req",
")",
"\n",
"}"
] | // ServeHTTP makes Router implement the http.Handler interface. | [
"ServeHTTP",
"makes",
"Router",
"implement",
"the",
"http",
".",
"Handler",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/router.go#L129-L131 |
8,484 | luci/luci-go | server/router/router.go | NotFound | func (r *Router) NotFound(mc MiddlewareChain, h Handler) {
handle := r.adapt(mc, h, "")
r.hrouter.NotFound = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
handle(rw, req, nil)
})
} | go | func (r *Router) NotFound(mc MiddlewareChain, h Handler) {
handle := r.adapt(mc, h, "")
r.hrouter.NotFound = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
handle(rw, req, nil)
})
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"NotFound",
"(",
"mc",
"MiddlewareChain",
",",
"h",
"Handler",
")",
"{",
"handle",
":=",
"r",
".",
"adapt",
"(",
"mc",
",",
"h",
",",
"\"",
"\"",
")",
"\n",
"r",
".",
"hrouter",
".",
"NotFound",
"=",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"handle",
"(",
"rw",
",",
"req",
",",
"nil",
")",
"\n",
"}",
")",
"\n",
"}"
] | // NotFound sets the handler to be called when no matching route is found. | [
"NotFound",
"sets",
"the",
"handler",
"to",
"be",
"called",
"when",
"no",
"matching",
"route",
"is",
"found",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/router.go#L144-L149 |
8,485 | luci/luci-go | server/router/router.go | adapt | func (r *Router) adapt(mc MiddlewareChain, h Handler, path string) httprouter.Handle {
return httprouter.Handle(func(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
runChains(&Context{
Context: r.rootCtx,
Writer: rw,
Request: req,
Params: p,
HandlerPath: path,
}, r.middleware, mc, h)
})
} | go | func (r *Router) adapt(mc MiddlewareChain, h Handler, path string) httprouter.Handle {
return httprouter.Handle(func(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
runChains(&Context{
Context: r.rootCtx,
Writer: rw,
Request: req,
Params: p,
HandlerPath: path,
}, r.middleware, mc, h)
})
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"adapt",
"(",
"mc",
"MiddlewareChain",
",",
"h",
"Handler",
",",
"path",
"string",
")",
"httprouter",
".",
"Handle",
"{",
"return",
"httprouter",
".",
"Handle",
"(",
"func",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"p",
"httprouter",
".",
"Params",
")",
"{",
"runChains",
"(",
"&",
"Context",
"{",
"Context",
":",
"r",
".",
"rootCtx",
",",
"Writer",
":",
"rw",
",",
"Request",
":",
"req",
",",
"Params",
":",
"p",
",",
"HandlerPath",
":",
"path",
",",
"}",
",",
"r",
".",
"middleware",
",",
"mc",
",",
"h",
")",
"\n",
"}",
")",
"\n",
"}"
] | // adapt adapts given middleware chain and handler into a httprouter-style handle. | [
"adapt",
"adapts",
"given",
"middleware",
"chain",
"and",
"handler",
"into",
"a",
"httprouter",
"-",
"style",
"handle",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/router.go#L152-L162 |
8,486 | luci/luci-go | scheduler/appengine/schedule/schedule.go | parseCronSchedule | func parseCronSchedule(expr string, randSeed uint64) (*Schedule, error) {
cronexprLock.Lock()
exp, err := cronexpr.Parse(expr)
cronexprLock.Unlock()
if err != nil {
return nil, err
}
return &Schedule{cronExpr: exp}, nil
} | go | func parseCronSchedule(expr string, randSeed uint64) (*Schedule, error) {
cronexprLock.Lock()
exp, err := cronexpr.Parse(expr)
cronexprLock.Unlock()
if err != nil {
return nil, err
}
return &Schedule{cronExpr: exp}, nil
} | [
"func",
"parseCronSchedule",
"(",
"expr",
"string",
",",
"randSeed",
"uint64",
")",
"(",
"*",
"Schedule",
",",
"error",
")",
"{",
"cronexprLock",
".",
"Lock",
"(",
")",
"\n",
"exp",
",",
"err",
":=",
"cronexpr",
".",
"Parse",
"(",
"expr",
")",
"\n",
"cronexprLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"Schedule",
"{",
"cronExpr",
":",
"exp",
"}",
",",
"nil",
"\n",
"}"
] | // parseCronSchedule parses crontab-like schedule string. | [
"parseCronSchedule",
"parses",
"crontab",
"-",
"like",
"schedule",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/schedule/schedule.go#L158-L166 |
8,487 | luci/luci-go | milo/frontend/view_error.go | ErrorHandler | func ErrorHandler(c *router.Context, err error) {
code := grpcutil.Code(err)
switch code {
case codes.Unauthenticated:
loginURL, err := auth.LoginURL(c.Context, c.Request.URL.RequestURI())
if err == nil {
http.Redirect(c.Writer, c.Request, loginURL, http.StatusFound)
return
}
errors.Log(
c.Context, errors.Annotate(err, "Failed to retrieve login URL").Err())
case codes.OK:
// All good.
default:
errors.Log(c.Context, err)
}
status := grpcutil.CodeStatus(code)
c.Writer.WriteHeader(status)
templates.MustRender(c.Context, c.Writer, "pages/error.html", templates.Args{
"Code": status,
"Message": err.Error(),
})
} | go | func ErrorHandler(c *router.Context, err error) {
code := grpcutil.Code(err)
switch code {
case codes.Unauthenticated:
loginURL, err := auth.LoginURL(c.Context, c.Request.URL.RequestURI())
if err == nil {
http.Redirect(c.Writer, c.Request, loginURL, http.StatusFound)
return
}
errors.Log(
c.Context, errors.Annotate(err, "Failed to retrieve login URL").Err())
case codes.OK:
// All good.
default:
errors.Log(c.Context, err)
}
status := grpcutil.CodeStatus(code)
c.Writer.WriteHeader(status)
templates.MustRender(c.Context, c.Writer, "pages/error.html", templates.Args{
"Code": status,
"Message": err.Error(),
})
} | [
"func",
"ErrorHandler",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"err",
"error",
")",
"{",
"code",
":=",
"grpcutil",
".",
"Code",
"(",
"err",
")",
"\n",
"switch",
"code",
"{",
"case",
"codes",
".",
"Unauthenticated",
":",
"loginURL",
",",
"err",
":=",
"auth",
".",
"LoginURL",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Request",
".",
"URL",
".",
"RequestURI",
"(",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"http",
".",
"Redirect",
"(",
"c",
".",
"Writer",
",",
"c",
".",
"Request",
",",
"loginURL",
",",
"http",
".",
"StatusFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"errors",
".",
"Log",
"(",
"c",
".",
"Context",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
")",
"\n",
"case",
"codes",
".",
"OK",
":",
"// All good.",
"default",
":",
"errors",
".",
"Log",
"(",
"c",
".",
"Context",
",",
"err",
")",
"\n",
"}",
"\n\n",
"status",
":=",
"grpcutil",
".",
"CodeStatus",
"(",
"code",
")",
"\n",
"c",
".",
"Writer",
".",
"WriteHeader",
"(",
"status",
")",
"\n",
"templates",
".",
"MustRender",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Writer",
",",
"\"",
"\"",
",",
"templates",
".",
"Args",
"{",
"\"",
"\"",
":",
"status",
",",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
",",
"}",
")",
"\n",
"}"
] | // ErrorHandler renders an error page for the user. | [
"ErrorHandler",
"renders",
"an",
"error",
"page",
"for",
"the",
"user",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_error.go#L19-L42 |
8,488 | luci/luci-go | scheduler/appengine/engine/policy/validation.go | ValidateDefinition | func ValidateDefinition(ctx *validation.Context, p *messages.TriggeringPolicy) {
switch p.Kind {
case
messages.TriggeringPolicy_UNDEFINED, // same as GREEDY_BATCHING
messages.TriggeringPolicy_GREEDY_BATCHING,
messages.TriggeringPolicy_LOGARITHMIC_BATCHING:
// ok
default:
ctx.Errorf("unrecognized policy kind %d", p.Kind)
}
// Note: 0 is fine. It means "use default".
if p.MaxConcurrentInvocations < 0 {
ctx.Errorf("max_concurrent_invocations should be positive, got %d", p.MaxConcurrentInvocations)
}
// Same here.
if p.MaxBatchSize < 0 {
ctx.Errorf("max_batch_size should be positive, got %d", p.MaxBatchSize)
}
if p.Kind == messages.TriggeringPolicy_LOGARITHMIC_BATCHING && p.LogBase < 1.0001 {
ctx.Errorf("log_base should be larger or equal 1.0001, got %f", p.LogBase)
}
} | go | func ValidateDefinition(ctx *validation.Context, p *messages.TriggeringPolicy) {
switch p.Kind {
case
messages.TriggeringPolicy_UNDEFINED, // same as GREEDY_BATCHING
messages.TriggeringPolicy_GREEDY_BATCHING,
messages.TriggeringPolicy_LOGARITHMIC_BATCHING:
// ok
default:
ctx.Errorf("unrecognized policy kind %d", p.Kind)
}
// Note: 0 is fine. It means "use default".
if p.MaxConcurrentInvocations < 0 {
ctx.Errorf("max_concurrent_invocations should be positive, got %d", p.MaxConcurrentInvocations)
}
// Same here.
if p.MaxBatchSize < 0 {
ctx.Errorf("max_batch_size should be positive, got %d", p.MaxBatchSize)
}
if p.Kind == messages.TriggeringPolicy_LOGARITHMIC_BATCHING && p.LogBase < 1.0001 {
ctx.Errorf("log_base should be larger or equal 1.0001, got %f", p.LogBase)
}
} | [
"func",
"ValidateDefinition",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"p",
"*",
"messages",
".",
"TriggeringPolicy",
")",
"{",
"switch",
"p",
".",
"Kind",
"{",
"case",
"messages",
".",
"TriggeringPolicy_UNDEFINED",
",",
"// same as GREEDY_BATCHING",
"messages",
".",
"TriggeringPolicy_GREEDY_BATCHING",
",",
"messages",
".",
"TriggeringPolicy_LOGARITHMIC_BATCHING",
":",
"// ok",
"default",
":",
"ctx",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
".",
"Kind",
")",
"\n",
"}",
"\n\n",
"// Note: 0 is fine. It means \"use default\".",
"if",
"p",
".",
"MaxConcurrentInvocations",
"<",
"0",
"{",
"ctx",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
".",
"MaxConcurrentInvocations",
")",
"\n",
"}",
"\n",
"// Same here.",
"if",
"p",
".",
"MaxBatchSize",
"<",
"0",
"{",
"ctx",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
".",
"MaxBatchSize",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"Kind",
"==",
"messages",
".",
"TriggeringPolicy_LOGARITHMIC_BATCHING",
"&&",
"p",
".",
"LogBase",
"<",
"1.0001",
"{",
"ctx",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
".",
"LogBase",
")",
"\n",
"}",
"\n",
"}"
] | // ValidateDefinition validates the triggering policy message.
//
// Emits errors into the given context. | [
"ValidateDefinition",
"validates",
"the",
"triggering",
"policy",
"message",
".",
"Emits",
"errors",
"into",
"the",
"given",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/validation.go#L26-L48 |
8,489 | luci/luci-go | scheduler/appengine/engine/policy/simulator.go | DebugLog | func (s *SimulatedEnvironment) DebugLog(format string, args ...interface{}) {
if s.OnDebugLog != nil {
s.OnDebugLog(format, args...)
}
} | go | func (s *SimulatedEnvironment) DebugLog(format string, args ...interface{}) {
if s.OnDebugLog != nil {
s.OnDebugLog(format, args...)
}
} | [
"func",
"(",
"s",
"*",
"SimulatedEnvironment",
")",
"DebugLog",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"s",
".",
"OnDebugLog",
"!=",
"nil",
"{",
"s",
".",
"OnDebugLog",
"(",
"format",
",",
"args",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // DebugLog is part of Environment interface. | [
"DebugLog",
"is",
"part",
"of",
"Environment",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/simulator.go#L109-L113 |
8,490 | luci/luci-go | scheduler/appengine/engine/policy/simulator.go | triage | func (s *Simulator) triage() {
// Collect the unordered list of currently running invocations.
invs := make([]int64, 0, len(s.invIDs))
for id := range s.invIDs {
invs = append(invs, id)
}
// Clone pending triggers list since we don't want the policy to mutate them.
triggers := make([]*internal.Trigger, len(s.PendingTriggers))
for i, t := range s.PendingTriggers {
triggers[i] = proto.Clone(t).(*internal.Trigger)
}
// Execute the policy function, collecting its log.
out := s.Policy(&SimulatedEnvironment{s.OnDebugLog}, In{
Now: s.Now,
ActiveInvocations: invs,
Triggers: triggers,
})
// Instantiate all new invocations and collect a set of consumed triggers.
consumed := stringset.New(0)
for _, r := range out.Requests {
s.handleRequest(r)
for _, t := range r.IncomingTriggers {
consumed.Add(t.Id)
}
}
// Pop all consumed triggers from PendingTriggers list (keeping it sorted).
if consumed.Len() != 0 {
filtered := make([]*internal.Trigger, 0, len(s.PendingTriggers))
for _, t := range s.PendingTriggers {
if !consumed.Has(t.Id) {
filtered = append(filtered, t)
}
}
s.PendingTriggers = filtered
}
} | go | func (s *Simulator) triage() {
// Collect the unordered list of currently running invocations.
invs := make([]int64, 0, len(s.invIDs))
for id := range s.invIDs {
invs = append(invs, id)
}
// Clone pending triggers list since we don't want the policy to mutate them.
triggers := make([]*internal.Trigger, len(s.PendingTriggers))
for i, t := range s.PendingTriggers {
triggers[i] = proto.Clone(t).(*internal.Trigger)
}
// Execute the policy function, collecting its log.
out := s.Policy(&SimulatedEnvironment{s.OnDebugLog}, In{
Now: s.Now,
ActiveInvocations: invs,
Triggers: triggers,
})
// Instantiate all new invocations and collect a set of consumed triggers.
consumed := stringset.New(0)
for _, r := range out.Requests {
s.handleRequest(r)
for _, t := range r.IncomingTriggers {
consumed.Add(t.Id)
}
}
// Pop all consumed triggers from PendingTriggers list (keeping it sorted).
if consumed.Len() != 0 {
filtered := make([]*internal.Trigger, 0, len(s.PendingTriggers))
for _, t := range s.PendingTriggers {
if !consumed.Has(t.Id) {
filtered = append(filtered, t)
}
}
s.PendingTriggers = filtered
}
} | [
"func",
"(",
"s",
"*",
"Simulator",
")",
"triage",
"(",
")",
"{",
"// Collect the unordered list of currently running invocations.",
"invs",
":=",
"make",
"(",
"[",
"]",
"int64",
",",
"0",
",",
"len",
"(",
"s",
".",
"invIDs",
")",
")",
"\n",
"for",
"id",
":=",
"range",
"s",
".",
"invIDs",
"{",
"invs",
"=",
"append",
"(",
"invs",
",",
"id",
")",
"\n",
"}",
"\n\n",
"// Clone pending triggers list since we don't want the policy to mutate them.",
"triggers",
":=",
"make",
"(",
"[",
"]",
"*",
"internal",
".",
"Trigger",
",",
"len",
"(",
"s",
".",
"PendingTriggers",
")",
")",
"\n",
"for",
"i",
",",
"t",
":=",
"range",
"s",
".",
"PendingTriggers",
"{",
"triggers",
"[",
"i",
"]",
"=",
"proto",
".",
"Clone",
"(",
"t",
")",
".",
"(",
"*",
"internal",
".",
"Trigger",
")",
"\n",
"}",
"\n\n",
"// Execute the policy function, collecting its log.",
"out",
":=",
"s",
".",
"Policy",
"(",
"&",
"SimulatedEnvironment",
"{",
"s",
".",
"OnDebugLog",
"}",
",",
"In",
"{",
"Now",
":",
"s",
".",
"Now",
",",
"ActiveInvocations",
":",
"invs",
",",
"Triggers",
":",
"triggers",
",",
"}",
")",
"\n\n",
"// Instantiate all new invocations and collect a set of consumed triggers.",
"consumed",
":=",
"stringset",
".",
"New",
"(",
"0",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"out",
".",
"Requests",
"{",
"s",
".",
"handleRequest",
"(",
"r",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"r",
".",
"IncomingTriggers",
"{",
"consumed",
".",
"Add",
"(",
"t",
".",
"Id",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Pop all consumed triggers from PendingTriggers list (keeping it sorted).",
"if",
"consumed",
".",
"Len",
"(",
")",
"!=",
"0",
"{",
"filtered",
":=",
"make",
"(",
"[",
"]",
"*",
"internal",
".",
"Trigger",
",",
"0",
",",
"len",
"(",
"s",
".",
"PendingTriggers",
")",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"s",
".",
"PendingTriggers",
"{",
"if",
"!",
"consumed",
".",
"Has",
"(",
"t",
".",
"Id",
")",
"{",
"filtered",
"=",
"append",
"(",
"filtered",
",",
"t",
")",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"PendingTriggers",
"=",
"filtered",
"\n",
"}",
"\n",
"}"
] | // triage executes the triggering policy function. | [
"triage",
"executes",
"the",
"triggering",
"policy",
"function",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/simulator.go#L154-L193 |
8,491 | luci/luci-go | scheduler/appengine/engine/policy/simulator.go | handleRequest | func (s *Simulator) handleRequest(r task.Request) {
dur := s.OnRequest(s, r)
if dur <= 0 {
panic("the invocation duration should be positive")
}
inv := &SimulatedInvocation{
Request: r,
Created: s.Now.Sub(s.Epoch),
Duration: dur,
Running: true,
}
s.Invocations = append(s.Invocations, inv)
s.nextInvID++
id := s.nextInvID
if s.invIDs == nil {
s.invIDs = map[int64]*SimulatedInvocation{}
}
s.invIDs[id] = inv
s.scheduleEvent(event{
eta: s.Now.Add(inv.Duration),
cb: func() {
// On invocation completion, kick it from the active invocations set and
// rerun the triggering policy function to decide what to do next.
inv.Running = false
delete(s.invIDs, id)
s.triage()
},
})
} | go | func (s *Simulator) handleRequest(r task.Request) {
dur := s.OnRequest(s, r)
if dur <= 0 {
panic("the invocation duration should be positive")
}
inv := &SimulatedInvocation{
Request: r,
Created: s.Now.Sub(s.Epoch),
Duration: dur,
Running: true,
}
s.Invocations = append(s.Invocations, inv)
s.nextInvID++
id := s.nextInvID
if s.invIDs == nil {
s.invIDs = map[int64]*SimulatedInvocation{}
}
s.invIDs[id] = inv
s.scheduleEvent(event{
eta: s.Now.Add(inv.Duration),
cb: func() {
// On invocation completion, kick it from the active invocations set and
// rerun the triggering policy function to decide what to do next.
inv.Running = false
delete(s.invIDs, id)
s.triage()
},
})
} | [
"func",
"(",
"s",
"*",
"Simulator",
")",
"handleRequest",
"(",
"r",
"task",
".",
"Request",
")",
"{",
"dur",
":=",
"s",
".",
"OnRequest",
"(",
"s",
",",
"r",
")",
"\n",
"if",
"dur",
"<=",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"inv",
":=",
"&",
"SimulatedInvocation",
"{",
"Request",
":",
"r",
",",
"Created",
":",
"s",
".",
"Now",
".",
"Sub",
"(",
"s",
".",
"Epoch",
")",
",",
"Duration",
":",
"dur",
",",
"Running",
":",
"true",
",",
"}",
"\n",
"s",
".",
"Invocations",
"=",
"append",
"(",
"s",
".",
"Invocations",
",",
"inv",
")",
"\n\n",
"s",
".",
"nextInvID",
"++",
"\n",
"id",
":=",
"s",
".",
"nextInvID",
"\n",
"if",
"s",
".",
"invIDs",
"==",
"nil",
"{",
"s",
".",
"invIDs",
"=",
"map",
"[",
"int64",
"]",
"*",
"SimulatedInvocation",
"{",
"}",
"\n",
"}",
"\n",
"s",
".",
"invIDs",
"[",
"id",
"]",
"=",
"inv",
"\n\n",
"s",
".",
"scheduleEvent",
"(",
"event",
"{",
"eta",
":",
"s",
".",
"Now",
".",
"Add",
"(",
"inv",
".",
"Duration",
")",
",",
"cb",
":",
"func",
"(",
")",
"{",
"// On invocation completion, kick it from the active invocations set and",
"// rerun the triggering policy function to decide what to do next.",
"inv",
".",
"Running",
"=",
"false",
"\n",
"delete",
"(",
"s",
".",
"invIDs",
",",
"id",
")",
"\n",
"s",
".",
"triage",
"(",
")",
"\n",
"}",
",",
"}",
")",
"\n",
"}"
] | // handleRequest is called for each invocation request created by the policy.
//
// It adds new SimulatedInvocation to Invocations list. | [
"handleRequest",
"is",
"called",
"for",
"each",
"invocation",
"request",
"created",
"by",
"the",
"policy",
".",
"It",
"adds",
"new",
"SimulatedInvocation",
"to",
"Invocations",
"list",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/simulator.go#L198-L229 |
8,492 | luci/luci-go | scheduler/appengine/engine/policy/simulator.go | AdvanceTime | func (s *Simulator) AdvanceTime(d time.Duration) {
switch {
case d == 0:
return
case d < 0:
panic("time must move forward only")
}
// First tick ever? Reset Now to Epoch, since Epoch is our beginning of times.
if s.Now.IsZero() {
s.Now = s.Epoch
}
deadline := s.Now.Add(d)
for {
// Nothing is happening at all or events happen later than we wish to go?
if ev := s.peekEvent(); ev == nil || ev.eta.After(deadline) {
s.Now = deadline
return
}
// Advance the time to the point when the event is happening and execute the
// event's callback. It may result in most stuff added to the timeline which
// we will discover on the next iteration of the loop.
ev := s.popEvent()
s.Now = ev.eta
ev.cb()
}
} | go | func (s *Simulator) AdvanceTime(d time.Duration) {
switch {
case d == 0:
return
case d < 0:
panic("time must move forward only")
}
// First tick ever? Reset Now to Epoch, since Epoch is our beginning of times.
if s.Now.IsZero() {
s.Now = s.Epoch
}
deadline := s.Now.Add(d)
for {
// Nothing is happening at all or events happen later than we wish to go?
if ev := s.peekEvent(); ev == nil || ev.eta.After(deadline) {
s.Now = deadline
return
}
// Advance the time to the point when the event is happening and execute the
// event's callback. It may result in most stuff added to the timeline which
// we will discover on the next iteration of the loop.
ev := s.popEvent()
s.Now = ev.eta
ev.cb()
}
} | [
"func",
"(",
"s",
"*",
"Simulator",
")",
"AdvanceTime",
"(",
"d",
"time",
".",
"Duration",
")",
"{",
"switch",
"{",
"case",
"d",
"==",
"0",
":",
"return",
"\n",
"case",
"d",
"<",
"0",
":",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// First tick ever? Reset Now to Epoch, since Epoch is our beginning of times.",
"if",
"s",
".",
"Now",
".",
"IsZero",
"(",
")",
"{",
"s",
".",
"Now",
"=",
"s",
".",
"Epoch",
"\n",
"}",
"\n\n",
"deadline",
":=",
"s",
".",
"Now",
".",
"Add",
"(",
"d",
")",
"\n",
"for",
"{",
"// Nothing is happening at all or events happen later than we wish to go?",
"if",
"ev",
":=",
"s",
".",
"peekEvent",
"(",
")",
";",
"ev",
"==",
"nil",
"||",
"ev",
".",
"eta",
".",
"After",
"(",
"deadline",
")",
"{",
"s",
".",
"Now",
"=",
"deadline",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Advance the time to the point when the event is happening and execute the",
"// event's callback. It may result in most stuff added to the timeline which",
"// we will discover on the next iteration of the loop.",
"ev",
":=",
"s",
".",
"popEvent",
"(",
")",
"\n",
"s",
".",
"Now",
"=",
"ev",
".",
"eta",
"\n",
"ev",
".",
"cb",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // AdvanceTime moves the simulated time, executing all events that happen. | [
"AdvanceTime",
"moves",
"the",
"simulated",
"time",
"executing",
"all",
"events",
"that",
"happen",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/simulator.go#L256-L284 |
8,493 | luci/luci-go | scheduler/appengine/engine/policy/simulator.go | scheduleEvent | func (s *Simulator) scheduleEvent(e event) {
if !e.eta.After(s.Now) {
panic("event's ETA should be in the future")
}
heap.Push(&s.events, e)
} | go | func (s *Simulator) scheduleEvent(e event) {
if !e.eta.After(s.Now) {
panic("event's ETA should be in the future")
}
heap.Push(&s.events, e)
} | [
"func",
"(",
"s",
"*",
"Simulator",
")",
"scheduleEvent",
"(",
"e",
"event",
")",
"{",
"if",
"!",
"e",
".",
"eta",
".",
"After",
"(",
"s",
".",
"Now",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"heap",
".",
"Push",
"(",
"&",
"s",
".",
"events",
",",
"e",
")",
"\n",
"}"
] | // scheduleEvent adds an event to the event queue.
//
// Panics if event's ETA is not in the future. | [
"scheduleEvent",
"adds",
"an",
"event",
"to",
"the",
"event",
"queue",
".",
"Panics",
"if",
"event",
"s",
"ETA",
"is",
"not",
"in",
"the",
"future",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/simulator.go#L289-L294 |
8,494 | luci/luci-go | scheduler/appengine/engine/policy/simulator.go | peekEvent | func (s *Simulator) peekEvent() *event {
if len(s.events) == 0 {
return nil
}
return &s.events[0]
} | go | func (s *Simulator) peekEvent() *event {
if len(s.events) == 0 {
return nil
}
return &s.events[0]
} | [
"func",
"(",
"s",
"*",
"Simulator",
")",
"peekEvent",
"(",
")",
"*",
"event",
"{",
"if",
"len",
"(",
"s",
".",
"events",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"s",
".",
"events",
"[",
"0",
"]",
"\n",
"}"
] | // peekEvent peeks at the event that happens next.
//
// Returns nil if there are no pending events. | [
"peekEvent",
"peeks",
"at",
"the",
"event",
"that",
"happens",
"next",
".",
"Returns",
"nil",
"if",
"there",
"are",
"no",
"pending",
"events",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/simulator.go#L299-L304 |
8,495 | luci/luci-go | scheduler/appengine/engine/policy/simulator.go | popEvent | func (s *Simulator) popEvent() event {
if len(s.events) == 0 {
panic("no events to pop")
}
return heap.Pop(&s.events).(event)
} | go | func (s *Simulator) popEvent() event {
if len(s.events) == 0 {
panic("no events to pop")
}
return heap.Pop(&s.events).(event)
} | [
"func",
"(",
"s",
"*",
"Simulator",
")",
"popEvent",
"(",
")",
"event",
"{",
"if",
"len",
"(",
"s",
".",
"events",
")",
"==",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"heap",
".",
"Pop",
"(",
"&",
"s",
".",
"events",
")",
".",
"(",
"event",
")",
"\n",
"}"
] | // popEvent removes the event that happens next.
//
// Panics if there's no pending events. | [
"popEvent",
"removes",
"the",
"event",
"that",
"happens",
"next",
".",
"Panics",
"if",
"there",
"s",
"no",
"pending",
"events",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/simulator.go#L309-L314 |
8,496 | luci/luci-go | lucicfg/cli/base/validate.go | ValidateOutput | func ValidateOutput(ctx context.Context, output lucicfg.Output, svc ConfigServiceFactory, host string, failOnWarns bool) ([]*lucicfg.ValidationResult, error) {
configSets := output.ConfigSets()
if len(configSets) == 0 {
return nil, nil // nothing to validate
}
// Log the warning only if there were some config sets we needed to validate.
if host == "" {
logging.Warningf(ctx, "Config service host is not set, skipping validation against LUCI Config service")
return nil, nil
}
srv, err := svc(ctx, host)
if err != nil {
return nil, err
}
validator := lucicfg.RemoteValidator(srv)
// Validate all config sets in parallel.
results := make([]*lucicfg.ValidationResult, len(configSets))
wg := sync.WaitGroup{}
wg.Add(len(configSets))
for i, cs := range configSets {
i, cs := i, cs
go func() {
results[i] = cs.Validate(ctx, validator)
wg.Done()
}()
}
wg.Wait()
// Log all messages, assemble the final verdict. Note that OverallError
// mutates r.Failed.
var merr errors.MultiError
for _, r := range results {
r.Log(ctx)
if err := r.OverallError(failOnWarns); err != nil {
merr = append(merr, err)
}
}
if len(merr) != 0 {
return results, merr
}
return results, nil
} | go | func ValidateOutput(ctx context.Context, output lucicfg.Output, svc ConfigServiceFactory, host string, failOnWarns bool) ([]*lucicfg.ValidationResult, error) {
configSets := output.ConfigSets()
if len(configSets) == 0 {
return nil, nil // nothing to validate
}
// Log the warning only if there were some config sets we needed to validate.
if host == "" {
logging.Warningf(ctx, "Config service host is not set, skipping validation against LUCI Config service")
return nil, nil
}
srv, err := svc(ctx, host)
if err != nil {
return nil, err
}
validator := lucicfg.RemoteValidator(srv)
// Validate all config sets in parallel.
results := make([]*lucicfg.ValidationResult, len(configSets))
wg := sync.WaitGroup{}
wg.Add(len(configSets))
for i, cs := range configSets {
i, cs := i, cs
go func() {
results[i] = cs.Validate(ctx, validator)
wg.Done()
}()
}
wg.Wait()
// Log all messages, assemble the final verdict. Note that OverallError
// mutates r.Failed.
var merr errors.MultiError
for _, r := range results {
r.Log(ctx)
if err := r.OverallError(failOnWarns); err != nil {
merr = append(merr, err)
}
}
if len(merr) != 0 {
return results, merr
}
return results, nil
} | [
"func",
"ValidateOutput",
"(",
"ctx",
"context",
".",
"Context",
",",
"output",
"lucicfg",
".",
"Output",
",",
"svc",
"ConfigServiceFactory",
",",
"host",
"string",
",",
"failOnWarns",
"bool",
")",
"(",
"[",
"]",
"*",
"lucicfg",
".",
"ValidationResult",
",",
"error",
")",
"{",
"configSets",
":=",
"output",
".",
"ConfigSets",
"(",
")",
"\n",
"if",
"len",
"(",
"configSets",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"// nothing to validate",
"\n",
"}",
"\n\n",
"// Log the warning only if there were some config sets we needed to validate.",
"if",
"host",
"==",
"\"",
"\"",
"{",
"logging",
".",
"Warningf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"srv",
",",
"err",
":=",
"svc",
"(",
"ctx",
",",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"validator",
":=",
"lucicfg",
".",
"RemoteValidator",
"(",
"srv",
")",
"\n\n",
"// Validate all config sets in parallel.",
"results",
":=",
"make",
"(",
"[",
"]",
"*",
"lucicfg",
".",
"ValidationResult",
",",
"len",
"(",
"configSets",
")",
")",
"\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"wg",
".",
"Add",
"(",
"len",
"(",
"configSets",
")",
")",
"\n",
"for",
"i",
",",
"cs",
":=",
"range",
"configSets",
"{",
"i",
",",
"cs",
":=",
"i",
",",
"cs",
"\n",
"go",
"func",
"(",
")",
"{",
"results",
"[",
"i",
"]",
"=",
"cs",
".",
"Validate",
"(",
"ctx",
",",
"validator",
")",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"// Log all messages, assemble the final verdict. Note that OverallError",
"// mutates r.Failed.",
"var",
"merr",
"errors",
".",
"MultiError",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"results",
"{",
"r",
".",
"Log",
"(",
"ctx",
")",
"\n",
"if",
"err",
":=",
"r",
".",
"OverallError",
"(",
"failOnWarns",
")",
";",
"err",
"!=",
"nil",
"{",
"merr",
"=",
"append",
"(",
"merr",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"merr",
")",
"!=",
"0",
"{",
"return",
"results",
",",
"merr",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // ValidateOutput splits the output into 0 or more config sets and sends them
// for validation to LUCI Config.
//
// It is a common part of subcommands that validate configs.
//
// It is allowed for 'host' to be empty. This causes a warning and
// the validation is skipped.
//
// If failOnWarn is true, treat warnings from LUCI Config as errors.
//
// Dumps validation errors to the logger. In addition to detailed validation
// results, also returns a multi-error with all validation and RPC errors. | [
"ValidateOutput",
"splits",
"the",
"output",
"into",
"0",
"or",
"more",
"config",
"sets",
"and",
"sends",
"them",
"for",
"validation",
"to",
"LUCI",
"Config",
".",
"It",
"is",
"a",
"common",
"part",
"of",
"subcommands",
"that",
"validate",
"configs",
".",
"It",
"is",
"allowed",
"for",
"host",
"to",
"be",
"empty",
".",
"This",
"causes",
"a",
"warning",
"and",
"the",
"validation",
"is",
"skipped",
".",
"If",
"failOnWarn",
"is",
"true",
"treat",
"warnings",
"from",
"LUCI",
"Config",
"as",
"errors",
".",
"Dumps",
"validation",
"errors",
"to",
"the",
"logger",
".",
"In",
"addition",
"to",
"detailed",
"validation",
"results",
"also",
"returns",
"a",
"multi",
"-",
"error",
"with",
"all",
"validation",
"and",
"RPC",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/cli/base/validate.go#L46-L91 |
8,497 | luci/luci-go | cipd/client/cipd/deployer/paranoia.go | Validate | func (p ParanoidMode) Validate() error {
switch p {
case NotParanoid, CheckPresence, CheckIntegrity:
return nil
default:
return fmt.Errorf("unrecognized paranoid mode %q", p)
}
} | go | func (p ParanoidMode) Validate() error {
switch p {
case NotParanoid, CheckPresence, CheckIntegrity:
return nil
default:
return fmt.Errorf("unrecognized paranoid mode %q", p)
}
} | [
"func",
"(",
"p",
"ParanoidMode",
")",
"Validate",
"(",
")",
"error",
"{",
"switch",
"p",
"{",
"case",
"NotParanoid",
",",
"CheckPresence",
",",
"CheckIntegrity",
":",
"return",
"nil",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
")",
"\n",
"}",
"\n",
"}"
] | // Validate returns an error if the mode is unrecognized. | [
"Validate",
"returns",
"an",
"error",
"if",
"the",
"mode",
"is",
"unrecognized",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/paranoia.go#L47-L54 |
8,498 | luci/luci-go | machine-db/client/cli/nics.go | printNICs | func printNICs(tsv bool, nics ...*crimson.NIC) {
if len(nics) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Machine", "MAC Address", "Switch", "Port")
}
for _, n := range nics {
p.Row(n.Name, n.Machine, n.MacAddress, n.Switch, n.Switchport)
}
}
} | go | func printNICs(tsv bool, nics ...*crimson.NIC) {
if len(nics) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Machine", "MAC Address", "Switch", "Port")
}
for _, n := range nics {
p.Row(n.Name, n.Machine, n.MacAddress, n.Switch, n.Switchport)
}
}
} | [
"func",
"printNICs",
"(",
"tsv",
"bool",
",",
"nics",
"...",
"*",
"crimson",
".",
"NIC",
")",
"{",
"if",
"len",
"(",
"nics",
")",
">",
"0",
"{",
"p",
":=",
"newStdoutPrinter",
"(",
"tsv",
")",
"\n",
"defer",
"p",
".",
"Flush",
"(",
")",
"\n",
"if",
"!",
"tsv",
"{",
"p",
".",
"Row",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"nics",
"{",
"p",
".",
"Row",
"(",
"n",
".",
"Name",
",",
"n",
".",
"Machine",
",",
"n",
".",
"MacAddress",
",",
"n",
".",
"Switch",
",",
"n",
".",
"Switchport",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // printNICs prints network interface data to stdout in tab-separated columns. | [
"printNICs",
"prints",
"network",
"interface",
"data",
"to",
"stdout",
"in",
"tab",
"-",
"separated",
"columns",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/nics.go#L28-L39 |
8,499 | luci/luci-go | machine-db/client/cli/nics.go | Run | func (c *AddNICCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
// TODO(smut): Validate required fields client-side.
req := &crimson.CreateNICRequest{
Nic: &c.nic,
}
client := getClient(ctx)
resp, err := client.CreateNIC(ctx, req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printNICs(c.f.tsv, resp)
return 0
} | go | func (c *AddNICCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
// TODO(smut): Validate required fields client-side.
req := &crimson.CreateNICRequest{
Nic: &c.nic,
}
client := getClient(ctx)
resp, err := client.CreateNIC(ctx, req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printNICs(c.f.tsv, resp)
return 0
} | [
"func",
"(",
"c",
"*",
"AddNICCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"c",
",",
"env",
")",
"\n",
"// TODO(smut): Validate required fields client-side.",
"req",
":=",
"&",
"crimson",
".",
"CreateNICRequest",
"{",
"Nic",
":",
"&",
"c",
".",
"nic",
",",
"}",
"\n",
"client",
":=",
"getClient",
"(",
"ctx",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"CreateNIC",
"(",
"ctx",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Log",
"(",
"ctx",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"printNICs",
"(",
"c",
".",
"f",
".",
"tsv",
",",
"resp",
")",
"\n",
"return",
"0",
"\n",
"}"
] | // Run runs the command to add a network interface. | [
"Run",
"runs",
"the",
"command",
"to",
"add",
"a",
"network",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/nics.go#L48-L62 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.