id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
7,400
luci/luci-go
appengine/datastorecache/cache.go
InstallCronRoute
func (cache *Cache) InstallCronRoute(path string, r *router.Router, base router.MiddlewareChain) { m := cache.manager() m.installCronRoute(path, r, base) }
go
func (cache *Cache) InstallCronRoute(path string, r *router.Router, base router.MiddlewareChain) { m := cache.manager() m.installCronRoute(path, r, base) }
[ "func", "(", "cache", "*", "Cache", ")", "InstallCronRoute", "(", "path", "string", ",", "r", "*", "router", ".", "Router", ",", "base", "router", ".", "MiddlewareChain", ")", "{", "m", ":=", "cache", ".", "manager", "(", ")", "\n", "m", ".", "installCronRoute", "(", "path", ",", "r", ",", "base", ")", "\n", "}" ]
// InstallCronRoute installs a handler for this Cache's management cron task // into the supplied Router at the specified path. // // It is recommended to assert in the middleware that this endpoint is only // accessible from a cron task.
[ "InstallCronRoute", "installs", "a", "handler", "for", "this", "Cache", "s", "management", "cron", "task", "into", "the", "supplied", "Router", "at", "the", "specified", "path", ".", "It", "is", "recommended", "to", "assert", "in", "the", "middleware", "that", "this", "endpoint", "is", "only", "accessible", "from", "a", "cron", "task", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/datastorecache/cache.go#L190-L193
7,401
luci/luci-go
appengine/datastorecache/cache.go
Get
func (cache *Cache) Get(c context.Context, key []byte) (Value, error) { // Leave any current transaction. c = datastore.WithoutTransaction(c) var h Handler if hf := cache.HandlerFunc; hf != nil { h = hf(c) } if h == nil { return Value{}, errors.New("unable to generate Handler") } // Determine which Locker to use. locker := h.Locker(c) if locker == nil { locker = nopLocker{} } bci := boundCacheInst{ Cache: cache, h: h, locker: locker, } return bci.get(c, key) }
go
func (cache *Cache) Get(c context.Context, key []byte) (Value, error) { // Leave any current transaction. c = datastore.WithoutTransaction(c) var h Handler if hf := cache.HandlerFunc; hf != nil { h = hf(c) } if h == nil { return Value{}, errors.New("unable to generate Handler") } // Determine which Locker to use. locker := h.Locker(c) if locker == nil { locker = nopLocker{} } bci := boundCacheInst{ Cache: cache, h: h, locker: locker, } return bci.get(c, key) }
[ "func", "(", "cache", "*", "Cache", ")", "Get", "(", "c", "context", ".", "Context", ",", "key", "[", "]", "byte", ")", "(", "Value", ",", "error", ")", "{", "// Leave any current transaction.", "c", "=", "datastore", ".", "WithoutTransaction", "(", "c", ")", "\n\n", "var", "h", "Handler", "\n", "if", "hf", ":=", "cache", ".", "HandlerFunc", ";", "hf", "!=", "nil", "{", "h", "=", "hf", "(", "c", ")", "\n", "}", "\n", "if", "h", "==", "nil", "{", "return", "Value", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Determine which Locker to use.", "locker", ":=", "h", ".", "Locker", "(", "c", ")", "\n", "if", "locker", "==", "nil", "{", "locker", "=", "nopLocker", "{", "}", "\n", "}", "\n\n", "bci", ":=", "boundCacheInst", "{", "Cache", ":", "cache", ",", "h", ":", "h", ",", "locker", ":", "locker", ",", "}", "\n", "return", "bci", ".", "get", "(", "c", ",", "key", ")", "\n", "}" ]
// Get retrieves a cached Value from the cache. // // If the value is not defined, the Handler's Refresh function will be used to // obtain the value and, upon success, the Value will be added to the cache // and returned. // // If the Refresh function returns an error, that error will be propagated // as-is and returned.
[ "Get", "retrieves", "a", "cached", "Value", "from", "the", "cache", ".", "If", "the", "value", "is", "not", "defined", "the", "Handler", "s", "Refresh", "function", "will", "be", "used", "to", "obtain", "the", "value", "and", "upon", "success", "the", "Value", "will", "be", "added", "to", "the", "cache", "and", "returned", ".", "If", "the", "Refresh", "function", "returns", "an", "error", "that", "error", "will", "be", "propagated", "as", "-", "is", "and", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/datastorecache/cache.go#L203-L227
7,402
luci/luci-go
appengine/datastorecache/cache.go
shouldAttemptUpdate
func shouldAttemptUpdate(ai time.Duration, now, lastAccessed time.Time, rf randFunc) bool { return xFetch(now, lastAccessed.Add(ai), (ai / accessUpdateDeltaFactor), 1, rf) }
go
func shouldAttemptUpdate(ai time.Duration, now, lastAccessed time.Time, rf randFunc) bool { return xFetch(now, lastAccessed.Add(ai), (ai / accessUpdateDeltaFactor), 1, rf) }
[ "func", "shouldAttemptUpdate", "(", "ai", "time", ".", "Duration", ",", "now", ",", "lastAccessed", "time", ".", "Time", ",", "rf", "randFunc", ")", "bool", "{", "return", "xFetch", "(", "now", ",", "lastAccessed", ".", "Add", "(", "ai", ")", ",", "(", "ai", "/", "accessUpdateDeltaFactor", ")", ",", "1", ",", "rf", ")", "\n", "}" ]
// shouldAttemptUpdate returns true if a cache entry update should be attempted // given the supplied parameters. // // We probabilistically update the "last accessed" field based on how close we // are to the configured AccessUpdateInterval using the xFetch function.
[ "shouldAttemptUpdate", "returns", "true", "if", "a", "cache", "entry", "update", "should", "be", "attempted", "given", "the", "supplied", "parameters", ".", "We", "probabilistically", "update", "the", "last", "accessed", "field", "based", "on", "how", "close", "we", "are", "to", "the", "configured", "AccessUpdateInterval", "using", "the", "xFetch", "function", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/datastorecache/cache.go#L454-L456
7,403
luci/luci-go
appengine/datastorecache/cache.go
xFetch
func xFetch(now, expiry time.Time, delta time.Duration, beta float64, rf randFunc) bool { offset := time.Duration(float64(delta) * beta * math.Log(rf())) return !now.Add(-offset).Before(expiry) }
go
func xFetch(now, expiry time.Time, delta time.Duration, beta float64, rf randFunc) bool { offset := time.Duration(float64(delta) * beta * math.Log(rf())) return !now.Add(-offset).Before(expiry) }
[ "func", "xFetch", "(", "now", ",", "expiry", "time", ".", "Time", ",", "delta", "time", ".", "Duration", ",", "beta", "float64", ",", "rf", "randFunc", ")", "bool", "{", "offset", ":=", "time", ".", "Duration", "(", "float64", "(", "delta", ")", "*", "beta", "*", "math", ".", "Log", "(", "rf", "(", ")", ")", ")", "\n", "return", "!", "now", ".", "Add", "(", "-", "offset", ")", ".", "Before", "(", "expiry", ")", "\n", "}" ]
// xFetch returns true if recomputation should be performed. // // The decision is probabilistic, based on the evaluation of a probability // distribution that scales according to the time since the value was last // recomputed. // // delta is a factor representing the amount of time that it takes to // recalculate the value. Higher delta values allow for earlier recomputation // for values that take longer to calculate. // // beta can be set to >1 to favor earlier recomputations; however, in practice // beta=1 works well.
[ "xFetch", "returns", "true", "if", "recomputation", "should", "be", "performed", ".", "The", "decision", "is", "probabilistic", "based", "on", "the", "evaluation", "of", "a", "probability", "distribution", "that", "scales", "according", "to", "the", "time", "since", "the", "value", "was", "last", "recomputed", ".", "delta", "is", "a", "factor", "representing", "the", "amount", "of", "time", "that", "it", "takes", "to", "recalculate", "the", "value", ".", "Higher", "delta", "values", "allow", "for", "earlier", "recomputation", "for", "values", "that", "take", "longer", "to", "calculate", ".", "beta", "can", "be", "set", "to", ">", "1", "to", "favor", "earlier", "recomputations", ";", "however", "in", "practice", "beta", "=", "1", "works", "well", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/datastorecache/cache.go#L470-L473
7,404
luci/luci-go
scheduler/appengine/engine/pubsub.go
createPubSubService
func createPubSubService(c context.Context, pubSubURL string) (*pubsub.Service, error) { // In real mode (not a unit test), use authenticated transport. var transport http.RoundTripper if pubSubURL == "" { var err error transport, err = auth.GetRPCTransport(c, auth.AsSelf, auth.WithScopes(pubsub.PubsubScope)) if err != nil { return nil, err } } else { transport = http.DefaultTransport } service, err := pubsub.New(&http.Client{Transport: transport}) if err != nil { return nil, err } if pubSubURL != "" { service.BasePath = pubSubURL } return service, nil }
go
func createPubSubService(c context.Context, pubSubURL string) (*pubsub.Service, error) { // In real mode (not a unit test), use authenticated transport. var transport http.RoundTripper if pubSubURL == "" { var err error transport, err = auth.GetRPCTransport(c, auth.AsSelf, auth.WithScopes(pubsub.PubsubScope)) if err != nil { return nil, err } } else { transport = http.DefaultTransport } service, err := pubsub.New(&http.Client{Transport: transport}) if err != nil { return nil, err } if pubSubURL != "" { service.BasePath = pubSubURL } return service, nil }
[ "func", "createPubSubService", "(", "c", "context", ".", "Context", ",", "pubSubURL", "string", ")", "(", "*", "pubsub", ".", "Service", ",", "error", ")", "{", "// In real mode (not a unit test), use authenticated transport.", "var", "transport", "http", ".", "RoundTripper", "\n", "if", "pubSubURL", "==", "\"", "\"", "{", "var", "err", "error", "\n", "transport", ",", "err", "=", "auth", ".", "GetRPCTransport", "(", "c", ",", "auth", ".", "AsSelf", ",", "auth", ".", "WithScopes", "(", "pubsub", ".", "PubsubScope", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "transport", "=", "http", ".", "DefaultTransport", "\n", "}", "\n", "service", ",", "err", ":=", "pubsub", ".", "New", "(", "&", "http", ".", "Client", "{", "Transport", ":", "transport", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "pubSubURL", "!=", "\"", "\"", "{", "service", ".", "BasePath", "=", "pubSubURL", "\n", "}", "\n", "return", "service", ",", "nil", "\n", "}" ]
// createPubSubService returns configured instance of pubsub.Service.
[ "createPubSubService", "returns", "configured", "instance", "of", "pubsub", ".", "Service", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/pubsub.go#L34-L54
7,405
luci/luci-go
scheduler/appengine/engine/pubsub.go
pullSubcription
func pullSubcription(c context.Context, subscription, pubSubURL string) (*pubsub.PubsubMessage, func(), error) { service, err := createPubSubService(c, pubSubURL) if err != nil { return nil, nil, err } resp, err := service.Projects.Subscriptions.Pull(subscription, &pubsub.PullRequest{ ReturnImmediately: true, MaxMessages: 1, }).Context(c).Do() if err != nil { return nil, nil, err } switch len(resp.ReceivedMessages) { case 0: return nil, nil, nil case 1: ackID := resp.ReceivedMessages[0].AckId ackCb := func() { _, err := service.Projects.Subscriptions.Acknowledge(subscription, &pubsub.AcknowledgeRequest{ AckIds: []string{ackID}, }).Context(c).Do() if err != nil { logging.Errorf(c, "Failed to acknowledge the message - %s", err) } } return resp.ReceivedMessages[0].Message, ackCb, nil default: panic(errors.New("received more than one message from PubSub while asking only one")) } }
go
func pullSubcription(c context.Context, subscription, pubSubURL string) (*pubsub.PubsubMessage, func(), error) { service, err := createPubSubService(c, pubSubURL) if err != nil { return nil, nil, err } resp, err := service.Projects.Subscriptions.Pull(subscription, &pubsub.PullRequest{ ReturnImmediately: true, MaxMessages: 1, }).Context(c).Do() if err != nil { return nil, nil, err } switch len(resp.ReceivedMessages) { case 0: return nil, nil, nil case 1: ackID := resp.ReceivedMessages[0].AckId ackCb := func() { _, err := service.Projects.Subscriptions.Acknowledge(subscription, &pubsub.AcknowledgeRequest{ AckIds: []string{ackID}, }).Context(c).Do() if err != nil { logging.Errorf(c, "Failed to acknowledge the message - %s", err) } } return resp.ReceivedMessages[0].Message, ackCb, nil default: panic(errors.New("received more than one message from PubSub while asking only one")) } }
[ "func", "pullSubcription", "(", "c", "context", ".", "Context", ",", "subscription", ",", "pubSubURL", "string", ")", "(", "*", "pubsub", ".", "PubsubMessage", ",", "func", "(", ")", ",", "error", ")", "{", "service", ",", "err", ":=", "createPubSubService", "(", "c", ",", "pubSubURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "resp", ",", "err", ":=", "service", ".", "Projects", ".", "Subscriptions", ".", "Pull", "(", "subscription", ",", "&", "pubsub", ".", "PullRequest", "{", "ReturnImmediately", ":", "true", ",", "MaxMessages", ":", "1", ",", "}", ")", ".", "Context", "(", "c", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "switch", "len", "(", "resp", ".", "ReceivedMessages", ")", "{", "case", "0", ":", "return", "nil", ",", "nil", ",", "nil", "\n", "case", "1", ":", "ackID", ":=", "resp", ".", "ReceivedMessages", "[", "0", "]", ".", "AckId", "\n", "ackCb", ":=", "func", "(", ")", "{", "_", ",", "err", ":=", "service", ".", "Projects", ".", "Subscriptions", ".", "Acknowledge", "(", "subscription", ",", "&", "pubsub", ".", "AcknowledgeRequest", "{", "AckIds", ":", "[", "]", "string", "{", "ackID", "}", ",", "}", ")", ".", "Context", "(", "c", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "resp", ".", "ReceivedMessages", "[", "0", "]", ".", "Message", ",", "ackCb", ",", "nil", "\n", "default", ":", "panic", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "}" ]
// pullSubcription pulls one message from PubSub subscription. // // Used on dev server only. Returns the message and callback to call to // acknowledge the message.
[ "pullSubcription", "pulls", "one", "message", "from", "PubSub", "subscription", ".", "Used", "on", "dev", "server", "only", ".", "Returns", "the", "message", "and", "callback", "to", "call", "to", "acknowledge", "the", "message", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/pubsub.go#L119-L150
7,406
luci/luci-go
machine-db/appengine/rpc/crimson.go
authPrelude
func authPrelude(c context.Context, methodName string, req proto.Message) (context.Context, error) { groups := []string{"machine-db-administrators", "machine-db-writers"} if strings.HasPrefix(methodName, "Find") || strings.HasPrefix(methodName, "List") { groups = append(groups, "machine-db-readers") } switch is, err := auth.IsMember(c, groups...); { case err != nil: return c, err case !is: return c, status.Errorf(codes.PermissionDenied, "unauthorized user") } logging.Debugf(c, "%s called %q:\n%s", auth.CurrentIdentity(c), methodName, req) return c, nil }
go
func authPrelude(c context.Context, methodName string, req proto.Message) (context.Context, error) { groups := []string{"machine-db-administrators", "machine-db-writers"} if strings.HasPrefix(methodName, "Find") || strings.HasPrefix(methodName, "List") { groups = append(groups, "machine-db-readers") } switch is, err := auth.IsMember(c, groups...); { case err != nil: return c, err case !is: return c, status.Errorf(codes.PermissionDenied, "unauthorized user") } logging.Debugf(c, "%s called %q:\n%s", auth.CurrentIdentity(c), methodName, req) return c, nil }
[ "func", "authPrelude", "(", "c", "context", ".", "Context", ",", "methodName", "string", ",", "req", "proto", ".", "Message", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "groups", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "methodName", ",", "\"", "\"", ")", "||", "strings", ".", "HasPrefix", "(", "methodName", ",", "\"", "\"", ")", "{", "groups", "=", "append", "(", "groups", ",", "\"", "\"", ")", "\n", "}", "\n", "switch", "is", ",", "err", ":=", "auth", ".", "IsMember", "(", "c", ",", "groups", "...", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "c", ",", "err", "\n", "case", "!", "is", ":", "return", "c", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\\n", "\"", ",", "auth", ".", "CurrentIdentity", "(", "c", ")", ",", "methodName", ",", "req", ")", "\n", "return", "c", ",", "nil", "\n", "}" ]
// authPrelude ensures the user is authorized to use the Crimson API.
[ "authPrelude", "ensures", "the", "user", "is", "authorized", "to", "use", "the", "Crimson", "API", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/crimson.go#L35-L48
7,407
luci/luci-go
machine-db/appengine/rpc/crimson.go
gRPCifyAndLogErr
func gRPCifyAndLogErr(c context.Context, methodName string, rsp proto.Message, err error) error { return grpcutil.GRPCifyAndLogErr(c, err) }
go
func gRPCifyAndLogErr(c context.Context, methodName string, rsp proto.Message, err error) error { return grpcutil.GRPCifyAndLogErr(c, err) }
[ "func", "gRPCifyAndLogErr", "(", "c", "context", ".", "Context", ",", "methodName", "string", ",", "rsp", "proto", ".", "Message", ",", "err", "error", ")", "error", "{", "return", "grpcutil", ".", "GRPCifyAndLogErr", "(", "c", ",", "err", ")", "\n", "}" ]
// gRPCifyAndLogErr ensures any error being returned is a gRPC error, logging Internal and Unknown errors.
[ "gRPCifyAndLogErr", "ensures", "any", "error", "being", "returned", "is", "a", "gRPC", "error", "logging", "Internal", "and", "Unknown", "errors", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/crimson.go#L51-L53
7,408
luci/luci-go
machine-db/appengine/rpc/crimson.go
matches
func matches(s string, set stringset.Set) bool { return set.Has(s) || set.Len() == 0 }
go
func matches(s string, set stringset.Set) bool { return set.Has(s) || set.Len() == 0 }
[ "func", "matches", "(", "s", "string", ",", "set", "stringset", ".", "Set", ")", "bool", "{", "return", "set", ".", "Has", "(", "s", ")", "||", "set", ".", "Len", "(", ")", "==", "0", "\n", "}" ]
// matches returns whether the given string matches the given set. // An empty set matches all strings.
[ "matches", "returns", "whether", "the", "given", "string", "matches", "the", "given", "set", ".", "An", "empty", "set", "matches", "all", "strings", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/crimson.go#L57-L59
7,409
luci/luci-go
machine-db/appengine/rpc/crimson.go
NewServer
func NewServer() crimson.CrimsonServer { return &crimson.DecoratedCrimson{ Prelude: authPrelude, Service: &Service{}, Postlude: gRPCifyAndLogErr, } }
go
func NewServer() crimson.CrimsonServer { return &crimson.DecoratedCrimson{ Prelude: authPrelude, Service: &Service{}, Postlude: gRPCifyAndLogErr, } }
[ "func", "NewServer", "(", ")", "crimson", ".", "CrimsonServer", "{", "return", "&", "crimson", ".", "DecoratedCrimson", "{", "Prelude", ":", "authPrelude", ",", "Service", ":", "&", "Service", "{", "}", ",", "Postlude", ":", "gRPCifyAndLogErr", ",", "}", "\n", "}" ]
// NewServer returns a new Crimson RPC server.
[ "NewServer", "returns", "a", "new", "Crimson", "RPC", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/crimson.go#L62-L68
7,410
luci/luci-go
logdog/appengine/coordinator/endpoints/services/taskQueue.go
TaskArchival
func TaskArchival(c context.Context, state *coordinator.LogStreamState, delay time.Duration) error { // Now task the archival. state.Updated = clock.Now(c).UTC() state.ArchivalKey = []byte{'1'} // Use a fake key just to signal that we've tasked the archival. if err := ds.Put(c, state); err != nil { log.Fields{ log.ErrorKey: err, }.Errorf(c, "Failed to Put() LogStream.") return grpcutil.Internal } project := string(coordinator.ProjectFromNamespace(state.Parent.Namespace())) id := string(state.ID()) t, err := tqTask(&logdog.ArchiveTask{Project: project, Id: id}) if err != nil { log.WithError(err).Errorf(c, "could not create archival task") return grpcutil.Internal } t.Delay = delay if err := taskqueue.Add(c, ArchiveQueueName, t); err != nil { log.WithError(err).Errorf(c, "could not task archival") return grpcutil.Internal } return nil }
go
func TaskArchival(c context.Context, state *coordinator.LogStreamState, delay time.Duration) error { // Now task the archival. state.Updated = clock.Now(c).UTC() state.ArchivalKey = []byte{'1'} // Use a fake key just to signal that we've tasked the archival. if err := ds.Put(c, state); err != nil { log.Fields{ log.ErrorKey: err, }.Errorf(c, "Failed to Put() LogStream.") return grpcutil.Internal } project := string(coordinator.ProjectFromNamespace(state.Parent.Namespace())) id := string(state.ID()) t, err := tqTask(&logdog.ArchiveTask{Project: project, Id: id}) if err != nil { log.WithError(err).Errorf(c, "could not create archival task") return grpcutil.Internal } t.Delay = delay if err := taskqueue.Add(c, ArchiveQueueName, t); err != nil { log.WithError(err).Errorf(c, "could not task archival") return grpcutil.Internal } return nil }
[ "func", "TaskArchival", "(", "c", "context", ".", "Context", ",", "state", "*", "coordinator", ".", "LogStreamState", ",", "delay", "time", ".", "Duration", ")", "error", "{", "// Now task the archival.", "state", ".", "Updated", "=", "clock", ".", "Now", "(", "c", ")", ".", "UTC", "(", ")", "\n", "state", ".", "ArchivalKey", "=", "[", "]", "byte", "{", "'1'", "}", "// Use a fake key just to signal that we've tasked the archival.", "\n", "if", "err", ":=", "ds", ".", "Put", "(", "c", ",", "state", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fields", "{", "log", ".", "ErrorKey", ":", "err", ",", "}", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "grpcutil", ".", "Internal", "\n", "}", "\n\n", "project", ":=", "string", "(", "coordinator", ".", "ProjectFromNamespace", "(", "state", ".", "Parent", ".", "Namespace", "(", ")", ")", ")", "\n", "id", ":=", "string", "(", "state", ".", "ID", "(", ")", ")", "\n", "t", ",", "err", ":=", "tqTask", "(", "&", "logdog", ".", "ArchiveTask", "{", "Project", ":", "project", ",", "Id", ":", "id", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "grpcutil", ".", "Internal", "\n", "}", "\n", "t", ".", "Delay", "=", "delay", "\n", "if", "err", ":=", "taskqueue", ".", "Add", "(", "c", ",", "ArchiveQueueName", ",", "t", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "grpcutil", ".", "Internal", "\n", "}", "\n", "return", "nil", "\n\n", "}" ]
// TaskArchival tasks an archival of a stream with the given delay.
[ "TaskArchival", "tasks", "an", "archival", "of", "a", "stream", "with", "the", "given", "delay", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/taskQueue.go#L53-L78
7,411
luci/luci-go
logdog/appengine/coordinator/endpoints/services/taskQueue.go
tqTask
func tqTask(task *logdog.ArchiveTask) (*taskqueue.Task, error) { payload, err := proto.Marshal(task) return &taskqueue.Task{ Name: task.TaskName, Payload: payload, Method: "PULL", }, err }
go
func tqTask(task *logdog.ArchiveTask) (*taskqueue.Task, error) { payload, err := proto.Marshal(task) return &taskqueue.Task{ Name: task.TaskName, Payload: payload, Method: "PULL", }, err }
[ "func", "tqTask", "(", "task", "*", "logdog", ".", "ArchiveTask", ")", "(", "*", "taskqueue", ".", "Task", ",", "error", ")", "{", "payload", ",", "err", ":=", "proto", ".", "Marshal", "(", "task", ")", "\n", "return", "&", "taskqueue", ".", "Task", "{", "Name", ":", "task", ".", "TaskName", ",", "Payload", ":", "payload", ",", "Method", ":", "\"", "\"", ",", "}", ",", "err", "\n", "}" ]
// tqTask returns a taskqueue task for an archive task.
[ "tqTask", "returns", "a", "taskqueue", "task", "for", "an", "archive", "task", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/taskQueue.go#L81-L88
7,412
luci/luci-go
logdog/appengine/coordinator/endpoints/services/taskQueue.go
tqTaskLite
func tqTaskLite(task *logdog.ArchiveTask) *taskqueue.Task { return &taskqueue.Task{ Name: task.TaskName, Method: "PULL", } }
go
func tqTaskLite(task *logdog.ArchiveTask) *taskqueue.Task { return &taskqueue.Task{ Name: task.TaskName, Method: "PULL", } }
[ "func", "tqTaskLite", "(", "task", "*", "logdog", ".", "ArchiveTask", ")", "*", "taskqueue", ".", "Task", "{", "return", "&", "taskqueue", ".", "Task", "{", "Name", ":", "task", ".", "TaskName", ",", "Method", ":", "\"", "\"", ",", "}", "\n", "}" ]
// tqTaskLite returns a taskqueue task for an archive task without the payload.
[ "tqTaskLite", "returns", "a", "taskqueue", "task", "for", "an", "archive", "task", "without", "the", "payload", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/taskQueue.go#L91-L96
7,413
luci/luci-go
logdog/appengine/coordinator/endpoints/services/taskQueue.go
archiveTask
func archiveTask(task *taskqueue.Task) (*logdog.ArchiveTask, error) { result := logdog.ArchiveTask{} err := proto.Unmarshal(task.Payload, &result) result.TaskName = task.Name return &result, err }
go
func archiveTask(task *taskqueue.Task) (*logdog.ArchiveTask, error) { result := logdog.ArchiveTask{} err := proto.Unmarshal(task.Payload, &result) result.TaskName = task.Name return &result, err }
[ "func", "archiveTask", "(", "task", "*", "taskqueue", ".", "Task", ")", "(", "*", "logdog", ".", "ArchiveTask", ",", "error", ")", "{", "result", ":=", "logdog", ".", "ArchiveTask", "{", "}", "\n", "err", ":=", "proto", ".", "Unmarshal", "(", "task", ".", "Payload", ",", "&", "result", ")", "\n", "result", ".", "TaskName", "=", "task", ".", "Name", "\n", "return", "&", "result", ",", "err", "\n", "}" ]
// archiveTask creates a archiveTask proto from a taskqueue task.
[ "archiveTask", "creates", "a", "archiveTask", "proto", "from", "a", "taskqueue", "task", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/taskQueue.go#L99-L104
7,414
luci/luci-go
logdog/appengine/coordinator/endpoints/services/taskQueue.go
isArchived
func isArchived(c context.Context, task *logdog.ArchiveTask) bool { var err error defer func() { if err != nil { logging.WithError(err).Errorf(c, "while checking if %s/%s is archived", task.Project, task.Id) } }() if c, err = info.Namespace(c, "luci."+task.Project); err != nil { return false } state := (&coordinator.LogStream{ID: coordinator.HashID(task.Id)}).State(c) if err = datastore.Get(c, state); err != nil { return false } return state.ArchivalState() == coordinator.ArchivedComplete }
go
func isArchived(c context.Context, task *logdog.ArchiveTask) bool { var err error defer func() { if err != nil { logging.WithError(err).Errorf(c, "while checking if %s/%s is archived", task.Project, task.Id) } }() if c, err = info.Namespace(c, "luci."+task.Project); err != nil { return false } state := (&coordinator.LogStream{ID: coordinator.HashID(task.Id)}).State(c) if err = datastore.Get(c, state); err != nil { return false } return state.ArchivalState() == coordinator.ArchivedComplete }
[ "func", "isArchived", "(", "c", "context", ".", "Context", ",", "task", "*", "logdog", ".", "ArchiveTask", ")", "bool", "{", "var", "err", "error", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "task", ".", "Project", ",", "task", ".", "Id", ")", "\n", "}", "\n", "}", "(", ")", "\n", "if", "c", ",", "err", "=", "info", ".", "Namespace", "(", "c", ",", "\"", "\"", "+", "task", ".", "Project", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "state", ":=", "(", "&", "coordinator", ".", "LogStream", "{", "ID", ":", "coordinator", ".", "HashID", "(", "task", ".", "Id", ")", "}", ")", ".", "State", "(", "c", ")", "\n", "if", "err", "=", "datastore", ".", "Get", "(", "c", ",", "state", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "state", ".", "ArchivalState", "(", ")", "==", "coordinator", ".", "ArchivedComplete", "\n", "}" ]
// checkArchived is a best-effort check to see if a task is archived. // If this fails, an error is logged, and it returns false.
[ "checkArchived", "is", "a", "best", "-", "effort", "check", "to", "see", "if", "a", "task", "is", "archived", ".", "If", "this", "fails", "an", "error", "is", "logged", "and", "it", "returns", "false", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/taskQueue.go#L108-L123
7,415
luci/luci-go
logdog/appengine/coordinator/endpoints/services/taskQueue.go
LeaseArchiveTasks
func (b *server) LeaseArchiveTasks(c context.Context, req *logdog.LeaseRequest) (*logdog.LeaseResponse, error) { duration, err := ptypes.Duration(req.LeaseTime) if err != nil { return nil, err } logging.Infof(c, "got request to lease %d tasks for %s", req.MaxTasks, req.GetLeaseTime()) tasks, err := taskqueue.Lease(c, int(req.MaxTasks), ArchiveQueueName, duration) if err != nil { logging.WithError(err).Errorf(c, "could not lease %d tasks from queue", req.MaxTasks) return nil, err } archiveTasks := make([]*logdog.ArchiveTask, 0, len(tasks)) for _, task := range tasks { at, err := archiveTask(task) if err != nil { // Ignore malformed name errors, just log them. logging.WithError(err).Errorf(c, "while leasing task") continue } // Optimization: Delete the task if it's already archived. if isArchived(c, at) { if err := taskqueue.Delete(c, ArchiveQueueName, task); err != nil { logging.WithError(err).Errorf(c, "failed to delete %s/%s (%s)", at.Project, at.Id, task.Name) } continue } archiveTasks = append(archiveTasks, at) leaseTask.Add(c, 1, task.RetryCount) } logging.Infof(c, "Leasing %d tasks", len(archiveTasks)) return &logdog.LeaseResponse{Tasks: archiveTasks}, nil }
go
func (b *server) LeaseArchiveTasks(c context.Context, req *logdog.LeaseRequest) (*logdog.LeaseResponse, error) { duration, err := ptypes.Duration(req.LeaseTime) if err != nil { return nil, err } logging.Infof(c, "got request to lease %d tasks for %s", req.MaxTasks, req.GetLeaseTime()) tasks, err := taskqueue.Lease(c, int(req.MaxTasks), ArchiveQueueName, duration) if err != nil { logging.WithError(err).Errorf(c, "could not lease %d tasks from queue", req.MaxTasks) return nil, err } archiveTasks := make([]*logdog.ArchiveTask, 0, len(tasks)) for _, task := range tasks { at, err := archiveTask(task) if err != nil { // Ignore malformed name errors, just log them. logging.WithError(err).Errorf(c, "while leasing task") continue } // Optimization: Delete the task if it's already archived. if isArchived(c, at) { if err := taskqueue.Delete(c, ArchiveQueueName, task); err != nil { logging.WithError(err).Errorf(c, "failed to delete %s/%s (%s)", at.Project, at.Id, task.Name) } continue } archiveTasks = append(archiveTasks, at) leaseTask.Add(c, 1, task.RetryCount) } logging.Infof(c, "Leasing %d tasks", len(archiveTasks)) return &logdog.LeaseResponse{Tasks: archiveTasks}, nil }
[ "func", "(", "b", "*", "server", ")", "LeaseArchiveTasks", "(", "c", "context", ".", "Context", ",", "req", "*", "logdog", ".", "LeaseRequest", ")", "(", "*", "logdog", ".", "LeaseResponse", ",", "error", ")", "{", "duration", ",", "err", ":=", "ptypes", ".", "Duration", "(", "req", ".", "LeaseTime", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "req", ".", "MaxTasks", ",", "req", ".", "GetLeaseTime", "(", ")", ")", "\n", "tasks", ",", "err", ":=", "taskqueue", ".", "Lease", "(", "c", ",", "int", "(", "req", ".", "MaxTasks", ")", ",", "ArchiveQueueName", ",", "duration", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "req", ".", "MaxTasks", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "archiveTasks", ":=", "make", "(", "[", "]", "*", "logdog", ".", "ArchiveTask", ",", "0", ",", "len", "(", "tasks", ")", ")", "\n", "for", "_", ",", "task", ":=", "range", "tasks", "{", "at", ",", "err", ":=", "archiveTask", "(", "task", ")", "\n", "if", "err", "!=", "nil", "{", "// Ignore malformed name errors, just log them.", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n", "// Optimization: Delete the task if it's already archived.", "if", "isArchived", "(", "c", ",", "at", ")", "{", "if", "err", ":=", "taskqueue", ".", "Delete", "(", "c", ",", "ArchiveQueueName", ",", "task", ")", ";", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "at", ".", "Project", ",", "at", ".", "Id", ",", "task", ".", "Name", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "archiveTasks", "=", "append", "(", "archiveTasks", ",", "at", ")", "\n", "leaseTask", ".", "Add", "(", "c", ",", "1", ",", "task", ".", "RetryCount", ")", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "len", "(", "archiveTasks", ")", ")", "\n", "return", "&", "logdog", ".", "LeaseResponse", "{", "Tasks", ":", "archiveTasks", "}", ",", "nil", "\n", "}" ]
// LeaseArchiveTasks leases archive tasks to the requestor from a pull queue.
[ "LeaseArchiveTasks", "leases", "archive", "tasks", "to", "the", "requestor", "from", "a", "pull", "queue", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/taskQueue.go#L126-L158
7,416
luci/luci-go
logdog/appengine/coordinator/endpoints/services/taskQueue.go
DeleteArchiveTasks
func (b *server) DeleteArchiveTasks(c context.Context, req *logdog.DeleteRequest) (*empty.Empty, error) { deleteTask.Add(c, int64(len(req.Tasks))) tasks := make([]*taskqueue.Task, 0, len(req.Tasks)) for _, at := range req.Tasks { tasks = append(tasks, tqTaskLite(at)) } logging.Infof(c, "Deleting %d tasks", len(req.Tasks)) err := taskqueue.Delete(c, ArchiveQueueName, tasks...) if err != nil { logging.WithError(err).Errorf(c, "while deleting tasks\n%#v", tasks) } return &empty.Empty{}, nil }
go
func (b *server) DeleteArchiveTasks(c context.Context, req *logdog.DeleteRequest) (*empty.Empty, error) { deleteTask.Add(c, int64(len(req.Tasks))) tasks := make([]*taskqueue.Task, 0, len(req.Tasks)) for _, at := range req.Tasks { tasks = append(tasks, tqTaskLite(at)) } logging.Infof(c, "Deleting %d tasks", len(req.Tasks)) err := taskqueue.Delete(c, ArchiveQueueName, tasks...) if err != nil { logging.WithError(err).Errorf(c, "while deleting tasks\n%#v", tasks) } return &empty.Empty{}, nil }
[ "func", "(", "b", "*", "server", ")", "DeleteArchiveTasks", "(", "c", "context", ".", "Context", ",", "req", "*", "logdog", ".", "DeleteRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "deleteTask", ".", "Add", "(", "c", ",", "int64", "(", "len", "(", "req", ".", "Tasks", ")", ")", ")", "\n", "tasks", ":=", "make", "(", "[", "]", "*", "taskqueue", ".", "Task", ",", "0", ",", "len", "(", "req", ".", "Tasks", ")", ")", "\n", "for", "_", ",", "at", ":=", "range", "req", ".", "Tasks", "{", "tasks", "=", "append", "(", "tasks", ",", "tqTaskLite", "(", "at", ")", ")", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "len", "(", "req", ".", "Tasks", ")", ")", "\n", "err", ":=", "taskqueue", ".", "Delete", "(", "c", ",", "ArchiveQueueName", ",", "tasks", "...", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\\n", "\"", ",", "tasks", ")", "\n", "}", "\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeleteArchiveTasks deletes archive tasks from the task queue. // Errors are logged but ignored.
[ "DeleteArchiveTasks", "deletes", "archive", "tasks", "from", "the", "task", "queue", ".", "Errors", "are", "logged", "but", "ignored", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/taskQueue.go#L162-L174
7,417
luci/luci-go
tokenserver/appengine/impl/certconfig/rpc_import_ca_configs.go
decodeCACert
func decodeCACert(certPem string) (cert *x509.Certificate, certDer []byte, err error) { certDer, err = utils.ParsePEM(certPem, "CERTIFICATE") if err != nil { return nil, nil, fmt.Errorf("bad PEM - %s", err) } switch cert, err = x509.ParseCertificate(certDer); { case err != nil: return nil, nil, fmt.Errorf("bad cert - %s", err) case !cert.IsCA: return nil, nil, fmt.Errorf("not a CA cert") default: return cert, certDer, nil } }
go
func decodeCACert(certPem string) (cert *x509.Certificate, certDer []byte, err error) { certDer, err = utils.ParsePEM(certPem, "CERTIFICATE") if err != nil { return nil, nil, fmt.Errorf("bad PEM - %s", err) } switch cert, err = x509.ParseCertificate(certDer); { case err != nil: return nil, nil, fmt.Errorf("bad cert - %s", err) case !cert.IsCA: return nil, nil, fmt.Errorf("not a CA cert") default: return cert, certDer, nil } }
[ "func", "decodeCACert", "(", "certPem", "string", ")", "(", "cert", "*", "x509", ".", "Certificate", ",", "certDer", "[", "]", "byte", ",", "err", "error", ")", "{", "certDer", ",", "err", "=", "utils", ".", "ParsePEM", "(", "certPem", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "switch", "cert", ",", "err", "=", "x509", ".", "ParseCertificate", "(", "certDer", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "case", "!", "cert", ".", "IsCA", ":", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "default", ":", "return", "cert", ",", "certDer", ",", "nil", "\n", "}", "\n", "}" ]
// decodeCACert parses x509 pem-encoded certificate and checks it is a CA cert. // // Returns the decoded cert, as well as its der-encoded representation.
[ "decodeCACert", "parses", "x509", "pem", "-", "encoded", "certificate", "and", "checks", "it", "is", "a", "CA", "cert", ".", "Returns", "the", "decoded", "cert", "as", "well", "as", "its", "der", "-", "encoded", "representation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/rpc_import_ca_configs.go#L207-L220
7,418
luci/luci-go
tokenserver/appengine/impl/certconfig/rpc_import_ca_configs.go
removeCA
func removeCA(c context.Context, name string, rev string) error { return ds.RunInTransaction(c, func(c context.Context) error { existing := CA{CN: name} if err := ds.Get(c, &existing); err != nil { return err } if existing.Removed { return nil } logging.Infof(c, "Removing CA %q", name) existing.Removed = true existing.RemovedRev = rev return ds.Put(c, &existing) }, nil) }
go
func removeCA(c context.Context, name string, rev string) error { return ds.RunInTransaction(c, func(c context.Context) error { existing := CA{CN: name} if err := ds.Get(c, &existing); err != nil { return err } if existing.Removed { return nil } logging.Infof(c, "Removing CA %q", name) existing.Removed = true existing.RemovedRev = rev return ds.Put(c, &existing) }, nil) }
[ "func", "removeCA", "(", "c", "context", ".", "Context", ",", "name", "string", ",", "rev", "string", ")", "error", "{", "return", "ds", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "existing", ":=", "CA", "{", "CN", ":", "name", "}", "\n", "if", "err", ":=", "ds", ".", "Get", "(", "c", ",", "&", "existing", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "existing", ".", "Removed", "{", "return", "nil", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "name", ")", "\n", "existing", ".", "Removed", "=", "true", "\n", "existing", ".", "RemovedRev", "=", "rev", "\n", "return", "ds", ".", "Put", "(", "c", ",", "&", "existing", ")", "\n", "}", ",", "nil", ")", "\n", "}" ]
// removeCA marks the CA in the datastore as removed.
[ "removeCA", "marks", "the", "CA", "in", "the", "datastore", "as", "removed", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/rpc_import_ca_configs.go#L302-L316
7,419
luci/luci-go
logdog/appengine/coordinator/configservice.go
Config
func (s *LUCIConfigProvider) Config(c context.Context) (*config.Config, error) { s.lock.Lock() defer s.lock.Unlock() // Load/cache the global config. if s.gcfg == nil { var err error s.gcfg, err = config.Load(c) if err != nil { return nil, err } } return s.gcfg, nil }
go
func (s *LUCIConfigProvider) Config(c context.Context) (*config.Config, error) { s.lock.Lock() defer s.lock.Unlock() // Load/cache the global config. if s.gcfg == nil { var err error s.gcfg, err = config.Load(c) if err != nil { return nil, err } } return s.gcfg, nil }
[ "func", "(", "s", "*", "LUCIConfigProvider", ")", "Config", "(", "c", "context", ".", "Context", ")", "(", "*", "config", ".", "Config", ",", "error", ")", "{", "s", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "// Load/cache the global config.", "if", "s", ".", "gcfg", "==", "nil", "{", "var", "err", "error", "\n", "s", ".", "gcfg", ",", "err", "=", "config", ".", "Load", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "s", ".", "gcfg", ",", "nil", "\n", "}" ]
// Config implements ConfigProvider.
[ "Config", "implements", "ConfigProvider", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/configservice.go#L62-L76
7,420
luci/luci-go
logdog/appengine/coordinator/configservice.go
ProjectConfig
func (s *LUCIConfigProvider) ProjectConfig(c context.Context, project types.ProjectName) (*svcconfig.ProjectConfig, error) { return s.getOrCreateCachedProjectConfig(project).resolve(c) }
go
func (s *LUCIConfigProvider) ProjectConfig(c context.Context, project types.ProjectName) (*svcconfig.ProjectConfig, error) { return s.getOrCreateCachedProjectConfig(project).resolve(c) }
[ "func", "(", "s", "*", "LUCIConfigProvider", ")", "ProjectConfig", "(", "c", "context", ".", "Context", ",", "project", "types", ".", "ProjectName", ")", "(", "*", "svcconfig", ".", "ProjectConfig", ",", "error", ")", "{", "return", "s", ".", "getOrCreateCachedProjectConfig", "(", "project", ")", ".", "resolve", "(", "c", ")", "\n", "}" ]
// ProjectConfig implements ConfigProvider.
[ "ProjectConfig", "implements", "ConfigProvider", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/configservice.go#L119-L121
7,421
luci/luci-go
machine-db/appengine/config/datacenters.go
validateDatacentersCfg
func validateDatacentersCfg(c *validation.Context, cfg *configPB.Datacenters) { // Datacenter filenames must be unique. // Keep records of which ones we've already seen. files := stringset.New(len(cfg.Datacenter)) for _, file := range cfg.Datacenter { switch { case file == "": c.Errorf("datacenter filenames are required and must be non-empty") case !files.Add(file): c.Errorf("duplicate filename %q", file) } } }
go
func validateDatacentersCfg(c *validation.Context, cfg *configPB.Datacenters) { // Datacenter filenames must be unique. // Keep records of which ones we've already seen. files := stringset.New(len(cfg.Datacenter)) for _, file := range cfg.Datacenter { switch { case file == "": c.Errorf("datacenter filenames are required and must be non-empty") case !files.Add(file): c.Errorf("duplicate filename %q", file) } } }
[ "func", "validateDatacentersCfg", "(", "c", "*", "validation", ".", "Context", ",", "cfg", "*", "configPB", ".", "Datacenters", ")", "{", "// Datacenter filenames must be unique.", "// Keep records of which ones we've already seen.", "files", ":=", "stringset", ".", "New", "(", "len", "(", "cfg", ".", "Datacenter", ")", ")", "\n", "for", "_", ",", "file", ":=", "range", "cfg", ".", "Datacenter", "{", "switch", "{", "case", "file", "==", "\"", "\"", ":", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "!", "files", ".", "Add", "(", "file", ")", ":", "c", ".", "Errorf", "(", "\"", "\"", ",", "file", ")", "\n", "}", "\n", "}", "\n", "}" ]
// validateDatacentersCfg validates datacenters.cfg.
[ "validateDatacentersCfg", "validates", "datacenters", ".", "cfg", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/config/datacenters.go#L103-L115
7,422
luci/luci-go
milo/buildsource/buildbucket/common.go
parseStatus
func parseStatus(status buildbucketpb.Status) model.Status { if st, ok := statusMap[status]; ok { return st } return model.InfraFailure }
go
func parseStatus(status buildbucketpb.Status) model.Status { if st, ok := statusMap[status]; ok { return st } return model.InfraFailure }
[ "func", "parseStatus", "(", "status", "buildbucketpb", ".", "Status", ")", "model", ".", "Status", "{", "if", "st", ",", "ok", ":=", "statusMap", "[", "status", "]", ";", "ok", "{", "return", "st", "\n", "}", "\n", "return", "model", ".", "InfraFailure", "\n", "}" ]
// parseStatus converts a buildbucket status to model.Status.
[ "parseStatus", "converts", "a", "buildbucket", "status", "to", "model", ".", "Status", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/common.go#L73-L78
7,423
luci/luci-go
gce/cmd/agent/main.go
substitute
func substitute(c context.Context, s string, subs interface{}) (string, error) { t, err := template.New("tmpl").Parse(s) if err != nil { return "", err } buf := bytes.Buffer{} if err = t.Execute(&buf, subs); err != nil { return "", nil } return buf.String(), nil }
go
func substitute(c context.Context, s string, subs interface{}) (string, error) { t, err := template.New("tmpl").Parse(s) if err != nil { return "", err } buf := bytes.Buffer{} if err = t.Execute(&buf, subs); err != nil { return "", nil } return buf.String(), nil }
[ "func", "substitute", "(", "c", "context", ".", "Context", ",", "s", "string", ",", "subs", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "t", ",", "err", ":=", "template", ".", "New", "(", "\"", "\"", ")", ".", "Parse", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "buf", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", "=", "t", ".", "Execute", "(", "&", "buf", ",", "subs", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// substitute performs substitutions in a template string.
[ "substitute", "performs", "substitutions", "in", "a", "template", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/main.go#L40-L50
7,424
luci/luci-go
gce/cmd/agent/main.go
newInstances
func newInstances(c context.Context, acc, host string) instances.InstancesClient { return instances.NewInstancesPRPCClient(&prpc.Client{ C: client.NewClient(getMetadata(c), acc), Host: host, }) }
go
func newInstances(c context.Context, acc, host string) instances.InstancesClient { return instances.NewInstancesPRPCClient(&prpc.Client{ C: client.NewClient(getMetadata(c), acc), Host: host, }) }
[ "func", "newInstances", "(", "c", "context", ".", "Context", ",", "acc", ",", "host", "string", ")", "instances", ".", "InstancesClient", "{", "return", "instances", ".", "NewInstancesPRPCClient", "(", "&", "prpc", ".", "Client", "{", "C", ":", "client", ".", "NewClient", "(", "getMetadata", "(", "c", ")", ",", "acc", ")", ",", "Host", ":", "host", ",", "}", ")", "\n", "}" ]
// newInstances returns a new instances.InstancesClient.
[ "newInstances", "returns", "a", "new", "instances", ".", "InstancesClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/main.go#L66-L71
7,425
luci/luci-go
gce/cmd/agent/main.go
ModifyContext
func (b *cmdRunBase) ModifyContext(c context.Context) context.Context { c = logging.SetLevel(gologger.StdConfig.Use(c), logging.Debug) opts, err := b.authFlags.Options() if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get auth options") } b.serviceAccount = opts.GCEAccountName http, err := auth.NewAuthenticator(c, auth.OptionalLogin, opts).Client() if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get authenticator") } meta := metadata.NewClient(http) swr := &SwarmingClient{ Client: http, PlatformStrategy: newStrategy(), } return withSwarming(withMetadata(c, meta), swr) }
go
func (b *cmdRunBase) ModifyContext(c context.Context) context.Context { c = logging.SetLevel(gologger.StdConfig.Use(c), logging.Debug) opts, err := b.authFlags.Options() if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get auth options") } b.serviceAccount = opts.GCEAccountName http, err := auth.NewAuthenticator(c, auth.OptionalLogin, opts).Client() if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get authenticator") } meta := metadata.NewClient(http) swr := &SwarmingClient{ Client: http, PlatformStrategy: newStrategy(), } return withSwarming(withMetadata(c, meta), swr) }
[ "func", "(", "b", "*", "cmdRunBase", ")", "ModifyContext", "(", "c", "context", ".", "Context", ")", "context", ".", "Context", "{", "c", "=", "logging", ".", "SetLevel", "(", "gologger", ".", "StdConfig", ".", "Use", "(", "c", ")", ",", "logging", ".", "Debug", ")", "\n", "opts", ",", "err", ":=", "b", ".", "authFlags", ".", "Options", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "b", ".", "serviceAccount", "=", "opts", ".", "GCEAccountName", "\n", "http", ",", "err", ":=", "auth", ".", "NewAuthenticator", "(", "c", ",", "auth", ".", "OptionalLogin", ",", "opts", ")", ".", "Client", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "meta", ":=", "metadata", ".", "NewClient", "(", "http", ")", "\n", "swr", ":=", "&", "SwarmingClient", "{", "Client", ":", "http", ",", "PlatformStrategy", ":", "newStrategy", "(", ")", ",", "}", "\n", "return", "withSwarming", "(", "withMetadata", "(", "c", ",", "meta", ")", ",", "swr", ")", "\n", "}" ]
// ModifyContext returns a new context to be used by all commands. Implements // cli.ContextModificator.
[ "ModifyContext", "returns", "a", "new", "context", "to", "be", "used", "by", "all", "commands", ".", "Implements", "cli", ".", "ContextModificator", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/main.go#L89-L108
7,426
luci/luci-go
machine-db/appengine/rpc/vms.go
CreateVM
func (*Service) CreateVM(c context.Context, req *crimson.CreateVMRequest) (*crimson.VM, error) { return createVM(c, req.Vm) }
go
func (*Service) CreateVM(c context.Context, req *crimson.CreateVMRequest) (*crimson.VM, error) { return createVM(c, req.Vm) }
[ "func", "(", "*", "Service", ")", "CreateVM", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "CreateVMRequest", ")", "(", "*", "crimson", ".", "VM", ",", "error", ")", "{", "return", "createVM", "(", "c", ",", "req", ".", "Vm", ")", "\n", "}" ]
// CreateVM handles a request to create a new VM.
[ "CreateVM", "handles", "a", "request", "to", "create", "a", "new", "VM", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vms.go#L39-L41
7,427
luci/luci-go
machine-db/appengine/rpc/vms.go
ListVMs
func (*Service) ListVMs(c context.Context, req *crimson.ListVMsRequest) (*crimson.ListVMsResponse, error) { vms, err := listVMs(c, database.Get(c), req) if err != nil { return nil, err } return &crimson.ListVMsResponse{ Vms: vms, }, nil }
go
func (*Service) ListVMs(c context.Context, req *crimson.ListVMsRequest) (*crimson.ListVMsResponse, error) { vms, err := listVMs(c, database.Get(c), req) if err != nil { return nil, err } return &crimson.ListVMsResponse{ Vms: vms, }, nil }
[ "func", "(", "*", "Service", ")", "ListVMs", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "ListVMsRequest", ")", "(", "*", "crimson", ".", "ListVMsResponse", ",", "error", ")", "{", "vms", ",", "err", ":=", "listVMs", "(", "c", ",", "database", ".", "Get", "(", "c", ")", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "crimson", ".", "ListVMsResponse", "{", "Vms", ":", "vms", ",", "}", ",", "nil", "\n", "}" ]
// ListVMs handles a request to list VMs.
[ "ListVMs", "handles", "a", "request", "to", "list", "VMs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vms.go#L44-L52
7,428
luci/luci-go
machine-db/appengine/rpc/vms.go
UpdateVM
func (*Service) UpdateVM(c context.Context, req *crimson.UpdateVMRequest) (*crimson.VM, error) { return updateVM(c, req.Vm, req.UpdateMask) }
go
func (*Service) UpdateVM(c context.Context, req *crimson.UpdateVMRequest) (*crimson.VM, error) { return updateVM(c, req.Vm, req.UpdateMask) }
[ "func", "(", "*", "Service", ")", "UpdateVM", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "UpdateVMRequest", ")", "(", "*", "crimson", ".", "VM", ",", "error", ")", "{", "return", "updateVM", "(", "c", ",", "req", ".", "Vm", ",", "req", ".", "UpdateMask", ")", "\n", "}" ]
// UpdateVM handles a request to update an existing VM.
[ "UpdateVM", "handles", "a", "request", "to", "update", "an", "existing", "VM", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vms.go#L55-L57
7,429
luci/luci-go
machine-db/appengine/rpc/vms.go
createVM
func createVM(c context.Context, v *crimson.VM) (*crimson.VM, error) { if err := validateVMForCreation(v); err != nil { return nil, err } ip, _ := common.ParseIPv4(v.Ipv4) tx, err := database.Begin(c) if err != nil { return nil, errors.Annotate(err, "failed to begin transaction").Err() } defer tx.MaybeRollback(c) hostnameId, err := model.AssignHostnameAndIP(c, tx, v.Name, ip) if err != nil { return nil, err } // vms.hostname_id, vms.physical_host_id, and vms.os_id are NOT NULL as above. _, err = tx.ExecContext(c, ` INSERT INTO vms (hostname_id, physical_host_id, os_id, description, deployment_ticket, state) VALUES ( ?, (SELECT p.id FROM physical_hosts p, hostnames h WHERE p.hostname_id = h.id AND h.name = ?), (SELECT id FROM oses WHERE name = ?), ?, ?, ? ) `, hostnameId, v.Host, v.Os, v.Description, v.DeploymentTicket, v.State) if err != nil { switch e, ok := err.(*mysql.MySQLError); { case !ok: // Type assertion failed. case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'physical_host_id'"): // e.g. "Error 1048: Column 'physical_host_id' cannot be null". return nil, status.Errorf(codes.NotFound, "physical host %q does not exist", v.Host) case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'os_id'"): // e.g. "Error 1048: Column 'os_id' cannot be null". return nil, status.Errorf(codes.NotFound, "operating system %q does not exist", v.Os) } return nil, errors.Annotate(err, "failed to create VM").Err() } vms, err := listVMs(c, tx, &crimson.ListVMsRequest{ Names: []string{v.Name}, }) if err != nil { return nil, errors.Annotate(err, "failed to fetch created VM").Err() } if err := tx.Commit(); err != nil { return nil, errors.Annotate(err, "failed to commit transaction").Err() } return vms[0], nil }
go
func createVM(c context.Context, v *crimson.VM) (*crimson.VM, error) { if err := validateVMForCreation(v); err != nil { return nil, err } ip, _ := common.ParseIPv4(v.Ipv4) tx, err := database.Begin(c) if err != nil { return nil, errors.Annotate(err, "failed to begin transaction").Err() } defer tx.MaybeRollback(c) hostnameId, err := model.AssignHostnameAndIP(c, tx, v.Name, ip) if err != nil { return nil, err } // vms.hostname_id, vms.physical_host_id, and vms.os_id are NOT NULL as above. _, err = tx.ExecContext(c, ` INSERT INTO vms (hostname_id, physical_host_id, os_id, description, deployment_ticket, state) VALUES ( ?, (SELECT p.id FROM physical_hosts p, hostnames h WHERE p.hostname_id = h.id AND h.name = ?), (SELECT id FROM oses WHERE name = ?), ?, ?, ? ) `, hostnameId, v.Host, v.Os, v.Description, v.DeploymentTicket, v.State) if err != nil { switch e, ok := err.(*mysql.MySQLError); { case !ok: // Type assertion failed. case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'physical_host_id'"): // e.g. "Error 1048: Column 'physical_host_id' cannot be null". return nil, status.Errorf(codes.NotFound, "physical host %q does not exist", v.Host) case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'os_id'"): // e.g. "Error 1048: Column 'os_id' cannot be null". return nil, status.Errorf(codes.NotFound, "operating system %q does not exist", v.Os) } return nil, errors.Annotate(err, "failed to create VM").Err() } vms, err := listVMs(c, tx, &crimson.ListVMsRequest{ Names: []string{v.Name}, }) if err != nil { return nil, errors.Annotate(err, "failed to fetch created VM").Err() } if err := tx.Commit(); err != nil { return nil, errors.Annotate(err, "failed to commit transaction").Err() } return vms[0], nil }
[ "func", "createVM", "(", "c", "context", ".", "Context", ",", "v", "*", "crimson", ".", "VM", ")", "(", "*", "crimson", ".", "VM", ",", "error", ")", "{", "if", "err", ":=", "validateVMForCreation", "(", "v", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ip", ",", "_", ":=", "common", ".", "ParseIPv4", "(", "v", ".", "Ipv4", ")", "\n", "tx", ",", "err", ":=", "database", ".", "Begin", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "tx", ".", "MaybeRollback", "(", "c", ")", "\n\n", "hostnameId", ",", "err", ":=", "model", ".", "AssignHostnameAndIP", "(", "c", ",", "tx", ",", "v", ".", "Name", ",", "ip", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// vms.hostname_id, vms.physical_host_id, and vms.os_id are NOT NULL as above.", "_", ",", "err", "=", "tx", ".", "ExecContext", "(", "c", ",", "`\n\t\tINSERT INTO vms (hostname_id, physical_host_id, os_id, description, deployment_ticket, state)\n\t\tVALUES (\n\t\t\t?,\n\t\t\t(SELECT p.id FROM physical_hosts p, hostnames h WHERE p.hostname_id = h.id AND h.name = ?),\n\t\t\t(SELECT id FROM oses WHERE name = ?),\n\t\t\t?,\n\t\t\t?,\n\t\t\t?\n\t\t)\n\t`", ",", "hostnameId", ",", "v", ".", "Host", ",", "v", ".", "Os", ",", "v", ".", "Description", ",", "v", ".", "DeploymentTicket", ",", "v", ".", "State", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "e", ",", "ok", ":=", "err", ".", "(", "*", "mysql", ".", "MySQLError", ")", ";", "{", "case", "!", "ok", ":", "// Type assertion failed.", "case", "e", ".", "Number", "==", "mysqlerr", ".", "ER_BAD_NULL_ERROR", "&&", "strings", ".", "Contains", "(", "e", ".", "Message", ",", "\"", "\"", ")", ":", "// e.g. \"Error 1048: Column 'physical_host_id' cannot be null\".", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "v", ".", "Host", ")", "\n", "case", "e", ".", "Number", "==", "mysqlerr", ".", "ER_BAD_NULL_ERROR", "&&", "strings", ".", "Contains", "(", "e", ".", "Message", ",", "\"", "\"", ")", ":", "// e.g. \"Error 1048: Column 'os_id' cannot be null\".", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "v", ".", "Os", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "vms", ",", "err", ":=", "listVMs", "(", "c", ",", "tx", ",", "&", "crimson", ".", "ListVMsRequest", "{", "Names", ":", "[", "]", "string", "{", "v", ".", "Name", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "err", ":=", "tx", ".", "Commit", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "vms", "[", "0", "]", ",", "nil", "\n", "}" ]
// createVM creates a new VM in the database.
[ "createVM", "creates", "a", "new", "VM", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vms.go#L60-L113
7,430
luci/luci-go
machine-db/appengine/rpc/vms.go
listVMs
func listVMs(c context.Context, q database.QueryerContext, req *crimson.ListVMsRequest) ([]*crimson.VM, error) { ipv4s, err := parseIPv4s(req.Ipv4S) if err != nil { return nil, err } stmt := squirrel.Select( "hv.name", "hv.vlan_id", "hp.name", "hp.vlan_id", "o.name", "v.description", "v.deployment_ticket", "i.ipv4", "v.state", ) stmt = stmt.From("vms v, hostnames hv, physical_hosts p, hostnames hp, oses o, ips i"). Where("v.hostname_id = hv.id"). Where("v.physical_host_id = p.id"). Where("p.hostname_id = hp.id"). Where("v.os_id = o.id"). Where("i.hostname_id = hv.id") stmt = selectInString(stmt, "hv.name", req.Names) stmt = selectInInt64(stmt, "hv.vlan_id", req.Vlans) stmt = selectInInt64(stmt, "i.ipv4", ipv4s) stmt = selectInString(stmt, "hp.name", req.Hosts) stmt = selectInInt64(stmt, "hp.vlan_id", req.HostVlans) stmt = selectInString(stmt, "o.name", req.Oses) stmt = selectInState(stmt, "v.state", req.States) query, args, err := stmt.ToSql() if err != nil { return nil, errors.Annotate(err, "failed to generate statement").Err() } rows, err := q.QueryContext(c, query, args...) if err != nil { return nil, errors.Annotate(err, "failed to fetch VMs").Err() } defer rows.Close() var vms []*crimson.VM for rows.Next() { v := &crimson.VM{} var ipv4 common.IPv4 if err = rows.Scan( &v.Name, &v.Vlan, &v.Host, &v.HostVlan, &v.Os, &v.Description, &v.DeploymentTicket, &ipv4, &v.State, ); err != nil { return nil, errors.Annotate(err, "failed to fetch VM").Err() } v.Ipv4 = ipv4.String() vms = append(vms, v) } return vms, nil }
go
func listVMs(c context.Context, q database.QueryerContext, req *crimson.ListVMsRequest) ([]*crimson.VM, error) { ipv4s, err := parseIPv4s(req.Ipv4S) if err != nil { return nil, err } stmt := squirrel.Select( "hv.name", "hv.vlan_id", "hp.name", "hp.vlan_id", "o.name", "v.description", "v.deployment_ticket", "i.ipv4", "v.state", ) stmt = stmt.From("vms v, hostnames hv, physical_hosts p, hostnames hp, oses o, ips i"). Where("v.hostname_id = hv.id"). Where("v.physical_host_id = p.id"). Where("p.hostname_id = hp.id"). Where("v.os_id = o.id"). Where("i.hostname_id = hv.id") stmt = selectInString(stmt, "hv.name", req.Names) stmt = selectInInt64(stmt, "hv.vlan_id", req.Vlans) stmt = selectInInt64(stmt, "i.ipv4", ipv4s) stmt = selectInString(stmt, "hp.name", req.Hosts) stmt = selectInInt64(stmt, "hp.vlan_id", req.HostVlans) stmt = selectInString(stmt, "o.name", req.Oses) stmt = selectInState(stmt, "v.state", req.States) query, args, err := stmt.ToSql() if err != nil { return nil, errors.Annotate(err, "failed to generate statement").Err() } rows, err := q.QueryContext(c, query, args...) if err != nil { return nil, errors.Annotate(err, "failed to fetch VMs").Err() } defer rows.Close() var vms []*crimson.VM for rows.Next() { v := &crimson.VM{} var ipv4 common.IPv4 if err = rows.Scan( &v.Name, &v.Vlan, &v.Host, &v.HostVlan, &v.Os, &v.Description, &v.DeploymentTicket, &ipv4, &v.State, ); err != nil { return nil, errors.Annotate(err, "failed to fetch VM").Err() } v.Ipv4 = ipv4.String() vms = append(vms, v) } return vms, nil }
[ "func", "listVMs", "(", "c", "context", ".", "Context", ",", "q", "database", ".", "QueryerContext", ",", "req", "*", "crimson", ".", "ListVMsRequest", ")", "(", "[", "]", "*", "crimson", ".", "VM", ",", "error", ")", "{", "ipv4s", ",", "err", ":=", "parseIPv4s", "(", "req", ".", "Ipv4S", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stmt", ":=", "squirrel", ".", "Select", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", ")", "\n", "stmt", "=", "stmt", ".", "From", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Names", ")", "\n", "stmt", "=", "selectInInt64", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Vlans", ")", "\n", "stmt", "=", "selectInInt64", "(", "stmt", ",", "\"", "\"", ",", "ipv4s", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Hosts", ")", "\n", "stmt", "=", "selectInInt64", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "HostVlans", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Oses", ")", "\n", "stmt", "=", "selectInState", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "States", ")", "\n", "query", ",", "args", ",", "err", ":=", "stmt", ".", "ToSql", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "rows", ",", "err", ":=", "q", ".", "QueryContext", "(", "c", ",", "query", ",", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "var", "vms", "[", "]", "*", "crimson", ".", "VM", "\n", "for", "rows", ".", "Next", "(", ")", "{", "v", ":=", "&", "crimson", ".", "VM", "{", "}", "\n", "var", "ipv4", "common", ".", "IPv4", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "v", ".", "Name", ",", "&", "v", ".", "Vlan", ",", "&", "v", ".", "Host", ",", "&", "v", ".", "HostVlan", ",", "&", "v", ".", "Os", ",", "&", "v", ".", "Description", ",", "&", "v", ".", "DeploymentTicket", ",", "&", "ipv4", ",", "&", "v", ".", "State", ",", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "v", ".", "Ipv4", "=", "ipv4", ".", "String", "(", ")", "\n", "vms", "=", "append", "(", "vms", ",", "v", ")", "\n", "}", "\n", "return", "vms", ",", "nil", "\n", "}" ]
// listVMs returns a slice of VMs in the database.
[ "listVMs", "returns", "a", "slice", "of", "VMs", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vms.go#L116-L177
7,431
luci/luci-go
machine-db/appengine/rpc/vms.go
validateVMForCreation
func validateVMForCreation(v *crimson.VM) error { switch { case v == nil: return status.Error(codes.InvalidArgument, "VM specification is required") case v.Name == "": return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty") case v.Vlan != 0: return status.Error(codes.InvalidArgument, "VLAN must not be specified, use IP address instead") case v.Host == "": return status.Error(codes.InvalidArgument, "physical hostname is required and must be non-empty") case v.HostVlan != 0: return status.Error(codes.InvalidArgument, "host VLAN must not be specified, use physical hostname instead") case v.Os == "": return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty") case v.Ipv4 == "": return status.Error(codes.InvalidArgument, "IPv4 address is required and must be non-empty") case v.State == states.State_STATE_UNSPECIFIED: return status.Error(codes.InvalidArgument, "state is required") default: _, err := common.ParseIPv4(v.Ipv4) if err != nil { return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", v.Ipv4) } return nil } }
go
func validateVMForCreation(v *crimson.VM) error { switch { case v == nil: return status.Error(codes.InvalidArgument, "VM specification is required") case v.Name == "": return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty") case v.Vlan != 0: return status.Error(codes.InvalidArgument, "VLAN must not be specified, use IP address instead") case v.Host == "": return status.Error(codes.InvalidArgument, "physical hostname is required and must be non-empty") case v.HostVlan != 0: return status.Error(codes.InvalidArgument, "host VLAN must not be specified, use physical hostname instead") case v.Os == "": return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty") case v.Ipv4 == "": return status.Error(codes.InvalidArgument, "IPv4 address is required and must be non-empty") case v.State == states.State_STATE_UNSPECIFIED: return status.Error(codes.InvalidArgument, "state is required") default: _, err := common.ParseIPv4(v.Ipv4) if err != nil { return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", v.Ipv4) } return nil } }
[ "func", "validateVMForCreation", "(", "v", "*", "crimson", ".", "VM", ")", "error", "{", "switch", "{", "case", "v", "==", "nil", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "v", ".", "Name", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "v", ".", "Vlan", "!=", "0", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "v", ".", "Host", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "v", ".", "HostVlan", "!=", "0", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "v", ".", "Os", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "v", ".", "Ipv4", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "v", ".", "State", "==", "states", ".", "State_STATE_UNSPECIFIED", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "default", ":", "_", ",", "err", ":=", "common", ".", "ParseIPv4", "(", "v", ".", "Ipv4", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "v", ".", "Ipv4", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// validateVMForCreation validates a VM for creation.
[ "validateVMForCreation", "validates", "a", "VM", "for", "creation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vms.go#L249-L274
7,432
luci/luci-go
machine-db/appengine/rpc/vms.go
validateVMForUpdate
func validateVMForUpdate(v *crimson.VM, mask *field_mask.FieldMask) error { switch err := validateUpdateMask(mask); { case v == nil: return status.Error(codes.InvalidArgument, "VM specification is required") case v.Name == "": return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty") case err != nil: return err } for _, path := range mask.Paths { // TODO(smut): Allow IPv4 address to be updated. switch path { case "name": return status.Error(codes.InvalidArgument, "hostname cannot be updated, delete and create a new VM instead") case "vlan": return status.Error(codes.InvalidArgument, "VLAN cannot be updated, delete and create a new VM instead") case "host": if v.Host == "" { return status.Error(codes.InvalidArgument, "physical hostname is required and must be non-empty") } case "host_vlan": return status.Error(codes.InvalidArgument, "host VLAN cannot be updated, update the host instead") case "os": if v.Os == "" { return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty") } case "state": if v.State == states.State_STATE_UNSPECIFIED { return status.Error(codes.InvalidArgument, "state is required") } case "description": // Empty description is allowed, nothing to validate. case "deployment_ticket": // Empty deployment ticket is allowed, nothing to validate. default: return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path) } } return nil }
go
func validateVMForUpdate(v *crimson.VM, mask *field_mask.FieldMask) error { switch err := validateUpdateMask(mask); { case v == nil: return status.Error(codes.InvalidArgument, "VM specification is required") case v.Name == "": return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty") case err != nil: return err } for _, path := range mask.Paths { // TODO(smut): Allow IPv4 address to be updated. switch path { case "name": return status.Error(codes.InvalidArgument, "hostname cannot be updated, delete and create a new VM instead") case "vlan": return status.Error(codes.InvalidArgument, "VLAN cannot be updated, delete and create a new VM instead") case "host": if v.Host == "" { return status.Error(codes.InvalidArgument, "physical hostname is required and must be non-empty") } case "host_vlan": return status.Error(codes.InvalidArgument, "host VLAN cannot be updated, update the host instead") case "os": if v.Os == "" { return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty") } case "state": if v.State == states.State_STATE_UNSPECIFIED { return status.Error(codes.InvalidArgument, "state is required") } case "description": // Empty description is allowed, nothing to validate. case "deployment_ticket": // Empty deployment ticket is allowed, nothing to validate. default: return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path) } } return nil }
[ "func", "validateVMForUpdate", "(", "v", "*", "crimson", ".", "VM", ",", "mask", "*", "field_mask", ".", "FieldMask", ")", "error", "{", "switch", "err", ":=", "validateUpdateMask", "(", "mask", ")", ";", "{", "case", "v", "==", "nil", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "v", ".", "Name", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "err", "!=", "nil", ":", "return", "err", "\n", "}", "\n", "for", "_", ",", "path", ":=", "range", "mask", ".", "Paths", "{", "// TODO(smut): Allow IPv4 address to be updated.", "switch", "path", "{", "case", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "\"", "\"", ":", "if", "v", ".", "Host", "==", "\"", "\"", "{", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "\"", "\"", ":", "if", "v", ".", "Os", "==", "\"", "\"", "{", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "v", ".", "State", "==", "states", ".", "State_STATE_UNSPECIFIED", "{", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "// Empty description is allowed, nothing to validate.", "case", "\"", "\"", ":", "// Empty deployment ticket is allowed, nothing to validate.", "default", ":", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateVMForUpdate validates a VM for update.
[ "validateVMForUpdate", "validates", "a", "VM", "for", "update", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vms.go#L277-L316
7,433
luci/luci-go
machine-db/client/cli/flags.go
Register
func (f *CommonFlags) Register(flags *flag.FlagSet, params *Parameters) { f.authFlags.Register(flags, params.AuthOptions) flags.BoolVar(&f.tsv, "tsv", false, "Whether to emit data in tsv instead of human-readable format.") }
go
func (f *CommonFlags) Register(flags *flag.FlagSet, params *Parameters) { f.authFlags.Register(flags, params.AuthOptions) flags.BoolVar(&f.tsv, "tsv", false, "Whether to emit data in tsv instead of human-readable format.") }
[ "func", "(", "f", "*", "CommonFlags", ")", "Register", "(", "flags", "*", "flag", ".", "FlagSet", ",", "params", "*", "Parameters", ")", "{", "f", ".", "authFlags", ".", "Register", "(", "flags", ",", "params", ".", "AuthOptions", ")", "\n", "flags", ".", "BoolVar", "(", "&", "f", ".", "tsv", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "}" ]
// Register registers common flags with the given flag.FlagSet.
[ "Register", "registers", "common", "flags", "with", "the", "given", "flag", ".", "FlagSet", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/flags.go#L37-L40
7,434
luci/luci-go
machine-db/client/cli/flags.go
Set
func (f *stateFlag) Set(s string) error { i, err := common.GetState(s) if err != nil { return errors.Reason("value must be a valid state returned by get-states").Err() } *f = stateFlag(i) return nil }
go
func (f *stateFlag) Set(s string) error { i, err := common.GetState(s) if err != nil { return errors.Reason("value must be a valid state returned by get-states").Err() } *f = stateFlag(i) return nil }
[ "func", "(", "f", "*", "stateFlag", ")", "Set", "(", "s", "string", ")", "error", "{", "i", ",", "err", ":=", "common", ".", "GetState", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "*", "f", "=", "stateFlag", "(", "i", ")", "\n", "return", "nil", "\n", "}" ]
// Set stores a new state in this flag, overriding any existing state.
[ "Set", "stores", "a", "new", "state", "in", "this", "flag", "overriding", "any", "existing", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/flags.go#L58-L65
7,435
luci/luci-go
machine-db/client/cli/flags.go
String
func (f *stateSliceFlag) String() string { s := make([]string, len(*f)) for i, j := range *f { s[i] = j.Name() } return strings.Join(s, ", ") }
go
func (f *stateSliceFlag) String() string { s := make([]string, len(*f)) for i, j := range *f { s[i] = j.Name() } return strings.Join(s, ", ") }
[ "func", "(", "f", "*", "stateSliceFlag", ")", "String", "(", ")", "string", "{", "s", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "*", "f", ")", ")", "\n", "for", "i", ",", "j", ":=", "range", "*", "f", "{", "s", "[", "i", "]", "=", "j", ".", "Name", "(", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "s", ",", "\"", "\"", ")", "\n", "}" ]
// String returns a comma-separated string representation of flag.
[ "String", "returns", "a", "comma", "-", "separated", "string", "representation", "of", "flag", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/flags.go#L91-L97
7,436
luci/luci-go
milo/git/gerrit.go
CLEmail
func (p *implementation) CLEmail(c context.Context, host string, changeNumber int64) (email string, err error) { defer func() { err = common.TagGRPC(c, err) }() changeInfo, err := p.clEmailAndProjectNoACLs(c, host, changeNumber) if err != nil { return } allowed, err := p.acls.IsAllowed(c, host, changeInfo.Project) switch { case err != nil: return case allowed: email = changeInfo.GetOwner().GetEmail() default: err = errGRPCNotFound } return }
go
func (p *implementation) CLEmail(c context.Context, host string, changeNumber int64) (email string, err error) { defer func() { err = common.TagGRPC(c, err) }() changeInfo, err := p.clEmailAndProjectNoACLs(c, host, changeNumber) if err != nil { return } allowed, err := p.acls.IsAllowed(c, host, changeInfo.Project) switch { case err != nil: return case allowed: email = changeInfo.GetOwner().GetEmail() default: err = errGRPCNotFound } return }
[ "func", "(", "p", "*", "implementation", ")", "CLEmail", "(", "c", "context", ".", "Context", ",", "host", "string", ",", "changeNumber", "int64", ")", "(", "email", "string", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "err", "=", "common", ".", "TagGRPC", "(", "c", ",", "err", ")", "}", "(", ")", "\n", "changeInfo", ",", "err", ":=", "p", ".", "clEmailAndProjectNoACLs", "(", "c", ",", "host", ",", "changeNumber", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "allowed", ",", "err", ":=", "p", ".", "acls", ".", "IsAllowed", "(", "c", ",", "host", ",", "changeInfo", ".", "Project", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "\n", "case", "allowed", ":", "email", "=", "changeInfo", ".", "GetOwner", "(", ")", ".", "GetEmail", "(", ")", "\n", "default", ":", "err", "=", "errGRPCNotFound", "\n", "}", "\n", "return", "\n", "}" ]
// CLEmail implements Client interface.
[ "CLEmail", "implements", "Client", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/gerrit.go#L33-L49
7,437
luci/luci-go
client/cmd/cloudkms/common.go
validateCryptoKeysKMSPath
func validateCryptoKeysKMSPath(path string) error { if path[0] == '/' { path = path[1:] } components := strings.Split(path, "/") if len(components) < (len(cryptoKeysPathComponents)-1)*2 || len(components) > len(cryptoKeysPathComponents)*2 { return errors.Reason("path should have the form %s", strings.Join(cryptoKeysPathComponents, "/.../")+"/...").Err() } for i, c := range components { if i%2 == 1 { continue } expect := cryptoKeysPathComponents[i/2] if c != expect { return errors.Reason("expected component %d to be %s, got %s", i+1, expect, c).Err() } } return nil }
go
func validateCryptoKeysKMSPath(path string) error { if path[0] == '/' { path = path[1:] } components := strings.Split(path, "/") if len(components) < (len(cryptoKeysPathComponents)-1)*2 || len(components) > len(cryptoKeysPathComponents)*2 { return errors.Reason("path should have the form %s", strings.Join(cryptoKeysPathComponents, "/.../")+"/...").Err() } for i, c := range components { if i%2 == 1 { continue } expect := cryptoKeysPathComponents[i/2] if c != expect { return errors.Reason("expected component %d to be %s, got %s", i+1, expect, c).Err() } } return nil }
[ "func", "validateCryptoKeysKMSPath", "(", "path", "string", ")", "error", "{", "if", "path", "[", "0", "]", "==", "'/'", "{", "path", "=", "path", "[", "1", ":", "]", "\n", "}", "\n", "components", ":=", "strings", ".", "Split", "(", "path", ",", "\"", "\"", ")", "\n", "if", "len", "(", "components", ")", "<", "(", "len", "(", "cryptoKeysPathComponents", ")", "-", "1", ")", "*", "2", "||", "len", "(", "components", ")", ">", "len", "(", "cryptoKeysPathComponents", ")", "*", "2", "{", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "cryptoKeysPathComponents", ",", "\"", "\"", ")", "+", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "for", "i", ",", "c", ":=", "range", "components", "{", "if", "i", "%", "2", "==", "1", "{", "continue", "\n", "}", "\n", "expect", ":=", "cryptoKeysPathComponents", "[", "i", "/", "2", "]", "\n", "if", "c", "!=", "expect", "{", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "i", "+", "1", ",", "expect", ",", "c", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateCryptoKeysKMSPath validates a cloudkms path used for the API calls currently // supported by this client. // // What this means is we only care about paths that look exactly like the ones // constructed from kmsPathComponents.
[ "validateCryptoKeysKMSPath", "validates", "a", "cloudkms", "path", "used", "for", "the", "API", "calls", "currently", "supported", "by", "this", "client", ".", "What", "this", "means", "is", "we", "only", "care", "about", "paths", "that", "look", "exactly", "like", "the", "ones", "constructed", "from", "kmsPathComponents", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/cloudkms/common.go#L89-L107
7,438
luci/luci-go
common/tsmon/monitor/fake.go
Send
func (m *Fake) Send(c context.Context, cells []types.Cell) error { if m.SendErr != nil { return m.SendErr } m.Cells = append(m.Cells, cells) return nil }
go
func (m *Fake) Send(c context.Context, cells []types.Cell) error { if m.SendErr != nil { return m.SendErr } m.Cells = append(m.Cells, cells) return nil }
[ "func", "(", "m", "*", "Fake", ")", "Send", "(", "c", "context", ".", "Context", ",", "cells", "[", "]", "types", ".", "Cell", ")", "error", "{", "if", "m", ".", "SendErr", "!=", "nil", "{", "return", "m", ".", "SendErr", "\n", "}", "\n", "m", ".", "Cells", "=", "append", "(", "m", ".", "Cells", ",", "cells", ")", "\n", "return", "nil", "\n", "}" ]
// Send appends the cells to Cells, unless SendErr is set.
[ "Send", "appends", "the", "cells", "to", "Cells", "unless", "SendErr", "is", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/monitor/fake.go#L36-L42
7,439
luci/luci-go
dm/api/service/v1/graph_data_update.go
UpdateWith
func (g *GraphData) UpdateWith(other *GraphData) { for qid, q := range other.Quests { if curQ, ok := g.Quests[qid]; !ok { g.Quests[qid] = q } else { curQ.UpdateWith(q) } } }
go
func (g *GraphData) UpdateWith(other *GraphData) { for qid, q := range other.Quests { if curQ, ok := g.Quests[qid]; !ok { g.Quests[qid] = q } else { curQ.UpdateWith(q) } } }
[ "func", "(", "g", "*", "GraphData", ")", "UpdateWith", "(", "other", "*", "GraphData", ")", "{", "for", "qid", ",", "q", ":=", "range", "other", ".", "Quests", "{", "if", "curQ", ",", "ok", ":=", "g", ".", "Quests", "[", "qid", "]", ";", "!", "ok", "{", "g", ".", "Quests", "[", "qid", "]", "=", "q", "\n", "}", "else", "{", "curQ", ".", "UpdateWith", "(", "q", ")", "\n", "}", "\n", "}", "\n", "}" ]
// UpdateWith updates this GraphData with all of the data contained in other. // Assumes that any mutable data in other is more up-to-date than the data in g.
[ "UpdateWith", "updates", "this", "GraphData", "with", "all", "of", "the", "data", "contained", "in", "other", ".", "Assumes", "that", "any", "mutable", "data", "in", "other", "is", "more", "up", "-", "to", "-", "date", "than", "the", "data", "in", "g", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_data_update.go#L23-L31
7,440
luci/luci-go
dm/api/service/v1/graph_data_update.go
UpdateWith
func (q *Quest) UpdateWith(o *Quest) { if q.Data == nil { q.Data = o.Data q.Partial = false } else if !o.Partial { q.Data.UpdateWith(o.Data) q.Partial = false } if q.Id == nil { q.Id = o.Id } for aid, a := range o.Attempts { if curA, ok := q.Attempts[aid]; !ok { q.Attempts[aid] = a } else { curA.UpdateWith(a) } } }
go
func (q *Quest) UpdateWith(o *Quest) { if q.Data == nil { q.Data = o.Data q.Partial = false } else if !o.Partial { q.Data.UpdateWith(o.Data) q.Partial = false } if q.Id == nil { q.Id = o.Id } for aid, a := range o.Attempts { if curA, ok := q.Attempts[aid]; !ok { q.Attempts[aid] = a } else { curA.UpdateWith(a) } } }
[ "func", "(", "q", "*", "Quest", ")", "UpdateWith", "(", "o", "*", "Quest", ")", "{", "if", "q", ".", "Data", "==", "nil", "{", "q", ".", "Data", "=", "o", ".", "Data", "\n", "q", ".", "Partial", "=", "false", "\n", "}", "else", "if", "!", "o", ".", "Partial", "{", "q", ".", "Data", ".", "UpdateWith", "(", "o", ".", "Data", ")", "\n", "q", ".", "Partial", "=", "false", "\n", "}", "\n", "if", "q", ".", "Id", "==", "nil", "{", "q", ".", "Id", "=", "o", ".", "Id", "\n", "}", "\n", "for", "aid", ",", "a", ":=", "range", "o", ".", "Attempts", "{", "if", "curA", ",", "ok", ":=", "q", ".", "Attempts", "[", "aid", "]", ";", "!", "ok", "{", "q", ".", "Attempts", "[", "aid", "]", "=", "a", "\n", "}", "else", "{", "curA", ".", "UpdateWith", "(", "a", ")", "\n", "}", "\n", "}", "\n", "}" ]
// UpdateWith updates this Quest with data from other.
[ "UpdateWith", "updates", "this", "Quest", "with", "data", "from", "other", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_data_update.go#L34-L52
7,441
luci/luci-go
dm/api/service/v1/graph_data_update.go
UpdateWith
func (q *Quest_Data) UpdateWith(other *Quest_Data) { pivot := len(q.BuiltBy) q.BuiltBy = append(q.BuiltBy, other.BuiltBy...) q.BuiltBy = q.BuiltBy[:set.Union(QuestTemplateSpecs(q.BuiltBy), pivot)] }
go
func (q *Quest_Data) UpdateWith(other *Quest_Data) { pivot := len(q.BuiltBy) q.BuiltBy = append(q.BuiltBy, other.BuiltBy...) q.BuiltBy = q.BuiltBy[:set.Union(QuestTemplateSpecs(q.BuiltBy), pivot)] }
[ "func", "(", "q", "*", "Quest_Data", ")", "UpdateWith", "(", "other", "*", "Quest_Data", ")", "{", "pivot", ":=", "len", "(", "q", ".", "BuiltBy", ")", "\n", "q", ".", "BuiltBy", "=", "append", "(", "q", ".", "BuiltBy", ",", "other", ".", "BuiltBy", "...", ")", "\n", "q", ".", "BuiltBy", "=", "q", ".", "BuiltBy", "[", ":", "set", ".", "Union", "(", "QuestTemplateSpecs", "(", "q", ".", "BuiltBy", ")", ",", "pivot", ")", "]", "\n", "}" ]
// UpdateWith updates this Quest_Data with data from other.
[ "UpdateWith", "updates", "this", "Quest_Data", "with", "data", "from", "other", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_data_update.go#L55-L59
7,442
luci/luci-go
dm/api/service/v1/graph_data_update.go
UpdateWith
func (a *Attempt) UpdateWith(other *Attempt) { if a.Partial == nil { a.Partial = &Attempt_Partial{} } if a.Data == nil { a.Data = other.Data a.Partial.Data = false } else if other.Partial != nil && !other.Partial.Data { a.Data.UpdateWith(other.Data) a.Partial.Data = false } if a.Id == nil { a.Id = other.Id } for eid, e := range other.Executions { if curE, ok := a.Executions[eid]; !ok { a.Executions[eid] = e } else { curE.UpdateWith(e) } } if a.FwdDeps == nil { a.FwdDeps = other.FwdDeps } else { a.FwdDeps.UpdateWith(other.FwdDeps) } if a.BackDeps == nil { a.BackDeps = other.BackDeps } else { a.BackDeps.UpdateWith(other.BackDeps) } }
go
func (a *Attempt) UpdateWith(other *Attempt) { if a.Partial == nil { a.Partial = &Attempt_Partial{} } if a.Data == nil { a.Data = other.Data a.Partial.Data = false } else if other.Partial != nil && !other.Partial.Data { a.Data.UpdateWith(other.Data) a.Partial.Data = false } if a.Id == nil { a.Id = other.Id } for eid, e := range other.Executions { if curE, ok := a.Executions[eid]; !ok { a.Executions[eid] = e } else { curE.UpdateWith(e) } } if a.FwdDeps == nil { a.FwdDeps = other.FwdDeps } else { a.FwdDeps.UpdateWith(other.FwdDeps) } if a.BackDeps == nil { a.BackDeps = other.BackDeps } else { a.BackDeps.UpdateWith(other.BackDeps) } }
[ "func", "(", "a", "*", "Attempt", ")", "UpdateWith", "(", "other", "*", "Attempt", ")", "{", "if", "a", ".", "Partial", "==", "nil", "{", "a", ".", "Partial", "=", "&", "Attempt_Partial", "{", "}", "\n", "}", "\n\n", "if", "a", ".", "Data", "==", "nil", "{", "a", ".", "Data", "=", "other", ".", "Data", "\n", "a", ".", "Partial", ".", "Data", "=", "false", "\n", "}", "else", "if", "other", ".", "Partial", "!=", "nil", "&&", "!", "other", ".", "Partial", ".", "Data", "{", "a", ".", "Data", ".", "UpdateWith", "(", "other", ".", "Data", ")", "\n", "a", ".", "Partial", ".", "Data", "=", "false", "\n", "}", "\n\n", "if", "a", ".", "Id", "==", "nil", "{", "a", ".", "Id", "=", "other", ".", "Id", "\n", "}", "\n\n", "for", "eid", ",", "e", ":=", "range", "other", ".", "Executions", "{", "if", "curE", ",", "ok", ":=", "a", ".", "Executions", "[", "eid", "]", ";", "!", "ok", "{", "a", ".", "Executions", "[", "eid", "]", "=", "e", "\n", "}", "else", "{", "curE", ".", "UpdateWith", "(", "e", ")", "\n", "}", "\n", "}", "\n\n", "if", "a", ".", "FwdDeps", "==", "nil", "{", "a", ".", "FwdDeps", "=", "other", ".", "FwdDeps", "\n", "}", "else", "{", "a", ".", "FwdDeps", ".", "UpdateWith", "(", "other", ".", "FwdDeps", ")", "\n", "}", "\n\n", "if", "a", ".", "BackDeps", "==", "nil", "{", "a", ".", "BackDeps", "=", "other", ".", "BackDeps", "\n", "}", "else", "{", "a", ".", "BackDeps", ".", "UpdateWith", "(", "other", ".", "BackDeps", ")", "\n", "}", "\n", "}" ]
// UpdateWith updates this Attempt with data from other.
[ "UpdateWith", "updates", "this", "Attempt", "with", "data", "from", "other", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_data_update.go#L62-L98
7,443
luci/luci-go
dm/api/service/v1/graph_data_update.go
UpdateWith
func (a *Attempt_Data) UpdateWith(other *Attempt_Data) { if a.Created == nil { a.Created = other.Created } if other.Modified != nil { a.Modified = other.Modified } a.NumExecutions = other.NumExecutions if other.AttemptType != nil { a.AttemptType = other.AttemptType } }
go
func (a *Attempt_Data) UpdateWith(other *Attempt_Data) { if a.Created == nil { a.Created = other.Created } if other.Modified != nil { a.Modified = other.Modified } a.NumExecutions = other.NumExecutions if other.AttemptType != nil { a.AttemptType = other.AttemptType } }
[ "func", "(", "a", "*", "Attempt_Data", ")", "UpdateWith", "(", "other", "*", "Attempt_Data", ")", "{", "if", "a", ".", "Created", "==", "nil", "{", "a", ".", "Created", "=", "other", ".", "Created", "\n", "}", "\n", "if", "other", ".", "Modified", "!=", "nil", "{", "a", ".", "Modified", "=", "other", ".", "Modified", "\n", "}", "\n", "a", ".", "NumExecutions", "=", "other", ".", "NumExecutions", "\n", "if", "other", ".", "AttemptType", "!=", "nil", "{", "a", ".", "AttemptType", "=", "other", ".", "AttemptType", "\n", "}", "\n", "}" ]
// UpdateWith updates this Attempt_Data with data from other.
[ "UpdateWith", "updates", "this", "Attempt_Data", "with", "data", "from", "other", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_data_update.go#L101-L112
7,444
luci/luci-go
dm/api/service/v1/graph_data_update.go
UpdateWith
func (e *Execution) UpdateWith(other *Execution) { if e.Id == nil { e.Id = other.Id } if e.Data == nil { e.Data = other.Data e.Partial = false } else if !other.Partial { e.Data.UpdateWith(other.Data) e.Partial = false } }
go
func (e *Execution) UpdateWith(other *Execution) { if e.Id == nil { e.Id = other.Id } if e.Data == nil { e.Data = other.Data e.Partial = false } else if !other.Partial { e.Data.UpdateWith(other.Data) e.Partial = false } }
[ "func", "(", "e", "*", "Execution", ")", "UpdateWith", "(", "other", "*", "Execution", ")", "{", "if", "e", ".", "Id", "==", "nil", "{", "e", ".", "Id", "=", "other", ".", "Id", "\n", "}", "\n", "if", "e", ".", "Data", "==", "nil", "{", "e", ".", "Data", "=", "other", ".", "Data", "\n", "e", ".", "Partial", "=", "false", "\n", "}", "else", "if", "!", "other", ".", "Partial", "{", "e", ".", "Data", ".", "UpdateWith", "(", "other", ".", "Data", ")", "\n", "e", ".", "Partial", "=", "false", "\n", "}", "\n", "}" ]
// UpdateWith updates this Execution with data from other.
[ "UpdateWith", "updates", "this", "Execution", "with", "data", "from", "other", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_data_update.go#L115-L126
7,445
luci/luci-go
dm/api/service/v1/graph_data_update.go
UpdateWith
func (e *Execution_Data) UpdateWith(other *Execution_Data) { if e.Created == nil { e.Created = other.Created } if other.Modified != nil { e.Modified = other.Modified } if other.DistributorInfo != nil { e.DistributorInfo = other.DistributorInfo } if other.ExecutionType != nil { e.ExecutionType = other.ExecutionType } }
go
func (e *Execution_Data) UpdateWith(other *Execution_Data) { if e.Created == nil { e.Created = other.Created } if other.Modified != nil { e.Modified = other.Modified } if other.DistributorInfo != nil { e.DistributorInfo = other.DistributorInfo } if other.ExecutionType != nil { e.ExecutionType = other.ExecutionType } }
[ "func", "(", "e", "*", "Execution_Data", ")", "UpdateWith", "(", "other", "*", "Execution_Data", ")", "{", "if", "e", ".", "Created", "==", "nil", "{", "e", ".", "Created", "=", "other", ".", "Created", "\n", "}", "\n", "if", "other", ".", "Modified", "!=", "nil", "{", "e", ".", "Modified", "=", "other", ".", "Modified", "\n", "}", "\n", "if", "other", ".", "DistributorInfo", "!=", "nil", "{", "e", ".", "DistributorInfo", "=", "other", ".", "DistributorInfo", "\n", "}", "\n", "if", "other", ".", "ExecutionType", "!=", "nil", "{", "e", ".", "ExecutionType", "=", "other", ".", "ExecutionType", "\n", "}", "\n", "}" ]
// UpdateWith updates this Execution_Data with data from other.
[ "UpdateWith", "updates", "this", "Execution_Data", "with", "data", "from", "other", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_data_update.go#L129-L142
7,446
luci/luci-go
tumble/fire_tasks.go
nsToTaskName
func nsToTaskName(v string) string { // Escape single underscores in the namespace name. v = strings.Replace(v, "_", "__", -1) // Replace any invalid task queue name characters with underscore. return strings.Map(func(r rune) rune { switch { case (r >= 'a' && r <= 'z'), (r >= 'A' && r <= 'Z'), r == '_', r == '-': return r default: return '_' } }, v) }
go
func nsToTaskName(v string) string { // Escape single underscores in the namespace name. v = strings.Replace(v, "_", "__", -1) // Replace any invalid task queue name characters with underscore. return strings.Map(func(r rune) rune { switch { case (r >= 'a' && r <= 'z'), (r >= 'A' && r <= 'Z'), r == '_', r == '-': return r default: return '_' } }, v) }
[ "func", "nsToTaskName", "(", "v", "string", ")", "string", "{", "// Escape single underscores in the namespace name.", "v", "=", "strings", ".", "Replace", "(", "v", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n\n", "// Replace any invalid task queue name characters with underscore.", "return", "strings", ".", "Map", "(", "func", "(", "r", "rune", ")", "rune", "{", "switch", "{", "case", "(", "r", ">=", "'a'", "&&", "r", "<=", "'z'", ")", ",", "(", "r", ">=", "'A'", "&&", "r", "<=", "'Z'", ")", ",", "r", "==", "'_'", ",", "r", "==", "'-'", ":", "return", "r", "\n", "default", ":", "return", "'_'", "\n", "}", "\n", "}", ",", "v", ")", "\n", "}" ]
// nsToTaskName flattens a namespace into a string that can be part of a valid // task queue task name.
[ "nsToTaskName", "flattens", "a", "namespace", "into", "a", "string", "that", "can", "be", "part", "of", "a", "valid", "task", "queue", "task", "name", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tumble/fire_tasks.go#L105-L120
7,447
luci/luci-go
common/isolatedclient/isolatedfake/isolatedfake.go
handlerJSON
func handlerJSON(f failure, handler jsonAPI) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //log.Printf("%s", r.URL) if r.Header.Get("Content-Type") != contentType { f.Fail(fmt.Errorf("invalid content type: %q", r.Header.Get("Content-Type"))) return } defer r.Body.Close() out := handler(r) w.Header().Set("Content-Type", contentType) j := json.NewEncoder(w) if err := j.Encode(out); err != nil { f.Fail(err) } }) }
go
func handlerJSON(f failure, handler jsonAPI) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //log.Printf("%s", r.URL) if r.Header.Get("Content-Type") != contentType { f.Fail(fmt.Errorf("invalid content type: %q", r.Header.Get("Content-Type"))) return } defer r.Body.Close() out := handler(r) w.Header().Set("Content-Type", contentType) j := json.NewEncoder(w) if err := j.Encode(out); err != nil { f.Fail(err) } }) }
[ "func", "handlerJSON", "(", "f", "failure", ",", "handler", "jsonAPI", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "//log.Printf(\"%s\", r.URL)", "if", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "!=", "contentType", "{", "f", ".", "Fail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", ")", "\n", "return", "\n", "}", "\n", "defer", "r", ".", "Body", ".", "Close", "(", ")", "\n", "out", ":=", "handler", "(", "r", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "contentType", ")", "\n", "j", ":=", "json", ".", "NewEncoder", "(", "w", ")", "\n", "if", "err", ":=", "j", ".", "Encode", "(", "out", ")", ";", "err", "!=", "nil", "{", "f", ".", "Fail", "(", "err", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// handlerJSON converts a jsonAPI http handler to a proper http.Handler.
[ "handlerJSON", "converts", "a", "jsonAPI", "http", "handler", "to", "a", "proper", "http", ".", "Handler", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolatedclient/isolatedfake/isolatedfake.go#L44-L59
7,448
luci/luci-go
common/isolatedclient/isolatedfake/isolatedfake.go
New
func New() IsolatedFake { s := &isolatedFake{ mux: http.NewServeMux(), contents: map[string]map[isolated.HexDigest][]byte{}, staging: map[string]map[isolated.HexDigest][]byte{}, } s.handleJSON("/_ah/api/isolateservice/v1/server_details", s.serverDetails) s.handleJSON("/_ah/api/isolateservice/v1/preupload", s.preupload) s.handleJSON("/_ah/api/isolateservice/v1/finalize_gs_upload", s.finalizeGSUpload) s.handleJSON("/_ah/api/isolateservice/v1/store_inline", s.storeInline) s.handleJSON("/_ah/api/isolateservice/v1/retrieve", s.retrieve) s.mux.HandleFunc("/fake/cloudstorage/upload", s.fakeCloudStorageUpload) s.mux.HandleFunc("/fake/cloudstorage/download", s.fakeCloudStorageDownload) // Fail on anything else. s.mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { s.Fail(fmt.Errorf("unknown endpoint %q", req.URL)) }) return s }
go
func New() IsolatedFake { s := &isolatedFake{ mux: http.NewServeMux(), contents: map[string]map[isolated.HexDigest][]byte{}, staging: map[string]map[isolated.HexDigest][]byte{}, } s.handleJSON("/_ah/api/isolateservice/v1/server_details", s.serverDetails) s.handleJSON("/_ah/api/isolateservice/v1/preupload", s.preupload) s.handleJSON("/_ah/api/isolateservice/v1/finalize_gs_upload", s.finalizeGSUpload) s.handleJSON("/_ah/api/isolateservice/v1/store_inline", s.storeInline) s.handleJSON("/_ah/api/isolateservice/v1/retrieve", s.retrieve) s.mux.HandleFunc("/fake/cloudstorage/upload", s.fakeCloudStorageUpload) s.mux.HandleFunc("/fake/cloudstorage/download", s.fakeCloudStorageDownload) // Fail on anything else. s.mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { s.Fail(fmt.Errorf("unknown endpoint %q", req.URL)) }) return s }
[ "func", "New", "(", ")", "IsolatedFake", "{", "s", ":=", "&", "isolatedFake", "{", "mux", ":", "http", ".", "NewServeMux", "(", ")", ",", "contents", ":", "map", "[", "string", "]", "map", "[", "isolated", ".", "HexDigest", "]", "[", "]", "byte", "{", "}", ",", "staging", ":", "map", "[", "string", "]", "map", "[", "isolated", ".", "HexDigest", "]", "[", "]", "byte", "{", "}", ",", "}", "\n\n", "s", ".", "handleJSON", "(", "\"", "\"", ",", "s", ".", "serverDetails", ")", "\n", "s", ".", "handleJSON", "(", "\"", "\"", ",", "s", ".", "preupload", ")", "\n", "s", ".", "handleJSON", "(", "\"", "\"", ",", "s", ".", "finalizeGSUpload", ")", "\n", "s", ".", "handleJSON", "(", "\"", "\"", ",", "s", ".", "storeInline", ")", "\n", "s", ".", "handleJSON", "(", "\"", "\"", ",", "s", ".", "retrieve", ")", "\n", "s", ".", "mux", ".", "HandleFunc", "(", "\"", "\"", ",", "s", ".", "fakeCloudStorageUpload", ")", "\n", "s", ".", "mux", ".", "HandleFunc", "(", "\"", "\"", ",", "s", ".", "fakeCloudStorageDownload", ")", "\n\n", "// Fail on anything else.", "s", ".", "mux", ".", "HandleFunc", "(", "\"", "\"", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "s", ".", "Fail", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "URL", ")", ")", "\n", "}", ")", "\n", "return", "s", "\n", "}" ]
// New create a HTTP router that implements an isolated server.
[ "New", "create", "a", "HTTP", "router", "that", "implements", "an", "isolated", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolatedclient/isolatedfake/isolatedfake.go#L90-L110
7,449
luci/luci-go
dm/appengine/distributor/jobsim/distributor.go
AddFactory
func AddFactory(m distributor.FactoryMap) { m[(*jobsim.Config)(nil)] = func(c context.Context, cfg *distributor.Config) (distributor.D, error) { return &jobsimDist{c, cfg}, nil } }
go
func AddFactory(m distributor.FactoryMap) { m[(*jobsim.Config)(nil)] = func(c context.Context, cfg *distributor.Config) (distributor.D, error) { return &jobsimDist{c, cfg}, nil } }
[ "func", "AddFactory", "(", "m", "distributor", ".", "FactoryMap", ")", "{", "m", "[", "(", "*", "jobsim", ".", "Config", ")", "(", "nil", ")", "]", "=", "func", "(", "c", "context", ".", "Context", ",", "cfg", "*", "distributor", ".", "Config", ")", "(", "distributor", ".", "D", ",", "error", ")", "{", "return", "&", "jobsimDist", "{", "c", ",", "cfg", "}", ",", "nil", "\n", "}", "\n", "}" ]
// AddFactory adds this distributor implementation into the distributor // Registry.
[ "AddFactory", "adds", "this", "distributor", "implementation", "into", "the", "distributor", "Registry", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/jobsim/distributor.go#L245-L249
7,450
luci/luci-go
logdog/client/butler/output/directory/stream.go
ingestBundleEntry
func (s *stream) ingestBundleEntry(be *logpb.ButlerLogBundle_Entry) (closed bool, err error) { for _, le := range be.GetLogs() { curFile, err := s.getCurFile() if err != nil { return false, err } switch x := le.Content.(type) { case *logpb.LogEntry_Datagram: dg := x.Datagram _, err = s.curFile.Write(dg.Data) if err == nil { if dg.Partial == nil || dg.Partial.Last { s.closeCurFile() } } case *logpb.LogEntry_Text: for _, line := range x.Text.Lines { _, err = curFile.Write(line.Value) if err == nil { _, err = curFile.WriteString("\n") } } case *logpb.LogEntry_Binary: _, err = curFile.Write(x.Binary.Data) } if err != nil { return false, err } } if be.Terminal { s.Close() return true, nil } return false, nil }
go
func (s *stream) ingestBundleEntry(be *logpb.ButlerLogBundle_Entry) (closed bool, err error) { for _, le := range be.GetLogs() { curFile, err := s.getCurFile() if err != nil { return false, err } switch x := le.Content.(type) { case *logpb.LogEntry_Datagram: dg := x.Datagram _, err = s.curFile.Write(dg.Data) if err == nil { if dg.Partial == nil || dg.Partial.Last { s.closeCurFile() } } case *logpb.LogEntry_Text: for _, line := range x.Text.Lines { _, err = curFile.Write(line.Value) if err == nil { _, err = curFile.WriteString("\n") } } case *logpb.LogEntry_Binary: _, err = curFile.Write(x.Binary.Data) } if err != nil { return false, err } } if be.Terminal { s.Close() return true, nil } return false, nil }
[ "func", "(", "s", "*", "stream", ")", "ingestBundleEntry", "(", "be", "*", "logpb", ".", "ButlerLogBundle_Entry", ")", "(", "closed", "bool", ",", "err", "error", ")", "{", "for", "_", ",", "le", ":=", "range", "be", ".", "GetLogs", "(", ")", "{", "curFile", ",", "err", ":=", "s", ".", "getCurFile", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "switch", "x", ":=", "le", ".", "Content", ".", "(", "type", ")", "{", "case", "*", "logpb", ".", "LogEntry_Datagram", ":", "dg", ":=", "x", ".", "Datagram", "\n", "_", ",", "err", "=", "s", ".", "curFile", ".", "Write", "(", "dg", ".", "Data", ")", "\n", "if", "err", "==", "nil", "{", "if", "dg", ".", "Partial", "==", "nil", "||", "dg", ".", "Partial", ".", "Last", "{", "s", ".", "closeCurFile", "(", ")", "\n", "}", "\n", "}", "\n", "case", "*", "logpb", ".", "LogEntry_Text", ":", "for", "_", ",", "line", ":=", "range", "x", ".", "Text", ".", "Lines", "{", "_", ",", "err", "=", "curFile", ".", "Write", "(", "line", ".", "Value", ")", "\n", "if", "err", "==", "nil", "{", "_", ",", "err", "=", "curFile", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "}", "\n", "case", "*", "logpb", ".", "LogEntry_Binary", ":", "_", ",", "err", "=", "curFile", ".", "Write", "(", "x", ".", "Binary", ".", "Data", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "}", "\n", "if", "be", ".", "Terminal", "{", "s", ".", "Close", "(", ")", "\n", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// ingestBundleEntry writes the data from `be` to disk // // Returns closed == true if `be` was terminal and the stream can be closed now.
[ "ingestBundleEntry", "writes", "the", "data", "from", "be", "to", "disk", "Returns", "closed", "==", "true", "if", "be", "was", "terminal", "and", "the", "stream", "can", "be", "closed", "now", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/output/directory/stream.go#L98-L134
7,451
luci/luci-go
common/api/buildbucket/buildbucket/v1/address.go
ParseBuildAddress
func ParseBuildAddress(address string) (id int64, project, bucket, builder string, number int, err error) { parts := strings.Split(address, "/") switch len(parts) { case 3: var numberStr string bucket, builder, numberStr = parts[0], parts[1], parts[2] project = ProjectFromBucket(bucket) number, err = strconv.Atoi(numberStr) case 1: id, err = strconv.ParseInt(parts[0], 10, 64) default: err = fmt.Errorf("unrecognized build address format %q", address) } return }
go
func ParseBuildAddress(address string) (id int64, project, bucket, builder string, number int, err error) { parts := strings.Split(address, "/") switch len(parts) { case 3: var numberStr string bucket, builder, numberStr = parts[0], parts[1], parts[2] project = ProjectFromBucket(bucket) number, err = strconv.Atoi(numberStr) case 1: id, err = strconv.ParseInt(parts[0], 10, 64) default: err = fmt.Errorf("unrecognized build address format %q", address) } return }
[ "func", "ParseBuildAddress", "(", "address", "string", ")", "(", "id", "int64", ",", "project", ",", "bucket", ",", "builder", "string", ",", "number", "int", ",", "err", "error", ")", "{", "parts", ":=", "strings", ".", "Split", "(", "address", ",", "\"", "\"", ")", "\n", "switch", "len", "(", "parts", ")", "{", "case", "3", ":", "var", "numberStr", "string", "\n", "bucket", ",", "builder", ",", "numberStr", "=", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", ",", "parts", "[", "2", "]", "\n", "project", "=", "ProjectFromBucket", "(", "bucket", ")", "\n", "number", ",", "err", "=", "strconv", ".", "Atoi", "(", "numberStr", ")", "\n", "case", "1", ":", "id", ",", "err", "=", "strconv", ".", "ParseInt", "(", "parts", "[", "0", "]", ",", "10", ",", "64", ")", "\n", "default", ":", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "address", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ParseBuildAddress parses a value of a TagBuildAddress tag. // See also FormatBuildAddress. // // If id is non-zero, project, bucket and builder are zero. // If bucket is non-zero, id is zero.
[ "ParseBuildAddress", "parses", "a", "value", "of", "a", "TagBuildAddress", "tag", ".", "See", "also", "FormatBuildAddress", ".", "If", "id", "is", "non", "-", "zero", "project", "bucket", "and", "builder", "are", "zero", ".", "If", "bucket", "is", "non", "-", "zero", "id", "is", "zero", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/buildbucket/buildbucket/v1/address.go#L44-L58
7,452
luci/luci-go
common/api/buildbucket/buildbucket/v1/address.go
ValidateBuildAddress
func ValidateBuildAddress(address string) error { _, _, _, _, _, err := ParseBuildAddress(address) return err }
go
func ValidateBuildAddress(address string) error { _, _, _, _, _, err := ParseBuildAddress(address) return err }
[ "func", "ValidateBuildAddress", "(", "address", "string", ")", "error", "{", "_", ",", "_", ",", "_", ",", "_", ",", "_", ",", "err", ":=", "ParseBuildAddress", "(", "address", ")", "\n", "return", "err", "\n", "}" ]
// ValidateBuildAddress returns an error if the build address is invalid.
[ "ValidateBuildAddress", "returns", "an", "error", "if", "the", "build", "address", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/buildbucket/buildbucket/v1/address.go#L61-L64
7,453
luci/luci-go
common/api/buildbucket/buildbucket/v1/address.go
ProjectFromBucket
func ProjectFromBucket(bucket string) string { // Buildbucket guarantees that buckets that start with "luci." // have "luci.<project id>." prefix. parts := strings.Split(bucket, ".") if len(parts) >= 3 && parts[0] == "luci" { return parts[1] } return "" }
go
func ProjectFromBucket(bucket string) string { // Buildbucket guarantees that buckets that start with "luci." // have "luci.<project id>." prefix. parts := strings.Split(bucket, ".") if len(parts) >= 3 && parts[0] == "luci" { return parts[1] } return "" }
[ "func", "ProjectFromBucket", "(", "bucket", "string", ")", "string", "{", "// Buildbucket guarantees that buckets that start with \"luci.\"", "// have \"luci.<project id>.\" prefix.", "parts", ":=", "strings", ".", "Split", "(", "bucket", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", ">=", "3", "&&", "parts", "[", "0", "]", "==", "\"", "\"", "{", "return", "parts", "[", "1", "]", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// ProjectFromBucket tries to retrieve project id from bucket name. // Returns "" on failure.
[ "ProjectFromBucket", "tries", "to", "retrieve", "project", "id", "from", "bucket", "name", ".", "Returns", "on", "failure", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/buildbucket/buildbucket/v1/address.go#L103-L111
7,454
luci/luci-go
scheduler/appengine/ui/errors.go
render
func (e *presentableError) render(c *router.Context) { breadcrumps := []string{} for _, k := range []string{"ProjectID", "JobName", "InvID"} { p := c.Params.ByName(k) if p == "" { break } breadcrumps = append(breadcrumps, p) } c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8") c.Writer.WriteHeader(e.Status) templates.MustRender(c.Context, c.Writer, "pages/error.html", map[string]interface{}{ "Breadcrumps": breadcrumps, "LastCrumbIdx": len(breadcrumps) - 1, "Message": e.Message, "ReloginMayHelp": e.ReloginMayHelp, }) }
go
func (e *presentableError) render(c *router.Context) { breadcrumps := []string{} for _, k := range []string{"ProjectID", "JobName", "InvID"} { p := c.Params.ByName(k) if p == "" { break } breadcrumps = append(breadcrumps, p) } c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8") c.Writer.WriteHeader(e.Status) templates.MustRender(c.Context, c.Writer, "pages/error.html", map[string]interface{}{ "Breadcrumps": breadcrumps, "LastCrumbIdx": len(breadcrumps) - 1, "Message": e.Message, "ReloginMayHelp": e.ReloginMayHelp, }) }
[ "func", "(", "e", "*", "presentableError", ")", "render", "(", "c", "*", "router", ".", "Context", ")", "{", "breadcrumps", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "k", ":=", "range", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "{", "p", ":=", "c", ".", "Params", ".", "ByName", "(", "k", ")", "\n", "if", "p", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "breadcrumps", "=", "append", "(", "breadcrumps", ",", "p", ")", "\n", "}", "\n", "c", ".", "Writer", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Writer", ".", "WriteHeader", "(", "e", ".", "Status", ")", "\n", "templates", ".", "MustRender", "(", "c", ".", "Context", ",", "c", ".", "Writer", ",", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "breadcrumps", ",", "\"", "\"", ":", "len", "(", "breadcrumps", ")", "-", "1", ",", "\"", "\"", ":", "e", ".", "Message", ",", "\"", "\"", ":", "e", ".", "ReloginMayHelp", ",", "}", ")", "\n", "}" ]
// render renders the HTML into the writer and sets the response code.
[ "render", "renders", "the", "HTML", "into", "the", "writer", "and", "sets", "the", "response", "code", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/ui/errors.go#L67-L84
7,455
luci/luci-go
grpc/prpc/encoding.go
writeMessage
func writeMessage(c context.Context, w http.ResponseWriter, msg proto.Message, format Format) { if msg == nil { panic("msg is nil") } var body []byte var err error switch format { case FormatBinary: body, err = proto.Marshal(msg) case FormatJSONPB: var buf bytes.Buffer buf.WriteString(JSONPBPrefix) m := jsonpb.Marshaler{} err = m.Marshal(&buf, msg) if err == nil { _, err = buf.WriteRune('\n') } body = buf.Bytes() case FormatText: var buf bytes.Buffer err = proto.MarshalText(&buf, msg) body = buf.Bytes() default: panic(fmt.Errorf("impossible: invalid format %d", format)) } if err != nil { writeError(c, w, withCode(err, codes.Internal)) return } w.Header().Set(HeaderGRPCCode, strconv.Itoa(int(codes.OK))) w.Header().Set(headerContentType, format.MediaType()) w.Header().Set("X-Content-Type-Options", "nosniff") if _, err := w.Write(body); err != nil { logging.WithError(err).Errorf(c, "prpc: failed to write response body") } }
go
func writeMessage(c context.Context, w http.ResponseWriter, msg proto.Message, format Format) { if msg == nil { panic("msg is nil") } var body []byte var err error switch format { case FormatBinary: body, err = proto.Marshal(msg) case FormatJSONPB: var buf bytes.Buffer buf.WriteString(JSONPBPrefix) m := jsonpb.Marshaler{} err = m.Marshal(&buf, msg) if err == nil { _, err = buf.WriteRune('\n') } body = buf.Bytes() case FormatText: var buf bytes.Buffer err = proto.MarshalText(&buf, msg) body = buf.Bytes() default: panic(fmt.Errorf("impossible: invalid format %d", format)) } if err != nil { writeError(c, w, withCode(err, codes.Internal)) return } w.Header().Set(HeaderGRPCCode, strconv.Itoa(int(codes.OK))) w.Header().Set(headerContentType, format.MediaType()) w.Header().Set("X-Content-Type-Options", "nosniff") if _, err := w.Write(body); err != nil { logging.WithError(err).Errorf(c, "prpc: failed to write response body") } }
[ "func", "writeMessage", "(", "c", "context", ".", "Context", ",", "w", "http", ".", "ResponseWriter", ",", "msg", "proto", ".", "Message", ",", "format", "Format", ")", "{", "if", "msg", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "body", "[", "]", "byte", "\n", "var", "err", "error", "\n", "switch", "format", "{", "case", "FormatBinary", ":", "body", ",", "err", "=", "proto", ".", "Marshal", "(", "msg", ")", "\n\n", "case", "FormatJSONPB", ":", "var", "buf", "bytes", ".", "Buffer", "\n", "buf", ".", "WriteString", "(", "JSONPBPrefix", ")", "\n", "m", ":=", "jsonpb", ".", "Marshaler", "{", "}", "\n", "err", "=", "m", ".", "Marshal", "(", "&", "buf", ",", "msg", ")", "\n", "if", "err", "==", "nil", "{", "_", ",", "err", "=", "buf", ".", "WriteRune", "(", "'\\n'", ")", "\n", "}", "\n", "body", "=", "buf", ".", "Bytes", "(", ")", "\n\n", "case", "FormatText", ":", "var", "buf", "bytes", ".", "Buffer", "\n", "err", "=", "proto", ".", "MarshalText", "(", "&", "buf", ",", "msg", ")", "\n", "body", "=", "buf", ".", "Bytes", "(", ")", "\n\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "format", ")", ")", "\n\n", "}", "\n", "if", "err", "!=", "nil", "{", "writeError", "(", "c", ",", "w", ",", "withCode", "(", "err", ",", "codes", ".", "Internal", ")", ")", "\n", "return", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "HeaderGRPCCode", ",", "strconv", ".", "Itoa", "(", "int", "(", "codes", ".", "OK", ")", ")", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "headerContentType", ",", "format", ".", "MediaType", "(", ")", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "body", ")", ";", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// writeMessage writes msg to w in the specified format. // c is used to log errors. // panics if msg is nil.
[ "writeMessage", "writes", "msg", "to", "w", "in", "the", "specified", "format", ".", "c", "is", "used", "to", "log", "errors", ".", "panics", "if", "msg", "is", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/encoding.go#L82-L123
7,456
luci/luci-go
grpc/prpc/encoding.go
errorCode
func errorCode(err error) codes.Code { switch errors.Unwrap(err) { case context.DeadlineExceeded: return codes.DeadlineExceeded case context.Canceled: return codes.Canceled default: return grpc.Code(err) } }
go
func errorCode(err error) codes.Code { switch errors.Unwrap(err) { case context.DeadlineExceeded: return codes.DeadlineExceeded case context.Canceled: return codes.Canceled default: return grpc.Code(err) } }
[ "func", "errorCode", "(", "err", "error", ")", "codes", ".", "Code", "{", "switch", "errors", ".", "Unwrap", "(", "err", ")", "{", "case", "context", ".", "DeadlineExceeded", ":", "return", "codes", ".", "DeadlineExceeded", "\n\n", "case", "context", ".", "Canceled", ":", "return", "codes", ".", "Canceled", "\n\n", "default", ":", "return", "grpc", ".", "Code", "(", "err", ")", "\n", "}", "\n", "}" ]
// errorCode returns a most appropriate gRPC code for an error
[ "errorCode", "returns", "a", "most", "appropriate", "gRPC", "code", "for", "an", "error" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/encoding.go#L126-L137
7,457
luci/luci-go
grpc/prpc/encoding.go
writeError
func writeError(c context.Context, w http.ResponseWriter, err error) { var code codes.Code var httpStatus int var msg string if perr, ok := err.(*protocolError); ok { code = codes.InvalidArgument msg = perr.err.Error() httpStatus = perr.status } else { code = errorCode(err) msg = grpc.ErrorDesc(err) httpStatus = grpcutil.CodeStatus(code) } body := msg level := logging.Warning if httpStatus >= 500 { level = logging.Error // Hide potential implementation details from the user. body = http.StatusText(httpStatus) } logging.Logf(c, level, "prpc: responding with %s error: %s", code, msg) w.Header().Set(HeaderGRPCCode, strconv.Itoa(int(code))) w.Header().Set(headerContentType, "text/plain") w.WriteHeader(httpStatus) if _, err := io.WriteString(w, body); err != nil { logging.WithError(err).Errorf(c, "prpc: failed to write response body") // The header is already written. There is nothing more we can do. return } io.WriteString(w, "\n") }
go
func writeError(c context.Context, w http.ResponseWriter, err error) { var code codes.Code var httpStatus int var msg string if perr, ok := err.(*protocolError); ok { code = codes.InvalidArgument msg = perr.err.Error() httpStatus = perr.status } else { code = errorCode(err) msg = grpc.ErrorDesc(err) httpStatus = grpcutil.CodeStatus(code) } body := msg level := logging.Warning if httpStatus >= 500 { level = logging.Error // Hide potential implementation details from the user. body = http.StatusText(httpStatus) } logging.Logf(c, level, "prpc: responding with %s error: %s", code, msg) w.Header().Set(HeaderGRPCCode, strconv.Itoa(int(code))) w.Header().Set(headerContentType, "text/plain") w.WriteHeader(httpStatus) if _, err := io.WriteString(w, body); err != nil { logging.WithError(err).Errorf(c, "prpc: failed to write response body") // The header is already written. There is nothing more we can do. return } io.WriteString(w, "\n") }
[ "func", "writeError", "(", "c", "context", ".", "Context", ",", "w", "http", ".", "ResponseWriter", ",", "err", "error", ")", "{", "var", "code", "codes", ".", "Code", "\n", "var", "httpStatus", "int", "\n", "var", "msg", "string", "\n", "if", "perr", ",", "ok", ":=", "err", ".", "(", "*", "protocolError", ")", ";", "ok", "{", "code", "=", "codes", ".", "InvalidArgument", "\n", "msg", "=", "perr", ".", "err", ".", "Error", "(", ")", "\n", "httpStatus", "=", "perr", ".", "status", "\n", "}", "else", "{", "code", "=", "errorCode", "(", "err", ")", "\n", "msg", "=", "grpc", ".", "ErrorDesc", "(", "err", ")", "\n", "httpStatus", "=", "grpcutil", ".", "CodeStatus", "(", "code", ")", "\n", "}", "\n\n", "body", ":=", "msg", "\n", "level", ":=", "logging", ".", "Warning", "\n", "if", "httpStatus", ">=", "500", "{", "level", "=", "logging", ".", "Error", "\n", "// Hide potential implementation details from the user.", "body", "=", "http", ".", "StatusText", "(", "httpStatus", ")", "\n", "}", "\n", "logging", ".", "Logf", "(", "c", ",", "level", ",", "\"", "\"", ",", "code", ",", "msg", ")", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "HeaderGRPCCode", ",", "strconv", ".", "Itoa", "(", "int", "(", "code", ")", ")", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "headerContentType", ",", "\"", "\"", ")", "\n", "w", ".", "WriteHeader", "(", "httpStatus", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "WriteString", "(", "w", ",", "body", ")", ";", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "// The header is already written. There is nothing more we can do.", "return", "\n", "}", "\n", "io", ".", "WriteString", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// writeError writes err to w and logs it.
[ "writeError", "writes", "err", "to", "w", "and", "logs", "it", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/encoding.go#L140-L172
7,458
luci/luci-go
machine-db/appengine/ui/common.go
server
func server(c context.Context) crimson.CrimsonServer { s, _ := c.Value(&serverKey).(crimson.CrimsonServer) if s == nil { panic("impossible, &serverKey is not set") } return s }
go
func server(c context.Context) crimson.CrimsonServer { s, _ := c.Value(&serverKey).(crimson.CrimsonServer) if s == nil { panic("impossible, &serverKey is not set") } return s }
[ "func", "server", "(", "c", "context", ".", "Context", ")", "crimson", ".", "CrimsonServer", "{", "s", ",", "_", ":=", "c", ".", "Value", "(", "&", "serverKey", ")", ".", "(", "crimson", ".", "CrimsonServer", ")", "\n", "if", "s", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// server returns crimson.CrimsonServer as passed to InstallHandlers. // // It is used to pull all data necessary to render pages.
[ "server", "returns", "crimson", ".", "CrimsonServer", "as", "passed", "to", "InstallHandlers", ".", "It", "is", "used", "to", "pull", "all", "data", "necessary", "to", "render", "pages", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/ui/common.go#L103-L109
7,459
luci/luci-go
machine-db/appengine/ui/common.go
renderErr
func renderErr(c *router.Context, err error) { status := grpcCodeToHTTP[grpc.Code(err)] if status == 0 { status = http.StatusInternalServerError } c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8") c.Writer.WriteHeader(status) templates.MustRender(c.Context, c.Writer, "pages/error.html", map[string]interface{}{ "Message": err.Error(), }) }
go
func renderErr(c *router.Context, err error) { status := grpcCodeToHTTP[grpc.Code(err)] if status == 0 { status = http.StatusInternalServerError } c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8") c.Writer.WriteHeader(status) templates.MustRender(c.Context, c.Writer, "pages/error.html", map[string]interface{}{ "Message": err.Error(), }) }
[ "func", "renderErr", "(", "c", "*", "router", ".", "Context", ",", "err", "error", ")", "{", "status", ":=", "grpcCodeToHTTP", "[", "grpc", ".", "Code", "(", "err", ")", "]", "\n", "if", "status", "==", "0", "{", "status", "=", "http", ".", "StatusInternalServerError", "\n", "}", "\n", "c", ".", "Writer", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Writer", ".", "WriteHeader", "(", "status", ")", "\n", "templates", ".", "MustRender", "(", "c", ".", "Context", ",", "c", ".", "Writer", ",", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "err", ".", "Error", "(", ")", ",", "}", ")", "\n", "}" ]
// renderErr renders a page with error message.
[ "renderErr", "renders", "a", "page", "with", "error", "message", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/ui/common.go#L124-L134
7,460
luci/luci-go
appengine/gaeauth/server/session.go
OpenSession
func (s *SessionStore) OpenSession(c context.Context, userID string, u *auth.User, exp time.Time) (string, error) { if strings.IndexByte(s.Prefix, '/') != -1 { return "", fmt.Errorf("gaeauth: bad prefix (%q) in SessionStore", s.Prefix) } if strings.IndexByte(userID, '/') != -1 { return "", fmt.Errorf("gaeauth: bad userID (%q), cannot have '/' inside", userID) } if err := u.Identity.Validate(); err != nil { return "", fmt.Errorf("gaeauth: bad identity string (%q) - %s", u.Identity, err) } c = defaultNS(c) now := clock.Now(c).UTC() prof := profile{ Identity: string(u.Identity), Superuser: u.Superuser, Email: u.Email, Name: u.Name, Picture: u.Picture, } // Set in the transaction below. var sessionID string err := ds.RunInTransaction(ds.WithoutTransaction(c), func(c context.Context) error { // Grab existing userEntity or initialize a new one. userEnt := userEntity{ID: s.Prefix + "/" + userID} err := ds.Get(c, &userEnt) if err != nil && err != ds.ErrNoSuchEntity { return err } if err == ds.ErrNoSuchEntity { userEnt.Profile = prof userEnt.Created = now } userEnt.LastLogin = now // Make new session. ID will be generated by the datastore. sessionEnt := sessionEntity{ Parent: ds.KeyForObj(c, &userEnt), Profile: prof, Created: now, Expiration: exp.UTC(), } if err = ds.Put(c, &userEnt, &sessionEnt); err != nil { return err } sessionID = fmt.Sprintf("%s/%s/%d", s.Prefix, userID, sessionEnt.ID) return nil }, nil) if err != nil { return "", transient.Tag.Apply(err) } return sessionID, nil }
go
func (s *SessionStore) OpenSession(c context.Context, userID string, u *auth.User, exp time.Time) (string, error) { if strings.IndexByte(s.Prefix, '/') != -1 { return "", fmt.Errorf("gaeauth: bad prefix (%q) in SessionStore", s.Prefix) } if strings.IndexByte(userID, '/') != -1 { return "", fmt.Errorf("gaeauth: bad userID (%q), cannot have '/' inside", userID) } if err := u.Identity.Validate(); err != nil { return "", fmt.Errorf("gaeauth: bad identity string (%q) - %s", u.Identity, err) } c = defaultNS(c) now := clock.Now(c).UTC() prof := profile{ Identity: string(u.Identity), Superuser: u.Superuser, Email: u.Email, Name: u.Name, Picture: u.Picture, } // Set in the transaction below. var sessionID string err := ds.RunInTransaction(ds.WithoutTransaction(c), func(c context.Context) error { // Grab existing userEntity or initialize a new one. userEnt := userEntity{ID: s.Prefix + "/" + userID} err := ds.Get(c, &userEnt) if err != nil && err != ds.ErrNoSuchEntity { return err } if err == ds.ErrNoSuchEntity { userEnt.Profile = prof userEnt.Created = now } userEnt.LastLogin = now // Make new session. ID will be generated by the datastore. sessionEnt := sessionEntity{ Parent: ds.KeyForObj(c, &userEnt), Profile: prof, Created: now, Expiration: exp.UTC(), } if err = ds.Put(c, &userEnt, &sessionEnt); err != nil { return err } sessionID = fmt.Sprintf("%s/%s/%d", s.Prefix, userID, sessionEnt.ID) return nil }, nil) if err != nil { return "", transient.Tag.Apply(err) } return sessionID, nil }
[ "func", "(", "s", "*", "SessionStore", ")", "OpenSession", "(", "c", "context", ".", "Context", ",", "userID", "string", ",", "u", "*", "auth", ".", "User", ",", "exp", "time", ".", "Time", ")", "(", "string", ",", "error", ")", "{", "if", "strings", ".", "IndexByte", "(", "s", ".", "Prefix", ",", "'/'", ")", "!=", "-", "1", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "Prefix", ")", "\n", "}", "\n", "if", "strings", ".", "IndexByte", "(", "userID", ",", "'/'", ")", "!=", "-", "1", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "userID", ")", "\n", "}", "\n", "if", "err", ":=", "u", ".", "Identity", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ".", "Identity", ",", "err", ")", "\n", "}", "\n", "c", "=", "defaultNS", "(", "c", ")", "\n\n", "now", ":=", "clock", ".", "Now", "(", "c", ")", ".", "UTC", "(", ")", "\n", "prof", ":=", "profile", "{", "Identity", ":", "string", "(", "u", ".", "Identity", ")", ",", "Superuser", ":", "u", ".", "Superuser", ",", "Email", ":", "u", ".", "Email", ",", "Name", ":", "u", ".", "Name", ",", "Picture", ":", "u", ".", "Picture", ",", "}", "\n\n", "// Set in the transaction below.", "var", "sessionID", "string", "\n\n", "err", ":=", "ds", ".", "RunInTransaction", "(", "ds", ".", "WithoutTransaction", "(", "c", ")", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "// Grab existing userEntity or initialize a new one.", "userEnt", ":=", "userEntity", "{", "ID", ":", "s", ".", "Prefix", "+", "\"", "\"", "+", "userID", "}", "\n", "err", ":=", "ds", ".", "Get", "(", "c", ",", "&", "userEnt", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "ds", ".", "ErrNoSuchEntity", "{", "return", "err", "\n", "}", "\n", "if", "err", "==", "ds", ".", "ErrNoSuchEntity", "{", "userEnt", ".", "Profile", "=", "prof", "\n", "userEnt", ".", "Created", "=", "now", "\n", "}", "\n", "userEnt", ".", "LastLogin", "=", "now", "\n\n", "// Make new session. ID will be generated by the datastore.", "sessionEnt", ":=", "sessionEntity", "{", "Parent", ":", "ds", ".", "KeyForObj", "(", "c", ",", "&", "userEnt", ")", ",", "Profile", ":", "prof", ",", "Created", ":", "now", ",", "Expiration", ":", "exp", ".", "UTC", "(", ")", ",", "}", "\n", "if", "err", "=", "ds", ".", "Put", "(", "c", ",", "&", "userEnt", ",", "&", "sessionEnt", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "sessionID", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "Prefix", ",", "userID", ",", "sessionEnt", ".", "ID", ")", "\n", "return", "nil", "\n", "}", ",", "nil", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "return", "sessionID", ",", "nil", "\n", "}" ]
// OpenSession create a new session for a user with given expiration time. // It returns unique session ID.
[ "OpenSession", "create", "a", "new", "session", "for", "a", "user", "with", "given", "expiration", "time", ".", "It", "returns", "unique", "session", "ID", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/session.go#L46-L102
7,461
luci/luci-go
appengine/gaeauth/server/session.go
CloseSession
func (s *SessionStore) CloseSession(c context.Context, sessionID string) error { c = defaultNS(c) ent, err := s.fetchSession(c, sessionID) switch { case err != nil: return err case ent == nil: return nil default: ent.IsClosed = true ent.Closed = clock.Now(c).UTC() return transient.Tag.Apply(ds.Put(ds.WithoutTransaction(c), ent)) } }
go
func (s *SessionStore) CloseSession(c context.Context, sessionID string) error { c = defaultNS(c) ent, err := s.fetchSession(c, sessionID) switch { case err != nil: return err case ent == nil: return nil default: ent.IsClosed = true ent.Closed = clock.Now(c).UTC() return transient.Tag.Apply(ds.Put(ds.WithoutTransaction(c), ent)) } }
[ "func", "(", "s", "*", "SessionStore", ")", "CloseSession", "(", "c", "context", ".", "Context", ",", "sessionID", "string", ")", "error", "{", "c", "=", "defaultNS", "(", "c", ")", "\n", "ent", ",", "err", ":=", "s", ".", "fetchSession", "(", "c", ",", "sessionID", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "err", "\n", "case", "ent", "==", "nil", ":", "return", "nil", "\n", "default", ":", "ent", ".", "IsClosed", "=", "true", "\n", "ent", ".", "Closed", "=", "clock", ".", "Now", "(", "c", ")", ".", "UTC", "(", ")", "\n", "return", "transient", ".", "Tag", ".", "Apply", "(", "ds", ".", "Put", "(", "ds", ".", "WithoutTransaction", "(", "c", ")", ",", "ent", ")", ")", "\n", "}", "\n", "}" ]
// CloseSession closes a session given its ID. Does nothing if session is // already closed or doesn't exist. Returns only transient errors.
[ "CloseSession", "closes", "a", "session", "given", "its", "ID", ".", "Does", "nothing", "if", "session", "is", "already", "closed", "or", "doesn", "t", "exist", ".", "Returns", "only", "transient", "errors", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/session.go#L106-L119
7,462
luci/luci-go
appengine/gaeauth/server/session.go
GetSession
func (s *SessionStore) GetSession(c context.Context, sessionID string) (*auth.Session, error) { c = defaultNS(c) ent, err := s.fetchSession(c, sessionID) if ent == nil { return nil, err } return &auth.Session{ SessionID: sessionID, UserID: ent.Parent.StringID()[len(s.Prefix)+1:], User: auth.User{ Identity: identity.Identity(ent.Profile.Identity), Superuser: ent.Profile.Superuser, Email: ent.Profile.Email, Name: ent.Profile.Name, Picture: ent.Profile.Picture, }, Exp: ent.Expiration, }, nil }
go
func (s *SessionStore) GetSession(c context.Context, sessionID string) (*auth.Session, error) { c = defaultNS(c) ent, err := s.fetchSession(c, sessionID) if ent == nil { return nil, err } return &auth.Session{ SessionID: sessionID, UserID: ent.Parent.StringID()[len(s.Prefix)+1:], User: auth.User{ Identity: identity.Identity(ent.Profile.Identity), Superuser: ent.Profile.Superuser, Email: ent.Profile.Email, Name: ent.Profile.Name, Picture: ent.Profile.Picture, }, Exp: ent.Expiration, }, nil }
[ "func", "(", "s", "*", "SessionStore", ")", "GetSession", "(", "c", "context", ".", "Context", ",", "sessionID", "string", ")", "(", "*", "auth", ".", "Session", ",", "error", ")", "{", "c", "=", "defaultNS", "(", "c", ")", "\n", "ent", ",", "err", ":=", "s", ".", "fetchSession", "(", "c", ",", "sessionID", ")", "\n", "if", "ent", "==", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "auth", ".", "Session", "{", "SessionID", ":", "sessionID", ",", "UserID", ":", "ent", ".", "Parent", ".", "StringID", "(", ")", "[", "len", "(", "s", ".", "Prefix", ")", "+", "1", ":", "]", ",", "User", ":", "auth", ".", "User", "{", "Identity", ":", "identity", ".", "Identity", "(", "ent", ".", "Profile", ".", "Identity", ")", ",", "Superuser", ":", "ent", ".", "Profile", ".", "Superuser", ",", "Email", ":", "ent", ".", "Profile", ".", "Email", ",", "Name", ":", "ent", ".", "Profile", ".", "Name", ",", "Picture", ":", "ent", ".", "Profile", ".", "Picture", ",", "}", ",", "Exp", ":", "ent", ".", "Expiration", ",", "}", ",", "nil", "\n", "}" ]
// GetSession returns existing non-expired session given its ID. Returns nil // if session doesn't exist, closed or expired. Returns only transient errors.
[ "GetSession", "returns", "existing", "non", "-", "expired", "session", "given", "its", "ID", ".", "Returns", "nil", "if", "session", "doesn", "t", "exist", "closed", "or", "expired", ".", "Returns", "only", "transient", "errors", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/session.go#L123-L141
7,463
luci/luci-go
logdog/appengine/coordinator/endpoints/util.go
MinDuration
func MinDuration(candidates ...*duration.Duration) (exp time.Duration) { for _, c := range candidates { if cd := google.DurationFromProto(c); cd > 0 && (exp <= 0 || cd < exp) { exp = cd } } return }
go
func MinDuration(candidates ...*duration.Duration) (exp time.Duration) { for _, c := range candidates { if cd := google.DurationFromProto(c); cd > 0 && (exp <= 0 || cd < exp) { exp = cd } } return }
[ "func", "MinDuration", "(", "candidates", "...", "*", "duration", ".", "Duration", ")", "(", "exp", "time", ".", "Duration", ")", "{", "for", "_", ",", "c", ":=", "range", "candidates", "{", "if", "cd", ":=", "google", ".", "DurationFromProto", "(", "c", ")", ";", "cd", ">", "0", "&&", "(", "exp", "<=", "0", "||", "cd", "<", "exp", ")", "{", "exp", "=", "cd", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// MinDuration selects the smallest duration that is > 0 from a set of // duration.Duration protobufs. // // If none of the supplied Durations are > 0, 0 will be returned.
[ "MinDuration", "selects", "the", "smallest", "duration", "that", "is", ">", "0", "from", "a", "set", "of", "duration", ".", "Duration", "protobufs", ".", "If", "none", "of", "the", "supplied", "Durations", "are", ">", "0", "0", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/util.go#L28-L35
7,464
luci/luci-go
logdog/client/butlerlib/bootstrap/bootstrap.go
GetViewerURL
func (bs *Bootstrap) GetViewerURL(paths ...types.StreamPath) (string, error) { if bs.Project == "" { return "", errors.New("no project is configured") } if bs.CoordinatorHost == "" { return "", errors.New("no coordinator host is configured") } return viewer.GetURL(bs.CoordinatorHost, bs.Project, paths...), nil }
go
func (bs *Bootstrap) GetViewerURL(paths ...types.StreamPath) (string, error) { if bs.Project == "" { return "", errors.New("no project is configured") } if bs.CoordinatorHost == "" { return "", errors.New("no coordinator host is configured") } return viewer.GetURL(bs.CoordinatorHost, bs.Project, paths...), nil }
[ "func", "(", "bs", "*", "Bootstrap", ")", "GetViewerURL", "(", "paths", "...", "types", ".", "StreamPath", ")", "(", "string", ",", "error", ")", "{", "if", "bs", ".", "Project", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "bs", ".", "CoordinatorHost", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "viewer", ".", "GetURL", "(", "bs", ".", "CoordinatorHost", ",", "bs", ".", "Project", ",", "paths", "...", ")", ",", "nil", "\n", "}" ]
// GetViewerURL returns a log stream viewer URL to the aggregate set of supplied // stream paths. // // If both the Project and CoordinatorHost values are not populated, an error // will be returned.
[ "GetViewerURL", "returns", "a", "log", "stream", "viewer", "URL", "to", "the", "aggregate", "set", "of", "supplied", "stream", "paths", ".", "If", "both", "the", "Project", "and", "CoordinatorHost", "values", "are", "not", "populated", "an", "error", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/bootstrap/bootstrap.go#L112-L120
7,465
luci/luci-go
logdog/client/butlerlib/bootstrap/bootstrap.go
GetViewerURLForStreams
func (bs *Bootstrap) GetViewerURLForStreams(streams ...streamclient.Stream) (string, error) { if bs.Prefix == "" { return "", errors.New("no prefix is configured") } paths := make([]types.StreamPath, len(streams)) for i, s := range streams { paths[i] = bs.Prefix.Join(types.StreamName(s.Properties().Name)) } return bs.GetViewerURL(paths...) }
go
func (bs *Bootstrap) GetViewerURLForStreams(streams ...streamclient.Stream) (string, error) { if bs.Prefix == "" { return "", errors.New("no prefix is configured") } paths := make([]types.StreamPath, len(streams)) for i, s := range streams { paths[i] = bs.Prefix.Join(types.StreamName(s.Properties().Name)) } return bs.GetViewerURL(paths...) }
[ "func", "(", "bs", "*", "Bootstrap", ")", "GetViewerURLForStreams", "(", "streams", "...", "streamclient", ".", "Stream", ")", "(", "string", ",", "error", ")", "{", "if", "bs", ".", "Prefix", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "paths", ":=", "make", "(", "[", "]", "types", ".", "StreamPath", ",", "len", "(", "streams", ")", ")", "\n", "for", "i", ",", "s", ":=", "range", "streams", "{", "paths", "[", "i", "]", "=", "bs", ".", "Prefix", ".", "Join", "(", "types", ".", "StreamName", "(", "s", ".", "Properties", "(", ")", ".", "Name", ")", ")", "\n", "}", "\n", "return", "bs", ".", "GetViewerURL", "(", "paths", "...", ")", "\n", "}" ]
// GetViewerURLForStreams returns a log stream viewer URL to the aggregate set // of supplied streams. // // If the any of the Prefix, Project, or CoordinatorHost values is not // populated, an error will be returned.
[ "GetViewerURLForStreams", "returns", "a", "log", "stream", "viewer", "URL", "to", "the", "aggregate", "set", "of", "supplied", "streams", ".", "If", "the", "any", "of", "the", "Prefix", "Project", "or", "CoordinatorHost", "values", "is", "not", "populated", "an", "error", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/bootstrap/bootstrap.go#L127-L137
7,466
luci/luci-go
appengine/gaeauth/server/gaesigner/signer.go
SignBytes
func (Signer) SignBytes(c context.Context, blob []byte) (keyName string, signature []byte, err error) { return info.SignBytes(c, blob) }
go
func (Signer) SignBytes(c context.Context, blob []byte) (keyName string, signature []byte, err error) { return info.SignBytes(c, blob) }
[ "func", "(", "Signer", ")", "SignBytes", "(", "c", "context", ".", "Context", ",", "blob", "[", "]", "byte", ")", "(", "keyName", "string", ",", "signature", "[", "]", "byte", ",", "err", "error", ")", "{", "return", "info", ".", "SignBytes", "(", "c", ",", "blob", ")", "\n", "}" ]
// SignBytes signs the blob with some active private key. // // Returns the signature and name of the key used.
[ "SignBytes", "signs", "the", "blob", "with", "some", "active", "private", "key", ".", "Returns", "the", "signature", "and", "name", "of", "the", "key", "used", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/gaesigner/signer.go#L38-L40
7,467
luci/luci-go
appengine/gaeauth/server/gaesigner/signer.go
Certificates
func (Signer) Certificates(c context.Context) (*signing.PublicCertificates, error) { return getCachedCerts(c) }
go
func (Signer) Certificates(c context.Context) (*signing.PublicCertificates, error) { return getCachedCerts(c) }
[ "func", "(", "Signer", ")", "Certificates", "(", "c", "context", ".", "Context", ")", "(", "*", "signing", ".", "PublicCertificates", ",", "error", ")", "{", "return", "getCachedCerts", "(", "c", ")", "\n", "}" ]
// Certificates returns a bundle with public certificates for all active keys.
[ "Certificates", "returns", "a", "bundle", "with", "public", "certificates", "for", "all", "active", "keys", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/gaesigner/signer.go#L43-L45
7,468
luci/luci-go
appengine/gaeauth/server/gaesigner/signer.go
getCachedCerts
func getCachedCerts(c context.Context) (*signing.PublicCertificates, error) { v, err := certCache.Fetch(c, func(interface{}) (interface{}, time.Duration, error) { aeCerts, err := info.PublicCertificates(c) if err != nil { return nil, 0, err } certs := make([]signing.Certificate, len(aeCerts)) for i, ac := range aeCerts { certs[i] = signing.Certificate{ KeyName: ac.KeyName, X509CertificatePEM: string(ac.Data), } } inf, err := getCachedInfo(c) if err != nil { return nil, 0, err } return &signing.PublicCertificates{ AppID: inf.AppID, ServiceAccountName: inf.ServiceAccountName, Certificates: certs, Timestamp: signing.JSONTime(clock.Now(c)), }, time.Hour, nil }) if err != nil { return nil, err } return v.(*signing.PublicCertificates), nil }
go
func getCachedCerts(c context.Context) (*signing.PublicCertificates, error) { v, err := certCache.Fetch(c, func(interface{}) (interface{}, time.Duration, error) { aeCerts, err := info.PublicCertificates(c) if err != nil { return nil, 0, err } certs := make([]signing.Certificate, len(aeCerts)) for i, ac := range aeCerts { certs[i] = signing.Certificate{ KeyName: ac.KeyName, X509CertificatePEM: string(ac.Data), } } inf, err := getCachedInfo(c) if err != nil { return nil, 0, err } return &signing.PublicCertificates{ AppID: inf.AppID, ServiceAccountName: inf.ServiceAccountName, Certificates: certs, Timestamp: signing.JSONTime(clock.Now(c)), }, time.Hour, nil }) if err != nil { return nil, err } return v.(*signing.PublicCertificates), nil }
[ "func", "getCachedCerts", "(", "c", "context", ".", "Context", ")", "(", "*", "signing", ".", "PublicCertificates", ",", "error", ")", "{", "v", ",", "err", ":=", "certCache", ".", "Fetch", "(", "c", ",", "func", "(", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "time", ".", "Duration", ",", "error", ")", "{", "aeCerts", ",", "err", ":=", "info", ".", "PublicCertificates", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "certs", ":=", "make", "(", "[", "]", "signing", ".", "Certificate", ",", "len", "(", "aeCerts", ")", ")", "\n", "for", "i", ",", "ac", ":=", "range", "aeCerts", "{", "certs", "[", "i", "]", "=", "signing", ".", "Certificate", "{", "KeyName", ":", "ac", ".", "KeyName", ",", "X509CertificatePEM", ":", "string", "(", "ac", ".", "Data", ")", ",", "}", "\n", "}", "\n", "inf", ",", "err", ":=", "getCachedInfo", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "return", "&", "signing", ".", "PublicCertificates", "{", "AppID", ":", "inf", ".", "AppID", ",", "ServiceAccountName", ":", "inf", ".", "ServiceAccountName", ",", "Certificates", ":", "certs", ",", "Timestamp", ":", "signing", ".", "JSONTime", "(", "clock", ".", "Now", "(", "c", ")", ")", ",", "}", ",", "time", ".", "Hour", ",", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "v", ".", "(", "*", "signing", ".", "PublicCertificates", ")", ",", "nil", "\n", "}" ]
// cachedCerts caches this app certs in local memory for 1 hour.
[ "cachedCerts", "caches", "this", "app", "certs", "in", "local", "memory", "for", "1", "hour", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/gaesigner/signer.go#L61-L89
7,469
luci/luci-go
appengine/gaeauth/server/gaesigner/signer.go
getCachedInfo
func getCachedInfo(c context.Context) (*signing.ServiceInfo, error) { v, err := infoCache.Fetch(c, func(interface{}) (interface{}, time.Duration, error) { account, err := info.ServiceAccount(c) if err != nil { return nil, 0, err } return &signing.ServiceInfo{ AppID: info.AppID(c), AppRuntime: "go", AppRuntimeVersion: runtime.Version(), AppVersion: strings.Split(info.VersionID(c), ".")[0], ServiceAccountName: account, }, 0, nil }) if err != nil { return nil, err } return v.(*signing.ServiceInfo), nil }
go
func getCachedInfo(c context.Context) (*signing.ServiceInfo, error) { v, err := infoCache.Fetch(c, func(interface{}) (interface{}, time.Duration, error) { account, err := info.ServiceAccount(c) if err != nil { return nil, 0, err } return &signing.ServiceInfo{ AppID: info.AppID(c), AppRuntime: "go", AppRuntimeVersion: runtime.Version(), AppVersion: strings.Split(info.VersionID(c), ".")[0], ServiceAccountName: account, }, 0, nil }) if err != nil { return nil, err } return v.(*signing.ServiceInfo), nil }
[ "func", "getCachedInfo", "(", "c", "context", ".", "Context", ")", "(", "*", "signing", ".", "ServiceInfo", ",", "error", ")", "{", "v", ",", "err", ":=", "infoCache", ".", "Fetch", "(", "c", ",", "func", "(", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "time", ".", "Duration", ",", "error", ")", "{", "account", ",", "err", ":=", "info", ".", "ServiceAccount", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "return", "&", "signing", ".", "ServiceInfo", "{", "AppID", ":", "info", ".", "AppID", "(", "c", ")", ",", "AppRuntime", ":", "\"", "\"", ",", "AppRuntimeVersion", ":", "runtime", ".", "Version", "(", ")", ",", "AppVersion", ":", "strings", ".", "Split", "(", "info", ".", "VersionID", "(", "c", ")", ",", "\"", "\"", ")", "[", "0", "]", ",", "ServiceAccountName", ":", "account", ",", "}", ",", "0", ",", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "v", ".", "(", "*", "signing", ".", "ServiceInfo", ")", ",", "nil", "\n", "}" ]
// getCachedINfo caches this app service info in local memory forever. // // This info is static during lifetime of the process.
[ "getCachedINfo", "caches", "this", "app", "service", "info", "in", "local", "memory", "forever", ".", "This", "info", "is", "static", "during", "lifetime", "of", "the", "process", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/gaesigner/signer.go#L94-L112
7,470
luci/luci-go
logdog/client/coordinator/fetcher.go
Descriptor
func (s *coordinatorSource) Descriptor() *logpb.LogStreamDescriptor { if s.streamState != nil { return &s.streamState.Desc } return nil }
go
func (s *coordinatorSource) Descriptor() *logpb.LogStreamDescriptor { if s.streamState != nil { return &s.streamState.Desc } return nil }
[ "func", "(", "s", "*", "coordinatorSource", ")", "Descriptor", "(", ")", "*", "logpb", ".", "LogStreamDescriptor", "{", "if", "s", ".", "streamState", "!=", "nil", "{", "return", "&", "s", ".", "streamState", ".", "Desc", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Descriptor returns the LogStreamDescriptor for this stream, if known, // or returns nil.
[ "Descriptor", "returns", "the", "LogStreamDescriptor", "for", "this", "stream", "if", "known", "or", "returns", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/coordinator/fetcher.go#L105-L110
7,471
luci/luci-go
logdog/client/coordinator/fetcher.go
Fetcher
func (s *Stream) Fetcher(c context.Context, o *fetcher.Options) *fetcher.Fetcher { if o == nil { o = &fetcher.Options{} } else { o = &(*o) } o.Source = &coordinatorSource{ stream: s, tidx: -1, requireCompleteStream: o.RequireCompleteStream} return fetcher.New(c, *o) }
go
func (s *Stream) Fetcher(c context.Context, o *fetcher.Options) *fetcher.Fetcher { if o == nil { o = &fetcher.Options{} } else { o = &(*o) } o.Source = &coordinatorSource{ stream: s, tidx: -1, requireCompleteStream: o.RequireCompleteStream} return fetcher.New(c, *o) }
[ "func", "(", "s", "*", "Stream", ")", "Fetcher", "(", "c", "context", ".", "Context", ",", "o", "*", "fetcher", ".", "Options", ")", "*", "fetcher", ".", "Fetcher", "{", "if", "o", "==", "nil", "{", "o", "=", "&", "fetcher", ".", "Options", "{", "}", "\n", "}", "else", "{", "o", "=", "&", "(", "*", "o", ")", "\n", "}", "\n", "o", ".", "Source", "=", "&", "coordinatorSource", "{", "stream", ":", "s", ",", "tidx", ":", "-", "1", ",", "requireCompleteStream", ":", "o", ".", "RequireCompleteStream", "}", "\n", "return", "fetcher", ".", "New", "(", "c", ",", "*", "o", ")", "\n", "}" ]
// Fetcher returns a Fetcher implementation for this Stream. // // If you pass a nil fetcher.Options, a default option set will be used. The // o.Source field will always be overwritten to be based off this stream.
[ "Fetcher", "returns", "a", "Fetcher", "implementation", "for", "this", "Stream", ".", "If", "you", "pass", "a", "nil", "fetcher", ".", "Options", "a", "default", "option", "set", "will", "be", "used", ".", "The", "o", ".", "Source", "field", "will", "always", "be", "overwritten", "to", "be", "based", "off", "this", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/coordinator/fetcher.go#L116-L125
7,472
luci/luci-go
dm/appengine/distributor/tq_handler.go
TaskQueueHandler
func TaskQueueHandler(ctx *router.Context) { c, rw, r, p := ctx.Context, ctx.Writer, ctx.Request, ctx.Params defer r.Body.Close() cfgName := p.ByName("cfgName") dist, _, err := GetRegistry(c).MakeDistributor(c, cfgName) if err != nil { logging.Fields{"error": err, "cfg": cfgName}.Errorf(c, "Failed to make distributor") http.Error(rw, "bad distributor", http.StatusBadRequest) return } notifications, err := dist.HandleTaskQueueTask(r) if err != nil { logging.Fields{"error": err, "cfg": cfgName}.Errorf(c, "Failed to handle taskqueue task") http.Error(rw, "failure to execute handler", http.StatusInternalServerError) return } if len(notifications) > 0 { muts := make([]tumble.Mutation, 0, len(notifications)) for _, notify := range notifications { if notify != nil { muts = append(muts, &NotifyExecution{cfgName, notify}) } } err = tumble.AddToJournal(c, muts...) if err != nil { logging.Fields{"error": err, "cfg": cfgName}.Errorf(c, "Failed to handle notifications") http.Error(rw, "failure to handle notifications", http.StatusInternalServerError) return } } rw.WriteHeader(http.StatusOK) }
go
func TaskQueueHandler(ctx *router.Context) { c, rw, r, p := ctx.Context, ctx.Writer, ctx.Request, ctx.Params defer r.Body.Close() cfgName := p.ByName("cfgName") dist, _, err := GetRegistry(c).MakeDistributor(c, cfgName) if err != nil { logging.Fields{"error": err, "cfg": cfgName}.Errorf(c, "Failed to make distributor") http.Error(rw, "bad distributor", http.StatusBadRequest) return } notifications, err := dist.HandleTaskQueueTask(r) if err != nil { logging.Fields{"error": err, "cfg": cfgName}.Errorf(c, "Failed to handle taskqueue task") http.Error(rw, "failure to execute handler", http.StatusInternalServerError) return } if len(notifications) > 0 { muts := make([]tumble.Mutation, 0, len(notifications)) for _, notify := range notifications { if notify != nil { muts = append(muts, &NotifyExecution{cfgName, notify}) } } err = tumble.AddToJournal(c, muts...) if err != nil { logging.Fields{"error": err, "cfg": cfgName}.Errorf(c, "Failed to handle notifications") http.Error(rw, "failure to handle notifications", http.StatusInternalServerError) return } } rw.WriteHeader(http.StatusOK) }
[ "func", "TaskQueueHandler", "(", "ctx", "*", "router", ".", "Context", ")", "{", "c", ",", "rw", ",", "r", ",", "p", ":=", "ctx", ".", "Context", ",", "ctx", ".", "Writer", ",", "ctx", ".", "Request", ",", "ctx", ".", "Params", "\n", "defer", "r", ".", "Body", ".", "Close", "(", ")", "\n\n", "cfgName", ":=", "p", ".", "ByName", "(", "\"", "\"", ")", "\n", "dist", ",", "_", ",", "err", ":=", "GetRegistry", "(", "c", ")", ".", "MakeDistributor", "(", "c", ",", "cfgName", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Fields", "{", "\"", "\"", ":", "err", ",", "\"", "\"", ":", "cfgName", "}", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "http", ".", "Error", "(", "rw", ",", "\"", "\"", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "notifications", ",", "err", ":=", "dist", ".", "HandleTaskQueueTask", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Fields", "{", "\"", "\"", ":", "err", ",", "\"", "\"", ":", "cfgName", "}", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "http", ".", "Error", "(", "rw", ",", "\"", "\"", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "if", "len", "(", "notifications", ")", ">", "0", "{", "muts", ":=", "make", "(", "[", "]", "tumble", ".", "Mutation", ",", "0", ",", "len", "(", "notifications", ")", ")", "\n", "for", "_", ",", "notify", ":=", "range", "notifications", "{", "if", "notify", "!=", "nil", "{", "muts", "=", "append", "(", "muts", ",", "&", "NotifyExecution", "{", "cfgName", ",", "notify", "}", ")", "\n", "}", "\n", "}", "\n", "err", "=", "tumble", ".", "AddToJournal", "(", "c", ",", "muts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Fields", "{", "\"", "\"", ":", "err", ",", "\"", "\"", ":", "cfgName", "}", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "http", ".", "Error", "(", "rw", ",", "\"", "\"", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "rw", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "}" ]
// TaskQueueHandler is the http handler that routes taskqueue tasks made with // Config.EnqueueTask to a distributor's HandleTaskQueueTask method. // // This requires that ctx.Context already have a Registry installed via the // WithRegistry method.
[ "TaskQueueHandler", "is", "the", "http", "handler", "that", "routes", "taskqueue", "tasks", "made", "with", "Config", ".", "EnqueueTask", "to", "a", "distributor", "s", "HandleTaskQueueTask", "method", ".", "This", "requires", "that", "ctx", ".", "Context", "already", "have", "a", "Registry", "installed", "via", "the", "WithRegistry", "method", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/tq_handler.go#L38-L70
7,473
luci/luci-go
luci_notify/config/emailtemplate.go
emailTemplateFilenameRegexp
func emailTemplateFilenameRegexp(c context.Context) *regexp.Regexp { appId := info.AppID(c) pattern := fmt.Sprintf(`^%s+/email-templates/([a-z][a-z0-9_]*)\.template$`, regexp.QuoteMeta(appId)) return regexp.MustCompile(pattern) }
go
func emailTemplateFilenameRegexp(c context.Context) *regexp.Regexp { appId := info.AppID(c) pattern := fmt.Sprintf(`^%s+/email-templates/([a-z][a-z0-9_]*)\.template$`, regexp.QuoteMeta(appId)) return regexp.MustCompile(pattern) }
[ "func", "emailTemplateFilenameRegexp", "(", "c", "context", ".", "Context", ")", "*", "regexp", ".", "Regexp", "{", "appId", ":=", "info", ".", "AppID", "(", "c", ")", "\n", "pattern", ":=", "fmt", ".", "Sprintf", "(", "`^%s+/email-templates/([a-z][a-z0-9_]*)\\.template$`", ",", "regexp", ".", "QuoteMeta", "(", "appId", ")", ")", "\n", "return", "regexp", ".", "MustCompile", "(", "pattern", ")", "\n", "}" ]
// emailTemplateFilenameRegexp returns a regular expression for email template // file names.
[ "emailTemplateFilenameRegexp", "returns", "a", "regular", "expression", "for", "email", "template", "file", "names", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/emailtemplate.go#L45-L49
7,474
luci/luci-go
luci_notify/config/emailtemplate.go
fetchAllEmailTemplates
func fetchAllEmailTemplates(c context.Context, configService configInterface.Interface, projectId string) (map[string]*EmailTemplate, error) { configSet := configInterface.ProjectSet(projectId) files, err := configService.ListFiles(c, configSet) if err != nil { return nil, err } ret := map[string]*EmailTemplate{} // This runs in a cron job. It is not performance critical, so we don't have // to fetch files concurrently. filenameRegexp := emailTemplateFilenameRegexp(c) for _, f := range files { m := filenameRegexp.FindStringSubmatch(f) if m == nil { // Not a template file or a template of another instance of luci-notify. continue } templateName := m[1] logging.Infof(c, "fetching email template from %s:%s", configSet, f) config, err := configService.GetConfig(c, configSet, f, false) if err != nil { return nil, errors.Annotate(err, "failed to fetch %q", f).Err() } subject, body, err := splitEmailTemplateFile(config.Content) if err != nil { // Should not happen. luci-config should not have passed this commit in // because luci-notify exposes its validation code to luci-conifg. logging.Warningf(c, "invalid email template content in %q: %s", f, err) continue } ret[templateName] = &EmailTemplate{ Name: templateName, SubjectTextTemplate: subject, BodyHTMLTemplate: body, DefinitionURL: config.ViewURL, } } return ret, nil }
go
func fetchAllEmailTemplates(c context.Context, configService configInterface.Interface, projectId string) (map[string]*EmailTemplate, error) { configSet := configInterface.ProjectSet(projectId) files, err := configService.ListFiles(c, configSet) if err != nil { return nil, err } ret := map[string]*EmailTemplate{} // This runs in a cron job. It is not performance critical, so we don't have // to fetch files concurrently. filenameRegexp := emailTemplateFilenameRegexp(c) for _, f := range files { m := filenameRegexp.FindStringSubmatch(f) if m == nil { // Not a template file or a template of another instance of luci-notify. continue } templateName := m[1] logging.Infof(c, "fetching email template from %s:%s", configSet, f) config, err := configService.GetConfig(c, configSet, f, false) if err != nil { return nil, errors.Annotate(err, "failed to fetch %q", f).Err() } subject, body, err := splitEmailTemplateFile(config.Content) if err != nil { // Should not happen. luci-config should not have passed this commit in // because luci-notify exposes its validation code to luci-conifg. logging.Warningf(c, "invalid email template content in %q: %s", f, err) continue } ret[templateName] = &EmailTemplate{ Name: templateName, SubjectTextTemplate: subject, BodyHTMLTemplate: body, DefinitionURL: config.ViewURL, } } return ret, nil }
[ "func", "fetchAllEmailTemplates", "(", "c", "context", ".", "Context", ",", "configService", "configInterface", ".", "Interface", ",", "projectId", "string", ")", "(", "map", "[", "string", "]", "*", "EmailTemplate", ",", "error", ")", "{", "configSet", ":=", "configInterface", ".", "ProjectSet", "(", "projectId", ")", "\n", "files", ",", "err", ":=", "configService", ".", "ListFiles", "(", "c", ",", "configSet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ret", ":=", "map", "[", "string", "]", "*", "EmailTemplate", "{", "}", "\n\n", "// This runs in a cron job. It is not performance critical, so we don't have", "// to fetch files concurrently.", "filenameRegexp", ":=", "emailTemplateFilenameRegexp", "(", "c", ")", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "m", ":=", "filenameRegexp", ".", "FindStringSubmatch", "(", "f", ")", "\n", "if", "m", "==", "nil", "{", "// Not a template file or a template of another instance of luci-notify.", "continue", "\n", "}", "\n", "templateName", ":=", "m", "[", "1", "]", "\n\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "configSet", ",", "f", ")", "\n", "config", ",", "err", ":=", "configService", ".", "GetConfig", "(", "c", ",", "configSet", ",", "f", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "f", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "subject", ",", "body", ",", "err", ":=", "splitEmailTemplateFile", "(", "config", ".", "Content", ")", "\n", "if", "err", "!=", "nil", "{", "// Should not happen. luci-config should not have passed this commit in", "// because luci-notify exposes its validation code to luci-conifg.", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "f", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "ret", "[", "templateName", "]", "=", "&", "EmailTemplate", "{", "Name", ":", "templateName", ",", "SubjectTextTemplate", ":", "subject", ",", "BodyHTMLTemplate", ":", "body", ",", "DefinitionURL", ":", "config", ".", "ViewURL", ",", "}", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// fetchAllEmailTemplates fetches all valid email templates of the project from // a config service. Returned EmailTemplate entities do not have ProjectKey set.
[ "fetchAllEmailTemplates", "fetches", "all", "valid", "email", "templates", "of", "the", "project", "from", "a", "config", "service", ".", "Returned", "EmailTemplate", "entities", "do", "not", "have", "ProjectKey", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/emailtemplate.go#L75-L117
7,475
luci/luci-go
luci_notify/config/emailtemplate.go
splitEmailTemplateFile
func splitEmailTemplateFile(content string) (subject, body string, err error) { if len(content) == 0 { return "", "", fmt.Errorf("empty file") } parts := strings.SplitN(content, "\n", 3) switch { case len(parts) < 3: return "", "", fmt.Errorf("less than three lines") case len(strings.TrimSpace(parts[1])) > 0: return "", "", fmt.Errorf("second line is not blank: %q", parts[1]) default: return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[2]), nil } }
go
func splitEmailTemplateFile(content string) (subject, body string, err error) { if len(content) == 0 { return "", "", fmt.Errorf("empty file") } parts := strings.SplitN(content, "\n", 3) switch { case len(parts) < 3: return "", "", fmt.Errorf("less than three lines") case len(strings.TrimSpace(parts[1])) > 0: return "", "", fmt.Errorf("second line is not blank: %q", parts[1]) default: return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[2]), nil } }
[ "func", "splitEmailTemplateFile", "(", "content", "string", ")", "(", "subject", ",", "body", "string", ",", "err", "error", ")", "{", "if", "len", "(", "content", ")", "==", "0", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "parts", ":=", "strings", ".", "SplitN", "(", "content", ",", "\"", "\\n", "\"", ",", "3", ")", "\n", "switch", "{", "case", "len", "(", "parts", ")", "<", "3", ":", "return", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n\n", "case", "len", "(", "strings", ".", "TrimSpace", "(", "parts", "[", "1", "]", ")", ")", ">", "0", ":", "return", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "parts", "[", "1", "]", ")", "\n\n", "default", ":", "return", "strings", ".", "TrimSpace", "(", "parts", "[", "0", "]", ")", ",", "strings", ".", "TrimSpace", "(", "parts", "[", "2", "]", ")", ",", "nil", "\n", "}", "\n", "}" ]
// splitEmailTemplateFile splits an email template file into subject and body. // Does not validate their syntaxes. // See notify.proto for file format.
[ "splitEmailTemplateFile", "splits", "an", "email", "template", "file", "into", "subject", "and", "body", ".", "Does", "not", "validate", "their", "syntaxes", ".", "See", "notify", ".", "proto", "for", "file", "format", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/emailtemplate.go#L122-L138
7,476
luci/luci-go
milo/buildsource/buildbucket/build_legacy.go
GetRawBuild
func GetRawBuild(c context.Context, address string) (*bbv1.ApiCommonBuildMessage, error) { host, err := getHost(c) if err != nil { return nil, err } client, err := newBuildbucketClient(c, host) if err != nil { return nil, err } // This runs a search RPC against BuildBucket, but it is optimized for speed. build, err := bbv1.GetByAddress(c, client, address) switch { case err != nil: return nil, errors.Annotate(err, "could not get build at %q", address).Err() case build == nil && auth.CurrentUser(c).Identity == identity.AnonymousIdentity: return nil, errors.Reason("not logged in").Tag(grpcutil.UnauthenticatedTag).Err() case build == nil: return nil, errors.Reason("build at %q not found", address).Tag(grpcutil.NotFoundTag).Err() default: return build, nil } }
go
func GetRawBuild(c context.Context, address string) (*bbv1.ApiCommonBuildMessage, error) { host, err := getHost(c) if err != nil { return nil, err } client, err := newBuildbucketClient(c, host) if err != nil { return nil, err } // This runs a search RPC against BuildBucket, but it is optimized for speed. build, err := bbv1.GetByAddress(c, client, address) switch { case err != nil: return nil, errors.Annotate(err, "could not get build at %q", address).Err() case build == nil && auth.CurrentUser(c).Identity == identity.AnonymousIdentity: return nil, errors.Reason("not logged in").Tag(grpcutil.UnauthenticatedTag).Err() case build == nil: return nil, errors.Reason("build at %q not found", address).Tag(grpcutil.NotFoundTag).Err() default: return build, nil } }
[ "func", "GetRawBuild", "(", "c", "context", ".", "Context", ",", "address", "string", ")", "(", "*", "bbv1", ".", "ApiCommonBuildMessage", ",", "error", ")", "{", "host", ",", "err", ":=", "getHost", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "client", ",", "err", ":=", "newBuildbucketClient", "(", "c", ",", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// This runs a search RPC against BuildBucket, but it is optimized for speed.", "build", ",", "err", ":=", "bbv1", ".", "GetByAddress", "(", "c", ",", "client", ",", "address", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "address", ")", ".", "Err", "(", ")", "\n", "case", "build", "==", "nil", "&&", "auth", ".", "CurrentUser", "(", "c", ")", ".", "Identity", "==", "identity", ".", "AnonymousIdentity", ":", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "UnauthenticatedTag", ")", ".", "Err", "(", ")", "\n", "case", "build", "==", "nil", ":", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "address", ")", ".", "Tag", "(", "grpcutil", ".", "NotFoundTag", ")", ".", "Err", "(", ")", "\n", "default", ":", "return", "build", ",", "nil", "\n", "}", "\n", "}" ]
// GetRawBuild fetches a buildbucket build given its address.
[ "GetRawBuild", "fetches", "a", "buildbucket", "build", "given", "its", "address", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build_legacy.go#L263-L285
7,477
luci/luci-go
milo/buildsource/buildbucket/build_legacy.go
getStep
func getStep(c context.Context, bbBuildMessage *bbv1.ApiCommonBuildMessage) (*logDogTypes.StreamAddr, *miloProto.Step, error) { swarmingTags := strpair.ParseMap(bbBuildMessage.Tags)["swarming_tag"] logLocation := strpair.ParseMap(swarmingTags).Get("log_location") if logLocation == "" { return nil, nil, errors.New("Build is missing log_location") } addr, err := logDogTypes.ParseURL(logLocation) if err != nil { return nil, nil, errors.Annotate(err, "%s is invalid", addr).Err() } step, err := rawpresentation.ReadAnnotations(c, addr) return addr, step, err }
go
func getStep(c context.Context, bbBuildMessage *bbv1.ApiCommonBuildMessage) (*logDogTypes.StreamAddr, *miloProto.Step, error) { swarmingTags := strpair.ParseMap(bbBuildMessage.Tags)["swarming_tag"] logLocation := strpair.ParseMap(swarmingTags).Get("log_location") if logLocation == "" { return nil, nil, errors.New("Build is missing log_location") } addr, err := logDogTypes.ParseURL(logLocation) if err != nil { return nil, nil, errors.Annotate(err, "%s is invalid", addr).Err() } step, err := rawpresentation.ReadAnnotations(c, addr) return addr, step, err }
[ "func", "getStep", "(", "c", "context", ".", "Context", ",", "bbBuildMessage", "*", "bbv1", ".", "ApiCommonBuildMessage", ")", "(", "*", "logDogTypes", ".", "StreamAddr", ",", "*", "miloProto", ".", "Step", ",", "error", ")", "{", "swarmingTags", ":=", "strpair", ".", "ParseMap", "(", "bbBuildMessage", ".", "Tags", ")", "[", "\"", "\"", "]", "\n", "logLocation", ":=", "strpair", ".", "ParseMap", "(", "swarmingTags", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "logLocation", "==", "\"", "\"", "{", "return", "nil", ",", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "addr", ",", "err", ":=", "logDogTypes", ".", "ParseURL", "(", "logLocation", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "addr", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "step", ",", "err", ":=", "rawpresentation", ".", "ReadAnnotations", "(", "c", ",", "addr", ")", "\n", "return", "addr", ",", "step", ",", "err", "\n", "}" ]
// getStep fetches returns the Step annoations from LogDog.
[ "getStep", "fetches", "returns", "the", "Step", "annoations", "from", "LogDog", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build_legacy.go#L288-L301
7,478
luci/luci-go
milo/buildsource/buildbucket/build_legacy.go
GetBuildLegacy
func GetBuildLegacy(c context.Context, address string, fetchFull bool) (*ui.MiloBuildLegacy, error) { bbBuildMessage, err := GetRawBuild(c, address) if err != nil { return nil, err } return ToMiloBuild(c, bbBuildMessage, fetchFull) }
go
func GetBuildLegacy(c context.Context, address string, fetchFull bool) (*ui.MiloBuildLegacy, error) { bbBuildMessage, err := GetRawBuild(c, address) if err != nil { return nil, err } return ToMiloBuild(c, bbBuildMessage, fetchFull) }
[ "func", "GetBuildLegacy", "(", "c", "context", ".", "Context", ",", "address", "string", ",", "fetchFull", "bool", ")", "(", "*", "ui", ".", "MiloBuildLegacy", ",", "error", ")", "{", "bbBuildMessage", ",", "err", ":=", "GetRawBuild", "(", "c", ",", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ToMiloBuild", "(", "c", ",", "bbBuildMessage", ",", "fetchFull", ")", "\n", "}" ]
// GetBuild is a shortcut for GetRawBuild and ToMiloBuild.
[ "GetBuild", "is", "a", "shortcut", "for", "GetRawBuild", "and", "ToMiloBuild", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build_legacy.go#L304-L310
7,479
luci/luci-go
milo/buildsource/buildbucket/build_legacy.go
getBlameLegacy
func getBlameLegacy(c context.Context, msg *bbv1.ApiCommonBuildMessage) []*ui.Commit { host, err := getHost(c) if err != nil { return []*ui.Commit{{ Description: fmt.Sprintf("Failed to fetch blame information\n%s", err.Error()), }} } tags := strpair.ParseMap(msg.Tags) bSet, _ := tags["buildset"] bid := NewBuilderID(msg.Bucket, tags.Get("builder")) bs := &model.BuildSummary{ BuildKey: MakeBuildKey(c, host, tags.Get("build_address")), BuildSet: bSet, BuilderID: bid.String(), } blame, err := simplisticBlamelist(c, bs) if err != nil { logging.WithError(err).Warningf(c, "getting blamelist") } return blame }
go
func getBlameLegacy(c context.Context, msg *bbv1.ApiCommonBuildMessage) []*ui.Commit { host, err := getHost(c) if err != nil { return []*ui.Commit{{ Description: fmt.Sprintf("Failed to fetch blame information\n%s", err.Error()), }} } tags := strpair.ParseMap(msg.Tags) bSet, _ := tags["buildset"] bid := NewBuilderID(msg.Bucket, tags.Get("builder")) bs := &model.BuildSummary{ BuildKey: MakeBuildKey(c, host, tags.Get("build_address")), BuildSet: bSet, BuilderID: bid.String(), } blame, err := simplisticBlamelist(c, bs) if err != nil { logging.WithError(err).Warningf(c, "getting blamelist") } return blame }
[ "func", "getBlameLegacy", "(", "c", "context", ".", "Context", ",", "msg", "*", "bbv1", ".", "ApiCommonBuildMessage", ")", "[", "]", "*", "ui", ".", "Commit", "{", "host", ",", "err", ":=", "getHost", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "*", "ui", ".", "Commit", "{", "{", "Description", ":", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "err", ".", "Error", "(", ")", ")", ",", "}", "}", "\n", "}", "\n", "tags", ":=", "strpair", ".", "ParseMap", "(", "msg", ".", "Tags", ")", "\n", "bSet", ",", "_", ":=", "tags", "[", "\"", "\"", "]", "\n", "bid", ":=", "NewBuilderID", "(", "msg", ".", "Bucket", ",", "tags", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "bs", ":=", "&", "model", ".", "BuildSummary", "{", "BuildKey", ":", "MakeBuildKey", "(", "c", ",", "host", ",", "tags", ".", "Get", "(", "\"", "\"", ")", ")", ",", "BuildSet", ":", "bSet", ",", "BuilderID", ":", "bid", ".", "String", "(", ")", ",", "}", "\n", "blame", ",", "err", ":=", "simplisticBlamelist", "(", "c", ",", "bs", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "blame", "\n", "}" ]
// getBlameLegacy fetches blame information from Gitiles. This requires the // BuildSummary to be indexed in Milo.
[ "getBlameLegacy", "fetches", "blame", "information", "from", "Gitiles", ".", "This", "requires", "the", "BuildSummary", "to", "be", "indexed", "in", "Milo", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build_legacy.go#L355-L375
7,480
luci/luci-go
common/tsmon/registry/registry.go
Add
func Add(m types.Metric) { name := m.Info().Name lock.Lock() defer lock.Unlock() if _, ok := registry[name]; ok { panic(fmt.Sprintf("A metric with the name %q was already registered", name)) } registry[name] = m }
go
func Add(m types.Metric) { name := m.Info().Name lock.Lock() defer lock.Unlock() if _, ok := registry[name]; ok { panic(fmt.Sprintf("A metric with the name %q was already registered", name)) } registry[name] = m }
[ "func", "Add", "(", "m", "types", ".", "Metric", ")", "{", "name", ":=", "m", ".", "Info", "(", ")", ".", "Name", "\n\n", "lock", ".", "Lock", "(", ")", "\n", "defer", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "ok", ":=", "registry", "[", "name", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n", "registry", "[", "name", "]", "=", "m", "\n", "}" ]
// Add adds a metric to the metric registry. // // Panics if a metric with such name is already defined.
[ "Add", "adds", "a", "metric", "to", "the", "metric", "registry", ".", "Panics", "if", "a", "metric", "with", "such", "name", "is", "already", "defined", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/registry/registry.go#L36-L46
7,481
luci/luci-go
common/tsmon/registry/registry.go
Iter
func Iter(cb func(m types.Metric)) { lock.RLock() defer lock.RUnlock() for _, v := range registry { cb(v) } }
go
func Iter(cb func(m types.Metric)) { lock.RLock() defer lock.RUnlock() for _, v := range registry { cb(v) } }
[ "func", "Iter", "(", "cb", "func", "(", "m", "types", ".", "Metric", ")", ")", "{", "lock", ".", "RLock", "(", ")", "\n", "defer", "lock", ".", "RUnlock", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "registry", "{", "cb", "(", "v", ")", "\n", "}", "\n", "}" ]
// Iter calls a callback for each registered metric. // // Metrics are visited in no particular order. The callback must not modify // the registry.
[ "Iter", "calls", "a", "callback", "for", "each", "registered", "metric", ".", "Metrics", "are", "visited", "in", "no", "particular", "order", ".", "The", "callback", "must", "not", "modify", "the", "registry", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/registry/registry.go#L52-L58
7,482
luci/luci-go
logdog/appengine/coordinator/logStream.go
PopulateState
func (s *LogStream) PopulateState(c context.Context, lst *LogStreamState) { lst.Parent = ds.KeyForObj(c, s) }
go
func (s *LogStream) PopulateState(c context.Context, lst *LogStreamState) { lst.Parent = ds.KeyForObj(c, s) }
[ "func", "(", "s", "*", "LogStream", ")", "PopulateState", "(", "c", "context", ".", "Context", ",", "lst", "*", "LogStreamState", ")", "{", "lst", ".", "Parent", "=", "ds", ".", "KeyForObj", "(", "c", ",", "s", ")", "\n", "}" ]
// PopulateState populates the datastore key fields for the supplied // LogStreamState, binding them to the current LogStream.
[ "PopulateState", "populates", "the", "datastore", "key", "fields", "for", "the", "supplied", "LogStreamState", "binding", "them", "to", "the", "current", "LogStream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L146-L148
7,483
luci/luci-go
logdog/appengine/coordinator/logStream.go
State
func (s *LogStream) State(c context.Context) *LogStreamState { var lst LogStreamState s.PopulateState(c, &lst) return &lst }
go
func (s *LogStream) State(c context.Context) *LogStreamState { var lst LogStreamState s.PopulateState(c, &lst) return &lst }
[ "func", "(", "s", "*", "LogStream", ")", "State", "(", "c", "context", ".", "Context", ")", "*", "LogStreamState", "{", "var", "lst", "LogStreamState", "\n", "s", ".", "PopulateState", "(", "c", ",", "&", "lst", ")", "\n", "return", "&", "lst", "\n", "}" ]
// State returns the LogStreamState keyed for this LogStream.
[ "State", "returns", "the", "LogStreamState", "keyed", "for", "this", "LogStream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L151-L155
7,484
luci/luci-go
logdog/appengine/coordinator/logStream.go
Path
func (s *LogStream) Path() types.StreamPath { return types.StreamName(s.Prefix).Join(types.StreamName(s.Name)) }
go
func (s *LogStream) Path() types.StreamPath { return types.StreamName(s.Prefix).Join(types.StreamName(s.Name)) }
[ "func", "(", "s", "*", "LogStream", ")", "Path", "(", ")", "types", ".", "StreamPath", "{", "return", "types", ".", "StreamName", "(", "s", ".", "Prefix", ")", ".", "Join", "(", "types", ".", "StreamName", "(", "s", ".", "Name", ")", ")", "\n", "}" ]
// Path returns the LogDog path for this log stream.
[ "Path", "returns", "the", "LogDog", "path", "for", "this", "log", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L158-L160
7,485
luci/luci-go
logdog/appengine/coordinator/logStream.go
DescriptorValue
func (s *LogStream) DescriptorValue() (*logpb.LogStreamDescriptor, error) { pb := logpb.LogStreamDescriptor{} if err := proto.Unmarshal(s.Descriptor, &pb); err != nil { return nil, err } return &pb, nil }
go
func (s *LogStream) DescriptorValue() (*logpb.LogStreamDescriptor, error) { pb := logpb.LogStreamDescriptor{} if err := proto.Unmarshal(s.Descriptor, &pb); err != nil { return nil, err } return &pb, nil }
[ "func", "(", "s", "*", "LogStream", ")", "DescriptorValue", "(", ")", "(", "*", "logpb", ".", "LogStreamDescriptor", ",", "error", ")", "{", "pb", ":=", "logpb", ".", "LogStreamDescriptor", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "s", ".", "Descriptor", ",", "&", "pb", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "pb", ",", "nil", "\n", "}" ]
// DescriptorValue returns the unmarshalled Descriptor field protobuf.
[ "DescriptorValue", "returns", "the", "unmarshalled", "Descriptor", "field", "protobuf", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L269-L275
7,486
luci/luci-go
logdog/appengine/coordinator/logStream.go
DescriptorProto
func (s *LogStream) DescriptorProto() (*logpb.LogStreamDescriptor, error) { desc := logpb.LogStreamDescriptor{} if err := proto.Unmarshal(s.Descriptor, &desc); err != nil { return nil, err } return &desc, nil }
go
func (s *LogStream) DescriptorProto() (*logpb.LogStreamDescriptor, error) { desc := logpb.LogStreamDescriptor{} if err := proto.Unmarshal(s.Descriptor, &desc); err != nil { return nil, err } return &desc, nil }
[ "func", "(", "s", "*", "LogStream", ")", "DescriptorProto", "(", ")", "(", "*", "logpb", ".", "LogStreamDescriptor", ",", "error", ")", "{", "desc", ":=", "logpb", ".", "LogStreamDescriptor", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "s", ".", "Descriptor", ",", "&", "desc", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "desc", ",", "nil", "\n", "}" ]
// DescriptorProto unmarshals a LogStreamDescriptor from the stream's Descriptor // field. It will return an error if the unmarshalling fails.
[ "DescriptorProto", "unmarshals", "a", "LogStreamDescriptor", "from", "the", "stream", "s", "Descriptor", "field", ".", "It", "will", "return", "an", "error", "if", "the", "unmarshalling", "fails", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L314-L320
7,487
luci/luci-go
logdog/appengine/coordinator/logStream.go
generatePathComponents
func generatePathComponents(prefix, name string) ds.PropertySlice { ps, ns := types.StreamName(prefix).Segments(), types.StreamName(name).Segments() // Allocate our components array. For each component, there are two entries // (forward and reverse), as well as one count entry per component type. c := make(ds.PropertySlice, 0, (len(ps)+len(ns)+1)*2) gen := func(b string, segs []string) { // Generate count component (PC:4). c = append(c, ds.MkProperty(fmt.Sprintf("%sC:%d", b, len(segs)))) // Generate forward and reverse components. for i, s := range segs { c = append(c, // Forward (PF:0:foo). ds.MkProperty(fmt.Sprintf("%sF:%d:%s", b, i, s)), // Reverse (PR:3:foo) ds.MkProperty(fmt.Sprintf("%sR:%d:%s", b, len(segs)-i-1, s)), ) } } gen("P", ps) gen("N", ns) return c }
go
func generatePathComponents(prefix, name string) ds.PropertySlice { ps, ns := types.StreamName(prefix).Segments(), types.StreamName(name).Segments() // Allocate our components array. For each component, there are two entries // (forward and reverse), as well as one count entry per component type. c := make(ds.PropertySlice, 0, (len(ps)+len(ns)+1)*2) gen := func(b string, segs []string) { // Generate count component (PC:4). c = append(c, ds.MkProperty(fmt.Sprintf("%sC:%d", b, len(segs)))) // Generate forward and reverse components. for i, s := range segs { c = append(c, // Forward (PF:0:foo). ds.MkProperty(fmt.Sprintf("%sF:%d:%s", b, i, s)), // Reverse (PR:3:foo) ds.MkProperty(fmt.Sprintf("%sR:%d:%s", b, len(segs)-i-1, s)), ) } } gen("P", ps) gen("N", ns) return c }
[ "func", "generatePathComponents", "(", "prefix", ",", "name", "string", ")", "ds", ".", "PropertySlice", "{", "ps", ",", "ns", ":=", "types", ".", "StreamName", "(", "prefix", ")", ".", "Segments", "(", ")", ",", "types", ".", "StreamName", "(", "name", ")", ".", "Segments", "(", ")", "\n\n", "// Allocate our components array. For each component, there are two entries", "// (forward and reverse), as well as one count entry per component type.", "c", ":=", "make", "(", "ds", ".", "PropertySlice", ",", "0", ",", "(", "len", "(", "ps", ")", "+", "len", "(", "ns", ")", "+", "1", ")", "*", "2", ")", "\n\n", "gen", ":=", "func", "(", "b", "string", ",", "segs", "[", "]", "string", ")", "{", "// Generate count component (PC:4).", "c", "=", "append", "(", "c", ",", "ds", ".", "MkProperty", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ",", "len", "(", "segs", ")", ")", ")", ")", "\n\n", "// Generate forward and reverse components.", "for", "i", ",", "s", ":=", "range", "segs", "{", "c", "=", "append", "(", "c", ",", "// Forward (PF:0:foo).", "ds", ".", "MkProperty", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ",", "i", ",", "s", ")", ")", ",", "// Reverse (PR:3:foo)", "ds", ".", "MkProperty", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ",", "len", "(", "segs", ")", "-", "i", "-", "1", ",", "s", ")", ")", ",", ")", "\n", "}", "\n", "}", "\n", "gen", "(", "\"", "\"", ",", "ps", ")", "\n", "gen", "(", "\"", "\"", ",", "ns", ")", "\n", "return", "c", "\n", "}" ]
// generatePathComponents generates the "_C" property path components for path // glob querying. // // See the comment on LogStream for more infromation.
[ "generatePathComponents", "generates", "the", "_C", "property", "path", "components", "for", "path", "glob", "querying", ".", "See", "the", "comment", "on", "LogStream", "for", "more", "infromation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L334-L358
7,488
luci/luci-go
logdog/appengine/coordinator/logStream.go
AddLogStreamPathFilter
func AddLogStreamPathFilter(q *ds.Query, path string) (*ds.Query, error) { prefix, name := types.StreamPath(path).Split() err := error(nil) q, err = addComponentFilter(q, "Prefix", "_C", "P", prefix) if err != nil { return nil, err } q, err = addComponentFilter(q, "Name", "_C", "N", name) if err != nil { return nil, err } return q, nil }
go
func AddLogStreamPathFilter(q *ds.Query, path string) (*ds.Query, error) { prefix, name := types.StreamPath(path).Split() err := error(nil) q, err = addComponentFilter(q, "Prefix", "_C", "P", prefix) if err != nil { return nil, err } q, err = addComponentFilter(q, "Name", "_C", "N", name) if err != nil { return nil, err } return q, nil }
[ "func", "AddLogStreamPathFilter", "(", "q", "*", "ds", ".", "Query", ",", "path", "string", ")", "(", "*", "ds", ".", "Query", ",", "error", ")", "{", "prefix", ",", "name", ":=", "types", ".", "StreamPath", "(", "path", ")", ".", "Split", "(", ")", "\n\n", "err", ":=", "error", "(", "nil", ")", "\n", "q", ",", "err", "=", "addComponentFilter", "(", "q", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "prefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "q", ",", "err", "=", "addComponentFilter", "(", "q", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "q", ",", "nil", "\n", "}" ]
// AddLogStreamPathFilter constructs a compiled LogStreamPathQuery. It will // return an error if the supllied query string describes an invalid query.
[ "AddLogStreamPathFilter", "constructs", "a", "compiled", "LogStreamPathQuery", ".", "It", "will", "return", "an", "error", "if", "the", "supllied", "query", "string", "describes", "an", "invalid", "query", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L443-L456
7,489
luci/luci-go
logdog/appengine/coordinator/logStream.go
AddLogStreamTerminatedFilter
func AddLogStreamTerminatedFilter(q *ds.Query, v bool) *ds.Query { return q.Eq("_Terminated", v) }
go
func AddLogStreamTerminatedFilter(q *ds.Query, v bool) *ds.Query { return q.Eq("_Terminated", v) }
[ "func", "AddLogStreamTerminatedFilter", "(", "q", "*", "ds", ".", "Query", ",", "v", "bool", ")", "*", "ds", ".", "Query", "{", "return", "q", ".", "Eq", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// AddLogStreamTerminatedFilter returns a derived query that asserts that a log // stream has been terminated.
[ "AddLogStreamTerminatedFilter", "returns", "a", "derived", "query", "that", "asserts", "that", "a", "log", "stream", "has", "been", "terminated", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L460-L462
7,490
luci/luci-go
logdog/appengine/coordinator/logStream.go
AddLogStreamArchivedFilter
func AddLogStreamArchivedFilter(q *ds.Query, v bool) *ds.Query { return q.Eq("_Archived", v) }
go
func AddLogStreamArchivedFilter(q *ds.Query, v bool) *ds.Query { return q.Eq("_Archived", v) }
[ "func", "AddLogStreamArchivedFilter", "(", "q", "*", "ds", ".", "Query", ",", "v", "bool", ")", "*", "ds", ".", "Query", "{", "return", "q", ".", "Eq", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// AddLogStreamArchivedFilter returns a derived query that asserts that a log // stream has been archived.
[ "AddLogStreamArchivedFilter", "returns", "a", "derived", "query", "that", "asserts", "that", "a", "log", "stream", "has", "been", "archived", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L466-L468
7,491
luci/luci-go
logdog/appengine/coordinator/logStream.go
AddLogStreamPurgedFilter
func AddLogStreamPurgedFilter(q *ds.Query, v bool) *ds.Query { return q.Eq("Purged", v) }
go
func AddLogStreamPurgedFilter(q *ds.Query, v bool) *ds.Query { return q.Eq("Purged", v) }
[ "func", "AddLogStreamPurgedFilter", "(", "q", "*", "ds", ".", "Query", ",", "v", "bool", ")", "*", "ds", ".", "Query", "{", "return", "q", ".", "Eq", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// AddLogStreamPurgedFilter returns a derived query that asserts that a log // stream has been archived.
[ "AddLogStreamPurgedFilter", "returns", "a", "derived", "query", "that", "asserts", "that", "a", "log", "stream", "has", "been", "archived", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L472-L474
7,492
luci/luci-go
logdog/appengine/coordinator/logStream.go
AddOlderFilter
func AddOlderFilter(q *ds.Query, t time.Time) *ds.Query { return q.Lt("Created", t.UTC()).Order("-Created") }
go
func AddOlderFilter(q *ds.Query, t time.Time) *ds.Query { return q.Lt("Created", t.UTC()).Order("-Created") }
[ "func", "AddOlderFilter", "(", "q", "*", "ds", ".", "Query", ",", "t", "time", ".", "Time", ")", "*", "ds", ".", "Query", "{", "return", "q", ".", "Lt", "(", "\"", "\"", ",", "t", ".", "UTC", "(", ")", ")", ".", "Order", "(", "\"", "\"", ")", "\n", "}" ]
// AddOlderFilter adds a filter to queries that restricts them to results that // were created before the supplied time.
[ "AddOlderFilter", "adds", "a", "filter", "to", "queries", "that", "restricts", "them", "to", "results", "that", "were", "created", "before", "the", "supplied", "time", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L478-L480
7,493
luci/luci-go
logdog/appengine/coordinator/logStream.go
AddNewerFilter
func AddNewerFilter(q *ds.Query, t time.Time) *ds.Query { return q.Gt("Created", t.UTC()).Order("-Created") }
go
func AddNewerFilter(q *ds.Query, t time.Time) *ds.Query { return q.Gt("Created", t.UTC()).Order("-Created") }
[ "func", "AddNewerFilter", "(", "q", "*", "ds", ".", "Query", ",", "t", "time", ".", "Time", ")", "*", "ds", ".", "Query", "{", "return", "q", ".", "Gt", "(", "\"", "\"", ",", "t", ".", "UTC", "(", ")", ")", ".", "Order", "(", "\"", "\"", ")", "\n", "}" ]
// AddNewerFilter adds a filter to queries that restricts them to results that // were created after the supplied time.
[ "AddNewerFilter", "adds", "a", "filter", "to", "queries", "that", "restricts", "them", "to", "results", "that", "were", "created", "after", "the", "supplied", "time", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStream.go#L484-L486
7,494
luci/luci-go
server/templates/context.go
Get
func Get(c context.Context, name string) (*template.Template, error) { if b, _ := c.Value(&contextKey).(*boundBundle); b != nil { return b.Get(name) } return nil, errNoBundle }
go
func Get(c context.Context, name string) (*template.Template, error) { if b, _ := c.Value(&contextKey).(*boundBundle); b != nil { return b.Get(name) } return nil, errNoBundle }
[ "func", "Get", "(", "c", "context", ".", "Context", ",", "name", "string", ")", "(", "*", "template", ".", "Template", ",", "error", ")", "{", "if", "b", ",", "_", ":=", "c", ".", "Value", "(", "&", "contextKey", ")", ".", "(", "*", "boundBundle", ")", ";", "b", "!=", "nil", "{", "return", "b", ".", "Get", "(", "name", ")", "\n", "}", "\n", "return", "nil", ",", "errNoBundle", "\n", "}" ]
// Get returns template from the currently loaded bundle or error if not found.
[ "Get", "returns", "template", "from", "the", "currently", "loaded", "bundle", "or", "error", "if", "not", "found", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/templates/context.go#L50-L55
7,495
luci/luci-go
server/templates/context.go
MustRender
func MustRender(c context.Context, out io.Writer, name string, args Args) { if b, _ := c.Value(&contextKey).(*boundBundle); b != nil { b.MustRender(c, b.Extra, out, name, args) return } panic(errNoBundle) }
go
func MustRender(c context.Context, out io.Writer, name string, args Args) { if b, _ := c.Value(&contextKey).(*boundBundle); b != nil { b.MustRender(c, b.Extra, out, name, args) return } panic(errNoBundle) }
[ "func", "MustRender", "(", "c", "context", ".", "Context", ",", "out", "io", ".", "Writer", ",", "name", "string", ",", "args", "Args", ")", "{", "if", "b", ",", "_", ":=", "c", ".", "Value", "(", "&", "contextKey", ")", ".", "(", "*", "boundBundle", ")", ";", "b", "!=", "nil", "{", "b", ".", "MustRender", "(", "c", ",", "b", ".", "Extra", ",", "out", ",", "name", ",", "args", ")", "\n", "return", "\n", "}", "\n", "panic", "(", "errNoBundle", ")", "\n", "}" ]
// MustRender renders the template into the output writer or panics. // // It never writes partial output. It also panics if attempt to write to // the output fails.
[ "MustRender", "renders", "the", "template", "into", "the", "output", "writer", "or", "panics", ".", "It", "never", "writes", "partial", "output", ".", "It", "also", "panics", "if", "attempt", "to", "write", "to", "the", "output", "fails", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/templates/context.go#L73-L79
7,496
luci/luci-go
gce/api/config/v1/amount.go
Validate
func (a *Amount) Validate(c *validation.Context) { if a.GetDefault() < 0 { c.Errorf("default amount must be non-negative") } // The algorithm works with any time 7 days greater than the zero time. now := time.Date(2018, 1, 1, 12, 0, 0, 0, time.UTC) schs := make([]indexedSchedule, len(a.GetChange())) for i, s := range a.GetChange() { c.Enter("change %d", i) s.Validate(c) c.Exit() t, err := s.mostRecentStart(now) if err != nil { // s.Validate(c) already emitted this error. return } schs[i] = indexedSchedule{ Schedule: s, index: i, sortKey: t, } } sort.Slice(schs, func(i, j int) bool { return schs[i].sortKey.Before(schs[j].sortKey) }) prevEnd := time.Time{} for i := 0; i < len(schs); i++ { c.Enter("change %d", schs[i].index) start := schs[i].sortKey if schs[i].sortKey.Before(prevEnd) { // Implies intervals are half-open: [start, end). prevEnd // is initialized to the zero time, therefore this can't // succeed when i is 0, meaning i-1 is never -1. c.Errorf("start time is before change %d", schs[i-1].index) } sec, err := schs[i].Schedule.Length.ToSeconds() if err != nil { c.Exit() return } prevEnd = start.Add(time.Second * time.Duration(sec)) c.Exit() } if len(schs) > 0 { // Schedules are relative to the week. // Check for a conflict between the last and first. c.Enter("change %d", schs[0].index) // Treat the first schedule as starting in a week. This checks for a conflict // between the last configured schedule and the first configured schedule. start := schs[0].sortKey.Add(time.Hour * time.Duration(24*7)) if start.Before(prevEnd) { c.Errorf("start time is before change %d", schs[len(schs)-1].index) } } }
go
func (a *Amount) Validate(c *validation.Context) { if a.GetDefault() < 0 { c.Errorf("default amount must be non-negative") } // The algorithm works with any time 7 days greater than the zero time. now := time.Date(2018, 1, 1, 12, 0, 0, 0, time.UTC) schs := make([]indexedSchedule, len(a.GetChange())) for i, s := range a.GetChange() { c.Enter("change %d", i) s.Validate(c) c.Exit() t, err := s.mostRecentStart(now) if err != nil { // s.Validate(c) already emitted this error. return } schs[i] = indexedSchedule{ Schedule: s, index: i, sortKey: t, } } sort.Slice(schs, func(i, j int) bool { return schs[i].sortKey.Before(schs[j].sortKey) }) prevEnd := time.Time{} for i := 0; i < len(schs); i++ { c.Enter("change %d", schs[i].index) start := schs[i].sortKey if schs[i].sortKey.Before(prevEnd) { // Implies intervals are half-open: [start, end). prevEnd // is initialized to the zero time, therefore this can't // succeed when i is 0, meaning i-1 is never -1. c.Errorf("start time is before change %d", schs[i-1].index) } sec, err := schs[i].Schedule.Length.ToSeconds() if err != nil { c.Exit() return } prevEnd = start.Add(time.Second * time.Duration(sec)) c.Exit() } if len(schs) > 0 { // Schedules are relative to the week. // Check for a conflict between the last and first. c.Enter("change %d", schs[0].index) // Treat the first schedule as starting in a week. This checks for a conflict // between the last configured schedule and the first configured schedule. start := schs[0].sortKey.Add(time.Hour * time.Duration(24*7)) if start.Before(prevEnd) { c.Errorf("start time is before change %d", schs[len(schs)-1].index) } } }
[ "func", "(", "a", "*", "Amount", ")", "Validate", "(", "c", "*", "validation", ".", "Context", ")", "{", "if", "a", ".", "GetDefault", "(", ")", "<", "0", "{", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// The algorithm works with any time 7 days greater than the zero time.", "now", ":=", "time", ".", "Date", "(", "2018", ",", "1", ",", "1", ",", "12", ",", "0", ",", "0", ",", "0", ",", "time", ".", "UTC", ")", "\n", "schs", ":=", "make", "(", "[", "]", "indexedSchedule", ",", "len", "(", "a", ".", "GetChange", "(", ")", ")", ")", "\n", "for", "i", ",", "s", ":=", "range", "a", ".", "GetChange", "(", ")", "{", "c", ".", "Enter", "(", "\"", "\"", ",", "i", ")", "\n", "s", ".", "Validate", "(", "c", ")", "\n", "c", ".", "Exit", "(", ")", "\n", "t", ",", "err", ":=", "s", ".", "mostRecentStart", "(", "now", ")", "\n", "if", "err", "!=", "nil", "{", "// s.Validate(c) already emitted this error.", "return", "\n", "}", "\n", "schs", "[", "i", "]", "=", "indexedSchedule", "{", "Schedule", ":", "s", ",", "index", ":", "i", ",", "sortKey", ":", "t", ",", "}", "\n", "}", "\n", "sort", ".", "Slice", "(", "schs", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "schs", "[", "i", "]", ".", "sortKey", ".", "Before", "(", "schs", "[", "j", "]", ".", "sortKey", ")", "}", ")", "\n", "prevEnd", ":=", "time", ".", "Time", "{", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "schs", ")", ";", "i", "++", "{", "c", ".", "Enter", "(", "\"", "\"", ",", "schs", "[", "i", "]", ".", "index", ")", "\n", "start", ":=", "schs", "[", "i", "]", ".", "sortKey", "\n", "if", "schs", "[", "i", "]", ".", "sortKey", ".", "Before", "(", "prevEnd", ")", "{", "// Implies intervals are half-open: [start, end). prevEnd", "// is initialized to the zero time, therefore this can't", "// succeed when i is 0, meaning i-1 is never -1.", "c", ".", "Errorf", "(", "\"", "\"", ",", "schs", "[", "i", "-", "1", "]", ".", "index", ")", "\n", "}", "\n", "sec", ",", "err", ":=", "schs", "[", "i", "]", ".", "Schedule", ".", "Length", ".", "ToSeconds", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "Exit", "(", ")", "\n", "return", "\n", "}", "\n", "prevEnd", "=", "start", ".", "Add", "(", "time", ".", "Second", "*", "time", ".", "Duration", "(", "sec", ")", ")", "\n", "c", ".", "Exit", "(", ")", "\n", "}", "\n", "if", "len", "(", "schs", ")", ">", "0", "{", "// Schedules are relative to the week.", "// Check for a conflict between the last and first.", "c", ".", "Enter", "(", "\"", "\"", ",", "schs", "[", "0", "]", ".", "index", ")", "\n", "// Treat the first schedule as starting in a week. This checks for a conflict", "// between the last configured schedule and the first configured schedule.", "start", ":=", "schs", "[", "0", "]", ".", "sortKey", ".", "Add", "(", "time", ".", "Hour", "*", "time", ".", "Duration", "(", "24", "*", "7", ")", ")", "\n", "if", "start", ".", "Before", "(", "prevEnd", ")", "{", "c", ".", "Errorf", "(", "\"", "\"", ",", "schs", "[", "len", "(", "schs", ")", "-", "1", "]", ".", "index", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Validate validates this amount.
[ "Validate", "validates", "this", "amount", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/amount.go#L58-L110
7,497
luci/luci-go
starlark/starlarkproto/default.go
newDefaultValue
func newDefaultValue(typ reflect.Type) (starlark.Value, error) { switch typ.Kind() { case reflect.Bool: return starlark.False, nil case reflect.Float32, reflect.Float64: return starlark.Float(0), nil case reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64: return starlark.MakeInt(0), nil case reflect.String: return starlark.String(""), nil case reflect.Slice: // this is either a repeated field or 'bytes' return starlark.NewList(nil), nil case reflect.Ptr: // a message field (*Struct) or proto2 scalar field (*int64) if typ.Elem().Kind() != reflect.Struct { return nil, errNoProto2 } t, err := GetMessageType(typ) if err != nil { return nil, fmt.Errorf("can't instantiate value for go type %q - %s", typ, err) } return NewMessage(t), nil case reflect.Map: // a map<k,v> field return &starlark.Dict{}, nil } return nil, fmt.Errorf("do not know how to instantiate starlark value for go type %q", typ) }
go
func newDefaultValue(typ reflect.Type) (starlark.Value, error) { switch typ.Kind() { case reflect.Bool: return starlark.False, nil case reflect.Float32, reflect.Float64: return starlark.Float(0), nil case reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64: return starlark.MakeInt(0), nil case reflect.String: return starlark.String(""), nil case reflect.Slice: // this is either a repeated field or 'bytes' return starlark.NewList(nil), nil case reflect.Ptr: // a message field (*Struct) or proto2 scalar field (*int64) if typ.Elem().Kind() != reflect.Struct { return nil, errNoProto2 } t, err := GetMessageType(typ) if err != nil { return nil, fmt.Errorf("can't instantiate value for go type %q - %s", typ, err) } return NewMessage(t), nil case reflect.Map: // a map<k,v> field return &starlark.Dict{}, nil } return nil, fmt.Errorf("do not know how to instantiate starlark value for go type %q", typ) }
[ "func", "newDefaultValue", "(", "typ", "reflect", ".", "Type", ")", "(", "starlark", ".", "Value", ",", "error", ")", "{", "switch", "typ", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Bool", ":", "return", "starlark", ".", "False", ",", "nil", "\n\n", "case", "reflect", ".", "Float32", ",", "reflect", ".", "Float64", ":", "return", "starlark", ".", "Float", "(", "0", ")", ",", "nil", "\n\n", "case", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", ",", "reflect", ".", "Uint32", ",", "reflect", ".", "Uint64", ":", "return", "starlark", ".", "MakeInt", "(", "0", ")", ",", "nil", "\n\n", "case", "reflect", ".", "String", ":", "return", "starlark", ".", "String", "(", "\"", "\"", ")", ",", "nil", "\n\n", "case", "reflect", ".", "Slice", ":", "// this is either a repeated field or 'bytes'", "return", "starlark", ".", "NewList", "(", "nil", ")", ",", "nil", "\n\n", "case", "reflect", ".", "Ptr", ":", "// a message field (*Struct) or proto2 scalar field (*int64)", "if", "typ", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "nil", ",", "errNoProto2", "\n", "}", "\n", "t", ",", "err", ":=", "GetMessageType", "(", "typ", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "typ", ",", "err", ")", "\n", "}", "\n", "return", "NewMessage", "(", "t", ")", ",", "nil", "\n\n", "case", "reflect", ".", "Map", ":", "// a map<k,v> field", "return", "&", "starlark", ".", "Dict", "{", "}", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "typ", ")", "\n", "}" ]
// newDefaultValue returns a new "zero" starlark value for a field described by // the given Go type.
[ "newDefaultValue", "returns", "a", "new", "zero", "starlark", "value", "for", "a", "field", "described", "by", "the", "given", "Go", "type", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/default.go#L26-L58
7,498
luci/luci-go
tokenserver/appengine/impl/utils/tokensigning/inspector.go
checkLifetime
func (i *Inspector) checkLifetime(c context.Context, body proto.Message) string { lifespan := i.Lifespan(body) now := clock.Now(c) switch { case lifespan.NotAfter == lifespan.NotBefore: return "can't extract the token lifespan" case now.Before(lifespan.NotBefore): return "not active yet" case now.After(lifespan.NotAfter): return "expired" default: return "" } }
go
func (i *Inspector) checkLifetime(c context.Context, body proto.Message) string { lifespan := i.Lifespan(body) now := clock.Now(c) switch { case lifespan.NotAfter == lifespan.NotBefore: return "can't extract the token lifespan" case now.Before(lifespan.NotBefore): return "not active yet" case now.After(lifespan.NotAfter): return "expired" default: return "" } }
[ "func", "(", "i", "*", "Inspector", ")", "checkLifetime", "(", "c", "context", ".", "Context", ",", "body", "proto", ".", "Message", ")", "string", "{", "lifespan", ":=", "i", ".", "Lifespan", "(", "body", ")", "\n", "now", ":=", "clock", ".", "Now", "(", "c", ")", "\n", "switch", "{", "case", "lifespan", ".", "NotAfter", "==", "lifespan", ".", "NotBefore", ":", "return", "\"", "\"", "\n", "case", "now", ".", "Before", "(", "lifespan", ".", "NotBefore", ")", ":", "return", "\"", "\"", "\n", "case", "now", ".", "After", "(", "lifespan", ".", "NotAfter", ")", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// checkLifetime checks that token has not expired yet. // // Returns "" if it hasn't expire yet, or an invalidity reason if it has.
[ "checkLifetime", "checks", "that", "token", "has", "not", "expired", "yet", ".", "Returns", "if", "it", "hasn", "t", "expire", "yet", "or", "an", "invalidity", "reason", "if", "it", "has", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/tokensigning/inspector.go#L145-L158
7,499
luci/luci-go
tokenserver/appengine/impl/utils/tokensigning/inspector.go
checkSignature
func (i *Inspector) checkSignature(c context.Context, unwrapped *Unwrapped) (string, error) { certsBundle, err := i.Certificates.Certificates(c) if err != nil { return "", transient.Tag.Apply(err) } cert, err := certsBundle.CertificateForKey(unwrapped.KeyID) if err != nil { return fmt.Sprintf("invalid signing key - %s", err), nil } withCtx := prependSigningContext(unwrapped.Body, i.SigningContext) err = cert.CheckSignature(x509.SHA256WithRSA, withCtx, unwrapped.RsaSHA256Sig) if err != nil { return fmt.Sprintf("bad signature - %s", err), nil } return "", nil }
go
func (i *Inspector) checkSignature(c context.Context, unwrapped *Unwrapped) (string, error) { certsBundle, err := i.Certificates.Certificates(c) if err != nil { return "", transient.Tag.Apply(err) } cert, err := certsBundle.CertificateForKey(unwrapped.KeyID) if err != nil { return fmt.Sprintf("invalid signing key - %s", err), nil } withCtx := prependSigningContext(unwrapped.Body, i.SigningContext) err = cert.CheckSignature(x509.SHA256WithRSA, withCtx, unwrapped.RsaSHA256Sig) if err != nil { return fmt.Sprintf("bad signature - %s", err), nil } return "", nil }
[ "func", "(", "i", "*", "Inspector", ")", "checkSignature", "(", "c", "context", ".", "Context", ",", "unwrapped", "*", "Unwrapped", ")", "(", "string", ",", "error", ")", "{", "certsBundle", ",", "err", ":=", "i", ".", "Certificates", ".", "Certificates", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "cert", ",", "err", ":=", "certsBundle", ".", "CertificateForKey", "(", "unwrapped", ".", "KeyID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ",", "nil", "\n", "}", "\n", "withCtx", ":=", "prependSigningContext", "(", "unwrapped", ".", "Body", ",", "i", ".", "SigningContext", ")", "\n", "err", "=", "cert", ".", "CheckSignature", "(", "x509", ".", "SHA256WithRSA", ",", "withCtx", ",", "unwrapped", ".", "RsaSHA256Sig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "nil", "\n", "}" ]
// checkSignature verifies the signature of the token. // // Returns "" if the signature is correct, or an invalidity reason if it is not.
[ "checkSignature", "verifies", "the", "signature", "of", "the", "token", ".", "Returns", "if", "the", "signature", "is", "correct", "or", "an", "invalidity", "reason", "if", "it", "is", "not", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/tokensigning/inspector.go#L163-L178