id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
8,100
luci/luci-go
lucicfg/normalize/scheduler.go
Scheduler
func Scheduler(c context.Context, cfg *pb.ProjectConfig) error { // Sort jobs by ID. sort.Slice(cfg.Job, func(i, j int) bool { return cfg.Job[i].Id < cfg.Job[j].Id }) sort.Slice(cfg.Trigger, func(i, j int) bool { return cfg.Trigger[i].Id < cfg.Trigger[j].Id }) // ACL set name => list of ACLs. aclSets := make(map[string][]*pb.Acl) for _, s := range cfg.AclSets { aclSets[s.Name] = s.Acls } // Expand ACL sets. for _, x := range cfg.Job { x.Acls = normalizeACLs(x.Acls, x.AclSets, aclSets) x.AclSets = nil } for _, x := range cfg.Trigger { x.Acls = normalizeACLs(x.Acls, x.AclSets, aclSets) x.AclSets = nil } cfg.AclSets = nil // Normalize triggers. for _, x := range cfg.Trigger { sort.Strings(x.Triggers) if gt := x.Gitiles; gt != nil { for i, r := range gt.Refs { if !strings.HasPrefix(r, "regexp:") { gt.Refs[i] = "regexp:" + regexp.QuoteMeta(r) } } sort.Strings(gt.Refs) } } return nil }
go
func Scheduler(c context.Context, cfg *pb.ProjectConfig) error { // Sort jobs by ID. sort.Slice(cfg.Job, func(i, j int) bool { return cfg.Job[i].Id < cfg.Job[j].Id }) sort.Slice(cfg.Trigger, func(i, j int) bool { return cfg.Trigger[i].Id < cfg.Trigger[j].Id }) // ACL set name => list of ACLs. aclSets := make(map[string][]*pb.Acl) for _, s := range cfg.AclSets { aclSets[s.Name] = s.Acls } // Expand ACL sets. for _, x := range cfg.Job { x.Acls = normalizeACLs(x.Acls, x.AclSets, aclSets) x.AclSets = nil } for _, x := range cfg.Trigger { x.Acls = normalizeACLs(x.Acls, x.AclSets, aclSets) x.AclSets = nil } cfg.AclSets = nil // Normalize triggers. for _, x := range cfg.Trigger { sort.Strings(x.Triggers) if gt := x.Gitiles; gt != nil { for i, r := range gt.Refs { if !strings.HasPrefix(r, "regexp:") { gt.Refs[i] = "regexp:" + regexp.QuoteMeta(r) } } sort.Strings(gt.Refs) } } return nil }
[ "func", "Scheduler", "(", "c", "context", ".", "Context", ",", "cfg", "*", "pb", ".", "ProjectConfig", ")", "error", "{", "// Sort jobs by ID.", "sort", ".", "Slice", "(", "cfg", ".", "Job", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "cfg", ".", "Job", "[", "i", "]", ".", "Id", "<", "cfg", ".", "Job", "[", "j", "]", ".", "Id", "\n", "}", ")", "\n", "sort", ".", "Slice", "(", "cfg", ".", "Trigger", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "cfg", ".", "Trigger", "[", "i", "]", ".", "Id", "<", "cfg", ".", "Trigger", "[", "j", "]", ".", "Id", "\n", "}", ")", "\n\n", "// ACL set name => list of ACLs.", "aclSets", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "pb", ".", "Acl", ")", "\n", "for", "_", ",", "s", ":=", "range", "cfg", ".", "AclSets", "{", "aclSets", "[", "s", ".", "Name", "]", "=", "s", ".", "Acls", "\n", "}", "\n\n", "// Expand ACL sets.", "for", "_", ",", "x", ":=", "range", "cfg", ".", "Job", "{", "x", ".", "Acls", "=", "normalizeACLs", "(", "x", ".", "Acls", ",", "x", ".", "AclSets", ",", "aclSets", ")", "\n", "x", ".", "AclSets", "=", "nil", "\n", "}", "\n", "for", "_", ",", "x", ":=", "range", "cfg", ".", "Trigger", "{", "x", ".", "Acls", "=", "normalizeACLs", "(", "x", ".", "Acls", ",", "x", ".", "AclSets", ",", "aclSets", ")", "\n", "x", ".", "AclSets", "=", "nil", "\n", "}", "\n", "cfg", ".", "AclSets", "=", "nil", "\n\n", "// Normalize triggers.", "for", "_", ",", "x", ":=", "range", "cfg", ".", "Trigger", "{", "sort", ".", "Strings", "(", "x", ".", "Triggers", ")", "\n", "if", "gt", ":=", "x", ".", "Gitiles", ";", "gt", "!=", "nil", "{", "for", "i", ",", "r", ":=", "range", "gt", ".", "Refs", "{", "if", "!", "strings", ".", "HasPrefix", "(", "r", ",", "\"", "\"", ")", "{", "gt", ".", "Refs", "[", "i", "]", "=", "\"", "\"", "+", "regexp", ".", "QuoteMeta", "(", "r", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Strings", "(", "gt", ".", "Refs", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Scheduler normalizes luci-scheduler.cfg config.
[ "Scheduler", "normalizes", "luci", "-", "scheduler", ".", "cfg", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/normalize/scheduler.go#L30-L70
8,101
luci/luci-go
appengine/gaemiddleware/appengine.go
RequireCron
func RequireCron(c *router.Context, next router.Handler) { if !devAppserverBypassFn(c.Context) { if c.Request.Header.Get("X-Appengine-Cron") != "true" { logging.Errorf(c.Context, "request not made from cron") http.Error(c.Writer, "error: must be run from cron", http.StatusForbidden) return } } next(c) }
go
func RequireCron(c *router.Context, next router.Handler) { if !devAppserverBypassFn(c.Context) { if c.Request.Header.Get("X-Appengine-Cron") != "true" { logging.Errorf(c.Context, "request not made from cron") http.Error(c.Writer, "error: must be run from cron", http.StatusForbidden) return } } next(c) }
[ "func", "RequireCron", "(", "c", "*", "router", ".", "Context", ",", "next", "router", ".", "Handler", ")", "{", "if", "!", "devAppserverBypassFn", "(", "c", ".", "Context", ")", "{", "if", "c", ".", "Request", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "logging", ".", "Errorf", "(", "c", ".", "Context", ",", "\"", "\"", ")", "\n", "http", ".", "Error", "(", "c", ".", "Writer", ",", "\"", "\"", ",", "http", ".", "StatusForbidden", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "next", "(", "c", ")", "\n", "}" ]
// RequireCron ensures that the request is from the appengine 'cron' service. // // It checks the presence of a magical header that can be set only by GAE. // If the header is not there, it aborts the request with StatusForbidden. // // This middleware has no effect when using 'BaseTest' or when running under // dev_appserver.py
[ "RequireCron", "ensures", "that", "the", "request", "is", "from", "the", "appengine", "cron", "service", ".", "It", "checks", "the", "presence", "of", "a", "magical", "header", "that", "can", "be", "set", "only", "by", "GAE", ".", "If", "the", "header", "is", "not", "there", "it", "aborts", "the", "request", "with", "StatusForbidden", ".", "This", "middleware", "has", "no", "effect", "when", "using", "BaseTest", "or", "when", "running", "under", "dev_appserver", ".", "py" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaemiddleware/appengine.go#L34-L43
8,102
luci/luci-go
appengine/gaemiddleware/appengine.go
RequireTaskQueue
func RequireTaskQueue(queue string) router.Middleware { return func(c *router.Context, next router.Handler) { if !devAppserverBypassFn(c.Context) { qName := c.Request.Header.Get("X-AppEngine-QueueName") if qName == "" || (queue != "" && queue != qName) { logging.Errorf(c.Context, "request made from wrong taskqueue: %q v %q", qName, queue) http.Error(c.Writer, "error: must be run from the correct taskqueue", http.StatusForbidden) return } } next(c) } }
go
func RequireTaskQueue(queue string) router.Middleware { return func(c *router.Context, next router.Handler) { if !devAppserverBypassFn(c.Context) { qName := c.Request.Header.Get("X-AppEngine-QueueName") if qName == "" || (queue != "" && queue != qName) { logging.Errorf(c.Context, "request made from wrong taskqueue: %q v %q", qName, queue) http.Error(c.Writer, "error: must be run from the correct taskqueue", http.StatusForbidden) return } } next(c) } }
[ "func", "RequireTaskQueue", "(", "queue", "string", ")", "router", ".", "Middleware", "{", "return", "func", "(", "c", "*", "router", ".", "Context", ",", "next", "router", ".", "Handler", ")", "{", "if", "!", "devAppserverBypassFn", "(", "c", ".", "Context", ")", "{", "qName", ":=", "c", ".", "Request", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "qName", "==", "\"", "\"", "||", "(", "queue", "!=", "\"", "\"", "&&", "queue", "!=", "qName", ")", "{", "logging", ".", "Errorf", "(", "c", ".", "Context", ",", "\"", "\"", ",", "qName", ",", "queue", ")", "\n", "http", ".", "Error", "(", "c", ".", "Writer", ",", "\"", "\"", ",", "http", ".", "StatusForbidden", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "next", "(", "c", ")", "\n", "}", "\n", "}" ]
// RequireTaskQueue ensures that the request is from the specified task queue. // // It checks the presence of a magical header that can be set only by GAE. // If the header is not there, it aborts the request with StatusForbidden. // // if 'queue' is the empty string, than this simply checks that this handler was // run from ANY appengine taskqueue. // // This middleware has no effect when using 'BaseTest' or when running under // dev_appserver.py
[ "RequireTaskQueue", "ensures", "that", "the", "request", "is", "from", "the", "specified", "task", "queue", ".", "It", "checks", "the", "presence", "of", "a", "magical", "header", "that", "can", "be", "set", "only", "by", "GAE", ".", "If", "the", "header", "is", "not", "there", "it", "aborts", "the", "request", "with", "StatusForbidden", ".", "if", "queue", "is", "the", "empty", "string", "than", "this", "simply", "checks", "that", "this", "handler", "was", "run", "from", "ANY", "appengine", "taskqueue", ".", "This", "middleware", "has", "no", "effect", "when", "using", "BaseTest", "or", "when", "running", "under", "dev_appserver", ".", "py" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaemiddleware/appengine.go#L55-L67
8,103
luci/luci-go
auth/internal/gce.go
NewGCETokenProvider
func NewGCETokenProvider(ctx context.Context, account string, scopes []string) (TokenProvider, error) { // Grab an email associated with the account. This must not be failing on // a healthy VM if the account is present. If it does, the metadata server is // broken. email, err := metadata.Get("instance/service-accounts/" + account + "/email") if err != nil { if _, yep := err.(metadata.NotDefinedError); yep { return nil, ErrInsufficientAccess } return nil, err } // Ensure account has requested scopes. availableScopes, err := metadata.Scopes(account) if err != nil { return nil, err } availableSet := stringset.NewFromSlice(availableScopes...) for _, requested := range scopes { if !availableSet.Has(requested) { logging.Warningf(ctx, "GCE service account %q doesn't have required scope %q", account, requested) return nil, ErrInsufficientAccess } } return &gceTokenProvider{ account: account, email: email, cacheKey: CacheKey{ Key: fmt.Sprintf("gce/%s", account), Scopes: scopes, }, }, nil }
go
func NewGCETokenProvider(ctx context.Context, account string, scopes []string) (TokenProvider, error) { // Grab an email associated with the account. This must not be failing on // a healthy VM if the account is present. If it does, the metadata server is // broken. email, err := metadata.Get("instance/service-accounts/" + account + "/email") if err != nil { if _, yep := err.(metadata.NotDefinedError); yep { return nil, ErrInsufficientAccess } return nil, err } // Ensure account has requested scopes. availableScopes, err := metadata.Scopes(account) if err != nil { return nil, err } availableSet := stringset.NewFromSlice(availableScopes...) for _, requested := range scopes { if !availableSet.Has(requested) { logging.Warningf(ctx, "GCE service account %q doesn't have required scope %q", account, requested) return nil, ErrInsufficientAccess } } return &gceTokenProvider{ account: account, email: email, cacheKey: CacheKey{ Key: fmt.Sprintf("gce/%s", account), Scopes: scopes, }, }, nil }
[ "func", "NewGCETokenProvider", "(", "ctx", "context", ".", "Context", ",", "account", "string", ",", "scopes", "[", "]", "string", ")", "(", "TokenProvider", ",", "error", ")", "{", "// Grab an email associated with the account. This must not be failing on", "// a healthy VM if the account is present. If it does, the metadata server is", "// broken.", "email", ",", "err", ":=", "metadata", ".", "Get", "(", "\"", "\"", "+", "account", "+", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "yep", ":=", "err", ".", "(", "metadata", ".", "NotDefinedError", ")", ";", "yep", "{", "return", "nil", ",", "ErrInsufficientAccess", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Ensure account has requested scopes.", "availableScopes", ",", "err", ":=", "metadata", ".", "Scopes", "(", "account", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "availableSet", ":=", "stringset", ".", "NewFromSlice", "(", "availableScopes", "...", ")", "\n", "for", "_", ",", "requested", ":=", "range", "scopes", "{", "if", "!", "availableSet", ".", "Has", "(", "requested", ")", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "account", ",", "requested", ")", "\n", "return", "nil", ",", "ErrInsufficientAccess", "\n", "}", "\n", "}", "\n\n", "return", "&", "gceTokenProvider", "{", "account", ":", "account", ",", "email", ":", "email", ",", "cacheKey", ":", "CacheKey", "{", "Key", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "account", ")", ",", "Scopes", ":", "scopes", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// NewGCETokenProvider returns TokenProvider that knows how to use GCE metadata server.
[ "NewGCETokenProvider", "returns", "TokenProvider", "that", "knows", "how", "to", "use", "GCE", "metadata", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/internal/gce.go#L36-L69
8,104
luci/luci-go
appengine/gaemiddleware/context.go
ensurePrepared
func (e *Environment) ensurePrepared(c context.Context) { e.prepareOnce.Do(func() { e.processCacheData = caching.NewProcessCacheData() e.globalSettings = settings.New(gaesettings.Storage{}) if e.Prepare != nil { e.Prepare(c) } }) }
go
func (e *Environment) ensurePrepared(c context.Context) { e.prepareOnce.Do(func() { e.processCacheData = caching.NewProcessCacheData() e.globalSettings = settings.New(gaesettings.Storage{}) if e.Prepare != nil { e.Prepare(c) } }) }
[ "func", "(", "e", "*", "Environment", ")", "ensurePrepared", "(", "c", "context", ".", "Context", ")", "{", "e", ".", "prepareOnce", ".", "Do", "(", "func", "(", ")", "{", "e", ".", "processCacheData", "=", "caching", ".", "NewProcessCacheData", "(", ")", "\n", "e", ".", "globalSettings", "=", "settings", ".", "New", "(", "gaesettings", ".", "Storage", "{", "}", ")", "\n", "if", "e", ".", "Prepare", "!=", "nil", "{", "e", ".", "Prepare", "(", "c", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// ensurePrepared is called before handling requests to initialize global state.
[ "ensurePrepared", "is", "called", "before", "handling", "requests", "to", "initialize", "global", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaemiddleware/context.go#L111-L119
8,105
luci/luci-go
appengine/gaemiddleware/context.go
InstallHandlers
func (e *Environment) InstallHandlers(r *router.Router) { e.InstallHandlersWithMiddleware(r, e.Base()) }
go
func (e *Environment) InstallHandlers(r *router.Router) { e.InstallHandlersWithMiddleware(r, e.Base()) }
[ "func", "(", "e", "*", "Environment", ")", "InstallHandlers", "(", "r", "*", "router", ".", "Router", ")", "{", "e", ".", "InstallHandlersWithMiddleware", "(", "r", ",", "e", ".", "Base", "(", ")", ")", "\n", "}" ]
// InstallHandlers installs handlers for an Environment's framework routes. // // See InstallHandlersWithMiddleware for more information.
[ "InstallHandlers", "installs", "handlers", "for", "an", "Environment", "s", "framework", "routes", ".", "See", "InstallHandlersWithMiddleware", "for", "more", "information", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaemiddleware/context.go#L124-L126
8,106
luci/luci-go
common/data/text/templateproto/render.go
Convert
func (m LiteralMap) Convert() (map[string]*Value, error) { ret := make(map[string]*Value, len(m)) for k, v := range m { v, err := NewValue(v) if err != nil { return nil, fmt.Errorf("key %q: %s", k, err) } ret[k] = v } return ret, nil }
go
func (m LiteralMap) Convert() (map[string]*Value, error) { ret := make(map[string]*Value, len(m)) for k, v := range m { v, err := NewValue(v) if err != nil { return nil, fmt.Errorf("key %q: %s", k, err) } ret[k] = v } return ret, nil }
[ "func", "(", "m", "LiteralMap", ")", "Convert", "(", ")", "(", "map", "[", "string", "]", "*", "Value", ",", "error", ")", "{", "ret", ":=", "make", "(", "map", "[", "string", "]", "*", "Value", ",", "len", "(", "m", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "m", "{", "v", ",", "err", ":=", "NewValue", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ",", "err", ")", "\n", "}", "\n", "ret", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// Convert converts this to a parameter map that can be used with // Template.Render.
[ "Convert", "converts", "this", "to", "a", "parameter", "map", "that", "can", "be", "used", "with", "Template", ".", "Render", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/render.go#L90-L100
8,107
luci/luci-go
common/data/text/templateproto/render.go
RenderL
func (t *File_Template) RenderL(m LiteralMap) (string, error) { pm, err := m.Convert() if err != nil { return "", err } return t.Render(pm) }
go
func (t *File_Template) RenderL(m LiteralMap) (string, error) { pm, err := m.Convert() if err != nil { return "", err } return t.Render(pm) }
[ "func", "(", "t", "*", "File_Template", ")", "RenderL", "(", "m", "LiteralMap", ")", "(", "string", ",", "error", ")", "{", "pm", ",", "err", ":=", "m", ".", "Convert", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "t", ".", "Render", "(", "pm", ")", "\n", "}" ]
// RenderL renders this template with a LiteralMap, calling its Convert method // and passing the result to Render.
[ "RenderL", "renders", "this", "template", "with", "a", "LiteralMap", "calling", "its", "Convert", "method", "and", "passing", "the", "result", "to", "Render", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/render.go#L104-L110
8,108
luci/luci-go
common/data/text/templateproto/render.go
Render
func (t *File_Template) Render(params map[string]*Value) (string, error) { sSet := stringset.New(len(params)) replacementSlice := make([]string, 0, len(t.Param)*2) for k, param := range t.Param { replacementSlice = append(replacementSlice, k) if newVal, ok := params[k]; ok { if err := param.Accepts(newVal); err != nil { return "", fmt.Errorf("param %q: %s", k, err) } sSet.Add(k) replacementSlice = append(replacementSlice, newVal.JSONRender()) } else if param.Default != nil { replacementSlice = append(replacementSlice, param.Default.JSONRender()) } else { return "", fmt.Errorf("param %q: missing", k) } } if len(params) != sSet.Len() { unknown := make([]string, 0, len(params)) for k := range params { if !sSet.Has(k) { unknown = append(unknown, k) } } sort.Strings(unknown) return "", fmt.Errorf("unknown parameters: %q", unknown) } r := strings.NewReplacer(replacementSlice...) return r.Replace(t.Body), nil }
go
func (t *File_Template) Render(params map[string]*Value) (string, error) { sSet := stringset.New(len(params)) replacementSlice := make([]string, 0, len(t.Param)*2) for k, param := range t.Param { replacementSlice = append(replacementSlice, k) if newVal, ok := params[k]; ok { if err := param.Accepts(newVal); err != nil { return "", fmt.Errorf("param %q: %s", k, err) } sSet.Add(k) replacementSlice = append(replacementSlice, newVal.JSONRender()) } else if param.Default != nil { replacementSlice = append(replacementSlice, param.Default.JSONRender()) } else { return "", fmt.Errorf("param %q: missing", k) } } if len(params) != sSet.Len() { unknown := make([]string, 0, len(params)) for k := range params { if !sSet.Has(k) { unknown = append(unknown, k) } } sort.Strings(unknown) return "", fmt.Errorf("unknown parameters: %q", unknown) } r := strings.NewReplacer(replacementSlice...) return r.Replace(t.Body), nil }
[ "func", "(", "t", "*", "File_Template", ")", "Render", "(", "params", "map", "[", "string", "]", "*", "Value", ")", "(", "string", ",", "error", ")", "{", "sSet", ":=", "stringset", ".", "New", "(", "len", "(", "params", ")", ")", "\n", "replacementSlice", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "t", ".", "Param", ")", "*", "2", ")", "\n", "for", "k", ",", "param", ":=", "range", "t", ".", "Param", "{", "replacementSlice", "=", "append", "(", "replacementSlice", ",", "k", ")", "\n", "if", "newVal", ",", "ok", ":=", "params", "[", "k", "]", ";", "ok", "{", "if", "err", ":=", "param", ".", "Accepts", "(", "newVal", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ",", "err", ")", "\n", "}", "\n", "sSet", ".", "Add", "(", "k", ")", "\n", "replacementSlice", "=", "append", "(", "replacementSlice", ",", "newVal", ".", "JSONRender", "(", ")", ")", "\n", "}", "else", "if", "param", ".", "Default", "!=", "nil", "{", "replacementSlice", "=", "append", "(", "replacementSlice", ",", "param", ".", "Default", ".", "JSONRender", "(", ")", ")", "\n", "}", "else", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "params", ")", "!=", "sSet", ".", "Len", "(", ")", "{", "unknown", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "params", ")", ")", "\n", "for", "k", ":=", "range", "params", "{", "if", "!", "sSet", ".", "Has", "(", "k", ")", "{", "unknown", "=", "append", "(", "unknown", ",", "k", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Strings", "(", "unknown", ")", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "unknown", ")", "\n", "}", "\n\n", "r", ":=", "strings", ".", "NewReplacer", "(", "replacementSlice", "...", ")", "\n\n", "return", "r", ".", "Replace", "(", "t", ".", "Body", ")", ",", "nil", "\n", "}" ]
// Render turns the Template into a JSON document, filled with the given // parameters. It does not validate that the output is valid JSON, but if you // called Normalize on this Template already, then it WILL be valid JSON.
[ "Render", "turns", "the", "Template", "into", "a", "JSON", "document", "filled", "with", "the", "given", "parameters", ".", "It", "does", "not", "validate", "that", "the", "output", "is", "valid", "JSON", "but", "if", "you", "called", "Normalize", "on", "this", "Template", "already", "then", "it", "WILL", "be", "valid", "JSON", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/render.go#L115-L146
8,109
luci/luci-go
machine-db/common/ips.go
String
func (i IPv4) String() string { ip := make(net.IP, 4) binary.BigEndian.PutUint32(ip, uint32(i)) return ip.String() }
go
func (i IPv4) String() string { ip := make(net.IP, 4) binary.BigEndian.PutUint32(ip, uint32(i)) return ip.String() }
[ "func", "(", "i", "IPv4", ")", "String", "(", ")", "string", "{", "ip", ":=", "make", "(", "net", ".", "IP", ",", "4", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "ip", ",", "uint32", "(", "i", ")", ")", "\n", "return", "ip", ".", "String", "(", ")", "\n", "}" ]
// String returns a string representation of this IPv4 address.
[ "String", "returns", "a", "string", "representation", "of", "this", "IPv4", "address", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/common/ips.go#L29-L33
8,110
luci/luci-go
machine-db/common/ips.go
IPv4Range
func IPv4Range(block string) (IPv4, int64, error) { ip, subnet, err := net.ParseCIDR(block) if err != nil { return 0, 0, errors.Reason("invalid CIDR block %q", block).Err() } ipv4 := ip.Mask(subnet.Mask).To4() if ipv4 == nil { return 0, 0, errors.Reason("invalid IPv4 CIDR block %q", block).Err() } ones, _ := subnet.Mask.Size() return IPv4(binary.BigEndian.Uint32(ipv4)), 1 << uint32(32-ones), nil }
go
func IPv4Range(block string) (IPv4, int64, error) { ip, subnet, err := net.ParseCIDR(block) if err != nil { return 0, 0, errors.Reason("invalid CIDR block %q", block).Err() } ipv4 := ip.Mask(subnet.Mask).To4() if ipv4 == nil { return 0, 0, errors.Reason("invalid IPv4 CIDR block %q", block).Err() } ones, _ := subnet.Mask.Size() return IPv4(binary.BigEndian.Uint32(ipv4)), 1 << uint32(32-ones), nil }
[ "func", "IPv4Range", "(", "block", "string", ")", "(", "IPv4", ",", "int64", ",", "error", ")", "{", "ip", ",", "subnet", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "block", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "block", ")", ".", "Err", "(", ")", "\n", "}", "\n", "ipv4", ":=", "ip", ".", "Mask", "(", "subnet", ".", "Mask", ")", ".", "To4", "(", ")", "\n", "if", "ipv4", "==", "nil", "{", "return", "0", ",", "0", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "block", ")", ".", "Err", "(", ")", "\n", "}", "\n", "ones", ",", "_", ":=", "subnet", ".", "Mask", ".", "Size", "(", ")", "\n", "return", "IPv4", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "ipv4", ")", ")", ",", "1", "<<", "uint32", "(", "32", "-", "ones", ")", ",", "nil", "\n", "}" ]
// IPv4Range returns the starting address and length of the given IPv4 CIDR block.
[ "IPv4Range", "returns", "the", "starting", "address", "and", "length", "of", "the", "given", "IPv4", "CIDR", "block", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/common/ips.go#L36-L47
8,111
luci/luci-go
machine-db/common/ips.go
ParseIPv4
func ParseIPv4(s string) (IPv4, error) { ip := net.ParseIP(s) if ip != nil { ip = ip.To4() } if ip == nil { return 0, errors.Reason("invalid IPv4 address %q", s).Err() } return IPv4(binary.BigEndian.Uint32(ip)), nil }
go
func ParseIPv4(s string) (IPv4, error) { ip := net.ParseIP(s) if ip != nil { ip = ip.To4() } if ip == nil { return 0, errors.Reason("invalid IPv4 address %q", s).Err() } return IPv4(binary.BigEndian.Uint32(ip)), nil }
[ "func", "ParseIPv4", "(", "s", "string", ")", "(", "IPv4", ",", "error", ")", "{", "ip", ":=", "net", ".", "ParseIP", "(", "s", ")", "\n", "if", "ip", "!=", "nil", "{", "ip", "=", "ip", ".", "To4", "(", ")", "\n", "}", "\n", "if", "ip", "==", "nil", "{", "return", "0", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "s", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "IPv4", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "ip", ")", ")", ",", "nil", "\n", "}" ]
// ParseIPv4 returns an IPv4 address from the given string.
[ "ParseIPv4", "returns", "an", "IPv4", "address", "from", "the", "given", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/common/ips.go#L50-L59
8,112
luci/luci-go
logdog/client/cmd/logdog_butler/stream.go
properties
func (s streamConfig) properties() *streamproto.Properties { if s.ContentType == "" { // Choose content type based on format. s.ContentType = string(s.Type.DefaultContentType()) } return s.Properties() }
go
func (s streamConfig) properties() *streamproto.Properties { if s.ContentType == "" { // Choose content type based on format. s.ContentType = string(s.Type.DefaultContentType()) } return s.Properties() }
[ "func", "(", "s", "streamConfig", ")", "properties", "(", ")", "*", "streamproto", ".", "Properties", "{", "if", "s", ".", "ContentType", "==", "\"", "\"", "{", "// Choose content type based on format.", "s", ".", "ContentType", "=", "string", "(", "s", ".", "Type", ".", "DefaultContentType", "(", ")", ")", "\n", "}", "\n", "return", "s", ".", "Properties", "(", ")", "\n", "}" ]
// Converts command-line parameters into a stream.Config.
[ "Converts", "command", "-", "line", "parameters", "into", "a", "stream", ".", "Config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/stream.go#L52-L58
8,113
luci/luci-go
machine-db/client/cli/vms.go
printVMs
func printVMs(tsv bool, vms ...*crimson.VM) { if len(vms) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("Name", "VLAN", "IP Address", "Host", "Host VLAN", "Operating System", "Description", "Deployment Ticket", "State") } for _, vm := range vms { p.Row(vm.Name, vm.Vlan, vm.Ipv4, vm.Host, vm.HostVlan, vm.Os, vm.Description, vm.DeploymentTicket, vm.State) } } }
go
func printVMs(tsv bool, vms ...*crimson.VM) { if len(vms) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("Name", "VLAN", "IP Address", "Host", "Host VLAN", "Operating System", "Description", "Deployment Ticket", "State") } for _, vm := range vms { p.Row(vm.Name, vm.Vlan, vm.Ipv4, vm.Host, vm.HostVlan, vm.Os, vm.Description, vm.DeploymentTicket, vm.State) } } }
[ "func", "printVMs", "(", "tsv", "bool", ",", "vms", "...", "*", "crimson", ".", "VM", ")", "{", "if", "len", "(", "vms", ")", ">", "0", "{", "p", ":=", "newStdoutPrinter", "(", "tsv", ")", "\n", "defer", "p", ".", "Flush", "(", ")", "\n", "if", "!", "tsv", "{", "p", ".", "Row", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "vm", ":=", "range", "vms", "{", "p", ".", "Row", "(", "vm", ".", "Name", ",", "vm", ".", "Vlan", ",", "vm", ".", "Ipv4", ",", "vm", ".", "Host", ",", "vm", ".", "HostVlan", ",", "vm", ".", "Os", ",", "vm", ".", "Description", ",", "vm", ".", "DeploymentTicket", ",", "vm", ".", "State", ")", "\n", "}", "\n", "}", "\n", "}" ]
// printVMs prints VM data to stdout in tab-separated columns.
[ "printVMs", "prints", "VM", "data", "to", "stdout", "in", "tab", "-", "separated", "columns", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vms.go#L28-L39
8,114
luci/luci-go
machine-db/client/cli/vms.go
Run
func (c *AddVMCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.CreateVMRequest{ Vm: &c.vm, } client := getClient(ctx) resp, err := client.CreateVM(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printVMs(c.f.tsv, resp) return 0 }
go
func (c *AddVMCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.CreateVMRequest{ Vm: &c.vm, } client := getClient(ctx) resp, err := client.CreateVM(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printVMs(c.f.tsv, resp) return 0 }
[ "func", "(", "c", "*", "AddVMCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",", "env", ")", "\n", "// TODO(smut): Validate required fields client-side.", "req", ":=", "&", "crimson", ".", "CreateVMRequest", "{", "Vm", ":", "&", "c", ".", "vm", ",", "}", "\n", "client", ":=", "getClient", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "client", ".", "CreateVM", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Log", "(", "ctx", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "printVMs", "(", "c", ".", "f", ".", "tsv", ",", "resp", ")", "\n", "return", "0", "\n", "}" ]
// Run runs the command to add a VM.
[ "Run", "runs", "the", "command", "to", "add", "a", "VM", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vms.go#L48-L62
8,115
luci/luci-go
machine-db/client/cli/vms.go
addVMCmd
func addVMCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "add-vm -name <name> -host <name> -os <os> -ip <ip address> -state <state> [-desc <description>] [-tick <deployment ticket>]", ShortDesc: "adds a VM", LongDesc: "Adds a VM to the database.\n\nExample:\ncrimson add-vm -name vm100-x1 -host esxhost1 -os Windows -ip 99.99.99.99 -state prerelease -desc 'test VM' -tick crbug/111111", CommandRun: func() subcommands.CommandRun { cmd := &AddVMCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.vm.Name, "name", "", "The name of this VM on the network. Required and must be unique within the database.") cmd.Flags.StringVar(&cmd.vm.Host, "host", "", "The physical host backing this VM. Required and must be the name of a physical host returned by get-hosts.") cmd.Flags.Var(StateFlag(&cmd.vm.State), "state", "The state of this VM. Required and must be the name of a state returned by get-states.") cmd.Flags.StringVar(&cmd.vm.Os, "os", "", "The operating system this host is running. Required and must be the name of an operating system returned by get-oses.") cmd.Flags.StringVar(&cmd.vm.Ipv4, "ip", "", "The IPv4 address assigned to this host. Required and must be a free IP address returned by get-ips.") cmd.Flags.StringVar(&cmd.vm.Description, "desc", "", "A description of this host.") cmd.Flags.StringVar(&cmd.vm.DeploymentTicket, "tick", "", "The deployment ticket associated with this host.") return cmd }, } }
go
func addVMCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "add-vm -name <name> -host <name> -os <os> -ip <ip address> -state <state> [-desc <description>] [-tick <deployment ticket>]", ShortDesc: "adds a VM", LongDesc: "Adds a VM to the database.\n\nExample:\ncrimson add-vm -name vm100-x1 -host esxhost1 -os Windows -ip 99.99.99.99 -state prerelease -desc 'test VM' -tick crbug/111111", CommandRun: func() subcommands.CommandRun { cmd := &AddVMCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.vm.Name, "name", "", "The name of this VM on the network. Required and must be unique within the database.") cmd.Flags.StringVar(&cmd.vm.Host, "host", "", "The physical host backing this VM. Required and must be the name of a physical host returned by get-hosts.") cmd.Flags.Var(StateFlag(&cmd.vm.State), "state", "The state of this VM. Required and must be the name of a state returned by get-states.") cmd.Flags.StringVar(&cmd.vm.Os, "os", "", "The operating system this host is running. Required and must be the name of an operating system returned by get-oses.") cmd.Flags.StringVar(&cmd.vm.Ipv4, "ip", "", "The IPv4 address assigned to this host. Required and must be a free IP address returned by get-ips.") cmd.Flags.StringVar(&cmd.vm.Description, "desc", "", "A description of this host.") cmd.Flags.StringVar(&cmd.vm.DeploymentTicket, "tick", "", "The deployment ticket associated with this host.") return cmd }, } }
[ "func", "addVMCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", "\\n", "\\n", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "cmd", ":=", "&", "AddVMCmd", "{", "}", "\n", "cmd", ".", "Initialize", "(", "params", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "vm", ".", "Name", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "vm", ".", "Host", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "StateFlag", "(", "&", "cmd", ".", "vm", ".", "State", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "vm", ".", "Os", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "vm", ".", "Ipv4", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "vm", ".", "Description", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "vm", ".", "DeploymentTicket", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}", ",", "}", "\n", "}" ]
// addVMCmd returns a command to add a VM.
[ "addVMCmd", "returns", "a", "command", "to", "add", "a", "VM", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vms.go#L65-L83
8,116
luci/luci-go
machine-db/client/cli/vms.go
Run
func (c *GetVMsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListVMs(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printVMs(c.f.tsv, resp.Vms...) return 0 }
go
func (c *GetVMsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListVMs(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printVMs(c.f.tsv, resp.Vms...) return 0 }
[ "func", "(", "c", "*", "GetVMsCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",", "env", ")", "\n", "client", ":=", "getClient", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "client", ".", "ListVMs", "(", "ctx", ",", "&", "c", ".", "req", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Log", "(", "ctx", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "printVMs", "(", "c", ".", "f", ".", "tsv", ",", "resp", ".", "Vms", "...", ")", "\n", "return", "0", "\n", "}" ]
// Run runs the command to get VMs.
[ "Run", "runs", "the", "command", "to", "get", "VMs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vms.go#L142-L152
8,117
luci/luci-go
machine-db/client/cli/vms.go
getVMsCmd
func getVMsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-vms [-name <name>]... [-vlan <id>]... [-ip <ip address>]...", ShortDesc: "retrieves VMs", LongDesc: "Retrieves VMs matching the given names and VLANs, or all VMs if names and VLANs are omitted.\n\nExample to get all VMs:\ncrimson get-vms\nExample to get VMs on ESX host esxhost1:\ncrimson get-vms -host esxhost1", CommandRun: func() subcommands.CommandRun { cmd := &GetVMsCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a VM to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.Int64Slice(&cmd.req.Vlans), "vlan", "ID of a VLAN to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Hosts), "host", "Name of a host to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.Int64Slice(&cmd.req.HostVlans), "hvlan", "ID of a host VLAN to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Oses), "os", "Name of an operating system to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Ipv4S), "ip", "IPv4 address to filter by. Can be specified multiple times.") cmd.Flags.Var(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.") return cmd }, } }
go
func getVMsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-vms [-name <name>]... [-vlan <id>]... [-ip <ip address>]...", ShortDesc: "retrieves VMs", LongDesc: "Retrieves VMs matching the given names and VLANs, or all VMs if names and VLANs are omitted.\n\nExample to get all VMs:\ncrimson get-vms\nExample to get VMs on ESX host esxhost1:\ncrimson get-vms -host esxhost1", CommandRun: func() subcommands.CommandRun { cmd := &GetVMsCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a VM to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.Int64Slice(&cmd.req.Vlans), "vlan", "ID of a VLAN to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Hosts), "host", "Name of a host to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.Int64Slice(&cmd.req.HostVlans), "hvlan", "ID of a host VLAN to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Oses), "os", "Name of an operating system to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Ipv4S), "ip", "IPv4 address to filter by. Can be specified multiple times.") cmd.Flags.Var(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.") return cmd }, } }
[ "func", "getVMsCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", "\\n", "\\n", "\\n", "\\n", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "cmd", ":=", "&", "GetVMsCmd", "{", "}", "\n", "cmd", ".", "Initialize", "(", "params", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Names", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "Int64Slice", "(", "&", "cmd", ".", "req", ".", "Vlans", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Hosts", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "Int64Slice", "(", "&", "cmd", ".", "req", ".", "HostVlans", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Oses", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Ipv4S", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "StateSliceFlag", "(", "&", "cmd", ".", "req", ".", "States", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}", ",", "}", "\n", "}" ]
// getVMsCmd returns a command to get VMs.
[ "getVMsCmd", "returns", "a", "command", "to", "get", "VMs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vms.go#L155-L173
8,118
luci/luci-go
common/data/sortby/sortby.go
Use
func (c Chain) Use(i, j int) bool { for _, less := range c { if less == nil { continue } if less(i, j) { return true } else if less(j, i) { return false } } return false }
go
func (c Chain) Use(i, j int) bool { for _, less := range c { if less == nil { continue } if less(i, j) { return true } else if less(j, i) { return false } } return false }
[ "func", "(", "c", "Chain", ")", "Use", "(", "i", ",", "j", "int", ")", "bool", "{", "for", "_", ",", "less", ":=", "range", "c", "{", "if", "less", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "less", "(", "i", ",", "j", ")", "{", "return", "true", "\n", "}", "else", "if", "less", "(", "j", ",", "i", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Use is a sort-compatible LessFn that actually executes the full chain of // comparisons.
[ "Use", "is", "a", "sort", "-", "compatible", "LessFn", "that", "actually", "executes", "the", "full", "chain", "of", "comparisons", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/sortby/sortby.go#L32-L44
8,119
luci/luci-go
tokenserver/appengine/impl/serviceaccounts/rpc_inspect_oauth_token_grant.go
InspectOAuthTokenGrant
func (r *InspectOAuthTokenGrantRPC) InspectOAuthTokenGrant(c context.Context, req *admin.InspectOAuthTokenGrantRequest) (*admin.InspectOAuthTokenGrantResponse, error) { inspection, err := InspectGrant(c, r.Signer, req.Token) if err != nil { return nil, status.Errorf(codes.Internal, err.Error()) } resp := &admin.InspectOAuthTokenGrantResponse{ Valid: inspection.Signed && inspection.NonExpired, Signed: inspection.Signed, NonExpired: inspection.NonExpired, InvalidityReason: inspection.InvalidityReason, } addInvalidityReason := func(msg string, args ...interface{}) { reason := fmt.Sprintf(msg, args...) resp.Valid = false if resp.InvalidityReason == "" { resp.InvalidityReason = reason } else { resp.InvalidityReason += "; " + reason } } if env, _ := inspection.Envelope.(*tokenserver.OAuthTokenGrantEnvelope); env != nil { resp.SigningKeyId = env.KeyId } // Examine the body, even if the token is expired or unsigned. This helps to // debug expired or unsigned tokens... resp.TokenBody, _ = inspection.Body.(*tokenserver.OAuthTokenGrantBody) if resp.TokenBody != nil { rules, err := r.Rules(c) if err != nil { return nil, status.Errorf(codes.Internal, "failed to load service accounts rules") } // Always return the rule that matches the service account, even if the // token itself is not allowed by it (we check it separately below). rule, err := rules.Rule(c, resp.TokenBody.ServiceAccount, "") switch { case status.Code(err) == codes.PermissionDenied: s, _ := status.FromError(err) addInvalidityReason("%s", s.Message()) return resp, nil case err != nil: // usually codes.Internal return nil, err default: resp.MatchingRule = rule.Rule } q := &RulesQuery{ ServiceAccount: resp.TokenBody.ServiceAccount, Rule: rule, Proxy: identity.Identity(resp.TokenBody.Proxy), EndUser: identity.Identity(resp.TokenBody.EndUser), } switch _, err = rules.Check(c, q); { case err == nil: resp.AllowedByRules = true case status.Code(err) == codes.Internal: return nil, err // a transient error when checking rules default: // fatal gRPC error => the rules forbid the token addInvalidityReason("not allowed by the rules (rev %s)", rules.ConfigRevision()) } } return resp, nil }
go
func (r *InspectOAuthTokenGrantRPC) InspectOAuthTokenGrant(c context.Context, req *admin.InspectOAuthTokenGrantRequest) (*admin.InspectOAuthTokenGrantResponse, error) { inspection, err := InspectGrant(c, r.Signer, req.Token) if err != nil { return nil, status.Errorf(codes.Internal, err.Error()) } resp := &admin.InspectOAuthTokenGrantResponse{ Valid: inspection.Signed && inspection.NonExpired, Signed: inspection.Signed, NonExpired: inspection.NonExpired, InvalidityReason: inspection.InvalidityReason, } addInvalidityReason := func(msg string, args ...interface{}) { reason := fmt.Sprintf(msg, args...) resp.Valid = false if resp.InvalidityReason == "" { resp.InvalidityReason = reason } else { resp.InvalidityReason += "; " + reason } } if env, _ := inspection.Envelope.(*tokenserver.OAuthTokenGrantEnvelope); env != nil { resp.SigningKeyId = env.KeyId } // Examine the body, even if the token is expired or unsigned. This helps to // debug expired or unsigned tokens... resp.TokenBody, _ = inspection.Body.(*tokenserver.OAuthTokenGrantBody) if resp.TokenBody != nil { rules, err := r.Rules(c) if err != nil { return nil, status.Errorf(codes.Internal, "failed to load service accounts rules") } // Always return the rule that matches the service account, even if the // token itself is not allowed by it (we check it separately below). rule, err := rules.Rule(c, resp.TokenBody.ServiceAccount, "") switch { case status.Code(err) == codes.PermissionDenied: s, _ := status.FromError(err) addInvalidityReason("%s", s.Message()) return resp, nil case err != nil: // usually codes.Internal return nil, err default: resp.MatchingRule = rule.Rule } q := &RulesQuery{ ServiceAccount: resp.TokenBody.ServiceAccount, Rule: rule, Proxy: identity.Identity(resp.TokenBody.Proxy), EndUser: identity.Identity(resp.TokenBody.EndUser), } switch _, err = rules.Check(c, q); { case err == nil: resp.AllowedByRules = true case status.Code(err) == codes.Internal: return nil, err // a transient error when checking rules default: // fatal gRPC error => the rules forbid the token addInvalidityReason("not allowed by the rules (rev %s)", rules.ConfigRevision()) } } return resp, nil }
[ "func", "(", "r", "*", "InspectOAuthTokenGrantRPC", ")", "InspectOAuthTokenGrant", "(", "c", "context", ".", "Context", ",", "req", "*", "admin", ".", "InspectOAuthTokenGrantRequest", ")", "(", "*", "admin", ".", "InspectOAuthTokenGrantResponse", ",", "error", ")", "{", "inspection", ",", "err", ":=", "InspectGrant", "(", "c", ",", "r", ".", "Signer", ",", "req", ".", "Token", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "resp", ":=", "&", "admin", ".", "InspectOAuthTokenGrantResponse", "{", "Valid", ":", "inspection", ".", "Signed", "&&", "inspection", ".", "NonExpired", ",", "Signed", ":", "inspection", ".", "Signed", ",", "NonExpired", ":", "inspection", ".", "NonExpired", ",", "InvalidityReason", ":", "inspection", ".", "InvalidityReason", ",", "}", "\n\n", "addInvalidityReason", ":=", "func", "(", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "reason", ":=", "fmt", ".", "Sprintf", "(", "msg", ",", "args", "...", ")", "\n", "resp", ".", "Valid", "=", "false", "\n", "if", "resp", ".", "InvalidityReason", "==", "\"", "\"", "{", "resp", ".", "InvalidityReason", "=", "reason", "\n", "}", "else", "{", "resp", ".", "InvalidityReason", "+=", "\"", "\"", "+", "reason", "\n", "}", "\n", "}", "\n\n", "if", "env", ",", "_", ":=", "inspection", ".", "Envelope", ".", "(", "*", "tokenserver", ".", "OAuthTokenGrantEnvelope", ")", ";", "env", "!=", "nil", "{", "resp", ".", "SigningKeyId", "=", "env", ".", "KeyId", "\n", "}", "\n\n", "// Examine the body, even if the token is expired or unsigned. This helps to", "// debug expired or unsigned tokens...", "resp", ".", "TokenBody", ",", "_", "=", "inspection", ".", "Body", ".", "(", "*", "tokenserver", ".", "OAuthTokenGrantBody", ")", "\n", "if", "resp", ".", "TokenBody", "!=", "nil", "{", "rules", ",", "err", ":=", "r", ".", "Rules", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Always return the rule that matches the service account, even if the", "// token itself is not allowed by it (we check it separately below).", "rule", ",", "err", ":=", "rules", ".", "Rule", "(", "c", ",", "resp", ".", "TokenBody", ".", "ServiceAccount", ",", "\"", "\"", ")", "\n", "switch", "{", "case", "status", ".", "Code", "(", "err", ")", "==", "codes", ".", "PermissionDenied", ":", "s", ",", "_", ":=", "status", ".", "FromError", "(", "err", ")", "\n", "addInvalidityReason", "(", "\"", "\"", ",", "s", ".", "Message", "(", ")", ")", "\n", "return", "resp", ",", "nil", "\n", "case", "err", "!=", "nil", ":", "// usually codes.Internal", "return", "nil", ",", "err", "\n", "default", ":", "resp", ".", "MatchingRule", "=", "rule", ".", "Rule", "\n", "}", "\n\n", "q", ":=", "&", "RulesQuery", "{", "ServiceAccount", ":", "resp", ".", "TokenBody", ".", "ServiceAccount", ",", "Rule", ":", "rule", ",", "Proxy", ":", "identity", ".", "Identity", "(", "resp", ".", "TokenBody", ".", "Proxy", ")", ",", "EndUser", ":", "identity", ".", "Identity", "(", "resp", ".", "TokenBody", ".", "EndUser", ")", ",", "}", "\n", "switch", "_", ",", "err", "=", "rules", ".", "Check", "(", "c", ",", "q", ")", ";", "{", "case", "err", "==", "nil", ":", "resp", ".", "AllowedByRules", "=", "true", "\n", "case", "status", ".", "Code", "(", "err", ")", "==", "codes", ".", "Internal", ":", "return", "nil", ",", "err", "// a transient error when checking rules", "\n", "default", ":", "// fatal gRPC error => the rules forbid the token", "addInvalidityReason", "(", "\"", "\"", ",", "rules", ".", "ConfigRevision", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "resp", ",", "nil", "\n", "}" ]
// InspectOAuthTokenGrant decodes the given OAuth token grant.
[ "InspectOAuthTokenGrant", "decodes", "the", "given", "OAuth", "token", "grant", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/rpc_inspect_oauth_token_grant.go#L35-L102
8,120
luci/luci-go
cipd/common/iid.go
InstanceIDToObjectRef
func InstanceIDToObjectRef(iid string) *api.ObjectRef { // Legacy SHA1-based instances use hex(sha1) as instance ID, 40 chars. if len(iid) == 40 { if err := checkIsHex(iid); err != nil { panic(fmt.Errorf("not a valid package instance ID %q - %s", iid, err)) } return &api.ObjectRef{ HashAlgo: api.HashAlgo_SHA1, HexDigest: iid, } } ref, err := decodeObjectRef(iid) if err != nil { panic(fmt.Errorf("not a valid package instance ID %q - %s", iid, err)) } return ref }
go
func InstanceIDToObjectRef(iid string) *api.ObjectRef { // Legacy SHA1-based instances use hex(sha1) as instance ID, 40 chars. if len(iid) == 40 { if err := checkIsHex(iid); err != nil { panic(fmt.Errorf("not a valid package instance ID %q - %s", iid, err)) } return &api.ObjectRef{ HashAlgo: api.HashAlgo_SHA1, HexDigest: iid, } } ref, err := decodeObjectRef(iid) if err != nil { panic(fmt.Errorf("not a valid package instance ID %q - %s", iid, err)) } return ref }
[ "func", "InstanceIDToObjectRef", "(", "iid", "string", ")", "*", "api", ".", "ObjectRef", "{", "// Legacy SHA1-based instances use hex(sha1) as instance ID, 40 chars.", "if", "len", "(", "iid", ")", "==", "40", "{", "if", "err", ":=", "checkIsHex", "(", "iid", ")", ";", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "iid", ",", "err", ")", ")", "\n", "}", "\n", "return", "&", "api", ".", "ObjectRef", "{", "HashAlgo", ":", "api", ".", "HashAlgo_SHA1", ",", "HexDigest", ":", "iid", ",", "}", "\n", "}", "\n", "ref", ",", "err", ":=", "decodeObjectRef", "(", "iid", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "iid", ",", "err", ")", ")", "\n", "}", "\n", "return", "ref", "\n", "}" ]
// InstanceIDToObjectRef is a reverse of ObjectRefToInstanceID. // // Panics if the instance ID is incorrect. Use ValidateInstanceID if // this is a concern.
[ "InstanceIDToObjectRef", "is", "a", "reverse", "of", "ObjectRefToInstanceID", ".", "Panics", "if", "the", "instance", "ID", "is", "incorrect", ".", "Use", "ValidateInstanceID", "if", "this", "is", "a", "concern", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/iid.go#L145-L161
8,121
luci/luci-go
cipd/common/iid.go
decodeObjectRef
func decodeObjectRef(iid string) (*api.ObjectRef, error) { // Skip obviously wrong instance IDs faster and with a cleaner error message. // We assume we use at least 160 bit digests here (which translates to at // least 28 bytes of encoded iid). if len(iid) < 28 { return nil, fmt.Errorf("not a valid size for an encoded digest") } blob, err := base64.RawURLEncoding.DecodeString(iid) switch { case err != nil: return nil, fmt.Errorf("cannot base64 decode - %s", err) case len(blob) == 0: return nil, fmt.Errorf("empty") case len(blob)%2 != 1: // 1 byte for hashAlgo, the rest is the digest return nil, fmt.Errorf("the digest can't be odd") } hashAlgo := api.HashAlgo(blob[len(blob)-1]) digest := blob[:len(blob)-1] if hashAlgo == 0 { return nil, fmt.Errorf("unspecified hash algo (0)") } // If algo is known to us, make sure it is valid. Otherwise just decode what // we've given, assuming the caller will later verify the hash using // ValidateHashAlgo, if really needed. if int(hashAlgo) < len(supportedAlgos) { if prop := supportedAlgos[hashAlgo]; len(digest)*2 != prop.hexDigestLen { return nil, fmt.Errorf("wrong digest len %d for algo %s", len(digest), hashAlgo) } } return &api.ObjectRef{ HashAlgo: hashAlgo, HexDigest: hex.EncodeToString(digest), }, nil }
go
func decodeObjectRef(iid string) (*api.ObjectRef, error) { // Skip obviously wrong instance IDs faster and with a cleaner error message. // We assume we use at least 160 bit digests here (which translates to at // least 28 bytes of encoded iid). if len(iid) < 28 { return nil, fmt.Errorf("not a valid size for an encoded digest") } blob, err := base64.RawURLEncoding.DecodeString(iid) switch { case err != nil: return nil, fmt.Errorf("cannot base64 decode - %s", err) case len(blob) == 0: return nil, fmt.Errorf("empty") case len(blob)%2 != 1: // 1 byte for hashAlgo, the rest is the digest return nil, fmt.Errorf("the digest can't be odd") } hashAlgo := api.HashAlgo(blob[len(blob)-1]) digest := blob[:len(blob)-1] if hashAlgo == 0 { return nil, fmt.Errorf("unspecified hash algo (0)") } // If algo is known to us, make sure it is valid. Otherwise just decode what // we've given, assuming the caller will later verify the hash using // ValidateHashAlgo, if really needed. if int(hashAlgo) < len(supportedAlgos) { if prop := supportedAlgos[hashAlgo]; len(digest)*2 != prop.hexDigestLen { return nil, fmt.Errorf("wrong digest len %d for algo %s", len(digest), hashAlgo) } } return &api.ObjectRef{ HashAlgo: hashAlgo, HexDigest: hex.EncodeToString(digest), }, nil }
[ "func", "decodeObjectRef", "(", "iid", "string", ")", "(", "*", "api", ".", "ObjectRef", ",", "error", ")", "{", "// Skip obviously wrong instance IDs faster and with a cleaner error message.", "// We assume we use at least 160 bit digests here (which translates to at", "// least 28 bytes of encoded iid).", "if", "len", "(", "iid", ")", "<", "28", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "blob", ",", "err", ":=", "base64", ".", "RawURLEncoding", ".", "DecodeString", "(", "iid", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "case", "len", "(", "blob", ")", "==", "0", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "len", "(", "blob", ")", "%", "2", "!=", "1", ":", "// 1 byte for hashAlgo, the rest is the digest", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "hashAlgo", ":=", "api", ".", "HashAlgo", "(", "blob", "[", "len", "(", "blob", ")", "-", "1", "]", ")", "\n", "digest", ":=", "blob", "[", ":", "len", "(", "blob", ")", "-", "1", "]", "\n\n", "if", "hashAlgo", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// If algo is known to us, make sure it is valid. Otherwise just decode what", "// we've given, assuming the caller will later verify the hash using", "// ValidateHashAlgo, if really needed.", "if", "int", "(", "hashAlgo", ")", "<", "len", "(", "supportedAlgos", ")", "{", "if", "prop", ":=", "supportedAlgos", "[", "hashAlgo", "]", ";", "len", "(", "digest", ")", "*", "2", "!=", "prop", ".", "hexDigestLen", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "digest", ")", ",", "hashAlgo", ")", "\n", "}", "\n", "}", "\n\n", "return", "&", "api", ".", "ObjectRef", "{", "HashAlgo", ":", "hashAlgo", ",", "HexDigest", ":", "hex", ".", "EncodeToString", "(", "digest", ")", ",", "}", ",", "nil", "\n", "}" ]
// decodeObjectRef is a reverse of encodeObjectRef.
[ "decodeObjectRef", "is", "a", "reverse", "of", "encodeObjectRef", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/iid.go#L197-L235
8,122
luci/luci-go
cipd/common/iid.go
checkIsHex
func checkIsHex(s string) error { switch { case s == "": return fmt.Errorf("empty hex string") case len(s)%2 != 0: return fmt.Errorf("uneven number of symbols in the hex string") } for _, c := range s { if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) { return fmt.Errorf("bad lowercase hex string %q, wrong char %c", s, c) } } return nil }
go
func checkIsHex(s string) error { switch { case s == "": return fmt.Errorf("empty hex string") case len(s)%2 != 0: return fmt.Errorf("uneven number of symbols in the hex string") } for _, c := range s { if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) { return fmt.Errorf("bad lowercase hex string %q, wrong char %c", s, c) } } return nil }
[ "func", "checkIsHex", "(", "s", "string", ")", "error", "{", "switch", "{", "case", "s", "==", "\"", "\"", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "len", "(", "s", ")", "%", "2", "!=", "0", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "s", "{", "if", "!", "(", "(", "c", ">=", "'0'", "&&", "c", "<=", "'9'", ")", "||", "(", "c", ">=", "'a'", "&&", "c", "<=", "'f'", ")", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ",", "c", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkIsHex returns an error if a string is not a lowercase hex string. // // Empty string is rejected as invalid too.
[ "checkIsHex", "returns", "an", "error", "if", "a", "string", "is", "not", "a", "lowercase", "hex", "string", ".", "Empty", "string", "is", "rejected", "as", "invalid", "too", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/iid.go#L240-L253
8,123
luci/luci-go
server/auth/service/validation.go
validateAuthDB
func validateAuthDB(db *protocol.AuthDB) error { groups := make(map[string]*protocol.AuthGroup, len(db.GetGroups())) for _, g := range db.GetGroups() { groups[g.GetName()] = g } for name := range groups { if err := validateAuthGroup(name, groups); err != nil { return err } } for _, wl := range db.GetIpWhitelists() { if err := validateIPWhitelist(wl); err != nil { return fmt.Errorf("auth: bad IP whitlist %q - %s", wl.GetName(), err) } } // Make sure NewSnapshotDB is able to process it as well, since this is where // this proto usually ends up. Note that NewSnapshotDB relies on absence of // cycles in the groups, so the checks above are also important. _, err := authdb.NewSnapshotDB(db, "", 0) return err }
go
func validateAuthDB(db *protocol.AuthDB) error { groups := make(map[string]*protocol.AuthGroup, len(db.GetGroups())) for _, g := range db.GetGroups() { groups[g.GetName()] = g } for name := range groups { if err := validateAuthGroup(name, groups); err != nil { return err } } for _, wl := range db.GetIpWhitelists() { if err := validateIPWhitelist(wl); err != nil { return fmt.Errorf("auth: bad IP whitlist %q - %s", wl.GetName(), err) } } // Make sure NewSnapshotDB is able to process it as well, since this is where // this proto usually ends up. Note that NewSnapshotDB relies on absence of // cycles in the groups, so the checks above are also important. _, err := authdb.NewSnapshotDB(db, "", 0) return err }
[ "func", "validateAuthDB", "(", "db", "*", "protocol", ".", "AuthDB", ")", "error", "{", "groups", ":=", "make", "(", "map", "[", "string", "]", "*", "protocol", ".", "AuthGroup", ",", "len", "(", "db", ".", "GetGroups", "(", ")", ")", ")", "\n", "for", "_", ",", "g", ":=", "range", "db", ".", "GetGroups", "(", ")", "{", "groups", "[", "g", ".", "GetName", "(", ")", "]", "=", "g", "\n", "}", "\n", "for", "name", ":=", "range", "groups", "{", "if", "err", ":=", "validateAuthGroup", "(", "name", ",", "groups", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "for", "_", ",", "wl", ":=", "range", "db", ".", "GetIpWhitelists", "(", ")", "{", "if", "err", ":=", "validateIPWhitelist", "(", "wl", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "wl", ".", "GetName", "(", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Make sure NewSnapshotDB is able to process it as well, since this is where", "// this proto usually ends up. Note that NewSnapshotDB relies on absence of", "// cycles in the groups, so the checks above are also important.", "_", ",", "err", ":=", "authdb", ".", "NewSnapshotDB", "(", "db", ",", "\"", "\"", ",", "0", ")", "\n", "return", "err", "\n", "}" ]
// validateAuthDB returns nil if AuthDB looks correct.
[ "validateAuthDB", "returns", "nil", "if", "AuthDB", "looks", "correct", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/validation.go#L27-L48
8,124
luci/luci-go
server/auth/service/validation.go
validateAuthGroup
func validateAuthGroup(name string, groups map[string]*protocol.AuthGroup) error { g := groups[name] for _, ident := range g.GetMembers() { if _, err := identity.MakeIdentity(ident); err != nil { return fmt.Errorf("auth: invalid identity %q in group %q - %s", ident, name, err) } } for _, glob := range g.GetGlobs() { if _, err := identity.MakeGlob(glob); err != nil { return fmt.Errorf("auth: invalid glob %q in group %q - %s", glob, name, err) } } for _, nested := range g.GetNested() { if groups[nested] == nil { return fmt.Errorf("auth: unknown nested group %q in group %q", nested, name) } } if cycle := findGroupCycle(name, groups); len(cycle) != 0 { return fmt.Errorf("auth: dependency cycle found - %v", cycle) } return nil }
go
func validateAuthGroup(name string, groups map[string]*protocol.AuthGroup) error { g := groups[name] for _, ident := range g.GetMembers() { if _, err := identity.MakeIdentity(ident); err != nil { return fmt.Errorf("auth: invalid identity %q in group %q - %s", ident, name, err) } } for _, glob := range g.GetGlobs() { if _, err := identity.MakeGlob(glob); err != nil { return fmt.Errorf("auth: invalid glob %q in group %q - %s", glob, name, err) } } for _, nested := range g.GetNested() { if groups[nested] == nil { return fmt.Errorf("auth: unknown nested group %q in group %q", nested, name) } } if cycle := findGroupCycle(name, groups); len(cycle) != 0 { return fmt.Errorf("auth: dependency cycle found - %v", cycle) } return nil }
[ "func", "validateAuthGroup", "(", "name", "string", ",", "groups", "map", "[", "string", "]", "*", "protocol", ".", "AuthGroup", ")", "error", "{", "g", ":=", "groups", "[", "name", "]", "\n\n", "for", "_", ",", "ident", ":=", "range", "g", ".", "GetMembers", "(", ")", "{", "if", "_", ",", "err", ":=", "identity", ".", "MakeIdentity", "(", "ident", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ident", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "glob", ":=", "range", "g", ".", "GetGlobs", "(", ")", "{", "if", "_", ",", "err", ":=", "identity", ".", "MakeGlob", "(", "glob", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "glob", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "nested", ":=", "range", "g", ".", "GetNested", "(", ")", "{", "if", "groups", "[", "nested", "]", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "nested", ",", "name", ")", "\n", "}", "\n", "}", "\n\n", "if", "cycle", ":=", "findGroupCycle", "(", "name", ",", "groups", ")", ";", "len", "(", "cycle", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cycle", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateAuthGroup returns nil if AuthGroup looks correct.
[ "validateAuthGroup", "returns", "nil", "if", "AuthGroup", "looks", "correct", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/validation.go#L51-L77
8,125
luci/luci-go
server/auth/service/validation.go
findGroupCycle
func findGroupCycle(name string, groups map[string]*protocol.AuthGroup) []string { // Set of groups that are completely explored (all subtree is traversed). visited := map[string]bool{} // Stack of groups that are being explored now. In case a cycle is detected // it would contain that cycle. var visiting []string // Recursively explores `group` subtree, returns true if finds a cycle. var visit func(string) bool visit = func(group string) bool { g := groups[group] if g == nil { visited[group] = true return false } visiting = append(visiting, group) for _, nested := range g.GetNested() { // Cross edge. Can happen in diamond-like graph, not a cycle. if visited[nested] { continue } // Is `group` references its own ancestor -> cycle is detected. for _, v := range visiting { if v == nested { return true } } // Explore subtree. if visit(nested) { return true } } visiting = visiting[:len(visiting)-1] visited[group] = true return false } visit(name) return visiting // will contain a cycle, if any }
go
func findGroupCycle(name string, groups map[string]*protocol.AuthGroup) []string { // Set of groups that are completely explored (all subtree is traversed). visited := map[string]bool{} // Stack of groups that are being explored now. In case a cycle is detected // it would contain that cycle. var visiting []string // Recursively explores `group` subtree, returns true if finds a cycle. var visit func(string) bool visit = func(group string) bool { g := groups[group] if g == nil { visited[group] = true return false } visiting = append(visiting, group) for _, nested := range g.GetNested() { // Cross edge. Can happen in diamond-like graph, not a cycle. if visited[nested] { continue } // Is `group` references its own ancestor -> cycle is detected. for _, v := range visiting { if v == nested { return true } } // Explore subtree. if visit(nested) { return true } } visiting = visiting[:len(visiting)-1] visited[group] = true return false } visit(name) return visiting // will contain a cycle, if any }
[ "func", "findGroupCycle", "(", "name", "string", ",", "groups", "map", "[", "string", "]", "*", "protocol", ".", "AuthGroup", ")", "[", "]", "string", "{", "// Set of groups that are completely explored (all subtree is traversed).", "visited", ":=", "map", "[", "string", "]", "bool", "{", "}", "\n\n", "// Stack of groups that are being explored now. In case a cycle is detected", "// it would contain that cycle.", "var", "visiting", "[", "]", "string", "\n\n", "// Recursively explores `group` subtree, returns true if finds a cycle.", "var", "visit", "func", "(", "string", ")", "bool", "\n", "visit", "=", "func", "(", "group", "string", ")", "bool", "{", "g", ":=", "groups", "[", "group", "]", "\n", "if", "g", "==", "nil", "{", "visited", "[", "group", "]", "=", "true", "\n", "return", "false", "\n", "}", "\n", "visiting", "=", "append", "(", "visiting", ",", "group", ")", "\n", "for", "_", ",", "nested", ":=", "range", "g", ".", "GetNested", "(", ")", "{", "// Cross edge. Can happen in diamond-like graph, not a cycle.", "if", "visited", "[", "nested", "]", "{", "continue", "\n", "}", "\n", "// Is `group` references its own ancestor -> cycle is detected.", "for", "_", ",", "v", ":=", "range", "visiting", "{", "if", "v", "==", "nested", "{", "return", "true", "\n", "}", "\n", "}", "\n", "// Explore subtree.", "if", "visit", "(", "nested", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "visiting", "=", "visiting", "[", ":", "len", "(", "visiting", ")", "-", "1", "]", "\n", "visited", "[", "group", "]", "=", "true", "\n", "return", "false", "\n", "}", "\n\n", "visit", "(", "name", ")", "\n", "return", "visiting", "// will contain a cycle, if any", "\n", "}" ]
// findGroupCycle searches for a group dependency cycle that contains group // `name`. Returns list of groups that form the cycle if found, empty list // if no cycles. Unknown groups are considered empty.
[ "findGroupCycle", "searches", "for", "a", "group", "dependency", "cycle", "that", "contains", "group", "name", ".", "Returns", "list", "of", "groups", "that", "form", "the", "cycle", "if", "found", "empty", "list", "if", "no", "cycles", ".", "Unknown", "groups", "are", "considered", "empty", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/validation.go#L82-L122
8,126
luci/luci-go
server/auth/service/validation.go
validateIPWhitelist
func validateIPWhitelist(wl *protocol.AuthIPWhitelist) error { for _, subnet := range wl.GetSubnets() { if _, _, err := net.ParseCIDR(subnet); err != nil { return fmt.Errorf("bad subnet %q - %s", subnet, err) } } return nil }
go
func validateIPWhitelist(wl *protocol.AuthIPWhitelist) error { for _, subnet := range wl.GetSubnets() { if _, _, err := net.ParseCIDR(subnet); err != nil { return fmt.Errorf("bad subnet %q - %s", subnet, err) } } return nil }
[ "func", "validateIPWhitelist", "(", "wl", "*", "protocol", ".", "AuthIPWhitelist", ")", "error", "{", "for", "_", ",", "subnet", ":=", "range", "wl", ".", "GetSubnets", "(", ")", "{", "if", "_", ",", "_", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "subnet", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "subnet", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateIPWhitelist checks IPs in the whitelist are parsable.
[ "validateIPWhitelist", "checks", "IPs", "in", "the", "whitelist", "are", "parsable", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/service/validation.go#L125-L132
8,127
luci/luci-go
common/clock/clockflag/duration.go
ParseDuration
func ParseDuration(v string) (Duration, error) { duration, err := time.ParseDuration(v) if err != nil { return 0, err } return Duration(duration), nil }
go
func ParseDuration(v string) (Duration, error) { duration, err := time.ParseDuration(v) if err != nil { return 0, err } return Duration(duration), nil }
[ "func", "ParseDuration", "(", "v", "string", ")", "(", "Duration", ",", "error", ")", "{", "duration", ",", "err", ":=", "time", ".", "ParseDuration", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "Duration", "(", "duration", ")", ",", "nil", "\n", "}" ]
// ParseDuration parses a clockflag Duration from a string. This is basically // a typed fall-through to time.ParseDuration.
[ "ParseDuration", "parses", "a", "clockflag", "Duration", "from", "a", "string", ".", "This", "is", "basically", "a", "typed", "fall", "-", "through", "to", "time", ".", "ParseDuration", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/clock/clockflag/duration.go#L69-L75
8,128
luci/luci-go
milo/buildsource/buildbot/builder.go
mergeText
func mergeText(text []string) []string { merged := make([]string, 0, len(text)) merge := false for _, line := range text { if merge { merge = false merged[len(merged)-1] += " " + line continue } merged = append(merged, line) switch line { case "build", "failed", "exception": merge = true default: merge = false } } // Filter out special cased statuses to make the presentation look cleaner. result := make([]string, 0, len(merged)) for _, item := range merged { switch item { case "failed steps", "failed Failure reason": // Ignore because they're recipe artifacts. default: result = append(result, item) } } return result }
go
func mergeText(text []string) []string { merged := make([]string, 0, len(text)) merge := false for _, line := range text { if merge { merge = false merged[len(merged)-1] += " " + line continue } merged = append(merged, line) switch line { case "build", "failed", "exception": merge = true default: merge = false } } // Filter out special cased statuses to make the presentation look cleaner. result := make([]string, 0, len(merged)) for _, item := range merged { switch item { case "failed steps", "failed Failure reason": // Ignore because they're recipe artifacts. default: result = append(result, item) } } return result }
[ "func", "mergeText", "(", "text", "[", "]", "string", ")", "[", "]", "string", "{", "merged", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "text", ")", ")", "\n", "merge", ":=", "false", "\n", "for", "_", ",", "line", ":=", "range", "text", "{", "if", "merge", "{", "merge", "=", "false", "\n", "merged", "[", "len", "(", "merged", ")", "-", "1", "]", "+=", "\"", "\"", "+", "line", "\n", "continue", "\n", "}", "\n", "merged", "=", "append", "(", "merged", ",", "line", ")", "\n", "switch", "line", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "merge", "=", "true", "\n", "default", ":", "merge", "=", "false", "\n", "}", "\n", "}", "\n\n", "// Filter out special cased statuses to make the presentation look cleaner.", "result", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "merged", ")", ")", "\n", "for", "_", ",", "item", ":=", "range", "merged", "{", "switch", "item", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "// Ignore because they're recipe artifacts.", "default", ":", "result", "=", "append", "(", "result", ",", "item", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// mergeText merges buildbot summary texts, which sometimes separates // words that should be merged together, this combines them into a single // line.
[ "mergeText", "merges", "buildbot", "summary", "texts", "which", "sometimes", "separates", "words", "that", "should", "be", "merged", "together", "this", "combines", "them", "into", "a", "single", "line", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/builder.go#L49-L78
8,129
luci/luci-go
milo/buildsource/buildbot/builder.go
GetBuilder
func GetBuilder(c context.Context, masterName, builderName string, limit int, cursor string) (*ui.Builder, error) { if err := buildstore.CanAccessMaster(c, masterName); err != nil { return nil, err } result := &ui.Builder{ Name: builderName, } master, err := buildstore.GetMaster(c, masterName, false) if err != nil { return nil, err } if clock.Now(c).Sub(master.Modified) > 2*time.Minute { warning := fmt.Sprintf( "WARNING: buildbotMasterEntry data is stale (last updated %s)", master.Modified) logging.Warningf(c, warning) result.Warning = warning } builder, ok := master.Builders[builderName] if !ok { // This long block is just to return a good error message when an invalid // buildbot builder is specified. keys := make([]string, 0, len(master.Builders)) for k := range master.Builders { keys = append(keys, k) } sort.Strings(keys) // TODO(iannucci): add error-info-helper tags to give the error page enough // information to render link-to-master and link-to-builder. builders := strings.Join(keys, "\n") return nil, errors.Reason( "Cannot find builder %q in master %q.\nAvailable builders: \n%s", builderName, masterName, builders, ).Tag(grpcutil.NotFoundTag).Err() } // Extract pending builds out of the master. result.PendingBuilds = make([]*ui.BuildSummary, len(builder.PendingBuildStates)) result.PendingBuildNum = builder.PendingBuilds logging.Debugf(c, "Number of pending builds: %d", len(builder.PendingBuildStates)) for i, pb := range builder.PendingBuildStates { start := time.Unix(int64(pb.SubmittedAt), 0).UTC() result.PendingBuilds[i] = &ui.BuildSummary{ PendingTime: ui.NewInterval(c, start, time.Time{}), Blame: make([]*ui.Commit, len(pb.Source.Changes)), } for j, cm := range pb.Source.Changes { result.PendingBuilds[i].Blame[j] = &ui.Commit{ AuthorEmail: cm.Who, CommitURL: cm.Revlink, } } } baseURL := "https://build.chromium.org/p/" if master.Internal { baseURL = "https://uberchromegw.corp.google.com/i/" } result.MachinePool = summarizeSlavePool(c, baseURL+master.Name, builder.Slaves, master.Slaves) return result, parallel.FanOutIn(func(work chan<- func() error) { q := buildstore.Query{ Master: masterName, Builder: builderName, NoAnnotationFetch: true, } work <- func() error { q := q q.Limit = limit q.Cursor = cursor q.Finished = buildstore.Yes res, err := buildstore.GetBuilds(c, q) if err != nil { return err } result.NextCursor = res.NextCursor result.PrevCursor = res.PrevCursor result.FinishedBuilds = make([]*ui.BuildSummary, len(res.Builds)) for i, b := range res.Builds { result.FinishedBuilds[i] = renderBuild(c, b, false).BuildSummary() } return err } work <- func() error { q := q q.Finished = buildstore.No res, err := buildstore.GetBuilds(c, q) if err != nil { return err } result.CurrentBuilds = make([]*ui.BuildSummary, len(res.Builds)) for i, b := range res.Builds { // currentBuilds is presented in reversed order, so flip it result.CurrentBuilds[len(res.Builds)-i-1] = renderBuild(c, b, false).BuildSummary() } return err } }) }
go
func GetBuilder(c context.Context, masterName, builderName string, limit int, cursor string) (*ui.Builder, error) { if err := buildstore.CanAccessMaster(c, masterName); err != nil { return nil, err } result := &ui.Builder{ Name: builderName, } master, err := buildstore.GetMaster(c, masterName, false) if err != nil { return nil, err } if clock.Now(c).Sub(master.Modified) > 2*time.Minute { warning := fmt.Sprintf( "WARNING: buildbotMasterEntry data is stale (last updated %s)", master.Modified) logging.Warningf(c, warning) result.Warning = warning } builder, ok := master.Builders[builderName] if !ok { // This long block is just to return a good error message when an invalid // buildbot builder is specified. keys := make([]string, 0, len(master.Builders)) for k := range master.Builders { keys = append(keys, k) } sort.Strings(keys) // TODO(iannucci): add error-info-helper tags to give the error page enough // information to render link-to-master and link-to-builder. builders := strings.Join(keys, "\n") return nil, errors.Reason( "Cannot find builder %q in master %q.\nAvailable builders: \n%s", builderName, masterName, builders, ).Tag(grpcutil.NotFoundTag).Err() } // Extract pending builds out of the master. result.PendingBuilds = make([]*ui.BuildSummary, len(builder.PendingBuildStates)) result.PendingBuildNum = builder.PendingBuilds logging.Debugf(c, "Number of pending builds: %d", len(builder.PendingBuildStates)) for i, pb := range builder.PendingBuildStates { start := time.Unix(int64(pb.SubmittedAt), 0).UTC() result.PendingBuilds[i] = &ui.BuildSummary{ PendingTime: ui.NewInterval(c, start, time.Time{}), Blame: make([]*ui.Commit, len(pb.Source.Changes)), } for j, cm := range pb.Source.Changes { result.PendingBuilds[i].Blame[j] = &ui.Commit{ AuthorEmail: cm.Who, CommitURL: cm.Revlink, } } } baseURL := "https://build.chromium.org/p/" if master.Internal { baseURL = "https://uberchromegw.corp.google.com/i/" } result.MachinePool = summarizeSlavePool(c, baseURL+master.Name, builder.Slaves, master.Slaves) return result, parallel.FanOutIn(func(work chan<- func() error) { q := buildstore.Query{ Master: masterName, Builder: builderName, NoAnnotationFetch: true, } work <- func() error { q := q q.Limit = limit q.Cursor = cursor q.Finished = buildstore.Yes res, err := buildstore.GetBuilds(c, q) if err != nil { return err } result.NextCursor = res.NextCursor result.PrevCursor = res.PrevCursor result.FinishedBuilds = make([]*ui.BuildSummary, len(res.Builds)) for i, b := range res.Builds { result.FinishedBuilds[i] = renderBuild(c, b, false).BuildSummary() } return err } work <- func() error { q := q q.Finished = buildstore.No res, err := buildstore.GetBuilds(c, q) if err != nil { return err } result.CurrentBuilds = make([]*ui.BuildSummary, len(res.Builds)) for i, b := range res.Builds { // currentBuilds is presented in reversed order, so flip it result.CurrentBuilds[len(res.Builds)-i-1] = renderBuild(c, b, false).BuildSummary() } return err } }) }
[ "func", "GetBuilder", "(", "c", "context", ".", "Context", ",", "masterName", ",", "builderName", "string", ",", "limit", "int", ",", "cursor", "string", ")", "(", "*", "ui", ".", "Builder", ",", "error", ")", "{", "if", "err", ":=", "buildstore", ".", "CanAccessMaster", "(", "c", ",", "masterName", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "result", ":=", "&", "ui", ".", "Builder", "{", "Name", ":", "builderName", ",", "}", "\n", "master", ",", "err", ":=", "buildstore", ".", "GetMaster", "(", "c", ",", "masterName", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "clock", ".", "Now", "(", "c", ")", ".", "Sub", "(", "master", ".", "Modified", ")", ">", "2", "*", "time", ".", "Minute", "{", "warning", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "master", ".", "Modified", ")", "\n", "logging", ".", "Warningf", "(", "c", ",", "warning", ")", "\n", "result", ".", "Warning", "=", "warning", "\n", "}", "\n\n", "builder", ",", "ok", ":=", "master", ".", "Builders", "[", "builderName", "]", "\n", "if", "!", "ok", "{", "// This long block is just to return a good error message when an invalid", "// buildbot builder is specified.", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "master", ".", "Builders", ")", ")", "\n", "for", "k", ":=", "range", "master", ".", "Builders", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "// TODO(iannucci): add error-info-helper tags to give the error page enough", "// information to render link-to-master and link-to-builder.", "builders", ":=", "strings", ".", "Join", "(", "keys", ",", "\"", "\\n", "\"", ")", "\n", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\\n", "\\n", "\"", ",", "builderName", ",", "masterName", ",", "builders", ",", ")", ".", "Tag", "(", "grpcutil", ".", "NotFoundTag", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Extract pending builds out of the master.", "result", ".", "PendingBuilds", "=", "make", "(", "[", "]", "*", "ui", ".", "BuildSummary", ",", "len", "(", "builder", ".", "PendingBuildStates", ")", ")", "\n", "result", ".", "PendingBuildNum", "=", "builder", ".", "PendingBuilds", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "len", "(", "builder", ".", "PendingBuildStates", ")", ")", "\n", "for", "i", ",", "pb", ":=", "range", "builder", ".", "PendingBuildStates", "{", "start", ":=", "time", ".", "Unix", "(", "int64", "(", "pb", ".", "SubmittedAt", ")", ",", "0", ")", ".", "UTC", "(", ")", "\n", "result", ".", "PendingBuilds", "[", "i", "]", "=", "&", "ui", ".", "BuildSummary", "{", "PendingTime", ":", "ui", ".", "NewInterval", "(", "c", ",", "start", ",", "time", ".", "Time", "{", "}", ")", ",", "Blame", ":", "make", "(", "[", "]", "*", "ui", ".", "Commit", ",", "len", "(", "pb", ".", "Source", ".", "Changes", ")", ")", ",", "}", "\n", "for", "j", ",", "cm", ":=", "range", "pb", ".", "Source", ".", "Changes", "{", "result", ".", "PendingBuilds", "[", "i", "]", ".", "Blame", "[", "j", "]", "=", "&", "ui", ".", "Commit", "{", "AuthorEmail", ":", "cm", ".", "Who", ",", "CommitURL", ":", "cm", ".", "Revlink", ",", "}", "\n", "}", "\n", "}", "\n\n", "baseURL", ":=", "\"", "\"", "\n", "if", "master", ".", "Internal", "{", "baseURL", "=", "\"", "\"", "\n", "}", "\n", "result", ".", "MachinePool", "=", "summarizeSlavePool", "(", "c", ",", "baseURL", "+", "master", ".", "Name", ",", "builder", ".", "Slaves", ",", "master", ".", "Slaves", ")", "\n\n", "return", "result", ",", "parallel", ".", "FanOutIn", "(", "func", "(", "work", "chan", "<-", "func", "(", ")", "error", ")", "{", "q", ":=", "buildstore", ".", "Query", "{", "Master", ":", "masterName", ",", "Builder", ":", "builderName", ",", "NoAnnotationFetch", ":", "true", ",", "}", "\n", "work", "<-", "func", "(", ")", "error", "{", "q", ":=", "q", "\n", "q", ".", "Limit", "=", "limit", "\n", "q", ".", "Cursor", "=", "cursor", "\n", "q", ".", "Finished", "=", "buildstore", ".", "Yes", "\n", "res", ",", "err", ":=", "buildstore", ".", "GetBuilds", "(", "c", ",", "q", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "result", ".", "NextCursor", "=", "res", ".", "NextCursor", "\n", "result", ".", "PrevCursor", "=", "res", ".", "PrevCursor", "\n", "result", ".", "FinishedBuilds", "=", "make", "(", "[", "]", "*", "ui", ".", "BuildSummary", ",", "len", "(", "res", ".", "Builds", ")", ")", "\n", "for", "i", ",", "b", ":=", "range", "res", ".", "Builds", "{", "result", ".", "FinishedBuilds", "[", "i", "]", "=", "renderBuild", "(", "c", ",", "b", ",", "false", ")", ".", "BuildSummary", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "work", "<-", "func", "(", ")", "error", "{", "q", ":=", "q", "\n", "q", ".", "Finished", "=", "buildstore", ".", "No", "\n", "res", ",", "err", ":=", "buildstore", ".", "GetBuilds", "(", "c", ",", "q", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "result", ".", "CurrentBuilds", "=", "make", "(", "[", "]", "*", "ui", ".", "BuildSummary", ",", "len", "(", "res", ".", "Builds", ")", ")", "\n", "for", "i", ",", "b", ":=", "range", "res", ".", "Builds", "{", "// currentBuilds is presented in reversed order, so flip it", "result", ".", "CurrentBuilds", "[", "len", "(", "res", ".", "Builds", ")", "-", "i", "-", "1", "]", "=", "renderBuild", "(", "c", ",", "b", ",", "false", ")", ".", "BuildSummary", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", ")", "\n", "}" ]
// GetBuilder is the implementation for getting a milo builder page from // buildbot.
[ "GetBuilder", "is", "the", "implementation", "for", "getting", "a", "milo", "builder", "page", "from", "buildbot", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/builder.go#L110-L209
8,130
luci/luci-go
machine-db/appengine/rpc/hosts.go
DeleteHost
func (*Service) DeleteHost(c context.Context, req *crimson.DeleteHostRequest) (*empty.Empty, error) { if err := deleteHost(c, req.Name); err != nil { return nil, err } return &empty.Empty{}, nil }
go
func (*Service) DeleteHost(c context.Context, req *crimson.DeleteHostRequest) (*empty.Empty, error) { if err := deleteHost(c, req.Name); err != nil { return nil, err } return &empty.Empty{}, nil }
[ "func", "(", "*", "Service", ")", "DeleteHost", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "DeleteHostRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "if", "err", ":=", "deleteHost", "(", "c", ",", "req", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeleteHost handles a request to delete an existing host.
[ "DeleteHost", "handles", "a", "request", "to", "delete", "an", "existing", "host", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/hosts.go#L36-L41
8,131
luci/luci-go
machine-db/appengine/rpc/hosts.go
deleteHost
func deleteHost(c context.Context, name string) error { if name == "" { return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty") } db := database.Get(c) res, err := db.ExecContext(c, `DELETE FROM hostnames WHERE name = ?`, name) if err != nil { switch e, ok := err.(*mysql.MySQLError); { case !ok: // Type assertion failed. case e.Number == mysqlerr.ER_ROW_IS_REFERENCED_2 && strings.Contains(e.Message, "`physical_host_id`"): // e.g. "Error 1452: Cannot add or update a child row: a foreign key constraint fails (FOREIGN KEY (`physical_host_id`) REFERENCES `physical_hosts` (`id`))". return status.Errorf(codes.FailedPrecondition, "delete entities referencing this host first") } return errors.Annotate(err, "failed to delete host").Err() } switch rows, err := res.RowsAffected(); { case err != nil: return errors.Annotate(err, "failed to fetch affected rows").Err() case rows == 0: return status.Errorf(codes.NotFound, "host %q does not exist", name) case rows == 1: return nil default: // Shouldn't happen because name is unique in the database. return errors.Reason("unexpected number of affected rows %d", rows).Err() } }
go
func deleteHost(c context.Context, name string) error { if name == "" { return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty") } db := database.Get(c) res, err := db.ExecContext(c, `DELETE FROM hostnames WHERE name = ?`, name) if err != nil { switch e, ok := err.(*mysql.MySQLError); { case !ok: // Type assertion failed. case e.Number == mysqlerr.ER_ROW_IS_REFERENCED_2 && strings.Contains(e.Message, "`physical_host_id`"): // e.g. "Error 1452: Cannot add or update a child row: a foreign key constraint fails (FOREIGN KEY (`physical_host_id`) REFERENCES `physical_hosts` (`id`))". return status.Errorf(codes.FailedPrecondition, "delete entities referencing this host first") } return errors.Annotate(err, "failed to delete host").Err() } switch rows, err := res.RowsAffected(); { case err != nil: return errors.Annotate(err, "failed to fetch affected rows").Err() case rows == 0: return status.Errorf(codes.NotFound, "host %q does not exist", name) case rows == 1: return nil default: // Shouldn't happen because name is unique in the database. return errors.Reason("unexpected number of affected rows %d", rows).Err() } }
[ "func", "deleteHost", "(", "c", "context", ".", "Context", ",", "name", "string", ")", "error", "{", "if", "name", "==", "\"", "\"", "{", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "db", ":=", "database", ".", "Get", "(", "c", ")", "\n", "res", ",", "err", ":=", "db", ".", "ExecContext", "(", "c", ",", "`DELETE FROM hostnames WHERE name = ?`", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "e", ",", "ok", ":=", "err", ".", "(", "*", "mysql", ".", "MySQLError", ")", ";", "{", "case", "!", "ok", ":", "// Type assertion failed.", "case", "e", ".", "Number", "==", "mysqlerr", ".", "ER_ROW_IS_REFERENCED_2", "&&", "strings", ".", "Contains", "(", "e", ".", "Message", ",", "\"", "\"", ")", ":", "// e.g. \"Error 1452: Cannot add or update a child row: a foreign key constraint fails (FOREIGN KEY (`physical_host_id`) REFERENCES `physical_hosts` (`id`))\".", "return", "status", ".", "Errorf", "(", "codes", ".", "FailedPrecondition", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "switch", "rows", ",", "err", ":=", "res", ".", "RowsAffected", "(", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "case", "rows", "==", "0", ":", "return", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "name", ")", "\n", "case", "rows", "==", "1", ":", "return", "nil", "\n", "default", ":", "// Shouldn't happen because name is unique in the database.", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "rows", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// deleteHost deletes an existing host from the database.
[ "deleteHost", "deletes", "an", "existing", "host", "from", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/hosts.go#L44-L72
8,132
luci/luci-go
common/sync/parallel/buffer.go
process
func (b *Buffer) process() { defer close(b.tasksFinishedC) // outC is the channel that we send work to. We toggle it between nil and our // Runner's WorkC depending on whether we have work. // // cur is the current work to send. It is only valid if hasWork is true. var outC chan<- WorkItem var cur WorkItem // This is our work buffer. If we have unsent work, any additional work will // be written to this buffer. var buf list.List // Our main processing loop. inC := b.workC for { select { case work, ok := <-inC: if !ok { // Our work channel has been closed. We aren't accepting any new tasks. if outC == nil && buf.Len() == 0 { // We have no buffered work; exit immediately. return } // Mark that we're closed. When all of our work drains, we will exit. inC = nil break } // If we have no immediate work, send "work" directly; otherwise, buffer // work for future sending. if outC == nil { cur = work outC = b.Runner.WorkC() } else { buf.PushBack(&work) } case outC <- cur: // "cur" has been sent. Dequeue the next work item, or set outC to nil if // there are no more items. switch { case buf.Len() > 0: var e *list.Element if b.isFIFO() { e = buf.Front() } else { e = buf.Back() } cur = *(buf.Remove(e).(*WorkItem)) case inC == nil: // There's no more immediate work, no buffered work, and we're closed, // so we're finished. return default: // No more work to send. outC = nil } } } }
go
func (b *Buffer) process() { defer close(b.tasksFinishedC) // outC is the channel that we send work to. We toggle it between nil and our // Runner's WorkC depending on whether we have work. // // cur is the current work to send. It is only valid if hasWork is true. var outC chan<- WorkItem var cur WorkItem // This is our work buffer. If we have unsent work, any additional work will // be written to this buffer. var buf list.List // Our main processing loop. inC := b.workC for { select { case work, ok := <-inC: if !ok { // Our work channel has been closed. We aren't accepting any new tasks. if outC == nil && buf.Len() == 0 { // We have no buffered work; exit immediately. return } // Mark that we're closed. When all of our work drains, we will exit. inC = nil break } // If we have no immediate work, send "work" directly; otherwise, buffer // work for future sending. if outC == nil { cur = work outC = b.Runner.WorkC() } else { buf.PushBack(&work) } case outC <- cur: // "cur" has been sent. Dequeue the next work item, or set outC to nil if // there are no more items. switch { case buf.Len() > 0: var e *list.Element if b.isFIFO() { e = buf.Front() } else { e = buf.Back() } cur = *(buf.Remove(e).(*WorkItem)) case inC == nil: // There's no more immediate work, no buffered work, and we're closed, // so we're finished. return default: // No more work to send. outC = nil } } } }
[ "func", "(", "b", "*", "Buffer", ")", "process", "(", ")", "{", "defer", "close", "(", "b", ".", "tasksFinishedC", ")", "\n\n", "// outC is the channel that we send work to. We toggle it between nil and our", "// Runner's WorkC depending on whether we have work.", "//", "// cur is the current work to send. It is only valid if hasWork is true.", "var", "outC", "chan", "<-", "WorkItem", "\n", "var", "cur", "WorkItem", "\n\n", "// This is our work buffer. If we have unsent work, any additional work will", "// be written to this buffer.", "var", "buf", "list", ".", "List", "\n\n", "// Our main processing loop.", "inC", ":=", "b", ".", "workC", "\n", "for", "{", "select", "{", "case", "work", ",", "ok", ":=", "<-", "inC", ":", "if", "!", "ok", "{", "// Our work channel has been closed. We aren't accepting any new tasks.", "if", "outC", "==", "nil", "&&", "buf", ".", "Len", "(", ")", "==", "0", "{", "// We have no buffered work; exit immediately.", "return", "\n", "}", "\n\n", "// Mark that we're closed. When all of our work drains, we will exit.", "inC", "=", "nil", "\n", "break", "\n", "}", "\n\n", "// If we have no immediate work, send \"work\" directly; otherwise, buffer", "// work for future sending.", "if", "outC", "==", "nil", "{", "cur", "=", "work", "\n", "outC", "=", "b", ".", "Runner", ".", "WorkC", "(", ")", "\n", "}", "else", "{", "buf", ".", "PushBack", "(", "&", "work", ")", "\n", "}", "\n\n", "case", "outC", "<-", "cur", ":", "// \"cur\" has been sent. Dequeue the next work item, or set outC to nil if", "// there are no more items.", "switch", "{", "case", "buf", ".", "Len", "(", ")", ">", "0", ":", "var", "e", "*", "list", ".", "Element", "\n", "if", "b", ".", "isFIFO", "(", ")", "{", "e", "=", "buf", ".", "Front", "(", ")", "\n", "}", "else", "{", "e", "=", "buf", ".", "Back", "(", ")", "\n", "}", "\n\n", "cur", "=", "*", "(", "buf", ".", "Remove", "(", "e", ")", ".", "(", "*", "WorkItem", ")", ")", "\n", "case", "inC", "==", "nil", ":", "// There's no more immediate work, no buffered work, and we're closed,", "// so we're finished.", "return", "\n", "default", ":", "// No more work to send.", "outC", "=", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// process enqueues tasks into the Buffer and dispatches them to the underlying // Runner when available.
[ "process", "enqueues", "tasks", "into", "the", "Buffer", "and", "dispatches", "them", "to", "the", "underlying", "Runner", "when", "available", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/buffer.go#L52-L115
8,133
luci/luci-go
common/sync/parallel/buffer.go
RunOne
func (b *Buffer) RunOne(f func() error) <-chan error { b.init() errC := make(chan error) b.workC <- WorkItem{ F: f, ErrC: errC, After: func() { close(errC) }, } return errC }
go
func (b *Buffer) RunOne(f func() error) <-chan error { b.init() errC := make(chan error) b.workC <- WorkItem{ F: f, ErrC: errC, After: func() { close(errC) }, } return errC }
[ "func", "(", "b", "*", "Buffer", ")", "RunOne", "(", "f", "func", "(", ")", "error", ")", "<-", "chan", "error", "{", "b", ".", "init", "(", ")", "\n\n", "errC", ":=", "make", "(", "chan", "error", ")", "\n", "b", ".", "workC", "<-", "WorkItem", "{", "F", ":", "f", ",", "ErrC", ":", "errC", ",", "After", ":", "func", "(", ")", "{", "close", "(", "errC", ")", "}", ",", "}", "\n", "return", "errC", "\n", "}" ]
// RunOne implements the same semantics as Runner's RunOne. However, if the // dispatch pipeline is full, RunOne will buffer the work and return immediately // rather than block.
[ "RunOne", "implements", "the", "same", "semantics", "as", "Runner", "s", "RunOne", ".", "However", "if", "the", "dispatch", "pipeline", "is", "full", "RunOne", "will", "buffer", "the", "work", "and", "return", "immediately", "rather", "than", "block", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/buffer.go#L135-L145
8,134
luci/luci-go
common/sync/parallel/buffer.go
Close
func (b *Buffer) Close() { b.init() close(b.workC) <-b.tasksFinishedC b.Runner.Close() }
go
func (b *Buffer) Close() { b.init() close(b.workC) <-b.tasksFinishedC b.Runner.Close() }
[ "func", "(", "b", "*", "Buffer", ")", "Close", "(", ")", "{", "b", ".", "init", "(", ")", "\n\n", "close", "(", "b", ".", "workC", ")", "\n", "<-", "b", ".", "tasksFinishedC", "\n", "b", ".", "Runner", ".", "Close", "(", ")", "\n", "}" ]
// Close flushes the remaining tasks in the Buffer and Closes the underlying // Runner. // // Adding new tasks to the Buffer after Close has been invoked will cause a // panic.
[ "Close", "flushes", "the", "remaining", "tasks", "in", "the", "Buffer", "and", "Closes", "the", "underlying", "Runner", ".", "Adding", "new", "tasks", "to", "the", "Buffer", "after", "Close", "has", "been", "invoked", "will", "cause", "a", "panic", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/buffer.go#L161-L167
8,135
luci/luci-go
server/caching/process.go
LRU
func (h LRUHandle) LRU(c context.Context) *lru.Cache { return c.Value(&processCacheKey).(*ProcessCacheData).caches[int(h)] }
go
func (h LRUHandle) LRU(c context.Context) *lru.Cache { return c.Value(&processCacheKey).(*ProcessCacheData).caches[int(h)] }
[ "func", "(", "h", "LRUHandle", ")", "LRU", "(", "c", "context", ".", "Context", ")", "*", "lru", ".", "Cache", "{", "return", "c", ".", "Value", "(", "&", "processCacheKey", ")", ".", "(", "*", "ProcessCacheData", ")", ".", "caches", "[", "int", "(", "h", ")", "]", "\n", "}" ]
// LRU returns global lru.Cache referenced by this handle. // // If the context doesn't have ProcessCacheData installed, this will panic.
[ "LRU", "returns", "global", "lru", ".", "Cache", "referenced", "by", "this", "handle", ".", "If", "the", "context", "doesn", "t", "have", "ProcessCacheData", "installed", "this", "will", "panic", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/process.go#L63-L65
8,136
luci/luci-go
server/caching/process.go
Fetch
func (h SlotHandle) Fetch(c context.Context, cb FetchCallback) (interface{}, error) { return c.Value(&processCacheKey).(*ProcessCacheData).slots[int(h)].Get(c, lazyslot.Fetcher(cb)) }
go
func (h SlotHandle) Fetch(c context.Context, cb FetchCallback) (interface{}, error) { return c.Value(&processCacheKey).(*ProcessCacheData).slots[int(h)].Get(c, lazyslot.Fetcher(cb)) }
[ "func", "(", "h", "SlotHandle", ")", "Fetch", "(", "c", "context", ".", "Context", ",", "cb", "FetchCallback", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "c", ".", "Value", "(", "&", "processCacheKey", ")", ".", "(", "*", "ProcessCacheData", ")", ".", "slots", "[", "int", "(", "h", ")", "]", ".", "Get", "(", "c", ",", "lazyslot", ".", "Fetcher", "(", "cb", ")", ")", "\n", "}" ]
// Fetch returns the cached data, if it is available and fresh, or attempts to // refresh it by calling the given callback. // // If the context doesn't have ProcessCacheData installed, this will panic.
[ "Fetch", "returns", "the", "cached", "data", "if", "it", "is", "available", "and", "fresh", "or", "attempts", "to", "refresh", "it", "by", "calling", "the", "given", "callback", ".", "If", "the", "context", "doesn", "t", "have", "ProcessCacheData", "installed", "this", "will", "panic", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/process.go#L101-L103
8,137
luci/luci-go
cipd/client/cipd/pkg/manifest.go
ReadManifest
func ReadManifest(r io.Reader) (manifest Manifest, err error) { blob, err := ioutil.ReadAll(r) if err == nil { err = json.Unmarshal(blob, &manifest) } return }
go
func ReadManifest(r io.Reader) (manifest Manifest, err error) { blob, err := ioutil.ReadAll(r) if err == nil { err = json.Unmarshal(blob, &manifest) } return }
[ "func", "ReadManifest", "(", "r", "io", ".", "Reader", ")", "(", "manifest", "Manifest", ",", "err", "error", ")", "{", "blob", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "json", ".", "Unmarshal", "(", "blob", ",", "&", "manifest", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ReadManifest reads and decodes manifest JSON from io.Reader.
[ "ReadManifest", "reads", "and", "decodes", "manifest", "JSON", "from", "io", ".", "Reader", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/pkg/manifest.go#L99-L105
8,138
luci/luci-go
cipd/client/cipd/pkg/manifest.go
WriteManifest
func WriteManifest(m *Manifest, w io.Writer) error { data, err := json.MarshalIndent(m, "", " ") if err != nil { return err } _, err = w.Write(data) return err }
go
func WriteManifest(m *Manifest, w io.Writer) error { data, err := json.MarshalIndent(m, "", " ") if err != nil { return err } _, err = w.Write(data) return err }
[ "func", "WriteManifest", "(", "m", "*", "Manifest", ",", "w", "io", ".", "Writer", ")", "error", "{", "data", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "m", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "w", ".", "Write", "(", "data", ")", "\n", "return", "err", "\n", "}" ]
// WriteManifest encodes and writes manifest JSON to io.Writer.
[ "WriteManifest", "encodes", "and", "writes", "manifest", "JSON", "to", "io", ".", "Writer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/pkg/manifest.go#L108-L115
8,139
luci/luci-go
logdog/client/coordinator/client.go
NewClient
func NewClient(c *prpc.Client) *Client { return &Client{ C: logdog.NewLogsPRPCClient(c), Host: c.Host, } }
go
func NewClient(c *prpc.Client) *Client { return &Client{ C: logdog.NewLogsPRPCClient(c), Host: c.Host, } }
[ "func", "NewClient", "(", "c", "*", "prpc", ".", "Client", ")", "*", "Client", "{", "return", "&", "Client", "{", "C", ":", "logdog", ".", "NewLogsPRPCClient", "(", "c", ")", ",", "Host", ":", "c", ".", "Host", ",", "}", "\n", "}" ]
// NewClient returns a new Client instance bound to a pRPC Client.
[ "NewClient", "returns", "a", "new", "Client", "instance", "bound", "to", "a", "pRPC", "Client", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/coordinator/client.go#L43-L48
8,140
luci/luci-go
logdog/client/coordinator/client.go
Stream
func (c *Client) Stream(project types.ProjectName, path types.StreamPath) *Stream { return &Stream{ c: c, project: project, path: path, } }
go
func (c *Client) Stream(project types.ProjectName, path types.StreamPath) *Stream { return &Stream{ c: c, project: project, path: path, } }
[ "func", "(", "c", "*", "Client", ")", "Stream", "(", "project", "types", ".", "ProjectName", ",", "path", "types", ".", "StreamPath", ")", "*", "Stream", "{", "return", "&", "Stream", "{", "c", ":", "c", ",", "project", ":", "project", ",", "path", ":", "path", ",", "}", "\n", "}" ]
// Stream returns a Stream instance for the named stream.
[ "Stream", "returns", "a", "Stream", "instance", "for", "the", "named", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/coordinator/client.go#L51-L57
8,141
luci/luci-go
tokenserver/appengine/impl/utils/policy/policy.go
Queryable
func (p *Policy) Queryable(c context.Context) (Queryable, error) { val, err := p.cache.Get(c, func(prev interface{}) (newQ interface{}, exp time.Duration, err error) { prevQ, _ := prev.(Queryable) newQ, err = p.grabQueryable(c, prevQ) if err == nil { exp = cacheExpiry(c) } return }) if err != nil { return nil, err } return val.(Queryable), nil }
go
func (p *Policy) Queryable(c context.Context) (Queryable, error) { val, err := p.cache.Get(c, func(prev interface{}) (newQ interface{}, exp time.Duration, err error) { prevQ, _ := prev.(Queryable) newQ, err = p.grabQueryable(c, prevQ) if err == nil { exp = cacheExpiry(c) } return }) if err != nil { return nil, err } return val.(Queryable), nil }
[ "func", "(", "p", "*", "Policy", ")", "Queryable", "(", "c", "context", ".", "Context", ")", "(", "Queryable", ",", "error", ")", "{", "val", ",", "err", ":=", "p", ".", "cache", ".", "Get", "(", "c", ",", "func", "(", "prev", "interface", "{", "}", ")", "(", "newQ", "interface", "{", "}", ",", "exp", "time", ".", "Duration", ",", "err", "error", ")", "{", "prevQ", ",", "_", ":=", "prev", ".", "(", "Queryable", ")", "\n", "newQ", ",", "err", "=", "p", ".", "grabQueryable", "(", "c", ",", "prevQ", ")", "\n", "if", "err", "==", "nil", "{", "exp", "=", "cacheExpiry", "(", "c", ")", "\n", "}", "\n", "return", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "val", ".", "(", "Queryable", ")", ",", "nil", "\n", "}" ]
// Queryable returns a form of the policy document optimized for queries. // // This is hot function called from each RPC handler. It uses local in-memory // cache to store the configs, synchronizing it with the state stored in the // datastore once a minute. // // Returns ErrNoPolicy if the policy config wasn't imported yet.
[ "Queryable", "returns", "a", "form", "of", "the", "policy", "document", "optimized", "for", "queries", ".", "This", "is", "hot", "function", "called", "from", "each", "RPC", "handler", ".", "It", "uses", "local", "in", "-", "memory", "cache", "to", "store", "the", "configs", "synchronizing", "it", "with", "the", "state", "stored", "in", "the", "datastore", "once", "a", "minute", ".", "Returns", "ErrNoPolicy", "if", "the", "policy", "config", "wasn", "t", "imported", "yet", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/policy/policy.go#L199-L212
8,142
luci/luci-go
tokenserver/appengine/impl/utils/policy/policy.go
grabQueryable
func (p *Policy) grabQueryable(c context.Context, prevQ Queryable) (Queryable, error) { c = logging.SetField(c, "policy", p.Name) logging.Infof(c, "Checking version of the policy in the datastore") hdr, err := getImportedPolicyHeader(c, p.Name) switch { case err != nil: return nil, errors.Annotate(err, "failed to fetch importedPolicyHeader entity").Err() case hdr == nil: return nil, ErrNoPolicy } // Reuse existing Queryable object if configs didn't change. if prevQ != nil && prevQ.ConfigRevision() == hdr.Revision { return prevQ, nil } // Fetch new configs. logging.Infof(c, "Fetching policy configs from the datastore") body, err := getImportedPolicyBody(c, p.Name) switch { case err != nil: return nil, errors.Annotate(err, "failed to fetch importedPolicyBody entity").Err() case body == nil: // this is rare, the body shouldn't disappear logging.Errorf(c, "The policy body is unexpectedly gone") return nil, ErrNoPolicy } // An error here and below can happen if previously validated config is no // longer valid (e.g. if the service code is updated and new code doesn't like // the stored config anymore). // // If this check fails, the service is effectively offline until configs are // updated. Presumably, it is better than silently using no longer valid // config. logging.Infof(c, "Using configs at rev %s", body.Revision) configs, unknown, err := deserializeBundle(body.Data) if err != nil { return nil, errors.Annotate(err, "failed to deserialize cached configs").Err() } if len(unknown) != 0 { for _, cfg := range unknown { logging.Errorf(c, "Unknown proto type %q in cached config %q", cfg.Kind, cfg.Path) } return nil, errors.New("failed to deserialize some cached configs") } queryable, err := p.Prepare(c, configs, body.Revision) if err != nil { return nil, errors.Annotate(err, "failed to process cached configs").Err() } return queryable, nil }
go
func (p *Policy) grabQueryable(c context.Context, prevQ Queryable) (Queryable, error) { c = logging.SetField(c, "policy", p.Name) logging.Infof(c, "Checking version of the policy in the datastore") hdr, err := getImportedPolicyHeader(c, p.Name) switch { case err != nil: return nil, errors.Annotate(err, "failed to fetch importedPolicyHeader entity").Err() case hdr == nil: return nil, ErrNoPolicy } // Reuse existing Queryable object if configs didn't change. if prevQ != nil && prevQ.ConfigRevision() == hdr.Revision { return prevQ, nil } // Fetch new configs. logging.Infof(c, "Fetching policy configs from the datastore") body, err := getImportedPolicyBody(c, p.Name) switch { case err != nil: return nil, errors.Annotate(err, "failed to fetch importedPolicyBody entity").Err() case body == nil: // this is rare, the body shouldn't disappear logging.Errorf(c, "The policy body is unexpectedly gone") return nil, ErrNoPolicy } // An error here and below can happen if previously validated config is no // longer valid (e.g. if the service code is updated and new code doesn't like // the stored config anymore). // // If this check fails, the service is effectively offline until configs are // updated. Presumably, it is better than silently using no longer valid // config. logging.Infof(c, "Using configs at rev %s", body.Revision) configs, unknown, err := deserializeBundle(body.Data) if err != nil { return nil, errors.Annotate(err, "failed to deserialize cached configs").Err() } if len(unknown) != 0 { for _, cfg := range unknown { logging.Errorf(c, "Unknown proto type %q in cached config %q", cfg.Kind, cfg.Path) } return nil, errors.New("failed to deserialize some cached configs") } queryable, err := p.Prepare(c, configs, body.Revision) if err != nil { return nil, errors.Annotate(err, "failed to process cached configs").Err() } return queryable, nil }
[ "func", "(", "p", "*", "Policy", ")", "grabQueryable", "(", "c", "context", ".", "Context", ",", "prevQ", "Queryable", ")", "(", "Queryable", ",", "error", ")", "{", "c", "=", "logging", ".", "SetField", "(", "c", ",", "\"", "\"", ",", "p", ".", "Name", ")", "\n\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "hdr", ",", "err", ":=", "getImportedPolicyHeader", "(", "c", ",", "p", ".", "Name", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "case", "hdr", "==", "nil", ":", "return", "nil", ",", "ErrNoPolicy", "\n", "}", "\n\n", "// Reuse existing Queryable object if configs didn't change.", "if", "prevQ", "!=", "nil", "&&", "prevQ", ".", "ConfigRevision", "(", ")", "==", "hdr", ".", "Revision", "{", "return", "prevQ", ",", "nil", "\n", "}", "\n\n", "// Fetch new configs.", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "body", ",", "err", ":=", "getImportedPolicyBody", "(", "c", ",", "p", ".", "Name", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "case", "body", "==", "nil", ":", "// this is rare, the body shouldn't disappear", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "ErrNoPolicy", "\n", "}", "\n\n", "// An error here and below can happen if previously validated config is no", "// longer valid (e.g. if the service code is updated and new code doesn't like", "// the stored config anymore).", "//", "// If this check fails, the service is effectively offline until configs are", "// updated. Presumably, it is better than silently using no longer valid", "// config.", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "body", ".", "Revision", ")", "\n", "configs", ",", "unknown", ",", "err", ":=", "deserializeBundle", "(", "body", ".", "Data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "len", "(", "unknown", ")", "!=", "0", "{", "for", "_", ",", "cfg", ":=", "range", "unknown", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "cfg", ".", "Kind", ",", "cfg", ".", "Path", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "queryable", ",", "err", ":=", "p", ".", "Prepare", "(", "c", ",", "configs", ",", "body", ".", "Revision", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "return", "queryable", ",", "nil", "\n", "}" ]
// grabQueryable is called whenever cached Queryable in p.cache expires.
[ "grabQueryable", "is", "called", "whenever", "cached", "Queryable", "in", "p", ".", "cache", "expires", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/policy/policy.go#L215-L267
8,143
luci/luci-go
tokenserver/appengine/impl/utils/policy/policy.go
cacheExpiry
func cacheExpiry(c context.Context) time.Duration { rnd := time.Duration(mathrand.Int63n(c, int64(time.Minute))) return 4*time.Minute + rnd }
go
func cacheExpiry(c context.Context) time.Duration { rnd := time.Duration(mathrand.Int63n(c, int64(time.Minute))) return 4*time.Minute + rnd }
[ "func", "cacheExpiry", "(", "c", "context", ".", "Context", ")", "time", ".", "Duration", "{", "rnd", ":=", "time", ".", "Duration", "(", "mathrand", ".", "Int63n", "(", "c", ",", "int64", "(", "time", ".", "Minute", ")", ")", ")", "\n", "return", "4", "*", "time", ".", "Minute", "+", "rnd", "\n", "}" ]
// cacheExpiry returns a random duration from [4 min, 5 min). // // It's used to define when to refresh in-memory Queryable cache. We randomize // it to desynchronize cache updates of different Policy instances.
[ "cacheExpiry", "returns", "a", "random", "duration", "from", "[", "4", "min", "5", "min", ")", ".", "It", "s", "used", "to", "define", "when", "to", "refresh", "in", "-", "memory", "Queryable", "cache", ".", "We", "randomize", "it", "to", "desynchronize", "cache", "updates", "of", "different", "Policy", "instances", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/policy/policy.go#L273-L276
8,144
luci/luci-go
common/tsmon/target/context.go
Set
func Set(ctx context.Context, t types.Target) context.Context { return context.WithValue(ctx, targetKey, t) }
go
func Set(ctx context.Context, t types.Target) context.Context { return context.WithValue(ctx, targetKey, t) }
[ "func", "Set", "(", "ctx", "context", ".", "Context", ",", "t", "types", ".", "Target", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "targetKey", ",", "t", ")", "\n", "}" ]
// Set returns a new context with the given target set. If this context is // passed to metric Set, Get or Incr methods the metrics for that target will be // affected. A nil target means to use the default target.
[ "Set", "returns", "a", "new", "context", "with", "the", "given", "target", "set", ".", "If", "this", "context", "is", "passed", "to", "metric", "Set", "Get", "or", "Incr", "methods", "the", "metrics", "for", "that", "target", "will", "be", "affected", ".", "A", "nil", "target", "means", "to", "use", "the", "default", "target", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/target/context.go#L30-L32
8,145
luci/luci-go
common/tsmon/target/context.go
Get
func Get(ctx context.Context) types.Target { if t, ok := ctx.Value(targetKey).(types.Target); ok { return t } return nil }
go
func Get(ctx context.Context) types.Target { if t, ok := ctx.Value(targetKey).(types.Target); ok { return t } return nil }
[ "func", "Get", "(", "ctx", "context", ".", "Context", ")", "types", ".", "Target", "{", "if", "t", ",", "ok", ":=", "ctx", ".", "Value", "(", "targetKey", ")", ".", "(", "types", ".", "Target", ")", ";", "ok", "{", "return", "t", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Get returns the target set in this context.
[ "Get", "returns", "the", "target", "set", "in", "this", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/target/context.go#L35-L40
8,146
luci/luci-go
common/tsmon/target/context.go
GetWithDefault
func GetWithDefault(ctx context.Context, def types.Target) types.Target { if t := Get(ctx); t != nil { return t } return def }
go
func GetWithDefault(ctx context.Context, def types.Target) types.Target { if t := Get(ctx); t != nil { return t } return def }
[ "func", "GetWithDefault", "(", "ctx", "context", ".", "Context", ",", "def", "types", ".", "Target", ")", "types", ".", "Target", "{", "if", "t", ":=", "Get", "(", "ctx", ")", ";", "t", "!=", "nil", "{", "return", "t", "\n", "}", "\n", "return", "def", "\n", "}" ]
// GetWithDefault is like Get, except it returns the given default value if // there is no target set in the context.
[ "GetWithDefault", "is", "like", "Get", "except", "it", "returns", "the", "given", "default", "value", "if", "there", "is", "no", "target", "set", "in", "the", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/target/context.go#L44-L49
8,147
luci/luci-go
logdog/appengine/coordinator/flex/logs/query.go
applyTrinary
func applyTrinary(q *ds.Query, v logdog.QueryRequest_Trinary, f func(*ds.Query, bool) *ds.Query) *ds.Query { switch v { case logdog.QueryRequest_YES: return f(q, true) case logdog.QueryRequest_NO: return f(q, false) default: // Default is "both". return q } }
go
func applyTrinary(q *ds.Query, v logdog.QueryRequest_Trinary, f func(*ds.Query, bool) *ds.Query) *ds.Query { switch v { case logdog.QueryRequest_YES: return f(q, true) case logdog.QueryRequest_NO: return f(q, false) default: // Default is "both". return q } }
[ "func", "applyTrinary", "(", "q", "*", "ds", ".", "Query", ",", "v", "logdog", ".", "QueryRequest_Trinary", ",", "f", "func", "(", "*", "ds", ".", "Query", ",", "bool", ")", "*", "ds", ".", "Query", ")", "*", "ds", ".", "Query", "{", "switch", "v", "{", "case", "logdog", ".", "QueryRequest_YES", ":", "return", "f", "(", "q", ",", "true", ")", "\n\n", "case", "logdog", ".", "QueryRequest_NO", ":", "return", "f", "(", "q", ",", "false", ")", "\n\n", "default", ":", "// Default is \"both\".", "return", "q", "\n", "}", "\n", "}" ]
// applyTrinary executes the supplied query modification function based on a // trinary value. // // If the value is "YES", it will be executed with "true". If "NO", "false". If // "BOTH", it will not be executed.
[ "applyTrinary", "executes", "the", "supplied", "query", "modification", "function", "based", "on", "a", "trinary", "value", ".", "If", "the", "value", "is", "YES", "it", "will", "be", "executed", "with", "true", ".", "If", "NO", "false", ".", "If", "BOTH", "it", "will", "not", "be", "executed", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/query.go#L46-L58
8,148
luci/luci-go
logdog/appengine/coordinator/flex/logs/query.go
Query
func (s *server) Query(c context.Context, req *logdog.QueryRequest) (*logdog.QueryResponse, error) { // Non-admin users may not request purged results. canSeePurged := true if err := coordinator.IsAdminUser(c); err != nil { canSeePurged = false // Non-admin user. if req.Purged == logdog.QueryRequest_YES { log.Fields{ log.ErrorKey: err, }.Errorf(c, "Non-superuser requested to see purged logs. Denying.") return nil, grpcutil.Errf(codes.InvalidArgument, "non-admin user cannot request purged log streams") } } // Scale the maximum number of results based on the number of queries in this // request. If the user specified a maximum result count of zero, use the // default maximum. // // If this scaling results in a limit that is <1 per request, we will return // back a BadRequest error. limit := s.resultLimit if limit == 0 { limit = queryResultLimit } // Execute our queries in parallel. resp := logdog.QueryResponse{} e := &queryRunner{ Context: log.SetField(c, "path", req.Path), QueryRequest: req, canSeePurged: canSeePurged, limit: limit, } startTime := clock.Now(c) if err := e.runQuery(&resp); err != nil { // Transient errors would be handled at the "execute" level, so these are // specific failure errors. We must escalate individual errors to the user. // We will choose the most severe of the resulting errors. log.WithError(err).Errorf(c, "Failed to execute query.") return nil, err } log.Infof(c, "Query took: %s", clock.Now(c).Sub(startTime)) return &resp, nil }
go
func (s *server) Query(c context.Context, req *logdog.QueryRequest) (*logdog.QueryResponse, error) { // Non-admin users may not request purged results. canSeePurged := true if err := coordinator.IsAdminUser(c); err != nil { canSeePurged = false // Non-admin user. if req.Purged == logdog.QueryRequest_YES { log.Fields{ log.ErrorKey: err, }.Errorf(c, "Non-superuser requested to see purged logs. Denying.") return nil, grpcutil.Errf(codes.InvalidArgument, "non-admin user cannot request purged log streams") } } // Scale the maximum number of results based on the number of queries in this // request. If the user specified a maximum result count of zero, use the // default maximum. // // If this scaling results in a limit that is <1 per request, we will return // back a BadRequest error. limit := s.resultLimit if limit == 0 { limit = queryResultLimit } // Execute our queries in parallel. resp := logdog.QueryResponse{} e := &queryRunner{ Context: log.SetField(c, "path", req.Path), QueryRequest: req, canSeePurged: canSeePurged, limit: limit, } startTime := clock.Now(c) if err := e.runQuery(&resp); err != nil { // Transient errors would be handled at the "execute" level, so these are // specific failure errors. We must escalate individual errors to the user. // We will choose the most severe of the resulting errors. log.WithError(err).Errorf(c, "Failed to execute query.") return nil, err } log.Infof(c, "Query took: %s", clock.Now(c).Sub(startTime)) return &resp, nil }
[ "func", "(", "s", "*", "server", ")", "Query", "(", "c", "context", ".", "Context", ",", "req", "*", "logdog", ".", "QueryRequest", ")", "(", "*", "logdog", ".", "QueryResponse", ",", "error", ")", "{", "// Non-admin users may not request purged results.", "canSeePurged", ":=", "true", "\n", "if", "err", ":=", "coordinator", ".", "IsAdminUser", "(", "c", ")", ";", "err", "!=", "nil", "{", "canSeePurged", "=", "false", "\n\n", "// Non-admin user.", "if", "req", ".", "Purged", "==", "logdog", ".", "QueryRequest_YES", "{", "log", ".", "Fields", "{", "log", ".", "ErrorKey", ":", "err", ",", "}", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "Errf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// Scale the maximum number of results based on the number of queries in this", "// request. If the user specified a maximum result count of zero, use the", "// default maximum.", "//", "// If this scaling results in a limit that is <1 per request, we will return", "// back a BadRequest error.", "limit", ":=", "s", ".", "resultLimit", "\n", "if", "limit", "==", "0", "{", "limit", "=", "queryResultLimit", "\n", "}", "\n\n", "// Execute our queries in parallel.", "resp", ":=", "logdog", ".", "QueryResponse", "{", "}", "\n", "e", ":=", "&", "queryRunner", "{", "Context", ":", "log", ".", "SetField", "(", "c", ",", "\"", "\"", ",", "req", ".", "Path", ")", ",", "QueryRequest", ":", "req", ",", "canSeePurged", ":", "canSeePurged", ",", "limit", ":", "limit", ",", "}", "\n\n", "startTime", ":=", "clock", ".", "Now", "(", "c", ")", "\n", "if", "err", ":=", "e", ".", "runQuery", "(", "&", "resp", ")", ";", "err", "!=", "nil", "{", "// Transient errors would be handled at the \"execute\" level, so these are", "// specific failure errors. We must escalate individual errors to the user.", "// We will choose the most severe of the resulting errors.", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "clock", ".", "Now", "(", "c", ")", ".", "Sub", "(", "startTime", ")", ")", "\n", "return", "&", "resp", ",", "nil", "\n", "}" ]
// Query returns log stream paths that match the requested query.
[ "Query", "returns", "log", "stream", "paths", "that", "match", "the", "requested", "query", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/query.go#L61-L106
8,149
luci/luci-go
machine-db/appengine/rpc/queries.go
selectInInt64
func selectInInt64(b squirrel.SelectBuilder, expr string, values []int64) squirrel.SelectBuilder { if len(values) == 0 { return b } args := make([]interface{}, len(values)) for i, val := range values { args[i] = val } return b.Where(expr+" IN ("+squirrel.Placeholders(len(args))+")", args...) }
go
func selectInInt64(b squirrel.SelectBuilder, expr string, values []int64) squirrel.SelectBuilder { if len(values) == 0 { return b } args := make([]interface{}, len(values)) for i, val := range values { args[i] = val } return b.Where(expr+" IN ("+squirrel.Placeholders(len(args))+")", args...) }
[ "func", "selectInInt64", "(", "b", "squirrel", ".", "SelectBuilder", ",", "expr", "string", ",", "values", "[", "]", "int64", ")", "squirrel", ".", "SelectBuilder", "{", "if", "len", "(", "values", ")", "==", "0", "{", "return", "b", "\n", "}", "\n", "args", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "values", ")", ")", "\n", "for", "i", ",", "val", ":=", "range", "values", "{", "args", "[", "i", "]", "=", "val", "\n", "}", "\n", "return", "b", ".", "Where", "(", "expr", "+", "\"", "\"", "+", "squirrel", ".", "Placeholders", "(", "len", "(", "args", ")", ")", "+", "\"", "\"", ",", "args", "...", ")", "\n", "}" ]
// selectInInt64 returns the given SELECT modified with a WHERE IN clause. // expr is the left-hand side of the IN operator, values is the right-hand side. No-op if values is empty.
[ "selectInInt64", "returns", "the", "given", "SELECT", "modified", "with", "a", "WHERE", "IN", "clause", ".", "expr", "is", "the", "left", "-", "hand", "side", "of", "the", "IN", "operator", "values", "is", "the", "right", "-", "hand", "side", ".", "No", "-", "op", "if", "values", "is", "empty", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/queries.go#L25-L34
8,150
luci/luci-go
machine-db/appengine/rpc/queries.go
selectInState
func selectInState(b squirrel.SelectBuilder, expr string, values []common.State) squirrel.SelectBuilder { if len(values) == 0 { return b } args := make([]interface{}, len(values)) for i, val := range values { args[i] = val } return b.Where(expr+" IN ("+squirrel.Placeholders(len(args))+")", args...) }
go
func selectInState(b squirrel.SelectBuilder, expr string, values []common.State) squirrel.SelectBuilder { if len(values) == 0 { return b } args := make([]interface{}, len(values)) for i, val := range values { args[i] = val } return b.Where(expr+" IN ("+squirrel.Placeholders(len(args))+")", args...) }
[ "func", "selectInState", "(", "b", "squirrel", ".", "SelectBuilder", ",", "expr", "string", ",", "values", "[", "]", "common", ".", "State", ")", "squirrel", ".", "SelectBuilder", "{", "if", "len", "(", "values", ")", "==", "0", "{", "return", "b", "\n", "}", "\n", "args", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "values", ")", ")", "\n", "for", "i", ",", "val", ":=", "range", "values", "{", "args", "[", "i", "]", "=", "val", "\n", "}", "\n", "return", "b", ".", "Where", "(", "expr", "+", "\"", "\"", "+", "squirrel", ".", "Placeholders", "(", "len", "(", "args", ")", ")", "+", "\"", "\"", ",", "args", "...", ")", "\n", "}" ]
// selectInState returns the given SELECT modified with a WHERE IN clause. // expr is the left-hand side of the IN operator, values is the right-hand side. No-op if values is empty.
[ "selectInState", "returns", "the", "given", "SELECT", "modified", "with", "a", "WHERE", "IN", "clause", ".", "expr", "is", "the", "left", "-", "hand", "side", "of", "the", "IN", "operator", "values", "is", "the", "right", "-", "hand", "side", ".", "No", "-", "op", "if", "values", "is", "empty", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/queries.go#L38-L47
8,151
luci/luci-go
lucicfg/cli/cmds/diff/diff.go
Cmd
func Cmd(params base.Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "semantic-diff SCRIPT CONFIG [CONFIG CONFIG ...]", ShortDesc: "interprets a high-level config, compares the result to existing configs", LongDesc: `Interprets a high-level config, compares the result to existing configs. THIS SUBCOMMAND WILL BE DELETED AFTER IT IS NO LONGER USEFUL. DO NOT DEPEND ON IT IN ANY AUTOMATIC SCRIPTS. FOR MANUAL USE ONLY. IF YOU REALLY-REALLY NEED TO USE IT FROM AUTOMATION, PLEASE FILE A BUG. Uses semantic comparison. Normalizes all protos before comparing them via 'git diff'. Intended to be used manually when switching existing *.cfg to be generated from *.star. Accepts a path to the entry-point *.star script and paths to existing configs to diff against. Their filenames (not full paths) will be used to find corresponding generated files, and also to figure out the proto schema to use. Example: $ lucicfg semantic-diff main.star configs/cr-buildbucket.cfg configs/luci-milo.cfg `, CommandRun: func() subcommands.CommandRun { dr := &diffRun{} dr.Init(params) dr.AddMetaFlags() dr.Flags.StringVar(&dr.outputDir, "output-dir", "", "Where to put normalized configs if you want them preserved after the command completes.") return dr }, } }
go
func Cmd(params base.Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "semantic-diff SCRIPT CONFIG [CONFIG CONFIG ...]", ShortDesc: "interprets a high-level config, compares the result to existing configs", LongDesc: `Interprets a high-level config, compares the result to existing configs. THIS SUBCOMMAND WILL BE DELETED AFTER IT IS NO LONGER USEFUL. DO NOT DEPEND ON IT IN ANY AUTOMATIC SCRIPTS. FOR MANUAL USE ONLY. IF YOU REALLY-REALLY NEED TO USE IT FROM AUTOMATION, PLEASE FILE A BUG. Uses semantic comparison. Normalizes all protos before comparing them via 'git diff'. Intended to be used manually when switching existing *.cfg to be generated from *.star. Accepts a path to the entry-point *.star script and paths to existing configs to diff against. Their filenames (not full paths) will be used to find corresponding generated files, and also to figure out the proto schema to use. Example: $ lucicfg semantic-diff main.star configs/cr-buildbucket.cfg configs/luci-milo.cfg `, CommandRun: func() subcommands.CommandRun { dr := &diffRun{} dr.Init(params) dr.AddMetaFlags() dr.Flags.StringVar(&dr.outputDir, "output-dir", "", "Where to put normalized configs if you want them preserved after the command completes.") return dr }, } }
[ "func", "Cmd", "(", "params", "base", ".", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "`Interprets a high-level config, compares the result to existing configs.\n\nTHIS SUBCOMMAND WILL BE DELETED AFTER IT IS NO LONGER USEFUL. DO NOT DEPEND ON\nIT IN ANY AUTOMATIC SCRIPTS. FOR MANUAL USE ONLY. IF YOU REALLY-REALLY NEED TO\nUSE IT FROM AUTOMATION, PLEASE FILE A BUG.\n\nUses semantic comparison. Normalizes all protos before comparing them via\n'git diff'. Intended to be used manually when switching existing *.cfg to be\ngenerated from *.star.\n\nAccepts a path to the entry-point *.star script and paths to existing configs\nto diff against. Their filenames (not full paths) will be used to find\ncorresponding generated files, and also to figure out the proto schema to use.\n\nExample:\n\n $ lucicfg semantic-diff main.star configs/cr-buildbucket.cfg configs/luci-milo.cfg\n`", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "dr", ":=", "&", "diffRun", "{", "}", "\n", "dr", ".", "Init", "(", "params", ")", "\n", "dr", ".", "AddMetaFlags", "(", ")", "\n", "dr", ".", "Flags", ".", "StringVar", "(", "&", "dr", ".", "outputDir", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "dr", "\n", "}", ",", "}", "\n", "}" ]
// Cmd is 'semantic-diff' subcommand.
[ "Cmd", "is", "semantic", "-", "diff", "subcommand", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/cli/cmds/diff/diff.go#L48-L78
8,152
luci/luci-go
lucicfg/cli/cmds/diff/diff.go
normalizeOne
func normalizeOne(ctx context.Context, in []byte, p *configPair) (out []byte, err error) { msg := reflect.New(p.typ.Elem()).Interface().(proto.Message) if err = luciproto.UnmarshalTextML(string(in), msg); err != nil { return } if err = p.protoNormalizer(ctx, msg); err != nil { return } return []byte(proto.MarshalTextString(msg)), nil }
go
func normalizeOne(ctx context.Context, in []byte, p *configPair) (out []byte, err error) { msg := reflect.New(p.typ.Elem()).Interface().(proto.Message) if err = luciproto.UnmarshalTextML(string(in), msg); err != nil { return } if err = p.protoNormalizer(ctx, msg); err != nil { return } return []byte(proto.MarshalTextString(msg)), nil }
[ "func", "normalizeOne", "(", "ctx", "context", ".", "Context", ",", "in", "[", "]", "byte", ",", "p", "*", "configPair", ")", "(", "out", "[", "]", "byte", ",", "err", "error", ")", "{", "msg", ":=", "reflect", ".", "New", "(", "p", ".", "typ", ".", "Elem", "(", ")", ")", ".", "Interface", "(", ")", ".", "(", "proto", ".", "Message", ")", "\n", "if", "err", "=", "luciproto", ".", "UnmarshalTextML", "(", "string", "(", "in", ")", ",", "msg", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "p", ".", "protoNormalizer", "(", "ctx", ",", "msg", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "[", "]", "byte", "(", "proto", ".", "MarshalTextString", "(", "msg", ")", ")", ",", "nil", "\n", "}" ]
// normalizeOne deserializes the proto, passes it through normalizer, serializes // it back.
[ "normalizeOne", "deserializes", "the", "proto", "passes", "it", "through", "normalizer", "serializes", "it", "back", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/cli/cmds/diff/diff.go#L253-L262
8,153
luci/luci-go
milo/rpc/buildinfo.go
Get
func (svc *BuildInfoService) Get(c context.Context, req *milo.BuildInfoRequest) (*milo.BuildInfoResponse, error) { projectHint := req.ProjectHint if projectHint != "" { if err := config.ValidateProjectName(projectHint); err != nil { return nil, grpcutil.Errf(codes.InvalidArgument, "invalid project hint: %s", err.Error()) } } switch { case req.GetBuildbot() != nil: return buildbot.GetBuildInfo(c, req.GetBuildbot(), projectHint) case req.GetSwarming() != nil: return svc.Swarming.GetBuildInfo(c, req.GetSwarming(), projectHint) case req.GetBuildbucket() != nil: switch resp, err := svc.getFromContextURI(c, req.GetBuildbucket().GetId(), projectHint); err { case nil: return resp, nil case buildbucket.ErrNotFound: logging.WithError(err).Infof(c, "%d not found in context URI for build summary") // continue to fallback code. default: return nil, err } // Resolve the swarming host/task from buildbucket. host, taskID, err := buildbucket.GetSwarmingTaskID(c, strconv.FormatInt(req.GetBuildbucket().GetId(), 10)) if err != nil { return nil, err } sReq := &milo.BuildInfoRequest_Swarming{ Host: host, Task: taskID, } return svc.Swarming.GetBuildInfo(c, sReq, projectHint) default: return nil, grpcutil.Errf(codes.InvalidArgument, "must supply a build") } }
go
func (svc *BuildInfoService) Get(c context.Context, req *milo.BuildInfoRequest) (*milo.BuildInfoResponse, error) { projectHint := req.ProjectHint if projectHint != "" { if err := config.ValidateProjectName(projectHint); err != nil { return nil, grpcutil.Errf(codes.InvalidArgument, "invalid project hint: %s", err.Error()) } } switch { case req.GetBuildbot() != nil: return buildbot.GetBuildInfo(c, req.GetBuildbot(), projectHint) case req.GetSwarming() != nil: return svc.Swarming.GetBuildInfo(c, req.GetSwarming(), projectHint) case req.GetBuildbucket() != nil: switch resp, err := svc.getFromContextURI(c, req.GetBuildbucket().GetId(), projectHint); err { case nil: return resp, nil case buildbucket.ErrNotFound: logging.WithError(err).Infof(c, "%d not found in context URI for build summary") // continue to fallback code. default: return nil, err } // Resolve the swarming host/task from buildbucket. host, taskID, err := buildbucket.GetSwarmingTaskID(c, strconv.FormatInt(req.GetBuildbucket().GetId(), 10)) if err != nil { return nil, err } sReq := &milo.BuildInfoRequest_Swarming{ Host: host, Task: taskID, } return svc.Swarming.GetBuildInfo(c, sReq, projectHint) default: return nil, grpcutil.Errf(codes.InvalidArgument, "must supply a build") } }
[ "func", "(", "svc", "*", "BuildInfoService", ")", "Get", "(", "c", "context", ".", "Context", ",", "req", "*", "milo", ".", "BuildInfoRequest", ")", "(", "*", "milo", ".", "BuildInfoResponse", ",", "error", ")", "{", "projectHint", ":=", "req", ".", "ProjectHint", "\n", "if", "projectHint", "!=", "\"", "\"", "{", "if", "err", ":=", "config", ".", "ValidateProjectName", "(", "projectHint", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "grpcutil", ".", "Errf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "switch", "{", "case", "req", ".", "GetBuildbot", "(", ")", "!=", "nil", ":", "return", "buildbot", ".", "GetBuildInfo", "(", "c", ",", "req", ".", "GetBuildbot", "(", ")", ",", "projectHint", ")", "\n\n", "case", "req", ".", "GetSwarming", "(", ")", "!=", "nil", ":", "return", "svc", ".", "Swarming", ".", "GetBuildInfo", "(", "c", ",", "req", ".", "GetSwarming", "(", ")", ",", "projectHint", ")", "\n\n", "case", "req", ".", "GetBuildbucket", "(", ")", "!=", "nil", ":", "switch", "resp", ",", "err", ":=", "svc", ".", "getFromContextURI", "(", "c", ",", "req", ".", "GetBuildbucket", "(", ")", ".", "GetId", "(", ")", ",", "projectHint", ")", ";", "err", "{", "case", "nil", ":", "return", "resp", ",", "nil", "\n", "case", "buildbucket", ".", "ErrNotFound", ":", "logging", ".", "WithError", "(", "err", ")", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "// continue to fallback code.", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Resolve the swarming host/task from buildbucket.", "host", ",", "taskID", ",", "err", ":=", "buildbucket", ".", "GetSwarmingTaskID", "(", "c", ",", "strconv", ".", "FormatInt", "(", "req", ".", "GetBuildbucket", "(", ")", ".", "GetId", "(", ")", ",", "10", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sReq", ":=", "&", "milo", ".", "BuildInfoRequest_Swarming", "{", "Host", ":", "host", ",", "Task", ":", "taskID", ",", "}", "\n", "return", "svc", ".", "Swarming", ".", "GetBuildInfo", "(", "c", ",", "sReq", ",", "projectHint", ")", "\n\n", "default", ":", "return", "nil", ",", "grpcutil", ".", "Errf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Get implements milo.BuildInfoServer.
[ "Get", "implements", "milo", ".", "BuildInfoServer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/rpc/buildinfo.go#L90-L130
8,154
luci/luci-go
client/isolated/scattergather.go
Set
func (sc *ScatterGather) Set(value string) error { parsed := strings.SplitN(value, ":", 2) if len(parsed) != 2 { return errors.Reason("malformed input %q", value).Err() } if *sc == nil { *sc = ScatterGather{} } return sc.Add(parsed[0], parsed[1]) }
go
func (sc *ScatterGather) Set(value string) error { parsed := strings.SplitN(value, ":", 2) if len(parsed) != 2 { return errors.Reason("malformed input %q", value).Err() } if *sc == nil { *sc = ScatterGather{} } return sc.Add(parsed[0], parsed[1]) }
[ "func", "(", "sc", "*", "ScatterGather", ")", "Set", "(", "value", "string", ")", "error", "{", "parsed", ":=", "strings", ".", "SplitN", "(", "value", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "parsed", ")", "!=", "2", "{", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "value", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "*", "sc", "==", "nil", "{", "*", "sc", "=", "ScatterGather", "{", "}", "\n", "}", "\n", "return", "sc", ".", "Add", "(", "parsed", "[", "0", "]", ",", "parsed", "[", "1", "]", ")", "\n", "}" ]
// Set implements the flags.Var interface.
[ "Set", "implements", "the", "flags", ".", "Var", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolated/scattergather.go#L55-L64
8,155
luci/luci-go
common/proto/srcman/diff.go
add
func (c *modifiedTracker) add(st ManifestDiff_Stat) ManifestDiff_Stat { *c = *c || st != ManifestDiff_EQUAL return st }
go
func (c *modifiedTracker) add(st ManifestDiff_Stat) ManifestDiff_Stat { *c = *c || st != ManifestDiff_EQUAL return st }
[ "func", "(", "c", "*", "modifiedTracker", ")", "add", "(", "st", "ManifestDiff_Stat", ")", "ManifestDiff_Stat", "{", "*", "c", "=", "*", "c", "||", "st", "!=", "ManifestDiff_EQUAL", "\n", "return", "st", "\n", "}" ]
// add incorporates `st` into this modifiedTracker's state.
[ "add", "incorporates", "st", "into", "this", "modifiedTracker", "s", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/srcman/diff.go#L89-L92
8,156
luci/luci-go
common/proto/srcman/diff.go
Diff
func (old *Manifest_GitCheckout) Diff(new *Manifest_GitCheckout) *ManifestDiff_GitCheckout { if old == nil && new == nil { return nil } ret := &ManifestDiff_GitCheckout{} ret.Overall = zeroCmpTwo(old, new, func() ManifestDiff_Stat { if old.RepoUrl == new.RepoUrl { // For now, the canoncial 'diff' URL is always the new URL. If we add // support for source-of-truth migrations, this could change. ret.RepoUrl = new.RepoUrl // FetchRef doesn't matter for comparison purposes for now. ret.Revision = zeroCmpTwo(old.Revision, new.Revision, nil) if ret.Revision == ManifestDiff_MODIFIED { ret.Revision = ManifestDiff_DIFF } // We calculate DIFF for PatchRevision iff the two checkouts both include // patches from the same CL. ret.PatchRevision = zeroCmpTwo(old.PatchRevision, new.PatchRevision, nil) if ret.PatchRevision == ManifestDiff_MODIFIED { oldCL, newCL := parseChangeRef(old.PatchFetchRef), parseChangeRef(new.PatchFetchRef) if oldCL != "" && newCL != "" && oldCL == newCL { ret.PatchRevision = ManifestDiff_DIFF } } // If all the revisions are the same and the repo url is the same, that's // good enough for the whole checkout to be equal. if ret.Revision == ManifestDiff_EQUAL && ret.PatchRevision == ManifestDiff_EQUAL { return ManifestDiff_EQUAL } } return ManifestDiff_MODIFIED }) return ret }
go
func (old *Manifest_GitCheckout) Diff(new *Manifest_GitCheckout) *ManifestDiff_GitCheckout { if old == nil && new == nil { return nil } ret := &ManifestDiff_GitCheckout{} ret.Overall = zeroCmpTwo(old, new, func() ManifestDiff_Stat { if old.RepoUrl == new.RepoUrl { // For now, the canoncial 'diff' URL is always the new URL. If we add // support for source-of-truth migrations, this could change. ret.RepoUrl = new.RepoUrl // FetchRef doesn't matter for comparison purposes for now. ret.Revision = zeroCmpTwo(old.Revision, new.Revision, nil) if ret.Revision == ManifestDiff_MODIFIED { ret.Revision = ManifestDiff_DIFF } // We calculate DIFF for PatchRevision iff the two checkouts both include // patches from the same CL. ret.PatchRevision = zeroCmpTwo(old.PatchRevision, new.PatchRevision, nil) if ret.PatchRevision == ManifestDiff_MODIFIED { oldCL, newCL := parseChangeRef(old.PatchFetchRef), parseChangeRef(new.PatchFetchRef) if oldCL != "" && newCL != "" && oldCL == newCL { ret.PatchRevision = ManifestDiff_DIFF } } // If all the revisions are the same and the repo url is the same, that's // good enough for the whole checkout to be equal. if ret.Revision == ManifestDiff_EQUAL && ret.PatchRevision == ManifestDiff_EQUAL { return ManifestDiff_EQUAL } } return ManifestDiff_MODIFIED }) return ret }
[ "func", "(", "old", "*", "Manifest_GitCheckout", ")", "Diff", "(", "new", "*", "Manifest_GitCheckout", ")", "*", "ManifestDiff_GitCheckout", "{", "if", "old", "==", "nil", "&&", "new", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "ret", ":=", "&", "ManifestDiff_GitCheckout", "{", "}", "\n\n", "ret", ".", "Overall", "=", "zeroCmpTwo", "(", "old", ",", "new", ",", "func", "(", ")", "ManifestDiff_Stat", "{", "if", "old", ".", "RepoUrl", "==", "new", ".", "RepoUrl", "{", "// For now, the canoncial 'diff' URL is always the new URL. If we add", "// support for source-of-truth migrations, this could change.", "ret", ".", "RepoUrl", "=", "new", ".", "RepoUrl", "\n\n", "// FetchRef doesn't matter for comparison purposes for now.", "ret", ".", "Revision", "=", "zeroCmpTwo", "(", "old", ".", "Revision", ",", "new", ".", "Revision", ",", "nil", ")", "\n", "if", "ret", ".", "Revision", "==", "ManifestDiff_MODIFIED", "{", "ret", ".", "Revision", "=", "ManifestDiff_DIFF", "\n", "}", "\n\n", "// We calculate DIFF for PatchRevision iff the two checkouts both include", "// patches from the same CL.", "ret", ".", "PatchRevision", "=", "zeroCmpTwo", "(", "old", ".", "PatchRevision", ",", "new", ".", "PatchRevision", ",", "nil", ")", "\n", "if", "ret", ".", "PatchRevision", "==", "ManifestDiff_MODIFIED", "{", "oldCL", ",", "newCL", ":=", "parseChangeRef", "(", "old", ".", "PatchFetchRef", ")", ",", "parseChangeRef", "(", "new", ".", "PatchFetchRef", ")", "\n", "if", "oldCL", "!=", "\"", "\"", "&&", "newCL", "!=", "\"", "\"", "&&", "oldCL", "==", "newCL", "{", "ret", ".", "PatchRevision", "=", "ManifestDiff_DIFF", "\n", "}", "\n", "}", "\n\n", "// If all the revisions are the same and the repo url is the same, that's", "// good enough for the whole checkout to be equal.", "if", "ret", ".", "Revision", "==", "ManifestDiff_EQUAL", "&&", "ret", ".", "PatchRevision", "==", "ManifestDiff_EQUAL", "{", "return", "ManifestDiff_EQUAL", "\n", "}", "\n", "}", "\n\n", "return", "ManifestDiff_MODIFIED", "\n", "}", ")", "\n\n", "return", "ret", "\n", "}" ]
// Diff generates a Stat reflecting the difference between the `old` // GitCheckout and the `new` one. // // This will generate a Stat of `DIFF` if the two GitCheckout's are non-nil and // share the same RepoUrl. // // This only calculates the pure-data differences. Notably, this will not reach // out to any remote services to populate the git_history field.
[ "Diff", "generates", "a", "Stat", "reflecting", "the", "difference", "between", "the", "old", "GitCheckout", "and", "the", "new", "one", ".", "This", "will", "generate", "a", "Stat", "of", "DIFF", "if", "the", "two", "GitCheckout", "s", "are", "non", "-", "nil", "and", "share", "the", "same", "RepoUrl", ".", "This", "only", "calculates", "the", "pure", "-", "data", "differences", ".", "Notably", "this", "will", "not", "reach", "out", "to", "any", "remote", "services", "to", "populate", "the", "git_history", "field", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/srcman/diff.go#L123-L163
8,157
luci/luci-go
common/proto/srcman/diff.go
Diff
func (old *Manifest_CIPDPackage) Diff(new *Manifest_CIPDPackage) ManifestDiff_Stat { return zeroCmpTwo(old, new, func() ManifestDiff_Stat { // Version and PackagePattern don't matter for diff purposes. return zeroCmpTwo(old.InstanceId, new.InstanceId, nil) }) }
go
func (old *Manifest_CIPDPackage) Diff(new *Manifest_CIPDPackage) ManifestDiff_Stat { return zeroCmpTwo(old, new, func() ManifestDiff_Stat { // Version and PackagePattern don't matter for diff purposes. return zeroCmpTwo(old.InstanceId, new.InstanceId, nil) }) }
[ "func", "(", "old", "*", "Manifest_CIPDPackage", ")", "Diff", "(", "new", "*", "Manifest_CIPDPackage", ")", "ManifestDiff_Stat", "{", "return", "zeroCmpTwo", "(", "old", ",", "new", ",", "func", "(", ")", "ManifestDiff_Stat", "{", "// Version and PackagePattern don't matter for diff purposes.", "return", "zeroCmpTwo", "(", "old", ".", "InstanceId", ",", "new", ".", "InstanceId", ",", "nil", ")", "\n", "}", ")", "\n", "}" ]
// Diff generates a ManifestDiff_Stat reflecting the difference between the `old` // CIPDPackage and the `new` one.
[ "Diff", "generates", "a", "ManifestDiff_Stat", "reflecting", "the", "difference", "between", "the", "old", "CIPDPackage", "and", "the", "new", "one", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/srcman/diff.go#L167-L172
8,158
luci/luci-go
common/proto/srcman/diff.go
IsolatedDiff
func IsolatedDiff(oldisos, newisos []*Manifest_Isolated) ManifestDiff_Stat { return zeroCmpTwo(oldisos, newisos, func() ManifestDiff_Stat { // we know they're non-zero and also have the same length at this point for i, old := range oldisos { new := newisos[i] if old.Namespace != new.Namespace { return ManifestDiff_MODIFIED } if old.Hash != new.Hash { return ManifestDiff_MODIFIED } } return ManifestDiff_EQUAL }) }
go
func IsolatedDiff(oldisos, newisos []*Manifest_Isolated) ManifestDiff_Stat { return zeroCmpTwo(oldisos, newisos, func() ManifestDiff_Stat { // we know they're non-zero and also have the same length at this point for i, old := range oldisos { new := newisos[i] if old.Namespace != new.Namespace { return ManifestDiff_MODIFIED } if old.Hash != new.Hash { return ManifestDiff_MODIFIED } } return ManifestDiff_EQUAL }) }
[ "func", "IsolatedDiff", "(", "oldisos", ",", "newisos", "[", "]", "*", "Manifest_Isolated", ")", "ManifestDiff_Stat", "{", "return", "zeroCmpTwo", "(", "oldisos", ",", "newisos", ",", "func", "(", ")", "ManifestDiff_Stat", "{", "// we know they're non-zero and also have the same length at this point", "for", "i", ",", "old", ":=", "range", "oldisos", "{", "new", ":=", "newisos", "[", "i", "]", "\n", "if", "old", ".", "Namespace", "!=", "new", ".", "Namespace", "{", "return", "ManifestDiff_MODIFIED", "\n", "}", "\n", "if", "old", ".", "Hash", "!=", "new", ".", "Hash", "{", "return", "ManifestDiff_MODIFIED", "\n", "}", "\n", "}", "\n", "return", "ManifestDiff_EQUAL", "\n", "}", ")", "\n", "}" ]
// IsolatedDiff produces a ManifestDiff_Stat reflecting the difference between // two lists of Manifest_Isolated's.
[ "IsolatedDiff", "produces", "a", "ManifestDiff_Stat", "reflecting", "the", "difference", "between", "two", "lists", "of", "Manifest_Isolated", "s", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/srcman/diff.go#L176-L190
8,159
luci/luci-go
common/proto/srcman/diff.go
Diff
func (old *Manifest_Directory) Diff(new *Manifest_Directory) *ManifestDiff_Directory { ret := &ManifestDiff_Directory{} ret.Overall = zeroCmpTwo(old, new, func() ManifestDiff_Stat { var dirChanged modifiedTracker if ret.GitCheckout = old.GitCheckout.Diff(new.GitCheckout); ret.GitCheckout != nil { dirChanged.add(ret.GitCheckout.Overall) } ret.CipdServerHost = dirChanged.add(zeroCmpTwo(old.CipdServerHost, new.CipdServerHost, nil)) if ret.CipdServerHost == ManifestDiff_EQUAL && new.CipdServerHost != "" { cipdPackages := map[string]ManifestDiff_Stat{} for name, pkg := range old.CipdPackage { cipdPackages[name] = dirChanged.add(pkg.Diff(new.CipdPackage[name])) } for name, pkg := range new.CipdPackage { if _, ok := cipdPackages[name]; !ok { cipdPackages[name] = dirChanged.add(old.CipdPackage[name].Diff(pkg)) } } if len(cipdPackages) > 0 { ret.CipdPackage = cipdPackages } } ret.IsolatedServerHost = dirChanged.add(zeroCmpTwo(old.IsolatedServerHost, new.IsolatedServerHost, nil)) ret.Isolated = dirChanged.add(IsolatedDiff(old.Isolated, new.Isolated)) return dirChanged.status() }) return ret }
go
func (old *Manifest_Directory) Diff(new *Manifest_Directory) *ManifestDiff_Directory { ret := &ManifestDiff_Directory{} ret.Overall = zeroCmpTwo(old, new, func() ManifestDiff_Stat { var dirChanged modifiedTracker if ret.GitCheckout = old.GitCheckout.Diff(new.GitCheckout); ret.GitCheckout != nil { dirChanged.add(ret.GitCheckout.Overall) } ret.CipdServerHost = dirChanged.add(zeroCmpTwo(old.CipdServerHost, new.CipdServerHost, nil)) if ret.CipdServerHost == ManifestDiff_EQUAL && new.CipdServerHost != "" { cipdPackages := map[string]ManifestDiff_Stat{} for name, pkg := range old.CipdPackage { cipdPackages[name] = dirChanged.add(pkg.Diff(new.CipdPackage[name])) } for name, pkg := range new.CipdPackage { if _, ok := cipdPackages[name]; !ok { cipdPackages[name] = dirChanged.add(old.CipdPackage[name].Diff(pkg)) } } if len(cipdPackages) > 0 { ret.CipdPackage = cipdPackages } } ret.IsolatedServerHost = dirChanged.add(zeroCmpTwo(old.IsolatedServerHost, new.IsolatedServerHost, nil)) ret.Isolated = dirChanged.add(IsolatedDiff(old.Isolated, new.Isolated)) return dirChanged.status() }) return ret }
[ "func", "(", "old", "*", "Manifest_Directory", ")", "Diff", "(", "new", "*", "Manifest_Directory", ")", "*", "ManifestDiff_Directory", "{", "ret", ":=", "&", "ManifestDiff_Directory", "{", "}", "\n\n", "ret", ".", "Overall", "=", "zeroCmpTwo", "(", "old", ",", "new", ",", "func", "(", ")", "ManifestDiff_Stat", "{", "var", "dirChanged", "modifiedTracker", "\n\n", "if", "ret", ".", "GitCheckout", "=", "old", ".", "GitCheckout", ".", "Diff", "(", "new", ".", "GitCheckout", ")", ";", "ret", ".", "GitCheckout", "!=", "nil", "{", "dirChanged", ".", "add", "(", "ret", ".", "GitCheckout", ".", "Overall", ")", "\n", "}", "\n\n", "ret", ".", "CipdServerHost", "=", "dirChanged", ".", "add", "(", "zeroCmpTwo", "(", "old", ".", "CipdServerHost", ",", "new", ".", "CipdServerHost", ",", "nil", ")", ")", "\n", "if", "ret", ".", "CipdServerHost", "==", "ManifestDiff_EQUAL", "&&", "new", ".", "CipdServerHost", "!=", "\"", "\"", "{", "cipdPackages", ":=", "map", "[", "string", "]", "ManifestDiff_Stat", "{", "}", "\n\n", "for", "name", ",", "pkg", ":=", "range", "old", ".", "CipdPackage", "{", "cipdPackages", "[", "name", "]", "=", "dirChanged", ".", "add", "(", "pkg", ".", "Diff", "(", "new", ".", "CipdPackage", "[", "name", "]", ")", ")", "\n", "}", "\n", "for", "name", ",", "pkg", ":=", "range", "new", ".", "CipdPackage", "{", "if", "_", ",", "ok", ":=", "cipdPackages", "[", "name", "]", ";", "!", "ok", "{", "cipdPackages", "[", "name", "]", "=", "dirChanged", ".", "add", "(", "old", ".", "CipdPackage", "[", "name", "]", ".", "Diff", "(", "pkg", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "cipdPackages", ")", ">", "0", "{", "ret", ".", "CipdPackage", "=", "cipdPackages", "\n", "}", "\n", "}", "\n\n", "ret", ".", "IsolatedServerHost", "=", "dirChanged", ".", "add", "(", "zeroCmpTwo", "(", "old", ".", "IsolatedServerHost", ",", "new", ".", "IsolatedServerHost", ",", "nil", ")", ")", "\n", "ret", ".", "Isolated", "=", "dirChanged", ".", "add", "(", "IsolatedDiff", "(", "old", ".", "Isolated", ",", "new", ".", "Isolated", ")", ")", "\n\n", "return", "dirChanged", ".", "status", "(", ")", "\n", "}", ")", "\n\n", "return", "ret", "\n", "}" ]
// Diff generates a ManifestDiff_Directory object which shows what changed // between the `old` manifest directory and the `new` manifest directory.
[ "Diff", "generates", "a", "ManifestDiff_Directory", "object", "which", "shows", "what", "changed", "between", "the", "old", "manifest", "directory", "and", "the", "new", "manifest", "directory", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/srcman/diff.go#L194-L229
8,160
luci/luci-go
common/proto/srcman/diff.go
Diff
func (old *Manifest) Diff(new *Manifest) *ManifestDiff { ret := &ManifestDiff{ Old: old, New: new, Directories: map[string]*ManifestDiff_Directory{}, } ret.Overall = zeroCmpTwo(old, new, func() ManifestDiff_Stat { var anyChanged modifiedTracker for path, olddir := range old.Directories { dir := olddir.Diff(new.Directories[path]) ret.Directories[path] = dir anyChanged.add(dir.Overall) } for path, newdir := range new.Directories { if _, ok := ret.Directories[path]; !ok { dir := old.Directories[path].Diff(newdir) ret.Directories[path] = dir anyChanged.add(dir.Overall) } } return anyChanged.status() }) return ret }
go
func (old *Manifest) Diff(new *Manifest) *ManifestDiff { ret := &ManifestDiff{ Old: old, New: new, Directories: map[string]*ManifestDiff_Directory{}, } ret.Overall = zeroCmpTwo(old, new, func() ManifestDiff_Stat { var anyChanged modifiedTracker for path, olddir := range old.Directories { dir := olddir.Diff(new.Directories[path]) ret.Directories[path] = dir anyChanged.add(dir.Overall) } for path, newdir := range new.Directories { if _, ok := ret.Directories[path]; !ok { dir := old.Directories[path].Diff(newdir) ret.Directories[path] = dir anyChanged.add(dir.Overall) } } return anyChanged.status() }) return ret }
[ "func", "(", "old", "*", "Manifest", ")", "Diff", "(", "new", "*", "Manifest", ")", "*", "ManifestDiff", "{", "ret", ":=", "&", "ManifestDiff", "{", "Old", ":", "old", ",", "New", ":", "new", ",", "Directories", ":", "map", "[", "string", "]", "*", "ManifestDiff_Directory", "{", "}", ",", "}", "\n", "ret", ".", "Overall", "=", "zeroCmpTwo", "(", "old", ",", "new", ",", "func", "(", ")", "ManifestDiff_Stat", "{", "var", "anyChanged", "modifiedTracker", "\n\n", "for", "path", ",", "olddir", ":=", "range", "old", ".", "Directories", "{", "dir", ":=", "olddir", ".", "Diff", "(", "new", ".", "Directories", "[", "path", "]", ")", "\n", "ret", ".", "Directories", "[", "path", "]", "=", "dir", "\n", "anyChanged", ".", "add", "(", "dir", ".", "Overall", ")", "\n", "}", "\n", "for", "path", ",", "newdir", ":=", "range", "new", ".", "Directories", "{", "if", "_", ",", "ok", ":=", "ret", ".", "Directories", "[", "path", "]", ";", "!", "ok", "{", "dir", ":=", "old", ".", "Directories", "[", "path", "]", ".", "Diff", "(", "newdir", ")", "\n", "ret", ".", "Directories", "[", "path", "]", "=", "dir", "\n", "anyChanged", ".", "add", "(", "dir", ".", "Overall", ")", "\n", "}", "\n", "}", "\n\n", "return", "anyChanged", ".", "status", "(", ")", "\n", "}", ")", "\n", "return", "ret", "\n", "}" ]
// Diff generates a ManifestDiff object which shows what changed between the // `old` manifest and the `new` manifest. // // This only calculates the pure-data differences. Notably, this will not reach // out to any remote services to populate the git_history field.
[ "Diff", "generates", "a", "ManifestDiff", "object", "which", "shows", "what", "changed", "between", "the", "old", "manifest", "and", "the", "new", "manifest", ".", "This", "only", "calculates", "the", "pure", "-", "data", "differences", ".", "Notably", "this", "will", "not", "reach", "out", "to", "any", "remote", "services", "to", "populate", "the", "git_history", "field", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/srcman/diff.go#L236-L261
8,161
luci/luci-go
dm/api/template/loader.go
LoadFile
func LoadFile(c context.Context, project, ref string) (file *File, vers string, err error) { // If ref is "", this will be a standard project config set. cfgSet := config.RefSet(project, ref) file = &File{} var meta config.Meta if err = cfgclient.Get(c, cfgclient.AsService, cfgSet, "dm/quest_templates.cfg", textproto.Message(file), &meta); err != nil { return } vers = meta.ContentHash err = file.Normalize() return }
go
func LoadFile(c context.Context, project, ref string) (file *File, vers string, err error) { // If ref is "", this will be a standard project config set. cfgSet := config.RefSet(project, ref) file = &File{} var meta config.Meta if err = cfgclient.Get(c, cfgclient.AsService, cfgSet, "dm/quest_templates.cfg", textproto.Message(file), &meta); err != nil { return } vers = meta.ContentHash err = file.Normalize() return }
[ "func", "LoadFile", "(", "c", "context", ".", "Context", ",", "project", ",", "ref", "string", ")", "(", "file", "*", "File", ",", "vers", "string", ",", "err", "error", ")", "{", "// If ref is \"\", this will be a standard project config set.", "cfgSet", ":=", "config", ".", "RefSet", "(", "project", ",", "ref", ")", "\n\n", "file", "=", "&", "File", "{", "}", "\n", "var", "meta", "config", ".", "Meta", "\n", "if", "err", "=", "cfgclient", ".", "Get", "(", "c", ",", "cfgclient", ".", "AsService", ",", "cfgSet", ",", "\"", "\"", ",", "textproto", ".", "Message", "(", "file", ")", ",", "&", "meta", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "vers", "=", "meta", ".", "ContentHash", "\n", "err", "=", "file", ".", "Normalize", "(", ")", "\n", "return", "\n", "}" ]
// LoadFile loads a File by configSet and path.
[ "LoadFile", "loads", "a", "File", "by", "configSet", "and", "path", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/template/loader.go#L29-L41
8,162
luci/luci-go
dm/api/service/v1/attempt_data.go
NewJsonResult
func NewJsonResult(data string, exps ...time.Time) *JsonResult { exp := time.Time{} switch l := len(exps); { case l == 1: exp = exps[0] case l > 1: panic("too many exps") } return &JsonResult{ Object: data, Size: uint32(len(data)), Expiration: google_pb.NewTimestamp(exp), } }
go
func NewJsonResult(data string, exps ...time.Time) *JsonResult { exp := time.Time{} switch l := len(exps); { case l == 1: exp = exps[0] case l > 1: panic("too many exps") } return &JsonResult{ Object: data, Size: uint32(len(data)), Expiration: google_pb.NewTimestamp(exp), } }
[ "func", "NewJsonResult", "(", "data", "string", ",", "exps", "...", "time", ".", "Time", ")", "*", "JsonResult", "{", "exp", ":=", "time", ".", "Time", "{", "}", "\n", "switch", "l", ":=", "len", "(", "exps", ")", ";", "{", "case", "l", "==", "1", ":", "exp", "=", "exps", "[", "0", "]", "\n", "case", "l", ">", "1", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "JsonResult", "{", "Object", ":", "data", ",", "Size", ":", "uint32", "(", "len", "(", "data", ")", ")", ",", "Expiration", ":", "google_pb", ".", "NewTimestamp", "(", "exp", ")", ",", "}", "\n", "}" ]
// NewJsonResult creates a new JsonResult object with optional expiration time.
[ "NewJsonResult", "creates", "a", "new", "JsonResult", "object", "with", "optional", "expiration", "time", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_data.go#L24-L37
8,163
luci/luci-go
dm/api/service/v1/attempt_data.go
NewDatalessJsonResult
func NewDatalessJsonResult(size uint32, exps ...time.Time) *JsonResult { exp := time.Time{} switch l := len(exps); { case l == 1: exp = exps[0] case l > 1: panic("too many exps") } return &JsonResult{Size: size, Expiration: google_pb.NewTimestamp(exp)} }
go
func NewDatalessJsonResult(size uint32, exps ...time.Time) *JsonResult { exp := time.Time{} switch l := len(exps); { case l == 1: exp = exps[0] case l > 1: panic("too many exps") } return &JsonResult{Size: size, Expiration: google_pb.NewTimestamp(exp)} }
[ "func", "NewDatalessJsonResult", "(", "size", "uint32", ",", "exps", "...", "time", ".", "Time", ")", "*", "JsonResult", "{", "exp", ":=", "time", ".", "Time", "{", "}", "\n", "switch", "l", ":=", "len", "(", "exps", ")", ";", "{", "case", "l", "==", "1", ":", "exp", "=", "exps", "[", "0", "]", "\n", "case", "l", ">", "1", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "JsonResult", "{", "Size", ":", "size", ",", "Expiration", ":", "google_pb", ".", "NewTimestamp", "(", "exp", ")", "}", "\n", "}" ]
// NewDatalessJsonResult creates a new JsonResult object without data and with // optional expiration time.
[ "NewDatalessJsonResult", "creates", "a", "new", "JsonResult", "object", "without", "data", "and", "with", "optional", "expiration", "time", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_data.go#L41-L50
8,164
luci/luci-go
dm/api/service/v1/attempt_data.go
NewAttemptExecuting
func NewAttemptExecuting(curExID uint32) *Attempt { return &Attempt{ Data: &Attempt_Data{ NumExecutions: curExID, AttemptType: &Attempt_Data_Executing_{ &Attempt_Data_Executing{CurExecutionId: curExID}}}} }
go
func NewAttemptExecuting(curExID uint32) *Attempt { return &Attempt{ Data: &Attempt_Data{ NumExecutions: curExID, AttemptType: &Attempt_Data_Executing_{ &Attempt_Data_Executing{CurExecutionId: curExID}}}} }
[ "func", "NewAttemptExecuting", "(", "curExID", "uint32", ")", "*", "Attempt", "{", "return", "&", "Attempt", "{", "Data", ":", "&", "Attempt_Data", "{", "NumExecutions", ":", "curExID", ",", "AttemptType", ":", "&", "Attempt_Data_Executing_", "{", "&", "Attempt_Data_Executing", "{", "CurExecutionId", ":", "curExID", "}", "}", "}", "}", "\n", "}" ]
// NewAttemptExecuting creates an Attempt in the EXECUTING state.
[ "NewAttemptExecuting", "creates", "an", "Attempt", "in", "the", "EXECUTING", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_data.go#L61-L67
8,165
luci/luci-go
dm/api/service/v1/attempt_data.go
NewAttemptWaiting
func NewAttemptWaiting(numWaiting uint32) *Attempt { return &Attempt{ Data: &Attempt_Data{ AttemptType: &Attempt_Data_Waiting_{ &Attempt_Data_Waiting{NumWaiting: numWaiting}}}} }
go
func NewAttemptWaiting(numWaiting uint32) *Attempt { return &Attempt{ Data: &Attempt_Data{ AttemptType: &Attempt_Data_Waiting_{ &Attempt_Data_Waiting{NumWaiting: numWaiting}}}} }
[ "func", "NewAttemptWaiting", "(", "numWaiting", "uint32", ")", "*", "Attempt", "{", "return", "&", "Attempt", "{", "Data", ":", "&", "Attempt_Data", "{", "AttemptType", ":", "&", "Attempt_Data_Waiting_", "{", "&", "Attempt_Data_Waiting", "{", "NumWaiting", ":", "numWaiting", "}", "}", "}", "}", "\n", "}" ]
// NewAttemptWaiting creates an Attempt in the WAITING state.
[ "NewAttemptWaiting", "creates", "an", "Attempt", "in", "the", "WAITING", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_data.go#L70-L75
8,166
luci/luci-go
dm/api/service/v1/attempt_data.go
NewAttemptFinished
func NewAttemptFinished(result *JsonResult) *Attempt { return &Attempt{ Data: &Attempt_Data{ AttemptType: &Attempt_Data_Finished_{ &Attempt_Data_Finished{Data: result}}}} }
go
func NewAttemptFinished(result *JsonResult) *Attempt { return &Attempt{ Data: &Attempt_Data{ AttemptType: &Attempt_Data_Finished_{ &Attempt_Data_Finished{Data: result}}}} }
[ "func", "NewAttemptFinished", "(", "result", "*", "JsonResult", ")", "*", "Attempt", "{", "return", "&", "Attempt", "{", "Data", ":", "&", "Attempt_Data", "{", "AttemptType", ":", "&", "Attempt_Data_Finished_", "{", "&", "Attempt_Data_Finished", "{", "Data", ":", "result", "}", "}", "}", "}", "\n", "}" ]
// NewAttemptFinished creates an Attempt in the FINISHED state.
[ "NewAttemptFinished", "creates", "an", "Attempt", "in", "the", "FINISHED", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_data.go#L78-L83
8,167
luci/luci-go
dm/api/service/v1/attempt_data.go
NewAttemptAbnormalFinish
func NewAttemptAbnormalFinish(af *AbnormalFinish) *Attempt { return &Attempt{ Data: &Attempt_Data{ AttemptType: &Attempt_Data_AbnormalFinish{af}}} }
go
func NewAttemptAbnormalFinish(af *AbnormalFinish) *Attempt { return &Attempt{ Data: &Attempt_Data{ AttemptType: &Attempt_Data_AbnormalFinish{af}}} }
[ "func", "NewAttemptAbnormalFinish", "(", "af", "*", "AbnormalFinish", ")", "*", "Attempt", "{", "return", "&", "Attempt", "{", "Data", ":", "&", "Attempt_Data", "{", "AttemptType", ":", "&", "Attempt_Data_AbnormalFinish", "{", "af", "}", "}", "}", "\n", "}" ]
// NewAttemptAbnormalFinish creates an Attempt in the ABNORMAL_FINISH state.
[ "NewAttemptAbnormalFinish", "creates", "an", "Attempt", "in", "the", "ABNORMAL_FINISH", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_data.go#L86-L90
8,168
luci/luci-go
dm/api/service/v1/attempt_data.go
State
func (d *Attempt_Data) State() Attempt_State { if d != nil { switch d.AttemptType.(type) { case *Attempt_Data_Scheduling_: return Attempt_SCHEDULING case *Attempt_Data_Executing_: return Attempt_EXECUTING case *Attempt_Data_Waiting_: return Attempt_WAITING case *Attempt_Data_Finished_: return Attempt_FINISHED case *Attempt_Data_AbnormalFinish: return Attempt_ABNORMAL_FINISHED } } return Attempt_SCHEDULING }
go
func (d *Attempt_Data) State() Attempt_State { if d != nil { switch d.AttemptType.(type) { case *Attempt_Data_Scheduling_: return Attempt_SCHEDULING case *Attempt_Data_Executing_: return Attempt_EXECUTING case *Attempt_Data_Waiting_: return Attempt_WAITING case *Attempt_Data_Finished_: return Attempt_FINISHED case *Attempt_Data_AbnormalFinish: return Attempt_ABNORMAL_FINISHED } } return Attempt_SCHEDULING }
[ "func", "(", "d", "*", "Attempt_Data", ")", "State", "(", ")", "Attempt_State", "{", "if", "d", "!=", "nil", "{", "switch", "d", ".", "AttemptType", ".", "(", "type", ")", "{", "case", "*", "Attempt_Data_Scheduling_", ":", "return", "Attempt_SCHEDULING", "\n", "case", "*", "Attempt_Data_Executing_", ":", "return", "Attempt_EXECUTING", "\n", "case", "*", "Attempt_Data_Waiting_", ":", "return", "Attempt_WAITING", "\n", "case", "*", "Attempt_Data_Finished_", ":", "return", "Attempt_FINISHED", "\n", "case", "*", "Attempt_Data_AbnormalFinish", ":", "return", "Attempt_ABNORMAL_FINISHED", "\n", "}", "\n", "}", "\n", "return", "Attempt_SCHEDULING", "\n", "}" ]
// State computes the Attempt_State for the current Attempt_Data
[ "State", "computes", "the", "Attempt_State", "for", "the", "current", "Attempt_Data" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_data.go#L93-L109
8,169
luci/luci-go
dm/api/service/v1/attempt_data.go
NormalizePartial
func (d *Attempt) NormalizePartial() { p := d.GetPartial() if p == nil { return } if !(p.Data || p.Executions || p.FwdDeps || p.BackDeps || p.Result != Attempt_Partial_LOADED) { d.Partial = nil } }
go
func (d *Attempt) NormalizePartial() { p := d.GetPartial() if p == nil { return } if !(p.Data || p.Executions || p.FwdDeps || p.BackDeps || p.Result != Attempt_Partial_LOADED) { d.Partial = nil } }
[ "func", "(", "d", "*", "Attempt", ")", "NormalizePartial", "(", ")", "{", "p", ":=", "d", ".", "GetPartial", "(", ")", "\n", "if", "p", "==", "nil", "{", "return", "\n", "}", "\n", "if", "!", "(", "p", ".", "Data", "||", "p", ".", "Executions", "||", "p", ".", "FwdDeps", "||", "p", ".", "BackDeps", "||", "p", ".", "Result", "!=", "Attempt_Partial_LOADED", ")", "{", "d", ".", "Partial", "=", "nil", "\n", "}", "\n", "}" ]
// NormalizePartial will nil out the Partial field for this Attempt if all // Partial fields are false.
[ "NormalizePartial", "will", "nil", "out", "the", "Partial", "field", "for", "this", "Attempt", "if", "all", "Partial", "fields", "are", "false", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_data.go#L113-L122
8,170
luci/luci-go
dm/api/service/v1/attempt_data.go
Any
func (p *Attempt_Partial) Any() bool { return (p.BackDeps || p.Data || p.Executions || p.FwdDeps || p.Result == Attempt_Partial_NOT_LOADED) }
go
func (p *Attempt_Partial) Any() bool { return (p.BackDeps || p.Data || p.Executions || p.FwdDeps || p.Result == Attempt_Partial_NOT_LOADED) }
[ "func", "(", "p", "*", "Attempt_Partial", ")", "Any", "(", ")", "bool", "{", "return", "(", "p", ".", "BackDeps", "||", "p", ".", "Data", "||", "p", ".", "Executions", "||", "p", ".", "FwdDeps", "||", "p", ".", "Result", "==", "Attempt_Partial_NOT_LOADED", ")", "\n", "}" ]
// Any returns true iff any of the Partial fields are true such that they could // be successfully loaded on a subsequent query.
[ "Any", "returns", "true", "iff", "any", "of", "the", "Partial", "fields", "are", "true", "such", "that", "they", "could", "be", "successfully", "loaded", "on", "a", "subsequent", "query", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_data.go#L126-L129
8,171
luci/luci-go
common/sync/parallel/workPool.go
WorkPool
func WorkPool(workers int, gen func(chan<- func() error)) error { return multiErrorFromErrors(Run(workers, gen)) }
go
func WorkPool(workers int, gen func(chan<- func() error)) error { return multiErrorFromErrors(Run(workers, gen)) }
[ "func", "WorkPool", "(", "workers", "int", ",", "gen", "func", "(", "chan", "<-", "func", "(", ")", "error", ")", ")", "error", "{", "return", "multiErrorFromErrors", "(", "Run", "(", "workers", ",", "gen", ")", ")", "\n", "}" ]
// WorkPool creates a fixed-size pool of worker goroutines. A supplied generator // method creates task functions and passes them through to the work pool. // // WorkPool will use at most workers goroutines to execute the supplied tasks. // If workers is <= 0, WorkPool will be unbounded and behave like FanOutIn. // // WorkPool blocks until all the generator completes and all workers have // finished their tasks.
[ "WorkPool", "creates", "a", "fixed", "-", "size", "pool", "of", "worker", "goroutines", ".", "A", "supplied", "generator", "method", "creates", "task", "functions", "and", "passes", "them", "through", "to", "the", "work", "pool", ".", "WorkPool", "will", "use", "at", "most", "workers", "goroutines", "to", "execute", "the", "supplied", "tasks", ".", "If", "workers", "is", "<", "=", "0", "WorkPool", "will", "be", "unbounded", "and", "behave", "like", "FanOutIn", ".", "WorkPool", "blocks", "until", "all", "the", "generator", "completes", "and", "all", "workers", "have", "finished", "their", "tasks", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/workPool.go#L29-L31
8,172
luci/luci-go
common/sync/parallel/workPool.go
multiErrorFromErrors
func multiErrorFromErrors(ch <-chan error) error { if ch == nil { return nil } ret := errors.MultiError(nil) for e := range ch { if e == nil { continue } ret = append(ret, e) } if len(ret) == 0 { return nil } return ret }
go
func multiErrorFromErrors(ch <-chan error) error { if ch == nil { return nil } ret := errors.MultiError(nil) for e := range ch { if e == nil { continue } ret = append(ret, e) } if len(ret) == 0 { return nil } return ret }
[ "func", "multiErrorFromErrors", "(", "ch", "<-", "chan", "error", ")", "error", "{", "if", "ch", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "ret", ":=", "errors", ".", "MultiError", "(", "nil", ")", "\n", "for", "e", ":=", "range", "ch", "{", "if", "e", "==", "nil", "{", "continue", "\n", "}", "\n", "ret", "=", "append", "(", "ret", ",", "e", ")", "\n", "}", "\n", "if", "len", "(", "ret", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// multiErrorFromErrors takes an error-channel, blocks on it, and returns // a MultiError for any errors pushed to it over the channel, or nil if // all the errors were nil.
[ "multiErrorFromErrors", "takes", "an", "error", "-", "channel", "blocks", "on", "it", "and", "returns", "a", "MultiError", "for", "any", "errors", "pushed", "to", "it", "over", "the", "channel", "or", "nil", "if", "all", "the", "errors", "were", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/workPool.go#L51-L66
8,173
luci/luci-go
vpython/venv/venv.go
blocker
func blocker(c context.Context) fslock.Blocker { return func() error { logging.Debugf(c, "Lock is currently held. Sleeping %v and retrying...", lockHeldDelay) tr := clock.Sleep(c, lockHeldDelay) return tr.Err } }
go
func blocker(c context.Context) fslock.Blocker { return func() error { logging.Debugf(c, "Lock is currently held. Sleeping %v and retrying...", lockHeldDelay) tr := clock.Sleep(c, lockHeldDelay) return tr.Err } }
[ "func", "blocker", "(", "c", "context", ".", "Context", ")", "fslock", ".", "Blocker", "{", "return", "func", "(", ")", "error", "{", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "lockHeldDelay", ")", "\n", "tr", ":=", "clock", ".", "Sleep", "(", "c", ",", "lockHeldDelay", ")", "\n", "return", "tr", ".", "Err", "\n", "}", "\n", "}" ]
// blocker is an fslock.Blocker implementation that sleeps lockHeldDelay in // between attempts.
[ "blocker", "is", "an", "fslock", ".", "Blocker", "implementation", "that", "sleeps", "lockHeldDelay", "in", "between", "attempts", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L87-L93
8,174
luci/luci-go
vpython/venv/venv.go
With
func With(c context.Context, cfg Config, fn func(context.Context, *Env) error) error { // Track which VirtualEnv we use so we can exempt them from pruning. usedEnvs := stringset.New(2) // Start with an empty VirtualEnv. We will use this to probe the local // system. // // If our configured VirtualEnv is, itself, an empty then we can // skip this. var e *vpython.Environment if cfg.HasWheels() { // Use an empty VirtualEnv to probe the runtime environment. // // Disable pruning for this step since we'll be doing that later with the // full environment initialization. emptyEnv, err := cfg.WithoutWheels().makeEnv(c, nil) if err != nil { return errors.Annotate(err, "failed to initialize empty probe environment").Err() } if err := emptyEnv.ensure(c, !cfg.FailIfLocked); err != nil { return errors.Annotate(err, "failed to create empty probe environment").Err() } usedEnvs.Add(emptyEnv.Name) e = emptyEnv.Environment } // Run the real config, now with runtime data. env, err := cfg.makeEnv(c, e) if err != nil { return err } usedEnvs.Add(env.Name) return env.withImpl(c, !cfg.FailIfLocked, usedEnvs, fn) }
go
func With(c context.Context, cfg Config, fn func(context.Context, *Env) error) error { // Track which VirtualEnv we use so we can exempt them from pruning. usedEnvs := stringset.New(2) // Start with an empty VirtualEnv. We will use this to probe the local // system. // // If our configured VirtualEnv is, itself, an empty then we can // skip this. var e *vpython.Environment if cfg.HasWheels() { // Use an empty VirtualEnv to probe the runtime environment. // // Disable pruning for this step since we'll be doing that later with the // full environment initialization. emptyEnv, err := cfg.WithoutWheels().makeEnv(c, nil) if err != nil { return errors.Annotate(err, "failed to initialize empty probe environment").Err() } if err := emptyEnv.ensure(c, !cfg.FailIfLocked); err != nil { return errors.Annotate(err, "failed to create empty probe environment").Err() } usedEnvs.Add(emptyEnv.Name) e = emptyEnv.Environment } // Run the real config, now with runtime data. env, err := cfg.makeEnv(c, e) if err != nil { return err } usedEnvs.Add(env.Name) return env.withImpl(c, !cfg.FailIfLocked, usedEnvs, fn) }
[ "func", "With", "(", "c", "context", ".", "Context", ",", "cfg", "Config", ",", "fn", "func", "(", "context", ".", "Context", ",", "*", "Env", ")", "error", ")", "error", "{", "// Track which VirtualEnv we use so we can exempt them from pruning.", "usedEnvs", ":=", "stringset", ".", "New", "(", "2", ")", "\n\n", "// Start with an empty VirtualEnv. We will use this to probe the local", "// system.", "//", "// If our configured VirtualEnv is, itself, an empty then we can", "// skip this.", "var", "e", "*", "vpython", ".", "Environment", "\n", "if", "cfg", ".", "HasWheels", "(", ")", "{", "// Use an empty VirtualEnv to probe the runtime environment.", "//", "// Disable pruning for this step since we'll be doing that later with the", "// full environment initialization.", "emptyEnv", ",", "err", ":=", "cfg", ".", "WithoutWheels", "(", ")", ".", "makeEnv", "(", "c", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "err", ":=", "emptyEnv", ".", "ensure", "(", "c", ",", "!", "cfg", ".", "FailIfLocked", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "usedEnvs", ".", "Add", "(", "emptyEnv", ".", "Name", ")", "\n", "e", "=", "emptyEnv", ".", "Environment", "\n", "}", "\n\n", "// Run the real config, now with runtime data.", "env", ",", "err", ":=", "cfg", ".", "makeEnv", "(", "c", ",", "e", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "usedEnvs", ".", "Add", "(", "env", ".", "Name", ")", "\n", "return", "env", ".", "withImpl", "(", "c", ",", "!", "cfg", ".", "FailIfLocked", ",", "usedEnvs", ",", "fn", ")", "\n", "}" ]
// With creates a new Env and executes "fn" with assumed ownership of that Env. // // The Context passed to "fn" will be cancelled if we lose perceived ownership // of the configured environment. This is not an expected scenario, and should // be considered an error condition. The Env passed to "fn" is valid only for // the duration of the callback. // // It will lock around the VirtualEnv to ensure that multiple processes do not // conflict with each other. If a VirtualEnv for this specification already // exists, it will be used directly without any additional setup. // // If another process holds the lock, With will return an error if // cfg.FailIfLocked is true, or try again until it obtains the lock otherwise.
[ "With", "creates", "a", "new", "Env", "and", "executes", "fn", "with", "assumed", "ownership", "of", "that", "Env", ".", "The", "Context", "passed", "to", "fn", "will", "be", "cancelled", "if", "we", "lose", "perceived", "ownership", "of", "the", "configured", "environment", ".", "This", "is", "not", "an", "expected", "scenario", "and", "should", "be", "considered", "an", "error", "condition", ".", "The", "Env", "passed", "to", "fn", "is", "valid", "only", "for", "the", "duration", "of", "the", "callback", ".", "It", "will", "lock", "around", "the", "VirtualEnv", "to", "ensure", "that", "multiple", "processes", "do", "not", "conflict", "with", "each", "other", ".", "If", "a", "VirtualEnv", "for", "this", "specification", "already", "exists", "it", "will", "be", "used", "directly", "without", "any", "additional", "setup", ".", "If", "another", "process", "holds", "the", "lock", "With", "will", "return", "an", "error", "if", "cfg", ".", "FailIfLocked", "is", "true", "or", "try", "again", "until", "it", "obtains", "the", "lock", "otherwise", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L135-L169
8,175
luci/luci-go
vpython/venv/venv.go
Delete
func Delete(c context.Context, cfg Config) error { // Attempt to acquire the environment's lock. e, err := cfg.makeEnv(c, nil) if err != nil { return err } return e.Delete(c) }
go
func Delete(c context.Context, cfg Config) error { // Attempt to acquire the environment's lock. e, err := cfg.makeEnv(c, nil) if err != nil { return err } return e.Delete(c) }
[ "func", "Delete", "(", "c", "context", ".", "Context", ",", "cfg", "Config", ")", "error", "{", "// Attempt to acquire the environment's lock.", "e", ",", "err", ":=", "cfg", ".", "makeEnv", "(", "c", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "e", ".", "Delete", "(", "c", ")", "\n", "}" ]
// Delete removes all resources consumed by an environment. // // Delete will acquire an exclusive lock on the environment and assert that it // is not in use prior to deletion. This is non-blocking, and an error will be // returned if the lock could not be acquired. // // If deletion fails, a wrapped error will be returned.
[ "Delete", "removes", "all", "resources", "consumed", "by", "an", "environment", ".", "Delete", "will", "acquire", "an", "exclusive", "lock", "on", "the", "environment", "and", "assert", "that", "it", "is", "not", "in", "use", "prior", "to", "deletion", ".", "This", "is", "non", "-", "blocking", "and", "an", "error", "will", "be", "returned", "if", "the", "lock", "could", "not", "be", "acquired", ".", "If", "deletion", "fails", "a", "wrapped", "error", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L178-L185
8,176
luci/luci-go
vpython/venv/venv.go
Interpreter
func (e *Env) Interpreter() *python.Interpreter { if e.interpreter == nil { e.interpreter = &python.Interpreter{ Python: e.Python, } } return e.interpreter }
go
func (e *Env) Interpreter() *python.Interpreter { if e.interpreter == nil { e.interpreter = &python.Interpreter{ Python: e.Python, } } return e.interpreter }
[ "func", "(", "e", "*", "Env", ")", "Interpreter", "(", ")", "*", "python", ".", "Interpreter", "{", "if", "e", ".", "interpreter", "==", "nil", "{", "e", ".", "interpreter", "=", "&", "python", ".", "Interpreter", "{", "Python", ":", "e", ".", "Python", ",", "}", "\n", "}", "\n", "return", "e", ".", "interpreter", "\n", "}" ]
// Interpreter returns the VirtualEnv's isolated Python Interpreter instance.
[ "Interpreter", "returns", "the", "VirtualEnv", "s", "isolated", "Python", "Interpreter", "instance", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L394-L401
8,177
luci/luci-go
vpython/venv/venv.go
WriteEnvironmentStamp
func (e *Env) WriteEnvironmentStamp() error { environment := e.Environment if environment == nil { environment = &vpython.Environment{} } return writeTextProto(e.EnvironmentStampPath, environment) }
go
func (e *Env) WriteEnvironmentStamp() error { environment := e.Environment if environment == nil { environment = &vpython.Environment{} } return writeTextProto(e.EnvironmentStampPath, environment) }
[ "func", "(", "e", "*", "Env", ")", "WriteEnvironmentStamp", "(", ")", "error", "{", "environment", ":=", "e", ".", "Environment", "\n", "if", "environment", "==", "nil", "{", "environment", "=", "&", "vpython", ".", "Environment", "{", "}", "\n", "}", "\n", "return", "writeTextProto", "(", "e", ".", "EnvironmentStampPath", ",", "environment", ")", "\n", "}" ]
// WriteEnvironmentStamp writes a text protobuf form of spec to path.
[ "WriteEnvironmentStamp", "writes", "a", "text", "protobuf", "form", "of", "spec", "to", "path", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L412-L418
8,178
luci/luci-go
vpython/venv/venv.go
AssertCompleteAndLoad
func (e *Env) AssertCompleteAndLoad() error { if err := e.assertComplete(); err != nil { return err } var environment vpython.Environment if err := spec.LoadEnvironment(e.EnvironmentStampPath, &environment); err != nil { return err } if err := spec.NormalizeEnvironment(&environment); err != nil { return errors.Annotate(err, "failed to normalize stamp environment").Err() } // If we are configured with an environment, validate that it matches the // the environment that we just loaded. // // We only consider our environment-defining fields (Spec and Runtime). // // Note that both environments will have been normalized at this point, so // comparison should be reliable. if e.Environment != nil { if !proto.Equal(e.Environment.Spec, environment.Spec) { return errors.New("environment stamp specification does not match") } if !proto.Equal(e.Environment.Runtime, environment.Runtime) { return errors.New("environment stamp runtime does not match") } } e.Environment = &environment return nil }
go
func (e *Env) AssertCompleteAndLoad() error { if err := e.assertComplete(); err != nil { return err } var environment vpython.Environment if err := spec.LoadEnvironment(e.EnvironmentStampPath, &environment); err != nil { return err } if err := spec.NormalizeEnvironment(&environment); err != nil { return errors.Annotate(err, "failed to normalize stamp environment").Err() } // If we are configured with an environment, validate that it matches the // the environment that we just loaded. // // We only consider our environment-defining fields (Spec and Runtime). // // Note that both environments will have been normalized at this point, so // comparison should be reliable. if e.Environment != nil { if !proto.Equal(e.Environment.Spec, environment.Spec) { return errors.New("environment stamp specification does not match") } if !proto.Equal(e.Environment.Runtime, environment.Runtime) { return errors.New("environment stamp runtime does not match") } } e.Environment = &environment return nil }
[ "func", "(", "e", "*", "Env", ")", "AssertCompleteAndLoad", "(", ")", "error", "{", "if", "err", ":=", "e", ".", "assertComplete", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "environment", "vpython", ".", "Environment", "\n", "if", "err", ":=", "spec", ".", "LoadEnvironment", "(", "e", ".", "EnvironmentStampPath", ",", "&", "environment", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "spec", ".", "NormalizeEnvironment", "(", "&", "environment", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// If we are configured with an environment, validate that it matches the", "// the environment that we just loaded.", "//", "// We only consider our environment-defining fields (Spec and Runtime).", "//", "// Note that both environments will have been normalized at this point, so", "// comparison should be reliable.", "if", "e", ".", "Environment", "!=", "nil", "{", "if", "!", "proto", ".", "Equal", "(", "e", ".", "Environment", ".", "Spec", ",", "environment", ".", "Spec", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "proto", ".", "Equal", "(", "e", ".", "Environment", ".", "Runtime", ",", "environment", ".", "Runtime", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "e", ".", "Environment", "=", "&", "environment", "\n", "return", "nil", "\n", "}" ]
// AssertCompleteAndLoad asserts that the VirtualEnv's completion // flag exists. If it does, the environment's stamp is loaded into e.Environment // and nil is returned. // // An error is returned if the completion flag does not exist, or if the // VirtualEnv environment stamp could not be loaded.
[ "AssertCompleteAndLoad", "asserts", "that", "the", "VirtualEnv", "s", "completion", "flag", "exists", ".", "If", "it", "does", "the", "environment", "s", "stamp", "is", "loaded", "into", "e", ".", "Environment", "and", "nil", "is", "returned", ".", "An", "error", "is", "returned", "if", "the", "completion", "flag", "does", "not", "exist", "or", "if", "the", "VirtualEnv", "environment", "stamp", "could", "not", "be", "loaded", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L426-L456
8,179
luci/luci-go
vpython/venv/venv.go
getPEP425Tags
func (e *Env) getPEP425Tags(c context.Context, env []string) ([]*vpython.PEP425Tag, error) { // This script will return a list of 3-entry lists: // [0]: version (e.g., "cp27") // [1]: abi (e.g., "cp27mu", "none") // [2]: arch (e.g., "x86_64", "armv7l", "any") const script = `import json, pip.pep425tags, sys; ` + `sys.stdout.write(json.dumps(pip.pep425tags.get_supported()))` type pep425TagEntry []string cmd := e.Interpreter().IsolatedCommand(c, python.CommandTarget{Command: script}) cmd.Env = env var stdout bytes.Buffer cmd.Stdout = &stdout dumpOutput := attachOutputForLogging(c, logging.Debug, cmd) if err := cmd.Run(); err != nil { dumpOutput(c, logging.Error) return nil, errors.Annotate(err, "failed to get PEP425 tags").Err() } var tagEntries []pep425TagEntry if err := json.Unmarshal(stdout.Bytes(), &tagEntries); err != nil { return nil, errors.Annotate(err, "failed to unmarshal PEP425 tag output: %s", stdout.String()).Err() } tags := make([]*vpython.PEP425Tag, len(tagEntries)) for i, te := range tagEntries { if len(te) != 3 { return nil, errors.Reason("invalid PEP425 tag entry: %v", te). InternalReason("index(%d)", i).Err() } tags[i] = &vpython.PEP425Tag{ Python: te[0], Abi: te[1], Platform: te[2], } } // If we're Debug-logging, calculate and display the tags that were probed. if logging.IsLogging(c, logging.Debug) { tagStr := make([]string, len(tags)) for i, t := range tags { tagStr[i] = t.TagString() } logging.Debugf(c, "Loaded PEP425 tags: [%s]", strings.Join(tagStr, ", ")) } return tags, nil }
go
func (e *Env) getPEP425Tags(c context.Context, env []string) ([]*vpython.PEP425Tag, error) { // This script will return a list of 3-entry lists: // [0]: version (e.g., "cp27") // [1]: abi (e.g., "cp27mu", "none") // [2]: arch (e.g., "x86_64", "armv7l", "any") const script = `import json, pip.pep425tags, sys; ` + `sys.stdout.write(json.dumps(pip.pep425tags.get_supported()))` type pep425TagEntry []string cmd := e.Interpreter().IsolatedCommand(c, python.CommandTarget{Command: script}) cmd.Env = env var stdout bytes.Buffer cmd.Stdout = &stdout dumpOutput := attachOutputForLogging(c, logging.Debug, cmd) if err := cmd.Run(); err != nil { dumpOutput(c, logging.Error) return nil, errors.Annotate(err, "failed to get PEP425 tags").Err() } var tagEntries []pep425TagEntry if err := json.Unmarshal(stdout.Bytes(), &tagEntries); err != nil { return nil, errors.Annotate(err, "failed to unmarshal PEP425 tag output: %s", stdout.String()).Err() } tags := make([]*vpython.PEP425Tag, len(tagEntries)) for i, te := range tagEntries { if len(te) != 3 { return nil, errors.Reason("invalid PEP425 tag entry: %v", te). InternalReason("index(%d)", i).Err() } tags[i] = &vpython.PEP425Tag{ Python: te[0], Abi: te[1], Platform: te[2], } } // If we're Debug-logging, calculate and display the tags that were probed. if logging.IsLogging(c, logging.Debug) { tagStr := make([]string, len(tags)) for i, t := range tags { tagStr[i] = t.TagString() } logging.Debugf(c, "Loaded PEP425 tags: [%s]", strings.Join(tagStr, ", ")) } return tags, nil }
[ "func", "(", "e", "*", "Env", ")", "getPEP425Tags", "(", "c", "context", ".", "Context", ",", "env", "[", "]", "string", ")", "(", "[", "]", "*", "vpython", ".", "PEP425Tag", ",", "error", ")", "{", "// This script will return a list of 3-entry lists:", "// [0]: version (e.g., \"cp27\")", "// [1]: abi (e.g., \"cp27mu\", \"none\")", "// [2]: arch (e.g., \"x86_64\", \"armv7l\", \"any\")", "const", "script", "=", "`import json, pip.pep425tags, sys; `", "+", "`sys.stdout.write(json.dumps(pip.pep425tags.get_supported()))`", "\n", "type", "pep425TagEntry", "[", "]", "string", "\n\n", "cmd", ":=", "e", ".", "Interpreter", "(", ")", ".", "IsolatedCommand", "(", "c", ",", "python", ".", "CommandTarget", "{", "Command", ":", "script", "}", ")", "\n", "cmd", ".", "Env", "=", "env", "\n\n", "var", "stdout", "bytes", ".", "Buffer", "\n", "cmd", ".", "Stdout", "=", "&", "stdout", "\n\n", "dumpOutput", ":=", "attachOutputForLogging", "(", "c", ",", "logging", ".", "Debug", ",", "cmd", ")", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "dumpOutput", "(", "c", ",", "logging", ".", "Error", ")", "\n", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "var", "tagEntries", "[", "]", "pep425TagEntry", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "stdout", ".", "Bytes", "(", ")", ",", "&", "tagEntries", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "stdout", ".", "String", "(", ")", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "tags", ":=", "make", "(", "[", "]", "*", "vpython", ".", "PEP425Tag", ",", "len", "(", "tagEntries", ")", ")", "\n", "for", "i", ",", "te", ":=", "range", "tagEntries", "{", "if", "len", "(", "te", ")", "!=", "3", "{", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "te", ")", ".", "InternalReason", "(", "\"", "\"", ",", "i", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "tags", "[", "i", "]", "=", "&", "vpython", ".", "PEP425Tag", "{", "Python", ":", "te", "[", "0", "]", ",", "Abi", ":", "te", "[", "1", "]", ",", "Platform", ":", "te", "[", "2", "]", ",", "}", "\n", "}", "\n\n", "// If we're Debug-logging, calculate and display the tags that were probed.", "if", "logging", ".", "IsLogging", "(", "c", ",", "logging", ".", "Debug", ")", "{", "tagStr", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "tags", ")", ")", "\n", "for", "i", ",", "t", ":=", "range", "tags", "{", "tagStr", "[", "i", "]", "=", "t", ".", "TagString", "(", ")", "\n", "}", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "strings", ".", "Join", "(", "tagStr", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "return", "tags", ",", "nil", "\n", "}" ]
// getPEP425Tags calls Python's pip.pep425tags package to retrieve the tags. // // This must be run while "pip" is installed in the VirtualEnv.
[ "getPEP425Tags", "calls", "Python", "s", "pip", ".", "pep425tags", "package", "to", "retrieve", "the", "tags", ".", "This", "must", "be", "run", "while", "pip", "is", "installed", "in", "the", "VirtualEnv", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L640-L690
8,180
luci/luci-go
vpython/venv/venv.go
Delete
func (e *Env) Delete(c context.Context) error { removedLock := false err := e.withExclusiveLockNonBlocking(func() error { logging.Debugf(c, "(Delete) Got exclusive lock for: %s", e.Name) // Delete our environment directory. if err := filesystem.RemoveAll(e.Root); err != nil { return errors.Annotate(err, "failed to delete environment root").Err() } // Attempt to delete our lock. On POSIX systems, this will successfully // delete the lock. On Windows systems, there will be contention, since the // lock is held by us. // // In this case, we'll try again to delete it after we release the lock. // If someone else takes out the lock in between, the delete will similarly // fail. if err := os.Remove(e.lockPath); err == nil { removedLock = true } else { logging.WithError(err).Debugf(c, "failed to delete lock file while holding lock: %s", e.lockPath) } return nil }) logging.Debugf(c, "(Delete) Released exclusive lock for: %s", e.Name) if err != nil { return errors.Annotate(err, "failed to delete environment").Err() } // Try and remove the lock now that we don't hold it. if !removedLock { if err := os.Remove(e.lockPath); err != nil { return errors.Annotate(err, "failed to remove lock").Err() } } return nil }
go
func (e *Env) Delete(c context.Context) error { removedLock := false err := e.withExclusiveLockNonBlocking(func() error { logging.Debugf(c, "(Delete) Got exclusive lock for: %s", e.Name) // Delete our environment directory. if err := filesystem.RemoveAll(e.Root); err != nil { return errors.Annotate(err, "failed to delete environment root").Err() } // Attempt to delete our lock. On POSIX systems, this will successfully // delete the lock. On Windows systems, there will be contention, since the // lock is held by us. // // In this case, we'll try again to delete it after we release the lock. // If someone else takes out the lock in between, the delete will similarly // fail. if err := os.Remove(e.lockPath); err == nil { removedLock = true } else { logging.WithError(err).Debugf(c, "failed to delete lock file while holding lock: %s", e.lockPath) } return nil }) logging.Debugf(c, "(Delete) Released exclusive lock for: %s", e.Name) if err != nil { return errors.Annotate(err, "failed to delete environment").Err() } // Try and remove the lock now that we don't hold it. if !removedLock { if err := os.Remove(e.lockPath); err != nil { return errors.Annotate(err, "failed to remove lock").Err() } } return nil }
[ "func", "(", "e", "*", "Env", ")", "Delete", "(", "c", "context", ".", "Context", ")", "error", "{", "removedLock", ":=", "false", "\n", "err", ":=", "e", ".", "withExclusiveLockNonBlocking", "(", "func", "(", ")", "error", "{", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "e", ".", "Name", ")", "\n\n", "// Delete our environment directory.", "if", "err", ":=", "filesystem", ".", "RemoveAll", "(", "e", ".", "Root", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Attempt to delete our lock. On POSIX systems, this will successfully", "// delete the lock. On Windows systems, there will be contention, since the", "// lock is held by us.", "//", "// In this case, we'll try again to delete it after we release the lock.", "// If someone else takes out the lock in between, the delete will similarly", "// fail.", "if", "err", ":=", "os", ".", "Remove", "(", "e", ".", "lockPath", ")", ";", "err", "==", "nil", "{", "removedLock", "=", "true", "\n", "}", "else", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "e", ".", "lockPath", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "e", ".", "Name", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Try and remove the lock now that we don't hold it.", "if", "!", "removedLock", "{", "if", "err", ":=", "os", ".", "Remove", "(", "e", ".", "lockPath", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Delete removes all resources consumed by an environment. // // Delete will acquire an exclusive lock on the environment and assert that it // is not in use prior to deletion. This is non-blocking, and an error will be // returned if the lock could not be acquired. // // If the environment was not deleted, a non-nil wrapped error will be returned. // If the deletion failed because the lock was held, a wrapped // fslock.ErrLockHeld will be returned.
[ "Delete", "removes", "all", "resources", "consumed", "by", "an", "environment", ".", "Delete", "will", "acquire", "an", "exclusive", "lock", "on", "the", "environment", "and", "assert", "that", "it", "is", "not", "in", "use", "prior", "to", "deletion", ".", "This", "is", "non", "-", "blocking", "and", "an", "error", "will", "be", "returned", "if", "the", "lock", "could", "not", "be", "acquired", ".", "If", "the", "environment", "was", "not", "deleted", "a", "non", "-", "nil", "wrapped", "error", "will", "be", "returned", ".", "If", "the", "deletion", "failed", "because", "the", "lock", "was", "held", "a", "wrapped", "fslock", ".", "ErrLockHeld", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L845-L882
8,181
luci/luci-go
vpython/venv/venv.go
attachOutputForLogging
func attachOutputForLogging(c context.Context, l logging.Level, cmd *exec.Cmd) func(context.Context, logging.Level) { if logging.IsLogging(c, logging.Info) { logging.Infof(c, "Running Python command (cwd=%s): %s", cmd.Dir, strings.Join(cmd.Args, " ")) } var out io.Writer var buf bytes.Buffer if logging.IsLogging(c, l) { // If we're logging, redirect all process output to STDERR (same as logger // uses). out = os.Stderr } else { out = &buf } if cmd.Stdout == nil { // STDOUT will be sent to our output channel, since this logging for // debugging, not actual functional process output. cmd.Stdout = out } if cmd.Stderr == nil { cmd.Stderr = out } // Do not dump any additional error output. return func(c context.Context, l logging.Level) { logging.Logf(c, l, "Command (cwd=%s): %s\nProcess output:\n%s\nEnvironment:\n%s", cmd.Dir, cmd.Args, buf.Bytes(), strings.Join(cmd.Env, "\n")) } }
go
func attachOutputForLogging(c context.Context, l logging.Level, cmd *exec.Cmd) func(context.Context, logging.Level) { if logging.IsLogging(c, logging.Info) { logging.Infof(c, "Running Python command (cwd=%s): %s", cmd.Dir, strings.Join(cmd.Args, " ")) } var out io.Writer var buf bytes.Buffer if logging.IsLogging(c, l) { // If we're logging, redirect all process output to STDERR (same as logger // uses). out = os.Stderr } else { out = &buf } if cmd.Stdout == nil { // STDOUT will be sent to our output channel, since this logging for // debugging, not actual functional process output. cmd.Stdout = out } if cmd.Stderr == nil { cmd.Stderr = out } // Do not dump any additional error output. return func(c context.Context, l logging.Level) { logging.Logf(c, l, "Command (cwd=%s): %s\nProcess output:\n%s\nEnvironment:\n%s", cmd.Dir, cmd.Args, buf.Bytes(), strings.Join(cmd.Env, "\n")) } }
[ "func", "attachOutputForLogging", "(", "c", "context", ".", "Context", ",", "l", "logging", ".", "Level", ",", "cmd", "*", "exec", ".", "Cmd", ")", "func", "(", "context", ".", "Context", ",", "logging", ".", "Level", ")", "{", "if", "logging", ".", "IsLogging", "(", "c", ",", "logging", ".", "Info", ")", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "cmd", ".", "Dir", ",", "strings", ".", "Join", "(", "cmd", ".", "Args", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "var", "out", "io", ".", "Writer", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "logging", ".", "IsLogging", "(", "c", ",", "l", ")", "{", "// If we're logging, redirect all process output to STDERR (same as logger", "// uses).", "out", "=", "os", ".", "Stderr", "\n", "}", "else", "{", "out", "=", "&", "buf", "\n", "}", "\n\n", "if", "cmd", ".", "Stdout", "==", "nil", "{", "// STDOUT will be sent to our output channel, since this logging for", "// debugging, not actual functional process output.", "cmd", ".", "Stdout", "=", "out", "\n", "}", "\n", "if", "cmd", ".", "Stderr", "==", "nil", "{", "cmd", ".", "Stderr", "=", "out", "\n", "}", "\n\n", "// Do not dump any additional error output.", "return", "func", "(", "c", "context", ".", "Context", ",", "l", "logging", ".", "Level", ")", "{", "logging", ".", "Logf", "(", "c", ",", "l", ",", "\"", "\\n", "\\n", "\\n", "\\n", "\"", ",", "cmd", ".", "Dir", ",", "cmd", ".", "Args", ",", "buf", ".", "Bytes", "(", ")", ",", "strings", ".", "Join", "(", "cmd", ".", "Env", ",", "\"", "\\n", "\"", ")", ")", "\n", "}", "\n", "}" ]
// attachOutputForLogging modifies the supplied cmd's Stdout and Stderr fields // to output appropriately, assuming it isn't otherwise configured. // // If we are logging at level l, the process's Stdout and Stderr will be // directly connected to STDERR // // This will return a callback that can be invoked to dump any buffered process // output at the specified logging level.
[ "attachOutputForLogging", "modifies", "the", "supplied", "cmd", "s", "Stdout", "and", "Stderr", "fields", "to", "output", "appropriately", "assuming", "it", "isn", "t", "otherwise", "configured", ".", "If", "we", "are", "logging", "at", "level", "l", "the", "process", "s", "Stdout", "and", "Stderr", "will", "be", "directly", "connected", "to", "STDERR", "This", "will", "return", "a", "callback", "that", "can", "be", "invoked", "to", "dump", "any", "buffered", "process", "output", "at", "the", "specified", "logging", "level", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L915-L945
8,182
luci/luci-go
vpython/venv/venv.go
mustReleaseLock
func mustReleaseLock(c context.Context, lock fslock.Handle, fn func() error) error { defer func() { if err := lock.Unlock(); err != nil { errors.Log(c, errors.Annotate(err, "failed to release lock").Err()) // TODO(maruel): There's a bug somewhere here that cases failures on // Swarming tasks. Since they are running in a contained environment, it // is not as much as a big deal. Experimenting if a Swarming task can // survive the fact that the lock is not released. // https://crbug.com/869227 //panic(err) } }() return fn() }
go
func mustReleaseLock(c context.Context, lock fslock.Handle, fn func() error) error { defer func() { if err := lock.Unlock(); err != nil { errors.Log(c, errors.Annotate(err, "failed to release lock").Err()) // TODO(maruel): There's a bug somewhere here that cases failures on // Swarming tasks. Since they are running in a contained environment, it // is not as much as a big deal. Experimenting if a Swarming task can // survive the fact that the lock is not released. // https://crbug.com/869227 //panic(err) } }() return fn() }
[ "func", "mustReleaseLock", "(", "c", "context", ".", "Context", ",", "lock", "fslock", ".", "Handle", ",", "fn", "func", "(", ")", "error", ")", "error", "{", "defer", "func", "(", ")", "{", "if", "err", ":=", "lock", ".", "Unlock", "(", ")", ";", "err", "!=", "nil", "{", "errors", ".", "Log", "(", "c", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", ")", "\n", "// TODO(maruel): There's a bug somewhere here that cases failures on", "// Swarming tasks. Since they are running in a contained environment, it", "// is not as much as a big deal. Experimenting if a Swarming task can", "// survive the fact that the lock is not released.", "// https://crbug.com/869227", "//panic(err)", "}", "\n", "}", "(", ")", "\n", "return", "fn", "(", ")", "\n", "}" ]
// mustReleaseLock calls the wrapped function, releasing the lock at the end // of its execution. If the lock could not be released, this function will // panic, since the locking state can no longer be determined.
[ "mustReleaseLock", "calls", "the", "wrapped", "function", "releasing", "the", "lock", "at", "the", "end", "of", "its", "execution", ".", "If", "the", "lock", "could", "not", "be", "released", "this", "function", "will", "panic", "since", "the", "locking", "state", "can", "no", "longer", "be", "determined", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L950-L963
8,183
luci/luci-go
vpython/venv/venv.go
writeFile
func writeFile(path string, data []byte, mode os.FileMode) error { // Ensure that the parent directory is user-writable, since this is a // requirement in order to make modifications to that directory. parentDir := filepath.Dir(path) if err := filesystem.MakePathUserWritable(parentDir, nil); err != nil { return errors.Annotate(err, "failed to mark parent directory user-writable"). InternalReason("path(%q)", parentDir).Err() } // Ensure that the target path doesn't already exist. Use filesystem.RemoveAll // in case it exists, but is not user-writable. if err := filesystem.RemoveAll(path); err != nil { return err } if err := ioutil.WriteFile(path, data, mode); err != nil { return errors.Annotate(err, "could not write file contents").InternalReason("path(%q)", path).Err() } return nil }
go
func writeFile(path string, data []byte, mode os.FileMode) error { // Ensure that the parent directory is user-writable, since this is a // requirement in order to make modifications to that directory. parentDir := filepath.Dir(path) if err := filesystem.MakePathUserWritable(parentDir, nil); err != nil { return errors.Annotate(err, "failed to mark parent directory user-writable"). InternalReason("path(%q)", parentDir).Err() } // Ensure that the target path doesn't already exist. Use filesystem.RemoveAll // in case it exists, but is not user-writable. if err := filesystem.RemoveAll(path); err != nil { return err } if err := ioutil.WriteFile(path, data, mode); err != nil { return errors.Annotate(err, "could not write file contents").InternalReason("path(%q)", path).Err() } return nil }
[ "func", "writeFile", "(", "path", "string", ",", "data", "[", "]", "byte", ",", "mode", "os", ".", "FileMode", ")", "error", "{", "// Ensure that the parent directory is user-writable, since this is a", "// requirement in order to make modifications to that directory.", "parentDir", ":=", "filepath", ".", "Dir", "(", "path", ")", "\n", "if", "err", ":=", "filesystem", ".", "MakePathUserWritable", "(", "parentDir", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "InternalReason", "(", "\"", "\"", ",", "parentDir", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Ensure that the target path doesn't already exist. Use filesystem.RemoveAll", "// in case it exists, but is not user-writable.", "if", "err", ":=", "filesystem", ".", "RemoveAll", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "path", ",", "data", ",", "mode", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "InternalReason", "(", "\"", "\"", ",", "path", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// writeFile writes the contents of data to the specified path. It // handles additional cases where the file already exists by deleting it // first, allowing it to be overwritten.
[ "writeFile", "writes", "the", "contents", "of", "data", "to", "the", "specified", "path", ".", "It", "handles", "additional", "cases", "where", "the", "file", "already", "exists", "by", "deleting", "it", "first", "allowing", "it", "to", "be", "overwritten", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/venv.go#L968-L986
8,184
luci/luci-go
scheduler/appengine/engine/engine.go
NewEngine
func NewEngine(cfg Config) EngineInternal { eng := &engineImpl{cfg: cfg} eng.init() return eng }
go
func NewEngine(cfg Config) EngineInternal { eng := &engineImpl{cfg: cfg} eng.init() return eng }
[ "func", "NewEngine", "(", "cfg", "Config", ")", "EngineInternal", "{", "eng", ":=", "&", "engineImpl", "{", "cfg", ":", "cfg", "}", "\n", "eng", ".", "init", "(", ")", "\n", "return", "eng", "\n", "}" ]
// NewEngine returns default implementation of EngineInternal.
[ "NewEngine", "returns", "default", "implementation", "of", "EngineInternal", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L244-L248
8,185
luci/luci-go
scheduler/appengine/engine/engine.go
init
func (e *engineImpl) init() { // TODO(vadimsh): Figure out retry parameters for all tasks. e.cfg.Dispatcher.RegisterTask(&internal.LaunchInvocationsBatchTask{}, e.execLaunchInvocationsBatchTask, "batches", nil) e.cfg.Dispatcher.RegisterTask(&internal.LaunchInvocationTask{}, e.execLaunchInvocationTask, "launches", nil) e.cfg.Dispatcher.RegisterTask(&internal.TriageJobStateTask{}, e.execTriageJobStateTask, "triages", nil) e.cfg.Dispatcher.RegisterTask(&internal.KickTriageTask{}, e.execKickTriageTask, "triages", nil) e.cfg.Dispatcher.RegisterTask(&internal.InvocationFinishedTask{}, e.execInvocationFinishedTask, "completions", nil) e.cfg.Dispatcher.RegisterTask(&internal.FanOutTriggersTask{}, e.execFanOutTriggersTask, "triggers", nil) e.cfg.Dispatcher.RegisterTask(&internal.EnqueueTriggersTask{}, e.execEnqueueTriggersTask, "triggers", nil) e.cfg.Dispatcher.RegisterTask(&internal.ScheduleTimersTask{}, e.execScheduleTimersTask, "timers", nil) e.cfg.Dispatcher.RegisterTask(&internal.TimerTask{}, e.execTimerTask, "timers", nil) e.cfg.Dispatcher.RegisterTask(&internal.CronTickTask{}, e.execCronTickTask, "crons", nil) }
go
func (e *engineImpl) init() { // TODO(vadimsh): Figure out retry parameters for all tasks. e.cfg.Dispatcher.RegisterTask(&internal.LaunchInvocationsBatchTask{}, e.execLaunchInvocationsBatchTask, "batches", nil) e.cfg.Dispatcher.RegisterTask(&internal.LaunchInvocationTask{}, e.execLaunchInvocationTask, "launches", nil) e.cfg.Dispatcher.RegisterTask(&internal.TriageJobStateTask{}, e.execTriageJobStateTask, "triages", nil) e.cfg.Dispatcher.RegisterTask(&internal.KickTriageTask{}, e.execKickTriageTask, "triages", nil) e.cfg.Dispatcher.RegisterTask(&internal.InvocationFinishedTask{}, e.execInvocationFinishedTask, "completions", nil) e.cfg.Dispatcher.RegisterTask(&internal.FanOutTriggersTask{}, e.execFanOutTriggersTask, "triggers", nil) e.cfg.Dispatcher.RegisterTask(&internal.EnqueueTriggersTask{}, e.execEnqueueTriggersTask, "triggers", nil) e.cfg.Dispatcher.RegisterTask(&internal.ScheduleTimersTask{}, e.execScheduleTimersTask, "timers", nil) e.cfg.Dispatcher.RegisterTask(&internal.TimerTask{}, e.execTimerTask, "timers", nil) e.cfg.Dispatcher.RegisterTask(&internal.CronTickTask{}, e.execCronTickTask, "crons", nil) }
[ "func", "(", "e", "*", "engineImpl", ")", "init", "(", ")", "{", "// TODO(vadimsh): Figure out retry parameters for all tasks.", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "LaunchInvocationsBatchTask", "{", "}", ",", "e", ".", "execLaunchInvocationsBatchTask", ",", "\"", "\"", ",", "nil", ")", "\n", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "LaunchInvocationTask", "{", "}", ",", "e", ".", "execLaunchInvocationTask", ",", "\"", "\"", ",", "nil", ")", "\n", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "TriageJobStateTask", "{", "}", ",", "e", ".", "execTriageJobStateTask", ",", "\"", "\"", ",", "nil", ")", "\n", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "KickTriageTask", "{", "}", ",", "e", ".", "execKickTriageTask", ",", "\"", "\"", ",", "nil", ")", "\n", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "InvocationFinishedTask", "{", "}", ",", "e", ".", "execInvocationFinishedTask", ",", "\"", "\"", ",", "nil", ")", "\n", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "FanOutTriggersTask", "{", "}", ",", "e", ".", "execFanOutTriggersTask", ",", "\"", "\"", ",", "nil", ")", "\n", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "EnqueueTriggersTask", "{", "}", ",", "e", ".", "execEnqueueTriggersTask", ",", "\"", "\"", ",", "nil", ")", "\n", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "ScheduleTimersTask", "{", "}", ",", "e", ".", "execScheduleTimersTask", ",", "\"", "\"", ",", "nil", ")", "\n", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "TimerTask", "{", "}", ",", "e", ".", "execTimerTask", ",", "\"", "\"", ",", "nil", ")", "\n", "e", ".", "cfg", ".", "Dispatcher", ".", "RegisterTask", "(", "&", "internal", ".", "CronTickTask", "{", "}", ",", "e", ".", "execCronTickTask", ",", "\"", "\"", ",", "nil", ")", "\n", "}" ]
// init registers task queue handlers.
[ "init", "registers", "task", "queue", "handlers", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L259-L271
8,186
luci/luci-go
scheduler/appengine/engine/engine.go
GetVisibleProjectJobs
func (e *engineImpl) GetVisibleProjectJobs(c context.Context, projectID string) ([]*Job, error) { q := ds.NewQuery("Job").Eq("Enabled", true).Eq("ProjectID", projectID) return e.queryEnabledVisibleJobs(c, q) }
go
func (e *engineImpl) GetVisibleProjectJobs(c context.Context, projectID string) ([]*Job, error) { q := ds.NewQuery("Job").Eq("Enabled", true).Eq("ProjectID", projectID) return e.queryEnabledVisibleJobs(c, q) }
[ "func", "(", "e", "*", "engineImpl", ")", "GetVisibleProjectJobs", "(", "c", "context", ".", "Context", ",", "projectID", "string", ")", "(", "[", "]", "*", "Job", ",", "error", ")", "{", "q", ":=", "ds", ".", "NewQuery", "(", "\"", "\"", ")", ".", "Eq", "(", "\"", "\"", ",", "true", ")", ".", "Eq", "(", "\"", "\"", ",", "projectID", ")", "\n", "return", "e", ".", "queryEnabledVisibleJobs", "(", "c", ",", "q", ")", "\n", "}" ]
// GetVisibleProjectJobs enabled visible jobs belonging to a project. // // Part of the public interface, checks ACLs.
[ "GetVisibleProjectJobs", "enabled", "visible", "jobs", "belonging", "to", "a", "project", ".", "Part", "of", "the", "public", "interface", "checks", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L287-L290
8,187
luci/luci-go
scheduler/appengine/engine/engine.go
GetVisibleJob
func (e *engineImpl) GetVisibleJob(c context.Context, jobID string) (*Job, error) { job, err := e.getJob(c, jobID) switch { case err != nil: return nil, err case job == nil || !job.Enabled: return nil, ErrNoSuchJob } if err := job.CheckRole(c, acl.Reader); err != nil { if err == ErrNoPermission { err = ErrNoSuchJob // pretend protected jobs don't exist } return nil, err } return job, nil }
go
func (e *engineImpl) GetVisibleJob(c context.Context, jobID string) (*Job, error) { job, err := e.getJob(c, jobID) switch { case err != nil: return nil, err case job == nil || !job.Enabled: return nil, ErrNoSuchJob } if err := job.CheckRole(c, acl.Reader); err != nil { if err == ErrNoPermission { err = ErrNoSuchJob // pretend protected jobs don't exist } return nil, err } return job, nil }
[ "func", "(", "e", "*", "engineImpl", ")", "GetVisibleJob", "(", "c", "context", ".", "Context", ",", "jobID", "string", ")", "(", "*", "Job", ",", "error", ")", "{", "job", ",", "err", ":=", "e", ".", "getJob", "(", "c", ",", "jobID", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "case", "job", "==", "nil", "||", "!", "job", ".", "Enabled", ":", "return", "nil", ",", "ErrNoSuchJob", "\n", "}", "\n", "if", "err", ":=", "job", ".", "CheckRole", "(", "c", ",", "acl", ".", "Reader", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "ErrNoPermission", "{", "err", "=", "ErrNoSuchJob", "// pretend protected jobs don't exist", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "job", ",", "nil", "\n", "}" ]
// GetVisibleJob returns a single visible job given its full ID. // // Part of the public interface, checks ACLs.
[ "GetVisibleJob", "returns", "a", "single", "visible", "job", "given", "its", "full", "ID", ".", "Part", "of", "the", "public", "interface", "checks", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L295-L310
8,188
luci/luci-go
scheduler/appengine/engine/engine.go
GetVisibleJobBatch
func (e *engineImpl) GetVisibleJobBatch(c context.Context, jobIDs []string) (map[string]*Job, error) { // TODO(vadimsh): This can be parallelized to be single GetMulti RPC to fetch // jobs and single filterForRole to check ACLs. In practice O(len(jobIDs)) is // small, so there's no pressing need to do this. visible := make(map[string]*Job, len(jobIDs)) for _, id := range jobIDs { switch job, err := e.GetVisibleJob(c, id); { case err == nil: visible[id] = job case err != ErrNoSuchJob: return nil, err } } return visible, nil }
go
func (e *engineImpl) GetVisibleJobBatch(c context.Context, jobIDs []string) (map[string]*Job, error) { // TODO(vadimsh): This can be parallelized to be single GetMulti RPC to fetch // jobs and single filterForRole to check ACLs. In practice O(len(jobIDs)) is // small, so there's no pressing need to do this. visible := make(map[string]*Job, len(jobIDs)) for _, id := range jobIDs { switch job, err := e.GetVisibleJob(c, id); { case err == nil: visible[id] = job case err != ErrNoSuchJob: return nil, err } } return visible, nil }
[ "func", "(", "e", "*", "engineImpl", ")", "GetVisibleJobBatch", "(", "c", "context", ".", "Context", ",", "jobIDs", "[", "]", "string", ")", "(", "map", "[", "string", "]", "*", "Job", ",", "error", ")", "{", "// TODO(vadimsh): This can be parallelized to be single GetMulti RPC to fetch", "// jobs and single filterForRole to check ACLs. In practice O(len(jobIDs)) is", "// small, so there's no pressing need to do this.", "visible", ":=", "make", "(", "map", "[", "string", "]", "*", "Job", ",", "len", "(", "jobIDs", ")", ")", "\n", "for", "_", ",", "id", ":=", "range", "jobIDs", "{", "switch", "job", ",", "err", ":=", "e", ".", "GetVisibleJob", "(", "c", ",", "id", ")", ";", "{", "case", "err", "==", "nil", ":", "visible", "[", "id", "]", "=", "job", "\n", "case", "err", "!=", "ErrNoSuchJob", ":", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "visible", ",", "nil", "\n", "}" ]
// GetVisibleJobBatch is like GetVisibleJob, except it operates on a batch of // jobs at once. // // Part of the public interface. // // Part of the public interface, checks ACLs.
[ "GetVisibleJobBatch", "is", "like", "GetVisibleJob", "except", "it", "operates", "on", "a", "batch", "of", "jobs", "at", "once", ".", "Part", "of", "the", "public", "interface", ".", "Part", "of", "the", "public", "interface", "checks", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L318-L332
8,189
luci/luci-go
scheduler/appengine/engine/engine.go
ListInvocations
func (e *engineImpl) ListInvocations(c context.Context, job *Job, opts ListInvocationsOpts) ([]*Invocation, string, error) { if opts.ActiveOnly && opts.FinishedOnly { return nil, "", fmt.Errorf("using both ActiveOnly and FinishedOnly is not allowed") } if opts.PageSize <= 0 || opts.PageSize > 500 { opts.PageSize = 500 } var cursor internal.InvocationsCursor if err := decodeInvCursor(opts.Cursor, &cursor); err != nil { return nil, "", err } // We are going to merge results of multiple queries: // 1) Over historical finished invocations in the datastore. // 2) Over recently finished invocations, stored inline in the Job entity. // 3) Over active invocations, also stored inline in the Job entity. var qs []invQuery if !opts.ActiveOnly { // Most of the historical invocations came from the datastore query. But it // may not have recently finished invocations yet (due to Datastore eventual // consistently). q := finishedInvQuery(c, job, cursor.LastScanned) defer q.close() qs = append(qs, q) // Use recently finished invocations from the Job, since they may be more // up-to-date and do not depend on Datastore index consistency lag. qs = append(qs, recentInvQuery(c, job, cursor.LastScanned)) } if !opts.FinishedOnly { qs = append(qs, activeInvQuery(c, job, cursor.LastScanned)) } out := make([]*Invocation, 0, opts.PageSize) // Build the full page out of potentially incomplete (due to post-filtering) // smaller pages. Note that most of the time 'fetchInvsPage' will return the // full page right away. var page invsPage var err error for opts.PageSize > 0 { out, page, err = fetchInvsPage(c, qs, opts, out) switch { case err != nil: return nil, "", err case page.final: return out, "", nil // return empty cursor to indicate we are done } opts.PageSize -= page.count } // We end up here if the last fetched mini-page wasn't final, need new cursor. cursorStr, err := encodeInvCursor(&internal.InvocationsCursor{ LastScanned: page.lastScanned, }) if err != nil { return nil, "", errors.Annotate(err, "failed to serialize the cursor").Err() } return out, cursorStr, nil }
go
func (e *engineImpl) ListInvocations(c context.Context, job *Job, opts ListInvocationsOpts) ([]*Invocation, string, error) { if opts.ActiveOnly && opts.FinishedOnly { return nil, "", fmt.Errorf("using both ActiveOnly and FinishedOnly is not allowed") } if opts.PageSize <= 0 || opts.PageSize > 500 { opts.PageSize = 500 } var cursor internal.InvocationsCursor if err := decodeInvCursor(opts.Cursor, &cursor); err != nil { return nil, "", err } // We are going to merge results of multiple queries: // 1) Over historical finished invocations in the datastore. // 2) Over recently finished invocations, stored inline in the Job entity. // 3) Over active invocations, also stored inline in the Job entity. var qs []invQuery if !opts.ActiveOnly { // Most of the historical invocations came from the datastore query. But it // may not have recently finished invocations yet (due to Datastore eventual // consistently). q := finishedInvQuery(c, job, cursor.LastScanned) defer q.close() qs = append(qs, q) // Use recently finished invocations from the Job, since they may be more // up-to-date and do not depend on Datastore index consistency lag. qs = append(qs, recentInvQuery(c, job, cursor.LastScanned)) } if !opts.FinishedOnly { qs = append(qs, activeInvQuery(c, job, cursor.LastScanned)) } out := make([]*Invocation, 0, opts.PageSize) // Build the full page out of potentially incomplete (due to post-filtering) // smaller pages. Note that most of the time 'fetchInvsPage' will return the // full page right away. var page invsPage var err error for opts.PageSize > 0 { out, page, err = fetchInvsPage(c, qs, opts, out) switch { case err != nil: return nil, "", err case page.final: return out, "", nil // return empty cursor to indicate we are done } opts.PageSize -= page.count } // We end up here if the last fetched mini-page wasn't final, need new cursor. cursorStr, err := encodeInvCursor(&internal.InvocationsCursor{ LastScanned: page.lastScanned, }) if err != nil { return nil, "", errors.Annotate(err, "failed to serialize the cursor").Err() } return out, cursorStr, nil }
[ "func", "(", "e", "*", "engineImpl", ")", "ListInvocations", "(", "c", "context", ".", "Context", ",", "job", "*", "Job", ",", "opts", "ListInvocationsOpts", ")", "(", "[", "]", "*", "Invocation", ",", "string", ",", "error", ")", "{", "if", "opts", ".", "ActiveOnly", "&&", "opts", ".", "FinishedOnly", "{", "return", "nil", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "opts", ".", "PageSize", "<=", "0", "||", "opts", ".", "PageSize", ">", "500", "{", "opts", ".", "PageSize", "=", "500", "\n", "}", "\n\n", "var", "cursor", "internal", ".", "InvocationsCursor", "\n", "if", "err", ":=", "decodeInvCursor", "(", "opts", ".", "Cursor", ",", "&", "cursor", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// We are going to merge results of multiple queries:", "// 1) Over historical finished invocations in the datastore.", "// 2) Over recently finished invocations, stored inline in the Job entity.", "// 3) Over active invocations, also stored inline in the Job entity.", "var", "qs", "[", "]", "invQuery", "\n", "if", "!", "opts", ".", "ActiveOnly", "{", "// Most of the historical invocations came from the datastore query. But it", "// may not have recently finished invocations yet (due to Datastore eventual", "// consistently).", "q", ":=", "finishedInvQuery", "(", "c", ",", "job", ",", "cursor", ".", "LastScanned", ")", "\n", "defer", "q", ".", "close", "(", ")", "\n", "qs", "=", "append", "(", "qs", ",", "q", ")", "\n", "// Use recently finished invocations from the Job, since they may be more", "// up-to-date and do not depend on Datastore index consistency lag.", "qs", "=", "append", "(", "qs", ",", "recentInvQuery", "(", "c", ",", "job", ",", "cursor", ".", "LastScanned", ")", ")", "\n", "}", "\n", "if", "!", "opts", ".", "FinishedOnly", "{", "qs", "=", "append", "(", "qs", ",", "activeInvQuery", "(", "c", ",", "job", ",", "cursor", ".", "LastScanned", ")", ")", "\n", "}", "\n\n", "out", ":=", "make", "(", "[", "]", "*", "Invocation", ",", "0", ",", "opts", ".", "PageSize", ")", "\n\n", "// Build the full page out of potentially incomplete (due to post-filtering)", "// smaller pages. Note that most of the time 'fetchInvsPage' will return the", "// full page right away.", "var", "page", "invsPage", "\n", "var", "err", "error", "\n", "for", "opts", ".", "PageSize", ">", "0", "{", "out", ",", "page", ",", "err", "=", "fetchInvsPage", "(", "c", ",", "qs", ",", "opts", ",", "out", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "case", "page", ".", "final", ":", "return", "out", ",", "\"", "\"", ",", "nil", "// return empty cursor to indicate we are done", "\n", "}", "\n", "opts", ".", "PageSize", "-=", "page", ".", "count", "\n", "}", "\n\n", "// We end up here if the last fetched mini-page wasn't final, need new cursor.", "cursorStr", ",", "err", ":=", "encodeInvCursor", "(", "&", "internal", ".", "InvocationsCursor", "{", "LastScanned", ":", "page", ".", "lastScanned", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "out", ",", "cursorStr", ",", "nil", "\n", "}" ]
// ListInvocations returns invocations of a given job, most recent first. // // Part of the public interface.
[ "ListInvocations", "returns", "invocations", "of", "a", "given", "job", "most", "recent", "first", ".", "Part", "of", "the", "public", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L337-L397
8,190
luci/luci-go
scheduler/appengine/engine/engine.go
GetInvocation
func (e *engineImpl) GetInvocation(c context.Context, job *Job, invID int64) (*Invocation, error) { // Note: we want public API users to go through GetVisibleJob to check ACLs, // thus usage of *Job, even though JobID string is sufficient in this case. return e.getInvocation(c, job.JobID, invID) }
go
func (e *engineImpl) GetInvocation(c context.Context, job *Job, invID int64) (*Invocation, error) { // Note: we want public API users to go through GetVisibleJob to check ACLs, // thus usage of *Job, even though JobID string is sufficient in this case. return e.getInvocation(c, job.JobID, invID) }
[ "func", "(", "e", "*", "engineImpl", ")", "GetInvocation", "(", "c", "context", ".", "Context", ",", "job", "*", "Job", ",", "invID", "int64", ")", "(", "*", "Invocation", ",", "error", ")", "{", "// Note: we want public API users to go through GetVisibleJob to check ACLs,", "// thus usage of *Job, even though JobID string is sufficient in this case.", "return", "e", ".", "getInvocation", "(", "c", ",", "job", ".", "JobID", ",", "invID", ")", "\n", "}" ]
// GetInvocation returns some invocation of a given job. // // Part of the public interface.
[ "GetInvocation", "returns", "some", "invocation", "of", "a", "given", "job", ".", "Part", "of", "the", "public", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L402-L406
8,191
luci/luci-go
scheduler/appengine/engine/engine.go
PauseJob
func (e *engineImpl) PauseJob(c context.Context, job *Job) error { if err := job.CheckRole(c, acl.Owner); err != nil { return err } return e.setJobPausedFlag(c, job, true, auth.CurrentIdentity(c)) }
go
func (e *engineImpl) PauseJob(c context.Context, job *Job) error { if err := job.CheckRole(c, acl.Owner); err != nil { return err } return e.setJobPausedFlag(c, job, true, auth.CurrentIdentity(c)) }
[ "func", "(", "e", "*", "engineImpl", ")", "PauseJob", "(", "c", "context", ".", "Context", ",", "job", "*", "Job", ")", "error", "{", "if", "err", ":=", "job", ".", "CheckRole", "(", "c", ",", "acl", ".", "Owner", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "e", ".", "setJobPausedFlag", "(", "c", ",", "job", ",", "true", ",", "auth", ".", "CurrentIdentity", "(", "c", ")", ")", "\n", "}" ]
// PauseJob prevents new automatic invocations of a job. // // Part of the public interface, checks ACLs.
[ "PauseJob", "prevents", "new", "automatic", "invocations", "of", "a", "job", ".", "Part", "of", "the", "public", "interface", "checks", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L411-L416
8,192
luci/luci-go
scheduler/appengine/engine/engine.go
AbortInvocation
func (e *engineImpl) AbortInvocation(c context.Context, job *Job, invID int64) error { if err := job.CheckRole(c, acl.Owner); err != nil { return err } return e.abortInvocation(c, job.JobID, invID) }
go
func (e *engineImpl) AbortInvocation(c context.Context, job *Job, invID int64) error { if err := job.CheckRole(c, acl.Owner); err != nil { return err } return e.abortInvocation(c, job.JobID, invID) }
[ "func", "(", "e", "*", "engineImpl", ")", "AbortInvocation", "(", "c", "context", ".", "Context", ",", "job", "*", "Job", ",", "invID", "int64", ")", "error", "{", "if", "err", ":=", "job", ".", "CheckRole", "(", "c", ",", "acl", ".", "Owner", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "e", ".", "abortInvocation", "(", "c", ",", "job", ".", "JobID", ",", "invID", ")", "\n", "}" ]
// AbortInvocation forcefully moves the invocation to a failed state. // // Part of the public interface, checks ACLs.
[ "AbortInvocation", "forcefully", "moves", "the", "invocation", "to", "a", "failed", "state", ".", "Part", "of", "the", "public", "interface", "checks", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L477-L482
8,193
luci/luci-go
scheduler/appengine/engine/engine.go
EmitTriggers
func (e *engineImpl) EmitTriggers(c context.Context, perJob map[*Job][]*internal.Trigger) error { // Make sure the caller has permissions to add triggers to all jobs. jobs := make([]*Job, 0, len(perJob)) for j := range perJob { jobs = append(jobs, j) } switch filtered, err := e.filterForRole(c, jobs, acl.Triggerer); { case err != nil: return errors.Annotate(err, "transient error when checking Triggerer role").Err() case len(filtered) != len(jobs): return ErrNoPermission // some jobs are not triggerable } // Actually trigger. return parallel.FanOutIn(func(tasks chan<- func() error) { for job, triggers := range perJob { jobID := job.JobID triggers := triggers tasks <- func() error { return e.execEnqueueTriggersTask(c, &internal.EnqueueTriggersTask{ JobId: jobID, Triggers: triggers, }) } } }) }
go
func (e *engineImpl) EmitTriggers(c context.Context, perJob map[*Job][]*internal.Trigger) error { // Make sure the caller has permissions to add triggers to all jobs. jobs := make([]*Job, 0, len(perJob)) for j := range perJob { jobs = append(jobs, j) } switch filtered, err := e.filterForRole(c, jobs, acl.Triggerer); { case err != nil: return errors.Annotate(err, "transient error when checking Triggerer role").Err() case len(filtered) != len(jobs): return ErrNoPermission // some jobs are not triggerable } // Actually trigger. return parallel.FanOutIn(func(tasks chan<- func() error) { for job, triggers := range perJob { jobID := job.JobID triggers := triggers tasks <- func() error { return e.execEnqueueTriggersTask(c, &internal.EnqueueTriggersTask{ JobId: jobID, Triggers: triggers, }) } } }) }
[ "func", "(", "e", "*", "engineImpl", ")", "EmitTriggers", "(", "c", "context", ".", "Context", ",", "perJob", "map", "[", "*", "Job", "]", "[", "]", "*", "internal", ".", "Trigger", ")", "error", "{", "// Make sure the caller has permissions to add triggers to all jobs.", "jobs", ":=", "make", "(", "[", "]", "*", "Job", ",", "0", ",", "len", "(", "perJob", ")", ")", "\n", "for", "j", ":=", "range", "perJob", "{", "jobs", "=", "append", "(", "jobs", ",", "j", ")", "\n", "}", "\n", "switch", "filtered", ",", "err", ":=", "e", ".", "filterForRole", "(", "c", ",", "jobs", ",", "acl", ".", "Triggerer", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "case", "len", "(", "filtered", ")", "!=", "len", "(", "jobs", ")", ":", "return", "ErrNoPermission", "// some jobs are not triggerable", "\n", "}", "\n\n", "// Actually trigger.", "return", "parallel", ".", "FanOutIn", "(", "func", "(", "tasks", "chan", "<-", "func", "(", ")", "error", ")", "{", "for", "job", ",", "triggers", ":=", "range", "perJob", "{", "jobID", ":=", "job", ".", "JobID", "\n", "triggers", ":=", "triggers", "\n", "tasks", "<-", "func", "(", ")", "error", "{", "return", "e", ".", "execEnqueueTriggersTask", "(", "c", ",", "&", "internal", ".", "EnqueueTriggersTask", "{", "JobId", ":", "jobID", ",", "Triggers", ":", "triggers", ",", "}", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}" ]
// EmitTriggers puts one or more triggers into pending trigger queues of the // specified jobs.
[ "EmitTriggers", "puts", "one", "or", "more", "triggers", "into", "pending", "trigger", "queues", "of", "the", "specified", "jobs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L486-L512
8,194
luci/luci-go
scheduler/appengine/engine/engine.go
ListTriggers
func (e *engineImpl) ListTriggers(c context.Context, job *Job) ([]*internal.Trigger, error) { _, triggers, err := pendingTriggersSet(c, job.JobID).Triggers(c) if err != nil { return nil, transient.Tag.Apply(err) } sortTriggers(triggers) return triggers, nil }
go
func (e *engineImpl) ListTriggers(c context.Context, job *Job) ([]*internal.Trigger, error) { _, triggers, err := pendingTriggersSet(c, job.JobID).Triggers(c) if err != nil { return nil, transient.Tag.Apply(err) } sortTriggers(triggers) return triggers, nil }
[ "func", "(", "e", "*", "engineImpl", ")", "ListTriggers", "(", "c", "context", ".", "Context", ",", "job", "*", "Job", ")", "(", "[", "]", "*", "internal", ".", "Trigger", ",", "error", ")", "{", "_", ",", "triggers", ",", "err", ":=", "pendingTriggersSet", "(", "c", ",", "job", ".", "JobID", ")", ".", "Triggers", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "sortTriggers", "(", "triggers", ")", "\n", "return", "triggers", ",", "nil", "\n", "}" ]
// ListTriggers returns sorted list of job's pending triggers.
[ "ListTriggers", "returns", "sorted", "list", "of", "job", "s", "pending", "triggers", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L515-L522
8,195
luci/luci-go
scheduler/appengine/engine/engine.go
GetJobTriageLog
func (e *engineImpl) GetJobTriageLog(c context.Context, job *Job) (*JobTriageLog, error) { log := JobTriageLog{JobID: job.JobID} switch err := ds.Get(c, &log); { case err == ds.ErrNoSuchEntity: return nil, nil case err != nil: return nil, transient.Tag.Apply(err) } // We assume the log is stale if the latest triage transaction has landed // sufficiently log time ago, but JobTriageLog is still old. 1 second here // really means "we assume the log is stored no slower than 1 sec after the // triage transaction lands". In practice the log is stored immediately after // the transaction, so most of the time there should be no false positives // (but they are still possible). if !job.LastTriage.IsZero() && clock.Since(c, job.LastTriage) > time.Second { log.stale = log.LastTriage.Before(job.LastTriage) } return &log, nil }
go
func (e *engineImpl) GetJobTriageLog(c context.Context, job *Job) (*JobTriageLog, error) { log := JobTriageLog{JobID: job.JobID} switch err := ds.Get(c, &log); { case err == ds.ErrNoSuchEntity: return nil, nil case err != nil: return nil, transient.Tag.Apply(err) } // We assume the log is stale if the latest triage transaction has landed // sufficiently log time ago, but JobTriageLog is still old. 1 second here // really means "we assume the log is stored no slower than 1 sec after the // triage transaction lands". In practice the log is stored immediately after // the transaction, so most of the time there should be no false positives // (but they are still possible). if !job.LastTriage.IsZero() && clock.Since(c, job.LastTriage) > time.Second { log.stale = log.LastTriage.Before(job.LastTriage) } return &log, nil }
[ "func", "(", "e", "*", "engineImpl", ")", "GetJobTriageLog", "(", "c", "context", ".", "Context", ",", "job", "*", "Job", ")", "(", "*", "JobTriageLog", ",", "error", ")", "{", "log", ":=", "JobTriageLog", "{", "JobID", ":", "job", ".", "JobID", "}", "\n", "switch", "err", ":=", "ds", ".", "Get", "(", "c", ",", "&", "log", ")", ";", "{", "case", "err", "==", "ds", ".", "ErrNoSuchEntity", ":", "return", "nil", ",", "nil", "\n", "case", "err", "!=", "nil", ":", "return", "nil", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n\n", "// We assume the log is stale if the latest triage transaction has landed", "// sufficiently log time ago, but JobTriageLog is still old. 1 second here", "// really means \"we assume the log is stored no slower than 1 sec after the", "// triage transaction lands\". In practice the log is stored immediately after", "// the transaction, so most of the time there should be no false positives", "// (but they are still possible).", "if", "!", "job", ".", "LastTriage", ".", "IsZero", "(", ")", "&&", "clock", ".", "Since", "(", "c", ",", "job", ".", "LastTriage", ")", ">", "time", ".", "Second", "{", "log", ".", "stale", "=", "log", ".", "LastTriage", ".", "Before", "(", "job", ".", "LastTriage", ")", "\n", "}", "\n\n", "return", "&", "log", ",", "nil", "\n", "}" ]
// GetJobTriageLog returns a log from the latest job triage procedure.
[ "GetJobTriageLog", "returns", "a", "log", "from", "the", "latest", "job", "triage", "procedure", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L525-L545
8,196
luci/luci-go
scheduler/appengine/engine/engine.go
GetAllProjects
func (e *engineImpl) GetAllProjects(c context.Context) ([]string, error) { q := ds.NewQuery("Job"). Eq("Enabled", true). Project("ProjectID"). Distinct(true) entities := []Job{} if err := ds.GetAll(c, q, &entities); err != nil { return nil, transient.Tag.Apply(err) } // Filter out duplicates, sort. projects := stringset.New(len(entities)) for _, ent := range entities { projects.Add(ent.ProjectID) } out := projects.ToSlice() sort.Strings(out) return out, nil }
go
func (e *engineImpl) GetAllProjects(c context.Context) ([]string, error) { q := ds.NewQuery("Job"). Eq("Enabled", true). Project("ProjectID"). Distinct(true) entities := []Job{} if err := ds.GetAll(c, q, &entities); err != nil { return nil, transient.Tag.Apply(err) } // Filter out duplicates, sort. projects := stringset.New(len(entities)) for _, ent := range entities { projects.Add(ent.ProjectID) } out := projects.ToSlice() sort.Strings(out) return out, nil }
[ "func", "(", "e", "*", "engineImpl", ")", "GetAllProjects", "(", "c", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "q", ":=", "ds", ".", "NewQuery", "(", "\"", "\"", ")", ".", "Eq", "(", "\"", "\"", ",", "true", ")", ".", "Project", "(", "\"", "\"", ")", ".", "Distinct", "(", "true", ")", "\n", "entities", ":=", "[", "]", "Job", "{", "}", "\n", "if", "err", ":=", "ds", ".", "GetAll", "(", "c", ",", "q", ",", "&", "entities", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "// Filter out duplicates, sort.", "projects", ":=", "stringset", ".", "New", "(", "len", "(", "entities", ")", ")", "\n", "for", "_", ",", "ent", ":=", "range", "entities", "{", "projects", ".", "Add", "(", "ent", ".", "ProjectID", ")", "\n", "}", "\n", "out", ":=", "projects", ".", "ToSlice", "(", ")", "\n", "sort", ".", "Strings", "(", "out", ")", "\n", "return", "out", ",", "nil", "\n", "}" ]
// GetAllProjects returns projects that have at least one enabled job. // // Part of the internal interface, doesn't check ACLs.
[ "GetAllProjects", "returns", "projects", "that", "have", "at", "least", "one", "enabled", "job", ".", "Part", "of", "the", "internal", "interface", "doesn", "t", "check", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L558-L575
8,197
luci/luci-go
scheduler/appengine/engine/engine.go
UpdateProjectJobs
func (e *engineImpl) UpdateProjectJobs(c context.Context, projectID string, defs []catalog.Definition) error { // JobID -> *Job map. existing, err := e.getProjectJobs(c, projectID) if err != nil { return err } // JobID -> new definition revision map. updated := make(map[string]string, len(defs)) for _, def := range defs { updated[def.JobID] = def.Revision } // List of job ids to disable. var toDisable []string for id := range existing { if updated[id] == "" { toDisable = append(toDisable, id) } } wg := sync.WaitGroup{} // Add new jobs, update existing ones. updateErrs := errors.NewLazyMultiError(len(defs)) for i, def := range defs { if ent := existing[def.JobID]; ent != nil { if ent.Enabled && ent.MatchesDefinition(def) { continue } } wg.Add(1) go func(i int, def catalog.Definition) { updateErrs.Assign(i, e.updateJob(c, def)) wg.Done() }(i, def) } // Disable old jobs. disableErrs := errors.NewLazyMultiError(len(toDisable)) for i, jobID := range toDisable { wg.Add(1) go func(i int, jobID string) { disableErrs.Assign(i, e.disableJob(c, jobID)) wg.Done() }(i, jobID) } wg.Wait() if updateErrs.Get() == nil && disableErrs.Get() == nil { return nil } return transient.Tag.Apply(errors.NewMultiError(updateErrs.Get(), disableErrs.Get())) }
go
func (e *engineImpl) UpdateProjectJobs(c context.Context, projectID string, defs []catalog.Definition) error { // JobID -> *Job map. existing, err := e.getProjectJobs(c, projectID) if err != nil { return err } // JobID -> new definition revision map. updated := make(map[string]string, len(defs)) for _, def := range defs { updated[def.JobID] = def.Revision } // List of job ids to disable. var toDisable []string for id := range existing { if updated[id] == "" { toDisable = append(toDisable, id) } } wg := sync.WaitGroup{} // Add new jobs, update existing ones. updateErrs := errors.NewLazyMultiError(len(defs)) for i, def := range defs { if ent := existing[def.JobID]; ent != nil { if ent.Enabled && ent.MatchesDefinition(def) { continue } } wg.Add(1) go func(i int, def catalog.Definition) { updateErrs.Assign(i, e.updateJob(c, def)) wg.Done() }(i, def) } // Disable old jobs. disableErrs := errors.NewLazyMultiError(len(toDisable)) for i, jobID := range toDisable { wg.Add(1) go func(i int, jobID string) { disableErrs.Assign(i, e.disableJob(c, jobID)) wg.Done() }(i, jobID) } wg.Wait() if updateErrs.Get() == nil && disableErrs.Get() == nil { return nil } return transient.Tag.Apply(errors.NewMultiError(updateErrs.Get(), disableErrs.Get())) }
[ "func", "(", "e", "*", "engineImpl", ")", "UpdateProjectJobs", "(", "c", "context", ".", "Context", ",", "projectID", "string", ",", "defs", "[", "]", "catalog", ".", "Definition", ")", "error", "{", "// JobID -> *Job map.", "existing", ",", "err", ":=", "e", ".", "getProjectJobs", "(", "c", ",", "projectID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// JobID -> new definition revision map.", "updated", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "defs", ")", ")", "\n", "for", "_", ",", "def", ":=", "range", "defs", "{", "updated", "[", "def", ".", "JobID", "]", "=", "def", ".", "Revision", "\n", "}", "\n", "// List of job ids to disable.", "var", "toDisable", "[", "]", "string", "\n", "for", "id", ":=", "range", "existing", "{", "if", "updated", "[", "id", "]", "==", "\"", "\"", "{", "toDisable", "=", "append", "(", "toDisable", ",", "id", ")", "\n", "}", "\n", "}", "\n\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n\n", "// Add new jobs, update existing ones.", "updateErrs", ":=", "errors", ".", "NewLazyMultiError", "(", "len", "(", "defs", ")", ")", "\n", "for", "i", ",", "def", ":=", "range", "defs", "{", "if", "ent", ":=", "existing", "[", "def", ".", "JobID", "]", ";", "ent", "!=", "nil", "{", "if", "ent", ".", "Enabled", "&&", "ent", ".", "MatchesDefinition", "(", "def", ")", "{", "continue", "\n", "}", "\n", "}", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "i", "int", ",", "def", "catalog", ".", "Definition", ")", "{", "updateErrs", ".", "Assign", "(", "i", ",", "e", ".", "updateJob", "(", "c", ",", "def", ")", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", "i", ",", "def", ")", "\n", "}", "\n\n", "// Disable old jobs.", "disableErrs", ":=", "errors", ".", "NewLazyMultiError", "(", "len", "(", "toDisable", ")", ")", "\n", "for", "i", ",", "jobID", ":=", "range", "toDisable", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "i", "int", ",", "jobID", "string", ")", "{", "disableErrs", ".", "Assign", "(", "i", ",", "e", ".", "disableJob", "(", "c", ",", "jobID", ")", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", "i", ",", "jobID", ")", "\n", "}", "\n\n", "wg", ".", "Wait", "(", ")", "\n", "if", "updateErrs", ".", "Get", "(", ")", "==", "nil", "&&", "disableErrs", ".", "Get", "(", ")", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "transient", ".", "Tag", ".", "Apply", "(", "errors", ".", "NewMultiError", "(", "updateErrs", ".", "Get", "(", ")", ",", "disableErrs", ".", "Get", "(", ")", ")", ")", "\n", "}" ]
// UpdateProjectJobs adds new, removes old and updates existing jobs. // // Part of the internal interface, doesn't check ACLs.
[ "UpdateProjectJobs", "adds", "new", "removes", "old", "and", "updates", "existing", "jobs", ".", "Part", "of", "the", "internal", "interface", "doesn", "t", "check", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L580-L631
8,198
luci/luci-go
scheduler/appengine/engine/engine.go
ResetAllJobsOnDevServer
func (e *engineImpl) ResetAllJobsOnDevServer(c context.Context) error { if !info.IsDevAppServer(c) { return errors.New("ResetAllJobsOnDevServer must not be used in production") } q := ds.NewQuery("Job").Eq("Enabled", true) keys := []*ds.Key{} if err := ds.GetAll(c, q, &keys); err != nil { return transient.Tag.Apply(err) } wg := sync.WaitGroup{} errs := errors.NewLazyMultiError(len(keys)) for i, key := range keys { wg.Add(1) go func(i int, key *ds.Key) { errs.Assign(i, e.resetJobOnDevServer(c, key.StringID())) wg.Done() }(i, key) } wg.Wait() return transient.Tag.Apply(errs.Get()) }
go
func (e *engineImpl) ResetAllJobsOnDevServer(c context.Context) error { if !info.IsDevAppServer(c) { return errors.New("ResetAllJobsOnDevServer must not be used in production") } q := ds.NewQuery("Job").Eq("Enabled", true) keys := []*ds.Key{} if err := ds.GetAll(c, q, &keys); err != nil { return transient.Tag.Apply(err) } wg := sync.WaitGroup{} errs := errors.NewLazyMultiError(len(keys)) for i, key := range keys { wg.Add(1) go func(i int, key *ds.Key) { errs.Assign(i, e.resetJobOnDevServer(c, key.StringID())) wg.Done() }(i, key) } wg.Wait() return transient.Tag.Apply(errs.Get()) }
[ "func", "(", "e", "*", "engineImpl", ")", "ResetAllJobsOnDevServer", "(", "c", "context", ".", "Context", ")", "error", "{", "if", "!", "info", ".", "IsDevAppServer", "(", "c", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "q", ":=", "ds", ".", "NewQuery", "(", "\"", "\"", ")", ".", "Eq", "(", "\"", "\"", ",", "true", ")", "\n", "keys", ":=", "[", "]", "*", "ds", ".", "Key", "{", "}", "\n", "if", "err", ":=", "ds", ".", "GetAll", "(", "c", ",", "q", ",", "&", "keys", ")", ";", "err", "!=", "nil", "{", "return", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "errs", ":=", "errors", ".", "NewLazyMultiError", "(", "len", "(", "keys", ")", ")", "\n", "for", "i", ",", "key", ":=", "range", "keys", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "i", "int", ",", "key", "*", "ds", ".", "Key", ")", "{", "errs", ".", "Assign", "(", "i", ",", "e", ".", "resetJobOnDevServer", "(", "c", ",", "key", ".", "StringID", "(", ")", ")", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", "i", ",", "key", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "return", "transient", ".", "Tag", ".", "Apply", "(", "errs", ".", "Get", "(", ")", ")", "\n", "}" ]
// ResetAllJobsOnDevServer forcefully resets state of all enabled jobs. // // Part of the internal interface, doesn't check ACLs.
[ "ResetAllJobsOnDevServer", "forcefully", "resets", "state", "of", "all", "enabled", "jobs", ".", "Part", "of", "the", "internal", "interface", "doesn", "t", "check", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L636-L656
8,199
luci/luci-go
scheduler/appengine/engine/engine.go
ProcessPubSubPush
func (e *engineImpl) ProcessPubSubPush(c context.Context, body []byte) error { var pushBody struct { Message pubsub.PubsubMessage `json:"message"` } if err := json.Unmarshal(body, &pushBody); err != nil { return err } // Retry once after a slight adhoc delay (to let datastore transactions land) // instead of returning an error to PubSub immediately. We don't want errors // tagged with tq.Retry to engage PubSub flow control, since they are // semi-expected and it is also expected that an immediate retry helps. This // is still best effort only and on another error we let the PubSub retry // mechanism to handle it. err := e.handlePubSubMessage(c, &pushBody.Message) if err == nil || !tq.Retry.In(err) { return err } logging.Warningf(c, "Attempting a quick retry after 1s: %s", err) clock.Sleep(c, time.Second) return e.handlePubSubMessage(c, &pushBody.Message) }
go
func (e *engineImpl) ProcessPubSubPush(c context.Context, body []byte) error { var pushBody struct { Message pubsub.PubsubMessage `json:"message"` } if err := json.Unmarshal(body, &pushBody); err != nil { return err } // Retry once after a slight adhoc delay (to let datastore transactions land) // instead of returning an error to PubSub immediately. We don't want errors // tagged with tq.Retry to engage PubSub flow control, since they are // semi-expected and it is also expected that an immediate retry helps. This // is still best effort only and on another error we let the PubSub retry // mechanism to handle it. err := e.handlePubSubMessage(c, &pushBody.Message) if err == nil || !tq.Retry.In(err) { return err } logging.Warningf(c, "Attempting a quick retry after 1s: %s", err) clock.Sleep(c, time.Second) return e.handlePubSubMessage(c, &pushBody.Message) }
[ "func", "(", "e", "*", "engineImpl", ")", "ProcessPubSubPush", "(", "c", "context", ".", "Context", ",", "body", "[", "]", "byte", ")", "error", "{", "var", "pushBody", "struct", "{", "Message", "pubsub", ".", "PubsubMessage", "`json:\"message\"`", "\n", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "pushBody", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Retry once after a slight adhoc delay (to let datastore transactions land)", "// instead of returning an error to PubSub immediately. We don't want errors", "// tagged with tq.Retry to engage PubSub flow control, since they are", "// semi-expected and it is also expected that an immediate retry helps. This", "// is still best effort only and on another error we let the PubSub retry", "// mechanism to handle it.", "err", ":=", "e", ".", "handlePubSubMessage", "(", "c", ",", "&", "pushBody", ".", "Message", ")", "\n", "if", "err", "==", "nil", "||", "!", "tq", ".", "Retry", ".", "In", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "err", ")", "\n", "clock", ".", "Sleep", "(", "c", ",", "time", ".", "Second", ")", "\n", "return", "e", ".", "handlePubSubMessage", "(", "c", ",", "&", "pushBody", ".", "Message", ")", "\n", "}" ]
// ProcessPubSubPush is called whenever incoming PubSub message is received. // // Part of the internal interface, doesn't check ACLs.
[ "ProcessPubSubPush", "is", "called", "whenever", "incoming", "PubSub", "message", "is", "received", ".", "Part", "of", "the", "internal", "interface", "doesn", "t", "check", "ACLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L661-L681