id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
7,200 | luci/luci-go | mp/cmd/mpagent/agent_linux.go | configureAutoMount | func (LinuxStrategy) configureAutoMount(ctx context.Context, disk string) error {
// Wait for the disk to be attached.
for {
err := exec.Command("blkid", disk).Run()
if err == nil {
logging.Infof(ctx, "Attached: %s.", disk)
break
}
s := err.(*exec.ExitError).Sys().(syscall.WaitStatus)
if s.ExitStatus() != 2 {
// 2 means the specified device wasn't found.
// Keep waiting if 2, otherwise return an error.
return err
}
time.Sleep(60 * time.Second)
logging.Infof(ctx, "Waiting for disk to be attached...")
}
// Configure auto-mount using fstab.
f, err := os.OpenFile("/etc/fstab", os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if strings.Contains(scanner.Text(), disk) {
logging.Infof(ctx, "Already mounted: %s.", disk)
return nil
}
}
logging.Infof(ctx, "Mounting: %s.", disk)
// Ensure the cursor is at the end so the new line is appended.
f.Seek(0, io.SeekEnd)
line := []byte(fmt.Sprintf("%s /b ext4 defaults,nobootwait,nofail 0 2\n", disk))
if _, err := f.Write(line); err != nil {
return err
}
// Ensure the file is closed before mount reads from it.
f.Close()
return exec.Command("/bin/mount", "--all").Run()
} | go | func (LinuxStrategy) configureAutoMount(ctx context.Context, disk string) error {
// Wait for the disk to be attached.
for {
err := exec.Command("blkid", disk).Run()
if err == nil {
logging.Infof(ctx, "Attached: %s.", disk)
break
}
s := err.(*exec.ExitError).Sys().(syscall.WaitStatus)
if s.ExitStatus() != 2 {
// 2 means the specified device wasn't found.
// Keep waiting if 2, otherwise return an error.
return err
}
time.Sleep(60 * time.Second)
logging.Infof(ctx, "Waiting for disk to be attached...")
}
// Configure auto-mount using fstab.
f, err := os.OpenFile("/etc/fstab", os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if strings.Contains(scanner.Text(), disk) {
logging.Infof(ctx, "Already mounted: %s.", disk)
return nil
}
}
logging.Infof(ctx, "Mounting: %s.", disk)
// Ensure the cursor is at the end so the new line is appended.
f.Seek(0, io.SeekEnd)
line := []byte(fmt.Sprintf("%s /b ext4 defaults,nobootwait,nofail 0 2\n", disk))
if _, err := f.Write(line); err != nil {
return err
}
// Ensure the file is closed before mount reads from it.
f.Close()
return exec.Command("/bin/mount", "--all").Run()
} | [
"func",
"(",
"LinuxStrategy",
")",
"configureAutoMount",
"(",
"ctx",
"context",
".",
"Context",
",",
"disk",
"string",
")",
"error",
"{",
"// Wait for the disk to be attached.",
"for",
"{",
"err",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"disk",
"... | // configureAutoMount mounts the specified disk and configures mount on startup.
//
// Assumes the disk is already formatted as ext4. | [
"configureAutoMount",
"mounts",
"the",
"specified",
"disk",
"and",
"configures",
"mount",
"on",
"startup",
".",
"Assumes",
"the",
"disk",
"is",
"already",
"formatted",
"as",
"ext4",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/agent_linux.go#L57-L97 |
7,201 | luci/luci-go | mp/cmd/mpagent/agent_linux.go | enableSwarming | func (SystemdStrategy) enableSwarming(ctx context.Context) error {
if err := exec.Command("systemctl", "daemon-reload").Run(); err != nil {
return err
}
return exec.Command("systemctl", "enable", "swarming-start-bot").Run()
} | go | func (SystemdStrategy) enableSwarming(ctx context.Context) error {
if err := exec.Command("systemctl", "daemon-reload").Run(); err != nil {
return err
}
return exec.Command("systemctl", "enable", "swarming-start-bot").Run()
} | [
"func",
"(",
"SystemdStrategy",
")",
"enableSwarming",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"err",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
... | // enableSwarming enables installed service. | [
"enableSwarming",
"enables",
"installed",
"service",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/agent_linux.go#L109-L114 |
7,202 | luci/luci-go | mp/cmd/mpagent/agent_linux.go | getAgent | func getAgent(ctx context.Context) (*Agent, error) {
if systemdFound() {
agent := Agent{
agentAutoStartPath: "/etc/systemd/system/machine-provider-agent.service",
agentAutoStartTemplate: "machine-provider-agent.service.tmpl",
logsDir: "/var/log/machine-provider-agent",
swarmingAutoStartPath: "/etc/systemd/system/swarming-start-bot.service",
swarmingAutoStartTemplate: "swarming-start-bot.service.tmpl",
swarmingBotDir: "/b/s",
strategy: SystemdStrategy{},
}
logging.Infof(ctx, "Using systemd Linux agent.")
return &agent, nil
}
if upstartFound() {
agent := Agent{
agentAutoStartPath: "/etc/init/machine-provider-agent.conf",
agentAutoStartTemplate: "machine-provider-agent.conf.tmpl",
logsDir: "/var/log/messages/machine-provider-agent",
swarmingAutoStartPath: "/etc/init/swarming-start-bot.conf",
swarmingAutoStartTemplate: "swarming-start-bot.conf.tmpl",
swarmingBotDir: "/b/s",
strategy: UpstartStrategy{},
}
logging.Infof(ctx, "Using Upstart Linux agent.")
return &agent, nil
}
return nil, errors.New("unsupported init system, expected systemd or Upstart")
} | go | func getAgent(ctx context.Context) (*Agent, error) {
if systemdFound() {
agent := Agent{
agentAutoStartPath: "/etc/systemd/system/machine-provider-agent.service",
agentAutoStartTemplate: "machine-provider-agent.service.tmpl",
logsDir: "/var/log/machine-provider-agent",
swarmingAutoStartPath: "/etc/systemd/system/swarming-start-bot.service",
swarmingAutoStartTemplate: "swarming-start-bot.service.tmpl",
swarmingBotDir: "/b/s",
strategy: SystemdStrategy{},
}
logging.Infof(ctx, "Using systemd Linux agent.")
return &agent, nil
}
if upstartFound() {
agent := Agent{
agentAutoStartPath: "/etc/init/machine-provider-agent.conf",
agentAutoStartTemplate: "machine-provider-agent.conf.tmpl",
logsDir: "/var/log/messages/machine-provider-agent",
swarmingAutoStartPath: "/etc/init/swarming-start-bot.conf",
swarmingAutoStartTemplate: "swarming-start-bot.conf.tmpl",
swarmingBotDir: "/b/s",
strategy: UpstartStrategy{},
}
logging.Infof(ctx, "Using Upstart Linux agent.")
return &agent, nil
}
return nil, errors.New("unsupported init system, expected systemd or Upstart")
} | [
"func",
"getAgent",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"Agent",
",",
"error",
")",
"{",
"if",
"systemdFound",
"(",
")",
"{",
"agent",
":=",
"Agent",
"{",
"agentAutoStartPath",
":",
"\"",
"\"",
",",
"agentAutoStartTemplate",
":",
"\"",
... | // getAgent returns an agent which runs on Linux, depending on supported init systems. | [
"getAgent",
"returns",
"an",
"agent",
"which",
"runs",
"on",
"Linux",
"depending",
"on",
"supported",
"init",
"systems",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/agent_linux.go#L165-L195 |
7,203 | luci/luci-go | gce/appengine/backend/common.go | withConfig | func withConfig(c context.Context, cfg config.ConfigurationServer) context.Context {
return context.WithValue(c, &cfgKey, cfg)
} | go | func withConfig(c context.Context, cfg config.ConfigurationServer) context.Context {
return context.WithValue(c, &cfgKey, cfg)
} | [
"func",
"withConfig",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"config",
".",
"ConfigurationServer",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"cfgKey",
",",
"cfg",
")",
"\n",
"}"
] | // withConfig returns a new context with the given config.ConfigurationServer installed. | [
"withConfig",
"returns",
"a",
"new",
"context",
"with",
"the",
"given",
"config",
".",
"ConfigurationServer",
"installed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/common.go#L66-L68 |
7,204 | luci/luci-go | gce/appengine/backend/common.go | getConfig | func getConfig(c context.Context) config.ConfigurationServer {
return c.Value(&cfgKey).(config.ConfigurationServer)
} | go | func getConfig(c context.Context) config.ConfigurationServer {
return c.Value(&cfgKey).(config.ConfigurationServer)
} | [
"func",
"getConfig",
"(",
"c",
"context",
".",
"Context",
")",
"config",
".",
"ConfigurationServer",
"{",
"return",
"c",
".",
"Value",
"(",
"&",
"cfgKey",
")",
".",
"(",
"config",
".",
"ConfigurationServer",
")",
"\n",
"}"
] | // getConfig returns the config.ConfigurationServer installed in the current context. | [
"getConfig",
"returns",
"the",
"config",
".",
"ConfigurationServer",
"installed",
"in",
"the",
"current",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/common.go#L71-L73 |
7,205 | luci/luci-go | config/impl/erroring/erroring.go | New | func New(err error) config.Interface {
if err == nil {
panic("error cannot be nil")
}
return erroringInterface{err}
} | go | func New(err error) config.Interface {
if err == nil {
panic("error cannot be nil")
}
return erroringInterface{err}
} | [
"func",
"New",
"(",
"err",
"error",
")",
"config",
".",
"Interface",
"{",
"if",
"err",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"erroringInterface",
"{",
"err",
"}",
"\n",
"}"
] | // New creates a new erroring interface. This interface will always return an
// error for every API call.
//
// The supplied error must not be nil. If it is, New will panic. | [
"New",
"creates",
"a",
"new",
"erroring",
"interface",
".",
"This",
"interface",
"will",
"always",
"return",
"an",
"error",
"for",
"every",
"API",
"call",
".",
"The",
"supplied",
"error",
"must",
"not",
"be",
"nil",
".",
"If",
"it",
"is",
"New",
"will",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/erroring/erroring.go#L30-L35 |
7,206 | luci/luci-go | scheduler/appengine/presentation/state.go | GetPublicStateKind | func GetPublicStateKind(j *engine.Job, traits task.Traits) PublicStateKind {
// TODO(vadimsh): Expose more states.
cronTick := j.CronTickTime()
switch {
case len(j.ActiveInvocations) != 0:
return PublicStateRunning
case !j.Enabled:
return PublicStateDisabled
case j.Paused:
return PublicStatePaused
case !cronTick.IsZero() && cronTick != schedule.DistantFuture:
return PublicStateScheduled
default:
return PublicStateWaiting
}
} | go | func GetPublicStateKind(j *engine.Job, traits task.Traits) PublicStateKind {
// TODO(vadimsh): Expose more states.
cronTick := j.CronTickTime()
switch {
case len(j.ActiveInvocations) != 0:
return PublicStateRunning
case !j.Enabled:
return PublicStateDisabled
case j.Paused:
return PublicStatePaused
case !cronTick.IsZero() && cronTick != schedule.DistantFuture:
return PublicStateScheduled
default:
return PublicStateWaiting
}
} | [
"func",
"GetPublicStateKind",
"(",
"j",
"*",
"engine",
".",
"Job",
",",
"traits",
"task",
".",
"Traits",
")",
"PublicStateKind",
"{",
"// TODO(vadimsh): Expose more states.",
"cronTick",
":=",
"j",
".",
"CronTickTime",
"(",
")",
"\n",
"switch",
"{",
"case",
"l... | // GetPublicStateKind returns user-friendly state for a job. | [
"GetPublicStateKind",
"returns",
"user",
"-",
"friendly",
"state",
"for",
"a",
"job",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/presentation/state.go#L43-L58 |
7,207 | luci/luci-go | scheduler/appengine/presentation/state.go | GetJobTraits | func GetJobTraits(ctx context.Context, cat catalog.Catalog, j *engine.Job) (task.Traits, error) {
taskDef, err := cat.UnmarshalTask(ctx, j.Task)
if err != nil {
logging.WithError(err).Warningf(ctx, "Failed to unmarshal task proto for %s", j.JobID)
return task.Traits{}, err
}
if manager := cat.GetTaskManager(taskDef); manager != nil {
return manager.Traits(), nil
}
return task.Traits{}, nil
} | go | func GetJobTraits(ctx context.Context, cat catalog.Catalog, j *engine.Job) (task.Traits, error) {
taskDef, err := cat.UnmarshalTask(ctx, j.Task)
if err != nil {
logging.WithError(err).Warningf(ctx, "Failed to unmarshal task proto for %s", j.JobID)
return task.Traits{}, err
}
if manager := cat.GetTaskManager(taskDef); manager != nil {
return manager.Traits(), nil
}
return task.Traits{}, nil
} | [
"func",
"GetJobTraits",
"(",
"ctx",
"context",
".",
"Context",
",",
"cat",
"catalog",
".",
"Catalog",
",",
"j",
"*",
"engine",
".",
"Job",
")",
"(",
"task",
".",
"Traits",
",",
"error",
")",
"{",
"taskDef",
",",
"err",
":=",
"cat",
".",
"UnmarshalTas... | // GetJobTraits asks the corresponding task manager for a traits struct. | [
"GetJobTraits",
"asks",
"the",
"corresponding",
"task",
"manager",
"for",
"a",
"traits",
"struct",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/presentation/state.go#L61-L71 |
7,208 | luci/luci-go | cipd/client/cipd/ensure/file.go | Serialize | func (f *ResolvedFile) Serialize(w io.Writer) error {
// piggyback on top of File.Serialize.
packagesBySubdir := make(map[string]PackageSlice, len(f.PackagesBySubdir))
for k, v := range f.PackagesBySubdir {
slc := make(PackageSlice, len(v))
for i, pkg := range v {
slc[i] = PackageDef{
PackageTemplate: pkg.PackageName,
UnresolvedVersion: pkg.InstanceID,
}
}
packagesBySubdir[k] = slc
}
return (&File{
ServiceURL: f.ServiceURL,
ParanoidMode: f.ParanoidMode,
PackagesBySubdir: packagesBySubdir,
}).Serialize(w)
} | go | func (f *ResolvedFile) Serialize(w io.Writer) error {
// piggyback on top of File.Serialize.
packagesBySubdir := make(map[string]PackageSlice, len(f.PackagesBySubdir))
for k, v := range f.PackagesBySubdir {
slc := make(PackageSlice, len(v))
for i, pkg := range v {
slc[i] = PackageDef{
PackageTemplate: pkg.PackageName,
UnresolvedVersion: pkg.InstanceID,
}
}
packagesBySubdir[k] = slc
}
return (&File{
ServiceURL: f.ServiceURL,
ParanoidMode: f.ParanoidMode,
PackagesBySubdir: packagesBySubdir,
}).Serialize(w)
} | [
"func",
"(",
"f",
"*",
"ResolvedFile",
")",
"Serialize",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"// piggyback on top of File.Serialize.",
"packagesBySubdir",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"PackageSlice",
",",
"len",
"(",
"f",
".",
... | // Serialize writes the ResolvedFile to an io.Writer in canonical order. | [
"Serialize",
"writes",
"the",
"ResolvedFile",
"to",
"an",
"io",
".",
"Writer",
"in",
"canonical",
"order",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/ensure/file.go#L139-L157 |
7,209 | luci/luci-go | cipd/client/cipd/ensure/file.go | Serialize | func (f *File) Serialize(w io.Writer) error {
_, err := iotools.WriteTracker(w, func(w io.Writer) error {
needsNLs := 0
maybeAddNL := func() {
if needsNLs > 0 {
w.Write(bytes.Repeat([]byte("\n"), needsNLs))
needsNLs = 0
}
}
if f.ServiceURL != "" {
maybeAddNL()
fmt.Fprintf(w, "$ServiceURL %s", f.ServiceURL)
needsNLs = 1
}
if f.ParanoidMode != "" && f.ParanoidMode != deployer.NotParanoid {
maybeAddNL()
fmt.Fprintf(w, "$ParanoidMode %s", f.ParanoidMode)
needsNLs = 1
}
if f.ResolvedVersions != "" {
maybeAddNL()
fmt.Fprintf(w, "$ResolvedVersions %s", f.ResolvedVersions)
needsNLs = 1
}
if needsNLs != 0 {
needsNLs += 1 // new line separator if any of $Directives were used
}
if len(f.VerifyPlatforms) > 0 {
for _, plat := range f.VerifyPlatforms {
maybeAddNL()
fmt.Fprintf(w, "$VerifiedPlatform %s", plat.String())
needsNLs = 1
}
needsNLs = 2
}
keys := make(sort.StringSlice, 0, len(f.PackagesBySubdir))
for k := range f.PackagesBySubdir {
keys = append(keys, k)
}
keys.Sort()
for _, k := range keys {
maybeAddNL()
if k != "" {
fmt.Fprintf(w, "@Subdir %s", k)
needsNLs = 1
}
pkgs := f.PackagesBySubdir[k]
pkgsSort := make(PackageSlice, len(pkgs))
maxLength := 0
for i, pkg := range pkgs {
pkgsSort[i] = pkg
if l := len(pkg.PackageTemplate); l > maxLength {
maxLength = l
}
}
sort.Sort(pkgsSort)
for _, p := range pkgsSort {
maybeAddNL()
fmt.Fprintf(w, "%-*s %s", maxLength+1, p.PackageTemplate, p.UnresolvedVersion)
needsNLs = 1
}
needsNLs++
}
// We only ever want to end the file with 1 newline.
if needsNLs > 0 {
needsNLs = 1
}
maybeAddNL()
return nil
})
return err
} | go | func (f *File) Serialize(w io.Writer) error {
_, err := iotools.WriteTracker(w, func(w io.Writer) error {
needsNLs := 0
maybeAddNL := func() {
if needsNLs > 0 {
w.Write(bytes.Repeat([]byte("\n"), needsNLs))
needsNLs = 0
}
}
if f.ServiceURL != "" {
maybeAddNL()
fmt.Fprintf(w, "$ServiceURL %s", f.ServiceURL)
needsNLs = 1
}
if f.ParanoidMode != "" && f.ParanoidMode != deployer.NotParanoid {
maybeAddNL()
fmt.Fprintf(w, "$ParanoidMode %s", f.ParanoidMode)
needsNLs = 1
}
if f.ResolvedVersions != "" {
maybeAddNL()
fmt.Fprintf(w, "$ResolvedVersions %s", f.ResolvedVersions)
needsNLs = 1
}
if needsNLs != 0 {
needsNLs += 1 // new line separator if any of $Directives were used
}
if len(f.VerifyPlatforms) > 0 {
for _, plat := range f.VerifyPlatforms {
maybeAddNL()
fmt.Fprintf(w, "$VerifiedPlatform %s", plat.String())
needsNLs = 1
}
needsNLs = 2
}
keys := make(sort.StringSlice, 0, len(f.PackagesBySubdir))
for k := range f.PackagesBySubdir {
keys = append(keys, k)
}
keys.Sort()
for _, k := range keys {
maybeAddNL()
if k != "" {
fmt.Fprintf(w, "@Subdir %s", k)
needsNLs = 1
}
pkgs := f.PackagesBySubdir[k]
pkgsSort := make(PackageSlice, len(pkgs))
maxLength := 0
for i, pkg := range pkgs {
pkgsSort[i] = pkg
if l := len(pkg.PackageTemplate); l > maxLength {
maxLength = l
}
}
sort.Sort(pkgsSort)
for _, p := range pkgsSort {
maybeAddNL()
fmt.Fprintf(w, "%-*s %s", maxLength+1, p.PackageTemplate, p.UnresolvedVersion)
needsNLs = 1
}
needsNLs++
}
// We only ever want to end the file with 1 newline.
if needsNLs > 0 {
needsNLs = 1
}
maybeAddNL()
return nil
})
return err
} | [
"func",
"(",
"f",
"*",
"File",
")",
"Serialize",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"_",
",",
"err",
":=",
"iotools",
".",
"WriteTracker",
"(",
"w",
",",
"func",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"needsNLs",
":=",
... | // Serialize writes the File to an io.Writer in canonical order. | [
"Serialize",
"writes",
"the",
"File",
"to",
"an",
"io",
".",
"Writer",
"in",
"canonical",
"order",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/ensure/file.go#L300-L381 |
7,210 | luci/luci-go | server/caching/request.go | WithRequestCache | func WithRequestCache(c context.Context) context.Context {
return context.WithValue(c, &requestCacheKey, lru.New(0))
} | go | func WithRequestCache(c context.Context) context.Context {
return context.WithValue(c, &requestCacheKey, lru.New(0))
} | [
"func",
"WithRequestCache",
"(",
"c",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"requestCacheKey",
",",
"lru",
".",
"New",
"(",
"0",
")",
")",
"\n",
"}"
] | // WithRequestCache initializes context-bound local cache and adds it to the
// Context.
//
// The cache has unbounded size. This is fine, since the lifetime of the cache
// is still scoped to a single request.
//
// It can be used as a second fast layer of caching in front of memcache.
// It is never trimmed, only released at once upon the request completion. | [
"WithRequestCache",
"initializes",
"context",
"-",
"bound",
"local",
"cache",
"and",
"adds",
"it",
"to",
"the",
"Context",
".",
"The",
"cache",
"has",
"unbounded",
"size",
".",
"This",
"is",
"fine",
"since",
"the",
"lifetime",
"of",
"the",
"cache",
"is",
"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/request.go#L33-L35 |
7,211 | luci/luci-go | server/caching/request.go | RequestCache | func RequestCache(c context.Context) *lru.Cache {
rc, _ := c.Value(&requestCacheKey).(*lru.Cache)
if rc == nil {
panic("server/caching: no request cache installed in Context")
}
return rc
} | go | func RequestCache(c context.Context) *lru.Cache {
rc, _ := c.Value(&requestCacheKey).(*lru.Cache)
if rc == nil {
panic("server/caching: no request cache installed in Context")
}
return rc
} | [
"func",
"RequestCache",
"(",
"c",
"context",
".",
"Context",
")",
"*",
"lru",
".",
"Cache",
"{",
"rc",
",",
"_",
":=",
"c",
".",
"Value",
"(",
"&",
"requestCacheKey",
")",
".",
"(",
"*",
"lru",
".",
"Cache",
")",
"\n",
"if",
"rc",
"==",
"nil",
... | // RequestCache retrieves a per-request in-memory cache of the Context. If no
// request cache is installed, this will panic. | [
"RequestCache",
"retrieves",
"a",
"per",
"-",
"request",
"in",
"-",
"memory",
"cache",
"of",
"the",
"Context",
".",
"If",
"no",
"request",
"cache",
"is",
"installed",
"this",
"will",
"panic",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/request.go#L39-L45 |
7,212 | luci/luci-go | config/appengine/backend/memcache/cache.go | Backend | func Backend(b backend.B, exp time.Duration) backend.B {
return &caching.Backend{
B: b,
CacheGet: func(c context.Context, key caching.Key, l caching.Loader) (*caching.Value, error) {
if key.Authority != backend.AsService {
return l(c, key, nil)
}
// Is the item already cached?
k := memcacheKey(&key)
mci, err := mc.GetKey(c, k)
switch err {
case nil:
// Value was cached, successfully retrieved.
v, err := caching.DecodeValue(mci.Value())
if err != nil {
return nil, errors.Annotate(err, "failed to decode cache value from %q", k).Err()
}
return v, nil
case mc.ErrCacheMiss:
// Value was not cached. Load from Loader and cache.
v, err := l(c, key, nil)
if err != nil {
return nil, err
}
// Attempt to cache the value. If this fails, we'll log a warning and
// move on.
err = func() error {
d, err := v.Encode()
if err != nil {
return errors.Annotate(err, "failed to encode value").Err()
}
if len(d) > maxMemCacheSize {
return errors.Reason("entry exceeds memcache size (%d > %d)", len(d), maxMemCacheSize).Err()
}
item := mc.NewItem(c, k).SetValue(d).SetExpiration(exp)
if err := mc.Set(c, item); err != nil {
return errors.Annotate(err, "").Err()
}
return nil
}()
if err != nil {
log.Fields{
log.ErrorKey: err,
"key": k,
}.Warningf(c, "Failed to cache config.")
}
// Return the loaded value.
return v, nil
default:
// Unknown memcache error.
log.Fields{
log.ErrorKey: err,
"key": k,
}.Warningf(c, "Failed to decode memcached config.")
return l(c, key, nil)
}
},
}
} | go | func Backend(b backend.B, exp time.Duration) backend.B {
return &caching.Backend{
B: b,
CacheGet: func(c context.Context, key caching.Key, l caching.Loader) (*caching.Value, error) {
if key.Authority != backend.AsService {
return l(c, key, nil)
}
// Is the item already cached?
k := memcacheKey(&key)
mci, err := mc.GetKey(c, k)
switch err {
case nil:
// Value was cached, successfully retrieved.
v, err := caching.DecodeValue(mci.Value())
if err != nil {
return nil, errors.Annotate(err, "failed to decode cache value from %q", k).Err()
}
return v, nil
case mc.ErrCacheMiss:
// Value was not cached. Load from Loader and cache.
v, err := l(c, key, nil)
if err != nil {
return nil, err
}
// Attempt to cache the value. If this fails, we'll log a warning and
// move on.
err = func() error {
d, err := v.Encode()
if err != nil {
return errors.Annotate(err, "failed to encode value").Err()
}
if len(d) > maxMemCacheSize {
return errors.Reason("entry exceeds memcache size (%d > %d)", len(d), maxMemCacheSize).Err()
}
item := mc.NewItem(c, k).SetValue(d).SetExpiration(exp)
if err := mc.Set(c, item); err != nil {
return errors.Annotate(err, "").Err()
}
return nil
}()
if err != nil {
log.Fields{
log.ErrorKey: err,
"key": k,
}.Warningf(c, "Failed to cache config.")
}
// Return the loaded value.
return v, nil
default:
// Unknown memcache error.
log.Fields{
log.ErrorKey: err,
"key": k,
}.Warningf(c, "Failed to decode memcached config.")
return l(c, key, nil)
}
},
}
} | [
"func",
"Backend",
"(",
"b",
"backend",
".",
"B",
",",
"exp",
"time",
".",
"Duration",
")",
"backend",
".",
"B",
"{",
"return",
"&",
"caching",
".",
"Backend",
"{",
"B",
":",
"b",
",",
"CacheGet",
":",
"func",
"(",
"c",
"context",
".",
"Context",
... | // Backend wraps a backend.B instance with a memcache-backed caching layer whose
// entries expire after exp. | [
"Backend",
"wraps",
"a",
"backend",
".",
"B",
"instance",
"with",
"a",
"memcache",
"-",
"backed",
"caching",
"layer",
"whose",
"entries",
"expire",
"after",
"exp",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/appengine/backend/memcache/cache.go#L39-L104 |
7,213 | luci/luci-go | common/tsmon/types/value_type.go | IsCumulative | func (v ValueType) IsCumulative() bool {
return v == CumulativeIntType ||
v == CumulativeFloatType ||
v == CumulativeDistributionType
} | go | func (v ValueType) IsCumulative() bool {
return v == CumulativeIntType ||
v == CumulativeFloatType ||
v == CumulativeDistributionType
} | [
"func",
"(",
"v",
"ValueType",
")",
"IsCumulative",
"(",
")",
"bool",
"{",
"return",
"v",
"==",
"CumulativeIntType",
"||",
"v",
"==",
"CumulativeFloatType",
"||",
"v",
"==",
"CumulativeDistributionType",
"\n",
"}"
] | // IsCumulative returns true if this is a cumulative metric value type. | [
"IsCumulative",
"returns",
"true",
"if",
"this",
"is",
"a",
"cumulative",
"metric",
"value",
"type",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/types/value_type.go#L59-L63 |
7,214 | luci/luci-go | appengine/datastorecache/lock.go | MemLocker | func MemLocker(c context.Context) Locker {
return &memLocker{
clientID: strings.Join([]string{
"datastore_cache",
info.RequestID(c),
}, "\x00"),
}
} | go | func MemLocker(c context.Context) Locker {
return &memLocker{
clientID: strings.Join([]string{
"datastore_cache",
info.RequestID(c),
}, "\x00"),
}
} | [
"func",
"MemLocker",
"(",
"c",
"context",
".",
"Context",
")",
"Locker",
"{",
"return",
"&",
"memLocker",
"{",
"clientID",
":",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"info",
".",
"RequestID",
"(",
"c",
")",
",",
"}"... | // MemLocker returns a Locker instance that uses a memcache lock bound to the
// current request ID. | [
"MemLocker",
"returns",
"a",
"Locker",
"instance",
"that",
"uses",
"a",
"memcache",
"lock",
"bound",
"to",
"the",
"current",
"request",
"ID",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/datastorecache/lock.go#L48-L55 |
7,215 | luci/luci-go | server/auth/openid/id_token.go | VerifyIDToken | func VerifyIDToken(c context.Context, token string, keys *JSONWebKeySet, issuer, audience string) (*IDToken, error) {
// See https://developers.google.com/identity/protocols/OpenIDConnect#validatinganidtoken
body, err := keys.VerifyJWT(token)
if err != nil {
return nil, err
}
tok := &IDToken{}
if err := json.Unmarshal(body, tok); err != nil {
return nil, fmt.Errorf("bad ID token - not JSON - %s", err)
}
exp := time.Unix(tok.Exp, 0)
now := clock.Now(c)
switch {
case tok.Iss != issuer && "https://"+tok.Iss != issuer:
return nil, fmt.Errorf("bad ID token - expecting issuer %q, got %q", issuer, tok.Iss)
case tok.Aud != audience:
return nil, fmt.Errorf("bad ID token - expecting audience %q, got %q", audience, tok.Aud)
case !tok.EmailVerified:
return nil, fmt.Errorf("bad ID token - the email %q is not verified", tok.Email)
case tok.Sub == "":
return nil, fmt.Errorf("bad ID token - the subject is missing")
case exp.Add(allowedClockSkew).Before(now):
return nil, fmt.Errorf("bad ID token - expired %s ago", now.Sub(exp))
}
return tok, nil
} | go | func VerifyIDToken(c context.Context, token string, keys *JSONWebKeySet, issuer, audience string) (*IDToken, error) {
// See https://developers.google.com/identity/protocols/OpenIDConnect#validatinganidtoken
body, err := keys.VerifyJWT(token)
if err != nil {
return nil, err
}
tok := &IDToken{}
if err := json.Unmarshal(body, tok); err != nil {
return nil, fmt.Errorf("bad ID token - not JSON - %s", err)
}
exp := time.Unix(tok.Exp, 0)
now := clock.Now(c)
switch {
case tok.Iss != issuer && "https://"+tok.Iss != issuer:
return nil, fmt.Errorf("bad ID token - expecting issuer %q, got %q", issuer, tok.Iss)
case tok.Aud != audience:
return nil, fmt.Errorf("bad ID token - expecting audience %q, got %q", audience, tok.Aud)
case !tok.EmailVerified:
return nil, fmt.Errorf("bad ID token - the email %q is not verified", tok.Email)
case tok.Sub == "":
return nil, fmt.Errorf("bad ID token - the subject is missing")
case exp.Add(allowedClockSkew).Before(now):
return nil, fmt.Errorf("bad ID token - expired %s ago", now.Sub(exp))
}
return tok, nil
} | [
"func",
"VerifyIDToken",
"(",
"c",
"context",
".",
"Context",
",",
"token",
"string",
",",
"keys",
"*",
"JSONWebKeySet",
",",
"issuer",
",",
"audience",
"string",
")",
"(",
"*",
"IDToken",
",",
"error",
")",
"{",
"// See https://developers.google.com/identity/pr... | // VerifyIDToken deserializes and verifies the ID token.
//
// This is a fast local operation. | [
"VerifyIDToken",
"deserializes",
"and",
"verifies",
"the",
"ID",
"token",
".",
"This",
"is",
"a",
"fast",
"local",
"operation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/id_token.go#L51-L80 |
7,216 | luci/luci-go | scheduler/appengine/acl/acl.go | CallerHasRole | func (g *GrantsByRole) CallerHasRole(c context.Context, role Role) (bool, error) {
switch role {
case Owner:
return hasGrant(c, g.Owners, groupsAdministrators)
case Triggerer:
return hasGrant(c, g.Owners, g.Triggerers, groupsAdministrators)
case Reader:
return hasGrant(c, g.Owners, g.Readers, g.Triggerers, groupsAdministrators)
default:
panic(errors.New("unknown role, bug in code"))
}
} | go | func (g *GrantsByRole) CallerHasRole(c context.Context, role Role) (bool, error) {
switch role {
case Owner:
return hasGrant(c, g.Owners, groupsAdministrators)
case Triggerer:
return hasGrant(c, g.Owners, g.Triggerers, groupsAdministrators)
case Reader:
return hasGrant(c, g.Owners, g.Readers, g.Triggerers, groupsAdministrators)
default:
panic(errors.New("unknown role, bug in code"))
}
} | [
"func",
"(",
"g",
"*",
"GrantsByRole",
")",
"CallerHasRole",
"(",
"c",
"context",
".",
"Context",
",",
"role",
"Role",
")",
"(",
"bool",
",",
"error",
")",
"{",
"switch",
"role",
"{",
"case",
"Owner",
":",
"return",
"hasGrant",
"(",
"c",
",",
"g",
... | // CallerHasRole does what it says and returns only transient errors. | [
"CallerHasRole",
"does",
"what",
"it",
"says",
"and",
"returns",
"only",
"transient",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/acl/acl.go#L56-L67 |
7,217 | luci/luci-go | scheduler/appengine/acl/acl.go | ValidateACLSets | func ValidateACLSets(ctx *validation.Context, sets []*messages.AclSet) Sets {
as := make(Sets, len(sets))
reportedDups := stringset.New(len(sets))
for _, s := range sets {
_, isDup := as[s.Name]
validName := false
switch {
case s.Name == "":
ctx.Errorf("missing 'name' field'")
case !aclSetNameRe.MatchString(s.Name):
ctx.Errorf("%q is not valid value for 'name' field", s.Name)
case isDup:
if reportedDups.Add(s.Name) {
// Report only first dup.
ctx.Errorf("aclSet name %q is not unique", s.Name)
}
default:
validName = true
}
// record this error regardless of whether name is valid or not
if len(s.GetAcls()) == 0 {
ctx.Errorf("aclSet %q has no entries", s.Name)
} else if validName {
// add if and only if it is valid
as[s.Name] = s.GetAcls()
}
}
return as
} | go | func ValidateACLSets(ctx *validation.Context, sets []*messages.AclSet) Sets {
as := make(Sets, len(sets))
reportedDups := stringset.New(len(sets))
for _, s := range sets {
_, isDup := as[s.Name]
validName := false
switch {
case s.Name == "":
ctx.Errorf("missing 'name' field'")
case !aclSetNameRe.MatchString(s.Name):
ctx.Errorf("%q is not valid value for 'name' field", s.Name)
case isDup:
if reportedDups.Add(s.Name) {
// Report only first dup.
ctx.Errorf("aclSet name %q is not unique", s.Name)
}
default:
validName = true
}
// record this error regardless of whether name is valid or not
if len(s.GetAcls()) == 0 {
ctx.Errorf("aclSet %q has no entries", s.Name)
} else if validName {
// add if and only if it is valid
as[s.Name] = s.GetAcls()
}
}
return as
} | [
"func",
"ValidateACLSets",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"sets",
"[",
"]",
"*",
"messages",
".",
"AclSet",
")",
"Sets",
"{",
"as",
":=",
"make",
"(",
"Sets",
",",
"len",
"(",
"sets",
")",
")",
"\n",
"reportedDups",
":=",
"string... | // ValidateACLSets validates list of AclSet of a project and returns Sets.
//
// Errors are returned via validation.Context. | [
"ValidateACLSets",
"validates",
"list",
"of",
"AclSet",
"of",
"a",
"project",
"and",
"returns",
"Sets",
".",
"Errors",
"are",
"returned",
"via",
"validation",
".",
"Context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/acl/acl.go#L90-L118 |
7,218 | luci/luci-go | scheduler/appengine/acl/acl.go | ValidateTaskACLs | func ValidateTaskACLs(ctx *validation.Context, pSets Sets, tSets []string, tAcls []*messages.Acl) *GrantsByRole {
grantsLists := make([][]*messages.Acl, 0, 1+len(tSets))
ctx.Enter("acls")
validateGrants(ctx, tAcls)
ctx.Exit()
grantsLists = append(grantsLists, tAcls)
ctx.Enter("acl_sets")
for _, set := range tSets {
if grantsList, exists := pSets[set]; exists {
grantsLists = append(grantsLists, grantsList)
} else {
ctx.Errorf("referencing AclSet %q which doesn't exist", set)
}
}
ctx.Exit()
mg := mergeGrants(grantsLists...)
if n := len(mg.Owners) + len(mg.Readers) + len(mg.Triggerers); n > maxGrantsPerJob {
ctx.Errorf("Job or Trigger can have at most %d acls, but %d given", maxGrantsPerJob, n)
}
if len(mg.Owners) == 0 {
ctx.Errorf("Job or Trigger must have OWNER acl set")
}
return mg
} | go | func ValidateTaskACLs(ctx *validation.Context, pSets Sets, tSets []string, tAcls []*messages.Acl) *GrantsByRole {
grantsLists := make([][]*messages.Acl, 0, 1+len(tSets))
ctx.Enter("acls")
validateGrants(ctx, tAcls)
ctx.Exit()
grantsLists = append(grantsLists, tAcls)
ctx.Enter("acl_sets")
for _, set := range tSets {
if grantsList, exists := pSets[set]; exists {
grantsLists = append(grantsLists, grantsList)
} else {
ctx.Errorf("referencing AclSet %q which doesn't exist", set)
}
}
ctx.Exit()
mg := mergeGrants(grantsLists...)
if n := len(mg.Owners) + len(mg.Readers) + len(mg.Triggerers); n > maxGrantsPerJob {
ctx.Errorf("Job or Trigger can have at most %d acls, but %d given", maxGrantsPerJob, n)
}
if len(mg.Owners) == 0 {
ctx.Errorf("Job or Trigger must have OWNER acl set")
}
return mg
} | [
"func",
"ValidateTaskACLs",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"pSets",
"Sets",
",",
"tSets",
"[",
"]",
"string",
",",
"tAcls",
"[",
"]",
"*",
"messages",
".",
"Acl",
")",
"*",
"GrantsByRole",
"{",
"grantsLists",
":=",
"make",
"(",
"["... | // ValidateTaskACLs validates task's ACLs and returns TaskAcls.
//
// Errors are returned via validation.Context. | [
"ValidateTaskACLs",
"validates",
"task",
"s",
"ACLs",
"and",
"returns",
"TaskAcls",
".",
"Errors",
"are",
"returned",
"via",
"validation",
".",
"Context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/acl/acl.go#L123-L146 |
7,219 | luci/luci-go | scheduler/appengine/acl/acl.go | validateGrants | func validateGrants(ctx *validation.Context, gs []*messages.Acl) {
for _, g := range gs {
switch {
case g.GetRole() != messages.Acl_OWNER && g.GetRole() != messages.Acl_READER && g.GetRole() != messages.Acl_TRIGGERER:
ctx.Errorf("invalid role %q", g.GetRole())
case g.GetGrantedTo() == "":
ctx.Errorf("missing granted_to for role %s", g.GetRole())
case strings.HasPrefix(g.GetGrantedTo(), "group:"):
if g.GetGrantedTo()[len("group:"):] == "" {
ctx.Errorf("invalid granted_to %q for role %s: needs a group name", g.GetGrantedTo(), g.GetRole())
}
default:
id := g.GetGrantedTo()
if !strings.ContainsRune(g.GetGrantedTo(), ':') {
id = "user:" + g.GetGrantedTo()
}
if _, err := identity.MakeIdentity(id); err != nil {
ctx.Error(errors.Annotate(err, "invalid granted_to %q for role %s", g.GetGrantedTo(), g.GetRole()).Err())
}
}
}
} | go | func validateGrants(ctx *validation.Context, gs []*messages.Acl) {
for _, g := range gs {
switch {
case g.GetRole() != messages.Acl_OWNER && g.GetRole() != messages.Acl_READER && g.GetRole() != messages.Acl_TRIGGERER:
ctx.Errorf("invalid role %q", g.GetRole())
case g.GetGrantedTo() == "":
ctx.Errorf("missing granted_to for role %s", g.GetRole())
case strings.HasPrefix(g.GetGrantedTo(), "group:"):
if g.GetGrantedTo()[len("group:"):] == "" {
ctx.Errorf("invalid granted_to %q for role %s: needs a group name", g.GetGrantedTo(), g.GetRole())
}
default:
id := g.GetGrantedTo()
if !strings.ContainsRune(g.GetGrantedTo(), ':') {
id = "user:" + g.GetGrantedTo()
}
if _, err := identity.MakeIdentity(id); err != nil {
ctx.Error(errors.Annotate(err, "invalid granted_to %q for role %s", g.GetGrantedTo(), g.GetRole()).Err())
}
}
}
} | [
"func",
"validateGrants",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"gs",
"[",
"]",
"*",
"messages",
".",
"Acl",
")",
"{",
"for",
"_",
",",
"g",
":=",
"range",
"gs",
"{",
"switch",
"{",
"case",
"g",
".",
"GetRole",
"(",
")",
"!=",
"mess... | // validateGrants validates the fields of the provided grants.
//
// Errors are returned via validation.Context. | [
"validateGrants",
"validates",
"the",
"fields",
"of",
"the",
"provided",
"grants",
".",
"Errors",
"are",
"returned",
"via",
"validation",
".",
"Context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/acl/acl.go#L162-L183 |
7,220 | luci/luci-go | scheduler/appengine/acl/acl.go | mergeGrants | func mergeGrants(grantsLists ...[]*messages.Acl) *GrantsByRole {
all := map[messages.Acl_Role]stringset.Set{
messages.Acl_OWNER: stringset.New(maxGrantsPerJob),
messages.Acl_TRIGGERER: stringset.New(maxGrantsPerJob),
messages.Acl_READER: stringset.New(maxGrantsPerJob),
}
for _, grantsList := range grantsLists {
for _, g := range grantsList {
all[g.GetRole()].Add(g.GetGrantedTo())
}
}
sortedSlice := func(s stringset.Set) []string {
r := s.ToSlice()
sort.Strings(r)
return r
}
return &GrantsByRole{
Owners: sortedSlice(all[messages.Acl_OWNER]),
Triggerers: sortedSlice(all[messages.Acl_TRIGGERER]),
Readers: sortedSlice(all[messages.Acl_READER]),
}
} | go | func mergeGrants(grantsLists ...[]*messages.Acl) *GrantsByRole {
all := map[messages.Acl_Role]stringset.Set{
messages.Acl_OWNER: stringset.New(maxGrantsPerJob),
messages.Acl_TRIGGERER: stringset.New(maxGrantsPerJob),
messages.Acl_READER: stringset.New(maxGrantsPerJob),
}
for _, grantsList := range grantsLists {
for _, g := range grantsList {
all[g.GetRole()].Add(g.GetGrantedTo())
}
}
sortedSlice := func(s stringset.Set) []string {
r := s.ToSlice()
sort.Strings(r)
return r
}
return &GrantsByRole{
Owners: sortedSlice(all[messages.Acl_OWNER]),
Triggerers: sortedSlice(all[messages.Acl_TRIGGERER]),
Readers: sortedSlice(all[messages.Acl_READER]),
}
} | [
"func",
"mergeGrants",
"(",
"grantsLists",
"...",
"[",
"]",
"*",
"messages",
".",
"Acl",
")",
"*",
"GrantsByRole",
"{",
"all",
":=",
"map",
"[",
"messages",
".",
"Acl_Role",
"]",
"stringset",
".",
"Set",
"{",
"messages",
".",
"Acl_OWNER",
":",
"stringset... | // mergeGrants merges valid grants into GrantsByRole, removing and sorting duplicates. | [
"mergeGrants",
"merges",
"valid",
"grants",
"into",
"GrantsByRole",
"removing",
"and",
"sorting",
"duplicates",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/acl/acl.go#L186-L207 |
7,221 | luci/luci-go | scheduler/appengine/acl/acl.go | hasGrant | func hasGrant(c context.Context, grantsList ...[]string) (bool, error) {
currentIdentity := auth.CurrentIdentity(c)
var groups []string
for _, grants := range grantsList {
for _, grant := range grants {
if strings.HasPrefix(grant, "group:") {
groups = append(groups, grant[len("group:"):])
continue
}
grantedIdentity := identity.Identity(grant)
if !strings.ContainsRune(grant, ':') {
// Just email.
grantedIdentity = identity.Identity("user:" + grant)
}
if grantedIdentity == currentIdentity {
return true, nil
}
}
}
if isMember, err := auth.IsMember(c, groups...); err != nil {
return false, transient.Tag.Apply(err)
} else {
return isMember, nil
}
} | go | func hasGrant(c context.Context, grantsList ...[]string) (bool, error) {
currentIdentity := auth.CurrentIdentity(c)
var groups []string
for _, grants := range grantsList {
for _, grant := range grants {
if strings.HasPrefix(grant, "group:") {
groups = append(groups, grant[len("group:"):])
continue
}
grantedIdentity := identity.Identity(grant)
if !strings.ContainsRune(grant, ':') {
// Just email.
grantedIdentity = identity.Identity("user:" + grant)
}
if grantedIdentity == currentIdentity {
return true, nil
}
}
}
if isMember, err := auth.IsMember(c, groups...); err != nil {
return false, transient.Tag.Apply(err)
} else {
return isMember, nil
}
} | [
"func",
"hasGrant",
"(",
"c",
"context",
".",
"Context",
",",
"grantsList",
"...",
"[",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"currentIdentity",
":=",
"auth",
".",
"CurrentIdentity",
"(",
"c",
")",
"\n",
"var",
"groups",
"[",
"]",
... | // hasGrant is current user is covered by any given grants. | [
"hasGrant",
"is",
"current",
"user",
"is",
"covered",
"by",
"any",
"given",
"grants",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/acl/acl.go#L210-L234 |
7,222 | luci/luci-go | buildbucket/cli/prop.go | PropertiesFlag | func PropertiesFlag(props *structpb.Struct) flag.Getter {
if props == nil {
panic("props is nil")
}
return &propertiesFlag{
props: props,
first: true,
// We don't expect a lot of properties.
// After a certain number, it is easier to pass properties via a file.
// Choose an arbitrary number.
explicitlySet: stringset.New(4),
}
} | go | func PropertiesFlag(props *structpb.Struct) flag.Getter {
if props == nil {
panic("props is nil")
}
return &propertiesFlag{
props: props,
first: true,
// We don't expect a lot of properties.
// After a certain number, it is easier to pass properties via a file.
// Choose an arbitrary number.
explicitlySet: stringset.New(4),
}
} | [
"func",
"PropertiesFlag",
"(",
"props",
"*",
"structpb",
".",
"Struct",
")",
"flag",
".",
"Getter",
"{",
"if",
"props",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"propertiesFlag",
"{",
"props",
":",
"props",
","... | // PropertiesFlag returns a flag.Getter that can read property values into props.
//
// If a flag value starts with @, properties are read from the JSON file at the
// path that follows @. Example:
// -p @my_properties.json
// This form can be used only in the first flag value.
//
// Otherwise, a flag value must have name=value form.
// If the property value is valid JSON, then it is parsed as JSON;
// otherwise treated as a string. Example:
// -p foo=1 -p 'bar={"a": 2}'
// Different property names can be specified multiple times.
//
// Panics if props is nil.
// String() of the return value panics if marshaling of props to JSON fails. | [
"PropertiesFlag",
"returns",
"a",
"flag",
".",
"Getter",
"that",
"can",
"read",
"property",
"values",
"into",
"props",
".",
"If",
"a",
"flag",
"value",
"starts",
"with"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/prop.go#L50-L62 |
7,223 | luci/luci-go | server/tsmon/middleware.go | Middleware | func (s *State) Middleware(c *router.Context, next router.Handler) {
state, settings := s.checkSettings(c.Context)
if settings.Enabled {
started := clock.Now(c.Context)
req := c.Request
userAgent, ok := req.Header["User-Agent"]
if !ok || len(userAgent) == 0 {
userAgent = []string{"Unknown"}
}
ctx := c.Context
contentLength := c.Request.ContentLength
nrw := newResponseWriter(c.Writer)
c.Writer = nrw
defer func() {
dur := clock.Now(ctx).Sub(started)
metric.UpdateServerMetrics(ctx, c.HandlerPath, nrw.Status(), dur,
contentLength, nrw.Size(), userAgent[0])
}()
next(c)
s.flushIfNeeded(ctx, req, state, settings)
} else {
next(c)
}
} | go | func (s *State) Middleware(c *router.Context, next router.Handler) {
state, settings := s.checkSettings(c.Context)
if settings.Enabled {
started := clock.Now(c.Context)
req := c.Request
userAgent, ok := req.Header["User-Agent"]
if !ok || len(userAgent) == 0 {
userAgent = []string{"Unknown"}
}
ctx := c.Context
contentLength := c.Request.ContentLength
nrw := newResponseWriter(c.Writer)
c.Writer = nrw
defer func() {
dur := clock.Now(ctx).Sub(started)
metric.UpdateServerMetrics(ctx, c.HandlerPath, nrw.Status(), dur,
contentLength, nrw.Size(), userAgent[0])
}()
next(c)
s.flushIfNeeded(ctx, req, state, settings)
} else {
next(c)
}
} | [
"func",
"(",
"s",
"*",
"State",
")",
"Middleware",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"next",
"router",
".",
"Handler",
")",
"{",
"state",
",",
"settings",
":=",
"s",
".",
"checkSettings",
"(",
"c",
".",
"Context",
")",
"\n",
"if",
"sett... | // Middleware is a middleware that collects request metrics and triggers metric
// flushes. | [
"Middleware",
"is",
"a",
"middleware",
"that",
"collects",
"request",
"metrics",
"and",
"triggers",
"metric",
"flushes",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tsmon/middleware.go#L106-L129 |
7,224 | luci/luci-go | server/tsmon/middleware.go | checkSettings | func (s *State) checkSettings(c context.Context) (*tsmon.State, *tsmonSettings) {
state := tsmon.GetState(c)
var settings tsmonSettings
if s.testingSettings != nil {
settings = *s.testingSettings
} else {
settings = fetchCachedSettings(c)
}
// Read the values used when handling previous request. In most cases they
// are identical to current ones and we can skip grabbing a heavier write
// lock.
s.lock.RLock()
if s.state == state && s.lastSettings == settings {
s.lock.RUnlock()
return state, &settings
}
s.lock.RUnlock()
// 'settings' or 'state' has changed. Reinitialize tsmon as needed under
// the write lock.
s.lock.Lock()
defer s.lock.Unlock()
// First call to 'checkSettings' ever?
if s.state == nil {
s.state = state
s.state.SetMonitor(monitor.NewNilMonitor()) // doFlush uses its own monitor
s.state.InhibitGlobalCallbacksOnFlush()
} else if state != s.state {
panic("tsmon state in the context was unexpectedly changed between requests")
}
switch {
case !bool(s.lastSettings.Enabled) && bool(settings.Enabled):
s.enableTsMon(c)
case bool(s.lastSettings.Enabled) && !bool(settings.Enabled):
s.disableTsMon(c)
}
s.lastSettings = settings
return state, &settings
} | go | func (s *State) checkSettings(c context.Context) (*tsmon.State, *tsmonSettings) {
state := tsmon.GetState(c)
var settings tsmonSettings
if s.testingSettings != nil {
settings = *s.testingSettings
} else {
settings = fetchCachedSettings(c)
}
// Read the values used when handling previous request. In most cases they
// are identical to current ones and we can skip grabbing a heavier write
// lock.
s.lock.RLock()
if s.state == state && s.lastSettings == settings {
s.lock.RUnlock()
return state, &settings
}
s.lock.RUnlock()
// 'settings' or 'state' has changed. Reinitialize tsmon as needed under
// the write lock.
s.lock.Lock()
defer s.lock.Unlock()
// First call to 'checkSettings' ever?
if s.state == nil {
s.state = state
s.state.SetMonitor(monitor.NewNilMonitor()) // doFlush uses its own monitor
s.state.InhibitGlobalCallbacksOnFlush()
} else if state != s.state {
panic("tsmon state in the context was unexpectedly changed between requests")
}
switch {
case !bool(s.lastSettings.Enabled) && bool(settings.Enabled):
s.enableTsMon(c)
case bool(s.lastSettings.Enabled) && !bool(settings.Enabled):
s.disableTsMon(c)
}
s.lastSettings = settings
return state, &settings
} | [
"func",
"(",
"s",
"*",
"State",
")",
"checkSettings",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"*",
"tsmon",
".",
"State",
",",
"*",
"tsmonSettings",
")",
"{",
"state",
":=",
"tsmon",
".",
"GetState",
"(",
"c",
")",
"\n\n",
"var",
"settings",
... | // checkSettings fetches tsmon settings and initializes, reinitializes or
// deinitializes tsmon, as needed.
//
// Returns current tsmon state and settings. Panics if the context is using
// unexpected tsmon state. | [
"checkSettings",
"fetches",
"tsmon",
"settings",
"and",
"initializes",
"reinitializes",
"or",
"deinitializes",
"tsmon",
"as",
"needed",
".",
"Returns",
"current",
"tsmon",
"state",
"and",
"settings",
".",
"Panics",
"if",
"the",
"context",
"is",
"using",
"unexpecte... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tsmon/middleware.go#L136-L179 |
7,225 | luci/luci-go | server/tsmon/middleware.go | enableTsMon | func (s *State) enableTsMon(c context.Context) {
t := s.Target(c)
t.TaskNum = -1 // will be assigned later via TaskNumAllocator
s.state.SetStore(store.NewInMemory(&t))
// Request the flush to be executed ASAP, so it registers a claim for a task
// number via NotifyTaskIsAlive. Also reset 'lastFlush', so that we don't get
// invalid logging that the last flush was long time ago.
s.nextFlush = clock.Now(c)
s.lastFlush = s.nextFlush
// Set initial value for retry delay.
s.flushRetry = flushInitialRetry
} | go | func (s *State) enableTsMon(c context.Context) {
t := s.Target(c)
t.TaskNum = -1 // will be assigned later via TaskNumAllocator
s.state.SetStore(store.NewInMemory(&t))
// Request the flush to be executed ASAP, so it registers a claim for a task
// number via NotifyTaskIsAlive. Also reset 'lastFlush', so that we don't get
// invalid logging that the last flush was long time ago.
s.nextFlush = clock.Now(c)
s.lastFlush = s.nextFlush
// Set initial value for retry delay.
s.flushRetry = flushInitialRetry
} | [
"func",
"(",
"s",
"*",
"State",
")",
"enableTsMon",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"t",
":=",
"s",
".",
"Target",
"(",
"c",
")",
"\n",
"t",
".",
"TaskNum",
"=",
"-",
"1",
"// will be assigned later via TaskNumAllocator",
"\n\n",
"s",
".... | // enableTsMon puts in-memory metrics store in the context's tsmon state.
//
// Called with 's.lock' locked. | [
"enableTsMon",
"puts",
"in",
"-",
"memory",
"metrics",
"store",
"in",
"the",
"context",
"s",
"tsmon",
"state",
".",
"Called",
"with",
"s",
".",
"lock",
"locked",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tsmon/middleware.go#L184-L197 |
7,226 | luci/luci-go | server/tsmon/middleware.go | disableTsMon | func (s *State) disableTsMon(c context.Context) {
s.state.SetStore(store.NewNilStore())
} | go | func (s *State) disableTsMon(c context.Context) {
s.state.SetStore(store.NewNilStore())
} | [
"func",
"(",
"s",
"*",
"State",
")",
"disableTsMon",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"s",
".",
"state",
".",
"SetStore",
"(",
"store",
".",
"NewNilStore",
"(",
")",
")",
"\n",
"}"
] | // disableTsMon puts nil metrics store in the context's tsmon state.
//
// Called with 's.lock' locked. | [
"disableTsMon",
"puts",
"nil",
"metrics",
"store",
"in",
"the",
"context",
"s",
"tsmon",
"state",
".",
"Called",
"with",
"s",
".",
"lock",
"locked",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tsmon/middleware.go#L202-L204 |
7,227 | luci/luci-go | server/tsmon/middleware.go | flushIfNeeded | func (s *State) flushIfNeeded(c context.Context, req *http.Request, state *tsmon.State, settings *tsmonSettings) {
now := clock.Now(c)
// Most of the time the flush is not needed and we can get away with
// lightweight RLock.
s.lock.RLock()
skip := s.flushingNow || now.Before(s.nextFlush)
s.lock.RUnlock()
if skip {
return
}
// Need to flush. Update flushingNow. Redo the check under write lock, as well
// as do a bunch of other calls while we hold the lock. Will be useful later.
s.lock.Lock()
if s.instanceID == "" {
s.instanceID = s.InstanceID(c)
}
instanceID := s.instanceID
lastFlush := s.lastFlush
skip = s.flushingNow || now.Before(s.nextFlush)
if !skip {
s.flushingNow = true
}
s.lock.Unlock()
if skip {
return
}
// The flush must be fast. Limit it by some timeout.
c, cancel := clock.WithTimeout(c, flushTimeout)
defer cancel()
// Report per-process statistic.
versions.Report(c)
if settings.ReportRuntimeStats {
runtimestats.Report(c)
}
// Unset 'flushingNow' no matter what (even on panics).
// If flush has failed, retry with back off to avoid
// hammering the receiver.
var err error
defer func() {
s.lock.Lock()
defer s.lock.Unlock()
s.flushingNow = false
if err == nil || err == ErrNoTaskNumber {
// Reset retry delay.
s.flushRetry = flushInitialRetry
s.nextFlush = now.Add(time.Duration(settings.FlushIntervalSec) * time.Second)
if err == nil {
s.lastFlush = now
}
} else {
// Flush has failed, back off the next flush.
if s.flushRetry < flushMaxRetry {
s.flushRetry *= 2
}
s.nextFlush = now.Add(s.flushRetry)
}
}()
err = s.ensureTaskNumAndFlush(c, instanceID, state, settings)
if err != nil {
if err == ErrNoTaskNumber {
logging.Warningf(c, "Skipping the tsmon flush: no task number assigned yet")
} else {
logging.WithError(err).Errorf(c, "Failed to flush tsmon metrics")
}
if sinceLastFlush := now.Sub(lastFlush); sinceLastFlush > noFlushErrorThreshold {
logging.Errorf(c, "No successful tsmon flush for %s. Is /internal/cron/ts_mon/housekeeping running?", sinceLastFlush)
}
}
} | go | func (s *State) flushIfNeeded(c context.Context, req *http.Request, state *tsmon.State, settings *tsmonSettings) {
now := clock.Now(c)
// Most of the time the flush is not needed and we can get away with
// lightweight RLock.
s.lock.RLock()
skip := s.flushingNow || now.Before(s.nextFlush)
s.lock.RUnlock()
if skip {
return
}
// Need to flush. Update flushingNow. Redo the check under write lock, as well
// as do a bunch of other calls while we hold the lock. Will be useful later.
s.lock.Lock()
if s.instanceID == "" {
s.instanceID = s.InstanceID(c)
}
instanceID := s.instanceID
lastFlush := s.lastFlush
skip = s.flushingNow || now.Before(s.nextFlush)
if !skip {
s.flushingNow = true
}
s.lock.Unlock()
if skip {
return
}
// The flush must be fast. Limit it by some timeout.
c, cancel := clock.WithTimeout(c, flushTimeout)
defer cancel()
// Report per-process statistic.
versions.Report(c)
if settings.ReportRuntimeStats {
runtimestats.Report(c)
}
// Unset 'flushingNow' no matter what (even on panics).
// If flush has failed, retry with back off to avoid
// hammering the receiver.
var err error
defer func() {
s.lock.Lock()
defer s.lock.Unlock()
s.flushingNow = false
if err == nil || err == ErrNoTaskNumber {
// Reset retry delay.
s.flushRetry = flushInitialRetry
s.nextFlush = now.Add(time.Duration(settings.FlushIntervalSec) * time.Second)
if err == nil {
s.lastFlush = now
}
} else {
// Flush has failed, back off the next flush.
if s.flushRetry < flushMaxRetry {
s.flushRetry *= 2
}
s.nextFlush = now.Add(s.flushRetry)
}
}()
err = s.ensureTaskNumAndFlush(c, instanceID, state, settings)
if err != nil {
if err == ErrNoTaskNumber {
logging.Warningf(c, "Skipping the tsmon flush: no task number assigned yet")
} else {
logging.WithError(err).Errorf(c, "Failed to flush tsmon metrics")
}
if sinceLastFlush := now.Sub(lastFlush); sinceLastFlush > noFlushErrorThreshold {
logging.Errorf(c, "No successful tsmon flush for %s. Is /internal/cron/ts_mon/housekeeping running?", sinceLastFlush)
}
}
} | [
"func",
"(",
"s",
"*",
"State",
")",
"flushIfNeeded",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"http",
".",
"Request",
",",
"state",
"*",
"tsmon",
".",
"State",
",",
"settings",
"*",
"tsmonSettings",
")",
"{",
"now",
":=",
"clock",
".",
... | // flushIfNeeded periodically flushes the accumulated metrics.
//
// It skips the flush if some other goroutine is already flushing. Logs errors. | [
"flushIfNeeded",
"periodically",
"flushes",
"the",
"accumulated",
"metrics",
".",
"It",
"skips",
"the",
"flush",
"if",
"some",
"other",
"goroutine",
"is",
"already",
"flushing",
".",
"Logs",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tsmon/middleware.go#L209-L283 |
7,228 | luci/luci-go | server/tsmon/middleware.go | ensureTaskNumAndFlush | func (s *State) ensureTaskNumAndFlush(c context.Context, instanceID string, state *tsmon.State, settings *tsmonSettings) error {
var task target.Task
defTarget := state.Store().DefaultTarget()
if t, ok := defTarget.(*target.Task); ok {
task = *t
} else {
return fmt.Errorf("default tsmon target is not a Task (%T): %v", defTarget, defTarget)
}
// Notify the task number allocator that we are still alive and grab the
// TaskNum assigned to us.
assignedTaskNum, err := s.TaskNumAllocator.NotifyTaskIsAlive(c, &task, instanceID)
if err != nil && err != ErrNoTaskNumber {
return fmt.Errorf("failed to get task number assigned for %q - %s", instanceID, err)
}
// Don't do the flush if we still haven't got a task number.
if err == ErrNoTaskNumber {
if task.TaskNum >= 0 {
logging.Warningf(c, "The task was inactive for too long and lost its task number, clearing cumulative metrics")
state.ResetCumulativeMetrics(c)
}
task.TaskNum = -1
state.Store().SetDefaultTarget(&task)
return ErrNoTaskNumber
}
task.TaskNum = int32(assignedTaskNum)
state.Store().SetDefaultTarget(&task)
return s.doFlush(c, state, settings)
} | go | func (s *State) ensureTaskNumAndFlush(c context.Context, instanceID string, state *tsmon.State, settings *tsmonSettings) error {
var task target.Task
defTarget := state.Store().DefaultTarget()
if t, ok := defTarget.(*target.Task); ok {
task = *t
} else {
return fmt.Errorf("default tsmon target is not a Task (%T): %v", defTarget, defTarget)
}
// Notify the task number allocator that we are still alive and grab the
// TaskNum assigned to us.
assignedTaskNum, err := s.TaskNumAllocator.NotifyTaskIsAlive(c, &task, instanceID)
if err != nil && err != ErrNoTaskNumber {
return fmt.Errorf("failed to get task number assigned for %q - %s", instanceID, err)
}
// Don't do the flush if we still haven't got a task number.
if err == ErrNoTaskNumber {
if task.TaskNum >= 0 {
logging.Warningf(c, "The task was inactive for too long and lost its task number, clearing cumulative metrics")
state.ResetCumulativeMetrics(c)
}
task.TaskNum = -1
state.Store().SetDefaultTarget(&task)
return ErrNoTaskNumber
}
task.TaskNum = int32(assignedTaskNum)
state.Store().SetDefaultTarget(&task)
return s.doFlush(c, state, settings)
} | [
"func",
"(",
"s",
"*",
"State",
")",
"ensureTaskNumAndFlush",
"(",
"c",
"context",
".",
"Context",
",",
"instanceID",
"string",
",",
"state",
"*",
"tsmon",
".",
"State",
",",
"settings",
"*",
"tsmonSettings",
")",
"error",
"{",
"var",
"task",
"target",
"... | // ensureTaskNumAndFlush gets a task number assigned to the process and flushes
// the metrics.
//
// Returns ErrNoTaskNumber if the task wasn't assigned a task number yet. | [
"ensureTaskNumAndFlush",
"gets",
"a",
"task",
"number",
"assigned",
"to",
"the",
"process",
"and",
"flushes",
"the",
"metrics",
".",
"Returns",
"ErrNoTaskNumber",
"if",
"the",
"task",
"wasn",
"t",
"assigned",
"a",
"task",
"number",
"yet",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tsmon/middleware.go#L289-L319 |
7,229 | luci/luci-go | server/tsmon/middleware.go | doFlush | func (s *State) doFlush(c context.Context, state *tsmon.State, settings *tsmonSettings) error {
var mon monitor.Monitor
var err error
if s.testingMonitor != nil {
mon = s.testingMonitor
} else if s.IsDevMode || settings.ProdXAccount == "" {
mon = monitor.NewDebugMonitor("")
} else {
logging.Infof(c, "Sending metrics to ProdX using %s", settings.ProdXAccount)
transport, err := auth.GetRPCTransport(
c,
auth.AsActor,
auth.WithServiceAccount(settings.ProdXAccount),
auth.WithScopes(monitor.ProdxmonScopes...))
if err != nil {
return err
}
endpoint, err := url.Parse(prodXEndpoint)
if err != nil {
return err
}
mon, err = monitor.NewHTTPMonitor(c, &http.Client{Transport: transport}, endpoint)
if err != nil {
return err
}
}
defer mon.Close()
if err = state.Flush(c, mon); err != nil {
return err
}
return nil
} | go | func (s *State) doFlush(c context.Context, state *tsmon.State, settings *tsmonSettings) error {
var mon monitor.Monitor
var err error
if s.testingMonitor != nil {
mon = s.testingMonitor
} else if s.IsDevMode || settings.ProdXAccount == "" {
mon = monitor.NewDebugMonitor("")
} else {
logging.Infof(c, "Sending metrics to ProdX using %s", settings.ProdXAccount)
transport, err := auth.GetRPCTransport(
c,
auth.AsActor,
auth.WithServiceAccount(settings.ProdXAccount),
auth.WithScopes(monitor.ProdxmonScopes...))
if err != nil {
return err
}
endpoint, err := url.Parse(prodXEndpoint)
if err != nil {
return err
}
mon, err = monitor.NewHTTPMonitor(c, &http.Client{Transport: transport}, endpoint)
if err != nil {
return err
}
}
defer mon.Close()
if err = state.Flush(c, mon); err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"State",
")",
"doFlush",
"(",
"c",
"context",
".",
"Context",
",",
"state",
"*",
"tsmon",
".",
"State",
",",
"settings",
"*",
"tsmonSettings",
")",
"error",
"{",
"var",
"mon",
"monitor",
".",
"Monitor",
"\n",
"var",
"err",
"err... | // doFlush actually sends the metrics to the monitor. | [
"doFlush",
"actually",
"sends",
"the",
"metrics",
"to",
"the",
"monitor",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tsmon/middleware.go#L322-L356 |
7,230 | luci/luci-go | client/cmd/isolate/archive.go | Printf | func (al *archiveLogger) Printf(format string, a ...interface{}) (n int, err error) {
return al.Fprintf(os.Stdout, format, a...)
} | go | func (al *archiveLogger) Printf(format string, a ...interface{}) (n int, err error) {
return al.Fprintf(os.Stdout, format, a...)
} | [
"func",
"(",
"al",
"*",
"archiveLogger",
")",
"Printf",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"return",
"al",
".",
"Fprintf",
"(",
"os",
".",
"Stdout",
",",
"format",
... | // Print acts like fmt.Printf, but may prepend a prefix to format, depending on the value of al.quiet. | [
"Print",
"acts",
"like",
"fmt",
".",
"Printf",
"but",
"may",
"prepend",
"a",
"prefix",
"to",
"format",
"depending",
"on",
"the",
"value",
"of",
"al",
".",
"quiet",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/isolate/archive.go#L127-L129 |
7,231 | luci/luci-go | client/cmd/isolate/archive.go | Fprintf | func (al *archiveLogger) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
prefix := "\n"
if al.quiet {
prefix = ""
}
args := []interface{}{prefix}
args = append(args, a...)
return fmt.Printf("%s"+format, args...)
} | go | func (al *archiveLogger) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
prefix := "\n"
if al.quiet {
prefix = ""
}
args := []interface{}{prefix}
args = append(args, a...)
return fmt.Printf("%s"+format, args...)
} | [
"func",
"(",
"al",
"*",
"archiveLogger",
")",
"Fprintf",
"(",
"w",
"io",
".",
"Writer",
",",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"prefix",
":=",
"\"",
"\\n",
"\"",
"\n",... | // Print acts like fmt.fprintf, but may prepend a prefix to format, depending on the value of al.quiet. | [
"Print",
"acts",
"like",
"fmt",
".",
"fprintf",
"but",
"may",
"prepend",
"a",
"prefix",
"to",
"format",
"depending",
"on",
"the",
"value",
"of",
"al",
".",
"quiet",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/isolate/archive.go#L132-L140 |
7,232 | luci/luci-go | client/cmd/isolate/archive.go | archive | func archive(ctx context.Context, client *isolatedclient.Client, opts *isolate.ArchiveOptions, dumpJSON string, concurrentChecks, concurrentUploads int, al archiveLogger) error {
// Parse the incoming isolate file.
deps, rootDir, isol, err := isolate.ProcessIsolate(opts)
if err != nil {
return fmt.Errorf("isolate %s: failed to process: %v", opts.Isolate, err)
}
log.Printf("Isolate %s referenced %d deps", opts.Isolate, len(deps))
// Set up a checker and uploader.
checker := archiver.NewChecker(ctx, client, concurrentChecks)
uploader := archiver.NewUploader(ctx, client, concurrentUploads)
archiver := archiver.NewTarringArchiver(checker, uploader)
isolSummary, err := archiver.Archive(deps, rootDir, isol, opts.Blacklist, opts.Isolated)
if err != nil {
return fmt.Errorf("isolate %s: %v", opts.Isolate, err)
}
// Make sure that all pending items have been checked.
if err := checker.Close(); err != nil {
return err
}
// Make sure that all the uploads have completed successfully.
if err := uploader.Close(); err != nil {
return err
}
printSummary(al, isolSummary)
if err := dumpSummaryJSON(dumpJSON, isolSummary); err != nil {
return err
}
al.LogSummary(ctx, int64(checker.Hit.Count()), int64(checker.Miss.Count()), units.Size(checker.Hit.Bytes()), units.Size(checker.Miss.Bytes()), []string{string(isolSummary.Digest)})
return nil
} | go | func archive(ctx context.Context, client *isolatedclient.Client, opts *isolate.ArchiveOptions, dumpJSON string, concurrentChecks, concurrentUploads int, al archiveLogger) error {
// Parse the incoming isolate file.
deps, rootDir, isol, err := isolate.ProcessIsolate(opts)
if err != nil {
return fmt.Errorf("isolate %s: failed to process: %v", opts.Isolate, err)
}
log.Printf("Isolate %s referenced %d deps", opts.Isolate, len(deps))
// Set up a checker and uploader.
checker := archiver.NewChecker(ctx, client, concurrentChecks)
uploader := archiver.NewUploader(ctx, client, concurrentUploads)
archiver := archiver.NewTarringArchiver(checker, uploader)
isolSummary, err := archiver.Archive(deps, rootDir, isol, opts.Blacklist, opts.Isolated)
if err != nil {
return fmt.Errorf("isolate %s: %v", opts.Isolate, err)
}
// Make sure that all pending items have been checked.
if err := checker.Close(); err != nil {
return err
}
// Make sure that all the uploads have completed successfully.
if err := uploader.Close(); err != nil {
return err
}
printSummary(al, isolSummary)
if err := dumpSummaryJSON(dumpJSON, isolSummary); err != nil {
return err
}
al.LogSummary(ctx, int64(checker.Hit.Count()), int64(checker.Miss.Count()), units.Size(checker.Hit.Bytes()), units.Size(checker.Miss.Bytes()), []string{string(isolSummary.Digest)})
return nil
} | [
"func",
"archive",
"(",
"ctx",
"context",
".",
"Context",
",",
"client",
"*",
"isolatedclient",
".",
"Client",
",",
"opts",
"*",
"isolate",
".",
"ArchiveOptions",
",",
"dumpJSON",
"string",
",",
"concurrentChecks",
",",
"concurrentUploads",
"int",
",",
"al",
... | // archive performs the archive operation for an isolate specified by opts.
// dumpJSON is the path to write a JSON summary of the uploaded isolate, in the same format as batch_archive. | [
"archive",
"performs",
"the",
"archive",
"operation",
"for",
"an",
"isolate",
"specified",
"by",
"opts",
".",
"dumpJSON",
"is",
"the",
"path",
"to",
"write",
"a",
"JSON",
"summary",
"of",
"the",
"uploaded",
"isolate",
"in",
"the",
"same",
"format",
"as",
"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/isolate/archive.go#L144-L179 |
7,233 | luci/luci-go | common/tsmon/store/fake.go | Get | func (s *Fake) Get(context.Context, types.Metric, time.Time, []interface{}) interface{} {
return nil
} | go | func (s *Fake) Get(context.Context, types.Metric, time.Time, []interface{}) interface{} {
return nil
} | [
"func",
"(",
"s",
"*",
"Fake",
")",
"Get",
"(",
"context",
".",
"Context",
",",
"types",
".",
"Metric",
",",
"time",
".",
"Time",
",",
"[",
"]",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
"{",
"return",
"nil",
"\n",
"}"
] | // Get does nothing. | [
"Get",
"does",
"nothing",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/store/fake.go#L37-L39 |
7,234 | luci/luci-go | common/data/text/units/units.go | Round | func Round(value time.Duration, resolution time.Duration) time.Duration {
if value < 0 {
value -= resolution / 2
} else {
value += resolution / 2
}
return value / resolution * resolution
} | go | func Round(value time.Duration, resolution time.Duration) time.Duration {
if value < 0 {
value -= resolution / 2
} else {
value += resolution / 2
}
return value / resolution * resolution
} | [
"func",
"Round",
"(",
"value",
"time",
".",
"Duration",
",",
"resolution",
"time",
".",
"Duration",
")",
"time",
".",
"Duration",
"{",
"if",
"value",
"<",
"0",
"{",
"value",
"-=",
"resolution",
"/",
"2",
"\n",
"}",
"else",
"{",
"value",
"+=",
"resolu... | // Round rounds a time.Duration at round. | [
"Round",
"rounds",
"a",
"time",
".",
"Duration",
"at",
"round",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/units/units.go#L51-L58 |
7,235 | luci/luci-go | buildbucket/cli/printrun.go | RegisterIDFlag | func (r *printRun) RegisterIDFlag() {
r.Flags.BoolVar(&r.id, "id", false, doc(`
Print only build ids.
Intended for piping the output into another bb subcommand:
bb ls -cl myCL -id | bb cancel
`))
} | go | func (r *printRun) RegisterIDFlag() {
r.Flags.BoolVar(&r.id, "id", false, doc(`
Print only build ids.
Intended for piping the output into another bb subcommand:
bb ls -cl myCL -id | bb cancel
`))
} | [
"func",
"(",
"r",
"*",
"printRun",
")",
"RegisterIDFlag",
"(",
")",
"{",
"r",
".",
"Flags",
".",
"BoolVar",
"(",
"&",
"r",
".",
"id",
",",
"\"",
"\"",
",",
"false",
",",
"doc",
"(",
"`\n\t\tPrint only build ids.\n\n\t\tIntended for piping the output into anoth... | // RegisterIDFlag registers -id flag. | [
"RegisterIDFlag",
"registers",
"-",
"id",
"flag",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/printrun.go#L60-L67 |
7,236 | luci/luci-go | buildbucket/cli/printrun.go | RegisterFieldFlags | func (r *printRun) RegisterFieldFlags() {
r.Flags.BoolVar(&r.all, "A", false, doc(`
Print builds in their entirety.
With -json, prints all build fields.
Without -json, implies -steps and -p.
`))
r.Flags.BoolVar(&r.steps, "steps", false, "Print steps")
r.Flags.BoolVar(&r.properties, "p", false, "Print input/output properties")
} | go | func (r *printRun) RegisterFieldFlags() {
r.Flags.BoolVar(&r.all, "A", false, doc(`
Print builds in their entirety.
With -json, prints all build fields.
Without -json, implies -steps and -p.
`))
r.Flags.BoolVar(&r.steps, "steps", false, "Print steps")
r.Flags.BoolVar(&r.properties, "p", false, "Print input/output properties")
} | [
"func",
"(",
"r",
"*",
"printRun",
")",
"RegisterFieldFlags",
"(",
")",
"{",
"r",
".",
"Flags",
".",
"BoolVar",
"(",
"&",
"r",
".",
"all",
",",
"\"",
"\"",
",",
"false",
",",
"doc",
"(",
"`\n\t\tPrint builds in their entirety.\n\t\tWith -json, prints all build... | // RegisterFieldFlags registers -A, -steps and -p flags. | [
"RegisterFieldFlags",
"registers",
"-",
"A",
"-",
"steps",
"and",
"-",
"p",
"flags",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/printrun.go#L70-L78 |
7,237 | luci/luci-go | buildbucket/cli/printrun.go | FieldMask | func (r *printRun) FieldMask() (*field_mask.FieldMask, error) {
if r.id {
if r.all || r.properties || r.steps {
return nil, fmt.Errorf("-id is mutually exclusive with -A, -p and -steps")
}
return proto.Clone(idFieldMask).(*field_mask.FieldMask), nil
}
if r.all {
if r.properties || r.steps {
return nil, fmt.Errorf("-A is mutually exclusive with -p and -steps")
}
return proto.Clone(completeBuildFieldMask).(*field_mask.FieldMask), nil
}
ret := &field_mask.FieldMask{
Paths: []string{
"builder",
"create_time",
"created_by",
"end_time",
"id",
"input.experimental",
"input.gerrit_changes",
"input.gitiles_commit",
"number",
"start_time",
"status",
"status_details",
"summary_markdown",
"tags",
"update_time",
},
}
if r.properties {
ret.Paths = append(ret.Paths, "input.properties", "output.properties")
}
if r.steps {
ret.Paths = append(ret.Paths, "steps")
}
return ret, nil
} | go | func (r *printRun) FieldMask() (*field_mask.FieldMask, error) {
if r.id {
if r.all || r.properties || r.steps {
return nil, fmt.Errorf("-id is mutually exclusive with -A, -p and -steps")
}
return proto.Clone(idFieldMask).(*field_mask.FieldMask), nil
}
if r.all {
if r.properties || r.steps {
return nil, fmt.Errorf("-A is mutually exclusive with -p and -steps")
}
return proto.Clone(completeBuildFieldMask).(*field_mask.FieldMask), nil
}
ret := &field_mask.FieldMask{
Paths: []string{
"builder",
"create_time",
"created_by",
"end_time",
"id",
"input.experimental",
"input.gerrit_changes",
"input.gitiles_commit",
"number",
"start_time",
"status",
"status_details",
"summary_markdown",
"tags",
"update_time",
},
}
if r.properties {
ret.Paths = append(ret.Paths, "input.properties", "output.properties")
}
if r.steps {
ret.Paths = append(ret.Paths, "steps")
}
return ret, nil
} | [
"func",
"(",
"r",
"*",
"printRun",
")",
"FieldMask",
"(",
")",
"(",
"*",
"field_mask",
".",
"FieldMask",
",",
"error",
")",
"{",
"if",
"r",
".",
"id",
"{",
"if",
"r",
".",
"all",
"||",
"r",
".",
"properties",
"||",
"r",
".",
"steps",
"{",
"retu... | // FieldMask returns the field mask to use in buildbucket requests. | [
"FieldMask",
"returns",
"the",
"field",
"mask",
"to",
"use",
"in",
"buildbucket",
"requests",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/printrun.go#L81-L125 |
7,238 | luci/luci-go | buildbucket/cli/printrun.go | PrintAndDone | func (r *printRun) PrintAndDone(ctx context.Context, args []string, fn func(context.Context, string) (*pb.Build, error)) int {
stdout, stderr := newStdioPrinters(r.noColor)
return r.printAndDone(ctx, stdout, stderr, args, fn)
} | go | func (r *printRun) PrintAndDone(ctx context.Context, args []string, fn func(context.Context, string) (*pb.Build, error)) int {
stdout, stderr := newStdioPrinters(r.noColor)
return r.printAndDone(ctx, stdout, stderr, args, fn)
} | [
"func",
"(",
"r",
"*",
"printRun",
")",
"PrintAndDone",
"(",
"ctx",
"context",
".",
"Context",
",",
"args",
"[",
"]",
"string",
",",
"fn",
"func",
"(",
"context",
".",
"Context",
",",
"string",
")",
"(",
"*",
"pb",
".",
"Build",
",",
"error",
")",
... | // PrintAndDone calls fn for each argument, prints builds and returns exit code.
// fn is called concurrently, but builds are printed in the same order
// as args. | [
"PrintAndDone",
"calls",
"fn",
"for",
"each",
"argument",
"prints",
"builds",
"and",
"returns",
"exit",
"code",
".",
"fn",
"is",
"called",
"concurrently",
"but",
"builds",
"are",
"printed",
"in",
"the",
"same",
"order",
"as",
"args",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/printrun.go#L152-L155 |
7,239 | luci/luci-go | buildbucket/cli/printrun.go | argChan | func argChan(args []string) chan string {
ret := make(chan string)
go func() {
defer close(ret)
if len(args) > 0 {
for _, a := range args {
ret <- strings.TrimSpace(a)
}
return
}
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('\n')
line = strings.TrimSpace(line)
switch {
case err == io.EOF:
return
case err != nil:
panic(err)
case len(line) == 0:
continue
default:
ret <- line
}
}
}()
return ret
} | go | func argChan(args []string) chan string {
ret := make(chan string)
go func() {
defer close(ret)
if len(args) > 0 {
for _, a := range args {
ret <- strings.TrimSpace(a)
}
return
}
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('\n')
line = strings.TrimSpace(line)
switch {
case err == io.EOF:
return
case err != nil:
panic(err)
case len(line) == 0:
continue
default:
ret <- line
}
}
}()
return ret
} | [
"func",
"argChan",
"(",
"args",
"[",
"]",
"string",
")",
"chan",
"string",
"{",
"ret",
":=",
"make",
"(",
"chan",
"string",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"close",
"(",
"ret",
")",
"\n\n",
"if",
"len",
"(",
"args",
")",
">",
"... | // argChan returns a channel of args.
//
// If args is empty, reads from stdin. Trims whitespace and skips blank lines.
// Panics if reading from stdin fails. | [
"argChan",
"returns",
"a",
"channel",
"of",
"args",
".",
"If",
"args",
"is",
"empty",
"reads",
"from",
"stdin",
".",
"Trims",
"whitespace",
"and",
"skips",
"blank",
"lines",
".",
"Panics",
"if",
"reading",
"from",
"stdin",
"fails",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/printrun.go#L225-L254 |
7,240 | luci/luci-go | common/proto/google/descutil/util.go | FindService | func FindService(s *pb.FileDescriptorSet, fullName string) (file *pb.FileDescriptorProto, serviceIndex int) {
pkg, name := splitFullName(fullName)
for _, f := range s.GetFile() {
if f.GetPackage() == pkg {
if i := FindServiceForFile(f, name); i != -1 {
return f, i
}
}
}
return nil, -1
} | go | func FindService(s *pb.FileDescriptorSet, fullName string) (file *pb.FileDescriptorProto, serviceIndex int) {
pkg, name := splitFullName(fullName)
for _, f := range s.GetFile() {
if f.GetPackage() == pkg {
if i := FindServiceForFile(f, name); i != -1 {
return f, i
}
}
}
return nil, -1
} | [
"func",
"FindService",
"(",
"s",
"*",
"pb",
".",
"FileDescriptorSet",
",",
"fullName",
"string",
")",
"(",
"file",
"*",
"pb",
".",
"FileDescriptorProto",
",",
"serviceIndex",
"int",
")",
"{",
"pkg",
",",
"name",
":=",
"splitFullName",
"(",
"fullName",
")",... | // FindService searches for a service by full name. | [
"FindService",
"searches",
"for",
"a",
"service",
"by",
"full",
"name",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/descutil/util.go#L115-L125 |
7,241 | luci/luci-go | common/proto/google/descutil/util.go | FindMessageForFile | func FindMessageForFile(f *pb.FileDescriptorProto, name string) int {
for i, x := range f.GetMessageType() {
if x.GetName() == name {
return i
}
}
return -1
} | go | func FindMessageForFile(f *pb.FileDescriptorProto, name string) int {
for i, x := range f.GetMessageType() {
if x.GetName() == name {
return i
}
}
return -1
} | [
"func",
"FindMessageForFile",
"(",
"f",
"*",
"pb",
".",
"FileDescriptorProto",
",",
"name",
"string",
")",
"int",
"{",
"for",
"i",
",",
"x",
":=",
"range",
"f",
".",
"GetMessageType",
"(",
")",
"{",
"if",
"x",
".",
"GetName",
"(",
")",
"==",
"name",
... | // FindMessageForFile searches for a DescriptorProto by name. | [
"FindMessageForFile",
"searches",
"for",
"a",
"DescriptorProto",
"by",
"name",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/descutil/util.go#L141-L148 |
7,242 | luci/luci-go | common/proto/google/descutil/util.go | FindEnumForFile | func FindEnumForFile(f *pb.FileDescriptorProto, name string) int {
for i, x := range f.GetEnumType() {
if x.GetName() == name {
return i
}
}
return -1
} | go | func FindEnumForFile(f *pb.FileDescriptorProto, name string) int {
for i, x := range f.GetEnumType() {
if x.GetName() == name {
return i
}
}
return -1
} | [
"func",
"FindEnumForFile",
"(",
"f",
"*",
"pb",
".",
"FileDescriptorProto",
",",
"name",
"string",
")",
"int",
"{",
"for",
"i",
",",
"x",
":=",
"range",
"f",
".",
"GetEnumType",
"(",
")",
"{",
"if",
"x",
".",
"GetName",
"(",
")",
"==",
"name",
"{",... | // FindEnumForFile searches for an EnumDescriptorProto by name. | [
"FindEnumForFile",
"searches",
"for",
"an",
"EnumDescriptorProto",
"by",
"name",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/descutil/util.go#L151-L158 |
7,243 | luci/luci-go | common/proto/google/descutil/util.go | FindMessage | func FindMessage(d *pb.DescriptorProto, name string) int {
for i, x := range d.GetNestedType() {
if x.GetName() == name {
return i
}
}
return -1
} | go | func FindMessage(d *pb.DescriptorProto, name string) int {
for i, x := range d.GetNestedType() {
if x.GetName() == name {
return i
}
}
return -1
} | [
"func",
"FindMessage",
"(",
"d",
"*",
"pb",
".",
"DescriptorProto",
",",
"name",
"string",
")",
"int",
"{",
"for",
"i",
",",
"x",
":=",
"range",
"d",
".",
"GetNestedType",
"(",
")",
"{",
"if",
"x",
".",
"GetName",
"(",
")",
"==",
"name",
"{",
"re... | // FindMessage searches for a nested DescriptorProto by name. | [
"FindMessage",
"searches",
"for",
"a",
"nested",
"DescriptorProto",
"by",
"name",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/descutil/util.go#L187-L194 |
7,244 | luci/luci-go | common/proto/google/descutil/util.go | FindEnum | func FindEnum(d *pb.DescriptorProto, name string) int {
for i, x := range d.GetEnumType() {
if x.GetName() == name {
return i
}
}
return -1
} | go | func FindEnum(d *pb.DescriptorProto, name string) int {
for i, x := range d.GetEnumType() {
if x.GetName() == name {
return i
}
}
return -1
} | [
"func",
"FindEnum",
"(",
"d",
"*",
"pb",
".",
"DescriptorProto",
",",
"name",
"string",
")",
"int",
"{",
"for",
"i",
",",
"x",
":=",
"range",
"d",
".",
"GetEnumType",
"(",
")",
"{",
"if",
"x",
".",
"GetName",
"(",
")",
"==",
"name",
"{",
"return"... | // FindEnum searches for a nested EnumDescriptorProto by name. | [
"FindEnum",
"searches",
"for",
"a",
"nested",
"EnumDescriptorProto",
"by",
"name",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/descutil/util.go#L197-L204 |
7,245 | luci/luci-go | common/proto/google/descutil/util.go | FindOneOf | func FindOneOf(d *pb.DescriptorProto, name string) int {
for i, x := range d.GetOneofDecl() {
if x.GetName() == name {
return i
}
}
return -1
} | go | func FindOneOf(d *pb.DescriptorProto, name string) int {
for i, x := range d.GetOneofDecl() {
if x.GetName() == name {
return i
}
}
return -1
} | [
"func",
"FindOneOf",
"(",
"d",
"*",
"pb",
".",
"DescriptorProto",
",",
"name",
"string",
")",
"int",
"{",
"for",
"i",
",",
"x",
":=",
"range",
"d",
".",
"GetOneofDecl",
"(",
")",
"{",
"if",
"x",
".",
"GetName",
"(",
")",
"==",
"name",
"{",
"retur... | // FindOneOf searches for a nested OneofDescriptorProto by name. | [
"FindOneOf",
"searches",
"for",
"a",
"nested",
"OneofDescriptorProto",
"by",
"name",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/descutil/util.go#L207-L214 |
7,246 | luci/luci-go | common/proto/google/descutil/util.go | FindValueByNumber | func FindValueByNumber(e *pb.EnumDescriptorProto, number int32) int {
for i, x := range e.GetValue() {
if x.GetNumber() == number {
return i
}
}
return -1
} | go | func FindValueByNumber(e *pb.EnumDescriptorProto, number int32) int {
for i, x := range e.GetValue() {
if x.GetNumber() == number {
return i
}
}
return -1
} | [
"func",
"FindValueByNumber",
"(",
"e",
"*",
"pb",
".",
"EnumDescriptorProto",
",",
"number",
"int32",
")",
"int",
"{",
"for",
"i",
",",
"x",
":=",
"range",
"e",
".",
"GetValue",
"(",
")",
"{",
"if",
"x",
".",
"GetNumber",
"(",
")",
"==",
"number",
... | // FindValueByNumber searches for an EnumValueDescriptorProto by number. | [
"FindValueByNumber",
"searches",
"for",
"an",
"EnumValueDescriptorProto",
"by",
"number",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/descutil/util.go#L243-L250 |
7,247 | luci/luci-go | milo/common/utils.go | MergeStrings | func MergeStrings(sss ...[]string) []string {
result := []string{}
seen := map[string]bool{}
for _, ss := range sss {
for _, s := range ss {
if seen[s] {
continue
}
seen[s] = true
result = append(result, s)
}
}
sort.Strings(result)
return result
} | go | func MergeStrings(sss ...[]string) []string {
result := []string{}
seen := map[string]bool{}
for _, ss := range sss {
for _, s := range ss {
if seen[s] {
continue
}
seen[s] = true
result = append(result, s)
}
}
sort.Strings(result)
return result
} | [
"func",
"MergeStrings",
"(",
"sss",
"...",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"result",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"seen",
":=",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
"\n",
"for",
"_",
",",
"ss",
":=",
"rang... | // MergeStrings merges multiple string slices together into a single slice,
// removing duplicates. | [
"MergeStrings",
"merges",
"multiple",
"string",
"slices",
"together",
"into",
"a",
"single",
"slice",
"removing",
"duplicates",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/utils.go#L31-L45 |
7,248 | luci/luci-go | scheduler/appengine/engine/policy/logarithmic_batching.go | LogarithmicBatchingPolicy | func LogarithmicBatchingPolicy(maxConcurrentInvs, maxBatchSize int, logBase float64) (Func, error) {
// We use 1.0001 to ensure that operation below returns a value small enough
// to fit into int and to avoid numerical stability issues resulting from
// very small values being approximated as 0 and resulting in
// division-by-zero errors.
if logBase < 1.0001 {
return nil, errors.Reason("log_base should be more or equal than 1.0001").Err()
}
log := math.Log(logBase)
return basePolicy(maxConcurrentInvs, maxBatchSize, func(triggers []*internal.Trigger) int {
return int(math.Max(math.Log(float64(len(triggers)))/log, 1.0))
})
} | go | func LogarithmicBatchingPolicy(maxConcurrentInvs, maxBatchSize int, logBase float64) (Func, error) {
// We use 1.0001 to ensure that operation below returns a value small enough
// to fit into int and to avoid numerical stability issues resulting from
// very small values being approximated as 0 and resulting in
// division-by-zero errors.
if logBase < 1.0001 {
return nil, errors.Reason("log_base should be more or equal than 1.0001").Err()
}
log := math.Log(logBase)
return basePolicy(maxConcurrentInvs, maxBatchSize, func(triggers []*internal.Trigger) int {
return int(math.Max(math.Log(float64(len(triggers)))/log, 1.0))
})
} | [
"func",
"LogarithmicBatchingPolicy",
"(",
"maxConcurrentInvs",
",",
"maxBatchSize",
"int",
",",
"logBase",
"float64",
")",
"(",
"Func",
",",
"error",
")",
"{",
"// We use 1.0001 to ensure that operation below returns a value small enough",
"// to fit into int and to avoid numeric... | // LogarithmicBatchingPolicy instantiates new LOGARITHMIC_BATCHING policy
// function.
//
// It takes all pending triggers and collapses log_k N of them into one new
// invocation, deriving its properties from the most recent trigger alone. | [
"LogarithmicBatchingPolicy",
"instantiates",
"new",
"LOGARITHMIC_BATCHING",
"policy",
"function",
".",
"It",
"takes",
"all",
"pending",
"triggers",
"and",
"collapses",
"log_k",
"N",
"of",
"them",
"into",
"one",
"new",
"invocation",
"deriving",
"its",
"properties",
"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/logarithmic_batching.go#L29-L42 |
7,249 | luci/luci-go | vpython/wheel/wheel.go | ParseName | func ParseName(v string) (wn Name, err error) {
base := strings.TrimSuffix(v, ".whl")
if len(base) == len(v) {
err = errors.New("missing .whl suffix")
return
}
skip := 0
switch parts := strings.Split(base, "-"); len(parts) {
case 6:
// Extra part: build tag.
wn.BuildTag = parts[2]
skip = 1
fallthrough
case 5:
wn.Distribution = parts[0]
wn.Version = parts[1]
wn.PythonTag = parts[2+skip]
wn.ABITag = parts[3+skip]
wn.PlatformTag = parts[4+skip]
default:
err = errors.Reason("unknown number of segments (%d)", len(parts)).Err()
return
}
return
} | go | func ParseName(v string) (wn Name, err error) {
base := strings.TrimSuffix(v, ".whl")
if len(base) == len(v) {
err = errors.New("missing .whl suffix")
return
}
skip := 0
switch parts := strings.Split(base, "-"); len(parts) {
case 6:
// Extra part: build tag.
wn.BuildTag = parts[2]
skip = 1
fallthrough
case 5:
wn.Distribution = parts[0]
wn.Version = parts[1]
wn.PythonTag = parts[2+skip]
wn.ABITag = parts[3+skip]
wn.PlatformTag = parts[4+skip]
default:
err = errors.Reason("unknown number of segments (%d)", len(parts)).Err()
return
}
return
} | [
"func",
"ParseName",
"(",
"v",
"string",
")",
"(",
"wn",
"Name",
",",
"err",
"error",
")",
"{",
"base",
":=",
"strings",
".",
"TrimSuffix",
"(",
"v",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"base",
")",
"==",
"len",
"(",
"v",
")",
"{",
... | // ParseName parses a wheel Name from its filename. | [
"ParseName",
"parses",
"a",
"wheel",
"Name",
"from",
"its",
"filename",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/wheel/wheel.go#L58-L85 |
7,250 | luci/luci-go | vpython/wheel/wheel.go | ScanDir | func ScanDir(dir string) ([]Name, error) {
globPattern := filepath.Join(dir, "*.whl")
matches, err := filepath.Glob(globPattern)
if err != nil {
return nil, errors.Annotate(err, "failed to list wheel directory: %s", dir).
InternalReason("pattern(%s)", globPattern).Err()
}
names := make([]Name, 0, len(matches))
for _, match := range matches {
switch st, err := os.Stat(match); {
case err != nil:
return nil, errors.Annotate(err, "failed to stat wheel: %s", match).Err()
case st.IsDir():
// Ignore directories.
continue
default:
// A ".whl" file.
name := filepath.Base(match)
wheelName, err := ParseName(name)
if err != nil {
return nil, errors.Annotate(err, "failed to parse wheel from: %s", name).
InternalReason("dir(%s)", dir).Err()
}
names = append(names, wheelName)
}
}
return names, nil
} | go | func ScanDir(dir string) ([]Name, error) {
globPattern := filepath.Join(dir, "*.whl")
matches, err := filepath.Glob(globPattern)
if err != nil {
return nil, errors.Annotate(err, "failed to list wheel directory: %s", dir).
InternalReason("pattern(%s)", globPattern).Err()
}
names := make([]Name, 0, len(matches))
for _, match := range matches {
switch st, err := os.Stat(match); {
case err != nil:
return nil, errors.Annotate(err, "failed to stat wheel: %s", match).Err()
case st.IsDir():
// Ignore directories.
continue
default:
// A ".whl" file.
name := filepath.Base(match)
wheelName, err := ParseName(name)
if err != nil {
return nil, errors.Annotate(err, "failed to parse wheel from: %s", name).
InternalReason("dir(%s)", dir).Err()
}
names = append(names, wheelName)
}
}
return names, nil
} | [
"func",
"ScanDir",
"(",
"dir",
"string",
")",
"(",
"[",
"]",
"Name",
",",
"error",
")",
"{",
"globPattern",
":=",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
"\n",
"matches",
",",
"err",
":=",
"filepath",
".",
"Glob",
"(",
"globPatte... | // ScanDir identifies all wheel files in the immediate directory dir and
// returns their parsed wheel names. | [
"ScanDir",
"identifies",
"all",
"wheel",
"files",
"in",
"the",
"immediate",
"directory",
"dir",
"and",
"returns",
"their",
"parsed",
"wheel",
"names",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/wheel/wheel.go#L89-L119 |
7,251 | luci/luci-go | milo/frontend/view_config.go | ConfigsHandler | func ConfigsHandler(c *router.Context) {
consoles, err := common.GetAllConsoles(c.Context, "")
if err != nil {
ErrorHandler(c, errors.Annotate(err, "Error while getting projects").Err())
return
}
sc, err := common.GetCurrentServiceConfig(c.Context)
if err != nil && err != datastore.ErrNoSuchEntity {
ErrorHandler(c, errors.Annotate(err, "Error while getting service config").Err())
return
}
templates.MustRender(c.Context, c.Writer, "pages/configs.html", templates.Args{
"Consoles": consoles,
"ServiceConfig": sc,
})
} | go | func ConfigsHandler(c *router.Context) {
consoles, err := common.GetAllConsoles(c.Context, "")
if err != nil {
ErrorHandler(c, errors.Annotate(err, "Error while getting projects").Err())
return
}
sc, err := common.GetCurrentServiceConfig(c.Context)
if err != nil && err != datastore.ErrNoSuchEntity {
ErrorHandler(c, errors.Annotate(err, "Error while getting service config").Err())
return
}
templates.MustRender(c.Context, c.Writer, "pages/configs.html", templates.Args{
"Consoles": consoles,
"ServiceConfig": sc,
})
} | [
"func",
"ConfigsHandler",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"consoles",
",",
"err",
":=",
"common",
".",
"GetAllConsoles",
"(",
"c",
".",
"Context",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ErrorHandler",
"(",
"c",... | // ConfigsHandler renders the page showing the currently loaded set of luci-configs. | [
"ConfigsHandler",
"renders",
"the",
"page",
"showing",
"the",
"currently",
"loaded",
"set",
"of",
"luci",
"-",
"configs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_config.go#L31-L47 |
7,252 | luci/luci-go | milo/frontend/view_config.go | UpdateConfigHandler | func UpdateConfigHandler(ctx *router.Context) {
c, h := ctx.Context, ctx.Writer
// Needed to access the PubSub API
c = appengine.WithContext(c, ctx.Request)
projErr := common.UpdateConsoles(c)
if projErr != nil {
if merr, ok := projErr.(errors.MultiError); ok {
for _, ierr := range merr {
logging.WithError(ierr).Errorf(c, "project update handler encountered error")
}
} else {
logging.WithError(projErr).Errorf(c, "project update handler encountered error")
}
}
settings, servErr := common.UpdateServiceConfig(c)
if servErr != nil {
logging.WithError(servErr).Errorf(c, "service update handler encountered error")
} else {
servErr = common.EnsurePubSubSubscribed(c, settings)
if servErr != nil {
logging.WithError(servErr).Errorf(
c, "pubsub subscriber handler encountered error")
}
}
if projErr != nil || servErr != nil {
h.WriteHeader(http.StatusInternalServerError)
return
}
h.WriteHeader(http.StatusOK)
} | go | func UpdateConfigHandler(ctx *router.Context) {
c, h := ctx.Context, ctx.Writer
// Needed to access the PubSub API
c = appengine.WithContext(c, ctx.Request)
projErr := common.UpdateConsoles(c)
if projErr != nil {
if merr, ok := projErr.(errors.MultiError); ok {
for _, ierr := range merr {
logging.WithError(ierr).Errorf(c, "project update handler encountered error")
}
} else {
logging.WithError(projErr).Errorf(c, "project update handler encountered error")
}
}
settings, servErr := common.UpdateServiceConfig(c)
if servErr != nil {
logging.WithError(servErr).Errorf(c, "service update handler encountered error")
} else {
servErr = common.EnsurePubSubSubscribed(c, settings)
if servErr != nil {
logging.WithError(servErr).Errorf(
c, "pubsub subscriber handler encountered error")
}
}
if projErr != nil || servErr != nil {
h.WriteHeader(http.StatusInternalServerError)
return
}
h.WriteHeader(http.StatusOK)
} | [
"func",
"UpdateConfigHandler",
"(",
"ctx",
"*",
"router",
".",
"Context",
")",
"{",
"c",
",",
"h",
":=",
"ctx",
".",
"Context",
",",
"ctx",
".",
"Writer",
"\n",
"// Needed to access the PubSub API",
"c",
"=",
"appengine",
".",
"WithContext",
"(",
"c",
",",... | // UpdateHandler is an HTTP handler that handles configuration update requests. | [
"UpdateHandler",
"is",
"an",
"HTTP",
"handler",
"that",
"handles",
"configuration",
"update",
"requests",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_config.go#L50-L79 |
7,253 | luci/luci-go | scheduler/appengine/task/task.go | Final | func (s Status) Final() bool {
switch s {
case StatusSucceeded, StatusFailed, StatusOverrun, StatusAborted:
return true
default:
return false
}
} | go | func (s Status) Final() bool {
switch s {
case StatusSucceeded, StatusFailed, StatusOverrun, StatusAborted:
return true
default:
return false
}
} | [
"func",
"(",
"s",
"Status",
")",
"Final",
"(",
")",
"bool",
"{",
"switch",
"s",
"{",
"case",
"StatusSucceeded",
",",
"StatusFailed",
",",
"StatusOverrun",
",",
"StatusAborted",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\... | // Final returns true if Status represents some final status. | [
"Final",
"returns",
"true",
"if",
"Status",
"represents",
"some",
"final",
"status",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/task.go#L73-L80 |
7,254 | luci/luci-go | scheduler/appengine/task/task.go | TriggerIDs | func (r *Request) TriggerIDs() []string {
ids := make([]string, len(r.IncomingTriggers))
for i, t := range r.IncomingTriggers {
ids[i] = t.Id
}
return ids
} | go | func (r *Request) TriggerIDs() []string {
ids := make([]string, len(r.IncomingTriggers))
for i, t := range r.IncomingTriggers {
ids[i] = t.Id
}
return ids
} | [
"func",
"(",
"r",
"*",
"Request",
")",
"TriggerIDs",
"(",
")",
"[",
"]",
"string",
"{",
"ids",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"r",
".",
"IncomingTriggers",
")",
")",
"\n",
"for",
"i",
",",
"t",
":=",
"range",
"r",
".",
... | // TriggerIDs extracts list of IDs from IncomingTriggers.
//
// This is useful in tests for asserts. | [
"TriggerIDs",
"extracts",
"list",
"of",
"IDs",
"from",
"IncomingTriggers",
".",
"This",
"is",
"useful",
"in",
"tests",
"for",
"asserts",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/task.go#L340-L346 |
7,255 | luci/luci-go | scheduler/appengine/task/task.go | StringProperty | func (r *Request) StringProperty(k string) string {
if r.Properties == nil {
return ""
}
prop := r.Properties.Fields[k]
if prop == nil {
return ""
}
return prop.GetStringValue()
} | go | func (r *Request) StringProperty(k string) string {
if r.Properties == nil {
return ""
}
prop := r.Properties.Fields[k]
if prop == nil {
return ""
}
return prop.GetStringValue()
} | [
"func",
"(",
"r",
"*",
"Request",
")",
"StringProperty",
"(",
"k",
"string",
")",
"string",
"{",
"if",
"r",
".",
"Properties",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"prop",
":=",
"r",
".",
"Properties",
".",
"Fields",
"[",
"k",
... | // StringProperty returns a value of string property or "" if no such property
// or it has a different type.
//
// This is useful in tests for asserts. | [
"StringProperty",
"returns",
"a",
"value",
"of",
"string",
"property",
"or",
"if",
"no",
"such",
"property",
"or",
"it",
"has",
"a",
"different",
"type",
".",
"This",
"is",
"useful",
"in",
"tests",
"for",
"asserts",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/task.go#L352-L361 |
7,256 | luci/luci-go | logdog/server/service/config/opts.go | WrapBackend | func (o *CacheOptions) WrapBackend(c context.Context, base backend.B) context.Context {
return backend.WithFactory(c, func(c context.Context) backend.B {
// Start with our base Backend.
be := base
// If our datastore cache is available, fetch settings to see if it's
// enabled.
if o.DatastoreCacheAvailable {
switch s, err := gaeconfig.FetchCachedSettings(c); err {
case nil:
// Successfully fetched settings, is our datastore cache enabled?
switch s.DatastoreCacheMode {
case gaeconfig.DSCacheEnabled:
// Datastore cache is enabled, do we have an expiration configured?
exp := time.Duration(s.CacheExpirationSec) * time.Second
if exp > 0 {
// The cache enabled enable. Install it into our backend.
locker := &dsCacheLocker{}
dsCfg := datastore.Config{
RefreshInterval: exp,
LockerFunc: func(context.Context) datastorecache.Locker { return locker },
}
be = dsCfg.Backend(be)
}
}
default:
log.WithError(err).Warningf(c, "Failed to fetch datastore cache settings.")
}
}
// Add a proccache-based config cache.
if o.CacheExpiration > 0 {
be = caching.LRUBackend(be, messageCache.LRU(c), o.CacheExpiration)
}
return be
})
} | go | func (o *CacheOptions) WrapBackend(c context.Context, base backend.B) context.Context {
return backend.WithFactory(c, func(c context.Context) backend.B {
// Start with our base Backend.
be := base
// If our datastore cache is available, fetch settings to see if it's
// enabled.
if o.DatastoreCacheAvailable {
switch s, err := gaeconfig.FetchCachedSettings(c); err {
case nil:
// Successfully fetched settings, is our datastore cache enabled?
switch s.DatastoreCacheMode {
case gaeconfig.DSCacheEnabled:
// Datastore cache is enabled, do we have an expiration configured?
exp := time.Duration(s.CacheExpirationSec) * time.Second
if exp > 0 {
// The cache enabled enable. Install it into our backend.
locker := &dsCacheLocker{}
dsCfg := datastore.Config{
RefreshInterval: exp,
LockerFunc: func(context.Context) datastorecache.Locker { return locker },
}
be = dsCfg.Backend(be)
}
}
default:
log.WithError(err).Warningf(c, "Failed to fetch datastore cache settings.")
}
}
// Add a proccache-based config cache.
if o.CacheExpiration > 0 {
be = caching.LRUBackend(be, messageCache.LRU(c), o.CacheExpiration)
}
return be
})
} | [
"func",
"(",
"o",
"*",
"CacheOptions",
")",
"WrapBackend",
"(",
"c",
"context",
".",
"Context",
",",
"base",
"backend",
".",
"B",
")",
"context",
".",
"Context",
"{",
"return",
"backend",
".",
"WithFactory",
"(",
"c",
",",
"func",
"(",
"c",
"context",
... | // WrapBackend wraps the supplied base backend in caching layers and returns a
// Context with the resulting backend installed. | [
"WrapBackend",
"wraps",
"the",
"supplied",
"base",
"backend",
"in",
"caching",
"layers",
"and",
"returns",
"a",
"Context",
"with",
"the",
"resulting",
"backend",
"installed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/config/opts.go#L47-L85 |
7,257 | luci/luci-go | lucicfg/docgen/generator.go | Render | func (g *Generator) Render(templ string) ([]byte, error) {
if g.loader == nil {
g.loader = &symbols.Loader{Source: g.Starlark}
g.links = map[string]*symbol{}
}
t, err := template.New("main").Funcs(g.funcMap()).Parse(templ)
if err != nil {
return nil, err
}
buf := bytes.Buffer{}
if err := t.Execute(&buf, nil); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func (g *Generator) Render(templ string) ([]byte, error) {
if g.loader == nil {
g.loader = &symbols.Loader{Source: g.Starlark}
g.links = map[string]*symbol{}
}
t, err := template.New("main").Funcs(g.funcMap()).Parse(templ)
if err != nil {
return nil, err
}
buf := bytes.Buffer{}
if err := t.Execute(&buf, nil); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"(",
"g",
"*",
"Generator",
")",
"Render",
"(",
"templ",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"g",
".",
"loader",
"==",
"nil",
"{",
"g",
".",
"loader",
"=",
"&",
"symbols",
".",
"Loader",
"{",
"Source",
":... | // Render renders the given text template in an environment with access to
// parsed structured Starlark comments. | [
"Render",
"renders",
"the",
"given",
"text",
"template",
"in",
"an",
"environment",
"with",
"access",
"to",
"parsed",
"structured",
"Starlark",
"comments",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/generator.go#L49-L65 |
7,258 | luci/luci-go | lucicfg/docgen/generator.go | funcMap | func (g *Generator) funcMap() template.FuncMap {
return template.FuncMap{
"EscapeMD": escapeMD,
"Symbol": g.symbol,
"LinkifySymbols": g.linkifySymbols,
}
} | go | func (g *Generator) funcMap() template.FuncMap {
return template.FuncMap{
"EscapeMD": escapeMD,
"Symbol": g.symbol,
"LinkifySymbols": g.linkifySymbols,
}
} | [
"func",
"(",
"g",
"*",
"Generator",
")",
"funcMap",
"(",
")",
"template",
".",
"FuncMap",
"{",
"return",
"template",
".",
"FuncMap",
"{",
"\"",
"\"",
":",
"escapeMD",
",",
"\"",
"\"",
":",
"g",
".",
"symbol",
",",
"\"",
"\"",
":",
"g",
".",
"link... | // funcMap are functions available to templates. | [
"funcMap",
"are",
"functions",
"available",
"to",
"templates",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/generator.go#L68-L74 |
7,259 | luci/luci-go | lucicfg/docgen/generator.go | linkifySymbols | func (g *Generator) linkifySymbols(text string) string {
return symRefRe.ReplaceAllStringFunc(text, func(match string) string {
if sym := g.links[strings.TrimSuffix(match, "(...)")]; sym != nil {
return fmt.Sprintf("[%s](#%s)", match, sym.Anchor())
} else {
return match
}
})
} | go | func (g *Generator) linkifySymbols(text string) string {
return symRefRe.ReplaceAllStringFunc(text, func(match string) string {
if sym := g.links[strings.TrimSuffix(match, "(...)")]; sym != nil {
return fmt.Sprintf("[%s](#%s)", match, sym.Anchor())
} else {
return match
}
})
} | [
"func",
"(",
"g",
"*",
"Generator",
")",
"linkifySymbols",
"(",
"text",
"string",
")",
"string",
"{",
"return",
"symRefRe",
".",
"ReplaceAllStringFunc",
"(",
"text",
",",
"func",
"(",
"match",
"string",
")",
"string",
"{",
"if",
"sym",
":=",
"g",
".",
... | // linkifySymbols replaces recognized symbol names with markdown links to
// symbols. | [
"linkifySymbols",
"replaces",
"recognized",
"symbol",
"names",
"with",
"markdown",
"links",
"to",
"symbols",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/generator.go#L150-L158 |
7,260 | luci/luci-go | lucicfg/docgen/generator.go | Flavor | func (s *symbol) Flavor() string {
switch s.Symbol.(type) {
case *symbols.Term:
switch s.Symbol.Def().(type) {
case *ast.Function:
return "func"
case *ast.Var:
return "var"
default:
return "unknown"
}
case *symbols.Invocation:
return "inv"
case *symbols.Struct:
return "struct"
default:
return "unknown"
}
} | go | func (s *symbol) Flavor() string {
switch s.Symbol.(type) {
case *symbols.Term:
switch s.Symbol.Def().(type) {
case *ast.Function:
return "func"
case *ast.Var:
return "var"
default:
return "unknown"
}
case *symbols.Invocation:
return "inv"
case *symbols.Struct:
return "struct"
default:
return "unknown"
}
} | [
"func",
"(",
"s",
"*",
"symbol",
")",
"Flavor",
"(",
")",
"string",
"{",
"switch",
"s",
".",
"Symbol",
".",
"(",
"type",
")",
"{",
"case",
"*",
"symbols",
".",
"Term",
":",
"switch",
"s",
".",
"Symbol",
".",
"Def",
"(",
")",
".",
"(",
"type",
... | // Flavor returns one of "func", "var", "struct", "unknown". | [
"Flavor",
"returns",
"one",
"of",
"func",
"var",
"struct",
"unknown",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/generator.go#L176-L194 |
7,261 | luci/luci-go | lucicfg/docgen/generator.go | HasDocTag | func (s *symbol) HasDocTag(tag string) bool {
if s.tags == nil {
s.tags = stringset.Set{}
for _, word := range strings.Fields(s.Doc().RemarkBlock("DocTags").Body) {
s.tags.Add(strings.ToLower(strings.Trim(word, ".,")))
}
}
return s.tags.Has(strings.ToLower(tag))
} | go | func (s *symbol) HasDocTag(tag string) bool {
if s.tags == nil {
s.tags = stringset.Set{}
for _, word := range strings.Fields(s.Doc().RemarkBlock("DocTags").Body) {
s.tags.Add(strings.ToLower(strings.Trim(word, ".,")))
}
}
return s.tags.Has(strings.ToLower(tag))
} | [
"func",
"(",
"s",
"*",
"symbol",
")",
"HasDocTag",
"(",
"tag",
"string",
")",
"bool",
"{",
"if",
"s",
".",
"tags",
"==",
"nil",
"{",
"s",
".",
"tags",
"=",
"stringset",
".",
"Set",
"{",
"}",
"\n",
"for",
"_",
",",
"word",
":=",
"range",
"string... | // HasDocTag returns true if the docstring has a section "DocTags" and the
// given tag is listed there.
//
// Used to mark some symbols as advanced, or experimental. | [
"HasDocTag",
"returns",
"true",
"if",
"the",
"docstring",
"has",
"a",
"section",
"DocTags",
"and",
"the",
"given",
"tag",
"is",
"listed",
"there",
".",
"Used",
"to",
"mark",
"some",
"symbols",
"as",
"advanced",
"or",
"experimental",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/generator.go#L200-L208 |
7,262 | luci/luci-go | lucicfg/docgen/generator.go | Anchor | func (s *symbol) Anchor(sub ...string) string {
return strings.Join(append([]string{s.FullName}, sub...), "-")
} | go | func (s *symbol) Anchor(sub ...string) string {
return strings.Join(append([]string{s.FullName}, sub...), "-")
} | [
"func",
"(",
"s",
"*",
"symbol",
")",
"Anchor",
"(",
"sub",
"...",
"string",
")",
"string",
"{",
"return",
"strings",
".",
"Join",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"s",
".",
"FullName",
"}",
",",
"sub",
"...",
")",
",",
"\"",
"\"",
... | // Anchor returns a markdown anchor name that can be used to link to some part
// of this symbol's documentation from other parts of the doc. | [
"Anchor",
"returns",
"a",
"markdown",
"anchor",
"name",
"that",
"can",
"be",
"used",
"to",
"link",
"to",
"some",
"part",
"of",
"this",
"symbol",
"s",
"documentation",
"from",
"other",
"parts",
"of",
"the",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/generator.go#L246-L248 |
7,263 | luci/luci-go | gce/appengine/rpc/memory/config.go | Delete | func (srv *Config) Delete(c context.Context, req *config.DeleteRequest) (*empty.Empty, error) {
srv.cfg.Delete(req.GetId())
return &empty.Empty{}, nil
} | go | func (srv *Config) Delete(c context.Context, req *config.DeleteRequest) (*empty.Empty, error) {
srv.cfg.Delete(req.GetId())
return &empty.Empty{}, nil
} | [
"func",
"(",
"srv",
"*",
"Config",
")",
"Delete",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"config",
".",
"DeleteRequest",
")",
"(",
"*",
"empty",
".",
"Empty",
",",
"error",
")",
"{",
"srv",
".",
"cfg",
".",
"Delete",
"(",
"req",
".... | // Delete handles a request to delete a config. | [
"Delete",
"handles",
"a",
"request",
"to",
"delete",
"a",
"config",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/memory/config.go#L39-L42 |
7,264 | luci/luci-go | gce/appengine/rpc/memory/config.go | Ensure | func (srv *Config) Ensure(c context.Context, req *config.EnsureRequest) (*config.Config, error) {
srv.cfg.Store(req.GetId(), req.GetConfig())
return req.GetConfig(), nil
} | go | func (srv *Config) Ensure(c context.Context, req *config.EnsureRequest) (*config.Config, error) {
srv.cfg.Store(req.GetId(), req.GetConfig())
return req.GetConfig(), nil
} | [
"func",
"(",
"srv",
"*",
"Config",
")",
"Ensure",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"config",
".",
"EnsureRequest",
")",
"(",
"*",
"config",
".",
"Config",
",",
"error",
")",
"{",
"srv",
".",
"cfg",
".",
"Store",
"(",
"req",
"... | // Ensure handles a request to create or update a config. | [
"Ensure",
"handles",
"a",
"request",
"to",
"create",
"or",
"update",
"a",
"config",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/memory/config.go#L45-L48 |
7,265 | luci/luci-go | tokenserver/appengine/impl/certconfig/crl.go | GetStatusProto | func (crl *CRL) GetStatusProto() *admin.CRLStatus {
return &admin.CRLStatus{
LastUpdateTime: google.NewTimestamp(crl.LastUpdateTime),
LastFetchTime: google.NewTimestamp(crl.LastFetchTime),
LastFetchEtag: crl.LastFetchETag,
RevokedCertsCount: int64(crl.RevokedCertsCount),
}
} | go | func (crl *CRL) GetStatusProto() *admin.CRLStatus {
return &admin.CRLStatus{
LastUpdateTime: google.NewTimestamp(crl.LastUpdateTime),
LastFetchTime: google.NewTimestamp(crl.LastFetchTime),
LastFetchEtag: crl.LastFetchETag,
RevokedCertsCount: int64(crl.RevokedCertsCount),
}
} | [
"func",
"(",
"crl",
"*",
"CRL",
")",
"GetStatusProto",
"(",
")",
"*",
"admin",
".",
"CRLStatus",
"{",
"return",
"&",
"admin",
".",
"CRLStatus",
"{",
"LastUpdateTime",
":",
"google",
".",
"NewTimestamp",
"(",
"crl",
".",
"LastUpdateTime",
")",
",",
"LastF... | // GetStatusProto returns populated CRLStatus proto message. | [
"GetStatusProto",
"returns",
"populated",
"CRLStatus",
"proto",
"message",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/crl.go#L83-L90 |
7,266 | luci/luci-go | tokenserver/appengine/impl/certconfig/crl.go | updateCRLShard | func updateCRLShard(c context.Context, cn string, shard shards.Shard, count, idx int) error {
blob := shard.Serialize()
hash := sha1.Sum(blob)
digest := hex.EncodeToString(hash[:])
// Have it already?
header := CRLShardHeader{ID: shardEntityID(cn, count, idx)}
switch err := ds.Get(c, &header); {
case err != nil && err != ds.ErrNoSuchEntity:
return err
case err == nil && header.SHA1 == digest:
logging.Infof(c, "CRL for %q: shard %d/%d is up-to-date", cn, idx, count)
return nil
}
// Zip before uploading.
zipped, err := utils.ZlibCompress(blob)
if err != nil {
return err
}
logging.Infof(
c, "CRL for %q: shard %d/%d updated (%d bytes zipped, %d%% compression)",
cn, idx, count, len(zipped), 100*len(zipped)/len(blob))
// Upload, updating the header and the body at once.
return ds.RunInTransaction(c, func(c context.Context) error {
header.SHA1 = digest
body := CRLShardBody{
Parent: ds.KeyForObj(c, &header),
SHA1: digest,
ZippedData: zipped,
}
return ds.Put(c, &header, &body)
}, nil)
} | go | func updateCRLShard(c context.Context, cn string, shard shards.Shard, count, idx int) error {
blob := shard.Serialize()
hash := sha1.Sum(blob)
digest := hex.EncodeToString(hash[:])
// Have it already?
header := CRLShardHeader{ID: shardEntityID(cn, count, idx)}
switch err := ds.Get(c, &header); {
case err != nil && err != ds.ErrNoSuchEntity:
return err
case err == nil && header.SHA1 == digest:
logging.Infof(c, "CRL for %q: shard %d/%d is up-to-date", cn, idx, count)
return nil
}
// Zip before uploading.
zipped, err := utils.ZlibCompress(blob)
if err != nil {
return err
}
logging.Infof(
c, "CRL for %q: shard %d/%d updated (%d bytes zipped, %d%% compression)",
cn, idx, count, len(zipped), 100*len(zipped)/len(blob))
// Upload, updating the header and the body at once.
return ds.RunInTransaction(c, func(c context.Context) error {
header.SHA1 = digest
body := CRLShardBody{
Parent: ds.KeyForObj(c, &header),
SHA1: digest,
ZippedData: zipped,
}
return ds.Put(c, &header, &body)
}, nil)
} | [
"func",
"updateCRLShard",
"(",
"c",
"context",
".",
"Context",
",",
"cn",
"string",
",",
"shard",
"shards",
".",
"Shard",
",",
"count",
",",
"idx",
"int",
")",
"error",
"{",
"blob",
":=",
"shard",
".",
"Serialize",
"(",
")",
"\n",
"hash",
":=",
"sha1... | // updateCRLShard updates entities that holds a single shard of a CRL set. | [
"updateCRLShard",
"updates",
"entities",
"that",
"holds",
"a",
"single",
"shard",
"of",
"a",
"CRL",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/crl.go#L151-L185 |
7,267 | luci/luci-go | tokenserver/appengine/impl/certconfig/crl.go | shardEntityID | func shardEntityID(cn string, total, index int) string {
return fmt.Sprintf("%s|%d|%d", cn, total, index)
} | go | func shardEntityID(cn string, total, index int) string {
return fmt.Sprintf("%s|%d|%d", cn, total, index)
} | [
"func",
"shardEntityID",
"(",
"cn",
"string",
",",
"total",
",",
"index",
"int",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cn",
",",
"total",
",",
"index",
")",
"\n",
"}"
] | // shardEntityID returns an ID of CRLShardHeader entity for given shard.
//
// 'cn' is Common Name of the CRL. 'total' is total number of shards expected,
// and 'index' is an index of some particular shard. | [
"shardEntityID",
"returns",
"an",
"ID",
"of",
"CRLShardHeader",
"entity",
"for",
"given",
"shard",
".",
"cn",
"is",
"Common",
"Name",
"of",
"the",
"CRL",
".",
"total",
"is",
"total",
"number",
"of",
"shards",
"expected",
"and",
"index",
"is",
"an",
"index"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/crl.go#L191-L193 |
7,268 | luci/luci-go | tokenserver/appengine/impl/certconfig/crl.go | IsRevokedSN | func (ch *CRLChecker) IsRevokedSN(c context.Context, sn *big.Int) (bool, error) {
snBlob, err := utils.SerializeSN(sn)
if err != nil {
return false, err
}
shard, err := ch.shard(c, shards.ShardIndex(snBlob, ch.shardCount))
if err != nil {
return false, err
}
_, revoked := shard[string(snBlob)]
return revoked, nil
} | go | func (ch *CRLChecker) IsRevokedSN(c context.Context, sn *big.Int) (bool, error) {
snBlob, err := utils.SerializeSN(sn)
if err != nil {
return false, err
}
shard, err := ch.shard(c, shards.ShardIndex(snBlob, ch.shardCount))
if err != nil {
return false, err
}
_, revoked := shard[string(snBlob)]
return revoked, nil
} | [
"func",
"(",
"ch",
"*",
"CRLChecker",
")",
"IsRevokedSN",
"(",
"c",
"context",
".",
"Context",
",",
"sn",
"*",
"big",
".",
"Int",
")",
"(",
"bool",
",",
"error",
")",
"{",
"snBlob",
",",
"err",
":=",
"utils",
".",
"SerializeSN",
"(",
"sn",
")",
"... | // IsRevokedSN returns true if given serial number is in the CRL. | [
"IsRevokedSN",
"returns",
"true",
"if",
"given",
"serial",
"number",
"is",
"in",
"the",
"CRL",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/crl.go#L236-L247 |
7,269 | luci/luci-go | tokenserver/appengine/impl/certconfig/crl.go | shard | func (ch *CRLChecker) shard(c context.Context, idx int) (shards.Shard, error) {
val, err := ch.shards[idx].Get(c, func(prev interface{}) (interface{}, time.Duration, error) {
prevState, _ := prev.(shardCache)
newState, err := ch.refetchShard(c, idx, prevState)
return newState, ch.cacheDuration, err
})
if err != nil {
return nil, err
}
// lazyslot.Get always returns non-nil val on success. It is safe to cast it
// to whatever we returned in the callback (which is always shardCache, see
// refetchShard).
return val.(shardCache).shard, nil
} | go | func (ch *CRLChecker) shard(c context.Context, idx int) (shards.Shard, error) {
val, err := ch.shards[idx].Get(c, func(prev interface{}) (interface{}, time.Duration, error) {
prevState, _ := prev.(shardCache)
newState, err := ch.refetchShard(c, idx, prevState)
return newState, ch.cacheDuration, err
})
if err != nil {
return nil, err
}
// lazyslot.Get always returns non-nil val on success. It is safe to cast it
// to whatever we returned in the callback (which is always shardCache, see
// refetchShard).
return val.(shardCache).shard, nil
} | [
"func",
"(",
"ch",
"*",
"CRLChecker",
")",
"shard",
"(",
"c",
"context",
".",
"Context",
",",
"idx",
"int",
")",
"(",
"shards",
".",
"Shard",
",",
"error",
")",
"{",
"val",
",",
"err",
":=",
"ch",
".",
"shards",
"[",
"idx",
"]",
".",
"Get",
"("... | // shard returns a shard given its index. | [
"shard",
"returns",
"a",
"shard",
"given",
"its",
"index",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/crl.go#L250-L263 |
7,270 | luci/luci-go | tokenserver/appengine/impl/certconfig/crl.go | refetchShard | func (ch *CRLChecker) refetchShard(c context.Context, idx int, prevState shardCache) (newState shardCache, err error) {
// Have something locally already? Quickly fetch CRLShardHeader to check
// whether we need to pull a heavy CRLShardBody.
hdr := CRLShardHeader{ID: shardEntityID(ch.cn, ch.shardCount, idx)}
if prevState.sha1 != "" {
switch err = ds.Get(c, &hdr); {
case err == ds.ErrNoSuchEntity:
err = fmt.Errorf("shard header %q is missing", hdr.ID)
return
case err != nil:
err = transient.Tag.Apply(err)
return
}
// The currently cached copy is still good enough?
if hdr.SHA1 == prevState.sha1 {
newState = prevState
return
}
}
// Nothing is cached, or the datastore copy is fresher than what we have in
// the cache. Need to fetch a new copy, unzip and deserialize it. This entity
// is prepared by updateCRLShard.
body := CRLShardBody{Parent: ds.KeyForObj(c, &hdr)}
switch err = ds.Get(c, &body); {
case err == ds.ErrNoSuchEntity:
err = fmt.Errorf("shard body %q is missing", hdr.ID)
return
case err != nil:
err = transient.Tag.Apply(err)
return
}
// Unzip and deserialize.
blob, err := utils.ZlibDecompress(body.ZippedData)
if err != nil {
return
}
shard, err := shards.ParseShard(blob)
if err != nil {
return
}
newState = shardCache{shard: shard, sha1: body.SHA1}
return
} | go | func (ch *CRLChecker) refetchShard(c context.Context, idx int, prevState shardCache) (newState shardCache, err error) {
// Have something locally already? Quickly fetch CRLShardHeader to check
// whether we need to pull a heavy CRLShardBody.
hdr := CRLShardHeader{ID: shardEntityID(ch.cn, ch.shardCount, idx)}
if prevState.sha1 != "" {
switch err = ds.Get(c, &hdr); {
case err == ds.ErrNoSuchEntity:
err = fmt.Errorf("shard header %q is missing", hdr.ID)
return
case err != nil:
err = transient.Tag.Apply(err)
return
}
// The currently cached copy is still good enough?
if hdr.SHA1 == prevState.sha1 {
newState = prevState
return
}
}
// Nothing is cached, or the datastore copy is fresher than what we have in
// the cache. Need to fetch a new copy, unzip and deserialize it. This entity
// is prepared by updateCRLShard.
body := CRLShardBody{Parent: ds.KeyForObj(c, &hdr)}
switch err = ds.Get(c, &body); {
case err == ds.ErrNoSuchEntity:
err = fmt.Errorf("shard body %q is missing", hdr.ID)
return
case err != nil:
err = transient.Tag.Apply(err)
return
}
// Unzip and deserialize.
blob, err := utils.ZlibDecompress(body.ZippedData)
if err != nil {
return
}
shard, err := shards.ParseShard(blob)
if err != nil {
return
}
newState = shardCache{shard: shard, sha1: body.SHA1}
return
} | [
"func",
"(",
"ch",
"*",
"CRLChecker",
")",
"refetchShard",
"(",
"c",
"context",
".",
"Context",
",",
"idx",
"int",
",",
"prevState",
"shardCache",
")",
"(",
"newState",
"shardCache",
",",
"err",
"error",
")",
"{",
"// Have something locally already? Quickly fetc... | // refetchShard is called by 'shard' to fetch a new version of a shard. | [
"refetchShard",
"is",
"called",
"by",
"shard",
"to",
"fetch",
"a",
"new",
"version",
"of",
"a",
"shard",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/crl.go#L266-L311 |
7,271 | luci/luci-go | milo/buildsource/builder.go | Get | func (b BuilderID) Get(c context.Context, limit int, cursor string) (*ui.Builder, error) {
// TODO(iannucci): replace these implementations with a BuildSummary query.
source, group, builderName, err := b.Split()
if err != nil {
return nil, err
}
var builder *ui.Builder
var consoles []*common.Console
err = parallel.FanOutIn(func(work chan<- func() error) {
work <- func() (err error) {
switch source {
case "buildbot":
builder, err = buildbot.GetBuilder(c, group, builderName, limit, cursor)
case "buildbucket":
bid := buildbucket.NewBuilderID(group, builderName)
builder, err = buildbucket.GetBuilder(c, bid, limit, cursor)
default:
panic(fmt.Errorf("unexpected build source %q", source))
}
return
}
work <- func() (err error) {
consoles, err = common.GetAllConsoles(c, string(b))
return
}
})
if err != nil {
return nil, err
}
builder.Groups = make([]*ui.Link, len(consoles))
for i, c := range consoles {
builder.Groups[i] = ui.NewLink(
fmt.Sprintf("%s / %s", c.ProjectID(), c.ID),
fmt.Sprintf("/p/%s/g/%s", c.ProjectID(), c.ID),
fmt.Sprintf("builder group %s in project %s", c.ID, c.ProjectID()))
}
sort.Slice(builder.Groups, func(i, j int) bool {
return builder.Groups[i].Label < builder.Groups[j].Label
})
for _, b := range builder.FinishedBuilds {
if len(b.Blame) > 0 {
builder.HasBlamelist = true
break
}
}
return builder, nil
} | go | func (b BuilderID) Get(c context.Context, limit int, cursor string) (*ui.Builder, error) {
// TODO(iannucci): replace these implementations with a BuildSummary query.
source, group, builderName, err := b.Split()
if err != nil {
return nil, err
}
var builder *ui.Builder
var consoles []*common.Console
err = parallel.FanOutIn(func(work chan<- func() error) {
work <- func() (err error) {
switch source {
case "buildbot":
builder, err = buildbot.GetBuilder(c, group, builderName, limit, cursor)
case "buildbucket":
bid := buildbucket.NewBuilderID(group, builderName)
builder, err = buildbucket.GetBuilder(c, bid, limit, cursor)
default:
panic(fmt.Errorf("unexpected build source %q", source))
}
return
}
work <- func() (err error) {
consoles, err = common.GetAllConsoles(c, string(b))
return
}
})
if err != nil {
return nil, err
}
builder.Groups = make([]*ui.Link, len(consoles))
for i, c := range consoles {
builder.Groups[i] = ui.NewLink(
fmt.Sprintf("%s / %s", c.ProjectID(), c.ID),
fmt.Sprintf("/p/%s/g/%s", c.ProjectID(), c.ID),
fmt.Sprintf("builder group %s in project %s", c.ID, c.ProjectID()))
}
sort.Slice(builder.Groups, func(i, j int) bool {
return builder.Groups[i].Label < builder.Groups[j].Label
})
for _, b := range builder.FinishedBuilds {
if len(b.Blame) > 0 {
builder.HasBlamelist = true
break
}
}
return builder, nil
} | [
"func",
"(",
"b",
"BuilderID",
")",
"Get",
"(",
"c",
"context",
".",
"Context",
",",
"limit",
"int",
",",
"cursor",
"string",
")",
"(",
"*",
"ui",
".",
"Builder",
",",
"error",
")",
"{",
"// TODO(iannucci): replace these implementations with a BuildSummary query... | // Get allows you to obtain the resp.Builder that corresponds with this
// BuilderID. | [
"Get",
"allows",
"you",
"to",
"obtain",
"the",
"resp",
".",
"Builder",
"that",
"corresponds",
"with",
"this",
"BuilderID",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/builder.go#L64-L114 |
7,272 | luci/luci-go | milo/buildsource/builder.go | SelfLink | func (b BuilderID) SelfLink(project string) string {
return model.BuilderIDLink(string(b), project)
} | go | func (b BuilderID) SelfLink(project string) string {
return model.BuilderIDLink(string(b), project)
} | [
"func",
"(",
"b",
"BuilderID",
")",
"SelfLink",
"(",
"project",
"string",
")",
"string",
"{",
"return",
"model",
".",
"BuilderIDLink",
"(",
"string",
"(",
"b",
")",
",",
"project",
")",
"\n",
"}"
] | // SelfLink returns LUCI URL of the builder. | [
"SelfLink",
"returns",
"LUCI",
"URL",
"of",
"the",
"builder",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/builder.go#L117-L119 |
7,273 | luci/luci-go | milo/buildsource/rawpresentation/html.go | NewClient | func NewClient(c context.Context, host string) (*coordinator.Client, error) {
if client, _ := c.Value(&fakeLogKey).(logdog.LogsClient); client != nil {
return &coordinator.Client{
C: client,
Host: "example.com",
}, nil
}
var err error
if host, err = resolveHost(host); err != nil {
return nil, err
}
// Initialize the LogDog client authentication.
t, err := auth.GetRPCTransport(c, auth.AsUser)
if err != nil {
return nil, errors.New("failed to get transport for LogDog server")
}
// Setup our LogDog client.
return coordinator.NewClient(&prpc.Client{
C: &http.Client{
Transport: t,
},
Host: host,
}), nil
} | go | func NewClient(c context.Context, host string) (*coordinator.Client, error) {
if client, _ := c.Value(&fakeLogKey).(logdog.LogsClient); client != nil {
return &coordinator.Client{
C: client,
Host: "example.com",
}, nil
}
var err error
if host, err = resolveHost(host); err != nil {
return nil, err
}
// Initialize the LogDog client authentication.
t, err := auth.GetRPCTransport(c, auth.AsUser)
if err != nil {
return nil, errors.New("failed to get transport for LogDog server")
}
// Setup our LogDog client.
return coordinator.NewClient(&prpc.Client{
C: &http.Client{
Transport: t,
},
Host: host,
}), nil
} | [
"func",
"NewClient",
"(",
"c",
"context",
".",
"Context",
",",
"host",
"string",
")",
"(",
"*",
"coordinator",
".",
"Client",
",",
"error",
")",
"{",
"if",
"client",
",",
"_",
":=",
"c",
".",
"Value",
"(",
"&",
"fakeLogKey",
")",
".",
"(",
"logdog"... | // NewClient generates a new LogDog client that issues requests on behalf of the
// current user. | [
"NewClient",
"generates",
"a",
"new",
"LogDog",
"client",
"that",
"issues",
"requests",
"on",
"behalf",
"of",
"the",
"current",
"user",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/rawpresentation/html.go#L64-L90 |
7,274 | luci/luci-go | milo/buildsource/buildbot/buildinfo.go | getLogDogAnnotationAddr | func getLogDogAnnotationAddr(c context.Context, build *buildbot.Build) (*types.StreamAddr, error) {
if v, ok := build.PropertyValue("log_location").(string); ok && v != "" {
return types.ParseURL(v)
}
return nil, grpcutil.Errf(codes.NotFound, "annotation stream not found")
} | go | func getLogDogAnnotationAddr(c context.Context, build *buildbot.Build) (*types.StreamAddr, error) {
if v, ok := build.PropertyValue("log_location").(string); ok && v != "" {
return types.ParseURL(v)
}
return nil, grpcutil.Errf(codes.NotFound, "annotation stream not found")
} | [
"func",
"getLogDogAnnotationAddr",
"(",
"c",
"context",
".",
"Context",
",",
"build",
"*",
"buildbot",
".",
"Build",
")",
"(",
"*",
"types",
".",
"StreamAddr",
",",
"error",
")",
"{",
"if",
"v",
",",
"ok",
":=",
"build",
".",
"PropertyValue",
"(",
"\""... | // Resolve LogDog annotation stream for this build. | [
"Resolve",
"LogDog",
"annotation",
"stream",
"for",
"this",
"build",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildinfo.go#L99-L104 |
7,275 | luci/luci-go | milo/buildsource/buildbot/buildinfo.go | mergeBuildIntoAnnotation | func mergeBuildIntoAnnotation(c context.Context, step *miloProto.Step, build *buildbot.Build) error {
allProps := stringset.New(len(step.Property) + len(build.Properties))
for _, prop := range step.Property {
allProps.Add(prop.Name)
}
for _, prop := range build.Properties {
// Annotation protobuf overrides BuildBot properties.
if allProps.Has(prop.Name) {
continue
}
allProps.Add(prop.Name)
step.Property = append(step.Property, &miloProto.Step_Property{
Name: prop.Name,
Value: fmt.Sprintf("%v", prop.Value),
})
}
return nil
} | go | func mergeBuildIntoAnnotation(c context.Context, step *miloProto.Step, build *buildbot.Build) error {
allProps := stringset.New(len(step.Property) + len(build.Properties))
for _, prop := range step.Property {
allProps.Add(prop.Name)
}
for _, prop := range build.Properties {
// Annotation protobuf overrides BuildBot properties.
if allProps.Has(prop.Name) {
continue
}
allProps.Add(prop.Name)
step.Property = append(step.Property, &miloProto.Step_Property{
Name: prop.Name,
Value: fmt.Sprintf("%v", prop.Value),
})
}
return nil
} | [
"func",
"mergeBuildIntoAnnotation",
"(",
"c",
"context",
".",
"Context",
",",
"step",
"*",
"miloProto",
".",
"Step",
",",
"build",
"*",
"buildbot",
".",
"Build",
")",
"error",
"{",
"allProps",
":=",
"stringset",
".",
"New",
"(",
"len",
"(",
"step",
".",
... | // mergeBuildInfoIntoAnnotation merges BuildBot-specific build informtion into
// a LogDog annotation protobuf.
//
// This consists of augmenting the Step's properties with BuildBot's properties,
// favoring the Step's version of the properties if there are two with the same
// name. | [
"mergeBuildInfoIntoAnnotation",
"merges",
"BuildBot",
"-",
"specific",
"build",
"informtion",
"into",
"a",
"LogDog",
"annotation",
"protobuf",
".",
"This",
"consists",
"of",
"augmenting",
"the",
"Step",
"s",
"properties",
"with",
"BuildBot",
"s",
"properties",
"favo... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildinfo.go#L112-L131 |
7,276 | luci/luci-go | tokenserver/appengine/impl/certconfig/rpc_fetch_crl.go | FetchCRL | func (r *FetchCRLRPC) FetchCRL(c context.Context, req *admin.FetchCRLRequest) (*admin.FetchCRLResponse, error) {
// Grab a corresponding CA entity. It contains URL of CRL to fetch.
ca := &CA{CN: req.Cn}
switch err := ds.Get(c, ca); {
case err == ds.ErrNoSuchEntity:
return nil, status.Errorf(codes.NotFound, "no such CA %q", ca.CN)
case err != nil:
return nil, status.Errorf(codes.Internal, "datastore error - %s", err)
}
// Grab CRL URL from the CA config.
cfg, err := ca.ParseConfig()
if err != nil {
return nil, status.Errorf(codes.Internal, "broken CA config in the datastore - %s", err)
}
if cfg.CrlUrl == "" {
return nil, status.Errorf(codes.NotFound, "CA %q doesn't have CRL defined", ca.CN)
}
// Grab info about last processed CRL, if any.
crl := &CRL{Parent: ds.KeyForObj(c, ca)}
if err = ds.Get(c, crl); err != nil && err != ds.ErrNoSuchEntity {
return nil, status.Errorf(codes.Internal, "datastore error - %s", err)
}
// Fetch latest CRL blob.
logging.Infof(c, "Fetching CRL for %q from %s", ca.CN, cfg.CrlUrl)
knownETag := crl.LastFetchETag
if req.Force {
knownETag = ""
}
fetchCtx, _ := clock.WithTimeout(c, time.Minute)
crlDer, newEtag, err := fetchCRL(fetchCtx, cfg, knownETag)
switch {
case transient.Tag.In(err):
return nil, status.Errorf(codes.Internal, "transient error when fetching CRL - %s", err)
case err != nil:
return nil, status.Errorf(codes.Unknown, "can't fetch CRL - %s", err)
}
// No changes?
if knownETag != "" && knownETag == newEtag {
logging.Infof(c, "No changes to CRL (etag is %s), skipping", knownETag)
} else {
logging.Infof(c, "Fetched CRL size is %d bytes, etag is %s", len(crlDer), newEtag)
crl, err = validateAndStoreCRL(c, crlDer, newEtag, ca, crl)
switch {
case transient.Tag.In(err):
return nil, status.Errorf(codes.Internal, "transient error when storing CRL - %s", err)
case err != nil:
return nil, status.Errorf(codes.Unknown, "bad CRL - %s", err)
}
}
return &admin.FetchCRLResponse{CrlStatus: crl.GetStatusProto()}, nil
} | go | func (r *FetchCRLRPC) FetchCRL(c context.Context, req *admin.FetchCRLRequest) (*admin.FetchCRLResponse, error) {
// Grab a corresponding CA entity. It contains URL of CRL to fetch.
ca := &CA{CN: req.Cn}
switch err := ds.Get(c, ca); {
case err == ds.ErrNoSuchEntity:
return nil, status.Errorf(codes.NotFound, "no such CA %q", ca.CN)
case err != nil:
return nil, status.Errorf(codes.Internal, "datastore error - %s", err)
}
// Grab CRL URL from the CA config.
cfg, err := ca.ParseConfig()
if err != nil {
return nil, status.Errorf(codes.Internal, "broken CA config in the datastore - %s", err)
}
if cfg.CrlUrl == "" {
return nil, status.Errorf(codes.NotFound, "CA %q doesn't have CRL defined", ca.CN)
}
// Grab info about last processed CRL, if any.
crl := &CRL{Parent: ds.KeyForObj(c, ca)}
if err = ds.Get(c, crl); err != nil && err != ds.ErrNoSuchEntity {
return nil, status.Errorf(codes.Internal, "datastore error - %s", err)
}
// Fetch latest CRL blob.
logging.Infof(c, "Fetching CRL for %q from %s", ca.CN, cfg.CrlUrl)
knownETag := crl.LastFetchETag
if req.Force {
knownETag = ""
}
fetchCtx, _ := clock.WithTimeout(c, time.Minute)
crlDer, newEtag, err := fetchCRL(fetchCtx, cfg, knownETag)
switch {
case transient.Tag.In(err):
return nil, status.Errorf(codes.Internal, "transient error when fetching CRL - %s", err)
case err != nil:
return nil, status.Errorf(codes.Unknown, "can't fetch CRL - %s", err)
}
// No changes?
if knownETag != "" && knownETag == newEtag {
logging.Infof(c, "No changes to CRL (etag is %s), skipping", knownETag)
} else {
logging.Infof(c, "Fetched CRL size is %d bytes, etag is %s", len(crlDer), newEtag)
crl, err = validateAndStoreCRL(c, crlDer, newEtag, ca, crl)
switch {
case transient.Tag.In(err):
return nil, status.Errorf(codes.Internal, "transient error when storing CRL - %s", err)
case err != nil:
return nil, status.Errorf(codes.Unknown, "bad CRL - %s", err)
}
}
return &admin.FetchCRLResponse{CrlStatus: crl.GetStatusProto()}, nil
} | [
"func",
"(",
"r",
"*",
"FetchCRLRPC",
")",
"FetchCRL",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"admin",
".",
"FetchCRLRequest",
")",
"(",
"*",
"admin",
".",
"FetchCRLResponse",
",",
"error",
")",
"{",
"// Grab a corresponding CA entity. It contai... | // FetchCRL makes the server fetch a CRL for some CA. | [
"FetchCRL",
"makes",
"the",
"server",
"fetch",
"a",
"CRL",
"for",
"some",
"CA",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/rpc_fetch_crl.go#L50-L105 |
7,277 | luci/luci-go | tokenserver/appengine/impl/certconfig/rpc_fetch_crl.go | validateAndStoreCRL | func validateAndStoreCRL(c context.Context, crlDer []byte, etag string, ca *CA, prev *CRL) (*CRL, error) {
// Make sure it is signed by the CA.
caCert, err := x509.ParseCertificate(ca.Cert)
if err != nil {
return nil, fmt.Errorf("cert in the datastore is broken - %s", err)
}
crl, err := x509.ParseDERCRL(crlDer)
if err != nil {
return nil, fmt.Errorf("not a valid x509 CRL - %s", err)
}
if err = caCert.CheckCRLSignature(crl); err != nil {
return nil, fmt.Errorf("CRL is not signed by the CA - %s", err)
}
// The CRL is peachy. Update a sharded set of all revoked certs.
logging.Infof(c, "CRL last updated %s", crl.TBSCertList.ThisUpdate)
logging.Infof(c, "Found %d entries in the CRL", len(crl.TBSCertList.RevokedCertificates))
if err = UpdateCRLSet(c, ca.CN, CRLShardCount, crl); err != nil {
return nil, err
}
logging.Infof(c, "All CRL entries stored")
// Update the CRL entity. Use EntityVersion to make sure we are not
// overwriting someone else's changes.
var updated *CRL
err = ds.RunInTransaction(c, func(c context.Context) error {
entity := *prev
if err := ds.Get(c, &entity); err != nil && err != ds.ErrNoSuchEntity {
return err
}
if entity.EntityVersion != prev.EntityVersion {
return fmt.Errorf("CRL for %q was updated concurrently while we were working on it", ca.CN)
}
entity.EntityVersion++
entity.LastUpdateTime = crl.TBSCertList.ThisUpdate.UTC()
entity.LastFetchTime = clock.Now(c).UTC()
entity.LastFetchETag = etag
entity.RevokedCertsCount = len(crl.TBSCertList.RevokedCertificates)
updated = &entity // used outside of this function
toPut := []interface{}{updated}
// Mark CA entity as ready for usage.
curCA := CA{CN: ca.CN}
switch err := ds.Get(c, &curCA); {
case err == ds.ErrNoSuchEntity:
return fmt.Errorf("CA entity for %q is unexpectedly gone", ca.CN)
case err != nil:
return err
}
if !curCA.Ready {
logging.Infof(c, "CA %q is ready now", curCA.CN)
curCA.Ready = true
toPut = append(toPut, &curCA)
}
return ds.Put(c, toPut)
}, nil)
if err != nil {
return nil, transient.Tag.Apply(err)
}
logging.Infof(c, "CRL for %q is updated, entity version is %d", ca.CN, updated.EntityVersion)
return updated, nil
} | go | func validateAndStoreCRL(c context.Context, crlDer []byte, etag string, ca *CA, prev *CRL) (*CRL, error) {
// Make sure it is signed by the CA.
caCert, err := x509.ParseCertificate(ca.Cert)
if err != nil {
return nil, fmt.Errorf("cert in the datastore is broken - %s", err)
}
crl, err := x509.ParseDERCRL(crlDer)
if err != nil {
return nil, fmt.Errorf("not a valid x509 CRL - %s", err)
}
if err = caCert.CheckCRLSignature(crl); err != nil {
return nil, fmt.Errorf("CRL is not signed by the CA - %s", err)
}
// The CRL is peachy. Update a sharded set of all revoked certs.
logging.Infof(c, "CRL last updated %s", crl.TBSCertList.ThisUpdate)
logging.Infof(c, "Found %d entries in the CRL", len(crl.TBSCertList.RevokedCertificates))
if err = UpdateCRLSet(c, ca.CN, CRLShardCount, crl); err != nil {
return nil, err
}
logging.Infof(c, "All CRL entries stored")
// Update the CRL entity. Use EntityVersion to make sure we are not
// overwriting someone else's changes.
var updated *CRL
err = ds.RunInTransaction(c, func(c context.Context) error {
entity := *prev
if err := ds.Get(c, &entity); err != nil && err != ds.ErrNoSuchEntity {
return err
}
if entity.EntityVersion != prev.EntityVersion {
return fmt.Errorf("CRL for %q was updated concurrently while we were working on it", ca.CN)
}
entity.EntityVersion++
entity.LastUpdateTime = crl.TBSCertList.ThisUpdate.UTC()
entity.LastFetchTime = clock.Now(c).UTC()
entity.LastFetchETag = etag
entity.RevokedCertsCount = len(crl.TBSCertList.RevokedCertificates)
updated = &entity // used outside of this function
toPut := []interface{}{updated}
// Mark CA entity as ready for usage.
curCA := CA{CN: ca.CN}
switch err := ds.Get(c, &curCA); {
case err == ds.ErrNoSuchEntity:
return fmt.Errorf("CA entity for %q is unexpectedly gone", ca.CN)
case err != nil:
return err
}
if !curCA.Ready {
logging.Infof(c, "CA %q is ready now", curCA.CN)
curCA.Ready = true
toPut = append(toPut, &curCA)
}
return ds.Put(c, toPut)
}, nil)
if err != nil {
return nil, transient.Tag.Apply(err)
}
logging.Infof(c, "CRL for %q is updated, entity version is %d", ca.CN, updated.EntityVersion)
return updated, nil
} | [
"func",
"validateAndStoreCRL",
"(",
"c",
"context",
".",
"Context",
",",
"crlDer",
"[",
"]",
"byte",
",",
"etag",
"string",
",",
"ca",
"*",
"CA",
",",
"prev",
"*",
"CRL",
")",
"(",
"*",
"CRL",
",",
"error",
")",
"{",
"// Make sure it is signed by the CA.... | // validateAndStoreCRL handles incoming CRL blob fetched by 'fetchCRL'. | [
"validateAndStoreCRL",
"handles",
"incoming",
"CRL",
"blob",
"fetched",
"by",
"fetchCRL",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/rpc_fetch_crl.go#L202-L265 |
7,278 | luci/luci-go | client/internal/common/filesystem_view.go | NewFilesystemView | func NewFilesystemView(root string, blacklist []string) (FilesystemView, error) {
for _, b := range blacklist {
if _, err := filepath.Match(b, b); err != nil {
return FilesystemView{}, fmt.Errorf("bad blacklist pattern \"%s\"", b)
}
}
return FilesystemView{root: root, blacklist: blacklist}, nil
} | go | func NewFilesystemView(root string, blacklist []string) (FilesystemView, error) {
for _, b := range blacklist {
if _, err := filepath.Match(b, b); err != nil {
return FilesystemView{}, fmt.Errorf("bad blacklist pattern \"%s\"", b)
}
}
return FilesystemView{root: root, blacklist: blacklist}, nil
} | [
"func",
"NewFilesystemView",
"(",
"root",
"string",
",",
"blacklist",
"[",
"]",
"string",
")",
"(",
"FilesystemView",
",",
"error",
")",
"{",
"for",
"_",
",",
"b",
":=",
"range",
"blacklist",
"{",
"if",
"_",
",",
"err",
":=",
"filepath",
".",
"Match",
... | // NewFilesystemView returns a FilesystemView based on the supplied root and blacklist, or
// an error if blacklist contains a bad pattern.
// root is the the base path used by RelativePath to calulate relative paths.
// blacklist is a list of globs of files to ignore. See RelativePath for more information. | [
"NewFilesystemView",
"returns",
"a",
"FilesystemView",
"based",
"on",
"the",
"supplied",
"root",
"and",
"blacklist",
"or",
"an",
"error",
"if",
"blacklist",
"contains",
"a",
"bad",
"pattern",
".",
"root",
"is",
"the",
"the",
"base",
"path",
"used",
"by",
"Re... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/filesystem_view.go#L38-L45 |
7,279 | luci/luci-go | client/internal/common/filesystem_view.go | NewSymlinkedView | func (ff FilesystemView) NewSymlinkedView(source, linkname string) FilesystemView {
prefix := source
if ff.sourcePrefix != "" {
prefix = filepath.Join(ff.sourcePrefix, source)
}
return FilesystemView{root: linkname, blacklist: ff.blacklist, sourcePrefix: prefix}
} | go | func (ff FilesystemView) NewSymlinkedView(source, linkname string) FilesystemView {
prefix := source
if ff.sourcePrefix != "" {
prefix = filepath.Join(ff.sourcePrefix, source)
}
return FilesystemView{root: linkname, blacklist: ff.blacklist, sourcePrefix: prefix}
} | [
"func",
"(",
"ff",
"FilesystemView",
")",
"NewSymlinkedView",
"(",
"source",
",",
"linkname",
"string",
")",
"FilesystemView",
"{",
"prefix",
":=",
"source",
"\n",
"if",
"ff",
".",
"sourcePrefix",
"!=",
"\"",
"\"",
"{",
"prefix",
"=",
"filepath",
".",
"Joi... | // NewSymlinkedView returns a filesystem view from a symlinked directory within itself. | [
"NewSymlinkedView",
"returns",
"a",
"filesystem",
"view",
"from",
"a",
"symlinked",
"directory",
"within",
"itself",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/filesystem_view.go#L84-L90 |
7,280 | luci/luci-go | client/internal/common/filesystem_view.go | match | func match(pattern, name string) bool {
matched, _ := filepath.Match(pattern, name)
return matched
} | go | func match(pattern, name string) bool {
matched, _ := filepath.Match(pattern, name)
return matched
} | [
"func",
"match",
"(",
"pattern",
",",
"name",
"string",
")",
"bool",
"{",
"matched",
",",
"_",
":=",
"filepath",
".",
"Match",
"(",
"pattern",
",",
"name",
")",
"\n",
"return",
"matched",
"\n",
"}"
] | // match is equivalent to filepath.Match, but assumes that pattern is valid. | [
"match",
"is",
"equivalent",
"to",
"filepath",
".",
"Match",
"but",
"assumes",
"that",
"pattern",
"is",
"valid",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/filesystem_view.go#L93-L96 |
7,281 | luci/luci-go | client/internal/common/filesystem_view.go | WalkFuncSkipFile | func WalkFuncSkipFile(file os.FileInfo) error {
if file.IsDir() {
return filepath.SkipDir
}
// If we were to return SkipDir for a file, it would cause
// filepath.Walk to skip the file's containing directory, which we do
// not want (see https://golang.org/pkg/path/filepath/#WalkFunc).
return nil
} | go | func WalkFuncSkipFile(file os.FileInfo) error {
if file.IsDir() {
return filepath.SkipDir
}
// If we were to return SkipDir for a file, it would cause
// filepath.Walk to skip the file's containing directory, which we do
// not want (see https://golang.org/pkg/path/filepath/#WalkFunc).
return nil
} | [
"func",
"WalkFuncSkipFile",
"(",
"file",
"os",
".",
"FileInfo",
")",
"error",
"{",
"if",
"file",
".",
"IsDir",
"(",
")",
"{",
"return",
"filepath",
".",
"SkipDir",
"\n",
"}",
"\n",
"// If we were to return SkipDir for a file, it would cause",
"// filepath.Walk to sk... | // WalkFuncSkipFile is a helper for implemenations of filepath.WalkFunc. The
// value that it returns may in turn be returned by the WalkFunc implementaiton
// to indicate that file should be skipped. | [
"WalkFuncSkipFile",
"is",
"a",
"helper",
"for",
"implemenations",
"of",
"filepath",
".",
"WalkFunc",
".",
"The",
"value",
"that",
"it",
"returns",
"may",
"in",
"turn",
"be",
"returned",
"by",
"the",
"WalkFunc",
"implementaiton",
"to",
"indicate",
"that",
"file... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/filesystem_view.go#L101-L109 |
7,282 | luci/luci-go | common/lhttp/utils.go | IsLocalHost | func IsLocalHost(hostport string) bool {
host, _, err := net.SplitHostPort(hostport)
if err != nil {
return false
}
switch {
case host == "localhost", host == "":
case net.ParseIP(host).IsLoopback():
default:
return false
}
return true
} | go | func IsLocalHost(hostport string) bool {
host, _, err := net.SplitHostPort(hostport)
if err != nil {
return false
}
switch {
case host == "localhost", host == "":
case net.ParseIP(host).IsLoopback():
default:
return false
}
return true
} | [
"func",
"IsLocalHost",
"(",
"hostport",
"string",
")",
"bool",
"{",
"host",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"hostport",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"switch",
"{",
"case",... | // IsLocalHost returns true if hostport is local. | [
"IsLocalHost",
"returns",
"true",
"if",
"hostport",
"is",
"local",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/lhttp/utils.go#L55-L68 |
7,283 | luci/luci-go | tokenserver/appengine/impl/machinetoken/rpc_inspect_machine_token.go | InspectMachineToken | func (r *InspectMachineTokenRPC) InspectMachineToken(c context.Context, req *admin.InspectMachineTokenRequest) (*admin.InspectMachineTokenResponse, error) {
// Defaults.
if req.TokenType == 0 {
req.TokenType = tokenserver.MachineTokenType_LUCI_MACHINE_TOKEN
}
// Only LUCI_MACHINE_TOKEN is supported currently.
switch req.TokenType {
case tokenserver.MachineTokenType_LUCI_MACHINE_TOKEN:
// supported
default:
return nil, status.Errorf(codes.InvalidArgument, "unsupported token type %s", req.TokenType)
}
// Deserialize the token, check its signature.
inspection, err := InspectToken(c, r.Signer, req.Token)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
resp := &admin.InspectMachineTokenResponse{
Signed: inspection.Signed,
NonExpired: inspection.NonExpired,
InvalidityReason: inspection.InvalidityReason,
}
// Grab the signing key from the envelope, if managed to deserialize it.
if env, _ := inspection.Envelope.(*tokenserver.MachineTokenEnvelope); env != nil {
resp.SigningKeyId = env.KeyId
}
// If we could not deserialize the body, that's all checks we could do.
body, _ := inspection.Body.(*tokenserver.MachineTokenBody)
if body == nil {
return resp, nil
}
resp.TokenType = &admin.InspectMachineTokenResponse_LuciMachineToken{
LuciMachineToken: body,
}
addReason := func(r string) {
if resp.InvalidityReason == "" {
resp.InvalidityReason = r
} else {
resp.InvalidityReason += "; " + r
}
}
// Check revocation status. Find CA name that signed the certificate used when
// minting the token.
caName, err := certconfig.GetCAByUniqueID(c, body.CaId)
switch {
case err != nil:
return nil, status.Errorf(codes.Internal, "can't resolve ca_id to CA name - %s", err)
case caName == "":
addReason("no CA with given ID")
return resp, nil
}
resp.CertCaName = caName
// Grab CertChecker for this CA. It has CRL cached.
certChecker, err := certchecker.GetCertChecker(c, caName)
switch {
case transient.Tag.In(err):
return nil, status.Errorf(codes.Internal, "can't fetch CRL - %s", err)
case err != nil:
addReason(fmt.Sprintf("can't fetch CRL - %s", err))
return resp, nil
}
// Check that certificate SN is not in the revocation list.
sn := big.NewInt(0).SetUint64(body.CertSn)
revoked, err := certChecker.CRL.IsRevokedSN(c, sn)
if err != nil {
return nil, status.Errorf(codes.Internal, "can't check CRL - %s", err)
}
resp.NonRevoked = !revoked
// Note: if Signed or NonExpired is false, InvalidityReason is already set.
if resp.Signed && resp.NonExpired {
if resp.NonRevoked {
resp.Valid = true
} else {
addReason("corresponding cert was revoked")
}
}
return resp, nil
} | go | func (r *InspectMachineTokenRPC) InspectMachineToken(c context.Context, req *admin.InspectMachineTokenRequest) (*admin.InspectMachineTokenResponse, error) {
// Defaults.
if req.TokenType == 0 {
req.TokenType = tokenserver.MachineTokenType_LUCI_MACHINE_TOKEN
}
// Only LUCI_MACHINE_TOKEN is supported currently.
switch req.TokenType {
case tokenserver.MachineTokenType_LUCI_MACHINE_TOKEN:
// supported
default:
return nil, status.Errorf(codes.InvalidArgument, "unsupported token type %s", req.TokenType)
}
// Deserialize the token, check its signature.
inspection, err := InspectToken(c, r.Signer, req.Token)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
resp := &admin.InspectMachineTokenResponse{
Signed: inspection.Signed,
NonExpired: inspection.NonExpired,
InvalidityReason: inspection.InvalidityReason,
}
// Grab the signing key from the envelope, if managed to deserialize it.
if env, _ := inspection.Envelope.(*tokenserver.MachineTokenEnvelope); env != nil {
resp.SigningKeyId = env.KeyId
}
// If we could not deserialize the body, that's all checks we could do.
body, _ := inspection.Body.(*tokenserver.MachineTokenBody)
if body == nil {
return resp, nil
}
resp.TokenType = &admin.InspectMachineTokenResponse_LuciMachineToken{
LuciMachineToken: body,
}
addReason := func(r string) {
if resp.InvalidityReason == "" {
resp.InvalidityReason = r
} else {
resp.InvalidityReason += "; " + r
}
}
// Check revocation status. Find CA name that signed the certificate used when
// minting the token.
caName, err := certconfig.GetCAByUniqueID(c, body.CaId)
switch {
case err != nil:
return nil, status.Errorf(codes.Internal, "can't resolve ca_id to CA name - %s", err)
case caName == "":
addReason("no CA with given ID")
return resp, nil
}
resp.CertCaName = caName
// Grab CertChecker for this CA. It has CRL cached.
certChecker, err := certchecker.GetCertChecker(c, caName)
switch {
case transient.Tag.In(err):
return nil, status.Errorf(codes.Internal, "can't fetch CRL - %s", err)
case err != nil:
addReason(fmt.Sprintf("can't fetch CRL - %s", err))
return resp, nil
}
// Check that certificate SN is not in the revocation list.
sn := big.NewInt(0).SetUint64(body.CertSn)
revoked, err := certChecker.CRL.IsRevokedSN(c, sn)
if err != nil {
return nil, status.Errorf(codes.Internal, "can't check CRL - %s", err)
}
resp.NonRevoked = !revoked
// Note: if Signed or NonExpired is false, InvalidityReason is already set.
if resp.Signed && resp.NonExpired {
if resp.NonRevoked {
resp.Valid = true
} else {
addReason("corresponding cert was revoked")
}
}
return resp, nil
} | [
"func",
"(",
"r",
"*",
"InspectMachineTokenRPC",
")",
"InspectMachineToken",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"admin",
".",
"InspectMachineTokenRequest",
")",
"(",
"*",
"admin",
".",
"InspectMachineTokenResponse",
",",
"error",
")",
"{",
"... | // InspectMachineToken decodes a machine token and verifies it is valid. | [
"InspectMachineToken",
"decodes",
"a",
"machine",
"token",
"and",
"verifies",
"it",
"is",
"valid",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/machinetoken/rpc_inspect_machine_token.go#L46-L133 |
7,284 | luci/luci-go | lucicfg/state.go | clear | func (s *State) clear() {
*s = State{Inputs: s.Inputs, vars: s.vars}
s.vars.ClearValues()
} | go | func (s *State) clear() {
*s = State{Inputs: s.Inputs, vars: s.vars}
s.vars.ClearValues()
} | [
"func",
"(",
"s",
"*",
"State",
")",
"clear",
"(",
")",
"{",
"*",
"s",
"=",
"State",
"{",
"Inputs",
":",
"s",
".",
"Inputs",
",",
"vars",
":",
"s",
".",
"vars",
"}",
"\n",
"s",
".",
"vars",
".",
"ClearValues",
"(",
")",
"\n",
"}"
] | // clear resets the state. | [
"clear",
"resets",
"the",
"state",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/state.go#L55-L58 |
7,285 | luci/luci-go | lucicfg/state.go | err | func (s *State) err(err ...error) error {
if s.seenErrs == nil {
s.seenErrs = stringset.New(len(err))
}
for _, e := range err {
if bt, _ := e.(BacktracableError); bt == nil || s.seenErrs.Add(bt.Backtrace()) {
s.errors = append(s.errors, e)
}
}
return s.errors
} | go | func (s *State) err(err ...error) error {
if s.seenErrs == nil {
s.seenErrs = stringset.New(len(err))
}
for _, e := range err {
if bt, _ := e.(BacktracableError); bt == nil || s.seenErrs.Add(bt.Backtrace()) {
s.errors = append(s.errors, e)
}
}
return s.errors
} | [
"func",
"(",
"s",
"*",
"State",
")",
"err",
"(",
"err",
"...",
"error",
")",
"error",
"{",
"if",
"s",
".",
"seenErrs",
"==",
"nil",
"{",
"s",
".",
"seenErrs",
"=",
"stringset",
".",
"New",
"(",
"len",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"f... | // err adds errors to the list of errors and returns the list as MultiError,
// deduplicating errors with identical backtraces. | [
"err",
"adds",
"errors",
"to",
"the",
"list",
"of",
"errors",
"and",
"returns",
"the",
"list",
"as",
"MultiError",
"deduplicating",
"errors",
"with",
"identical",
"backtraces",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/state.go#L62-L72 |
7,286 | luci/luci-go | tokenserver/appengine/impl/certchecker/rpc_check_certificate.go | CheckCertificate | func (r *CheckCertificateRPC) CheckCertificate(c context.Context, req *admin.CheckCertificateRequest) (*admin.CheckCertificateResponse, error) {
// Deserialize the cert.
der, err := utils.ParsePEM(req.CertPem, "CERTIFICATE")
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "can't parse 'cert_pem' - %s", err)
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "can't parse 'cert-pem' - %s", err)
}
// Find a checker for the CA that signed the cert, check the certificate.
checker, err := GetCertChecker(c, cert.Issuer.CommonName)
if err == nil {
_, err = checker.CheckCertificate(c, cert)
if err == nil {
return &admin.CheckCertificateResponse{
IsValid: true,
}, nil
}
}
// Recognize error codes related to CA cert checking. Everything else is
// transient errors.
if details, ok := err.(Error); ok {
return &admin.CheckCertificateResponse{
IsValid: false,
InvalidReason: details.Error(),
}, nil
}
return nil, status.Errorf(codes.Internal, "failed to check the certificate - %s", err)
} | go | func (r *CheckCertificateRPC) CheckCertificate(c context.Context, req *admin.CheckCertificateRequest) (*admin.CheckCertificateResponse, error) {
// Deserialize the cert.
der, err := utils.ParsePEM(req.CertPem, "CERTIFICATE")
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "can't parse 'cert_pem' - %s", err)
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "can't parse 'cert-pem' - %s", err)
}
// Find a checker for the CA that signed the cert, check the certificate.
checker, err := GetCertChecker(c, cert.Issuer.CommonName)
if err == nil {
_, err = checker.CheckCertificate(c, cert)
if err == nil {
return &admin.CheckCertificateResponse{
IsValid: true,
}, nil
}
}
// Recognize error codes related to CA cert checking. Everything else is
// transient errors.
if details, ok := err.(Error); ok {
return &admin.CheckCertificateResponse{
IsValid: false,
InvalidReason: details.Error(),
}, nil
}
return nil, status.Errorf(codes.Internal, "failed to check the certificate - %s", err)
} | [
"func",
"(",
"r",
"*",
"CheckCertificateRPC",
")",
"CheckCertificate",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"admin",
".",
"CheckCertificateRequest",
")",
"(",
"*",
"admin",
".",
"CheckCertificateResponse",
",",
"error",
")",
"{",
"// Deseriali... | // CheckCertificate says whether a certificate is valid or not. | [
"CheckCertificate",
"says",
"whether",
"a",
"certificate",
"is",
"valid",
"or",
"not",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certchecker/rpc_check_certificate.go#L34-L65 |
7,287 | luci/luci-go | common/data/text/sanitizehtml/sanitize.go | p | func (s *sanitizer) p(safeMarkup string) {
if s.err == nil {
_, s.err = s.sw.WriteString(safeMarkup)
}
} | go | func (s *sanitizer) p(safeMarkup string) {
if s.err == nil {
_, s.err = s.sw.WriteString(safeMarkup)
}
} | [
"func",
"(",
"s",
"*",
"sanitizer",
")",
"p",
"(",
"safeMarkup",
"string",
")",
"{",
"if",
"s",
".",
"err",
"==",
"nil",
"{",
"_",
",",
"s",
".",
"err",
"=",
"s",
".",
"sw",
".",
"WriteString",
"(",
"safeMarkup",
")",
"\n",
"}",
"\n",
"}"
] | // p prints the text, unless there was an error before. | [
"p",
"prints",
"the",
"text",
"unless",
"there",
"was",
"an",
"error",
"before",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/sanitizehtml/sanitize.go#L58-L62 |
7,288 | luci/luci-go | common/data/text/sanitizehtml/sanitize.go | printAttr | func (s *sanitizer) printAttr(key, value string) {
s.p(" ")
s.p(key)
s.p("=\"")
s.p(html.EscapeString(value))
s.p("\"")
} | go | func (s *sanitizer) printAttr(key, value string) {
s.p(" ")
s.p(key)
s.p("=\"")
s.p(html.EscapeString(value))
s.p("\"")
} | [
"func",
"(",
"s",
"*",
"sanitizer",
")",
"printAttr",
"(",
"key",
",",
"value",
"string",
")",
"{",
"s",
".",
"p",
"(",
"\"",
"\"",
")",
"\n",
"s",
".",
"p",
"(",
"key",
")",
"\n",
"s",
".",
"p",
"(",
"\"",
"\\\"",
"\"",
")",
"\n",
"s",
"... | // printAttr prints a space and then an HTML attribute node. | [
"printAttr",
"prints",
"a",
"space",
"and",
"then",
"an",
"HTML",
"attribute",
"node",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/sanitizehtml/sanitize.go#L65-L71 |
7,289 | luci/luci-go | config/server/cfgclient/backend/erroring/erroring.go | New | func New(err error) backend.B {
if err == nil {
panic("the error must not be nil")
}
return erroringImpl{err}
} | go | func New(err error) backend.B {
if err == nil {
panic("the error must not be nil")
}
return erroringImpl{err}
} | [
"func",
"New",
"(",
"err",
"error",
")",
"backend",
".",
"B",
"{",
"if",
"err",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"erroringImpl",
"{",
"err",
"}",
"\n",
"}"
] | // New produces backend.B instance that returns the given error for all calls.
//
// Panics if given err is nil. | [
"New",
"produces",
"backend",
".",
"B",
"instance",
"that",
"returns",
"the",
"given",
"error",
"for",
"all",
"calls",
".",
"Panics",
"if",
"given",
"err",
"is",
"nil",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/erroring/erroring.go#L33-L38 |
7,290 | luci/luci-go | logdog/appengine/coordinator/logStreamState.go | NewLogStreamState | func NewLogStreamState(c context.Context, id HashID) *LogStreamState {
return &LogStreamState{Parent: ds.NewKey(c, "LogStream", string(id), 0, nil)}
} | go | func NewLogStreamState(c context.Context, id HashID) *LogStreamState {
return &LogStreamState{Parent: ds.NewKey(c, "LogStream", string(id), 0, nil)}
} | [
"func",
"NewLogStreamState",
"(",
"c",
"context",
".",
"Context",
",",
"id",
"HashID",
")",
"*",
"LogStreamState",
"{",
"return",
"&",
"LogStreamState",
"{",
"Parent",
":",
"ds",
".",
"NewKey",
"(",
"c",
",",
"\"",
"\"",
",",
"string",
"(",
"id",
")",
... | // NewLogStreamState returns a LogStreamState with its parent key populated to
// the LogStream with the supplied ID. | [
"NewLogStreamState",
"returns",
"a",
"LogStreamState",
"with",
"its",
"parent",
"key",
"populated",
"to",
"the",
"LogStream",
"with",
"the",
"supplied",
"ID",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStreamState.go#L147-L149 |
7,291 | luci/luci-go | logdog/appengine/coordinator/logStreamState.go | Validate | func (lst *LogStreamState) Validate() error {
if lst.Created.IsZero() {
return errors.New("missing created time")
}
if lst.Updated.IsZero() {
return errors.New("missing updated time")
}
if lst.Terminated() && lst.TerminatedTime.IsZero() {
return errors.New("log stream is terminated, but missing terminated time")
}
if err := types.PrefixSecret(lst.Secret).Validate(); err != nil {
return fmt.Errorf("invalid prefix secret: %v", err)
}
return nil
} | go | func (lst *LogStreamState) Validate() error {
if lst.Created.IsZero() {
return errors.New("missing created time")
}
if lst.Updated.IsZero() {
return errors.New("missing updated time")
}
if lst.Terminated() && lst.TerminatedTime.IsZero() {
return errors.New("log stream is terminated, but missing terminated time")
}
if err := types.PrefixSecret(lst.Secret).Validate(); err != nil {
return fmt.Errorf("invalid prefix secret: %v", err)
}
return nil
} | [
"func",
"(",
"lst",
"*",
"LogStreamState",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"lst",
".",
"Created",
".",
"IsZero",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"lst",
".",
"Updated",
"."... | // Validate evaluates the state and data contents of the LogStreamState and
// returns an error if it is invalid. | [
"Validate",
"evaluates",
"the",
"state",
"and",
"data",
"contents",
"of",
"the",
"LogStreamState",
"and",
"returns",
"an",
"error",
"if",
"it",
"is",
"invalid",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStreamState.go#L183-L199 |
7,292 | luci/luci-go | logdog/appengine/coordinator/logStreamState.go | Terminated | func (lst *LogStreamState) Terminated() bool {
if lst.ArchivalState().Archived() {
return true
}
return lst.TerminalIndex >= 0
} | go | func (lst *LogStreamState) Terminated() bool {
if lst.ArchivalState().Archived() {
return true
}
return lst.TerminalIndex >= 0
} | [
"func",
"(",
"lst",
"*",
"LogStreamState",
")",
"Terminated",
"(",
")",
"bool",
"{",
"if",
"lst",
".",
"ArchivalState",
"(",
")",
".",
"Archived",
"(",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"lst",
".",
"TerminalIndex",
">=",
"0",
"\n... | // Terminated returns true if this stream has been terminated. | [
"Terminated",
"returns",
"true",
"if",
"this",
"stream",
"has",
"been",
"terminated",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStreamState.go#L202-L207 |
7,293 | luci/luci-go | logdog/appengine/coordinator/logStreamState.go | ArchivalState | func (lst *LogStreamState) ArchivalState() ArchivalState {
if lst.ArchivedTime.IsZero() {
// Not archived, have we dispatched an archival?
if len(lst.ArchivalKey) > 0 {
return ArchiveTasked
}
return NotArchived
}
if lst.ArchiveLogEntryCount > lst.TerminalIndex {
return ArchivedComplete
}
return ArchivedPartial
} | go | func (lst *LogStreamState) ArchivalState() ArchivalState {
if lst.ArchivedTime.IsZero() {
// Not archived, have we dispatched an archival?
if len(lst.ArchivalKey) > 0 {
return ArchiveTasked
}
return NotArchived
}
if lst.ArchiveLogEntryCount > lst.TerminalIndex {
return ArchivedComplete
}
return ArchivedPartial
} | [
"func",
"(",
"lst",
"*",
"LogStreamState",
")",
"ArchivalState",
"(",
")",
"ArchivalState",
"{",
"if",
"lst",
".",
"ArchivedTime",
".",
"IsZero",
"(",
")",
"{",
"// Not archived, have we dispatched an archival?",
"if",
"len",
"(",
"lst",
".",
"ArchivalKey",
")",... | // ArchivalState returns the archival state of the log stream. | [
"ArchivalState",
"returns",
"the",
"archival",
"state",
"of",
"the",
"log",
"stream",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStreamState.go#L210-L223 |
7,294 | luci/luci-go | scheduler/appengine/task/gitiles/state.go | loadStateEntry | func loadStateEntry(c context.Context, jobID, repo string) (*Repository, error) {
id, err := repositoryID(jobID, repo)
if err != nil {
return nil, err
}
entry := &Repository{ID: id}
if err := ds.Get(c, entry); err == ds.ErrNoSuchEntity {
return nil, err
} else {
return entry, transient.Tag.Apply(err)
}
} | go | func loadStateEntry(c context.Context, jobID, repo string) (*Repository, error) {
id, err := repositoryID(jobID, repo)
if err != nil {
return nil, err
}
entry := &Repository{ID: id}
if err := ds.Get(c, entry); err == ds.ErrNoSuchEntity {
return nil, err
} else {
return entry, transient.Tag.Apply(err)
}
} | [
"func",
"loadStateEntry",
"(",
"c",
"context",
".",
"Context",
",",
"jobID",
",",
"repo",
"string",
")",
"(",
"*",
"Repository",
",",
"error",
")",
"{",
"id",
",",
"err",
":=",
"repositoryID",
"(",
"jobID",
",",
"repo",
")",
"\n",
"if",
"err",
"!=",
... | // loadStateEntry loads Repository instance from datastore. | [
"loadStateEntry",
"loads",
"Repository",
"instance",
"from",
"datastore",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/gitiles/state.go#L75-L86 |
7,295 | luci/luci-go | milo/frontend/view_build_legacy.go | handleBuildbotBuild | func handleBuildbotBuild(c *router.Context) error {
buildNum, err := strconv.Atoi(c.Params.ByName("number"))
if err != nil {
return errors.Annotate(err, "build number is not a number").
Tag(grpcutil.InvalidArgumentTag).
Err()
}
id := buildbotapi.BuildID{
Master: c.Params.ByName("master"),
Builder: c.Params.ByName("builder"),
Number: buildNum,
}
if err := id.Validate(); err != nil {
return err
}
// If this build is emulated, redirect to LUCI.
b, err := buildstore.EmulationOf(c.Context, id)
switch {
case err != nil:
return err
case b != nil && b.Number != nil:
u := *c.Request.URL
u.Path = fmt.Sprintf("/p/%s/builders/%s/%s/%d", b.Project, b.Bucket, b.Builder, *b.Number)
http.Redirect(c.Writer, c.Request, u.String(), http.StatusFound)
return nil
default:
build, err := buildbot.GetBuild(c.Context, id)
return renderBuildLegacy(c, build, false, err)
}
} | go | func handleBuildbotBuild(c *router.Context) error {
buildNum, err := strconv.Atoi(c.Params.ByName("number"))
if err != nil {
return errors.Annotate(err, "build number is not a number").
Tag(grpcutil.InvalidArgumentTag).
Err()
}
id := buildbotapi.BuildID{
Master: c.Params.ByName("master"),
Builder: c.Params.ByName("builder"),
Number: buildNum,
}
if err := id.Validate(); err != nil {
return err
}
// If this build is emulated, redirect to LUCI.
b, err := buildstore.EmulationOf(c.Context, id)
switch {
case err != nil:
return err
case b != nil && b.Number != nil:
u := *c.Request.URL
u.Path = fmt.Sprintf("/p/%s/builders/%s/%s/%d", b.Project, b.Bucket, b.Builder, *b.Number)
http.Redirect(c.Writer, c.Request, u.String(), http.StatusFound)
return nil
default:
build, err := buildbot.GetBuild(c.Context, id)
return renderBuildLegacy(c, build, false, err)
}
} | [
"func",
"handleBuildbotBuild",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"error",
"{",
"buildNum",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"c",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",... | // handleBuildbotBuild renders a buildbot build.
// Requires emulationMiddleware. | [
"handleBuildbotBuild",
"renders",
"a",
"buildbot",
"build",
".",
"Requires",
"emulationMiddleware",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_build_legacy.go#L47-L77 |
7,296 | luci/luci-go | milo/frontend/view_build_legacy.go | handleLUCIBuildLegacy | func handleLUCIBuildLegacy(c *router.Context, bucket, builder, numberOrId string) error {
var address string
if strings.HasPrefix(numberOrId, "b") {
address = numberOrId[1:]
} else {
address = fmt.Sprintf("%s/%s/%s", bucket, builder, numberOrId)
}
build, err := buildbucket.GetBuildLegacy(c.Context, address, true)
return renderBuildLegacy(c, build, true, err)
} | go | func handleLUCIBuildLegacy(c *router.Context, bucket, builder, numberOrId string) error {
var address string
if strings.HasPrefix(numberOrId, "b") {
address = numberOrId[1:]
} else {
address = fmt.Sprintf("%s/%s/%s", bucket, builder, numberOrId)
}
build, err := buildbucket.GetBuildLegacy(c.Context, address, true)
return renderBuildLegacy(c, build, true, err)
} | [
"func",
"handleLUCIBuildLegacy",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"bucket",
",",
"builder",
",",
"numberOrId",
"string",
")",
"error",
"{",
"var",
"address",
"string",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"numberOrId",
",",
"\"",
"\""... | // handleLUCIBuildLegacy renders a LUCI build. | [
"handleLUCIBuildLegacy",
"renders",
"a",
"LUCI",
"build",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_build_legacy.go#L80-L90 |
7,297 | luci/luci-go | milo/frontend/view_build_legacy.go | makeFeedbackLink | func makeFeedbackLink(c *router.Context, build *ui.MiloBuildLegacy) string {
project, err := common.GetProject(c.Context, c.Params.ByName("project"))
if err != nil || proto.Equal(&project.BuildBugTemplate, &config.BugTemplate{}) {
return ""
}
buildURL := c.Request.URL
var builderURL *url.URL
if build.Summary.ParentLabel != nil && build.Summary.ParentLabel.URL != "" {
builderURL, err = buildURL.Parse(build.Summary.ParentLabel.URL)
if err != nil {
logging.WithError(err).Errorf(c.Context, "Unable to parse build.Summary.ParentLabel.URL for custom feedback link")
return ""
}
}
link, err := buildbucket.MakeBuildBugLink(&project.BuildBugTemplate, map[string]interface{}{
"Build": makeBuild(c.Params, build),
"MiloBuildUrl": buildURL,
"MiloBuilderUrl": builderURL,
})
if err != nil {
logging.WithError(err).Errorf(c.Context, "Unable to make custom feedback link")
return ""
}
return link
} | go | func makeFeedbackLink(c *router.Context, build *ui.MiloBuildLegacy) string {
project, err := common.GetProject(c.Context, c.Params.ByName("project"))
if err != nil || proto.Equal(&project.BuildBugTemplate, &config.BugTemplate{}) {
return ""
}
buildURL := c.Request.URL
var builderURL *url.URL
if build.Summary.ParentLabel != nil && build.Summary.ParentLabel.URL != "" {
builderURL, err = buildURL.Parse(build.Summary.ParentLabel.URL)
if err != nil {
logging.WithError(err).Errorf(c.Context, "Unable to parse build.Summary.ParentLabel.URL for custom feedback link")
return ""
}
}
link, err := buildbucket.MakeBuildBugLink(&project.BuildBugTemplate, map[string]interface{}{
"Build": makeBuild(c.Params, build),
"MiloBuildUrl": buildURL,
"MiloBuilderUrl": builderURL,
})
if err != nil {
logging.WithError(err).Errorf(c.Context, "Unable to make custom feedback link")
return ""
}
return link
} | [
"func",
"makeFeedbackLink",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"build",
"*",
"ui",
".",
"MiloBuildLegacy",
")",
"string",
"{",
"project",
",",
"err",
":=",
"common",
".",
"GetProject",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Params",
".",
... | // makeFeedbackLink attempts to create the feedback link for the build page. If the
// project is not configured for a custom feedback link or an interpolation placeholder
// cannot be satisfied an empty string is returned. | [
"makeFeedbackLink",
"attempts",
"to",
"create",
"the",
"feedback",
"link",
"for",
"the",
"build",
"page",
".",
"If",
"the",
"project",
"is",
"not",
"configured",
"for",
"a",
"custom",
"feedback",
"link",
"or",
"an",
"interpolation",
"placeholder",
"cannot",
"b... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_build_legacy.go#L129-L157 |
7,298 | luci/luci-go | milo/frontend/view_build_legacy.go | makeBuild | func makeBuild(params httprouter.Params, build *ui.MiloBuildLegacy) *buildbucketpb.Build {
return &buildbucketpb.Build{
Builder: &buildbucketpb.BuilderID{
Project: build.Trigger.Project, // equivalent params.ByName("project")
Bucket: params.ByName("bucket"), // way to get from ui.MiloBuildLegacy so don't need params here?
Builder: build.Summary.ParentLabel.Label, // params.ByName("builder")
},
}
} | go | func makeBuild(params httprouter.Params, build *ui.MiloBuildLegacy) *buildbucketpb.Build {
return &buildbucketpb.Build{
Builder: &buildbucketpb.BuilderID{
Project: build.Trigger.Project, // equivalent params.ByName("project")
Bucket: params.ByName("bucket"), // way to get from ui.MiloBuildLegacy so don't need params here?
Builder: build.Summary.ParentLabel.Label, // params.ByName("builder")
},
}
} | [
"func",
"makeBuild",
"(",
"params",
"httprouter",
".",
"Params",
",",
"build",
"*",
"ui",
".",
"MiloBuildLegacy",
")",
"*",
"buildbucketpb",
".",
"Build",
"{",
"return",
"&",
"buildbucketpb",
".",
"Build",
"{",
"Builder",
":",
"&",
"buildbucketpb",
".",
"B... | // makeBuild partially populates a buildbucketpb.Build. Currently it attempts to
// make available .Builder.Project, .Builder.Bucket, and .Builder.Builder. | [
"makeBuild",
"partially",
"populates",
"a",
"buildbucketpb",
".",
"Build",
".",
"Currently",
"it",
"attempts",
"to",
"make",
"available",
".",
"Builder",
".",
"Project",
".",
"Builder",
".",
"Bucket",
"and",
".",
"Builder",
".",
"Builder",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_build_legacy.go#L161-L169 |
7,299 | luci/luci-go | lucicfg/graph/key.go | Less | func (k *Key) Less(an *Key) bool {
return k.cmp < an.cmp
} | go | func (k *Key) Less(an *Key) bool {
return k.cmp < an.cmp
} | [
"func",
"(",
"k",
"*",
"Key",
")",
"Less",
"(",
"an",
"*",
"Key",
")",
"bool",
"{",
"return",
"k",
".",
"cmp",
"<",
"an",
".",
"cmp",
"\n",
"}"
] | // Less returns true if this key is lexicographically before another key. | [
"Less",
"returns",
"true",
"if",
"this",
"key",
"is",
"lexicographically",
"before",
"another",
"key",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/key.go#L72-L74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.