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
9,200
luci/luci-go
gce/cmd/agent/swarming.go
fetch
func (s *SwarmingClient) fetch(c context.Context, path, user string) error { botCode := s.server + "/bot_code" logging.Infof(c, "downloading: %s", botCode) rsp, err := s.Get(botCode) if err != nil { return errors.Annotate(err, "failed to fetch bot code").Err() } defer rsp.Body.Close() if rsp.StatusCode != http.StatusOK { return errors.Reason("server returned %q", rsp.Status).Err() } logging.Infof(c, "installing: %s", path) // 0644 allows the bot code to be read by all users. // Useful when SSHing to the instance. out, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return errors.Annotate(err, "failed to open: %s", path).Err() } defer out.Close() _, err = io.Copy(out, rsp.Body) if err != nil { return errors.Annotate(err, "failed to write: %s", path).Err() } if err := s.chown(c, path, user); err != nil { return errors.Annotate(err, "failed to chown: %s", path).Err() } return nil }
go
func (s *SwarmingClient) fetch(c context.Context, path, user string) error { botCode := s.server + "/bot_code" logging.Infof(c, "downloading: %s", botCode) rsp, err := s.Get(botCode) if err != nil { return errors.Annotate(err, "failed to fetch bot code").Err() } defer rsp.Body.Close() if rsp.StatusCode != http.StatusOK { return errors.Reason("server returned %q", rsp.Status).Err() } logging.Infof(c, "installing: %s", path) // 0644 allows the bot code to be read by all users. // Useful when SSHing to the instance. out, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return errors.Annotate(err, "failed to open: %s", path).Err() } defer out.Close() _, err = io.Copy(out, rsp.Body) if err != nil { return errors.Annotate(err, "failed to write: %s", path).Err() } if err := s.chown(c, path, user); err != nil { return errors.Annotate(err, "failed to chown: %s", path).Err() } return nil }
[ "func", "(", "s", "*", "SwarmingClient", ")", "fetch", "(", "c", "context", ".", "Context", ",", "path", ",", "user", "string", ")", "error", "{", "botCode", ":=", "s", ".", "server", "+", "\"", "\"", "\n", "logging", ".", "Infof", "(", "c", ",", ...
// fetch fetches the Swarming bot code.
[ "fetch", "fetches", "the", "Swarming", "bot", "code", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/swarming.go#L52-L80
9,201
luci/luci-go
gce/cmd/agent/swarming.go
Configure
func (s *SwarmingClient) Configure(c context.Context, dir, user string) error { // 0755 allows the directory structure to be read and listed by all users. // Useful when SSHing fo the instance. if err := os.MkdirAll(dir, 0755); err != nil { return errors.Annotate(err, "failed to create: %s", dir).Err() } if err := s.chown(c, dir, user); err != nil { return errors.Annotate(err, "failed to chown: %s", dir).Err() } zip := filepath.Join(dir, "swarming_bot.zip") switch _, err := os.Stat(zip); { case os.IsNotExist(err): case err != nil: return errors.Annotate(err, "failed to stat: %s", zip).Err() default: logging.Infof(c, "already installed: %s", zip) return nil } if err := s.fetch(c, zip, user); err != nil { return err } return s.autostart(c, zip, user) }
go
func (s *SwarmingClient) Configure(c context.Context, dir, user string) error { // 0755 allows the directory structure to be read and listed by all users. // Useful when SSHing fo the instance. if err := os.MkdirAll(dir, 0755); err != nil { return errors.Annotate(err, "failed to create: %s", dir).Err() } if err := s.chown(c, dir, user); err != nil { return errors.Annotate(err, "failed to chown: %s", dir).Err() } zip := filepath.Join(dir, "swarming_bot.zip") switch _, err := os.Stat(zip); { case os.IsNotExist(err): case err != nil: return errors.Annotate(err, "failed to stat: %s", zip).Err() default: logging.Infof(c, "already installed: %s", zip) return nil } if err := s.fetch(c, zip, user); err != nil { return err } return s.autostart(c, zip, user) }
[ "func", "(", "s", "*", "SwarmingClient", ")", "Configure", "(", "c", "context", ".", "Context", ",", "dir", ",", "user", "string", ")", "error", "{", "// 0755 allows the directory structure to be read and listed by all users.", "// Useful when SSHing fo the instance.", "i...
// Configure fetches the Swarming bot code and configures it to run on startup.
[ "Configure", "fetches", "the", "Swarming", "bot", "code", "and", "configures", "it", "to", "run", "on", "startup", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/swarming.go#L83-L105
9,202
luci/luci-go
machine-db/appengine/config/config.go
Import
func Import(c context.Context) error { configSet := cfgclient.CurrentServiceConfigSet(c) if err := importOSes(c, configSet); err != nil { return errors.Annotate(err, "failed to import operating systems").Err() } platformIds, err := importPlatforms(c, configSet) if err != nil { return errors.Annotate(err, "failed to import platforms").Err() } if err := importVLANs(c, configSet); err != nil { return errors.Annotate(err, "failed to import vlans").Err() } if err := importDatacenters(c, configSet, platformIds); err != nil { return errors.Annotate(err, "failed to import datacenters").Err() } return nil }
go
func Import(c context.Context) error { configSet := cfgclient.CurrentServiceConfigSet(c) if err := importOSes(c, configSet); err != nil { return errors.Annotate(err, "failed to import operating systems").Err() } platformIds, err := importPlatforms(c, configSet) if err != nil { return errors.Annotate(err, "failed to import platforms").Err() } if err := importVLANs(c, configSet); err != nil { return errors.Annotate(err, "failed to import vlans").Err() } if err := importDatacenters(c, configSet, platformIds); err != nil { return errors.Annotate(err, "failed to import datacenters").Err() } return nil }
[ "func", "Import", "(", "c", "context", ".", "Context", ")", "error", "{", "configSet", ":=", "cfgclient", ".", "CurrentServiceConfigSet", "(", "c", ")", "\n", "if", "err", ":=", "importOSes", "(", "c", ",", "configSet", ")", ";", "err", "!=", "nil", "{...
// Import fetches, validates, and applies configs from the config service.
[ "Import", "fetches", "validates", "and", "applies", "configs", "from", "the", "config", "service", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/config/config.go#L41-L57
9,203
luci/luci-go
machine-db/appengine/config/config.go
InstallHandlers
func InstallHandlers(r *router.Router, middleware router.MiddlewareChain) { cronMiddleware := middleware.Extend(gaemiddleware.RequireCron) r.GET("/internal/cron/import-config", cronMiddleware, importHandler) }
go
func InstallHandlers(r *router.Router, middleware router.MiddlewareChain) { cronMiddleware := middleware.Extend(gaemiddleware.RequireCron) r.GET("/internal/cron/import-config", cronMiddleware, importHandler) }
[ "func", "InstallHandlers", "(", "r", "*", "router", ".", "Router", ",", "middleware", "router", ".", "MiddlewareChain", ")", "{", "cronMiddleware", ":=", "middleware", ".", "Extend", "(", "gaemiddleware", ".", "RequireCron", ")", "\n", "r", ".", "GET", "(", ...
// InstallHandlers installs handlers for HTTP requests pertaining to configs.
[ "InstallHandlers", "installs", "handlers", "for", "HTTP", "requests", "pertaining", "to", "configs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/config/config.go#L60-L63
9,204
luci/luci-go
logdog/appengine/cmd/coordinator/default/dummy_services.go
dummyServicePrelude
func dummyServicePrelude(c context.Context, methodName string, req proto.Message) (context.Context, error) { return nil, grpcutil.Errf(codes.FailedPrecondition, "This pRPC endpoint cannot be handled by the default service. It should have been routed to the "+ "appropriate service via dispatch. This error indicates that the routing is not working as intended. "+ "Please report this error to the maintainers.") }
go
func dummyServicePrelude(c context.Context, methodName string, req proto.Message) (context.Context, error) { return nil, grpcutil.Errf(codes.FailedPrecondition, "This pRPC endpoint cannot be handled by the default service. It should have been routed to the "+ "appropriate service via dispatch. This error indicates that the routing is not working as intended. "+ "Please report this error to the maintainers.") }
[ "func", "dummyServicePrelude", "(", "c", "context", ".", "Context", ",", "methodName", "string", ",", "req", "proto", ".", "Message", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "return", "nil", ",", "grpcutil", ".", "Errf", "(", "codes"...
// dummyServicePrelude is a service decorator prelude that always returns // "codes.FailedPrecondition". // This is implemented this way so that the decorated service can be made // discoverable without actually hosting an implementation of that service. // The actual implementation is hosted in a separate GAE service, and RPCs // directed directed at this dummy service should be automatically routed to // the implementing GAE service through "dispatch.yaml".
[ "dummyServicePrelude", "is", "a", "service", "decorator", "prelude", "that", "always", "returns", "codes", ".", "FailedPrecondition", ".", "This", "is", "implemented", "this", "way", "so", "that", "the", "decorated", "service", "can", "be", "made", "discoverable",...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/cmd/coordinator/default/dummy_services.go#L55-L60
9,205
luci/luci-go
mp/cmd/mpagent/main.go
configureAutoMount
func (agent *Agent) configureAutoMount(ctx context.Context, disk string) error { return agent.strategy.configureAutoMount(ctx, disk) }
go
func (agent *Agent) configureAutoMount(ctx context.Context, disk string) error { return agent.strategy.configureAutoMount(ctx, disk) }
[ "func", "(", "agent", "*", "Agent", ")", "configureAutoMount", "(", "ctx", "context", ".", "Context", ",", "disk", "string", ")", "error", "{", "return", "agent", ".", "strategy", ".", "configureAutoMount", "(", "ctx", ",", "disk", ")", "\n", "}" ]
// configureAutoMount mounts the specified disk and configures mount on startup. // // Assumes the disk is already formatted correctly.
[ "configureAutoMount", "mounts", "the", "specified", "disk", "and", "configures", "mount", "on", "startup", ".", "Assumes", "the", "disk", "is", "already", "formatted", "correctly", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L91-L93
9,206
luci/luci-go
mp/cmd/mpagent/main.go
configureLogging
func (agent *Agent) configureLogging(ctx context.Context) (context.Context, error) { log := fmt.Sprintf("agent.%s.log", strconv.FormatInt(time.Now().Unix(), 10)) if err := os.MkdirAll(agent.logsDir, 0755); err != nil { return ctx, err } // TODO(smut): Capture logging emitted before configureLogging was called and // write it to the log file. out, err := os.OpenFile(filepath.Join(agent.logsDir, log), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return ctx, err } config := gologger.LoggerConfig{Out: out} return teelogger.Use(ctx, config.NewLogger), nil }
go
func (agent *Agent) configureLogging(ctx context.Context) (context.Context, error) { log := fmt.Sprintf("agent.%s.log", strconv.FormatInt(time.Now().Unix(), 10)) if err := os.MkdirAll(agent.logsDir, 0755); err != nil { return ctx, err } // TODO(smut): Capture logging emitted before configureLogging was called and // write it to the log file. out, err := os.OpenFile(filepath.Join(agent.logsDir, log), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return ctx, err } config := gologger.LoggerConfig{Out: out} return teelogger.Use(ctx, config.NewLogger), nil }
[ "func", "(", "agent", "*", "Agent", ")", "configureLogging", "(", "ctx", "context", ".", "Context", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "log", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(...
// configureLogging configures logging to a file, in addition to any other logging. // // Returns modified context.Context.
[ "configureLogging", "configures", "logging", "to", "a", "file", "in", "addition", "to", "any", "other", "logging", ".", "Returns", "modified", "context", ".", "Context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L98-L112
9,207
luci/luci-go
mp/cmd/mpagent/main.go
configureMonitoring
func (agent *Agent) configureMonitoring(ctx context.Context) error { flags := tsmon.NewFlags() flags.Flush = "manual" flags.Target.AutoGenHostname = true flags.Target.TargetType = "task" flags.Target.TaskJobName = "default" flags.Target.TaskServiceName = "mpagent" return tsmon.InitializeFromFlags(ctx, &flags) }
go
func (agent *Agent) configureMonitoring(ctx context.Context) error { flags := tsmon.NewFlags() flags.Flush = "manual" flags.Target.AutoGenHostname = true flags.Target.TargetType = "task" flags.Target.TaskJobName = "default" flags.Target.TaskServiceName = "mpagent" return tsmon.InitializeFromFlags(ctx, &flags) }
[ "func", "(", "agent", "*", "Agent", ")", "configureMonitoring", "(", "ctx", "context", ".", "Context", ")", "error", "{", "flags", ":=", "tsmon", ".", "NewFlags", "(", ")", "\n", "flags", ".", "Flush", "=", "\"", "\"", "\n", "flags", ".", "Target", "...
// configureMonitoring configures tsmon monitoring.
[ "configureMonitoring", "configures", "tsmon", "monitoring", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L115-L123
9,208
luci/luci-go
mp/cmd/mpagent/main.go
configureSwarmingAutoStart
func (agent *Agent) configureSwarmingAutoStart(ctx context.Context, server string) error { if err := os.MkdirAll(agent.swarmingBotDir, 0755); err != nil { return err } if err := agent.strategy.chown(ctx, agent.swarmingUser, agent.swarmingBotDir); err != nil { return err } path := filepath.Join(agent.swarmingBotDir, "swarming_bot.zip") if err := agent.downloadSwarmingBotCode(ctx, server, path); err != nil { return err } substitutions := map[string]string{ "Path": path, "User": agent.swarmingUser, } content, err := substituteAsset(ctx, agent.swarmingAutoStartTemplate, substitutions) if err != nil { return err } path, err = substitute(ctx, agent.swarmingAutoStartPath, substitutions) if err != nil { return err } _, err = os.Stat(path) switch { case err == nil: logging.Infof(ctx, "Reinstalling: %s.", path) case os.IsNotExist(err): logging.Infof(ctx, "Installing: %s.", path) default: return err } if err := ioutil.WriteFile(path, []byte(content), 0644); err != nil { return err } return agent.strategy.enableSwarming(ctx) }
go
func (agent *Agent) configureSwarmingAutoStart(ctx context.Context, server string) error { if err := os.MkdirAll(agent.swarmingBotDir, 0755); err != nil { return err } if err := agent.strategy.chown(ctx, agent.swarmingUser, agent.swarmingBotDir); err != nil { return err } path := filepath.Join(agent.swarmingBotDir, "swarming_bot.zip") if err := agent.downloadSwarmingBotCode(ctx, server, path); err != nil { return err } substitutions := map[string]string{ "Path": path, "User": agent.swarmingUser, } content, err := substituteAsset(ctx, agent.swarmingAutoStartTemplate, substitutions) if err != nil { return err } path, err = substitute(ctx, agent.swarmingAutoStartPath, substitutions) if err != nil { return err } _, err = os.Stat(path) switch { case err == nil: logging.Infof(ctx, "Reinstalling: %s.", path) case os.IsNotExist(err): logging.Infof(ctx, "Installing: %s.", path) default: return err } if err := ioutil.WriteFile(path, []byte(content), 0644); err != nil { return err } return agent.strategy.enableSwarming(ctx) }
[ "func", "(", "agent", "*", "Agent", ")", "configureSwarmingAutoStart", "(", "ctx", "context", ".", "Context", ",", "server", "string", ")", "error", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "agent", ".", "swarmingBotDir", ",", "0755", ")", ";"...
// configureSwarmingAutoStart configures auto-connect to the given Swarming server on reboot.
[ "configureSwarmingAutoStart", "configures", "auto", "-", "connect", "to", "the", "given", "Swarming", "server", "on", "reboot", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L126-L164
9,209
luci/luci-go
mp/cmd/mpagent/main.go
downloadSwarmingBotCode
func (agent *Agent) downloadSwarmingBotCode(ctx context.Context, server, path string) error { _, err := os.Stat(path) if err == nil { logging.Infof(ctx, "Already installed: %s.", path) return nil } logging.Infof(ctx, "Downloading: %s.", path) response, err := agent.client.Get(server + "/bot_code") if err != nil { return err } defer response.Body.Close() if response.StatusCode != 200 { // TODO(smut): Differentiate between transient and non-transient. return errors.New("unexpected HTTP status: " + response.Status) } out, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } defer out.Close() _, err = io.Copy(out, response.Body) if err != nil { return err } return agent.strategy.chown(ctx, agent.swarmingUser, path) }
go
func (agent *Agent) downloadSwarmingBotCode(ctx context.Context, server, path string) error { _, err := os.Stat(path) if err == nil { logging.Infof(ctx, "Already installed: %s.", path) return nil } logging.Infof(ctx, "Downloading: %s.", path) response, err := agent.client.Get(server + "/bot_code") if err != nil { return err } defer response.Body.Close() if response.StatusCode != 200 { // TODO(smut): Differentiate between transient and non-transient. return errors.New("unexpected HTTP status: " + response.Status) } out, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } defer out.Close() _, err = io.Copy(out, response.Body) if err != nil { return err } return agent.strategy.chown(ctx, agent.swarmingUser, path) }
[ "func", "(", "agent", "*", "Agent", ")", "downloadSwarmingBotCode", "(", "ctx", "context", ".", "Context", ",", "server", ",", "path", "string", ")", "error", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", "\n", "if", "err", "==", ...
// downloadSwarminBotCode downloads the Swarming bot code from the given server.
[ "downloadSwarminBotCode", "downloads", "the", "Swarming", "bot", "code", "from", "the", "given", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L167-L194
9,210
luci/luci-go
mp/cmd/mpagent/main.go
initialize
func (agent *Agent) initialize(ctx context.Context) (context.Context, error) { ctx, err := agent.configureLogging(ctx) if err != nil { return ctx, err } if err = agent.configureMonitoring(ctx); err != nil { return ctx, err } // TODO(smut): Remove fallback on metadata server. if agent.server == "" { agent.server, err = metadata.Get("instance/attributes/machine_provider_server") if err != nil { return ctx, err } } if agent.serviceAccount == "" { agent.serviceAccount, err = metadata.Get("instance/attributes/machine_service_account") if err != nil { return ctx, err } } options := auth.Options{ GCEAccountName: agent.serviceAccount, ServiceAccountJSONPath: auth.GCEServiceAccount, } agent.client, err = auth.NewAuthenticator(ctx, auth.SilentLogin, options).Client() if err != nil { return ctx, err } metadataClient := metadata.NewClient(agent.client) agent.hostname, err = metadataClient.InstanceName() if err != nil { return ctx, err } agent.mp, err = getClient(ctx, agent.client, agent.server) if err != nil { return ctx, err } return ctx, nil }
go
func (agent *Agent) initialize(ctx context.Context) (context.Context, error) { ctx, err := agent.configureLogging(ctx) if err != nil { return ctx, err } if err = agent.configureMonitoring(ctx); err != nil { return ctx, err } // TODO(smut): Remove fallback on metadata server. if agent.server == "" { agent.server, err = metadata.Get("instance/attributes/machine_provider_server") if err != nil { return ctx, err } } if agent.serviceAccount == "" { agent.serviceAccount, err = metadata.Get("instance/attributes/machine_service_account") if err != nil { return ctx, err } } options := auth.Options{ GCEAccountName: agent.serviceAccount, ServiceAccountJSONPath: auth.GCEServiceAccount, } agent.client, err = auth.NewAuthenticator(ctx, auth.SilentLogin, options).Client() if err != nil { return ctx, err } metadataClient := metadata.NewClient(agent.client) agent.hostname, err = metadataClient.InstanceName() if err != nil { return ctx, err } agent.mp, err = getClient(ctx, agent.client, agent.server) if err != nil { return ctx, err } return ctx, nil }
[ "func", "(", "agent", "*", "Agent", ")", "initialize", "(", "ctx", "context", ".", "Context", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "ctx", ",", "err", ":=", "agent", ".", "configureLogging", "(", "ctx", ")", "\n", "if", "err", ...
// initialize initializes the agent.
[ "initialize", "initializes", "the", "agent", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L197-L238
9,211
luci/luci-go
mp/cmd/mpagent/main.go
install
func (agent *Agent) install(ctx context.Context) error { exe, err := os.Executable() if err != nil { return err } substitutions := map[string]string{ "Agent": exe, "Server": agent.server, "ServiceAccount": agent.serviceAccount, "User": agent.swarmingUser, } content, err := substituteAsset(ctx, agent.agentAutoStartTemplate, substitutions) if err != nil { return err } path, err := substitute(ctx, agent.agentAutoStartPath, substitutions) if err != nil { return err } _, err = os.Stat(path) if err == nil || os.IsExist(err) { bytes, err := ioutil.ReadFile(path) if err != nil { return err } if string(bytes) == content { logging.Infof(ctx, "Already installed: %s.", path) return nil } logging.Infof(ctx, "Reinstalling: %s.", path) if err = agent.strategy.stop(ctx); err != nil { return err } } else { logging.Infof(ctx, "Installing: %s.", path) } if err = ioutil.WriteFile(path, []byte(content), 0644); err != nil { return err } return agent.strategy.start(ctx, path) }
go
func (agent *Agent) install(ctx context.Context) error { exe, err := os.Executable() if err != nil { return err } substitutions := map[string]string{ "Agent": exe, "Server": agent.server, "ServiceAccount": agent.serviceAccount, "User": agent.swarmingUser, } content, err := substituteAsset(ctx, agent.agentAutoStartTemplate, substitutions) if err != nil { return err } path, err := substitute(ctx, agent.agentAutoStartPath, substitutions) if err != nil { return err } _, err = os.Stat(path) if err == nil || os.IsExist(err) { bytes, err := ioutil.ReadFile(path) if err != nil { return err } if string(bytes) == content { logging.Infof(ctx, "Already installed: %s.", path) return nil } logging.Infof(ctx, "Reinstalling: %s.", path) if err = agent.strategy.stop(ctx); err != nil { return err } } else { logging.Infof(ctx, "Installing: %s.", path) } if err = ioutil.WriteFile(path, []byte(content), 0644); err != nil { return err } return agent.strategy.start(ctx, path) }
[ "func", "(", "agent", "*", "Agent", ")", "install", "(", "ctx", "context", ".", "Context", ")", "error", "{", "exe", ",", "err", ":=", "os", ".", "Executable", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "su...
// install installs the agent, starts it, and configures auto-start on reboot.
[ "install", "installs", "the", "agent", "starts", "it", "and", "configures", "auto", "-", "start", "on", "reboot", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L241-L283
9,212
luci/luci-go
mp/cmd/mpagent/main.go
poll
func (agent *Agent) poll(ctx context.Context) error { // Metadata tells us which Machine Provider instance to talk to // and how to authenticate. for { logging.Infof(ctx, "Polling.") instruction, err := agent.mp.poll(ctx, agent.hostname, "GCE") if err != nil { // Log error but don't return. Keep polling. logging.Errorf(ctx, "%s", err.Error()) } else { if err = agent.handle(ctx, instruction); err != nil { return err } } tsmon.Flush(ctx) time.Sleep(time.Minute) } }
go
func (agent *Agent) poll(ctx context.Context) error { // Metadata tells us which Machine Provider instance to talk to // and how to authenticate. for { logging.Infof(ctx, "Polling.") instruction, err := agent.mp.poll(ctx, agent.hostname, "GCE") if err != nil { // Log error but don't return. Keep polling. logging.Errorf(ctx, "%s", err.Error()) } else { if err = agent.handle(ctx, instruction); err != nil { return err } } tsmon.Flush(ctx) time.Sleep(time.Minute) } }
[ "func", "(", "agent", "*", "Agent", ")", "poll", "(", "ctx", "context", ".", "Context", ")", "error", "{", "// Metadata tells us which Machine Provider instance to talk to", "// and how to authenticate.", "for", "{", "logging", ".", "Infof", "(", "ctx", ",", "\"", ...
// poll polls for instructions from Machine Provider. // // Does not return except in case of error.
[ "poll", "polls", "for", "instructions", "from", "Machine", "Provider", ".", "Does", "not", "return", "except", "in", "case", "of", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L288-L305
9,213
luci/luci-go
mp/cmd/mpagent/main.go
handle
func (agent *Agent) handle(ctx context.Context, instruction *machine.ComponentsMachineProviderRpcMessagesPollResponse) error { if instruction.State == "" || instruction.State == "EXECUTED" { return nil } // The only type of instruction that exists is to connect to Swarming. if instruction.Instruction == nil || instruction.Instruction.SwarmingServer == "" { return nil } logging.Infof(ctx, "Received new instruction:\n%s", instruction) start := time.Now() if err := agent.configureSwarmingAutoStart(ctx, instruction.Instruction.SwarmingServer); err != nil { return err } if err := agent.mp.ack(ctx, agent.hostname, "GCE"); err != nil { return err } duration := float64(time.Since(start)) / float64(time.Second) instructionsAcked.Add(ctx, 1, agent.server, instruction.Instruction.SwarmingServer) instructionsAckedTime.Add(ctx, duration, agent.server, instruction.Instruction.SwarmingServer) return agent.reboot(ctx) }
go
func (agent *Agent) handle(ctx context.Context, instruction *machine.ComponentsMachineProviderRpcMessagesPollResponse) error { if instruction.State == "" || instruction.State == "EXECUTED" { return nil } // The only type of instruction that exists is to connect to Swarming. if instruction.Instruction == nil || instruction.Instruction.SwarmingServer == "" { return nil } logging.Infof(ctx, "Received new instruction:\n%s", instruction) start := time.Now() if err := agent.configureSwarmingAutoStart(ctx, instruction.Instruction.SwarmingServer); err != nil { return err } if err := agent.mp.ack(ctx, agent.hostname, "GCE"); err != nil { return err } duration := float64(time.Since(start)) / float64(time.Second) instructionsAcked.Add(ctx, 1, agent.server, instruction.Instruction.SwarmingServer) instructionsAckedTime.Add(ctx, duration, agent.server, instruction.Instruction.SwarmingServer) return agent.reboot(ctx) }
[ "func", "(", "agent", "*", "Agent", ")", "handle", "(", "ctx", "context", ".", "Context", ",", "instruction", "*", "machine", ".", "ComponentsMachineProviderRpcMessagesPollResponse", ")", "error", "{", "if", "instruction", ".", "State", "==", "\"", "\"", "||",...
// handle handles a received instruction.
[ "handle", "handles", "a", "received", "instruction", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L308-L330
9,214
luci/luci-go
mp/cmd/mpagent/main.go
reboot
func (agent *Agent) reboot(ctx context.Context) error { logging.Infof(ctx, "Rebooting.") tsmon.Flush(ctx) for { if err := agent.strategy.reboot(ctx); err != nil { return err } time.Sleep(60 * time.Second) logging.Infof(ctx, "Waiting to reboot...") } }
go
func (agent *Agent) reboot(ctx context.Context) error { logging.Infof(ctx, "Rebooting.") tsmon.Flush(ctx) for { if err := agent.strategy.reboot(ctx); err != nil { return err } time.Sleep(60 * time.Second) logging.Infof(ctx, "Waiting to reboot...") } }
[ "func", "(", "agent", "*", "Agent", ")", "reboot", "(", "ctx", "context", ".", "Context", ")", "error", "{", "logging", ".", "Infof", "(", "ctx", ",", "\"", "\"", ")", "\n", "tsmon", ".", "Flush", "(", "ctx", ")", "\n", "for", "{", "if", "err", ...
// reboot attempts to reboot the machine. // // Does not return except in case of error.
[ "reboot", "attempts", "to", "reboot", "the", "machine", ".", "Does", "not", "return", "except", "in", "case", "of", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/main.go#L335-L345
9,215
luci/luci-go
common/isolated/algo.go
GetHash
func GetHash(namespace string) crypto.Hash { if strings.HasPrefix(namespace, "sha256-") { return crypto.SHA256 } if strings.HasPrefix(namespace, "sha512-") { return crypto.SHA512 } return crypto.SHA1 }
go
func GetHash(namespace string) crypto.Hash { if strings.HasPrefix(namespace, "sha256-") { return crypto.SHA256 } if strings.HasPrefix(namespace, "sha512-") { return crypto.SHA512 } return crypto.SHA1 }
[ "func", "GetHash", "(", "namespace", "string", ")", "crypto", ".", "Hash", "{", "if", "strings", ".", "HasPrefix", "(", "namespace", ",", "\"", "\"", ")", "{", "return", "crypto", ".", "SHA256", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", ...
// GetHash returns a fresh instance of the hashing algorithm to be used to // calculate the HexDigest. // // A prefix of "sha256-" and "sha512-" respectively returns a sha-256 and // sha-512 instance. Otherwise a sha-1 instance is returned.
[ "GetHash", "returns", "a", "fresh", "instance", "of", "the", "hashing", "algorithm", "to", "be", "used", "to", "calculate", "the", "HexDigest", ".", "A", "prefix", "of", "sha256", "-", "and", "sha512", "-", "respectively", "returns", "a", "sha", "-", "256"...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolated/algo.go#L32-L40
9,216
luci/luci-go
common/isolated/algo.go
Validate
func (d HexDigest) Validate(h crypto.Hash) bool { if l := h.Size() * 2; len(d) != l { return false } for _, c := range d { if ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') { continue } return false } return true }
go
func (d HexDigest) Validate(h crypto.Hash) bool { if l := h.Size() * 2; len(d) != l { return false } for _, c := range d { if ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') { continue } return false } return true }
[ "func", "(", "d", "HexDigest", ")", "Validate", "(", "h", "crypto", ".", "Hash", ")", "bool", "{", "if", "l", ":=", "h", ".", "Size", "(", ")", "*", "2", ";", "len", "(", "d", ")", "!=", "l", "{", "return", "false", "\n", "}", "\n", "for", ...
// Validate returns true if the hash is valid.
[ "Validate", "returns", "true", "if", "the", "hash", "is", "valid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolated/algo.go#L72-L83
9,217
luci/luci-go
server/portal/page.go
ReadSettings
func (BasePage) ReadSettings(c context.Context) (map[string]string, error) { return nil, nil }
go
func (BasePage) ReadSettings(c context.Context) (map[string]string, error) { return nil, nil }
[ "func", "(", "BasePage", ")", "ReadSettings", "(", "c", "context", ".", "Context", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "nil", ",", "nil", "\n", "}" ]
// ReadSettings returns a map "field ID => field value to display".
[ "ReadSettings", "returns", "a", "map", "field", "ID", "=", ">", "field", "value", "to", "display", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/portal/page.go#L126-L128
9,218
luci/luci-go
server/portal/page.go
WriteSettings
func (BasePage) WriteSettings(c context.Context, values map[string]string, who, why string) error { return errors.New("not implemented") }
go
func (BasePage) WriteSettings(c context.Context, values map[string]string, who, why string) error { return errors.New("not implemented") }
[ "func", "(", "BasePage", ")", "WriteSettings", "(", "c", "context", ".", "Context", ",", "values", "map", "[", "string", "]", "string", ",", "who", ",", "why", "string", ")", "error", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", ...
// WriteSettings saves settings described as a map "field ID => field value".
[ "WriteSettings", "saves", "settings", "described", "as", "a", "map", "field", "ID", "=", ">", "field", "value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/portal/page.go#L131-L133
9,219
luci/luci-go
config/server/cfgclient/naming.go
CurrentServiceConfigSet
func CurrentServiceConfigSet(c context.Context) config.Set { return config.ServiceSet(CurrentServiceName(c)) }
go
func CurrentServiceConfigSet(c context.Context) config.Set { return config.ServiceSet(CurrentServiceName(c)) }
[ "func", "CurrentServiceConfigSet", "(", "c", "context", ".", "Context", ")", "config", ".", "Set", "{", "return", "config", ".", "ServiceSet", "(", "CurrentServiceName", "(", "c", ")", ")", "\n", "}" ]
// CurrentServiceConfigSet returns the config set for the current AppEngine // service, based on its current service name.
[ "CurrentServiceConfigSet", "returns", "the", "config", "set", "for", "the", "current", "AppEngine", "service", "based", "on", "its", "current", "service", "name", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/naming.go#L33-L35
9,220
luci/luci-go
machine-db/client/cli/states.go
Run
func (c *GetStatesCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { if c.prefix == "" { if !c.f.tsv { fmt.Println("State") } for _, state := range common.ValidStates() { fmt.Println(state.Name()) } return 0 } state, err := common.GetState(c.prefix) if err != nil { return 1 } if !c.f.tsv { fmt.Println("State") } fmt.Println(state.Name()) return 0 }
go
func (c *GetStatesCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { if c.prefix == "" { if !c.f.tsv { fmt.Println("State") } for _, state := range common.ValidStates() { fmt.Println(state.Name()) } return 0 } state, err := common.GetState(c.prefix) if err != nil { return 1 } if !c.f.tsv { fmt.Println("State") } fmt.Println(state.Name()) return 0 }
[ "func", "(", "c", "*", "GetStatesCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "if", "c", ".", "prefix", "==", "\"", "\"", "{", "if", "!", ...
// Run runs the command to get state.
[ "Run", "runs", "the", "command", "to", "get", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/states.go#L32-L51
9,221
luci/luci-go
machine-db/client/cli/states.go
getStatesCmd
func getStatesCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-states [-prefix <prefix>]", ShortDesc: "retrieves states", LongDesc: "Retrieves the state matching the given prefix, or all states if prefix is omitted.\n\nExample:\ncrimson get-states", CommandRun: func() subcommands.CommandRun { cmd := &GetStatesCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.prefix, "prefix", "", "Prefix to get the matching state for.") return cmd }, } }
go
func getStatesCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-states [-prefix <prefix>]", ShortDesc: "retrieves states", LongDesc: "Retrieves the state matching the given prefix, or all states if prefix is omitted.\n\nExample:\ncrimson get-states", CommandRun: func() subcommands.CommandRun { cmd := &GetStatesCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.prefix, "prefix", "", "Prefix to get the matching state for.") return cmd }, } }
[ "func", "getStatesCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n",...
// getStatesCmd returns a command to get states.
[ "getStatesCmd", "returns", "a", "command", "to", "get", "states", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/states.go#L54-L66
9,222
luci/luci-go
buildbucket/cli/ls.go
parseSearchRequests
func (r *lsRun) parseSearchRequests(ctx context.Context, args []string) ([]*pb.SearchBuildsRequest, error) { baseReq, err := r.parseBaseRequest(ctx) if err != nil { return nil, err } if len(args) == 0 { return []*pb.SearchBuildsRequest{baseReq}, nil } ret := make([]*pb.SearchBuildsRequest, len(args)) for i, path := range args { ret[i] = proto.Clone(baseReq).(*pb.SearchBuildsRequest) var err error if ret[i].Predicate.Builder, err = r.parsePath(path); err != nil { return nil, fmt.Errorf("invalid path %q: %s", path, err) } } return ret, nil }
go
func (r *lsRun) parseSearchRequests(ctx context.Context, args []string) ([]*pb.SearchBuildsRequest, error) { baseReq, err := r.parseBaseRequest(ctx) if err != nil { return nil, err } if len(args) == 0 { return []*pb.SearchBuildsRequest{baseReq}, nil } ret := make([]*pb.SearchBuildsRequest, len(args)) for i, path := range args { ret[i] = proto.Clone(baseReq).(*pb.SearchBuildsRequest) var err error if ret[i].Predicate.Builder, err = r.parsePath(path); err != nil { return nil, fmt.Errorf("invalid path %q: %s", path, err) } } return ret, nil }
[ "func", "(", "r", "*", "lsRun", ")", "parseSearchRequests", "(", "ctx", "context", ".", "Context", ",", "args", "[", "]", "string", ")", "(", "[", "]", "*", "pb", ".", "SearchBuildsRequest", ",", "error", ")", "{", "baseReq", ",", "err", ":=", "r", ...
// parseSearchRequests converts flags and arguments to search requests.
[ "parseSearchRequests", "converts", "flags", "and", "arguments", "to", "search", "requests", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/ls.go#L148-L167
9,223
luci/luci-go
buildbucket/cli/ls.go
parseBaseRequest
func (r *lsRun) parseBaseRequest(ctx context.Context) (*pb.SearchBuildsRequest, error) { ret := &pb.SearchBuildsRequest{ Predicate: &pb.BuildPredicate{ Tags: r.Tags(), Status: r.status, IncludeExperimental: r.includeExperimental, }, PageSize: 100, } if r.limit > 0 && r.limit < int(ret.PageSize) { ret.PageSize = int32(r.limit) } // Prepare a field mask. var err error ret.Fields, err = r.FieldMask() if err != nil { return nil, err } for i, p := range ret.Fields.Paths { ret.Fields.Paths[i] = "builds.*." + p } if ret.Predicate.GerritChanges, err = r.clsFlag.retrieveCLs(ctx, r.httpClient, kRequirePatchset); err != nil { return nil, err } return ret, nil }
go
func (r *lsRun) parseBaseRequest(ctx context.Context) (*pb.SearchBuildsRequest, error) { ret := &pb.SearchBuildsRequest{ Predicate: &pb.BuildPredicate{ Tags: r.Tags(), Status: r.status, IncludeExperimental: r.includeExperimental, }, PageSize: 100, } if r.limit > 0 && r.limit < int(ret.PageSize) { ret.PageSize = int32(r.limit) } // Prepare a field mask. var err error ret.Fields, err = r.FieldMask() if err != nil { return nil, err } for i, p := range ret.Fields.Paths { ret.Fields.Paths[i] = "builds.*." + p } if ret.Predicate.GerritChanges, err = r.clsFlag.retrieveCLs(ctx, r.httpClient, kRequirePatchset); err != nil { return nil, err } return ret, nil }
[ "func", "(", "r", "*", "lsRun", ")", "parseBaseRequest", "(", "ctx", "context", ".", "Context", ")", "(", "*", "pb", ".", "SearchBuildsRequest", ",", "error", ")", "{", "ret", ":=", "&", "pb", ".", "SearchBuildsRequest", "{", "Predicate", ":", "&", "pb...
// parseBaseRequest returns a base SearchBuildsRequest without builder filter.
[ "parseBaseRequest", "returns", "a", "base", "SearchBuildsRequest", "without", "builder", "filter", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/ls.go#L170-L198
9,224
luci/luci-go
common/data/cmpbin/string.go
WriteString
func WriteString(buf io.ByteWriter, s string) (n int, err error) { return WriteBytes(buf, []byte(s)) }
go
func WriteString(buf io.ByteWriter, s string) (n int, err error) { return WriteBytes(buf, []byte(s)) }
[ "func", "WriteString", "(", "buf", "io", ".", "ByteWriter", ",", "s", "string", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "WriteBytes", "(", "buf", ",", "[", "]", "byte", "(", "s", ")", ")", "\n", "}" ]
// WriteString writes an encoded string to buf, returning the number of bytes // written, and any write error encountered.
[ "WriteString", "writes", "an", "encoded", "string", "to", "buf", "returning", "the", "number", "of", "bytes", "written", "and", "any", "write", "error", "encountered", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/cmpbin/string.go#L35-L37
9,225
luci/luci-go
common/data/cmpbin/string.go
ReadString
func ReadString(buf io.ByteReader) (ret string, n int, err error) { b, n, err := ReadBytes(buf) if err != nil { return } ret = string(b) return }
go
func ReadString(buf io.ByteReader) (ret string, n int, err error) { b, n, err := ReadBytes(buf) if err != nil { return } ret = string(b) return }
[ "func", "ReadString", "(", "buf", "io", ".", "ByteReader", ")", "(", "ret", "string", ",", "n", "int", ",", "err", "error", ")", "{", "b", ",", "n", ",", "err", ":=", "ReadBytes", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// ReadString reads an encoded string from buf, returning the number of bytes // read, and any read error encountered.
[ "ReadString", "reads", "an", "encoded", "string", "from", "buf", "returning", "the", "number", "of", "bytes", "read", "and", "any", "read", "error", "encountered", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/cmpbin/string.go#L41-L48
9,226
luci/luci-go
common/gcloud/gs/gs.go
NewProdClient
func NewProdClient(ctx context.Context, rt http.RoundTripper) (Client, error) { c := prodClient{ Context: ctx, rt: rt, } var err error c.baseClient, err = c.newClient() if err != nil { return nil, err } return &c, nil }
go
func NewProdClient(ctx context.Context, rt http.RoundTripper) (Client, error) { c := prodClient{ Context: ctx, rt: rt, } var err error c.baseClient, err = c.newClient() if err != nil { return nil, err } return &c, nil }
[ "func", "NewProdClient", "(", "ctx", "context", ".", "Context", ",", "rt", "http", ".", "RoundTripper", ")", "(", "Client", ",", "error", ")", "{", "c", ":=", "prodClient", "{", "Context", ":", "ctx", ",", "rt", ":", "rt", ",", "}", "\n", "var", "e...
// NewProdClient creates a new Client instance that uses production Cloud // Storage. // // The supplied RoundTripper will be used to make connections. If nil, the // default HTTP client will be used.
[ "NewProdClient", "creates", "a", "new", "Client", "instance", "that", "uses", "production", "Cloud", "Storage", ".", "The", "supplied", "RoundTripper", "will", "be", "used", "to", "make", "connections", ".", "If", "nil", "the", "default", "HTTP", "client", "wi...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/gs/gs.go#L95-L106
9,227
luci/luci-go
milo/frontend/ui/build_legacy.go
fixComponentDuration
func fixComponentDuration(c context.Context, comp *BuildComponent) Interval { // Leaf nodes do not require fixing. if len(comp.Children) == 0 { return comp.ExecutionTime } // Set start and end times to be out of bounds. // Each variable can have 3 states: // 1. Undefined. In which case they're set to farFuture/PastTime // 2. Current (fin only). In which case it's set to zero time (time.Time{}) // 3. Definite. In which case it's set to a time that isn't either of the above. start := farFutureTime fin := farPastTime for _, subcomp := range comp.Children { i := fixComponentDuration(c, subcomp) if i.Started.Before(start) { start = i.Started } switch { case fin.IsZero(): continue // fin is current, it can't get any farther in the future than that. case i.Finished.IsZero(), i.Finished.After(fin): fin = i.Finished // Both of these cased are considered "after". } } comp.ExecutionTime = NewInterval(c, start, fin) return comp.ExecutionTime }
go
func fixComponentDuration(c context.Context, comp *BuildComponent) Interval { // Leaf nodes do not require fixing. if len(comp.Children) == 0 { return comp.ExecutionTime } // Set start and end times to be out of bounds. // Each variable can have 3 states: // 1. Undefined. In which case they're set to farFuture/PastTime // 2. Current (fin only). In which case it's set to zero time (time.Time{}) // 3. Definite. In which case it's set to a time that isn't either of the above. start := farFutureTime fin := farPastTime for _, subcomp := range comp.Children { i := fixComponentDuration(c, subcomp) if i.Started.Before(start) { start = i.Started } switch { case fin.IsZero(): continue // fin is current, it can't get any farther in the future than that. case i.Finished.IsZero(), i.Finished.After(fin): fin = i.Finished // Both of these cased are considered "after". } } comp.ExecutionTime = NewInterval(c, start, fin) return comp.ExecutionTime }
[ "func", "fixComponentDuration", "(", "c", "context", ".", "Context", ",", "comp", "*", "BuildComponent", ")", "Interval", "{", "// Leaf nodes do not require fixing.", "if", "len", "(", "comp", ".", "Children", ")", "==", "0", "{", "return", "comp", ".", "Execu...
// fixComponentDuration makes all parent steps have the max duration of all // of its children.
[ "fixComponentDuration", "makes", "all", "parent", "steps", "have", "the", "max", "duration", "of", "all", "of", "its", "children", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build_legacy.go#L123-L149
9,228
luci/luci-go
milo/frontend/ui/build_legacy.go
BuildSummary
func (b *MiloBuildLegacy) BuildSummary() *BuildSummary { if b == nil { return nil } result := &BuildSummary{ Link: b.Summary.Label, Status: b.Summary.Status, PendingTime: b.Summary.PendingTime, ExecutionTime: b.Summary.ExecutionTime, Text: b.Summary.Text, Blame: b.Blame, } if b.Trigger != nil { result.Revision = &b.Trigger.Commit } return result }
go
func (b *MiloBuildLegacy) BuildSummary() *BuildSummary { if b == nil { return nil } result := &BuildSummary{ Link: b.Summary.Label, Status: b.Summary.Status, PendingTime: b.Summary.PendingTime, ExecutionTime: b.Summary.ExecutionTime, Text: b.Summary.Text, Blame: b.Blame, } if b.Trigger != nil { result.Revision = &b.Trigger.Commit } return result }
[ "func", "(", "b", "*", "MiloBuildLegacy", ")", "BuildSummary", "(", ")", "*", "BuildSummary", "{", "if", "b", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "result", ":=", "&", "BuildSummary", "{", "Link", ":", "b", ".", "Summary", ".", "Label"...
// BuildSummary returns the BuildSummary representation of the MiloBuildLegacy. This // is the subset of fields that is interesting to the builder view.
[ "BuildSummary", "returns", "the", "BuildSummary", "representation", "of", "the", "MiloBuildLegacy", ".", "This", "is", "the", "subset", "of", "fields", "that", "is", "interesting", "to", "the", "builder", "view", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build_legacy.go#L176-L192
9,229
luci/luci-go
common/gcloud/iam/policy.go
GrantRole
func (p *Policy) GrantRole(role string, principals ...string) { if len(principals) == 0 { return } if p.Bindings == nil { p.Bindings = make(PolicyBindings, 1) } members := p.Bindings[role] if members == nil { members = make(membersSet, len(principals)) p.Bindings[role] = members } for _, principal := range principals { members[principal] = struct{}{} } }
go
func (p *Policy) GrantRole(role string, principals ...string) { if len(principals) == 0 { return } if p.Bindings == nil { p.Bindings = make(PolicyBindings, 1) } members := p.Bindings[role] if members == nil { members = make(membersSet, len(principals)) p.Bindings[role] = members } for _, principal := range principals { members[principal] = struct{}{} } }
[ "func", "(", "p", "*", "Policy", ")", "GrantRole", "(", "role", "string", ",", "principals", "...", "string", ")", "{", "if", "len", "(", "principals", ")", "==", "0", "{", "return", "\n", "}", "\n", "if", "p", ".", "Bindings", "==", "nil", "{", ...
// GrantRole grants a role to the given set of principals.
[ "GrantRole", "grants", "a", "role", "to", "the", "given", "set", "of", "principals", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/iam/policy.go#L146-L161
9,230
luci/luci-go
common/gcloud/iam/policy.go
RevokeRole
func (p *Policy) RevokeRole(role string, principals ...string) { members := p.Bindings[role] for _, principal := range principals { delete(members, principal) } }
go
func (p *Policy) RevokeRole(role string, principals ...string) { members := p.Bindings[role] for _, principal := range principals { delete(members, principal) } }
[ "func", "(", "p", "*", "Policy", ")", "RevokeRole", "(", "role", "string", ",", "principals", "...", "string", ")", "{", "members", ":=", "p", ".", "Bindings", "[", "role", "]", "\n", "for", "_", ",", "principal", ":=", "range", "principals", "{", "d...
// RevokeRole removes a role from the given set of principals.
[ "RevokeRole", "removes", "a", "role", "from", "the", "given", "set", "of", "principals", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/iam/policy.go#L164-L169
9,231
luci/luci-go
server/auth/service/service.go
Acknowledge
func (n *Notification) Acknowledge(c context.Context) error { if n.service != nil { // may be nil if Notification is generated in tests return n.service.ackMessages(c, n.subscription, n.ackIDs) } return nil }
go
func (n *Notification) Acknowledge(c context.Context) error { if n.service != nil { // may be nil if Notification is generated in tests return n.service.ackMessages(c, n.subscription, n.ackIDs) } return nil }
[ "func", "(", "n", "*", "Notification", ")", "Acknowledge", "(", "c", "context", ".", "Context", ")", "error", "{", "if", "n", ".", "service", "!=", "nil", "{", "// may be nil if Notification is generated in tests", "return", "n", ".", "service", ".", "ackMessa...
// Acknowledge tells PubSub to stop redelivering this notification.
[ "Acknowledge", "tells", "PubSub", "to", "stop", "redelivering", "this", "notification", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/service.go#L56-L61
9,232
luci/luci-go
server/auth/service/service.go
pubSubURL
func (s *AuthService) pubSubURL(path string) string { if s.pubSubURLRoot != "" { return s.pubSubURLRoot + path } return "https://pubsub.googleapis.com/v1/" + path }
go
func (s *AuthService) pubSubURL(path string) string { if s.pubSubURLRoot != "" { return s.pubSubURLRoot + path } return "https://pubsub.googleapis.com/v1/" + path }
[ "func", "(", "s", "*", "AuthService", ")", "pubSubURL", "(", "path", "string", ")", "string", "{", "if", "s", ".", "pubSubURLRoot", "!=", "\"", "\"", "{", "return", "s", ".", "pubSubURLRoot", "+", "path", "\n", "}", "\n", "return", "\"", "\"", "+", ...
// pubSubURL returns full URL to pubsub API endpoint.
[ "pubSubURL", "returns", "full", "URL", "to", "pubsub", "API", "endpoint", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/service.go#L95-L100
9,233
luci/luci-go
server/auth/service/service.go
DeleteSubscription
func (s *AuthService) DeleteSubscription(c context.Context, subscription string) error { var reply struct { Error struct { Code int `json:"code"` } `json:"error"` } req := internal.Request{ Method: "DELETE", URL: s.pubSubURL(subscription), Scopes: oauthScopes, Out: &reply, } if err := req.Do(c); err != nil && reply.Error.Code != 404 { return err } return nil }
go
func (s *AuthService) DeleteSubscription(c context.Context, subscription string) error { var reply struct { Error struct { Code int `json:"code"` } `json:"error"` } req := internal.Request{ Method: "DELETE", URL: s.pubSubURL(subscription), Scopes: oauthScopes, Out: &reply, } if err := req.Do(c); err != nil && reply.Error.Code != 404 { return err } return nil }
[ "func", "(", "s", "*", "AuthService", ")", "DeleteSubscription", "(", "c", "context", ".", "Context", ",", "subscription", "string", ")", "error", "{", "var", "reply", "struct", "{", "Error", "struct", "{", "Code", "int", "`json:\"code\"`", "\n", "}", "`js...
// DeleteSubscription removes PubSub subscription if it exists.
[ "DeleteSubscription", "removes", "PubSub", "subscription", "if", "it", "exists", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/service.go#L189-L205
9,234
luci/luci-go
server/auth/service/service.go
ackMessages
func (s *AuthService) ackMessages(c context.Context, subscription string, ackIDs []string) error { if len(ackIDs) == 0 { return nil } request := struct { AckIDs []string `json:"ackIds"` }{ackIDs} req := internal.Request{ Method: "POST", URL: s.pubSubURL(subscription + ":acknowledge"), Scopes: oauthScopes, Body: &request, } return req.Do(c) }
go
func (s *AuthService) ackMessages(c context.Context, subscription string, ackIDs []string) error { if len(ackIDs) == 0 { return nil } request := struct { AckIDs []string `json:"ackIds"` }{ackIDs} req := internal.Request{ Method: "POST", URL: s.pubSubURL(subscription + ":acknowledge"), Scopes: oauthScopes, Body: &request, } return req.Do(c) }
[ "func", "(", "s", "*", "AuthService", ")", "ackMessages", "(", "c", "context", ".", "Context", ",", "subscription", "string", ",", "ackIDs", "[", "]", "string", ")", "error", "{", "if", "len", "(", "ackIDs", ")", "==", "0", "{", "return", "nil", "\n"...
// ackMessages acknowledges processing of pubsub messages.
[ "ackMessages", "acknowledges", "processing", "of", "pubsub", "messages", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/service.go#L351-L365
9,235
luci/luci-go
server/auth/service/service.go
DeflateAuthDB
func DeflateAuthDB(msg *protocol.AuthDB) ([]byte, error) { blob, err := proto.Marshal(msg) if err != nil { return nil, err } out := bytes.Buffer{} writer := zlib.NewWriter(&out) _, err1 := io.Copy(writer, bytes.NewReader(blob)) err2 := writer.Close() if err1 != nil { return nil, err1 } if err2 != nil { return nil, err2 } return out.Bytes(), nil }
go
func DeflateAuthDB(msg *protocol.AuthDB) ([]byte, error) { blob, err := proto.Marshal(msg) if err != nil { return nil, err } out := bytes.Buffer{} writer := zlib.NewWriter(&out) _, err1 := io.Copy(writer, bytes.NewReader(blob)) err2 := writer.Close() if err1 != nil { return nil, err1 } if err2 != nil { return nil, err2 } return out.Bytes(), nil }
[ "func", "DeflateAuthDB", "(", "msg", "*", "protocol", ".", "AuthDB", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "blob", ",", "err", ":=", "proto", ".", "Marshal", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ","...
// DeflateAuthDB serializes AuthDB to byte buffer and compresses it with zlib.
[ "DeflateAuthDB", "serializes", "AuthDB", "to", "byte", "buffer", "and", "compresses", "it", "with", "zlib", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/service.go#L472-L488
9,236
luci/luci-go
server/auth/service/service.go
InflateAuthDB
func InflateAuthDB(blob []byte) (*protocol.AuthDB, error) { reader, err := zlib.NewReader(bytes.NewReader(blob)) if err != nil { return nil, err } defer reader.Close() inflated := bytes.Buffer{} if _, err := io.Copy(&inflated, reader); err != nil { return nil, err } out := &protocol.AuthDB{} if err := proto.Unmarshal(inflated.Bytes(), out); err != nil { return nil, err } return out, nil }
go
func InflateAuthDB(blob []byte) (*protocol.AuthDB, error) { reader, err := zlib.NewReader(bytes.NewReader(blob)) if err != nil { return nil, err } defer reader.Close() inflated := bytes.Buffer{} if _, err := io.Copy(&inflated, reader); err != nil { return nil, err } out := &protocol.AuthDB{} if err := proto.Unmarshal(inflated.Bytes(), out); err != nil { return nil, err } return out, nil }
[ "func", "InflateAuthDB", "(", "blob", "[", "]", "byte", ")", "(", "*", "protocol", ".", "AuthDB", ",", "error", ")", "{", "reader", ",", "err", ":=", "zlib", ".", "NewReader", "(", "bytes", ".", "NewReader", "(", "blob", ")", ")", "\n", "if", "err"...
// InflateAuthDB is reverse of DeflateAuthDB. It decompresses and deserializes // AuthDB message.
[ "InflateAuthDB", "is", "reverse", "of", "DeflateAuthDB", ".", "It", "decompresses", "and", "deserializes", "AuthDB", "message", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/service.go#L492-L507
9,237
luci/luci-go
common/retry/exponential.go
Next
func (b *ExponentialBackoff) Next(ctx context.Context, err error) time.Duration { // Get Limited base delay. delay := b.Limited.Next(ctx, err) if delay == Stop { return Stop } // Bound our delay. if b.MaxDelay > 0 && b.MaxDelay < delay { delay = b.MaxDelay } else { // Calculate the next delay exponentially. multiplier := b.Multiplier if multiplier < 1 { multiplier = 2 } b.Delay = time.Duration(float64(b.Delay) * multiplier) } return delay }
go
func (b *ExponentialBackoff) Next(ctx context.Context, err error) time.Duration { // Get Limited base delay. delay := b.Limited.Next(ctx, err) if delay == Stop { return Stop } // Bound our delay. if b.MaxDelay > 0 && b.MaxDelay < delay { delay = b.MaxDelay } else { // Calculate the next delay exponentially. multiplier := b.Multiplier if multiplier < 1 { multiplier = 2 } b.Delay = time.Duration(float64(b.Delay) * multiplier) } return delay }
[ "func", "(", "b", "*", "ExponentialBackoff", ")", "Next", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "time", ".", "Duration", "{", "// Get Limited base delay.", "delay", ":=", "b", ".", "Limited", ".", "Next", "(", "ctx", ",", "err"...
// Next implements Iterator.
[ "Next", "implements", "Iterator", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/retry/exponential.go#L35-L54
9,238
luci/luci-go
common/logging/gkelogger/config.go
Use
func Use(c context.Context, out io.Writer) context.Context { return logging.SetFactory(c, GetFactory(out)) }
go
func Use(c context.Context, out io.Writer) context.Context { return logging.SetFactory(c, GetFactory(out)) }
[ "func", "Use", "(", "c", "context", ".", "Context", ",", "out", "io", ".", "Writer", ")", "context", ".", "Context", "{", "return", "logging", ".", "SetFactory", "(", "c", ",", "GetFactory", "(", "out", ")", ")", "\n", "}" ]
// Use registers a JSON based logger as default logger of the context that // emits line to out.
[ "Use", "registers", "a", "JSON", "based", "logger", "as", "default", "logger", "of", "the", "context", "that", "emits", "line", "to", "out", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/gkelogger/config.go#L26-L28
9,239
luci/luci-go
common/retry/retry.go
LogCallback
func LogCallback(c context.Context, opname string) Callback { return func(err error, delay time.Duration) { logging.Fields{ logging.ErrorKey: err, "opname": opname, "delay": delay, }.Warningf(c, "operation failed transiently") } }
go
func LogCallback(c context.Context, opname string) Callback { return func(err error, delay time.Duration) { logging.Fields{ logging.ErrorKey: err, "opname": opname, "delay": delay, }.Warningf(c, "operation failed transiently") } }
[ "func", "LogCallback", "(", "c", "context", ".", "Context", ",", "opname", "string", ")", "Callback", "{", "return", "func", "(", "err", "error", ",", "delay", "time", ".", "Duration", ")", "{", "logging", ".", "Fields", "{", "logging", ".", "ErrorKey", ...
// LogCallback builds a Callback which logs a Warning with the opname, error // and delay.
[ "LogCallback", "builds", "a", "Callback", "which", "logs", "a", "Warning", "with", "the", "opname", "error", "and", "delay", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/retry/retry.go#L35-L43
9,240
luci/luci-go
machine-db/appengine/model/switches.go
fetch
func (t *SwitchesTable) fetch(c context.Context) error { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT id, name, description, ports, state, rack_id FROM switches `) if err != nil { return errors.Annotate(err, "failed to select switches").Err() } defer rows.Close() for rows.Next() { s := &Switch{} if err := rows.Scan(&s.Id, &s.Name, &s.Description, &s.Ports, &s.State, &s.RackId); err != nil { return errors.Annotate(err, "failed to scan switch").Err() } t.current = append(t.current, s) } return nil }
go
func (t *SwitchesTable) fetch(c context.Context) error { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT id, name, description, ports, state, rack_id FROM switches `) if err != nil { return errors.Annotate(err, "failed to select switches").Err() } defer rows.Close() for rows.Next() { s := &Switch{} if err := rows.Scan(&s.Id, &s.Name, &s.Description, &s.Ports, &s.State, &s.RackId); err != nil { return errors.Annotate(err, "failed to scan switch").Err() } t.current = append(t.current, s) } return nil }
[ "func", "(", "t", "*", "SwitchesTable", ")", "fetch", "(", "c", "context", ".", "Context", ")", "error", "{", "db", ":=", "database", ".", "Get", "(", "c", ")", "\n", "rows", ",", "err", ":=", "db", ".", "QueryContext", "(", "c", ",", "`\n\t\tSELEC...
// fetch fetches the switches from the database.
[ "fetch", "fetches", "the", "switches", "from", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/switches.go#L50-L68
9,241
luci/luci-go
machine-db/appengine/model/switches.go
computeChanges
func (t *SwitchesTable) computeChanges(c context.Context, datacenters []*config.Datacenter) error { cfgs := make(map[string]*Switch, len(datacenters)) for _, dc := range datacenters { for _, rack := range dc.Rack { for _, cfg := range rack.Switch { id, ok := t.racks[rack.Name] if !ok { return errors.Reason("failed to determine rack ID for switch %q: rack %q does not exist", cfg.Name, rack.Name).Err() } cfgs[cfg.Name] = &Switch{ Switch: config.Switch{ Name: cfg.Name, Description: cfg.Description, Ports: cfg.Ports, State: cfg.State, }, RackId: id, } } } } for _, s := range t.current { if cfg, ok := cfgs[s.Name]; ok { // Switch found in the config. if t.needsUpdate(s, cfg) { // Switch doesn't match the config. cfg.Id = s.Id t.updates = append(t.updates, cfg) } // Record that the switch config has been seen. delete(cfgs, cfg.Name) } else { // Switch not found in the config. t.removals = append(t.removals, s) } } // Switches remaining in the map are present in the config but not the database. // Iterate deterministically over the slices to determine which switches need to be added. for _, dc := range datacenters { for _, rack := range dc.Rack { for _, cfg := range rack.Switch { if s, ok := cfgs[cfg.Name]; ok { t.additions = append(t.additions, s) } } } } return nil }
go
func (t *SwitchesTable) computeChanges(c context.Context, datacenters []*config.Datacenter) error { cfgs := make(map[string]*Switch, len(datacenters)) for _, dc := range datacenters { for _, rack := range dc.Rack { for _, cfg := range rack.Switch { id, ok := t.racks[rack.Name] if !ok { return errors.Reason("failed to determine rack ID for switch %q: rack %q does not exist", cfg.Name, rack.Name).Err() } cfgs[cfg.Name] = &Switch{ Switch: config.Switch{ Name: cfg.Name, Description: cfg.Description, Ports: cfg.Ports, State: cfg.State, }, RackId: id, } } } } for _, s := range t.current { if cfg, ok := cfgs[s.Name]; ok { // Switch found in the config. if t.needsUpdate(s, cfg) { // Switch doesn't match the config. cfg.Id = s.Id t.updates = append(t.updates, cfg) } // Record that the switch config has been seen. delete(cfgs, cfg.Name) } else { // Switch not found in the config. t.removals = append(t.removals, s) } } // Switches remaining in the map are present in the config but not the database. // Iterate deterministically over the slices to determine which switches need to be added. for _, dc := range datacenters { for _, rack := range dc.Rack { for _, cfg := range rack.Switch { if s, ok := cfgs[cfg.Name]; ok { t.additions = append(t.additions, s) } } } } return nil }
[ "func", "(", "t", "*", "SwitchesTable", ")", "computeChanges", "(", "c", "context", ".", "Context", ",", "datacenters", "[", "]", "*", "config", ".", "Datacenter", ")", "error", "{", "cfgs", ":=", "make", "(", "map", "[", "string", "]", "*", "Switch", ...
// computeChanges computes the changes that need to be made to the switches in the database.
[ "computeChanges", "computes", "the", "changes", "that", "need", "to", "be", "made", "to", "the", "switches", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/switches.go#L76-L126
9,242
luci/luci-go
machine-db/appengine/model/switches.go
add
func (t *SwitchesTable) add(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.additions) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` INSERT INTO switches (name, description, ports, state, rack_id) VALUES (?, ?, ?, ?, ?) `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Add each switch to the database, and update the slice of switches with each addition. for len(t.additions) > 0 { s := t.additions[0] result, err := stmt.ExecContext(c, s.Name, s.Description, s.Ports, s.State, s.RackId) if err != nil { return errors.Annotate(err, "failed to add switch %q", s.Name).Err() } t.current = append(t.current, s) t.additions = t.additions[1:] logging.Infof(c, "Added switch %q", s.Name) s.Id, err = result.LastInsertId() if err != nil { return errors.Annotate(err, "failed to get switch ID %q", s.Name).Err() } } return nil }
go
func (t *SwitchesTable) add(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.additions) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` INSERT INTO switches (name, description, ports, state, rack_id) VALUES (?, ?, ?, ?, ?) `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Add each switch to the database, and update the slice of switches with each addition. for len(t.additions) > 0 { s := t.additions[0] result, err := stmt.ExecContext(c, s.Name, s.Description, s.Ports, s.State, s.RackId) if err != nil { return errors.Annotate(err, "failed to add switch %q", s.Name).Err() } t.current = append(t.current, s) t.additions = t.additions[1:] logging.Infof(c, "Added switch %q", s.Name) s.Id, err = result.LastInsertId() if err != nil { return errors.Annotate(err, "failed to get switch ID %q", s.Name).Err() } } return nil }
[ "func", "(", "t", "*", "SwitchesTable", ")", "add", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "additions", ")", "==", "0", "{", "return", "nil"...
// add adds all switches pending addition to the database, clearing pending additions. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "add", "adds", "all", "switches", "pending", "addition", "to", "the", "database", "clearing", "pending", "additions", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called", "again...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/switches.go#L130-L162
9,243
luci/luci-go
machine-db/appengine/model/switches.go
remove
func (t *SwitchesTable) remove(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.removals) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` DELETE FROM switches WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Remove each switch from the table. It's more efficient to update the slice of // switches once at the end rather than for each removal, so use a defer. removed := make(map[int64]struct{}, len(t.removals)) defer func() { var switches []*Switch for _, s := range t.current { if _, ok := removed[s.Id]; !ok { switches = append(switches, s) } } t.current = switches }() for len(t.removals) > 0 { s := t.removals[0] if _, err := stmt.ExecContext(c, s.Id); err != nil { // Defer ensures the slice of switches is updated even if we exit early. return errors.Annotate(err, "failed to remove switch %q", s.Name).Err() } removed[s.Id] = struct{}{} t.removals = t.removals[1:] logging.Infof(c, "Removed switch %q", s.Name) } return nil }
go
func (t *SwitchesTable) remove(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.removals) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` DELETE FROM switches WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Remove each switch from the table. It's more efficient to update the slice of // switches once at the end rather than for each removal, so use a defer. removed := make(map[int64]struct{}, len(t.removals)) defer func() { var switches []*Switch for _, s := range t.current { if _, ok := removed[s.Id]; !ok { switches = append(switches, s) } } t.current = switches }() for len(t.removals) > 0 { s := t.removals[0] if _, err := stmt.ExecContext(c, s.Id); err != nil { // Defer ensures the slice of switches is updated even if we exit early. return errors.Annotate(err, "failed to remove switch %q", s.Name).Err() } removed[s.Id] = struct{}{} t.removals = t.removals[1:] logging.Infof(c, "Removed switch %q", s.Name) } return nil }
[ "func", "(", "t", "*", "SwitchesTable", ")", "remove", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "removals", ")", "==", "0", "{", "return", "ni...
// remove removes all switches pending removal from the database, clearing pending removals. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "remove", "removes", "all", "switches", "pending", "removal", "from", "the", "database", "clearing", "pending", "removals", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/switches.go#L166-L205
9,244
luci/luci-go
machine-db/appengine/model/switches.go
update
func (t *SwitchesTable) update(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.updates) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` UPDATE switches SET description = ?, ports = ?, state = ?, rack_id = ? WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Update each switch in the table. It's more efficient to update the slice of // switches once at the end rather than for each update, so use a defer. updated := make(map[int64]*Switch, len(t.updates)) defer func() { for _, s := range t.current { if u, ok := updated[s.Id]; ok { s.Description = u.Description s.Ports = u.Ports s.State = u.State s.RackId = u.RackId } } }() for len(t.updates) > 0 { s := t.updates[0] if _, err := stmt.ExecContext(c, s.Description, s.Ports, s.State, s.RackId, s.Id); err != nil { return errors.Annotate(err, "failed to update switch %q", s.Name).Err() } updated[s.Id] = s t.updates = t.updates[1:] logging.Infof(c, "Updated switch %q", s.Name) } return nil }
go
func (t *SwitchesTable) update(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.updates) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` UPDATE switches SET description = ?, ports = ?, state = ?, rack_id = ? WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Update each switch in the table. It's more efficient to update the slice of // switches once at the end rather than for each update, so use a defer. updated := make(map[int64]*Switch, len(t.updates)) defer func() { for _, s := range t.current { if u, ok := updated[s.Id]; ok { s.Description = u.Description s.Ports = u.Ports s.State = u.State s.RackId = u.RackId } } }() for len(t.updates) > 0 { s := t.updates[0] if _, err := stmt.ExecContext(c, s.Description, s.Ports, s.State, s.RackId, s.Id); err != nil { return errors.Annotate(err, "failed to update switch %q", s.Name).Err() } updated[s.Id] = s t.updates = t.updates[1:] logging.Infof(c, "Updated switch %q", s.Name) } return nil }
[ "func", "(", "t", "*", "SwitchesTable", ")", "update", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "updates", ")", "==", "0", "{", "return", "nil...
// update updates all switches pending update in the database, clearing pending updates. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "update", "updates", "all", "switches", "pending", "update", "in", "the", "database", "clearing", "pending", "updates", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called", "aga...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/switches.go#L209-L249
9,245
luci/luci-go
machine-db/appengine/model/switches.go
ids
func (t *SwitchesTable) ids(c context.Context) map[string]int64 { switches := make(map[string]int64, len(t.current)) for _, s := range t.current { switches[s.Name] = s.Id } return switches }
go
func (t *SwitchesTable) ids(c context.Context) map[string]int64 { switches := make(map[string]int64, len(t.current)) for _, s := range t.current { switches[s.Name] = s.Id } return switches }
[ "func", "(", "t", "*", "SwitchesTable", ")", "ids", "(", "c", "context", ".", "Context", ")", "map", "[", "string", "]", "int64", "{", "switches", ":=", "make", "(", "map", "[", "string", "]", "int64", ",", "len", "(", "t", ".", "current", ")", "...
// ids returns a map of switch names to IDs.
[ "ids", "returns", "a", "map", "of", "switch", "names", "to", "IDs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/switches.go#L252-L258
9,246
luci/luci-go
machine-db/appengine/model/switches.go
EnsureSwitches
func EnsureSwitches(c context.Context, cfgs []*config.Datacenter, rackIds map[string]int64) error { t := &SwitchesTable{} t.racks = rackIds if err := t.fetch(c); err != nil { return errors.Annotate(err, "failed to fetch switches").Err() } if err := t.computeChanges(c, cfgs); err != nil { return errors.Annotate(err, "failed to compute changes").Err() } if err := t.add(c); err != nil { return errors.Annotate(err, "failed to add switches").Err() } if err := t.remove(c); err != nil { return errors.Annotate(err, "failed to remove switches").Err() } if err := t.update(c); err != nil { return errors.Annotate(err, "failed to update switches").Err() } return nil }
go
func EnsureSwitches(c context.Context, cfgs []*config.Datacenter, rackIds map[string]int64) error { t := &SwitchesTable{} t.racks = rackIds if err := t.fetch(c); err != nil { return errors.Annotate(err, "failed to fetch switches").Err() } if err := t.computeChanges(c, cfgs); err != nil { return errors.Annotate(err, "failed to compute changes").Err() } if err := t.add(c); err != nil { return errors.Annotate(err, "failed to add switches").Err() } if err := t.remove(c); err != nil { return errors.Annotate(err, "failed to remove switches").Err() } if err := t.update(c); err != nil { return errors.Annotate(err, "failed to update switches").Err() } return nil }
[ "func", "EnsureSwitches", "(", "c", "context", ".", "Context", ",", "cfgs", "[", "]", "*", "config", ".", "Datacenter", ",", "rackIds", "map", "[", "string", "]", "int64", ")", "error", "{", "t", ":=", "&", "SwitchesTable", "{", "}", "\n", "t", ".", ...
// EnsureSwitches ensures the database contains exactly the given switches.
[ "EnsureSwitches", "ensures", "the", "database", "contains", "exactly", "the", "given", "switches", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/switches.go#L261-L280
9,247
luci/luci-go
common/tsmon/distribution/distribution.go
New
func New(b *Bucketer) *Distribution { if b == nil { b = DefaultBucketer } return &Distribution{b: b, lastNonZeroBucket: -1} }
go
func New(b *Bucketer) *Distribution { if b == nil { b = DefaultBucketer } return &Distribution{b: b, lastNonZeroBucket: -1} }
[ "func", "New", "(", "b", "*", "Bucketer", ")", "*", "Distribution", "{", "if", "b", "==", "nil", "{", "b", "=", "DefaultBucketer", "\n", "}", "\n", "return", "&", "Distribution", "{", "b", ":", "b", ",", "lastNonZeroBucket", ":", "-", "1", "}", "\n...
// New creates a new distribution using the given bucketer. Passing a nil // Bucketer will use DefaultBucketer.
[ "New", "creates", "a", "new", "distribution", "using", "the", "given", "bucketer", ".", "Passing", "a", "nil", "Bucketer", "will", "use", "DefaultBucketer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/distribution/distribution.go#L32-L37
9,248
luci/luci-go
common/tsmon/distribution/distribution.go
Add
func (d *Distribution) Add(sample float64) { i := d.b.Bucket(sample) if i >= len(d.buckets) { d.buckets = append(d.buckets, make([]int64, i-len(d.buckets)+1)...) } d.buckets[i]++ d.sum += sample d.count++ if i > d.lastNonZeroBucket { d.lastNonZeroBucket = i } }
go
func (d *Distribution) Add(sample float64) { i := d.b.Bucket(sample) if i >= len(d.buckets) { d.buckets = append(d.buckets, make([]int64, i-len(d.buckets)+1)...) } d.buckets[i]++ d.sum += sample d.count++ if i > d.lastNonZeroBucket { d.lastNonZeroBucket = i } }
[ "func", "(", "d", "*", "Distribution", ")", "Add", "(", "sample", "float64", ")", "{", "i", ":=", "d", ".", "b", ".", "Bucket", "(", "sample", ")", "\n", "if", "i", ">=", "len", "(", "d", ".", "buckets", ")", "{", "d", ".", "buckets", "=", "a...
// Add adds the sample to the distribution and updates the statistics.
[ "Add", "adds", "the", "sample", "to", "the", "distribution", "and", "updates", "the", "statistics", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/distribution/distribution.go#L40-L51
9,249
luci/luci-go
common/logging/level.go
GetLevel
func GetLevel(c context.Context) Level { if l, ok := c.Value(levelKey).(Level); ok { return l } return DefaultLevel }
go
func GetLevel(c context.Context) Level { if l, ok := c.Value(levelKey).(Level); ok { return l } return DefaultLevel }
[ "func", "GetLevel", "(", "c", "context", ".", "Context", ")", "Level", "{", "if", "l", ",", "ok", ":=", "c", ".", "Value", "(", "levelKey", ")", ".", "(", "Level", ")", ";", "ok", "{", "return", "l", "\n", "}", "\n", "return", "DefaultLevel", "\n...
// GetLevel returns the Level for this context. It will return DefaultLevel if // none is defined.
[ "GetLevel", "returns", "the", "Level", "for", "this", "context", ".", "It", "will", "return", "DefaultLevel", "if", "none", "is", "defined", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/level.go#L84-L89
9,250
luci/luci-go
logdog/api/logpb/utils.go
Validate
func (d *LogStreamDescriptor) Validate(prefix bool) error { if d == nil { return errors.New("descriptor is nil") } if prefix { if err := types.StreamName(d.Prefix).Validate(); err != nil { return fmt.Errorf("invalid prefix: %s", err) } } if err := types.StreamName(d.Name).Validate(); err != nil { return fmt.Errorf("invalid name: %s", err) } switch d.StreamType { case StreamType_TEXT, StreamType_BINARY, StreamType_DATAGRAM: break default: return fmt.Errorf("invalid stream type: %v", d.StreamType) } if d.ContentType == "" { return errors.New("missing content type") } if d.Timestamp == nil { return errors.New("missing timestamp") } for k, v := range d.GetTags() { if err := types.ValidateTag(k, v); err != nil { return fmt.Errorf("invalid tag %q: %v", k, err) } } return nil }
go
func (d *LogStreamDescriptor) Validate(prefix bool) error { if d == nil { return errors.New("descriptor is nil") } if prefix { if err := types.StreamName(d.Prefix).Validate(); err != nil { return fmt.Errorf("invalid prefix: %s", err) } } if err := types.StreamName(d.Name).Validate(); err != nil { return fmt.Errorf("invalid name: %s", err) } switch d.StreamType { case StreamType_TEXT, StreamType_BINARY, StreamType_DATAGRAM: break default: return fmt.Errorf("invalid stream type: %v", d.StreamType) } if d.ContentType == "" { return errors.New("missing content type") } if d.Timestamp == nil { return errors.New("missing timestamp") } for k, v := range d.GetTags() { if err := types.ValidateTag(k, v); err != nil { return fmt.Errorf("invalid tag %q: %v", k, err) } } return nil }
[ "func", "(", "d", "*", "LogStreamDescriptor", ")", "Validate", "(", "prefix", "bool", ")", "error", "{", "if", "d", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "prefix", "{", "if", "err", ":=", ...
// Validate returns an error if the supplied LogStreamDescriptor is not complete // and valid. // // If prefix is true, the Prefix field will be validated; otherwise, it will // be ignored. This can be useful when attempting to validate a // LogStreamDescriptor before the application-assigned Prefix is known.
[ "Validate", "returns", "an", "error", "if", "the", "supplied", "LogStreamDescriptor", "is", "not", "complete", "and", "valid", ".", "If", "prefix", "is", "true", "the", "Prefix", "field", "will", "be", "validated", ";", "otherwise", "it", "will", "be", "igno...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/logpb/utils.go#L36-L71
9,251
luci/luci-go
logdog/api/logpb/utils.go
Equal
func (d *LogStreamDescriptor) Equal(o *LogStreamDescriptor) bool { return reflect.DeepEqual(d, o) }
go
func (d *LogStreamDescriptor) Equal(o *LogStreamDescriptor) bool { return reflect.DeepEqual(d, o) }
[ "func", "(", "d", "*", "LogStreamDescriptor", ")", "Equal", "(", "o", "*", "LogStreamDescriptor", ")", "bool", "{", "return", "reflect", ".", "DeepEqual", "(", "d", ",", "o", ")", "\n", "}" ]
// Equal tests if two LogStreamDescriptor instances have the same data.
[ "Equal", "tests", "if", "two", "LogStreamDescriptor", "instances", "have", "the", "same", "data", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/logpb/utils.go#L74-L76
9,252
luci/luci-go
logdog/api/logpb/utils.go
Path
func (d *LogStreamDescriptor) Path() types.StreamPath { return types.StreamName(d.Prefix).Join(types.StreamName(d.Name)) }
go
func (d *LogStreamDescriptor) Path() types.StreamPath { return types.StreamName(d.Prefix).Join(types.StreamName(d.Name)) }
[ "func", "(", "d", "*", "LogStreamDescriptor", ")", "Path", "(", ")", "types", ".", "StreamPath", "{", "return", "types", ".", "StreamName", "(", "d", ".", "Prefix", ")", ".", "Join", "(", "types", ".", "StreamName", "(", "d", ".", "Name", ")", ")", ...
// Path returns a types.StreamPath constructed from the LogStreamDesciptor's // Prefix and Name fields.
[ "Path", "returns", "a", "types", ".", "StreamPath", "constructed", "from", "the", "LogStreamDesciptor", "s", "Prefix", "and", "Name", "fields", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/logpb/utils.go#L80-L82
9,253
luci/luci-go
logdog/api/logpb/utils.go
Validate
func (e *LogEntry) Validate(d *LogStreamDescriptor) error { if e == nil { return errors.New("entry is nil") } // Check for content. switch d.StreamType { case StreamType_TEXT: if t := e.GetText(); t == nil || len(t.Lines) == 0 { return ErrNoContent } case StreamType_BINARY: if b := e.GetBinary(); b == nil || len(b.Data) == 0 { return ErrNoContent } case StreamType_DATAGRAM: if d := e.GetDatagram(); d == nil { return ErrNoContent } } return nil }
go
func (e *LogEntry) Validate(d *LogStreamDescriptor) error { if e == nil { return errors.New("entry is nil") } // Check for content. switch d.StreamType { case StreamType_TEXT: if t := e.GetText(); t == nil || len(t.Lines) == 0 { return ErrNoContent } case StreamType_BINARY: if b := e.GetBinary(); b == nil || len(b.Data) == 0 { return ErrNoContent } case StreamType_DATAGRAM: if d := e.GetDatagram(); d == nil { return ErrNoContent } } return nil }
[ "func", "(", "e", "*", "LogEntry", ")", "Validate", "(", "d", "*", "LogStreamDescriptor", ")", "error", "{", "if", "e", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check for content.", "switch", "d", ...
// Validate checks a supplied LogEntry against its LogStreamDescriptor for // validity, returning an error if it is not valid. // // If the LogEntry is otherwise valid, but has no content, ErrNoContent will be // returned.
[ "Validate", "checks", "a", "supplied", "LogEntry", "against", "its", "LogStreamDescriptor", "for", "validity", "returning", "an", "error", "if", "it", "is", "not", "valid", ".", "If", "the", "LogEntry", "is", "otherwise", "valid", "but", "has", "no", "content"...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/logpb/utils.go#L89-L112
9,254
luci/luci-go
milo/buildsource/buildbucket/buckets.go
GetBuilders
func GetBuilders(c context.Context) (*swarmbucket.LegacySwarmbucketApiGetBuildersResponseMessage, error) { host := common.GetSettings(c).GetBuildbucket().GetHost() if host == "" { return nil, errors.New("buildbucket host is missing in config") } return getBuilders(c, host) }
go
func GetBuilders(c context.Context) (*swarmbucket.LegacySwarmbucketApiGetBuildersResponseMessage, error) { host := common.GetSettings(c).GetBuildbucket().GetHost() if host == "" { return nil, errors.New("buildbucket host is missing in config") } return getBuilders(c, host) }
[ "func", "GetBuilders", "(", "c", "context", ".", "Context", ")", "(", "*", "swarmbucket", ".", "LegacySwarmbucketApiGetBuildersResponseMessage", ",", "error", ")", "{", "host", ":=", "common", ".", "GetSettings", "(", "c", ")", ".", "GetBuildbucket", "(", ")",...
// GetBuilders returns all Swarmbucket builders, cached for current identity.
[ "GetBuilders", "returns", "all", "Swarmbucket", "builders", "cached", "for", "current", "identity", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/buckets.go#L35-L41
9,255
luci/luci-go
server/auth/openid/settings.go
fetchCachedSettings
func fetchCachedSettings(c context.Context) (*Settings, error) { cfg := &Settings{} if err := settings.Get(c, SettingsKey, cfg); err != settings.ErrNoSettings { return cfg, err } return cfg, nil }
go
func fetchCachedSettings(c context.Context) (*Settings, error) { cfg := &Settings{} if err := settings.Get(c, SettingsKey, cfg); err != settings.ErrNoSettings { return cfg, err } return cfg, nil }
[ "func", "fetchCachedSettings", "(", "c", "context", ".", "Context", ")", "(", "*", "Settings", ",", "error", ")", "{", "cfg", ":=", "&", "Settings", "{", "}", "\n", "if", "err", ":=", "settings", ".", "Get", "(", "c", ",", "SettingsKey", ",", "cfg", ...
// fetchCachedSettings fetches OpenID configuration from the settings store.
[ "fetchCachedSettings", "fetches", "OpenID", "configuration", "from", "the", "settings", "store", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/settings.go#L58-L64
9,256
luci/luci-go
scheduler/appengine/apiservers/scheduler.go
GetJobs
func (s *SchedulerServer) GetJobs(ctx context.Context, in *scheduler.JobsRequest) (*scheduler.JobsReply, error) { if in.GetCursor() != "" { // Paging in GetJobs isn't implemented until we have enough jobs to care. // Until then, not empty cursor implies no more jobs to return. return &scheduler.JobsReply{Jobs: []*scheduler.Job{}, NextCursor: ""}, nil } var ejobs []*engine.Job var err error if in.GetProject() == "" { ejobs, err = s.Engine.GetVisibleJobs(ctx) } else { ejobs, err = s.Engine.GetVisibleProjectJobs(ctx, in.GetProject()) } if err != nil { return nil, status.Errorf(codes.Internal, "internal error: %s", err) } jobs := make([]*scheduler.Job, len(ejobs)) for i, ej := range ejobs { traits, err := presentation.GetJobTraits(ctx, s.Catalog, ej) if err != nil { return nil, status.Errorf(codes.Internal, "failed to get traits: %s", err) } jobs[i] = &scheduler.Job{ JobRef: &scheduler.JobRef{ Project: ej.ProjectID, Job: ej.JobName(), }, Schedule: ej.Schedule, State: &scheduler.JobState{ UiStatus: string(presentation.GetPublicStateKind(ej, traits)), }, Paused: ej.Paused, } } return &scheduler.JobsReply{Jobs: jobs, NextCursor: ""}, nil }
go
func (s *SchedulerServer) GetJobs(ctx context.Context, in *scheduler.JobsRequest) (*scheduler.JobsReply, error) { if in.GetCursor() != "" { // Paging in GetJobs isn't implemented until we have enough jobs to care. // Until then, not empty cursor implies no more jobs to return. return &scheduler.JobsReply{Jobs: []*scheduler.Job{}, NextCursor: ""}, nil } var ejobs []*engine.Job var err error if in.GetProject() == "" { ejobs, err = s.Engine.GetVisibleJobs(ctx) } else { ejobs, err = s.Engine.GetVisibleProjectJobs(ctx, in.GetProject()) } if err != nil { return nil, status.Errorf(codes.Internal, "internal error: %s", err) } jobs := make([]*scheduler.Job, len(ejobs)) for i, ej := range ejobs { traits, err := presentation.GetJobTraits(ctx, s.Catalog, ej) if err != nil { return nil, status.Errorf(codes.Internal, "failed to get traits: %s", err) } jobs[i] = &scheduler.Job{ JobRef: &scheduler.JobRef{ Project: ej.ProjectID, Job: ej.JobName(), }, Schedule: ej.Schedule, State: &scheduler.JobState{ UiStatus: string(presentation.GetPublicStateKind(ej, traits)), }, Paused: ej.Paused, } } return &scheduler.JobsReply{Jobs: jobs, NextCursor: ""}, nil }
[ "func", "(", "s", "*", "SchedulerServer", ")", "GetJobs", "(", "ctx", "context", ".", "Context", ",", "in", "*", "scheduler", ".", "JobsRequest", ")", "(", "*", "scheduler", ".", "JobsReply", ",", "error", ")", "{", "if", "in", ".", "GetCursor", "(", ...
// GetJobs fetches all jobs satisfying JobsRequest and visibility ACLs.
[ "GetJobs", "fetches", "all", "jobs", "satisfying", "JobsRequest", "and", "visibility", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/apiservers/scheduler.go#L50-L86
9,257
luci/luci-go
logdog/appengine/coordinator/config/projects.go
ProjectConfigPath
func ProjectConfigPath(c context.Context) string { return svcconfig.ProjectConfigPath(cfgclient.CurrentServiceName(c)) }
go
func ProjectConfigPath(c context.Context) string { return svcconfig.ProjectConfigPath(cfgclient.CurrentServiceName(c)) }
[ "func", "ProjectConfigPath", "(", "c", "context", ".", "Context", ")", "string", "{", "return", "svcconfig", ".", "ProjectConfigPath", "(", "cfgclient", ".", "CurrentServiceName", "(", "c", ")", ")", "\n", "}" ]
// ProjectConfigPath returns the path of the project-specific configuration. // This path should be used with a project config set. // // A given project's configuration is named after the current App ID.
[ "ProjectConfigPath", "returns", "the", "path", "of", "the", "project", "-", "specific", "configuration", ".", "This", "path", "should", "be", "used", "with", "a", "project", "config", "set", ".", "A", "given", "project", "s", "configuration", "is", "named", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/config/projects.go#L33-L35
9,258
luci/luci-go
logdog/appengine/coordinator/config/projects.go
ProjectNames
func ProjectNames(c context.Context, a cfgclient.Authority) ([]types.ProjectName, error) { configPath := ProjectConfigPath(c) var metas []*config.Meta if err := cfgclient.Projects(c, a, configPath, nil, &metas); err != nil { log.WithError(err).Errorf(c, "Failed to load project configs.") return nil, err } // Iterate through our Metas and extract the project names. projects := make([]types.ProjectName, 0, len(metas)) for _, meta := range metas { if projectName := meta.ConfigSet.Project(); projectName != "" { projects = append(projects, types.ProjectName(projectName)) } } sort.Sort(projectNameSlice(projects)) return projects, nil }
go
func ProjectNames(c context.Context, a cfgclient.Authority) ([]types.ProjectName, error) { configPath := ProjectConfigPath(c) var metas []*config.Meta if err := cfgclient.Projects(c, a, configPath, nil, &metas); err != nil { log.WithError(err).Errorf(c, "Failed to load project configs.") return nil, err } // Iterate through our Metas and extract the project names. projects := make([]types.ProjectName, 0, len(metas)) for _, meta := range metas { if projectName := meta.ConfigSet.Project(); projectName != "" { projects = append(projects, types.ProjectName(projectName)) } } sort.Sort(projectNameSlice(projects)) return projects, nil }
[ "func", "ProjectNames", "(", "c", "context", ".", "Context", ",", "a", "cfgclient", ".", "Authority", ")", "(", "[", "]", "types", ".", "ProjectName", ",", "error", ")", "{", "configPath", ":=", "ProjectConfigPath", "(", "c", ")", "\n\n", "var", "metas",...
// ProjectNames returns a sorted list of the names of all of the projects // that the supplied authority can view.
[ "ProjectNames", "returns", "a", "sorted", "list", "of", "the", "names", "of", "all", "of", "the", "projects", "that", "the", "supplied", "authority", "can", "view", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/config/projects.go#L70-L88
9,259
luci/luci-go
logdog/appengine/coordinator/config/projects.go
ActiveProjects
func ActiveProjects(c context.Context) ([]types.ProjectName, error) { return ProjectNames(c, cfgclient.AsService) }
go
func ActiveProjects(c context.Context) ([]types.ProjectName, error) { return ProjectNames(c, cfgclient.AsService) }
[ "func", "ActiveProjects", "(", "c", "context", ".", "Context", ")", "(", "[", "]", "types", ".", "ProjectName", ",", "error", ")", "{", "return", "ProjectNames", "(", "c", ",", "cfgclient", ".", "AsService", ")", "\n", "}" ]
// ActiveProjects returns a full list of all config service projects with // LogDog project configurations. // // The list will be alphabetically sorted.
[ "ActiveProjects", "returns", "a", "full", "list", "of", "all", "config", "service", "projects", "with", "LogDog", "project", "configurations", ".", "The", "list", "will", "be", "alphabetically", "sorted", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/config/projects.go#L94-L96
9,260
luci/luci-go
logdog/appengine/coordinator/config/projects.go
ActiveUserProjects
func ActiveUserProjects(c context.Context) ([]types.ProjectName, error) { return ProjectNames(c, cfgclient.AsUser) }
go
func ActiveUserProjects(c context.Context) ([]types.ProjectName, error) { return ProjectNames(c, cfgclient.AsUser) }
[ "func", "ActiveUserProjects", "(", "c", "context", ".", "Context", ")", "(", "[", "]", "types", ".", "ProjectName", ",", "error", ")", "{", "return", "ProjectNames", "(", "c", ",", "cfgclient", ".", "AsUser", ")", "\n", "}" ]
// ActiveUserProjects returns a full list of all config service projects with // LogDog project configurations that the current user can see. // // The list will be alphabetically sorted.
[ "ActiveUserProjects", "returns", "a", "full", "list", "of", "all", "config", "service", "projects", "with", "LogDog", "project", "configurations", "that", "the", "current", "user", "can", "see", ".", "The", "list", "will", "be", "alphabetically", "sorted", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/config/projects.go#L102-L104
9,261
luci/luci-go
gce/vmtoken/vmtoken.go
Clear
func Clear(c context.Context) context.Context { return context.WithValue(c, &pldKey, nil) }
go
func Clear(c context.Context) context.Context { return context.WithValue(c, &pldKey, nil) }
[ "func", "Clear", "(", "c", "context", ".", "Context", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "&", "pldKey", ",", "nil", ")", "\n", "}" ]
// Clear returns a new context without a GCE VM metadata token installed.
[ "Clear", "returns", "a", "new", "context", "without", "a", "GCE", "VM", "metadata", "token", "installed", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/vmtoken/vmtoken.go#L193-L195
9,262
luci/luci-go
gce/vmtoken/vmtoken.go
Hostname
func Hostname(c context.Context) string { p := getPayload(c) if p == nil { return "" } return p.Instance }
go
func Hostname(c context.Context) string { p := getPayload(c) if p == nil { return "" } return p.Instance }
[ "func", "Hostname", "(", "c", "context", ".", "Context", ")", "string", "{", "p", ":=", "getPayload", "(", "c", ")", "\n", "if", "p", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "p", ".", "Instance", "\n", "}" ]
// Hostname returns the hostname of the VM stored in the current context.
[ "Hostname", "returns", "the", "hostname", "of", "the", "VM", "stored", "in", "the", "current", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/vmtoken/vmtoken.go#L204-L210
9,263
luci/luci-go
gce/vmtoken/vmtoken.go
CurrentIdentity
func CurrentIdentity(c context.Context) string { p := getPayload(c) if p == nil { return "gce:anonymous" } // GCE hostnames must be unique per project, so <instance, project> suffices. return fmt.Sprintf("gce:%s:%s", p.Instance, p.Project) }
go
func CurrentIdentity(c context.Context) string { p := getPayload(c) if p == nil { return "gce:anonymous" } // GCE hostnames must be unique per project, so <instance, project> suffices. return fmt.Sprintf("gce:%s:%s", p.Instance, p.Project) }
[ "func", "CurrentIdentity", "(", "c", "context", ".", "Context", ")", "string", "{", "p", ":=", "getPayload", "(", "c", ")", "\n", "if", "p", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "// GCE hostnames must be unique per project, so <instance, pr...
// CurrentIdentity returns the identity of the VM stored in the current context.
[ "CurrentIdentity", "returns", "the", "identity", "of", "the", "VM", "stored", "in", "the", "current", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/vmtoken/vmtoken.go#L213-L220
9,264
luci/luci-go
gce/vmtoken/vmtoken.go
Matches
func Matches(c context.Context, host, zone, proj string) bool { p := getPayload(c) if p == nil { return false } logging.Debugf(c, "expecting VM token from %q in %q in %q", host, zone, proj) return p.Instance == host && p.Zone == zone && p.Project == proj }
go
func Matches(c context.Context, host, zone, proj string) bool { p := getPayload(c) if p == nil { return false } logging.Debugf(c, "expecting VM token from %q in %q in %q", host, zone, proj) return p.Instance == host && p.Zone == zone && p.Project == proj }
[ "func", "Matches", "(", "c", "context", ".", "Context", ",", "host", ",", "zone", ",", "proj", "string", ")", "bool", "{", "p", ":=", "getPayload", "(", "c", ")", "\n", "if", "p", "==", "nil", "{", "return", "false", "\n", "}", "\n", "logging", "...
// Matches returns whether the current context contains a GCE VM metadata // token matching the given identity.
[ "Matches", "returns", "whether", "the", "current", "context", "contains", "a", "GCE", "VM", "metadata", "token", "matching", "the", "given", "identity", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/vmtoken/vmtoken.go#L224-L231
9,265
luci/luci-go
gce/vmtoken/vmtoken.go
Middleware
func Middleware(c *router.Context, next router.Handler) { if tok := c.Request.Header.Get(Header); tok != "" { // TODO(smut): Support requests to other modules, versions. aud := "https://" + info.DefaultVersionHostname(c.Context) logging.Debugf(c.Context, "expecting VM token for: %s", aud) switch p, err := Verify(c.Context, tok); { case transient.Tag.In(err): logging.WithError(err).Errorf(c.Context, "transient error verifying VM token") http.Error(c.Writer, "error: failed to verify VM token", http.StatusInternalServerError) return case err != nil: logging.WithError(err).Errorf(c.Context, "invalid VM token") http.Error(c.Writer, "error: invalid VM token", http.StatusUnauthorized) return case p.Audience != aud: logging.Errorf(c.Context, "received VM token intended for: %s", p.Audience) http.Error(c.Writer, "error: VM token audience mismatch", http.StatusUnauthorized) return default: logging.Debugf(c.Context, "received VM token from %q in %q in %q for: %s", p.Instance, p.Zone, p.Project, p.Audience) c.Context = withPayload(c.Context, p) } } next(c) }
go
func Middleware(c *router.Context, next router.Handler) { if tok := c.Request.Header.Get(Header); tok != "" { // TODO(smut): Support requests to other modules, versions. aud := "https://" + info.DefaultVersionHostname(c.Context) logging.Debugf(c.Context, "expecting VM token for: %s", aud) switch p, err := Verify(c.Context, tok); { case transient.Tag.In(err): logging.WithError(err).Errorf(c.Context, "transient error verifying VM token") http.Error(c.Writer, "error: failed to verify VM token", http.StatusInternalServerError) return case err != nil: logging.WithError(err).Errorf(c.Context, "invalid VM token") http.Error(c.Writer, "error: invalid VM token", http.StatusUnauthorized) return case p.Audience != aud: logging.Errorf(c.Context, "received VM token intended for: %s", p.Audience) http.Error(c.Writer, "error: VM token audience mismatch", http.StatusUnauthorized) return default: logging.Debugf(c.Context, "received VM token from %q in %q in %q for: %s", p.Instance, p.Zone, p.Project, p.Audience) c.Context = withPayload(c.Context, p) } } next(c) }
[ "func", "Middleware", "(", "c", "*", "router", ".", "Context", ",", "next", "router", ".", "Handler", ")", "{", "if", "tok", ":=", "c", ".", "Request", ".", "Header", ".", "Get", "(", "Header", ")", ";", "tok", "!=", "\"", "\"", "{", "// TODO(smut)...
// Middleware embeds a Payload in the context if the request contains a GCE VM // metadata token.
[ "Middleware", "embeds", "a", "Payload", "in", "the", "context", "if", "the", "request", "contains", "a", "GCE", "VM", "metadata", "token", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/vmtoken/vmtoken.go#L235-L259
9,266
luci/luci-go
milo/frontend/view_builders.go
filterAuthorizedBuilders
func filterAuthorizedBuilders(c context.Context, builders []string) ([]string, error) { buckets := stringset.New(0) for _, b := range builders { id := buildsource.BuilderID(b) buildType, bucket, _, err := id.Split() if err != nil { logging.Warningf(c, "found malformed builder ID %q", id) continue } if buildType == "buildbucket" { buckets.Add(bucket) } } perms, err := common.BucketPermissions(c, buckets.ToSlice()...) if err != nil { return nil, err } okBuilders := make([]string, 0, len(builders)) for _, b := range builders { id := buildsource.BuilderID(b) buildType, bucket, _, err := id.Split() if err != nil { continue } if buildType != "buildbucket" || perms.Can(bucket, access.AccessBucket) { okBuilders = append(okBuilders, b) } } return okBuilders, nil }
go
func filterAuthorizedBuilders(c context.Context, builders []string) ([]string, error) { buckets := stringset.New(0) for _, b := range builders { id := buildsource.BuilderID(b) buildType, bucket, _, err := id.Split() if err != nil { logging.Warningf(c, "found malformed builder ID %q", id) continue } if buildType == "buildbucket" { buckets.Add(bucket) } } perms, err := common.BucketPermissions(c, buckets.ToSlice()...) if err != nil { return nil, err } okBuilders := make([]string, 0, len(builders)) for _, b := range builders { id := buildsource.BuilderID(b) buildType, bucket, _, err := id.Split() if err != nil { continue } if buildType != "buildbucket" || perms.Can(bucket, access.AccessBucket) { okBuilders = append(okBuilders, b) } } return okBuilders, nil }
[ "func", "filterAuthorizedBuilders", "(", "c", "context", ".", "Context", ",", "builders", "[", "]", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "buckets", ":=", "stringset", ".", "New", "(", "0", ")", "\n", "for", "_", ",", "b", ...
// filterAuthorizedBuilders filters out builders that the user does not have access to.
[ "filterAuthorizedBuilders", "filters", "out", "builders", "that", "the", "user", "does", "not", "have", "access", "to", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_builders.go#L115-L144
9,267
luci/luci-go
milo/frontend/view_builders.go
getBuilderHistories
func getBuilderHistories(c context.Context, builders []string, project string, limit int) ([]*builderHistory, error) { // Populate the recent histories. hists := make([]*builderHistory, len(builders)) err := parallel.WorkPool(16, func(ch chan<- func() error) { for i, builder := range builders { i := i builder := builder ch <- func() error { hist, err := getHistory(c, buildsource.BuilderID(builder), project, limit) if err != nil { return errors.Annotate( err, "error populating history for builder %s", builder).Err() } hists[i] = hist return nil } } }) if err != nil { return nil, err } // for all buildbot builders, we don't have pending BuildSummary entities, // so load pending counts from buildstore. var buildbotBuilders []string // "<master>/<builder>" strings var buildbotHists []*builderHistory for _, h := range hists { backend, master, builder, err := h.BuilderID.Split() if backend == "buildbot" && err == nil { buildbotHists = append(buildbotHists, h) buildbotBuilders = append(buildbotBuilders, fmt.Sprintf("%s/%s", master, builder)) } } if len(buildbotBuilders) > 0 { pendingCounts, err := buildstore.GetPendingCounts(c, buildbotBuilders) if err != nil { return nil, err } for i, count := range pendingCounts { buildbotHists[i].NumPending = count } } return hists, nil }
go
func getBuilderHistories(c context.Context, builders []string, project string, limit int) ([]*builderHistory, error) { // Populate the recent histories. hists := make([]*builderHistory, len(builders)) err := parallel.WorkPool(16, func(ch chan<- func() error) { for i, builder := range builders { i := i builder := builder ch <- func() error { hist, err := getHistory(c, buildsource.BuilderID(builder), project, limit) if err != nil { return errors.Annotate( err, "error populating history for builder %s", builder).Err() } hists[i] = hist return nil } } }) if err != nil { return nil, err } // for all buildbot builders, we don't have pending BuildSummary entities, // so load pending counts from buildstore. var buildbotBuilders []string // "<master>/<builder>" strings var buildbotHists []*builderHistory for _, h := range hists { backend, master, builder, err := h.BuilderID.Split() if backend == "buildbot" && err == nil { buildbotHists = append(buildbotHists, h) buildbotBuilders = append(buildbotBuilders, fmt.Sprintf("%s/%s", master, builder)) } } if len(buildbotBuilders) > 0 { pendingCounts, err := buildstore.GetPendingCounts(c, buildbotBuilders) if err != nil { return nil, err } for i, count := range pendingCounts { buildbotHists[i].NumPending = count } } return hists, nil }
[ "func", "getBuilderHistories", "(", "c", "context", ".", "Context", ",", "builders", "[", "]", "string", ",", "project", "string", ",", "limit", "int", ")", "(", "[", "]", "*", "builderHistory", ",", "error", ")", "{", "// Populate the recent histories.", "h...
// getBuilderHistories gets the recent histories for the builders in the given project.
[ "getBuilderHistories", "gets", "the", "recent", "histories", "for", "the", "builders", "in", "the", "given", "project", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_builders.go#L165-L209
9,268
luci/luci-go
milo/frontend/view_builders.go
getBuildersForProject
func getBuildersForProject(c context.Context, project, console string) ([]string, error) { var cons []*common.Console // Get consoles for project and extract builders into set. projKey := datastore.MakeKey(c, "Project", project) if console == "" { q := datastore.NewQuery("Console").Ancestor(projKey) if err := datastore.GetAll(c, q, &cons); err != nil { return nil, errors.Annotate( err, "error getting consoles for project %s", project).Err() } } else { con := common.Console{Parent: projKey, ID: console} switch err := datastore.Get(c, &con); err { case nil: case datastore.ErrNoSuchEntity: return nil, errors.Annotate( err, "error getting console %s in project %s", console, project). Tag(grpcutil.NotFoundTag).Err() default: return nil, errors.Annotate( err, "error getting console %s in project %s", console, project).Err() } cons = append(cons, &con) } bSet := stringset.New(0) for _, con := range cons { for _, builder := range con.Builders { bSet.Add(builder) } } // Get sorted builders. builders := bSet.ToSlice() sort.Strings(builders) return builders, nil }
go
func getBuildersForProject(c context.Context, project, console string) ([]string, error) { var cons []*common.Console // Get consoles for project and extract builders into set. projKey := datastore.MakeKey(c, "Project", project) if console == "" { q := datastore.NewQuery("Console").Ancestor(projKey) if err := datastore.GetAll(c, q, &cons); err != nil { return nil, errors.Annotate( err, "error getting consoles for project %s", project).Err() } } else { con := common.Console{Parent: projKey, ID: console} switch err := datastore.Get(c, &con); err { case nil: case datastore.ErrNoSuchEntity: return nil, errors.Annotate( err, "error getting console %s in project %s", console, project). Tag(grpcutil.NotFoundTag).Err() default: return nil, errors.Annotate( err, "error getting console %s in project %s", console, project).Err() } cons = append(cons, &con) } bSet := stringset.New(0) for _, con := range cons { for _, builder := range con.Builders { bSet.Add(builder) } } // Get sorted builders. builders := bSet.ToSlice() sort.Strings(builders) return builders, nil }
[ "func", "getBuildersForProject", "(", "c", "context", ".", "Context", ",", "project", ",", "console", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "cons", "[", "]", "*", "common", ".", "Console", "\n\n", "// Get consoles for proje...
// getBuildersForProject gets the sorted builder IDs associated with the given project.
[ "getBuildersForProject", "gets", "the", "sorted", "builder", "IDs", "associated", "with", "the", "given", "project", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_builders.go#L212-L249
9,269
luci/luci-go
tokenserver/appengine/impl/utils/sn.go
SerializeSN
func SerializeSN(sn *big.Int) ([]byte, error) { blob, err := sn.GobEncode() if err != nil { return nil, fmt.Errorf("can't encode SN - %s", err) } return blob, nil }
go
func SerializeSN(sn *big.Int) ([]byte, error) { blob, err := sn.GobEncode() if err != nil { return nil, fmt.Errorf("can't encode SN - %s", err) } return blob, nil }
[ "func", "SerializeSN", "(", "sn", "*", "big", ".", "Int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "blob", ",", "err", ":=", "sn", ".", "GobEncode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "...
// SerializeSN converts a certificate serial number to a byte blob.
[ "SerializeSN", "converts", "a", "certificate", "serial", "number", "to", "a", "byte", "blob", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/sn.go#L23-L29
9,270
luci/luci-go
scheduler/appengine/catalog/catalog.go
validateProjectConfig
func (cat *catalog) validateProjectConfig(ctx *validation.Context, configSet, path string, content []byte) error { var cfg messages.ProjectConfig err := proto.UnmarshalText(string(content), &cfg) if err != nil { ctx.Error(err) return nil } // AclSets. ctx.Enter("acl_sets") knownACLSets := acl.ValidateACLSets(ctx, cfg.GetAclSets()) ctx.Exit() knownIDs := stringset.New(len(cfg.Job) + len(cfg.Trigger)) // Jobs. ctx.Enter("job") for _, job := range cfg.Job { id := "(empty)" if job.Id != "" { id = job.Id } ctx.Enter(id) if job.Id != "" && !knownIDs.Add(job.Id) { ctx.Errorf("duplicate id %q", job.Id) } cat.validateJobProto(ctx, job) acl.ValidateTaskACLs(ctx, knownACLSets, job.GetAclSets(), job.GetAcls()) ctx.Exit() } ctx.Exit() // Triggers. ctx.Enter("trigger") allJobIDs := getAllJobIDs(&cfg) for _, trigger := range cfg.Trigger { id := "(empty)" if trigger.Id != "" { id = trigger.Id } ctx.Enter(id) if trigger.Id != "" && !knownIDs.Add(trigger.Id) { ctx.Errorf("duplicate id %q", trigger.Id) } cat.validateTriggerProto(ctx, trigger, allJobIDs, true) acl.ValidateTaskACLs(ctx, knownACLSets, trigger.GetAclSets(), trigger.GetAcls()) ctx.Exit() } ctx.Exit() return nil }
go
func (cat *catalog) validateProjectConfig(ctx *validation.Context, configSet, path string, content []byte) error { var cfg messages.ProjectConfig err := proto.UnmarshalText(string(content), &cfg) if err != nil { ctx.Error(err) return nil } // AclSets. ctx.Enter("acl_sets") knownACLSets := acl.ValidateACLSets(ctx, cfg.GetAclSets()) ctx.Exit() knownIDs := stringset.New(len(cfg.Job) + len(cfg.Trigger)) // Jobs. ctx.Enter("job") for _, job := range cfg.Job { id := "(empty)" if job.Id != "" { id = job.Id } ctx.Enter(id) if job.Id != "" && !knownIDs.Add(job.Id) { ctx.Errorf("duplicate id %q", job.Id) } cat.validateJobProto(ctx, job) acl.ValidateTaskACLs(ctx, knownACLSets, job.GetAclSets(), job.GetAcls()) ctx.Exit() } ctx.Exit() // Triggers. ctx.Enter("trigger") allJobIDs := getAllJobIDs(&cfg) for _, trigger := range cfg.Trigger { id := "(empty)" if trigger.Id != "" { id = trigger.Id } ctx.Enter(id) if trigger.Id != "" && !knownIDs.Add(trigger.Id) { ctx.Errorf("duplicate id %q", trigger.Id) } cat.validateTriggerProto(ctx, trigger, allJobIDs, true) acl.ValidateTaskACLs(ctx, knownACLSets, trigger.GetAclSets(), trigger.GetAcls()) ctx.Exit() } ctx.Exit() return nil }
[ "func", "(", "cat", "*", "catalog", ")", "validateProjectConfig", "(", "ctx", "*", "validation", ".", "Context", ",", "configSet", ",", "path", "string", ",", "content", "[", "]", "byte", ")", "error", "{", "var", "cfg", "messages", ".", "ProjectConfig", ...
// validateProjectConfig validates the content of a project config file. // // Validation errors are returned via validation.Context. Returns an error if // the validation itself fails for some reason.
[ "validateProjectConfig", "validates", "the", "content", "of", "a", "project", "config", "file", ".", "Validation", "errors", "are", "returned", "via", "validation", ".", "Context", ".", "Returns", "an", "error", "if", "the", "validation", "itself", "fails", "for...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/catalog/catalog.go#L366-L416
9,271
luci/luci-go
scheduler/appengine/catalog/catalog.go
validateTriggerProto
func (cat *catalog) validateTriggerProto(ctx *validation.Context, t *messages.Trigger, jobIDs stringset.Set, failOnMissing bool) proto.Message { if t.Id == "" { ctx.Errorf("missing 'id' field'") } else if !jobIDRe.MatchString(t.Id) { ctx.Errorf("%q is not valid value for 'id' field", t.Id) } if t.Schedule != "" { ctx.Enter("schedule") if _, err := schedule.Parse(t.Schedule, 0); err != nil { ctx.Errorf("%s is not valid value for 'schedule' field - %s", t.Schedule, err) } ctx.Exit() } filtered := make([]string, 0, len(t.Triggers)) for _, id := range t.Triggers { switch { case jobIDs.Has(id): filtered = append(filtered, id) case failOnMissing: ctx.Errorf("referencing unknown job %q in 'triggers' field", id) default: logging.Warningf(ctx.Context, "Trigger %q references unknown job %q in 'triggers' field", t.Id, id) } } t.Triggers = filtered cat.validateTriggeringPolicy(ctx, t.TriggeringPolicy) return cat.validateTaskProto(ctx, t) }
go
func (cat *catalog) validateTriggerProto(ctx *validation.Context, t *messages.Trigger, jobIDs stringset.Set, failOnMissing bool) proto.Message { if t.Id == "" { ctx.Errorf("missing 'id' field'") } else if !jobIDRe.MatchString(t.Id) { ctx.Errorf("%q is not valid value for 'id' field", t.Id) } if t.Schedule != "" { ctx.Enter("schedule") if _, err := schedule.Parse(t.Schedule, 0); err != nil { ctx.Errorf("%s is not valid value for 'schedule' field - %s", t.Schedule, err) } ctx.Exit() } filtered := make([]string, 0, len(t.Triggers)) for _, id := range t.Triggers { switch { case jobIDs.Has(id): filtered = append(filtered, id) case failOnMissing: ctx.Errorf("referencing unknown job %q in 'triggers' field", id) default: logging.Warningf(ctx.Context, "Trigger %q references unknown job %q in 'triggers' field", t.Id, id) } } t.Triggers = filtered cat.validateTriggeringPolicy(ctx, t.TriggeringPolicy) return cat.validateTaskProto(ctx, t) }
[ "func", "(", "cat", "*", "catalog", ")", "validateTriggerProto", "(", "ctx", "*", "validation", ".", "Context", ",", "t", "*", "messages", ".", "Trigger", ",", "jobIDs", "stringset", ".", "Set", ",", "failOnMissing", "bool", ")", "proto", ".", "Message", ...
// validateTriggerProto validates and filters messages.Trigger protobuf message. // // It also extracts a task definition from it. // // Takes a set of all defined job IDs, to verify the trigger triggers only // declared jobs. If failOnMissing is true, referencing an undefined job is // reported as a validation error. Otherwise it is logged as a warning, and the // reference to the undefined job is removed. // // Errors are returned via validation.Context.
[ "validateTriggerProto", "validates", "and", "filters", "messages", ".", "Trigger", "protobuf", "message", ".", "It", "also", "extracts", "a", "task", "definition", "from", "it", ".", "Takes", "a", "set", "of", "all", "defined", "job", "IDs", "to", "verify", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/catalog/catalog.go#L449-L477
9,272
luci/luci-go
scheduler/appengine/catalog/catalog.go
validateTriggeringPolicy
func (cat *catalog) validateTriggeringPolicy(ctx *validation.Context, p *messages.TriggeringPolicy) { if p != nil { ctx.Enter("triggering_policy") policy.ValidateDefinition(ctx, p) ctx.Exit() } }
go
func (cat *catalog) validateTriggeringPolicy(ctx *validation.Context, p *messages.TriggeringPolicy) { if p != nil { ctx.Enter("triggering_policy") policy.ValidateDefinition(ctx, p) ctx.Exit() } }
[ "func", "(", "cat", "*", "catalog", ")", "validateTriggeringPolicy", "(", "ctx", "*", "validation", ".", "Context", ",", "p", "*", "messages", ".", "TriggeringPolicy", ")", "{", "if", "p", "!=", "nil", "{", "ctx", ".", "Enter", "(", "\"", "\"", ")", ...
// validateTriggeringPolicy validates TriggeringPolicy proto. // // Errors are returned via validation.Context.
[ "validateTriggeringPolicy", "validates", "TriggeringPolicy", "proto", ".", "Errors", "are", "returned", "via", "validation", ".", "Context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/catalog/catalog.go#L529-L535
9,273
luci/luci-go
scheduler/appengine/catalog/catalog.go
normalizeTriggeredJobIDs
func normalizeTriggeredJobIDs(projectID string, t *messages.Trigger) []string { set := stringset.New(len(t.Triggers)) for _, j := range t.Triggers { set.Add(projectID + "/" + j) } out := set.ToSlice() sort.Strings(out) return out }
go
func normalizeTriggeredJobIDs(projectID string, t *messages.Trigger) []string { set := stringset.New(len(t.Triggers)) for _, j := range t.Triggers { set.Add(projectID + "/" + j) } out := set.ToSlice() sort.Strings(out) return out }
[ "func", "normalizeTriggeredJobIDs", "(", "projectID", "string", ",", "t", "*", "messages", ".", "Trigger", ")", "[", "]", "string", "{", "set", ":=", "stringset", ".", "New", "(", "len", "(", "t", ".", "Triggers", ")", ")", "\n", "for", "_", ",", "j"...
// normalizeTriggeredJobIDs returns sorted list without duplicates.
[ "normalizeTriggeredJobIDs", "returns", "sorted", "list", "without", "duplicates", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/catalog/catalog.go#L590-L598
9,274
luci/luci-go
scheduler/appengine/catalog/catalog.go
marshalTriggeringPolicy
func marshalTriggeringPolicy(p *messages.TriggeringPolicy) []byte { if p == nil { return nil } out, err := proto.Marshal(p) if err != nil { panic(fmt.Errorf("failed to marshal TriggeringPolicy - %s", err)) } return out }
go
func marshalTriggeringPolicy(p *messages.TriggeringPolicy) []byte { if p == nil { return nil } out, err := proto.Marshal(p) if err != nil { panic(fmt.Errorf("failed to marshal TriggeringPolicy - %s", err)) } return out }
[ "func", "marshalTriggeringPolicy", "(", "p", "*", "messages", ".", "TriggeringPolicy", ")", "[", "]", "byte", "{", "if", "p", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ",", "err", ":=", "proto", ".", "Marshal", "(", "p", ")", "\n", ...
// marshalTriggeringPolicy serializes TriggeringPolicy proto.
[ "marshalTriggeringPolicy", "serializes", "TriggeringPolicy", "proto", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/catalog/catalog.go#L601-L610
9,275
luci/luci-go
machine-db/client/cli/cli.go
createClient
func createClient(c context.Context, params *Parameters) crimson.CrimsonClient { client, err := auth.NewAuthenticator(c, auth.InteractiveLogin, params.AuthOptions).Client() if err != nil { errors.Log(c, err) panic("failed to get authenticated HTTP client") } return crimson.NewCrimsonPRPCClient(&prpc.Client{ C: client, Host: params.Host, }) }
go
func createClient(c context.Context, params *Parameters) crimson.CrimsonClient { client, err := auth.NewAuthenticator(c, auth.InteractiveLogin, params.AuthOptions).Client() if err != nil { errors.Log(c, err) panic("failed to get authenticated HTTP client") } return crimson.NewCrimsonPRPCClient(&prpc.Client{ C: client, Host: params.Host, }) }
[ "func", "createClient", "(", "c", "context", ".", "Context", ",", "params", "*", "Parameters", ")", "crimson", ".", "CrimsonClient", "{", "client", ",", "err", ":=", "auth", ".", "NewAuthenticator", "(", "c", ",", "auth", ".", "InteractiveLogin", ",", "par...
// createClient creates and returns a client which can make RPC requests to the Machine Database. // Panics if the client cannot be created.
[ "createClient", "creates", "and", "returns", "a", "client", "which", "can", "make", "RPC", "requests", "to", "the", "Machine", "Database", ".", "Panics", "if", "the", "client", "cannot", "be", "created", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/cli.go#L47-L57
9,276
luci/luci-go
machine-db/client/cli/cli.go
getClient
func getClient(c context.Context) crimson.CrimsonClient { return c.Value(&clientKey).(crimson.CrimsonClient) }
go
func getClient(c context.Context) crimson.CrimsonClient { return c.Value(&clientKey).(crimson.CrimsonClient) }
[ "func", "getClient", "(", "c", "context", ".", "Context", ")", "crimson", ".", "CrimsonClient", "{", "return", "c", ".", "Value", "(", "&", "clientKey", ")", ".", "(", "crimson", ".", "CrimsonClient", ")", "\n", "}" ]
// getClient retrieves the client pointer embedded in the current context. // The client pointer can be embedded in the current context using withClient.
[ "getClient", "retrieves", "the", "client", "pointer", "embedded", "in", "the", "current", "context", ".", "The", "client", "pointer", "can", "be", "embedded", "in", "the", "current", "context", "using", "withClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/cli.go#L61-L63
9,277
luci/luci-go
machine-db/client/cli/cli.go
withClient
func withClient(c context.Context, client crimson.CrimsonClient) context.Context { return context.WithValue(c, &clientKey, client) }
go
func withClient(c context.Context, client crimson.CrimsonClient) context.Context { return context.WithValue(c, &clientKey, client) }
[ "func", "withClient", "(", "c", "context", ".", "Context", ",", "client", "crimson", ".", "CrimsonClient", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "&", "clientKey", ",", "client", ")", "\n", "}" ]
// withClient installs an RPC client pointer into the given context. // It can be retrieved later on with getClient.
[ "withClient", "installs", "an", "RPC", "client", "pointer", "into", "the", "given", "context", ".", "It", "can", "be", "retrieved", "later", "on", "with", "getClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/cli.go#L67-L69
9,278
luci/luci-go
machine-db/client/cli/cli.go
Initialize
func (c *commandBase) Initialize(params *Parameters) { c.p = params c.f.Register(c.GetFlags(), params) }
go
func (c *commandBase) Initialize(params *Parameters) { c.p = params c.f.Register(c.GetFlags(), params) }
[ "func", "(", "c", "*", "commandBase", ")", "Initialize", "(", "params", "*", "Parameters", ")", "{", "c", ".", "p", "=", "params", "\n", "c", ".", "f", ".", "Register", "(", "c", ".", "GetFlags", "(", ")", ",", "params", ")", "\n", "}" ]
// Initialize initializes the commandBase instance, registering common flags.
[ "Initialize", "initializes", "the", "commandBase", "instance", "registering", "common", "flags", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/cli.go#L80-L83
9,279
luci/luci-go
machine-db/client/cli/cli.go
ModifyContext
func (c *commandBase) ModifyContext(ctx context.Context) context.Context { cfg := gologger.LoggerConfig{ Format: gologger.StdFormatWithColor, Out: os.Stderr, } opts, err := c.f.authFlags.Options() if err != nil { errors.Log(ctx, err) panic("failed to get authentication options") } c.p.AuthOptions = opts return withClient(cfg.Use(ctx), createClient(ctx, c.p)) }
go
func (c *commandBase) ModifyContext(ctx context.Context) context.Context { cfg := gologger.LoggerConfig{ Format: gologger.StdFormatWithColor, Out: os.Stderr, } opts, err := c.f.authFlags.Options() if err != nil { errors.Log(ctx, err) panic("failed to get authentication options") } c.p.AuthOptions = opts return withClient(cfg.Use(ctx), createClient(ctx, c.p)) }
[ "func", "(", "c", "*", "commandBase", ")", "ModifyContext", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "cfg", ":=", "gologger", ".", "LoggerConfig", "{", "Format", ":", "gologger", ".", "StdFormatWithColor", ",", "Out", ":"...
// ModifyContext returns a new context to be used with subcommands. // Configures the context's logging and embeds the Machine Database RPC client. // Implements cli.ContextModificator.
[ "ModifyContext", "returns", "a", "new", "context", "to", "be", "used", "with", "subcommands", ".", "Configures", "the", "context", "s", "logging", "and", "embeds", "the", "Machine", "Database", "RPC", "client", ".", "Implements", "cli", ".", "ContextModificator"...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/cli.go#L88-L100
9,280
luci/luci-go
machine-db/client/cli/cli.go
New
func New(params *Parameters) *cli.Application { return &cli.Application{ Name: "crimson", Title: "Machine Database client", Commands: []*subcommands.Command{ subcommands.CmdHelp, {}, // Create an empty command to separate groups of similar commands. // Authentication. authcli.SubcommandInfo(params.AuthOptions, "auth-info", true), authcli.SubcommandLogin(params.AuthOptions, "auth-login", false), authcli.SubcommandLogout(params.AuthOptions, "auth-logout", false), {}, // Static entities. getDatacentersCmd(params), getIPsCmd(params), getKVMsCmd(params), getOSesCmd(params), getPlatformsCmd(params), getRacksCmd(params), getSwitchesCmd(params), getVLANsCmd(params), {}, // Machines. addMachineCmd(params), deleteMachineCmd(params), editMachineCmd(params), getMachinesCmd(params), renameMachineCmd(params), {}, // Network interfaces. addNICCmd(params), deleteNICCmd(params), editNICCmd(params), getNICsCmd(params), {}, // DRACs. addDRACCmd(params), editDRACCmd(params), getDRACsCmd(params), {}, // Physical hosts. addPhysicalHostCmd(params), editPhysicalHostCmd(params), getPhysicalHostsCmd(params), {}, // VM slots. getVMSlotsCmd(params), {}, // Virtual hosts. addVMCmd(params), editVMCmd(params), getVMsCmd(params), {}, // Hostnames. deleteHostCmd(params), {}, // States. getStatesCmd(params), }, } }
go
func New(params *Parameters) *cli.Application { return &cli.Application{ Name: "crimson", Title: "Machine Database client", Commands: []*subcommands.Command{ subcommands.CmdHelp, {}, // Create an empty command to separate groups of similar commands. // Authentication. authcli.SubcommandInfo(params.AuthOptions, "auth-info", true), authcli.SubcommandLogin(params.AuthOptions, "auth-login", false), authcli.SubcommandLogout(params.AuthOptions, "auth-logout", false), {}, // Static entities. getDatacentersCmd(params), getIPsCmd(params), getKVMsCmd(params), getOSesCmd(params), getPlatformsCmd(params), getRacksCmd(params), getSwitchesCmd(params), getVLANsCmd(params), {}, // Machines. addMachineCmd(params), deleteMachineCmd(params), editMachineCmd(params), getMachinesCmd(params), renameMachineCmd(params), {}, // Network interfaces. addNICCmd(params), deleteNICCmd(params), editNICCmd(params), getNICsCmd(params), {}, // DRACs. addDRACCmd(params), editDRACCmd(params), getDRACsCmd(params), {}, // Physical hosts. addPhysicalHostCmd(params), editPhysicalHostCmd(params), getPhysicalHostsCmd(params), {}, // VM slots. getVMSlotsCmd(params), {}, // Virtual hosts. addVMCmd(params), editVMCmd(params), getVMsCmd(params), {}, // Hostnames. deleteHostCmd(params), {}, // States. getStatesCmd(params), }, } }
[ "func", "New", "(", "params", "*", "Parameters", ")", "*", "cli", ".", "Application", "{", "return", "&", "cli", ".", "Application", "{", "Name", ":", "\"", "\"", ",", "Title", ":", "\"", "\"", ",", "Commands", ":", "[", "]", "*", "subcommands", "....
// New returns the Machine Database command-line application.
[ "New", "returns", "the", "Machine", "Database", "command", "-", "line", "application", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/cli.go#L103-L173
9,281
luci/luci-go
auth/auth.go
GetAccessToken
func (a *Authenticator) GetAccessToken(lifetime time.Duration) (*oauth2.Token, error) { tok, err := a.currentToken() if err != nil { return nil, err } // Impose some arbitrary limit, since <= 0 lifetime won't work. if lifetime < time.Second { lifetime = time.Second } if tok == nil || internal.TokenExpiresInRnd(a.ctx, tok, lifetime) { // Give 5 sec extra to make sure callers definitely receive a token that // has at least 'lifetime' seconds of life left. Without this margin, we // can get into an unlucky situation where the token is valid here, but // no longer valid (has fewer than 'lifetime' life left) up the stack, due // to the passage of time. var err error tok, err = a.refreshToken(tok, lifetime+5*time.Second) if err != nil { return nil, err } // Note: no randomization here. It is a sanity check that verifies // refreshToken did its job. if internal.TokenExpiresIn(a.ctx, tok, lifetime) { return nil, fmt.Errorf("auth: failed to refresh the token") } } return &tok.Token, nil }
go
func (a *Authenticator) GetAccessToken(lifetime time.Duration) (*oauth2.Token, error) { tok, err := a.currentToken() if err != nil { return nil, err } // Impose some arbitrary limit, since <= 0 lifetime won't work. if lifetime < time.Second { lifetime = time.Second } if tok == nil || internal.TokenExpiresInRnd(a.ctx, tok, lifetime) { // Give 5 sec extra to make sure callers definitely receive a token that // has at least 'lifetime' seconds of life left. Without this margin, we // can get into an unlucky situation where the token is valid here, but // no longer valid (has fewer than 'lifetime' life left) up the stack, due // to the passage of time. var err error tok, err = a.refreshToken(tok, lifetime+5*time.Second) if err != nil { return nil, err } // Note: no randomization here. It is a sanity check that verifies // refreshToken did its job. if internal.TokenExpiresIn(a.ctx, tok, lifetime) { return nil, fmt.Errorf("auth: failed to refresh the token") } } return &tok.Token, nil }
[ "func", "(", "a", "*", "Authenticator", ")", "GetAccessToken", "(", "lifetime", "time", ".", "Duration", ")", "(", "*", "oauth2", ".", "Token", ",", "error", ")", "{", "tok", ",", "err", ":=", "a", ".", "currentToken", "(", ")", "\n", "if", "err", ...
// GetAccessToken returns a valid access token with specified minimum lifetime. // // Does not interact with the user. May return ErrLoginRequired.
[ "GetAccessToken", "returns", "a", "valid", "access", "token", "with", "specified", "minimum", "lifetime", ".", "Does", "not", "interact", "with", "the", "user", ".", "May", "return", "ErrLoginRequired", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L582-L609
9,282
luci/luci-go
auth/auth.go
GetEmail
func (a *Authenticator) GetEmail() (string, error) { // Grab last known token and its associated email. Note that this call also // initializes the guts of the authenticator, including a.authToken. tok, err := a.currentToken() switch { case err != nil: return "", err case tok != nil && tok.Email == internal.NoEmail: return "", ErrNoEmail case tok != nil && tok.Email != internal.UnknownEmail: return tok.Email, nil } // There's no token cached yet (and thus email is not known). First try to ask // the provider for email only. Most providers can return it without doing any // RPCs or heavy calls. If this is not supported, resort to a heavier code // paths that actually refreshes the token and grabs its email along the way. a.lock.RLock() email := a.authToken.provider.Email() a.lock.RUnlock() switch { case email == internal.NoEmail: return "", ErrNoEmail case email != "": return email, nil } // The provider doesn't know the email. We need a forceful token refresh to // grab it (or discover it is NoEmail). This is relatively rare. It happens // only when using UserAuth TokenProvider and there's no cached token at all // or it is in old format that don't have email field. // // Pass -1 as lifetime to force trigger the refresh right now. tok, err = a.refreshToken(tok, -1) switch { case err != nil: return "", err case tok.Email == internal.NoEmail: return "", ErrNoEmail case tok.Email == internal.UnknownEmail: // this must not happen, but let's be cautious return "", fmt.Errorf("internal error when fetching the email, see logs") default: return tok.Email, nil } }
go
func (a *Authenticator) GetEmail() (string, error) { // Grab last known token and its associated email. Note that this call also // initializes the guts of the authenticator, including a.authToken. tok, err := a.currentToken() switch { case err != nil: return "", err case tok != nil && tok.Email == internal.NoEmail: return "", ErrNoEmail case tok != nil && tok.Email != internal.UnknownEmail: return tok.Email, nil } // There's no token cached yet (and thus email is not known). First try to ask // the provider for email only. Most providers can return it without doing any // RPCs or heavy calls. If this is not supported, resort to a heavier code // paths that actually refreshes the token and grabs its email along the way. a.lock.RLock() email := a.authToken.provider.Email() a.lock.RUnlock() switch { case email == internal.NoEmail: return "", ErrNoEmail case email != "": return email, nil } // The provider doesn't know the email. We need a forceful token refresh to // grab it (or discover it is NoEmail). This is relatively rare. It happens // only when using UserAuth TokenProvider and there's no cached token at all // or it is in old format that don't have email field. // // Pass -1 as lifetime to force trigger the refresh right now. tok, err = a.refreshToken(tok, -1) switch { case err != nil: return "", err case tok.Email == internal.NoEmail: return "", ErrNoEmail case tok.Email == internal.UnknownEmail: // this must not happen, but let's be cautious return "", fmt.Errorf("internal error when fetching the email, see logs") default: return tok.Email, nil } }
[ "func", "(", "a", "*", "Authenticator", ")", "GetEmail", "(", ")", "(", "string", ",", "error", ")", "{", "// Grab last known token and its associated email. Note that this call also", "// initializes the guts of the authenticator, including a.authToken.", "tok", ",", "err", ...
// GetEmail returns an email associated with the credentials. // // In most cases this is a fast call that hits the cache. In some rare cases it // may do an RPC to the Token Info endpoint to grab an email associated with the // token. // // Returns ErrNoEmail if the email is not available. This may happen, for // example, when using a refresh token that doesn't have 'userinfo.email' scope. // Callers must expect this error to show up and should prepare a fallback. // // Returns an error if the email can't be fetched due to some other transient // or fatal error. In particular, returns ErrLoginRequired if interactive login // is required to get the token in the first place.
[ "GetEmail", "returns", "an", "email", "associated", "with", "the", "credentials", ".", "In", "most", "cases", "this", "is", "a", "fast", "call", "that", "hits", "the", "cache", ".", "In", "some", "rare", "cases", "it", "may", "do", "an", "RPC", "to", "...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L624-L668
9,283
luci/luci-go
auth/auth.go
PurgeCredentialsCache
func (a *Authenticator) PurgeCredentialsCache() error { a.lock.Lock() defer a.lock.Unlock() if err := a.ensureInitialized(); err != nil { return err } return a.purgeCredentialsCacheLocked() }
go
func (a *Authenticator) PurgeCredentialsCache() error { a.lock.Lock() defer a.lock.Unlock() if err := a.ensureInitialized(); err != nil { return err } return a.purgeCredentialsCacheLocked() }
[ "func", "(", "a", "*", "Authenticator", ")", "PurgeCredentialsCache", "(", ")", "error", "{", "a", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "lock", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "a", ".", "ensureInitialized", ...
// PurgeCredentialsCache removes cached tokens. // // Does not revoke them!
[ "PurgeCredentialsCache", "removes", "cached", "tokens", ".", "Does", "not", "revoke", "them!" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L753-L760
9,284
luci/luci-go
auth/auth.go
Token
func (s tokenSource) Token() (*oauth2.Token, error) { return s.a.GetAccessToken(minAcceptedLifetime) }
go
func (s tokenSource) Token() (*oauth2.Token, error) { return s.a.GetAccessToken(minAcceptedLifetime) }
[ "func", "(", "s", "tokenSource", ")", "Token", "(", ")", "(", "*", "oauth2", ".", "Token", ",", "error", ")", "{", "return", "s", ".", "a", ".", "GetAccessToken", "(", "minAcceptedLifetime", ")", "\n", "}" ]
// Token is part of oauth2.TokenSource inteface.
[ "Token", "is", "part", "of", "oauth2", ".", "TokenSource", "inteface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L817-L819
9,285
luci/luci-go
auth/auth.go
ensureInitialized
func (a *Authenticator) ensureInitialized() error { // Already initialized (successfully or not)? if initialized, err := a.checkInitialized(); initialized { return err } // SelectBestMethod may do heavy calls like talking to GCE metadata server, // call it lazily here rather than in NewAuthenticator. if a.opts.Method == AutoSelectMethod { a.opts.Method = SelectBestMethod(a.ctx, *a.opts) } // In Actor mode, make the base token IAM-scoped, to be able to use SignBlob // API. In non-actor mode, the base token is also the main auth token, so // scope it to whatever options were requested. scopes := a.opts.Scopes if a.isActing() { scopes = []string{iam.OAuthScope} } a.baseToken = &tokenWithProvider{} a.baseToken.provider, a.err = makeBaseTokenProvider(a.ctx, a.opts, scopes) if a.err != nil { return a.err // note: this can be ErrInsufficientAccess } // In non-actor mode, the token we must check in 'CheckLoginRequired' is the // same as returned by 'GetAccessToken'. In actor mode, they are different. // See comments for 'baseToken' and 'authToken'. if a.isActing() { a.authToken = &tokenWithProvider{} a.authToken.provider, a.err = makeIAMTokenProvider(a.ctx, a.opts) if a.err != nil { return a.err } } else { a.authToken = a.baseToken } // Initialize the token cache. Use the disk cache only if SecretsDir is given // and any of the providers is not "lightweight" (so it makes sense to // actually hit the disk, rather then call the provider each time new token is // needed). // // Note also that tests set a.testingCache before ensureInitialized() is // called to mock the cache. Respect this. if a.testingCache != nil { a.baseToken.cache = a.testingCache a.authToken.cache = a.testingCache } else { cache := internal.ProcTokenCache if !a.baseToken.provider.Lightweight() || !a.authToken.provider.Lightweight() { if a.opts.SecretsDir != "" { cache = &internal.DiskTokenCache{ Context: a.ctx, SecretsDir: a.opts.SecretsDir, } } else { logging.Warningf(a.ctx, "Disabling auth disk token cache. Not configured.") } } // Use the disk cache only for non-lightweight providers to avoid // unnecessarily leaks of tokens to the disk. if a.baseToken.provider.Lightweight() { a.baseToken.cache = internal.ProcTokenCache } else { a.baseToken.cache = cache } if a.authToken.provider.Lightweight() { a.authToken.cache = internal.ProcTokenCache } else { a.authToken.cache = cache } } // Interactive providers need to know whether there's a cached token (to ask // to run interactive login if there's none). Non-interactive providers do not // care about state of the cache that much (they know how to update it // themselves). So examine the cache here only when using interactive // provider. Non interactive providers will do it lazily on a first // refreshToken(...) call. if a.baseToken.provider.RequiresInteraction() { // Broken token cache is not a fatal error. So just log it and forget, a new // token will be minted in Login. if err := a.baseToken.fetchFromCache(a.ctx); err != nil { logging.Warningf(a.ctx, "Failed to read auth token from cache: %s", err) } } // Note: a.authToken.provider is either equal to a.baseToken.provider (if not // using actor mode), or (when using actor mode) it doesn't require // interaction (because it is an IAM one). So don't bother with fetching // 'authToken' from cache. It will be fetched lazily on the first use. return nil }
go
func (a *Authenticator) ensureInitialized() error { // Already initialized (successfully or not)? if initialized, err := a.checkInitialized(); initialized { return err } // SelectBestMethod may do heavy calls like talking to GCE metadata server, // call it lazily here rather than in NewAuthenticator. if a.opts.Method == AutoSelectMethod { a.opts.Method = SelectBestMethod(a.ctx, *a.opts) } // In Actor mode, make the base token IAM-scoped, to be able to use SignBlob // API. In non-actor mode, the base token is also the main auth token, so // scope it to whatever options were requested. scopes := a.opts.Scopes if a.isActing() { scopes = []string{iam.OAuthScope} } a.baseToken = &tokenWithProvider{} a.baseToken.provider, a.err = makeBaseTokenProvider(a.ctx, a.opts, scopes) if a.err != nil { return a.err // note: this can be ErrInsufficientAccess } // In non-actor mode, the token we must check in 'CheckLoginRequired' is the // same as returned by 'GetAccessToken'. In actor mode, they are different. // See comments for 'baseToken' and 'authToken'. if a.isActing() { a.authToken = &tokenWithProvider{} a.authToken.provider, a.err = makeIAMTokenProvider(a.ctx, a.opts) if a.err != nil { return a.err } } else { a.authToken = a.baseToken } // Initialize the token cache. Use the disk cache only if SecretsDir is given // and any of the providers is not "lightweight" (so it makes sense to // actually hit the disk, rather then call the provider each time new token is // needed). // // Note also that tests set a.testingCache before ensureInitialized() is // called to mock the cache. Respect this. if a.testingCache != nil { a.baseToken.cache = a.testingCache a.authToken.cache = a.testingCache } else { cache := internal.ProcTokenCache if !a.baseToken.provider.Lightweight() || !a.authToken.provider.Lightweight() { if a.opts.SecretsDir != "" { cache = &internal.DiskTokenCache{ Context: a.ctx, SecretsDir: a.opts.SecretsDir, } } else { logging.Warningf(a.ctx, "Disabling auth disk token cache. Not configured.") } } // Use the disk cache only for non-lightweight providers to avoid // unnecessarily leaks of tokens to the disk. if a.baseToken.provider.Lightweight() { a.baseToken.cache = internal.ProcTokenCache } else { a.baseToken.cache = cache } if a.authToken.provider.Lightweight() { a.authToken.cache = internal.ProcTokenCache } else { a.authToken.cache = cache } } // Interactive providers need to know whether there's a cached token (to ask // to run interactive login if there's none). Non-interactive providers do not // care about state of the cache that much (they know how to update it // themselves). So examine the cache here only when using interactive // provider. Non interactive providers will do it lazily on a first // refreshToken(...) call. if a.baseToken.provider.RequiresInteraction() { // Broken token cache is not a fatal error. So just log it and forget, a new // token will be minted in Login. if err := a.baseToken.fetchFromCache(a.ctx); err != nil { logging.Warningf(a.ctx, "Failed to read auth token from cache: %s", err) } } // Note: a.authToken.provider is either equal to a.baseToken.provider (if not // using actor mode), or (when using actor mode) it doesn't require // interaction (because it is an IAM one). So don't bother with fetching // 'authToken' from cache. It will be fetched lazily on the first use. return nil }
[ "func", "(", "a", "*", "Authenticator", ")", "ensureInitialized", "(", ")", "error", "{", "// Already initialized (successfully or not)?", "if", "initialized", ",", "err", ":=", "a", ".", "checkInitialized", "(", ")", ";", "initialized", "{", "return", "err", "\...
// ensureInitialized instantiates TokenProvider and reads token from cache. // // It is supposed to be called under the lock.
[ "ensureInitialized", "instantiates", "TokenProvider", "and", "reads", "token", "from", "cache", ".", "It", "is", "supposed", "to", "be", "called", "under", "the", "lock", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L843-L937
9,286
luci/luci-go
auth/auth.go
getBaseTokenLocked
func (a *Authenticator) getBaseTokenLocked(ctx context.Context, lifetime time.Duration) (*internal.Token, error) { if !a.isActing() { panic("impossible") } // Already have a good token? if lifetime > 0 && !internal.TokenExpiresInRnd(ctx, a.baseToken.token, lifetime) { return a.baseToken.token, nil } // Need to make one. return a.baseToken.compareAndRefresh(ctx, compareAndRefreshOp{ lock: nil, // already holding the lock prev: a.baseToken.token, lifetime: lifetime, refreshCb: func(ctx context.Context, prev *internal.Token) (*internal.Token, error) { return a.baseToken.renewToken(ctx, prev, nil) }, }) }
go
func (a *Authenticator) getBaseTokenLocked(ctx context.Context, lifetime time.Duration) (*internal.Token, error) { if !a.isActing() { panic("impossible") } // Already have a good token? if lifetime > 0 && !internal.TokenExpiresInRnd(ctx, a.baseToken.token, lifetime) { return a.baseToken.token, nil } // Need to make one. return a.baseToken.compareAndRefresh(ctx, compareAndRefreshOp{ lock: nil, // already holding the lock prev: a.baseToken.token, lifetime: lifetime, refreshCb: func(ctx context.Context, prev *internal.Token) (*internal.Token, error) { return a.baseToken.renewToken(ctx, prev, nil) }, }) }
[ "func", "(", "a", "*", "Authenticator", ")", "getBaseTokenLocked", "(", "ctx", "context", ".", "Context", ",", "lifetime", "time", ".", "Duration", ")", "(", "*", "internal", ".", "Token", ",", "error", ")", "{", "if", "!", "a", ".", "isActing", "(", ...
// getBaseTokenLocked is used to get an IAM-scoped token when running in // actor mode. // // Passing negative lifetime causes a forced refresh. // // It is called with a.lock locked.
[ "getBaseTokenLocked", "is", "used", "to", "get", "an", "IAM", "-", "scoped", "token", "when", "running", "in", "actor", "mode", ".", "Passing", "negative", "lifetime", "causes", "a", "forced", "refresh", ".", "It", "is", "called", "with", "a", ".", "lock",...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L1078-L1097
9,287
luci/luci-go
auth/auth.go
fetchFromCache
func (t *tokenWithProvider) fetchFromCache(ctx context.Context) error { key, err := t.provider.CacheKey(ctx) if err != nil { return err } tok, err := t.cache.GetToken(key) if err != nil { return err } t.token = tok return nil }
go
func (t *tokenWithProvider) fetchFromCache(ctx context.Context) error { key, err := t.provider.CacheKey(ctx) if err != nil { return err } tok, err := t.cache.GetToken(key) if err != nil { return err } t.token = tok return nil }
[ "func", "(", "t", "*", "tokenWithProvider", ")", "fetchFromCache", "(", "ctx", "context", ".", "Context", ")", "error", "{", "key", ",", "err", ":=", "t", ".", "provider", ".", "CacheKey", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return...
// fetchFromCache updates 't.token' by reading it from the cache.
[ "fetchFromCache", "updates", "t", ".", "token", "by", "reading", "it", "from", "the", "cache", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L1129-L1140
9,288
luci/luci-go
auth/auth.go
putToCache
func (t *tokenWithProvider) putToCache(ctx context.Context) error { key, err := t.provider.CacheKey(ctx) if err != nil { return err } return t.cache.PutToken(key, t.token) }
go
func (t *tokenWithProvider) putToCache(ctx context.Context) error { key, err := t.provider.CacheKey(ctx) if err != nil { return err } return t.cache.PutToken(key, t.token) }
[ "func", "(", "t", "*", "tokenWithProvider", ")", "putToCache", "(", "ctx", "context", ".", "Context", ")", "error", "{", "key", ",", "err", ":=", "t", ".", "provider", ".", "CacheKey", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// putToCache puts 't.token' value into the cache.
[ "putToCache", "puts", "t", ".", "token", "value", "into", "the", "cache", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L1143-L1149
9,289
luci/luci-go
auth/auth.go
purgeToken
func (t *tokenWithProvider) purgeToken(ctx context.Context) error { t.token = nil key, err := t.provider.CacheKey(ctx) if err != nil { return err } return t.cache.DeleteToken(key) }
go
func (t *tokenWithProvider) purgeToken(ctx context.Context) error { t.token = nil key, err := t.provider.CacheKey(ctx) if err != nil { return err } return t.cache.DeleteToken(key) }
[ "func", "(", "t", "*", "tokenWithProvider", ")", "purgeToken", "(", "ctx", "context", ".", "Context", ")", "error", "{", "t", ".", "token", "=", "nil", "\n", "key", ",", "err", ":=", "t", ".", "provider", ".", "CacheKey", "(", "ctx", ")", "\n", "if...
// purgeToken removes the token from both on-disk cache and memory.
[ "purgeToken", "removes", "the", "token", "from", "both", "on", "-", "disk", "cache", "and", "memory", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L1152-L1159
9,290
luci/luci-go
auth/auth.go
renewToken
func (t *tokenWithProvider) renewToken(ctx context.Context, prev, base *internal.Token) (*internal.Token, error) { if prev == nil { if t.provider.RequiresInteraction() { return nil, ErrLoginRequired } logging.Debugf(ctx, "Minting a new token") tok, err := t.mintTokenWithRetries(ctx, base) if err != nil { logging.Warningf(ctx, "Failed to mint a token: %s", err) return nil, err } return tok, nil } logging.Debugf(ctx, "Refreshing the token") tok, err := t.refreshTokenWithRetries(ctx, prev, base) if err != nil { logging.Warningf(ctx, "Failed to refresh the token: %s", err) return nil, err } return tok, nil }
go
func (t *tokenWithProvider) renewToken(ctx context.Context, prev, base *internal.Token) (*internal.Token, error) { if prev == nil { if t.provider.RequiresInteraction() { return nil, ErrLoginRequired } logging.Debugf(ctx, "Minting a new token") tok, err := t.mintTokenWithRetries(ctx, base) if err != nil { logging.Warningf(ctx, "Failed to mint a token: %s", err) return nil, err } return tok, nil } logging.Debugf(ctx, "Refreshing the token") tok, err := t.refreshTokenWithRetries(ctx, prev, base) if err != nil { logging.Warningf(ctx, "Failed to refresh the token: %s", err) return nil, err } return tok, nil }
[ "func", "(", "t", "*", "tokenWithProvider", ")", "renewToken", "(", "ctx", "context", ".", "Context", ",", "prev", ",", "base", "*", "internal", ".", "Token", ")", "(", "*", "internal", ".", "Token", ",", "error", ")", "{", "if", "prev", "==", "nil",...
// renewToken is called to mint a new token or update existing one. // // It is called from non-interactive 'refreshToken' method, and thus it can't // use interactive login flow.
[ "renewToken", "is", "called", "to", "mint", "a", "new", "token", "or", "update", "existing", "one", ".", "It", "is", "called", "from", "non", "-", "interactive", "refreshToken", "method", "and", "thus", "it", "can", "t", "use", "interactive", "login", "flo...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L1260-L1281
9,291
luci/luci-go
auth/auth.go
retryParams
func retryParams() retry.Iterator { return &retry.ExponentialBackoff{ Limited: retry.Limited{ Delay: 50 * time.Millisecond, Retries: 50, MaxTotal: 5 * time.Second, }, Multiplier: 2, } }
go
func retryParams() retry.Iterator { return &retry.ExponentialBackoff{ Limited: retry.Limited{ Delay: 50 * time.Millisecond, Retries: 50, MaxTotal: 5 * time.Second, }, Multiplier: 2, } }
[ "func", "retryParams", "(", ")", "retry", ".", "Iterator", "{", "return", "&", "retry", ".", "ExponentialBackoff", "{", "Limited", ":", "retry", ".", "Limited", "{", "Delay", ":", "50", "*", "time", ".", "Millisecond", ",", "Retries", ":", "50", ",", "...
// retryParams defines retry strategy for handling transient errors when minting // or refreshing tokens.
[ "retryParams", "defines", "retry", "strategy", "for", "handling", "transient", "errors", "when", "minting", "or", "refreshing", "tokens", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L1285-L1294
9,292
luci/luci-go
auth/auth.go
makeIAMTokenProvider
func makeIAMTokenProvider(ctx context.Context, opts *Options) (internal.TokenProvider, error) { if opts.testingIAMTokenProvider != nil { return opts.testingIAMTokenProvider, nil } return internal.NewIAMTokenProvider( ctx, opts.ActAsServiceAccount, opts.Scopes, opts.Transport) }
go
func makeIAMTokenProvider(ctx context.Context, opts *Options) (internal.TokenProvider, error) { if opts.testingIAMTokenProvider != nil { return opts.testingIAMTokenProvider, nil } return internal.NewIAMTokenProvider( ctx, opts.ActAsServiceAccount, opts.Scopes, opts.Transport) }
[ "func", "makeIAMTokenProvider", "(", "ctx", "context", ".", "Context", ",", "opts", "*", "Options", ")", "(", "internal", ".", "TokenProvider", ",", "error", ")", "{", "if", "opts", ".", "testingIAMTokenProvider", "!=", "nil", "{", "return", "opts", ".", "...
// makeIAMTokenProvider create TokenProvider to use in Actor mode. // // Called by ensureInitialized in actor mode.
[ "makeIAMTokenProvider", "create", "TokenProvider", "to", "use", "in", "Actor", "mode", ".", "Called", "by", "ensureInitialized", "in", "actor", "mode", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/auth.go#L1363-L1372
9,293
luci/luci-go
logdog/common/storage/bigtable/initialize.go
Initialize
func (s *Storage) Initialize(c context.Context) error { if s.AdminClient == nil { return errors.New("no admin client configured") } exists, err := tableExists(c, s.AdminClient, s.LogTable) if err != nil { return fmt.Errorf("failed to test for table: %s", err) } if !exists { log.Fields{ "table": s.LogTable, }.Infof(c, "Storage table does not exist. Creating...") if err := s.AdminClient.CreateTable(c, s.LogTable); err != nil { return fmt.Errorf("failed to create table: %s", err) } // Wait for the table to exist. BigTable API says this can be delayed from // creation. if err := waitForTable(c, s.AdminClient, s.LogTable); err != nil { return fmt.Errorf("failed to wait for table to exist: %s", err) } log.Fields{ "table": s.LogTable, }.Infof(c, "Successfully created storage table.") } // Get table info. ti, err := s.AdminClient.TableInfo(c, s.LogTable) if err != nil { return fmt.Errorf("failed to get table info: %s", err) } // The table must have the "log" column family. families := stringset.NewFromSlice(ti.Families...) if !families.Has(logColumnFamily) { log.Fields{ "table": s.LogTable, "family": logColumnFamily, }.Infof(c, "Column family 'log' does not exist. Creating...") // Create the logColumnFamily column family. if err := s.AdminClient.CreateColumnFamily(c, s.LogTable, logColumnFamily); err != nil { return fmt.Errorf("Failed to create 'log' column family: %s", err) } log.Fields{ "table": s.LogTable, "family": "log", }.Infof(c, "Successfully created 'log' column family.") } cfg := storage.Config{ MaxLogAge: DefaultMaxLogAge, } if err := s.Config(c, cfg); err != nil { log.WithError(err).Errorf(c, "Failed to push default configuration.") return err } return nil }
go
func (s *Storage) Initialize(c context.Context) error { if s.AdminClient == nil { return errors.New("no admin client configured") } exists, err := tableExists(c, s.AdminClient, s.LogTable) if err != nil { return fmt.Errorf("failed to test for table: %s", err) } if !exists { log.Fields{ "table": s.LogTable, }.Infof(c, "Storage table does not exist. Creating...") if err := s.AdminClient.CreateTable(c, s.LogTable); err != nil { return fmt.Errorf("failed to create table: %s", err) } // Wait for the table to exist. BigTable API says this can be delayed from // creation. if err := waitForTable(c, s.AdminClient, s.LogTable); err != nil { return fmt.Errorf("failed to wait for table to exist: %s", err) } log.Fields{ "table": s.LogTable, }.Infof(c, "Successfully created storage table.") } // Get table info. ti, err := s.AdminClient.TableInfo(c, s.LogTable) if err != nil { return fmt.Errorf("failed to get table info: %s", err) } // The table must have the "log" column family. families := stringset.NewFromSlice(ti.Families...) if !families.Has(logColumnFamily) { log.Fields{ "table": s.LogTable, "family": logColumnFamily, }.Infof(c, "Column family 'log' does not exist. Creating...") // Create the logColumnFamily column family. if err := s.AdminClient.CreateColumnFamily(c, s.LogTable, logColumnFamily); err != nil { return fmt.Errorf("Failed to create 'log' column family: %s", err) } log.Fields{ "table": s.LogTable, "family": "log", }.Infof(c, "Successfully created 'log' column family.") } cfg := storage.Config{ MaxLogAge: DefaultMaxLogAge, } if err := s.Config(c, cfg); err != nil { log.WithError(err).Errorf(c, "Failed to push default configuration.") return err } return nil }
[ "func", "(", "s", "*", "Storage", ")", "Initialize", "(", "c", "context", ".", "Context", ")", "error", "{", "if", "s", ".", "AdminClient", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "exists", ",", ...
// Initialize sets up a Storage schema in BigTable. If the schema is already // set up properly, no action will be taken. // // If, however, the table or table's schema doesn't exist, Initialize will // create and configure it. // // If nil is returned, the table is ready for use as a Storage via New.
[ "Initialize", "sets", "up", "a", "Storage", "schema", "in", "BigTable", ".", "If", "the", "schema", "is", "already", "set", "up", "properly", "no", "action", "will", "be", "taken", ".", "If", "however", "the", "table", "or", "table", "s", "schema", "does...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/bigtable/initialize.go#L79-L142
9,294
luci/luci-go
config/appengine/backend/datastore/ds.go
Backend
func (dc *Config) Backend(base backend.B) backend.B { return &caching.Backend{ B: base, FailOnError: !dc.FailOpen, CacheGet: dc.cacheGet, } }
go
func (dc *Config) Backend(base backend.B) backend.B { return &caching.Backend{ B: base, FailOnError: !dc.FailOpen, CacheGet: dc.cacheGet, } }
[ "func", "(", "dc", "*", "Config", ")", "Backend", "(", "base", "backend", ".", "B", ")", "backend", ".", "B", "{", "return", "&", "caching", ".", "Backend", "{", "B", ":", "base", ",", "FailOnError", ":", "!", "dc", ".", "FailOpen", ",", "CacheGet"...
// Backend wraps the specified Backend in a datastore-backed cache.
[ "Backend", "wraps", "the", "specified", "Backend", "in", "a", "datastore", "-", "backed", "cache", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/appengine/backend/datastore/ds.go#L87-L93
9,295
luci/luci-go
config/appengine/backend/datastore/ds.go
WithHandler
func (dc *Config) WithHandler(c context.Context, l caching.Loader, timeout time.Duration) context.Context { handler := dsCacheHandler{ refreshInterval: dc.RefreshInterval, failOpen: dc.FailOpen, lockerFunc: dc.LockerFunc, loader: l, loaderTimeout: timeout, } return context.WithValue(c, &dsHandlerKey, &handler) }
go
func (dc *Config) WithHandler(c context.Context, l caching.Loader, timeout time.Duration) context.Context { handler := dsCacheHandler{ refreshInterval: dc.RefreshInterval, failOpen: dc.FailOpen, lockerFunc: dc.LockerFunc, loader: l, loaderTimeout: timeout, } return context.WithValue(c, &dsHandlerKey, &handler) }
[ "func", "(", "dc", "*", "Config", ")", "WithHandler", "(", "c", "context", ".", "Context", ",", "l", "caching", ".", "Loader", ",", "timeout", "time", ".", "Duration", ")", "context", ".", "Context", "{", "handler", ":=", "dsCacheHandler", "{", "refreshI...
// WithHandler installs a datastorecache.Handler into our Context. This is // used during datastore cache's Refresh calls. // // The Handler binds the parameters and Loader to the resolution call. For // service resolution, this will be the Loader that is provided by the caching // layer. For cron refresh, this will be the generic Loader provided by // CronLoader.
[ "WithHandler", "installs", "a", "datastorecache", ".", "Handler", "into", "our", "Context", ".", "This", "is", "used", "during", "datastore", "cache", "s", "Refresh", "calls", ".", "The", "Handler", "binds", "the", "parameters", "and", "Loader", "to", "the", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/appengine/backend/datastore/ds.go#L102-L111
9,296
luci/luci-go
config/appengine/backend/datastore/ds.go
CronLoader
func CronLoader(b backend.B) caching.Loader { return func(c context.Context, k caching.Key, v *caching.Value) (*caching.Value, error) { return caching.CacheLoad(c, b, k, v) } }
go
func CronLoader(b backend.B) caching.Loader { return func(c context.Context, k caching.Key, v *caching.Value) (*caching.Value, error) { return caching.CacheLoad(c, b, k, v) } }
[ "func", "CronLoader", "(", "b", "backend", ".", "B", ")", "caching", ".", "Loader", "{", "return", "func", "(", "c", "context", ".", "Context", ",", "k", "caching", ".", "Key", ",", "v", "*", "caching", ".", "Value", ")", "(", "*", "caching", ".", ...
// CronLoader returns a caching.Loader implementation to be used // by the Cron task.
[ "CronLoader", "returns", "a", "caching", ".", "Loader", "implementation", "to", "be", "used", "by", "the", "Cron", "task", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/appengine/backend/datastore/ds.go#L307-L311
9,297
luci/luci-go
logdog/client/cli/subcommandCat.go
getDatagramWriter
func getDatagramWriter(c context.Context, desc *logpb.LogStreamDescriptor) renderer.DatagramWriter { return func(w io.Writer, dg []byte) bool { var pb proto.Message switch desc.ContentType { case milo.ContentTypeAnnotations: mp := milo.Step{} if err := proto.Unmarshal(dg, &mp); err != nil { log.WithError(err).Errorf(c, "Failed to unmarshal datagram data.") return false } pb = &mp default: return false } if err := proto.MarshalText(w, pb); err != nil { log.WithError(err).Errorf(c, "Failed to marshal datagram as text.") return false } return true } }
go
func getDatagramWriter(c context.Context, desc *logpb.LogStreamDescriptor) renderer.DatagramWriter { return func(w io.Writer, dg []byte) bool { var pb proto.Message switch desc.ContentType { case milo.ContentTypeAnnotations: mp := milo.Step{} if err := proto.Unmarshal(dg, &mp); err != nil { log.WithError(err).Errorf(c, "Failed to unmarshal datagram data.") return false } pb = &mp default: return false } if err := proto.MarshalText(w, pb); err != nil { log.WithError(err).Errorf(c, "Failed to marshal datagram as text.") return false } return true } }
[ "func", "getDatagramWriter", "(", "c", "context", ".", "Context", ",", "desc", "*", "logpb", ".", "LogStreamDescriptor", ")", "renderer", ".", "DatagramWriter", "{", "return", "func", "(", "w", "io", ".", "Writer", ",", "dg", "[", "]", "byte", ")", "bool...
// getDatagramWriter returns a datagram writer function that can be used as a // Renderer's DatagramWriter. The writer is bound to desc.
[ "getDatagramWriter", "returns", "a", "datagram", "writer", "function", "that", "can", "be", "used", "as", "a", "Renderer", "s", "DatagramWriter", ".", "The", "writer", "is", "bound", "to", "desc", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cli/subcommandCat.go#L242-L266
9,298
luci/luci-go
cipd/appengine/impl/model/tag.go
Proto
func (t *Tag) Proto() *api.Tag { kv := strings.SplitN(t.Tag, ":", 2) if len(kv) != 2 { panic(fmt.Sprintf("bad tag %q", t.Tag)) } return &api.Tag{ Key: kv[0], Value: kv[1], AttachedBy: t.RegisteredBy, AttachedTs: google.NewTimestamp(t.RegisteredTs), } }
go
func (t *Tag) Proto() *api.Tag { kv := strings.SplitN(t.Tag, ":", 2) if len(kv) != 2 { panic(fmt.Sprintf("bad tag %q", t.Tag)) } return &api.Tag{ Key: kv[0], Value: kv[1], AttachedBy: t.RegisteredBy, AttachedTs: google.NewTimestamp(t.RegisteredTs), } }
[ "func", "(", "t", "*", "Tag", ")", "Proto", "(", ")", "*", "api", ".", "Tag", "{", "kv", ":=", "strings", ".", "SplitN", "(", "t", ".", "Tag", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "kv", ")", "!=", "2", "{", "panic", "("...
// Proto returns cipd.Tag proto with information from this entity. // // Assumes the tag is valid.
[ "Proto", "returns", "cipd", ".", "Tag", "proto", "with", "information", "from", "this", "entity", ".", "Assumes", "the", "tag", "is", "valid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/tag.go#L72-L83
9,299
luci/luci-go
common/data/text/indented/writer.go
Write
func (w *Writer) Write(data []byte) (n int, err error) { // Do not print indentation if there is no data. indentBuf := indentationTabs if w.UseSpaces { indentBuf = indentationSpaces } for len(data) > 0 { var printUntil int endsWithNewLine := false lineBeginning := !w.insideLine if data[0] == '\n' && lineBeginning { // This is a blank line. Do not indent it, just print as is. printUntil = 1 } else { if lineBeginning { // Print indentation. w.Writer.Write(indentBuf[:w.Level]) w.insideLine = true } lineEnd := bytes.IndexRune(data, '\n') if lineEnd < 0 { // Print the whole thing. printUntil = len(data) } else { // Print until the newline inclusive. printUntil = lineEnd + 1 endsWithNewLine = true } } toPrint := data[:printUntil] data = data[printUntil:] // Assertion: none of the runes in toPrint // can be newline except the last rune. // The last rune is newline iff endsWithNewLine==true. m, err := w.Writer.Write(toPrint) n += m if m == len(toPrint) && endsWithNewLine { // We've printed the newline, so we are the line beginning again. w.insideLine = false } if err != nil { return n, err } } return n, nil }
go
func (w *Writer) Write(data []byte) (n int, err error) { // Do not print indentation if there is no data. indentBuf := indentationTabs if w.UseSpaces { indentBuf = indentationSpaces } for len(data) > 0 { var printUntil int endsWithNewLine := false lineBeginning := !w.insideLine if data[0] == '\n' && lineBeginning { // This is a blank line. Do not indent it, just print as is. printUntil = 1 } else { if lineBeginning { // Print indentation. w.Writer.Write(indentBuf[:w.Level]) w.insideLine = true } lineEnd := bytes.IndexRune(data, '\n') if lineEnd < 0 { // Print the whole thing. printUntil = len(data) } else { // Print until the newline inclusive. printUntil = lineEnd + 1 endsWithNewLine = true } } toPrint := data[:printUntil] data = data[printUntil:] // Assertion: none of the runes in toPrint // can be newline except the last rune. // The last rune is newline iff endsWithNewLine==true. m, err := w.Writer.Write(toPrint) n += m if m == len(toPrint) && endsWithNewLine { // We've printed the newline, so we are the line beginning again. w.insideLine = false } if err != nil { return n, err } } return n, nil }
[ "func", "(", "w", "*", "Writer", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "// Do not print indentation if there is no data.", "indentBuf", ":=", "indentationTabs", "\n", "if", "w", ".", "UseSpaces", ...
// Write writes data inserting a newline before each line. // Panics if w.Indent is outside of [0, Limit) range.
[ "Write", "writes", "data", "inserting", "a", "newline", "before", "each", "line", ".", "Panics", "if", "w", ".", "Indent", "is", "outside", "of", "[", "0", "Limit", ")", "range", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/indented/writer.go#L38-L89