id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
7,000
luci/luci-go
cq/appengine/config/config.go
validateRef
func validateRef(ctx *validation.Context, configSet, path string, content []byte) error { ctx.SetFile(path) // cq.cfg has been disallowed since Feb 1, 2019. // keep this error in place till Apr 1, 2019, to encourage clients remove this // config file from their repo. ctx.Errorf("cq.cfg is no longer used and has no effect. Please, delete cq.cfg in your repo.") ctx.Errorf("cq.cfg is replaced by commit-queue.cfg") return nil }
go
func validateRef(ctx *validation.Context, configSet, path string, content []byte) error { ctx.SetFile(path) // cq.cfg has been disallowed since Feb 1, 2019. // keep this error in place till Apr 1, 2019, to encourage clients remove this // config file from their repo. ctx.Errorf("cq.cfg is no longer used and has no effect. Please, delete cq.cfg in your repo.") ctx.Errorf("cq.cfg is replaced by commit-queue.cfg") return nil }
[ "func", "validateRef", "(", "ctx", "*", "validation", ".", "Context", ",", "configSet", ",", "path", "string", ",", "content", "[", "]", "byte", ")", "error", "{", "ctx", ".", "SetFile", "(", "path", ")", "\n", "// cq.cfg has been disallowed since Feb 1, 2019.", "// keep this error in place till Apr 1, 2019, to encourage clients remove this", "// config file from their repo.", "ctx", ".", "Errorf", "(", "\"", "\"", ")", "\n", "ctx", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// validateRefCfg validates legacy ref-specific cq.cfg. // Validation result is returned via validation ctx, // while error returned directly implies only a bug in this code.
[ "validateRefCfg", "validates", "legacy", "ref", "-", "specific", "cq", ".", "cfg", ".", "Validation", "result", "is", "returned", "via", "validation", "ctx", "while", "error", "returned", "directly", "implies", "only", "a", "bug", "in", "this", "code", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cq/appengine/config/config.go#L50-L58
7,001
luci/luci-go
cq/appengine/config/config.go
validateProject
func validateProject(ctx *validation.Context, configSet, path string, content []byte) error { ctx.SetFile(path) cfg := v2.Config{} if err := proto.UnmarshalText(string(content), &cfg); err != nil { ctx.Error(err) } else { validateProjectConfig(ctx, &cfg) } return nil }
go
func validateProject(ctx *validation.Context, configSet, path string, content []byte) error { ctx.SetFile(path) cfg := v2.Config{} if err := proto.UnmarshalText(string(content), &cfg); err != nil { ctx.Error(err) } else { validateProjectConfig(ctx, &cfg) } return nil }
[ "func", "validateProject", "(", "ctx", "*", "validation", ".", "Context", ",", "configSet", ",", "path", "string", ",", "content", "[", "]", "byte", ")", "error", "{", "ctx", ".", "SetFile", "(", "path", ")", "\n", "cfg", ":=", "v2", ".", "Config", "{", "}", "\n", "if", "err", ":=", "proto", ".", "UnmarshalText", "(", "string", "(", "content", ")", ",", "&", "cfg", ")", ";", "err", "!=", "nil", "{", "ctx", ".", "Error", "(", "err", ")", "\n", "}", "else", "{", "validateProjectConfig", "(", "ctx", ",", "&", "cfg", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateProjectCfg validates project-level cq.cfg. // Validation result is returned via validation ctx, // while error returned directly implies only a bug in this code.
[ "validateProjectCfg", "validates", "project", "-", "level", "cq", ".", "cfg", ".", "Validation", "result", "is", "returned", "via", "validation", "ctx", "while", "error", "returned", "directly", "implies", "only", "a", "bug", "in", "this", "code", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cq/appengine/config/config.go#L63-L72
7,002
luci/luci-go
cq/appengine/config/config.go
bestEffortDisjointGroups
func bestEffortDisjointGroups(ctx *validation.Context, cfg *v2.Config) { defaultRefRegexps := []string{"refs/heads/master"} // Multimap gerrit URL => project => refRegexp => config group index. seen := map[refKey]int{} for grIdx, gr := range cfg.ConfigGroups { for gIdx, g := range gr.Gerrit { for pIdx, p := range g.Projects { refRegexps := p.RefRegexp if len(p.RefRegexp) == 0 { refRegexps = defaultRefRegexps } for rIdx, refRegexp := range refRegexps { if seenIdx, aliasing := seen[refKey{g.Url, p.Name, refRegexp}]; !aliasing { seen[refKey{g.Url, p.Name, refRegexp}] = grIdx } else if seenIdx != grIdx { // NOTE: we have already emitted error on duplicate gerrit URL, // project name, or ref_regexp within their own respective // container, so only error here is cases when these span multiple // config_groups. ctx.Enter("config_group #%d", grIdx+1) ctx.Enter("gerrit #%d", gIdx+1) ctx.Enter("project #%d", pIdx+1) ctx.Enter("ref_regexp #%d", rIdx+1) ctx.Errorf("aliases config_group #%d", seenIdx+1) ctx.Exit() ctx.Exit() ctx.Exit() ctx.Exit() } } } } } // Second type of heuristics: match individual refs which are typically in // use, and check if they match against >1 configs. plainRefs := []string{ "refs/heads/master", "refs/heads/branch", "refs/heads/infra/config", "refs/branch-heads/1234", } // Multimap gerrit url => project => plainRef => list of config_group indexes // matching this plainRef. matchedBy := map[refKey][]int{} for ref, seenIdx := range seen { // Only check valid regexps here. if re, err := regexp.Compile("^" + ref.refStr + "$"); err == nil { for _, plainRef := range plainRefs { if re.MatchString(plainRef) { plainRefKey := refKey{ref.url, ref.project, plainRef} matchedBy[plainRefKey] = append(matchedBy[plainRefKey], seenIdx) } } } } for ref, matchedIdxs := range matchedBy { if len(matchedIdxs) > 1 { sort.Slice(matchedIdxs, func(i, j int) bool { return matchedIdxs[i] < matchedIdxs[j] }) ctx.Errorf("Overlapping config_groups not allowed. Gerrit %q project %q ref %q matches config_groups %v", ref.url, ref.project, ref.refStr, matchedIdxs) } } }
go
func bestEffortDisjointGroups(ctx *validation.Context, cfg *v2.Config) { defaultRefRegexps := []string{"refs/heads/master"} // Multimap gerrit URL => project => refRegexp => config group index. seen := map[refKey]int{} for grIdx, gr := range cfg.ConfigGroups { for gIdx, g := range gr.Gerrit { for pIdx, p := range g.Projects { refRegexps := p.RefRegexp if len(p.RefRegexp) == 0 { refRegexps = defaultRefRegexps } for rIdx, refRegexp := range refRegexps { if seenIdx, aliasing := seen[refKey{g.Url, p.Name, refRegexp}]; !aliasing { seen[refKey{g.Url, p.Name, refRegexp}] = grIdx } else if seenIdx != grIdx { // NOTE: we have already emitted error on duplicate gerrit URL, // project name, or ref_regexp within their own respective // container, so only error here is cases when these span multiple // config_groups. ctx.Enter("config_group #%d", grIdx+1) ctx.Enter("gerrit #%d", gIdx+1) ctx.Enter("project #%d", pIdx+1) ctx.Enter("ref_regexp #%d", rIdx+1) ctx.Errorf("aliases config_group #%d", seenIdx+1) ctx.Exit() ctx.Exit() ctx.Exit() ctx.Exit() } } } } } // Second type of heuristics: match individual refs which are typically in // use, and check if they match against >1 configs. plainRefs := []string{ "refs/heads/master", "refs/heads/branch", "refs/heads/infra/config", "refs/branch-heads/1234", } // Multimap gerrit url => project => plainRef => list of config_group indexes // matching this plainRef. matchedBy := map[refKey][]int{} for ref, seenIdx := range seen { // Only check valid regexps here. if re, err := regexp.Compile("^" + ref.refStr + "$"); err == nil { for _, plainRef := range plainRefs { if re.MatchString(plainRef) { plainRefKey := refKey{ref.url, ref.project, plainRef} matchedBy[plainRefKey] = append(matchedBy[plainRefKey], seenIdx) } } } } for ref, matchedIdxs := range matchedBy { if len(matchedIdxs) > 1 { sort.Slice(matchedIdxs, func(i, j int) bool { return matchedIdxs[i] < matchedIdxs[j] }) ctx.Errorf("Overlapping config_groups not allowed. Gerrit %q project %q ref %q matches config_groups %v", ref.url, ref.project, ref.refStr, matchedIdxs) } } }
[ "func", "bestEffortDisjointGroups", "(", "ctx", "*", "validation", ".", "Context", ",", "cfg", "*", "v2", ".", "Config", ")", "{", "defaultRefRegexps", ":=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "// Multimap gerrit URL => project => refRegexp => config group index.", "seen", ":=", "map", "[", "refKey", "]", "int", "{", "}", "\n\n", "for", "grIdx", ",", "gr", ":=", "range", "cfg", ".", "ConfigGroups", "{", "for", "gIdx", ",", "g", ":=", "range", "gr", ".", "Gerrit", "{", "for", "pIdx", ",", "p", ":=", "range", "g", ".", "Projects", "{", "refRegexps", ":=", "p", ".", "RefRegexp", "\n", "if", "len", "(", "p", ".", "RefRegexp", ")", "==", "0", "{", "refRegexps", "=", "defaultRefRegexps", "\n", "}", "\n", "for", "rIdx", ",", "refRegexp", ":=", "range", "refRegexps", "{", "if", "seenIdx", ",", "aliasing", ":=", "seen", "[", "refKey", "{", "g", ".", "Url", ",", "p", ".", "Name", ",", "refRegexp", "}", "]", ";", "!", "aliasing", "{", "seen", "[", "refKey", "{", "g", ".", "Url", ",", "p", ".", "Name", ",", "refRegexp", "}", "]", "=", "grIdx", "\n", "}", "else", "if", "seenIdx", "!=", "grIdx", "{", "// NOTE: we have already emitted error on duplicate gerrit URL,", "// project name, or ref_regexp within their own respective", "// container, so only error here is cases when these span multiple", "// config_groups.", "ctx", ".", "Enter", "(", "\"", "\"", ",", "grIdx", "+", "1", ")", "\n", "ctx", ".", "Enter", "(", "\"", "\"", ",", "gIdx", "+", "1", ")", "\n", "ctx", ".", "Enter", "(", "\"", "\"", ",", "pIdx", "+", "1", ")", "\n", "ctx", ".", "Enter", "(", "\"", "\"", ",", "rIdx", "+", "1", ")", "\n", "ctx", ".", "Errorf", "(", "\"", "\"", ",", "seenIdx", "+", "1", ")", "\n", "ctx", ".", "Exit", "(", ")", "\n", "ctx", ".", "Exit", "(", ")", "\n", "ctx", ".", "Exit", "(", ")", "\n", "ctx", ".", "Exit", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Second type of heuristics: match individual refs which are typically in", "// use, and check if they match against >1 configs.", "plainRefs", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n", "// Multimap gerrit url => project => plainRef => list of config_group indexes", "// matching this plainRef.", "matchedBy", ":=", "map", "[", "refKey", "]", "[", "]", "int", "{", "}", "\n", "for", "ref", ",", "seenIdx", ":=", "range", "seen", "{", "// Only check valid regexps here.", "if", "re", ",", "err", ":=", "regexp", ".", "Compile", "(", "\"", "\"", "+", "ref", ".", "refStr", "+", "\"", "\"", ")", ";", "err", "==", "nil", "{", "for", "_", ",", "plainRef", ":=", "range", "plainRefs", "{", "if", "re", ".", "MatchString", "(", "plainRef", ")", "{", "plainRefKey", ":=", "refKey", "{", "ref", ".", "url", ",", "ref", ".", "project", ",", "plainRef", "}", "\n", "matchedBy", "[", "plainRefKey", "]", "=", "append", "(", "matchedBy", "[", "plainRefKey", "]", ",", "seenIdx", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "ref", ",", "matchedIdxs", ":=", "range", "matchedBy", "{", "if", "len", "(", "matchedIdxs", ")", ">", "1", "{", "sort", ".", "Slice", "(", "matchedIdxs", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "matchedIdxs", "[", "i", "]", "<", "matchedIdxs", "[", "j", "]", "}", ")", "\n", "ctx", ".", "Errorf", "(", "\"", "\"", ",", "ref", ".", "url", ",", "ref", ".", "project", ",", "ref", ".", "refStr", ",", "matchedIdxs", ")", "\n", "}", "\n", "}", "\n", "}" ]
// bestEffortDisjointGroups errors out on easy to spot overlaps between // configGroups. // // It is non-trivial if it all possible to ensure that regexp across // config_groups don't overlap. But, we can catch typical copy-pasta mistakes // early on by checking for equality of regexps.
[ "bestEffortDisjointGroups", "errors", "out", "on", "easy", "to", "spot", "overlaps", "between", "configGroups", ".", "It", "is", "non", "-", "trivial", "if", "it", "all", "possible", "to", "ensure", "that", "regexp", "across", "config_groups", "don", "t", "overlap", ".", "But", "we", "can", "catch", "typical", "copy", "-", "pasta", "mistakes", "early", "on", "by", "checking", "for", "equality", "of", "regexps", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cq/appengine/config/config.go#L127-L191
7,003
luci/luci-go
logdog/appengine/coordinator/project.go
ProjectFromNamespace
func ProjectFromNamespace(ns string) types.ProjectName { if !strings.HasPrefix(ns, ProjectNamespacePrefix) { return "" } return types.ProjectName(ns[len(ProjectNamespacePrefix):]) }
go
func ProjectFromNamespace(ns string) types.ProjectName { if !strings.HasPrefix(ns, ProjectNamespacePrefix) { return "" } return types.ProjectName(ns[len(ProjectNamespacePrefix):]) }
[ "func", "ProjectFromNamespace", "(", "ns", "string", ")", "types", ".", "ProjectName", "{", "if", "!", "strings", ".", "HasPrefix", "(", "ns", ",", "ProjectNamespacePrefix", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "types", ".", "ProjectName", "(", "ns", "[", "len", "(", "ProjectNamespacePrefix", ")", ":", "]", ")", "\n", "}" ]
// ProjectFromNamespace returns the current project installed in the supplied // Context's namespace. // // If the namespace does not have a project namespace prefix, this function // will return an empty string.
[ "ProjectFromNamespace", "returns", "the", "current", "project", "installed", "in", "the", "supplied", "Context", "s", "namespace", ".", "If", "the", "namespace", "does", "not", "have", "a", "project", "namespace", "prefix", "this", "function", "will", "return", "an", "empty", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/project.go#L43-L48
7,004
luci/luci-go
logdog/appengine/coordinator/project.go
CurrentProject
func CurrentProject(c context.Context) types.ProjectName { if ns := info.GetNamespace(c); ns != "" { return ProjectFromNamespace(ns) } return "" }
go
func CurrentProject(c context.Context) types.ProjectName { if ns := info.GetNamespace(c); ns != "" { return ProjectFromNamespace(ns) } return "" }
[ "func", "CurrentProject", "(", "c", "context", ".", "Context", ")", "types", ".", "ProjectName", "{", "if", "ns", ":=", "info", ".", "GetNamespace", "(", "c", ")", ";", "ns", "!=", "\"", "\"", "{", "return", "ProjectFromNamespace", "(", "ns", ")", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// CurrentProject returns the current project based on the currently-loaded // namespace. // // If there is no current namespace, or if the current namespace is not a valid // project namespace, an empty string will be returned.
[ "CurrentProject", "returns", "the", "current", "project", "based", "on", "the", "currently", "-", "loaded", "namespace", ".", "If", "there", "is", "no", "current", "namespace", "or", "if", "the", "current", "namespace", "is", "not", "a", "valid", "project", "namespace", "an", "empty", "string", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/project.go#L55-L60
7,005
luci/luci-go
logdog/appengine/coordinator/project.go
CurrentProjectConfig
func CurrentProjectConfig(c context.Context) (*svcconfig.ProjectConfig, error) { return GetConfigProvider(c).ProjectConfig(c, CurrentProject(c)) }
go
func CurrentProjectConfig(c context.Context) (*svcconfig.ProjectConfig, error) { return GetConfigProvider(c).ProjectConfig(c, CurrentProject(c)) }
[ "func", "CurrentProjectConfig", "(", "c", "context", ".", "Context", ")", "(", "*", "svcconfig", ".", "ProjectConfig", ",", "error", ")", "{", "return", "GetConfigProvider", "(", "c", ")", ".", "ProjectConfig", "(", "c", ",", "CurrentProject", "(", "c", ")", ")", "\n", "}" ]
// CurrentProjectConfig returns the project-specific configuration for the // current project. // // If there is no current project namespace, or if the current project has no // configuration, config.ErrInvalidConfig will be returned.
[ "CurrentProjectConfig", "returns", "the", "project", "-", "specific", "configuration", "for", "the", "current", "project", ".", "If", "there", "is", "no", "current", "project", "namespace", "or", "if", "the", "current", "project", "has", "no", "configuration", "config", ".", "ErrInvalidConfig", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/project.go#L67-L69
7,006
luci/luci-go
common/iotools/deadlinereader.go
SetReadTimeout
func (r *DeadlineReader) SetReadTimeout(d time.Duration) error { r.Deadline = d return nil }
go
func (r *DeadlineReader) SetReadTimeout(d time.Duration) error { r.Deadline = d return nil }
[ "func", "(", "r", "*", "DeadlineReader", ")", "SetReadTimeout", "(", "d", "time", ".", "Duration", ")", "error", "{", "r", ".", "Deadline", "=", "d", "\n", "return", "nil", "\n", "}" ]
// SetReadTimeout implements ReadDeadlineSetter.
[ "SetReadTimeout", "implements", "ReadDeadlineSetter", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/iotools/deadlinereader.go#L69-L72
7,007
luci/luci-go
logdog/common/types/tag.go
ValidateTag
func ValidateTag(k, v string) error { if err := StreamName(k).Validate(); err != nil { return fmt.Errorf("invalid tag key: %s", err) } if len(k) > MaxTagKeySize { return fmt.Errorf("tag key exceeds maximum size (%d > %d)", len(k), MaxTagKeySize) } if len(v) > MaxTagValueSize { return fmt.Errorf("tag value exceeds maximum size (%d > %d)", len(v), MaxTagValueSize) } return nil }
go
func ValidateTag(k, v string) error { if err := StreamName(k).Validate(); err != nil { return fmt.Errorf("invalid tag key: %s", err) } if len(k) > MaxTagKeySize { return fmt.Errorf("tag key exceeds maximum size (%d > %d)", len(k), MaxTagKeySize) } if len(v) > MaxTagValueSize { return fmt.Errorf("tag value exceeds maximum size (%d > %d)", len(v), MaxTagValueSize) } return nil }
[ "func", "ValidateTag", "(", "k", ",", "v", "string", ")", "error", "{", "if", "err", ":=", "StreamName", "(", "k", ")", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "k", ")", ">", "MaxTagKeySize", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "k", ")", ",", "MaxTagKeySize", ")", "\n", "}", "\n", "if", "len", "(", "v", ")", ">", "MaxTagValueSize", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "v", ")", ",", "MaxTagValueSize", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateTag returns an error if a tag contains a nonconfirming value.
[ "ValidateTag", "returns", "an", "error", "if", "a", "tag", "contains", "a", "nonconfirming", "value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/tag.go#L32-L43
7,008
luci/luci-go
machine-db/appengine/rpc/nics.go
CreateNIC
func (*Service) CreateNIC(c context.Context, req *crimson.CreateNICRequest) (*crimson.NIC, error) { if err := createNIC(c, req.Nic); err != nil { return nil, err } return req.Nic, nil }
go
func (*Service) CreateNIC(c context.Context, req *crimson.CreateNICRequest) (*crimson.NIC, error) { if err := createNIC(c, req.Nic); err != nil { return nil, err } return req.Nic, nil }
[ "func", "(", "*", "Service", ")", "CreateNIC", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "CreateNICRequest", ")", "(", "*", "crimson", ".", "NIC", ",", "error", ")", "{", "if", "err", ":=", "createNIC", "(", "c", ",", "req", ".", "Nic", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "req", ".", "Nic", ",", "nil", "\n", "}" ]
// CreateNIC handles a request to create a new network interface.
[ "CreateNIC", "handles", "a", "request", "to", "create", "a", "new", "network", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L41-L46
7,009
luci/luci-go
machine-db/appengine/rpc/nics.go
DeleteNIC
func (*Service) DeleteNIC(c context.Context, req *crimson.DeleteNICRequest) (*empty.Empty, error) { if err := deleteNIC(c, req.Name, req.Machine); err != nil { return nil, err } return &empty.Empty{}, nil }
go
func (*Service) DeleteNIC(c context.Context, req *crimson.DeleteNICRequest) (*empty.Empty, error) { if err := deleteNIC(c, req.Name, req.Machine); err != nil { return nil, err } return &empty.Empty{}, nil }
[ "func", "(", "*", "Service", ")", "DeleteNIC", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "DeleteNICRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "if", "err", ":=", "deleteNIC", "(", "c", ",", "req", ".", "Name", ",", "req", ".", "Machine", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// DeleteNIC handles a request to delete an existing network interface.
[ "DeleteNIC", "handles", "a", "request", "to", "delete", "an", "existing", "network", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L49-L54
7,010
luci/luci-go
machine-db/appengine/rpc/nics.go
ListNICs
func (*Service) ListNICs(c context.Context, req *crimson.ListNICsRequest) (*crimson.ListNICsResponse, error) { nics, err := listNICs(c, database.Get(c), req) if err != nil { return nil, err } return &crimson.ListNICsResponse{ Nics: nics, }, nil }
go
func (*Service) ListNICs(c context.Context, req *crimson.ListNICsRequest) (*crimson.ListNICsResponse, error) { nics, err := listNICs(c, database.Get(c), req) if err != nil { return nil, err } return &crimson.ListNICsResponse{ Nics: nics, }, nil }
[ "func", "(", "*", "Service", ")", "ListNICs", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "ListNICsRequest", ")", "(", "*", "crimson", ".", "ListNICsResponse", ",", "error", ")", "{", "nics", ",", "err", ":=", "listNICs", "(", "c", ",", "database", ".", "Get", "(", "c", ")", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "crimson", ".", "ListNICsResponse", "{", "Nics", ":", "nics", ",", "}", ",", "nil", "\n", "}" ]
// ListNICs handles a request to list network interfaces.
[ "ListNICs", "handles", "a", "request", "to", "list", "network", "interfaces", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L57-L65
7,011
luci/luci-go
machine-db/appengine/rpc/nics.go
UpdateNIC
func (*Service) UpdateNIC(c context.Context, req *crimson.UpdateNICRequest) (*crimson.NIC, error) { return updateNIC(c, req.Nic, req.UpdateMask) }
go
func (*Service) UpdateNIC(c context.Context, req *crimson.UpdateNICRequest) (*crimson.NIC, error) { return updateNIC(c, req.Nic, req.UpdateMask) }
[ "func", "(", "*", "Service", ")", "UpdateNIC", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "UpdateNICRequest", ")", "(", "*", "crimson", ".", "NIC", ",", "error", ")", "{", "return", "updateNIC", "(", "c", ",", "req", ".", "Nic", ",", "req", ".", "UpdateMask", ")", "\n", "}" ]
// UpdateNIC handles a request to update an existing network interface.
[ "UpdateNIC", "handles", "a", "request", "to", "update", "an", "existing", "network", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L68-L70
7,012
luci/luci-go
machine-db/appengine/rpc/nics.go
createNIC
func createNIC(c context.Context, n *crimson.NIC) error { if err := validateNICForCreation(n); err != nil { return err } mac, _ := common.ParseMAC48(n.MacAddress) tx, err := database.Begin(c) if err != nil { return errors.Annotate(err, "failed to begin transaction").Err() } defer tx.MaybeRollback(c) var hostnameId sql.NullInt64 if n.Hostname != "" { ip, _ := common.ParseIPv4(n.Ipv4) id, err := model.AssignHostnameAndIP(c, tx, n.Hostname, ip) if err != nil { return err } hostnameId.Int64 = id hostnameId.Valid = true } // By setting nics.machine_id NOT NULL when setting up the database, we can avoid checking if the given machine is // valid. MySQL will turn up NULL for its column values which will be rejected as an error. _, err = tx.ExecContext(c, ` INSERT INTO nics (name, machine_id, mac_address, switch_id, switchport, hostname_id) VALUES (?, (SELECT id FROM machines WHERE name = ?), ?, (SELECT id FROM switches WHERE name = ?), ?, ?) `, n.Name, n.Machine, mac, n.Switch, n.Switchport, hostnameId) if err != nil { switch e, ok := err.(*mysql.MySQLError); { case !ok: // Type assertion failed. case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'name'"): // e.g. "Error 1062: Duplicate entry 'eth0-machineId' for key 'name'". return status.Errorf(codes.AlreadyExists, "duplicate NIC %q for machine %q", n.Name, n.Machine) case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'mac_address'"): // e.g. "Error 1062: Duplicate entry '1234567890' for key 'mac_address'". return status.Errorf(codes.AlreadyExists, "duplicate MAC address %q", n.MacAddress) case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'machine_id'"): // e.g. "Error 1048: Column 'machine_id' cannot be null". return status.Errorf(codes.NotFound, "machine %q does not exist", n.Machine) case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'switch_id'"): // e.g. "Error 1048: Column 'switch_id' cannot be null". return status.Errorf(codes.NotFound, "switch %q does not exist", n.Switch) } return errors.Annotate(err, "failed to create NIC").Err() } if err := tx.Commit(); err != nil { return errors.Annotate(err, "failed to commit transaction").Err() } return nil }
go
func createNIC(c context.Context, n *crimson.NIC) error { if err := validateNICForCreation(n); err != nil { return err } mac, _ := common.ParseMAC48(n.MacAddress) tx, err := database.Begin(c) if err != nil { return errors.Annotate(err, "failed to begin transaction").Err() } defer tx.MaybeRollback(c) var hostnameId sql.NullInt64 if n.Hostname != "" { ip, _ := common.ParseIPv4(n.Ipv4) id, err := model.AssignHostnameAndIP(c, tx, n.Hostname, ip) if err != nil { return err } hostnameId.Int64 = id hostnameId.Valid = true } // By setting nics.machine_id NOT NULL when setting up the database, we can avoid checking if the given machine is // valid. MySQL will turn up NULL for its column values which will be rejected as an error. _, err = tx.ExecContext(c, ` INSERT INTO nics (name, machine_id, mac_address, switch_id, switchport, hostname_id) VALUES (?, (SELECT id FROM machines WHERE name = ?), ?, (SELECT id FROM switches WHERE name = ?), ?, ?) `, n.Name, n.Machine, mac, n.Switch, n.Switchport, hostnameId) if err != nil { switch e, ok := err.(*mysql.MySQLError); { case !ok: // Type assertion failed. case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'name'"): // e.g. "Error 1062: Duplicate entry 'eth0-machineId' for key 'name'". return status.Errorf(codes.AlreadyExists, "duplicate NIC %q for machine %q", n.Name, n.Machine) case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'mac_address'"): // e.g. "Error 1062: Duplicate entry '1234567890' for key 'mac_address'". return status.Errorf(codes.AlreadyExists, "duplicate MAC address %q", n.MacAddress) case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'machine_id'"): // e.g. "Error 1048: Column 'machine_id' cannot be null". return status.Errorf(codes.NotFound, "machine %q does not exist", n.Machine) case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'switch_id'"): // e.g. "Error 1048: Column 'switch_id' cannot be null". return status.Errorf(codes.NotFound, "switch %q does not exist", n.Switch) } return errors.Annotate(err, "failed to create NIC").Err() } if err := tx.Commit(); err != nil { return errors.Annotate(err, "failed to commit transaction").Err() } return nil }
[ "func", "createNIC", "(", "c", "context", ".", "Context", ",", "n", "*", "crimson", ".", "NIC", ")", "error", "{", "if", "err", ":=", "validateNICForCreation", "(", "n", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "mac", ",", "_", ":=", "common", ".", "ParseMAC48", "(", "n", ".", "MacAddress", ")", "\n", "tx", ",", "err", ":=", "database", ".", "Begin", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "tx", ".", "MaybeRollback", "(", "c", ")", "\n\n", "var", "hostnameId", "sql", ".", "NullInt64", "\n", "if", "n", ".", "Hostname", "!=", "\"", "\"", "{", "ip", ",", "_", ":=", "common", ".", "ParseIPv4", "(", "n", ".", "Ipv4", ")", "\n", "id", ",", "err", ":=", "model", ".", "AssignHostnameAndIP", "(", "c", ",", "tx", ",", "n", ".", "Hostname", ",", "ip", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "hostnameId", ".", "Int64", "=", "id", "\n", "hostnameId", ".", "Valid", "=", "true", "\n", "}", "\n\n", "// By setting nics.machine_id NOT NULL when setting up the database, we can avoid checking if the given machine is", "// valid. MySQL will turn up NULL for its column values which will be rejected as an error.", "_", ",", "err", "=", "tx", ".", "ExecContext", "(", "c", ",", "`\n\t\tINSERT INTO nics (name, machine_id, mac_address, switch_id, switchport, hostname_id)\n\t\tVALUES (?, (SELECT id FROM machines WHERE name = ?), ?, (SELECT id FROM switches WHERE name = ?), ?, ?)\n\t`", ",", "n", ".", "Name", ",", "n", ".", "Machine", ",", "mac", ",", "n", ".", "Switch", ",", "n", ".", "Switchport", ",", "hostnameId", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "e", ",", "ok", ":=", "err", ".", "(", "*", "mysql", ".", "MySQLError", ")", ";", "{", "case", "!", "ok", ":", "// Type assertion failed.", "case", "e", ".", "Number", "==", "mysqlerr", ".", "ER_DUP_ENTRY", "&&", "strings", ".", "Contains", "(", "e", ".", "Message", ",", "\"", "\"", ")", ":", "// e.g. \"Error 1062: Duplicate entry 'eth0-machineId' for key 'name'\".", "return", "status", ".", "Errorf", "(", "codes", ".", "AlreadyExists", ",", "\"", "\"", ",", "n", ".", "Name", ",", "n", ".", "Machine", ")", "\n", "case", "e", ".", "Number", "==", "mysqlerr", ".", "ER_DUP_ENTRY", "&&", "strings", ".", "Contains", "(", "e", ".", "Message", ",", "\"", "\"", ")", ":", "// e.g. \"Error 1062: Duplicate entry '1234567890' for key 'mac_address'\".", "return", "status", ".", "Errorf", "(", "codes", ".", "AlreadyExists", ",", "\"", "\"", ",", "n", ".", "MacAddress", ")", "\n", "case", "e", ".", "Number", "==", "mysqlerr", ".", "ER_BAD_NULL_ERROR", "&&", "strings", ".", "Contains", "(", "e", ".", "Message", ",", "\"", "\"", ")", ":", "// e.g. \"Error 1048: Column 'machine_id' cannot be null\".", "return", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "n", ".", "Machine", ")", "\n", "case", "e", ".", "Number", "==", "mysqlerr", ".", "ER_BAD_NULL_ERROR", "&&", "strings", ".", "Contains", "(", "e", ".", "Message", ",", "\"", "\"", ")", ":", "// e.g. \"Error 1048: Column 'switch_id' cannot be null\".", "return", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "n", ".", "Switch", ")", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "err", ":=", "tx", ".", "Commit", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// createNIC creates a new NIC in the database.
[ "createNIC", "creates", "a", "new", "NIC", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L73-L125
7,013
luci/luci-go
machine-db/appengine/rpc/nics.go
getHostnameForNIC
func getHostnameForNIC(c context.Context, q database.QueryerContext, name, machine string) (*int64, error) { rows, err := q.QueryContext(c, ` SELECT h.id FROM nics n, machines m, hostnames h WHERE n.machine_id = m.id AND n.hostname_id = h.id AND n.name = ? AND m.name = ? `, name, machine) if err != nil { return nil, errors.Annotate(err, "failed to fetch associated hostname").Err() } defer rows.Close() if rows.Next() { var hostnameId int64 if err = rows.Scan(&hostnameId); err != nil { return nil, errors.Annotate(err, "failed to fetch hostname").Err() } return &hostnameId, nil } return nil, nil }
go
func getHostnameForNIC(c context.Context, q database.QueryerContext, name, machine string) (*int64, error) { rows, err := q.QueryContext(c, ` SELECT h.id FROM nics n, machines m, hostnames h WHERE n.machine_id = m.id AND n.hostname_id = h.id AND n.name = ? AND m.name = ? `, name, machine) if err != nil { return nil, errors.Annotate(err, "failed to fetch associated hostname").Err() } defer rows.Close() if rows.Next() { var hostnameId int64 if err = rows.Scan(&hostnameId); err != nil { return nil, errors.Annotate(err, "failed to fetch hostname").Err() } return &hostnameId, nil } return nil, nil }
[ "func", "getHostnameForNIC", "(", "c", "context", ".", "Context", ",", "q", "database", ".", "QueryerContext", ",", "name", ",", "machine", "string", ")", "(", "*", "int64", ",", "error", ")", "{", "rows", ",", "err", ":=", "q", ".", "QueryContext", "(", "c", ",", "`\n\t\tSELECT h.id FROM nics n, machines m, hostnames h\n\t\tWHERE n.machine_id = m.id AND n.hostname_id = h.id AND n.name = ? AND m.name = ?\n\t`", ",", "name", ",", "machine", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "if", "rows", ".", "Next", "(", ")", "{", "var", "hostnameId", "int64", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "hostnameId", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "&", "hostnameId", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// getHostnameForNIC gets the ID of the hostname associated with an existing NIC.
[ "getHostnameForNIC", "gets", "the", "ID", "of", "the", "hostname", "associated", "with", "an", "existing", "NIC", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L128-L145
7,014
luci/luci-go
machine-db/appengine/rpc/nics.go
deleteNIC
func deleteNIC(c context.Context, name, machine string) error { switch { case name == "": return status.Error(codes.InvalidArgument, "NIC name is required and must be non-empty") case machine == "": return status.Error(codes.InvalidArgument, "machine is required and must be non-empty") } tx, err := database.Begin(c) if err != nil { return errors.Annotate(err, "failed to begin transaction").Err() } defer tx.MaybeRollback(c) // If a NIC is backing a host, don't delete it. If not, delete it and its hostname (if it has one). // Deleting a hostname cascades to the host, so hostname can't be deleted without first checking // for a host. Deleting a hostname sets null in the NIC, so the NIC still has to be deleted. hosts, err := listPhysicalHosts(c, tx, &crimson.ListPhysicalHostsRequest{ Machines: []string{machine}, }) if err != nil { return errors.Annotate(err, "failed to fetch associated physical host").Err() } if len(hosts) > 0 { return status.Errorf(codes.FailedPrecondition, "delete entities referencing this NIC first") } // Delete the NIC's hostname, if it has one. hostnameId, err := getHostnameForNIC(c, tx, name, machine) if err != nil { return err } if hostnameId != nil { _, err = tx.ExecContext(c, `DELETE FROM hostnames WHERE id = ?`, *hostnameId) if err != nil { return errors.Annotate(err, "failed to delete associated hostname").Err() } } res, err := tx.ExecContext(c, ` DELETE FROM nics WHERE name = ? AND machine_id = (SELECT id FROM machines WHERE name = ?) `, name, machine) if err != nil { return errors.Annotate(err, "failed to delete NIC").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, "NIC %q does not exist on machine %q", name, machine) } if err := tx.Commit(); err != nil { return errors.Annotate(err, "failed to commit transaction").Err() } return nil }
go
func deleteNIC(c context.Context, name, machine string) error { switch { case name == "": return status.Error(codes.InvalidArgument, "NIC name is required and must be non-empty") case machine == "": return status.Error(codes.InvalidArgument, "machine is required and must be non-empty") } tx, err := database.Begin(c) if err != nil { return errors.Annotate(err, "failed to begin transaction").Err() } defer tx.MaybeRollback(c) // If a NIC is backing a host, don't delete it. If not, delete it and its hostname (if it has one). // Deleting a hostname cascades to the host, so hostname can't be deleted without first checking // for a host. Deleting a hostname sets null in the NIC, so the NIC still has to be deleted. hosts, err := listPhysicalHosts(c, tx, &crimson.ListPhysicalHostsRequest{ Machines: []string{machine}, }) if err != nil { return errors.Annotate(err, "failed to fetch associated physical host").Err() } if len(hosts) > 0 { return status.Errorf(codes.FailedPrecondition, "delete entities referencing this NIC first") } // Delete the NIC's hostname, if it has one. hostnameId, err := getHostnameForNIC(c, tx, name, machine) if err != nil { return err } if hostnameId != nil { _, err = tx.ExecContext(c, `DELETE FROM hostnames WHERE id = ?`, *hostnameId) if err != nil { return errors.Annotate(err, "failed to delete associated hostname").Err() } } res, err := tx.ExecContext(c, ` DELETE FROM nics WHERE name = ? AND machine_id = (SELECT id FROM machines WHERE name = ?) `, name, machine) if err != nil { return errors.Annotate(err, "failed to delete NIC").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, "NIC %q does not exist on machine %q", name, machine) } if err := tx.Commit(); err != nil { return errors.Annotate(err, "failed to commit transaction").Err() } return nil }
[ "func", "deleteNIC", "(", "c", "context", ".", "Context", ",", "name", ",", "machine", "string", ")", "error", "{", "switch", "{", "case", "name", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "machine", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "tx", ",", "err", ":=", "database", ".", "Begin", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "tx", ".", "MaybeRollback", "(", "c", ")", "\n\n", "// If a NIC is backing a host, don't delete it. If not, delete it and its hostname (if it has one).", "// Deleting a hostname cascades to the host, so hostname can't be deleted without first checking", "// for a host. Deleting a hostname sets null in the NIC, so the NIC still has to be deleted.", "hosts", ",", "err", ":=", "listPhysicalHosts", "(", "c", ",", "tx", ",", "&", "crimson", ".", "ListPhysicalHostsRequest", "{", "Machines", ":", "[", "]", "string", "{", "machine", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "len", "(", "hosts", ")", ">", "0", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "FailedPrecondition", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Delete the NIC's hostname, if it has one.", "hostnameId", ",", "err", ":=", "getHostnameForNIC", "(", "c", ",", "tx", ",", "name", ",", "machine", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "hostnameId", "!=", "nil", "{", "_", ",", "err", "=", "tx", ".", "ExecContext", "(", "c", ",", "`DELETE FROM hostnames WHERE id = ?`", ",", "*", "hostnameId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n\n", "res", ",", "err", ":=", "tx", ".", "ExecContext", "(", "c", ",", "`\n\t\tDELETE FROM nics WHERE name = ? AND machine_id = (SELECT id FROM machines WHERE name = ?)\n\t`", ",", "name", ",", "machine", ")", "\n", "if", "err", "!=", "nil", "{", "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", ",", "machine", ")", "\n", "}", "\n\n", "if", "err", ":=", "tx", ".", "Commit", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// deleteNIC deletes an existing NIC from the database.
[ "deleteNIC", "deletes", "an", "existing", "NIC", "from", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L148-L203
7,015
luci/luci-go
machine-db/appengine/rpc/nics.go
listNICs
func listNICs(c context.Context, q database.QueryerContext, req *crimson.ListNICsRequest) ([]*crimson.NIC, error) { mac48s, err := parseMAC48s(req.MacAddresses) if err != nil { return nil, err } stmt := squirrel.Select("n.name", "m.name", "n.mac_address", "s.name", "n.switchport"). From("nics n, machines m, switches s"). Where("n.machine_id = m.id").Where("n.switch_id = s.id") stmt = selectInString(stmt, "n.name", req.Names) stmt = selectInString(stmt, "m.name", req.Machines) stmt = selectInUint64(stmt, "n.mac_address", mac48s) stmt = selectInString(stmt, "s.name", req.Switches) query, args, err := stmt.ToSql() if err != nil { return nil, errors.Annotate(err, "failed to generate statement").Err() } rows, err := q.QueryContext(c, query, args...) if err != nil { return nil, errors.Annotate(err, "failed to fetch NICs").Err() } defer rows.Close() var nics []*crimson.NIC for rows.Next() { n := &crimson.NIC{} var mac48 common.MAC48 if err = rows.Scan(&n.Name, &n.Machine, &mac48, &n.Switch, &n.Switchport); err != nil { return nil, errors.Annotate(err, "failed to fetch NIC").Err() } n.MacAddress = mac48.String() nics = append(nics, n) } return nics, nil }
go
func listNICs(c context.Context, q database.QueryerContext, req *crimson.ListNICsRequest) ([]*crimson.NIC, error) { mac48s, err := parseMAC48s(req.MacAddresses) if err != nil { return nil, err } stmt := squirrel.Select("n.name", "m.name", "n.mac_address", "s.name", "n.switchport"). From("nics n, machines m, switches s"). Where("n.machine_id = m.id").Where("n.switch_id = s.id") stmt = selectInString(stmt, "n.name", req.Names) stmt = selectInString(stmt, "m.name", req.Machines) stmt = selectInUint64(stmt, "n.mac_address", mac48s) stmt = selectInString(stmt, "s.name", req.Switches) query, args, err := stmt.ToSql() if err != nil { return nil, errors.Annotate(err, "failed to generate statement").Err() } rows, err := q.QueryContext(c, query, args...) if err != nil { return nil, errors.Annotate(err, "failed to fetch NICs").Err() } defer rows.Close() var nics []*crimson.NIC for rows.Next() { n := &crimson.NIC{} var mac48 common.MAC48 if err = rows.Scan(&n.Name, &n.Machine, &mac48, &n.Switch, &n.Switchport); err != nil { return nil, errors.Annotate(err, "failed to fetch NIC").Err() } n.MacAddress = mac48.String() nics = append(nics, n) } return nics, nil }
[ "func", "listNICs", "(", "c", "context", ".", "Context", ",", "q", "database", ".", "QueryerContext", ",", "req", "*", "crimson", ".", "ListNICsRequest", ")", "(", "[", "]", "*", "crimson", ".", "NIC", ",", "error", ")", "{", "mac48s", ",", "err", ":=", "parseMAC48s", "(", "req", ".", "MacAddresses", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stmt", ":=", "squirrel", ".", "Select", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", ".", "From", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Names", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Machines", ")", "\n", "stmt", "=", "selectInUint64", "(", "stmt", ",", "\"", "\"", ",", "mac48s", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Switches", ")", "\n", "query", ",", "args", ",", "err", ":=", "stmt", ".", "ToSql", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "rows", ",", "err", ":=", "q", ".", "QueryContext", "(", "c", ",", "query", ",", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "var", "nics", "[", "]", "*", "crimson", ".", "NIC", "\n", "for", "rows", ".", "Next", "(", ")", "{", "n", ":=", "&", "crimson", ".", "NIC", "{", "}", "\n", "var", "mac48", "common", ".", "MAC48", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "n", ".", "Name", ",", "&", "n", ".", "Machine", ",", "&", "mac48", ",", "&", "n", ".", "Switch", ",", "&", "n", ".", "Switchport", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "n", ".", "MacAddress", "=", "mac48", ".", "String", "(", ")", "\n", "nics", "=", "append", "(", "nics", ",", "n", ")", "\n", "}", "\n", "return", "nics", ",", "nil", "\n", "}" ]
// listNICs returns a slice of NICs in the database.
[ "listNICs", "returns", "a", "slice", "of", "NICs", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L206-L240
7,016
luci/luci-go
machine-db/appengine/rpc/nics.go
parseMAC48s
func parseMAC48s(macs []string) ([]uint64, error) { mac48s := make([]uint64, len(macs)) for i, mac := range macs { mac48, err := common.ParseMAC48(mac) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", mac) } mac48s[i] = uint64(mac48) } return mac48s, nil }
go
func parseMAC48s(macs []string) ([]uint64, error) { mac48s := make([]uint64, len(macs)) for i, mac := range macs { mac48, err := common.ParseMAC48(mac) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", mac) } mac48s[i] = uint64(mac48) } return mac48s, nil }
[ "func", "parseMAC48s", "(", "macs", "[", "]", "string", ")", "(", "[", "]", "uint64", ",", "error", ")", "{", "mac48s", ":=", "make", "(", "[", "]", "uint64", ",", "len", "(", "macs", ")", ")", "\n", "for", "i", ",", "mac", ":=", "range", "macs", "{", "mac48", ",", "err", ":=", "common", ".", "ParseMAC48", "(", "mac", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "mac", ")", "\n", "}", "\n", "mac48s", "[", "i", "]", "=", "uint64", "(", "mac48", ")", "\n", "}", "\n", "return", "mac48s", ",", "nil", "\n", "}" ]
// parseMAC48s returns a slice of uint64 MAC addresses.
[ "parseMAC48s", "returns", "a", "slice", "of", "uint64", "MAC", "addresses", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L243-L253
7,017
luci/luci-go
machine-db/appengine/rpc/nics.go
validateNICForCreation
func validateNICForCreation(n *crimson.NIC) error { switch { case n == nil: return status.Error(codes.InvalidArgument, "NIC specification is required") case n.Name == "": return status.Error(codes.InvalidArgument, "NIC name is required and must be non-empty") case n.Machine == "": return status.Error(codes.InvalidArgument, "machine is required and must be non-empty") case n.Switch == "": return status.Error(codes.InvalidArgument, "switch is required and must be non-empty") case n.Switchport < 1: return status.Error(codes.InvalidArgument, "switchport must be positive") default: // If hostname or IPv4 address is specified, require both. if n.Hostname != "" || n.Ipv4 != "" { if n.Hostname == "" { return status.Errorf(codes.InvalidArgument, "if IPv4 is specified then hostname is required and must be non-empty") } if n.Ipv4 == "" { return status.Errorf(codes.InvalidArgument, "if hostname is specified then IPv4 address is required and must be non-empty") } _, err := common.ParseIPv4(n.Ipv4) if err != nil { return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", n.Ipv4) } } _, err := common.ParseMAC48(n.MacAddress) if err != nil { return status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", n.MacAddress) } return nil } }
go
func validateNICForCreation(n *crimson.NIC) error { switch { case n == nil: return status.Error(codes.InvalidArgument, "NIC specification is required") case n.Name == "": return status.Error(codes.InvalidArgument, "NIC name is required and must be non-empty") case n.Machine == "": return status.Error(codes.InvalidArgument, "machine is required and must be non-empty") case n.Switch == "": return status.Error(codes.InvalidArgument, "switch is required and must be non-empty") case n.Switchport < 1: return status.Error(codes.InvalidArgument, "switchport must be positive") default: // If hostname or IPv4 address is specified, require both. if n.Hostname != "" || n.Ipv4 != "" { if n.Hostname == "" { return status.Errorf(codes.InvalidArgument, "if IPv4 is specified then hostname is required and must be non-empty") } if n.Ipv4 == "" { return status.Errorf(codes.InvalidArgument, "if hostname is specified then IPv4 address is required and must be non-empty") } _, err := common.ParseIPv4(n.Ipv4) if err != nil { return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", n.Ipv4) } } _, err := common.ParseMAC48(n.MacAddress) if err != nil { return status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", n.MacAddress) } return nil } }
[ "func", "validateNICForCreation", "(", "n", "*", "crimson", ".", "NIC", ")", "error", "{", "switch", "{", "case", "n", "==", "nil", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "n", ".", "Name", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "n", ".", "Machine", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "n", ".", "Switch", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "n", ".", "Switchport", "<", "1", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "default", ":", "// If hostname or IPv4 address is specified, require both.", "if", "n", ".", "Hostname", "!=", "\"", "\"", "||", "n", ".", "Ipv4", "!=", "\"", "\"", "{", "if", "n", ".", "Hostname", "==", "\"", "\"", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "n", ".", "Ipv4", "==", "\"", "\"", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "_", ",", "err", ":=", "common", ".", "ParseIPv4", "(", "n", ".", "Ipv4", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "n", ".", "Ipv4", ")", "\n", "}", "\n", "}", "\n", "_", ",", "err", ":=", "common", ".", "ParseMAC48", "(", "n", ".", "MacAddress", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "n", ".", "MacAddress", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// validateNICForCreation validates a NIC for creation.
[ "validateNICForCreation", "validates", "a", "NIC", "for", "creation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L319-L351
7,018
luci/luci-go
machine-db/appengine/rpc/nics.go
validateNICForUpdate
func validateNICForUpdate(n *crimson.NIC, mask *field_mask.FieldMask) error { switch err := validateUpdateMask(mask); { case n == nil: return status.Error(codes.InvalidArgument, "NIC specification is required") case n.Name == "": return status.Error(codes.InvalidArgument, "NIC name is required and must be non-empty") case n.Machine == "": return status.Error(codes.InvalidArgument, "machine is required and must be non-empty") case err != nil: return err } for _, path := range mask.Paths { // TODO(smut): Allow hostname, IPv4 address to be updated. switch path { case "name": return status.Error(codes.InvalidArgument, "NIC name cannot be updated, delete and create a new NIC instead") case "machine": return status.Error(codes.InvalidArgument, "machine cannot be updated, delete and create a new NIC instead") case "mac_address": if n.MacAddress == "" { return status.Error(codes.InvalidArgument, "MAC address is required and must be non-empty") } _, err := common.ParseMAC48(n.MacAddress) if err != nil { return status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", n.MacAddress) } case "switch": if n.Switch == "" { return status.Error(codes.InvalidArgument, "switch is required and must be non-empty") } case "switchport": if n.Switchport < 1 { return status.Error(codes.InvalidArgument, "switchport must be positive") } default: return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path) } } return nil }
go
func validateNICForUpdate(n *crimson.NIC, mask *field_mask.FieldMask) error { switch err := validateUpdateMask(mask); { case n == nil: return status.Error(codes.InvalidArgument, "NIC specification is required") case n.Name == "": return status.Error(codes.InvalidArgument, "NIC name is required and must be non-empty") case n.Machine == "": return status.Error(codes.InvalidArgument, "machine is required and must be non-empty") case err != nil: return err } for _, path := range mask.Paths { // TODO(smut): Allow hostname, IPv4 address to be updated. switch path { case "name": return status.Error(codes.InvalidArgument, "NIC name cannot be updated, delete and create a new NIC instead") case "machine": return status.Error(codes.InvalidArgument, "machine cannot be updated, delete and create a new NIC instead") case "mac_address": if n.MacAddress == "" { return status.Error(codes.InvalidArgument, "MAC address is required and must be non-empty") } _, err := common.ParseMAC48(n.MacAddress) if err != nil { return status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", n.MacAddress) } case "switch": if n.Switch == "" { return status.Error(codes.InvalidArgument, "switch is required and must be non-empty") } case "switchport": if n.Switchport < 1 { return status.Error(codes.InvalidArgument, "switchport must be positive") } default: return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path) } } return nil }
[ "func", "validateNICForUpdate", "(", "n", "*", "crimson", ".", "NIC", ",", "mask", "*", "field_mask", ".", "FieldMask", ")", "error", "{", "switch", "err", ":=", "validateUpdateMask", "(", "mask", ")", ";", "{", "case", "n", "==", "nil", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "n", ".", "Name", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "n", ".", "Machine", "==", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "err", "!=", "nil", ":", "return", "err", "\n", "}", "\n", "for", "_", ",", "path", ":=", "range", "mask", ".", "Paths", "{", "// TODO(smut): Allow hostname, IPv4 address to be updated.", "switch", "path", "{", "case", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "\"", "\"", ":", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "case", "\"", "\"", ":", "if", "n", ".", "MacAddress", "==", "\"", "\"", "{", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "_", ",", "err", ":=", "common", ".", "ParseMAC48", "(", "n", ".", "MacAddress", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "n", ".", "MacAddress", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "n", ".", "Switch", "==", "\"", "\"", "{", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "n", ".", "Switchport", "<", "1", "{", "return", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateNICForUpdate validates a NIC for update.
[ "validateNICForUpdate", "validates", "a", "NIC", "for", "update", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/nics.go#L354-L393
7,019
luci/luci-go
buildbucket/protoutil/search.go
searchBuilds
func searchBuilds(ctx context.Context, buildC chan<- *pb.Build, client pb.BuildsClient, req *pb.SearchBuildsRequest) error { // Prepare a channel of responses, s.t. we make an RPC as soon as we started // consuming the response, as opposed to after the response is completely // consumed. resC := make(chan *pb.SearchBuildsResponse) errC := make(chan error) go func() { err := searchResponses(ctx, resC, client, req) close(resC) errC <- err }() // Forward builds. for res := range resC { for _, b := range res.Builds { select { case buildC <- b: // Note: selecting on errC here would be a race because goroutine // above might have been already done, but we still did not send // all builds to the caller. case <-ctx.Done(): return <-errC } } } return <-errC }
go
func searchBuilds(ctx context.Context, buildC chan<- *pb.Build, client pb.BuildsClient, req *pb.SearchBuildsRequest) error { // Prepare a channel of responses, s.t. we make an RPC as soon as we started // consuming the response, as opposed to after the response is completely // consumed. resC := make(chan *pb.SearchBuildsResponse) errC := make(chan error) go func() { err := searchResponses(ctx, resC, client, req) close(resC) errC <- err }() // Forward builds. for res := range resC { for _, b := range res.Builds { select { case buildC <- b: // Note: selecting on errC here would be a race because goroutine // above might have been already done, but we still did not send // all builds to the caller. case <-ctx.Done(): return <-errC } } } return <-errC }
[ "func", "searchBuilds", "(", "ctx", "context", ".", "Context", ",", "buildC", "chan", "<-", "*", "pb", ".", "Build", ",", "client", "pb", ".", "BuildsClient", ",", "req", "*", "pb", ".", "SearchBuildsRequest", ")", "error", "{", "// Prepare a channel of responses, s.t. we make an RPC as soon as we started", "// consuming the response, as opposed to after the response is completely", "// consumed.", "resC", ":=", "make", "(", "chan", "*", "pb", ".", "SearchBuildsResponse", ")", "\n", "errC", ":=", "make", "(", "chan", "error", ")", "\n", "go", "func", "(", ")", "{", "err", ":=", "searchResponses", "(", "ctx", ",", "resC", ",", "client", ",", "req", ")", "\n", "close", "(", "resC", ")", "\n", "errC", "<-", "err", "\n", "}", "(", ")", "\n\n", "// Forward builds.", "for", "res", ":=", "range", "resC", "{", "for", "_", ",", "b", ":=", "range", "res", ".", "Builds", "{", "select", "{", "case", "buildC", "<-", "b", ":", "// Note: selecting on errC here would be a race because goroutine", "// above might have been already done, but we still did not send", "// all builds to the caller.", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "<-", "errC", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "<-", "errC", "\n", "}" ]
// searchBuilds is like Search, but does not implement union of search results. // Sent builds have ids.
[ "searchBuilds", "is", "like", "Search", "but", "does", "not", "implement", "union", "of", "search", "results", ".", "Sent", "builds", "have", "ids", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/search.go#L110-L137
7,020
luci/luci-go
buildbucket/protoutil/search.go
searchResponses
func searchResponses(ctx context.Context, resC chan<- *pb.SearchBuildsResponse, client pb.BuildsClient, req *pb.SearchBuildsRequest) error { req = proto.Clone(req).(*pb.SearchBuildsRequest) // Ensure next_page_token and build id are requested. if len(req.GetFields().GetPaths()) > 0 { req.Fields.Paths = append(req.Fields.Paths, "next_page_token", "builds.*.id") } // Page through results. for { res, err := client.SearchBuilds(ctx, req) if err != nil { return err } select { case resC <- res: case <-ctx.Done(): return ctx.Err() } if res.NextPageToken == "" || len(res.Builds) == 0 { return nil } // Next page... req.PageToken = res.NextPageToken } }
go
func searchResponses(ctx context.Context, resC chan<- *pb.SearchBuildsResponse, client pb.BuildsClient, req *pb.SearchBuildsRequest) error { req = proto.Clone(req).(*pb.SearchBuildsRequest) // Ensure next_page_token and build id are requested. if len(req.GetFields().GetPaths()) > 0 { req.Fields.Paths = append(req.Fields.Paths, "next_page_token", "builds.*.id") } // Page through results. for { res, err := client.SearchBuilds(ctx, req) if err != nil { return err } select { case resC <- res: case <-ctx.Done(): return ctx.Err() } if res.NextPageToken == "" || len(res.Builds) == 0 { return nil } // Next page... req.PageToken = res.NextPageToken } }
[ "func", "searchResponses", "(", "ctx", "context", ".", "Context", ",", "resC", "chan", "<-", "*", "pb", ".", "SearchBuildsResponse", ",", "client", "pb", ".", "BuildsClient", ",", "req", "*", "pb", ".", "SearchBuildsRequest", ")", "error", "{", "req", "=", "proto", ".", "Clone", "(", "req", ")", ".", "(", "*", "pb", ".", "SearchBuildsRequest", ")", "\n\n", "// Ensure next_page_token and build id are requested.", "if", "len", "(", "req", ".", "GetFields", "(", ")", ".", "GetPaths", "(", ")", ")", ">", "0", "{", "req", ".", "Fields", ".", "Paths", "=", "append", "(", "req", ".", "Fields", ".", "Paths", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Page through results.", "for", "{", "res", ",", "err", ":=", "client", ".", "SearchBuilds", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "select", "{", "case", "resC", "<-", "res", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "res", ".", "NextPageToken", "==", "\"", "\"", "||", "len", "(", "res", ".", "Builds", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Next page...", "req", ".", "PageToken", "=", "res", ".", "NextPageToken", "\n", "}", "\n", "}" ]
// searchResponses pages through search results and sends search responses to // resC. // Builds in resC have ids.
[ "searchResponses", "pages", "through", "search", "results", "and", "sends", "search", "responses", "to", "resC", ".", "Builds", "in", "resC", "have", "ids", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/search.go#L142-L170
7,021
luci/luci-go
buildbucket/protoutil/search.go
Swap
func (h streamHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
go
func (h streamHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
[ "func", "(", "h", "streamHeap", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "h", "[", "i", "]", ",", "h", "[", "j", "]", "=", "h", "[", "j", "]", ",", "h", "[", "i", "]", "\n", "}" ]
// Swap implements sort.Interface.
[ "Swap", "implements", "sort", ".", "Interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/search.go#L189-L191
7,022
luci/luci-go
buildbucket/protoutil/search.go
Pop
func (h *streamHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x }
go
func (h *streamHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x }
[ "func", "(", "h", "*", "streamHeap", ")", "Pop", "(", ")", "interface", "{", "}", "{", "old", ":=", "*", "h", "\n", "n", ":=", "len", "(", "old", ")", "\n", "x", ":=", "old", "[", "n", "-", "1", "]", "\n", "*", "h", "=", "old", "[", "0", ":", "n", "-", "1", "]", "\n", "return", "x", "\n", "}" ]
// Pop implements heap.Interface.
[ "Pop", "implements", "heap", ".", "Interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/search.go#L201-L207
7,023
luci/luci-go
machine-db/api/common/v1/prefixes.go
Name
func (s State) Name() string { switch s { case State_STATE_UNSPECIFIED: return "" case State_FREE: return "free" case State_PRERELEASE: return "prerelease" case State_SERVING: return "serving" case State_TEST: return "test" case State_REPAIR: return "repair" case State_DECOMMISSIONED: return "decommissioned" default: return "invalid state" } }
go
func (s State) Name() string { switch s { case State_STATE_UNSPECIFIED: return "" case State_FREE: return "free" case State_PRERELEASE: return "prerelease" case State_SERVING: return "serving" case State_TEST: return "test" case State_REPAIR: return "repair" case State_DECOMMISSIONED: return "decommissioned" default: return "invalid state" } }
[ "func", "(", "s", "State", ")", "Name", "(", ")", "string", "{", "switch", "s", "{", "case", "State_STATE_UNSPECIFIED", ":", "return", "\"", "\"", "\n", "case", "State_FREE", ":", "return", "\"", "\"", "\n", "case", "State_PRERELEASE", ":", "return", "\"", "\"", "\n", "case", "State_SERVING", ":", "return", "\"", "\"", "\n", "case", "State_TEST", ":", "return", "\"", "\"", "\n", "case", "State_REPAIR", ":", "return", "\"", "\"", "\n", "case", "State_DECOMMISSIONED", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// Name returns a string which can be used as the human-readable representation expected by GetState.
[ "Name", "returns", "a", "string", "which", "can", "be", "used", "as", "the", "human", "-", "readable", "representation", "expected", "by", "GetState", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/api/common/v1/prefixes.go#L24-L43
7,024
luci/luci-go
machine-db/api/common/v1/prefixes.go
GetState
func GetState(s string) (State, error) { lower := strings.ToLower(s) switch { case lower == "": return State_STATE_UNSPECIFIED, nil case strings.HasPrefix("free", lower): return State_FREE, nil case strings.HasPrefix("prerelease", lower): return State_PRERELEASE, nil case strings.HasPrefix("serving", lower): return State_SERVING, nil case strings.HasPrefix("test", lower): return State_TEST, nil case strings.HasPrefix("repair", lower): return State_REPAIR, nil case strings.HasPrefix("decommissioned", lower): return State_DECOMMISSIONED, nil default: return -1, errors.Reason("string %q did not match any known state", s).Err() } }
go
func GetState(s string) (State, error) { lower := strings.ToLower(s) switch { case lower == "": return State_STATE_UNSPECIFIED, nil case strings.HasPrefix("free", lower): return State_FREE, nil case strings.HasPrefix("prerelease", lower): return State_PRERELEASE, nil case strings.HasPrefix("serving", lower): return State_SERVING, nil case strings.HasPrefix("test", lower): return State_TEST, nil case strings.HasPrefix("repair", lower): return State_REPAIR, nil case strings.HasPrefix("decommissioned", lower): return State_DECOMMISSIONED, nil default: return -1, errors.Reason("string %q did not match any known state", s).Err() } }
[ "func", "GetState", "(", "s", "string", ")", "(", "State", ",", "error", ")", "{", "lower", ":=", "strings", ".", "ToLower", "(", "s", ")", "\n", "switch", "{", "case", "lower", "==", "\"", "\"", ":", "return", "State_STATE_UNSPECIFIED", ",", "nil", "\n", "case", "strings", ".", "HasPrefix", "(", "\"", "\"", ",", "lower", ")", ":", "return", "State_FREE", ",", "nil", "\n", "case", "strings", ".", "HasPrefix", "(", "\"", "\"", ",", "lower", ")", ":", "return", "State_PRERELEASE", ",", "nil", "\n", "case", "strings", ".", "HasPrefix", "(", "\"", "\"", ",", "lower", ")", ":", "return", "State_SERVING", ",", "nil", "\n", "case", "strings", ".", "HasPrefix", "(", "\"", "\"", ",", "lower", ")", ":", "return", "State_TEST", ",", "nil", "\n", "case", "strings", ".", "HasPrefix", "(", "\"", "\"", ",", "lower", ")", ":", "return", "State_REPAIR", ",", "nil", "\n", "case", "strings", ".", "HasPrefix", "(", "\"", "\"", ",", "lower", ")", ":", "return", "State_DECOMMISSIONED", ",", "nil", "\n", "default", ":", "return", "-", "1", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "s", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// GetState returns a State given its name. Supports prefix matching.
[ "GetState", "returns", "a", "State", "given", "its", "name", ".", "Supports", "prefix", "matching", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/api/common/v1/prefixes.go#L46-L66
7,025
luci/luci-go
cipd/client/cipd/ensure/package_def.go
Expand
func (p *PackageDef) Expand(expander template.Expander) (pkg string, err error) { switch pkg, err = expander.Expand(p.PackageTemplate); { case err == template.ErrSkipTemplate: return "", err case err != nil: return "", errors.Annotate(err, "failed to expand package template (line %d)", p.LineNo).Err() } if err = common.ValidatePackageName(pkg); err != nil { return "", errors.Annotate(err, "bad package name (line %d)", p.LineNo).Err() } if err = common.ValidateInstanceVersion(p.UnresolvedVersion); err != nil { return "", errors.Annotate(err, "bad package version (line %d)", p.LineNo).Err() } return }
go
func (p *PackageDef) Expand(expander template.Expander) (pkg string, err error) { switch pkg, err = expander.Expand(p.PackageTemplate); { case err == template.ErrSkipTemplate: return "", err case err != nil: return "", errors.Annotate(err, "failed to expand package template (line %d)", p.LineNo).Err() } if err = common.ValidatePackageName(pkg); err != nil { return "", errors.Annotate(err, "bad package name (line %d)", p.LineNo).Err() } if err = common.ValidateInstanceVersion(p.UnresolvedVersion); err != nil { return "", errors.Annotate(err, "bad package version (line %d)", p.LineNo).Err() } return }
[ "func", "(", "p", "*", "PackageDef", ")", "Expand", "(", "expander", "template", ".", "Expander", ")", "(", "pkg", "string", ",", "err", "error", ")", "{", "switch", "pkg", ",", "err", "=", "expander", ".", "Expand", "(", "p", ".", "PackageTemplate", ")", ";", "{", "case", "err", "==", "template", ".", "ErrSkipTemplate", ":", "return", "\"", "\"", ",", "err", "\n", "case", "err", "!=", "nil", ":", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "p", ".", "LineNo", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "err", "=", "common", ".", "ValidatePackageName", "(", "pkg", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "p", ".", "LineNo", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "err", "=", "common", ".", "ValidateInstanceVersion", "(", "p", ".", "UnresolvedVersion", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "p", ".", "LineNo", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Expand expands the package name template and checks that resulting package // name and version are syntactically correct. // // May return template.ErrSkipTemplate is this package definition should be // skipped given the current expansion variables values.
[ "Expand", "expands", "the", "package", "name", "template", "and", "checks", "that", "resulting", "package", "name", "and", "version", "are", "syntactically", "correct", ".", "May", "return", "template", ".", "ErrSkipTemplate", "is", "this", "package", "definition", "should", "be", "skipped", "given", "the", "current", "expansion", "variables", "values", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/ensure/package_def.go#L52-L66
7,026
luci/luci-go
client/archiver/tar_archiver.go
shardItems
func shardItems(items []*Item, threshold int64) []*itemBundle { // For deterministic isolated hashes, sort the items by path. sort.Sort(itemByPath(items)) var bundles []*itemBundle for len(items) > 0 { var bundle *itemBundle bundle, items = oneBundle(items, threshold) bundles = append(bundles, bundle) } return bundles }
go
func shardItems(items []*Item, threshold int64) []*itemBundle { // For deterministic isolated hashes, sort the items by path. sort.Sort(itemByPath(items)) var bundles []*itemBundle for len(items) > 0 { var bundle *itemBundle bundle, items = oneBundle(items, threshold) bundles = append(bundles, bundle) } return bundles }
[ "func", "shardItems", "(", "items", "[", "]", "*", "Item", ",", "threshold", "int64", ")", "[", "]", "*", "itemBundle", "{", "// For deterministic isolated hashes, sort the items by path.", "sort", ".", "Sort", "(", "itemByPath", "(", "items", ")", ")", "\n\n", "var", "bundles", "[", "]", "*", "itemBundle", "\n", "for", "len", "(", "items", ")", ">", "0", "{", "var", "bundle", "*", "itemBundle", "\n", "bundle", ",", "items", "=", "oneBundle", "(", "items", ",", "threshold", ")", "\n", "bundles", "=", "append", "(", "bundles", ",", "bundle", ")", "\n", "}", "\n", "return", "bundles", "\n", "}" ]
// shardItems shards the provided items into itemBundles, using the provided // threshold as the maximum size the resultant tars should be. // // shardItems does not access the filesystem.
[ "shardItems", "shards", "the", "provided", "items", "into", "itemBundles", "using", "the", "provided", "threshold", "as", "the", "maximum", "size", "the", "resultant", "tars", "should", "be", ".", "shardItems", "does", "not", "access", "the", "filesystem", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/tar_archiver.go#L45-L56
7,027
luci/luci-go
client/archiver/tar_archiver.go
Digest
func (b *itemBundle) Digest(h crypto.Hash) (isolated.HexDigest, int64, error) { a := h.New() cw := &iotools.CountingWriter{Writer: a} if err := b.writeTar(cw); err != nil { return "", 0, err } return isolated.Sum(a), cw.Count, nil }
go
func (b *itemBundle) Digest(h crypto.Hash) (isolated.HexDigest, int64, error) { a := h.New() cw := &iotools.CountingWriter{Writer: a} if err := b.writeTar(cw); err != nil { return "", 0, err } return isolated.Sum(a), cw.Count, nil }
[ "func", "(", "b", "*", "itemBundle", ")", "Digest", "(", "h", "crypto", ".", "Hash", ")", "(", "isolated", ".", "HexDigest", ",", "int64", ",", "error", ")", "{", "a", ":=", "h", ".", "New", "(", ")", "\n", "cw", ":=", "&", "iotools", ".", "CountingWriter", "{", "Writer", ":", "a", "}", "\n", "if", "err", ":=", "b", ".", "writeTar", "(", "cw", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "0", ",", "err", "\n", "}", "\n", "return", "isolated", ".", "Sum", "(", "a", ")", ",", "cw", ".", "Count", ",", "nil", "\n", "}" ]
// Digest returns the hash and total size of the tar constructed from the // bundle's items.
[ "Digest", "returns", "the", "hash", "and", "total", "size", "of", "the", "tar", "constructed", "from", "the", "bundle", "s", "items", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/tar_archiver.go#L79-L86
7,028
luci/luci-go
client/archiver/tar_archiver.go
Contents
func (b *itemBundle) Contents() (io.ReadCloser, error) { pr, pw := io.Pipe() go func() { pw.CloseWithError(b.writeTar(pw)) }() return pr, nil }
go
func (b *itemBundle) Contents() (io.ReadCloser, error) { pr, pw := io.Pipe() go func() { pw.CloseWithError(b.writeTar(pw)) }() return pr, nil }
[ "func", "(", "b", "*", "itemBundle", ")", "Contents", "(", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "pr", ",", "pw", ":=", "io", ".", "Pipe", "(", ")", "\n", "go", "func", "(", ")", "{", "pw", ".", "CloseWithError", "(", "b", ".", "writeTar", "(", "pw", ")", ")", "\n", "}", "(", ")", "\n", "return", "pr", ",", "nil", "\n", "}" ]
// Contents returns an io.ReadCloser containing the tar's contents.
[ "Contents", "returns", "an", "io", ".", "ReadCloser", "containing", "the", "tar", "s", "contents", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/tar_archiver.go#L89-L95
7,029
luci/luci-go
common/errors/annotate.go
dumpWrappersTo
func (r *renderedFrame) dumpWrappersTo(w io.Writer, from, to int) (n int, err error) { return iotools.WriteTracker(w, func(rawWriter io.Writer) error { w := &indented.Writer{Writer: rawWriter, UseSpaces: true} fmt.Fprintf(w, "From frame %d to %d, the following wrappers were found:\n", from, to) for i, wrp := range r.wrappers { if i != 0 { w.Write(nlSlice) } w.Level = 2 for i, line := range wrp { if i == 0 { fmt.Fprintf(w, "%s\n", line) w.Level += 2 } else { fmt.Fprintf(w, "%s\n", line) } } } return nil }) }
go
func (r *renderedFrame) dumpWrappersTo(w io.Writer, from, to int) (n int, err error) { return iotools.WriteTracker(w, func(rawWriter io.Writer) error { w := &indented.Writer{Writer: rawWriter, UseSpaces: true} fmt.Fprintf(w, "From frame %d to %d, the following wrappers were found:\n", from, to) for i, wrp := range r.wrappers { if i != 0 { w.Write(nlSlice) } w.Level = 2 for i, line := range wrp { if i == 0 { fmt.Fprintf(w, "%s\n", line) w.Level += 2 } else { fmt.Fprintf(w, "%s\n", line) } } } return nil }) }
[ "func", "(", "r", "*", "renderedFrame", ")", "dumpWrappersTo", "(", "w", "io", ".", "Writer", ",", "from", ",", "to", "int", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "iotools", ".", "WriteTracker", "(", "w", ",", "func", "(", "rawWriter", "io", ".", "Writer", ")", "error", "{", "w", ":=", "&", "indented", ".", "Writer", "{", "Writer", ":", "rawWriter", ",", "UseSpaces", ":", "true", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "from", ",", "to", ")", "\n", "for", "i", ",", "wrp", ":=", "range", "r", ".", "wrappers", "{", "if", "i", "!=", "0", "{", "w", ".", "Write", "(", "nlSlice", ")", "\n", "}", "\n", "w", ".", "Level", "=", "2", "\n", "for", "i", ",", "line", ":=", "range", "wrp", "{", "if", "i", "==", "0", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "line", ")", "\n", "w", ".", "Level", "+=", "2", "\n", "}", "else", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "line", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// dumpWrappersTo formats the wrappers portion of this renderedFrame.
[ "dumpWrappersTo", "formats", "the", "wrappers", "portion", "of", "this", "renderedFrame", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/annotate.go#L270-L290
7,030
luci/luci-go
common/errors/annotate.go
dumpTo
func (r *renderedFrame) dumpTo(w io.Writer, idx int) (n int, err error) { return iotools.WriteTracker(w, func(rawWriter io.Writer) error { w := &indented.Writer{Writer: rawWriter, UseSpaces: true} fmt.Fprintf(w, "#%d %s/%s:%d - %s()\n", idx, r.pkg, r.file, r.lineNum, r.funcName) w.Level += 2 switch len(r.annotations) { case 0: // pass case 1: for _, line := range r.annotations[0] { fmt.Fprintf(w, "%s\n", line) } default: for i, ann := range r.annotations { fmt.Fprintf(w, "annotation #%d:\n", i) w.Level += 2 for _, line := range ann { fmt.Fprintf(w, "%s\n", line) } w.Level -= 2 } } return nil }) }
go
func (r *renderedFrame) dumpTo(w io.Writer, idx int) (n int, err error) { return iotools.WriteTracker(w, func(rawWriter io.Writer) error { w := &indented.Writer{Writer: rawWriter, UseSpaces: true} fmt.Fprintf(w, "#%d %s/%s:%d - %s()\n", idx, r.pkg, r.file, r.lineNum, r.funcName) w.Level += 2 switch len(r.annotations) { case 0: // pass case 1: for _, line := range r.annotations[0] { fmt.Fprintf(w, "%s\n", line) } default: for i, ann := range r.annotations { fmt.Fprintf(w, "annotation #%d:\n", i) w.Level += 2 for _, line := range ann { fmt.Fprintf(w, "%s\n", line) } w.Level -= 2 } } return nil }) }
[ "func", "(", "r", "*", "renderedFrame", ")", "dumpTo", "(", "w", "io", ".", "Writer", ",", "idx", "int", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "iotools", ".", "WriteTracker", "(", "w", ",", "func", "(", "rawWriter", "io", ".", "Writer", ")", "error", "{", "w", ":=", "&", "indented", ".", "Writer", "{", "Writer", ":", "rawWriter", ",", "UseSpaces", ":", "true", "}", "\n\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "idx", ",", "r", ".", "pkg", ",", "r", ".", "file", ",", "r", ".", "lineNum", ",", "r", ".", "funcName", ")", "\n", "w", ".", "Level", "+=", "2", "\n", "switch", "len", "(", "r", ".", "annotations", ")", "{", "case", "0", ":", "// pass", "case", "1", ":", "for", "_", ",", "line", ":=", "range", "r", ".", "annotations", "[", "0", "]", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "line", ")", "\n", "}", "\n", "default", ":", "for", "i", ",", "ann", ":=", "range", "r", ".", "annotations", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "i", ")", "\n", "w", ".", "Level", "+=", "2", "\n", "for", "_", ",", "line", ":=", "range", "ann", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "line", ")", "\n", "}", "\n", "w", ".", "Level", "-=", "2", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// dumpTo formats the Header and annotations for this renderedFrame.
[ "dumpTo", "formats", "the", "Header", "and", "annotations", "for", "this", "renderedFrame", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/annotate.go#L293-L319
7,031
luci/luci-go
common/errors/annotate.go
dumpTo
func (r *renderedStack) dumpTo(w io.Writer, excludePkgs ...string) (n int, err error) { excludeSet := stringset.NewFromSlice(excludePkgs...) return iotools.WriteTracker(w, func(w io.Writer) error { fmt.Fprintf(w, "goroutine %d:\n", r.goID) lastIdx := 0 needNL := false skipCount := 0 skipPkg := "" flushSkips := func(extra string) { if skipCount != 0 { if needNL { w.Write(nlSlice) needNL = false } fmt.Fprintf(w, "... skipped %d frames in pkg %q...\n%s", skipCount, skipPkg, extra) skipCount = 0 skipPkg = "" } } for i, f := range r.frames { if needNL { w.Write(nlSlice) needNL = false } if excludeSet.Has(f.pkg) { if skipPkg == f.pkg { skipCount++ } else { flushSkips("") skipCount++ skipPkg = f.pkg } continue } flushSkips("\n") if len(f.wrappers) > 0 { f.dumpWrappersTo(w, lastIdx, i) w.Write(nlSlice) } if len(f.annotations) > 0 { lastIdx = i needNL = true } f.dumpTo(w, i) } flushSkips("") return nil }) }
go
func (r *renderedStack) dumpTo(w io.Writer, excludePkgs ...string) (n int, err error) { excludeSet := stringset.NewFromSlice(excludePkgs...) return iotools.WriteTracker(w, func(w io.Writer) error { fmt.Fprintf(w, "goroutine %d:\n", r.goID) lastIdx := 0 needNL := false skipCount := 0 skipPkg := "" flushSkips := func(extra string) { if skipCount != 0 { if needNL { w.Write(nlSlice) needNL = false } fmt.Fprintf(w, "... skipped %d frames in pkg %q...\n%s", skipCount, skipPkg, extra) skipCount = 0 skipPkg = "" } } for i, f := range r.frames { if needNL { w.Write(nlSlice) needNL = false } if excludeSet.Has(f.pkg) { if skipPkg == f.pkg { skipCount++ } else { flushSkips("") skipCount++ skipPkg = f.pkg } continue } flushSkips("\n") if len(f.wrappers) > 0 { f.dumpWrappersTo(w, lastIdx, i) w.Write(nlSlice) } if len(f.annotations) > 0 { lastIdx = i needNL = true } f.dumpTo(w, i) } flushSkips("") return nil }) }
[ "func", "(", "r", "*", "renderedStack", ")", "dumpTo", "(", "w", "io", ".", "Writer", ",", "excludePkgs", "...", "string", ")", "(", "n", "int", ",", "err", "error", ")", "{", "excludeSet", ":=", "stringset", ".", "NewFromSlice", "(", "excludePkgs", "...", ")", "\n\n", "return", "iotools", ".", "WriteTracker", "(", "w", ",", "func", "(", "w", "io", ".", "Writer", ")", "error", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "r", ".", "goID", ")", "\n\n", "lastIdx", ":=", "0", "\n", "needNL", ":=", "false", "\n", "skipCount", ":=", "0", "\n", "skipPkg", ":=", "\"", "\"", "\n", "flushSkips", ":=", "func", "(", "extra", "string", ")", "{", "if", "skipCount", "!=", "0", "{", "if", "needNL", "{", "w", ".", "Write", "(", "nlSlice", ")", "\n", "needNL", "=", "false", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "skipCount", ",", "skipPkg", ",", "extra", ")", "\n", "skipCount", "=", "0", "\n", "skipPkg", "=", "\"", "\"", "\n", "}", "\n", "}", "\n", "for", "i", ",", "f", ":=", "range", "r", ".", "frames", "{", "if", "needNL", "{", "w", ".", "Write", "(", "nlSlice", ")", "\n", "needNL", "=", "false", "\n", "}", "\n", "if", "excludeSet", ".", "Has", "(", "f", ".", "pkg", ")", "{", "if", "skipPkg", "==", "f", ".", "pkg", "{", "skipCount", "++", "\n", "}", "else", "{", "flushSkips", "(", "\"", "\"", ")", "\n", "skipCount", "++", "\n", "skipPkg", "=", "f", ".", "pkg", "\n", "}", "\n", "continue", "\n", "}", "\n", "flushSkips", "(", "\"", "\\n", "\"", ")", "\n", "if", "len", "(", "f", ".", "wrappers", ")", ">", "0", "{", "f", ".", "dumpWrappersTo", "(", "w", ",", "lastIdx", ",", "i", ")", "\n", "w", ".", "Write", "(", "nlSlice", ")", "\n", "}", "\n", "if", "len", "(", "f", ".", "annotations", ")", ">", "0", "{", "lastIdx", "=", "i", "\n", "needNL", "=", "true", "\n", "}", "\n", "f", ".", "dumpTo", "(", "w", ",", "i", ")", "\n", "}", "\n", "flushSkips", "(", "\"", "\"", ")", "\n\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// dumpTo formats the full stack.
[ "dumpTo", "formats", "the", "full", "stack", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/annotate.go#L328-L379
7,032
luci/luci-go
common/errors/annotate.go
toLines
func (r *renderedError) toLines(excludePkgs ...string) lines { buf := bytes.Buffer{} r.dumpTo(&buf, excludePkgs...) return strings.Split(strings.TrimSuffix(buf.String(), "\n"), "\n") }
go
func (r *renderedError) toLines(excludePkgs ...string) lines { buf := bytes.Buffer{} r.dumpTo(&buf, excludePkgs...) return strings.Split(strings.TrimSuffix(buf.String(), "\n"), "\n") }
[ "func", "(", "r", "*", "renderedError", ")", "toLines", "(", "excludePkgs", "...", "string", ")", "lines", "{", "buf", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "r", ".", "dumpTo", "(", "&", "buf", ",", "excludePkgs", "...", ")", "\n", "return", "strings", ".", "Split", "(", "strings", ".", "TrimSuffix", "(", "buf", ".", "String", "(", ")", ",", "\"", "\\n", "\"", ")", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// toLines renders a full-information stack trace as a series of lines.
[ "toLines", "renders", "a", "full", "-", "information", "stack", "trace", "as", "a", "series", "of", "lines", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/annotate.go#L389-L393
7,033
luci/luci-go
common/errors/annotate.go
dumpTo
func (r *renderedError) dumpTo(w io.Writer, excludePkgs ...string) (n int, err error) { return iotools.WriteTracker(w, func(w io.Writer) error { if r.originalError != "" { fmt.Fprintf(w, "original error: %s\n\n", r.originalError) } for i := len(r.stacks) - 1; i >= 0; i-- { if i != len(r.stacks)-1 { w.Write(nlSlice) } r.stacks[i].dumpTo(w, excludePkgs...) } return nil }) }
go
func (r *renderedError) dumpTo(w io.Writer, excludePkgs ...string) (n int, err error) { return iotools.WriteTracker(w, func(w io.Writer) error { if r.originalError != "" { fmt.Fprintf(w, "original error: %s\n\n", r.originalError) } for i := len(r.stacks) - 1; i >= 0; i-- { if i != len(r.stacks)-1 { w.Write(nlSlice) } r.stacks[i].dumpTo(w, excludePkgs...) } return nil }) }
[ "func", "(", "r", "*", "renderedError", ")", "dumpTo", "(", "w", "io", ".", "Writer", ",", "excludePkgs", "...", "string", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "iotools", ".", "WriteTracker", "(", "w", ",", "func", "(", "w", "io", ".", "Writer", ")", "error", "{", "if", "r", ".", "originalError", "!=", "\"", "\"", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\\n", "\"", ",", "r", ".", "originalError", ")", "\n", "}", "\n\n", "for", "i", ":=", "len", "(", "r", ".", "stacks", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "i", "!=", "len", "(", "r", ".", "stacks", ")", "-", "1", "{", "w", ".", "Write", "(", "nlSlice", ")", "\n", "}", "\n", "r", ".", "stacks", "[", "i", "]", ".", "dumpTo", "(", "w", ",", "excludePkgs", "...", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// dumpTo writes the full-information stack trace to the writer.
[ "dumpTo", "writes", "the", "full", "-", "information", "stack", "trace", "to", "the", "writer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/annotate.go#L396-L410
7,034
luci/luci-go
common/errors/annotate.go
RenderStack
func RenderStack(err error, excludePkgs ...string) []string { return renderStack(err).toLines(excludePkgs...) }
go
func RenderStack(err error, excludePkgs ...string) []string { return renderStack(err).toLines(excludePkgs...) }
[ "func", "RenderStack", "(", "err", "error", ",", "excludePkgs", "...", "string", ")", "[", "]", "string", "{", "return", "renderStack", "(", "err", ")", ".", "toLines", "(", "excludePkgs", "...", ")", "\n", "}" ]
// RenderStack renders the error to a list of lines.
[ "RenderStack", "renders", "the", "error", "to", "a", "list", "of", "lines", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/annotate.go#L437-L439
7,035
luci/luci-go
common/errors/annotate.go
New
func New(msg string, tags ...TagValueGenerator) error { tse := &terminalStackError{ errors.New(msg), stackFrameInfo{forStack: captureStack(1)}, nil} if len(tags) > 0 { tse.tags = make(map[TagKey]interface{}, len(tags)) for _, t := range tags { v := t.GenerateErrorTagValue() tse.tags[v.Key] = v.Value } } return tse }
go
func New(msg string, tags ...TagValueGenerator) error { tse := &terminalStackError{ errors.New(msg), stackFrameInfo{forStack: captureStack(1)}, nil} if len(tags) > 0 { tse.tags = make(map[TagKey]interface{}, len(tags)) for _, t := range tags { v := t.GenerateErrorTagValue() tse.tags[v.Key] = v.Value } } return tse }
[ "func", "New", "(", "msg", "string", ",", "tags", "...", "TagValueGenerator", ")", "error", "{", "tse", ":=", "&", "terminalStackError", "{", "errors", ".", "New", "(", "msg", ")", ",", "stackFrameInfo", "{", "forStack", ":", "captureStack", "(", "1", ")", "}", ",", "nil", "}", "\n", "if", "len", "(", "tags", ")", ">", "0", "{", "tse", ".", "tags", "=", "make", "(", "map", "[", "TagKey", "]", "interface", "{", "}", ",", "len", "(", "tags", ")", ")", "\n", "for", "_", ",", "t", ":=", "range", "tags", "{", "v", ":=", "t", ".", "GenerateErrorTagValue", "(", ")", "\n", "tse", ".", "tags", "[", "v", ".", "Key", "]", "=", "v", ".", "Value", "\n", "}", "\n", "}", "\n", "return", "tse", "\n", "}" ]
// New is an API-compatible version of the standard errors.New function. Unlike // the stdlib errors.New, this will capture the current stack information at the // place this error was created.
[ "New", "is", "an", "API", "-", "compatible", "version", "of", "the", "standard", "errors", ".", "New", "function", ".", "Unlike", "the", "stdlib", "errors", ".", "New", "this", "will", "capture", "the", "current", "stack", "information", "at", "the", "place", "this", "error", "was", "created", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/annotate.go#L555-L566
7,036
luci/luci-go
starlark/starlarkproto/functions.go
toTextPb
func toTextPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { var msg *Message if err := starlark.UnpackArgs("to_textpb", args, kwargs, "msg", &msg); err != nil { return nil, err } pb, err := msg.ToProto() if err != nil { return nil, err } return starlark.String(proto.MarshalTextString(pb)), nil }
go
func toTextPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { var msg *Message if err := starlark.UnpackArgs("to_textpb", args, kwargs, "msg", &msg); err != nil { return nil, err } pb, err := msg.ToProto() if err != nil { return nil, err } return starlark.String(proto.MarshalTextString(pb)), nil }
[ "func", "toTextPb", "(", "_", "*", "starlark", ".", "Thread", ",", "_", "*", "starlark", ".", "Builtin", ",", "args", "starlark", ".", "Tuple", ",", "kwargs", "[", "]", "starlark", ".", "Tuple", ")", "(", "starlark", ".", "Value", ",", "error", ")", "{", "var", "msg", "*", "Message", "\n", "if", "err", ":=", "starlark", ".", "UnpackArgs", "(", "\"", "\"", ",", "args", ",", "kwargs", ",", "\"", "\"", ",", "&", "msg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pb", ",", "err", ":=", "msg", ".", "ToProto", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "starlark", ".", "String", "(", "proto", ".", "MarshalTextString", "(", "pb", ")", ")", ",", "nil", "\n", "}" ]
// toTextPb takes a single protobuf message and serializes it using text // protobuf serialization.
[ "toTextPb", "takes", "a", "single", "protobuf", "message", "and", "serializes", "it", "using", "text", "protobuf", "serialization", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/functions.go#L92-L102
7,037
luci/luci-go
starlark/starlarkproto/functions.go
toJSONPb
func toJSONPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { var msg *Message var emitDefaults starlark.Bool if err := starlark.UnpackArgs("to_jsonpb", args, kwargs, "msg", &msg, "emit_defaults?", &emitDefaults); err != nil { return nil, err } pb, err := msg.ToProto() if err != nil { return nil, err } // More jsonpb Marshaler options may be added here as needed. var jsonMarshaler = &jsonpb.Marshaler{Indent: "\t", EmitDefaults: bool(emitDefaults)} str, err := jsonMarshaler.MarshalToString(pb) if err != nil { return nil, err } return starlark.String(str), nil }
go
func toJSONPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { var msg *Message var emitDefaults starlark.Bool if err := starlark.UnpackArgs("to_jsonpb", args, kwargs, "msg", &msg, "emit_defaults?", &emitDefaults); err != nil { return nil, err } pb, err := msg.ToProto() if err != nil { return nil, err } // More jsonpb Marshaler options may be added here as needed. var jsonMarshaler = &jsonpb.Marshaler{Indent: "\t", EmitDefaults: bool(emitDefaults)} str, err := jsonMarshaler.MarshalToString(pb) if err != nil { return nil, err } return starlark.String(str), nil }
[ "func", "toJSONPb", "(", "_", "*", "starlark", ".", "Thread", ",", "_", "*", "starlark", ".", "Builtin", ",", "args", "starlark", ".", "Tuple", ",", "kwargs", "[", "]", "starlark", ".", "Tuple", ")", "(", "starlark", ".", "Value", ",", "error", ")", "{", "var", "msg", "*", "Message", "\n", "var", "emitDefaults", "starlark", ".", "Bool", "\n", "if", "err", ":=", "starlark", ".", "UnpackArgs", "(", "\"", "\"", ",", "args", ",", "kwargs", ",", "\"", "\"", ",", "&", "msg", ",", "\"", "\"", ",", "&", "emitDefaults", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pb", ",", "err", ":=", "msg", ".", "ToProto", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// More jsonpb Marshaler options may be added here as needed.", "var", "jsonMarshaler", "=", "&", "jsonpb", ".", "Marshaler", "{", "Indent", ":", "\"", "\\t", "\"", ",", "EmitDefaults", ":", "bool", "(", "emitDefaults", ")", "}", "\n", "str", ",", "err", ":=", "jsonMarshaler", ".", "MarshalToString", "(", "pb", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "starlark", ".", "String", "(", "str", ")", ",", "nil", "\n", "}" ]
// toJSONPb takes a single protobuf message and serializes it using JSONPB // serialization.
[ "toJSONPb", "takes", "a", "single", "protobuf", "message", "and", "serializes", "it", "using", "JSONPB", "serialization", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/functions.go#L106-L123
7,038
luci/luci-go
milo/buildsource/swarming/buildinfo.go
GetBuildInfo
func (p *BuildInfoProvider) GetBuildInfo(c context.Context, req *milo.BuildInfoRequest_Swarming, projectHint string) (*milo.BuildInfoResponse, error) { // Load the Swarming task (no log content). sf, err := p.newSwarmingService(c, req.Host) if err != nil { logging.WithError(err).Errorf(c, "Failed to create Swarming fetcher.") return nil, grpcutil.Internal } // Use default Swarming host. host := sf.GetHost() logging.Infof(c, "Loading build info for Swarming host %s, task %s.", host, req.Task) fr, err := swarmingFetch(c, sf, req.Task, swarmingFetchParams{}) if err != nil { if err == ErrNotMiloJob { logging.Warningf(c, "User requested nonexistent task or does not have permissions.") return nil, grpcutil.NotFound } logging.WithError(err).Errorf(c, "Failed to load Swarming task.") return nil, grpcutil.Internal } // Determine the LogDog annotation stream path for this Swarming task. // // On failure, will return a gRPC error. stream, err := resolveLogDogAnnotations(c, fr.res.Tags) if err != nil { logging.WithError(err).Warningf(c, "Failed to get annotation stream parameters.") return nil, err } logging.Fields{ "host": stream.Host, "project": stream.Project, "path": stream.Path, }.Infof(c, "Resolved LogDog annotation stream.") step, err := rawpresentation.ReadAnnotations(c, stream) if err != nil { return nil, errors.Annotate(err, "failed to read annotations").Err() } // Add Swarming task parameters to the Milo step. if err := addTaskToMiloStep(c, sf.GetHost(), fr.res, step); err != nil { return nil, err } prefix, name := stream.Path.Split() return &milo.BuildInfoResponse{ Project: string(stream.Project), Step: step, AnnotationStream: &miloProto.LogdogStream{ Server: stream.Host, Prefix: string(prefix), Name: string(name), }, }, nil }
go
func (p *BuildInfoProvider) GetBuildInfo(c context.Context, req *milo.BuildInfoRequest_Swarming, projectHint string) (*milo.BuildInfoResponse, error) { // Load the Swarming task (no log content). sf, err := p.newSwarmingService(c, req.Host) if err != nil { logging.WithError(err).Errorf(c, "Failed to create Swarming fetcher.") return nil, grpcutil.Internal } // Use default Swarming host. host := sf.GetHost() logging.Infof(c, "Loading build info for Swarming host %s, task %s.", host, req.Task) fr, err := swarmingFetch(c, sf, req.Task, swarmingFetchParams{}) if err != nil { if err == ErrNotMiloJob { logging.Warningf(c, "User requested nonexistent task or does not have permissions.") return nil, grpcutil.NotFound } logging.WithError(err).Errorf(c, "Failed to load Swarming task.") return nil, grpcutil.Internal } // Determine the LogDog annotation stream path for this Swarming task. // // On failure, will return a gRPC error. stream, err := resolveLogDogAnnotations(c, fr.res.Tags) if err != nil { logging.WithError(err).Warningf(c, "Failed to get annotation stream parameters.") return nil, err } logging.Fields{ "host": stream.Host, "project": stream.Project, "path": stream.Path, }.Infof(c, "Resolved LogDog annotation stream.") step, err := rawpresentation.ReadAnnotations(c, stream) if err != nil { return nil, errors.Annotate(err, "failed to read annotations").Err() } // Add Swarming task parameters to the Milo step. if err := addTaskToMiloStep(c, sf.GetHost(), fr.res, step); err != nil { return nil, err } prefix, name := stream.Path.Split() return &milo.BuildInfoResponse{ Project: string(stream.Project), Step: step, AnnotationStream: &miloProto.LogdogStream{ Server: stream.Host, Prefix: string(prefix), Name: string(name), }, }, nil }
[ "func", "(", "p", "*", "BuildInfoProvider", ")", "GetBuildInfo", "(", "c", "context", ".", "Context", ",", "req", "*", "milo", ".", "BuildInfoRequest_Swarming", ",", "projectHint", "string", ")", "(", "*", "milo", ".", "BuildInfoResponse", ",", "error", ")", "{", "// Load the Swarming task (no log content).", "sf", ",", "err", ":=", "p", ".", "newSwarmingService", "(", "c", ",", "req", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "Internal", "\n", "}", "\n\n", "// Use default Swarming host.", "host", ":=", "sf", ".", "GetHost", "(", ")", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "host", ",", "req", ".", "Task", ")", "\n\n", "fr", ",", "err", ":=", "swarmingFetch", "(", "c", ",", "sf", ",", "req", ".", "Task", ",", "swarmingFetchParams", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "ErrNotMiloJob", "{", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "NotFound", "\n", "}", "\n\n", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "Internal", "\n", "}", "\n\n", "// Determine the LogDog annotation stream path for this Swarming task.", "//", "// On failure, will return a gRPC error.", "stream", ",", "err", ":=", "resolveLogDogAnnotations", "(", "c", ",", "fr", ".", "res", ".", "Tags", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "logging", ".", "Fields", "{", "\"", "\"", ":", "stream", ".", "Host", ",", "\"", "\"", ":", "stream", ".", "Project", ",", "\"", "\"", ":", "stream", ".", "Path", ",", "}", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n\n", "step", ",", "err", ":=", "rawpresentation", ".", "ReadAnnotations", "(", "c", ",", "stream", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Add Swarming task parameters to the Milo step.", "if", "err", ":=", "addTaskToMiloStep", "(", "c", ",", "sf", ".", "GetHost", "(", ")", ",", "fr", ".", "res", ",", "step", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "prefix", ",", "name", ":=", "stream", ".", "Path", ".", "Split", "(", ")", "\n", "return", "&", "milo", ".", "BuildInfoResponse", "{", "Project", ":", "string", "(", "stream", ".", "Project", ")", ",", "Step", ":", "step", ",", "AnnotationStream", ":", "&", "miloProto", ".", "LogdogStream", "{", "Server", ":", "stream", ".", "Host", ",", "Prefix", ":", "string", "(", "prefix", ")", ",", "Name", ":", "string", "(", "name", ")", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// GetBuildInfo resolves a Milo protobuf Step for a given Swarming task.
[ "GetBuildInfo", "resolves", "a", "Milo", "protobuf", "Step", "for", "a", "given", "Swarming", "task", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/buildinfo.go#L49-L109
7,039
luci/luci-go
milo/buildsource/swarming/buildinfo.go
resolveLogDogAnnotations
func resolveLogDogAnnotations(c context.Context, tagsRaw []string) (*types.StreamAddr, error) { addr, err := resolveLogDogStreamAddrFromTags(swarmingTags(tagsRaw)) if err != nil { logging.WithError(err).Debugf(c, "Could not resolve stream address from tags.") return nil, grpcutil.NotFound } return addr, nil }
go
func resolveLogDogAnnotations(c context.Context, tagsRaw []string) (*types.StreamAddr, error) { addr, err := resolveLogDogStreamAddrFromTags(swarmingTags(tagsRaw)) if err != nil { logging.WithError(err).Debugf(c, "Could not resolve stream address from tags.") return nil, grpcutil.NotFound } return addr, nil }
[ "func", "resolveLogDogAnnotations", "(", "c", "context", ".", "Context", ",", "tagsRaw", "[", "]", "string", ")", "(", "*", "types", ".", "StreamAddr", ",", "error", ")", "{", "addr", ",", "err", ":=", "resolveLogDogStreamAddrFromTags", "(", "swarmingTags", "(", "tagsRaw", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "NotFound", "\n", "}", "\n", "return", "addr", ",", "nil", "\n", "}" ]
// resolveLogDogAnnotations returns a configured AnnotationStream given the input // parameters. // // This will return a gRPC error on failure.
[ "resolveLogDogAnnotations", "returns", "a", "configured", "AnnotationStream", "given", "the", "input", "parameters", ".", "This", "will", "return", "a", "gRPC", "error", "on", "failure", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/buildinfo.go#L115-L122
7,040
luci/luci-go
tokenserver/client/x509signer.go
LoadX509Signer
func LoadX509Signer(privateKeyPath, certPath string) (*X509Signer, error) { pkey, err := ioutil.ReadFile(privateKeyPath) if err != nil { return nil, err } cert, err := ioutil.ReadFile(certPath) if err != nil { return nil, err } signer := &X509Signer{ PrivateKeyPEM: pkey, CertificatePEM: cert, } if err = signer.Validate(); err != nil { return nil, err } return signer, nil }
go
func LoadX509Signer(privateKeyPath, certPath string) (*X509Signer, error) { pkey, err := ioutil.ReadFile(privateKeyPath) if err != nil { return nil, err } cert, err := ioutil.ReadFile(certPath) if err != nil { return nil, err } signer := &X509Signer{ PrivateKeyPEM: pkey, CertificatePEM: cert, } if err = signer.Validate(); err != nil { return nil, err } return signer, nil }
[ "func", "LoadX509Signer", "(", "privateKeyPath", ",", "certPath", "string", ")", "(", "*", "X509Signer", ",", "error", ")", "{", "pkey", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "privateKeyPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "certPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "signer", ":=", "&", "X509Signer", "{", "PrivateKeyPEM", ":", "pkey", ",", "CertificatePEM", ":", "cert", ",", "}", "\n", "if", "err", "=", "signer", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "signer", ",", "nil", "\n", "}" ]
// LoadX509Signer parses and validates private key and certificate PEM files. // // Returns X509Signer that is ready for work.
[ "LoadX509Signer", "parses", "and", "validates", "private", "key", "and", "certificate", "PEM", "files", ".", "Returns", "X509Signer", "that", "is", "ready", "for", "work", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/client/x509signer.go#L66-L83
7,041
luci/luci-go
tokenserver/client/x509signer.go
Algo
func (s *X509Signer) Algo(ctx context.Context) (x509.SignatureAlgorithm, error) { if err := s.Validate(); err != nil { return 0, err } return s.algo, nil }
go
func (s *X509Signer) Algo(ctx context.Context) (x509.SignatureAlgorithm, error) { if err := s.Validate(); err != nil { return 0, err } return s.algo, nil }
[ "func", "(", "s", "*", "X509Signer", ")", "Algo", "(", "ctx", "context", ".", "Context", ")", "(", "x509", ".", "SignatureAlgorithm", ",", "error", ")", "{", "if", "err", ":=", "s", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "s", ".", "algo", ",", "nil", "\n", "}" ]
// Algo returns an algorithm that the signer implements.
[ "Algo", "returns", "an", "algorithm", "that", "the", "signer", "implements", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/client/x509signer.go#L86-L91
7,042
luci/luci-go
tokenserver/client/x509signer.go
Certificate
func (s *X509Signer) Certificate(ctx context.Context) ([]byte, error) { if err := s.Validate(); err != nil { return nil, err } return s.certDer, nil }
go
func (s *X509Signer) Certificate(ctx context.Context) ([]byte, error) { if err := s.Validate(); err != nil { return nil, err } return s.certDer, nil }
[ "func", "(", "s", "*", "X509Signer", ")", "Certificate", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "err", ":=", "s", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "s", ".", "certDer", ",", "nil", "\n", "}" ]
// Certificate returns ASN.1 DER blob with the certificate of the signer.
[ "Certificate", "returns", "ASN", ".", "1", "DER", "blob", "with", "the", "certificate", "of", "the", "signer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/client/x509signer.go#L94-L99
7,043
luci/luci-go
tokenserver/client/x509signer.go
Sign
func (s *X509Signer) Sign(ctx context.Context, blob []byte) ([]byte, error) { if err := s.Validate(); err != nil { return nil, err } var hashFunc crypto.Hash switch s.algo { case x509.SHA256WithRSA: hashFunc = crypto.SHA256 default: panic("someone forgot to implement hashing algo for new kind of a key") } h := hashFunc.New() h.Write(blob) digest := h.Sum(nil) return s.pkey.Sign(cryptorand.Get(ctx), digest, hashFunc) }
go
func (s *X509Signer) Sign(ctx context.Context, blob []byte) ([]byte, error) { if err := s.Validate(); err != nil { return nil, err } var hashFunc crypto.Hash switch s.algo { case x509.SHA256WithRSA: hashFunc = crypto.SHA256 default: panic("someone forgot to implement hashing algo for new kind of a key") } h := hashFunc.New() h.Write(blob) digest := h.Sum(nil) return s.pkey.Sign(cryptorand.Get(ctx), digest, hashFunc) }
[ "func", "(", "s", "*", "X509Signer", ")", "Sign", "(", "ctx", "context", ".", "Context", ",", "blob", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "err", ":=", "s", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "hashFunc", "crypto", ".", "Hash", "\n", "switch", "s", ".", "algo", "{", "case", "x509", ".", "SHA256WithRSA", ":", "hashFunc", "=", "crypto", ".", "SHA256", "\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "h", ":=", "hashFunc", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "blob", ")", "\n", "digest", ":=", "h", ".", "Sum", "(", "nil", ")", "\n\n", "return", "s", ".", "pkey", ".", "Sign", "(", "cryptorand", ".", "Get", "(", "ctx", ")", ",", "digest", ",", "hashFunc", ")", "\n", "}" ]
// Sign signs a blob using the private key.
[ "Sign", "signs", "a", "blob", "using", "the", "private", "key", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/client/x509signer.go#L102-L120
7,044
luci/luci-go
tokenserver/client/x509signer.go
Validate
func (s *X509Signer) Validate() error { s.init.Do(func() { s.err = s.initialize() }) return s.err }
go
func (s *X509Signer) Validate() error { s.init.Do(func() { s.err = s.initialize() }) return s.err }
[ "func", "(", "s", "*", "X509Signer", ")", "Validate", "(", ")", "error", "{", "s", ".", "init", ".", "Do", "(", "func", "(", ")", "{", "s", ".", "err", "=", "s", ".", "initialize", "(", ")", "\n", "}", ")", "\n", "return", "s", ".", "err", "\n", "}" ]
// Validate parses the private key and certificate file and verifies them. // // It checks that the public portion of the key matches what's in the // certificate.
[ "Validate", "parses", "the", "private", "key", "and", "certificate", "file", "and", "verifies", "them", ".", "It", "checks", "that", "the", "public", "portion", "of", "the", "key", "matches", "what", "s", "in", "the", "certificate", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/client/x509signer.go#L126-L131
7,045
luci/luci-go
milo/buildsource/buildbucket/pubsub.go
getSummary
func getSummary(c context.Context, host string, project string, id int64) (*model.BuildSummary, error) { client, err := buildbucketClient(c, host, auth.AsProject, auth.WithProject(project)) if err != nil { return nil, err } b, err := client.GetBuild(c, &buildbucketpb.GetBuildRequest{ Id: id, Fields: summaryBuildMask, }) if err != nil { return nil, err } buildAddress := fmt.Sprintf("%d", b.Id) if b.Number != 0 { buildAddress = fmt.Sprintf("luci.%s.%s/%s/%d", b.Builder.Project, b.Builder.Bucket, b.Builder.Builder, b.Number) } // Note: The parent for buildbucket build summaries is currently a fake entity. // In the future, builds can be cached here, but we currently don't do that. buildKey := datastore.MakeKey(c, "buildbucket.Build", fmt.Sprintf("%s:%s", host, buildAddress)) swarming := b.GetInfra().GetSwarming() bs := &model.BuildSummary{ ProjectID: b.Builder.Project, BuildKey: buildKey, BuilderID: BuilderID{*b.Builder}.String(), BuildID: "buildbucket/" + buildAddress, BuildSet: protoutil.BuildSets(b), ContextURI: []string{fmt.Sprintf("buildbucket://%s/build/%d", host, id)}, Created: mustTimestamp(b.CreateTime), Summary: model.Summary{ Start: mustTimestamp(b.StartTime), End: mustTimestamp(b.EndTime), Status: statusMap[b.Status], }, Version: mustTimestamp(b.UpdateTime).UnixNano(), Experimental: b.GetInput().GetExperimental(), } if task := swarming.GetTaskId(); task != "" { bs.ContextURI = append( bs.ContextURI, fmt.Sprintf("swarming://%s/task/%s", swarming.GetHostname(), swarming.GetTaskId())) } return bs, nil }
go
func getSummary(c context.Context, host string, project string, id int64) (*model.BuildSummary, error) { client, err := buildbucketClient(c, host, auth.AsProject, auth.WithProject(project)) if err != nil { return nil, err } b, err := client.GetBuild(c, &buildbucketpb.GetBuildRequest{ Id: id, Fields: summaryBuildMask, }) if err != nil { return nil, err } buildAddress := fmt.Sprintf("%d", b.Id) if b.Number != 0 { buildAddress = fmt.Sprintf("luci.%s.%s/%s/%d", b.Builder.Project, b.Builder.Bucket, b.Builder.Builder, b.Number) } // Note: The parent for buildbucket build summaries is currently a fake entity. // In the future, builds can be cached here, but we currently don't do that. buildKey := datastore.MakeKey(c, "buildbucket.Build", fmt.Sprintf("%s:%s", host, buildAddress)) swarming := b.GetInfra().GetSwarming() bs := &model.BuildSummary{ ProjectID: b.Builder.Project, BuildKey: buildKey, BuilderID: BuilderID{*b.Builder}.String(), BuildID: "buildbucket/" + buildAddress, BuildSet: protoutil.BuildSets(b), ContextURI: []string{fmt.Sprintf("buildbucket://%s/build/%d", host, id)}, Created: mustTimestamp(b.CreateTime), Summary: model.Summary{ Start: mustTimestamp(b.StartTime), End: mustTimestamp(b.EndTime), Status: statusMap[b.Status], }, Version: mustTimestamp(b.UpdateTime).UnixNano(), Experimental: b.GetInput().GetExperimental(), } if task := swarming.GetTaskId(); task != "" { bs.ContextURI = append( bs.ContextURI, fmt.Sprintf("swarming://%s/task/%s", swarming.GetHostname(), swarming.GetTaskId())) } return bs, nil }
[ "func", "getSummary", "(", "c", "context", ".", "Context", ",", "host", "string", ",", "project", "string", ",", "id", "int64", ")", "(", "*", "model", ".", "BuildSummary", ",", "error", ")", "{", "client", ",", "err", ":=", "buildbucketClient", "(", "c", ",", "host", ",", "auth", ".", "AsProject", ",", "auth", ".", "WithProject", "(", "project", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b", ",", "err", ":=", "client", ".", "GetBuild", "(", "c", ",", "&", "buildbucketpb", ".", "GetBuildRequest", "{", "Id", ":", "id", ",", "Fields", ":", "summaryBuildMask", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "buildAddress", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "Id", ")", "\n", "if", "b", ".", "Number", "!=", "0", "{", "buildAddress", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "Builder", ".", "Project", ",", "b", ".", "Builder", ".", "Bucket", ",", "b", ".", "Builder", ".", "Builder", ",", "b", ".", "Number", ")", "\n", "}", "\n\n", "// Note: The parent for buildbucket build summaries is currently a fake entity.", "// In the future, builds can be cached here, but we currently don't do that.", "buildKey", ":=", "datastore", ".", "MakeKey", "(", "c", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "host", ",", "buildAddress", ")", ")", "\n", "swarming", ":=", "b", ".", "GetInfra", "(", ")", ".", "GetSwarming", "(", ")", "\n\n", "bs", ":=", "&", "model", ".", "BuildSummary", "{", "ProjectID", ":", "b", ".", "Builder", ".", "Project", ",", "BuildKey", ":", "buildKey", ",", "BuilderID", ":", "BuilderID", "{", "*", "b", ".", "Builder", "}", ".", "String", "(", ")", ",", "BuildID", ":", "\"", "\"", "+", "buildAddress", ",", "BuildSet", ":", "protoutil", ".", "BuildSets", "(", "b", ")", ",", "ContextURI", ":", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "host", ",", "id", ")", "}", ",", "Created", ":", "mustTimestamp", "(", "b", ".", "CreateTime", ")", ",", "Summary", ":", "model", ".", "Summary", "{", "Start", ":", "mustTimestamp", "(", "b", ".", "StartTime", ")", ",", "End", ":", "mustTimestamp", "(", "b", ".", "EndTime", ")", ",", "Status", ":", "statusMap", "[", "b", ".", "Status", "]", ",", "}", ",", "Version", ":", "mustTimestamp", "(", "b", ".", "UpdateTime", ")", ".", "UnixNano", "(", ")", ",", "Experimental", ":", "b", ".", "GetInput", "(", ")", ".", "GetExperimental", "(", ")", ",", "}", "\n", "if", "task", ":=", "swarming", ".", "GetTaskId", "(", ")", ";", "task", "!=", "\"", "\"", "{", "bs", ".", "ContextURI", "=", "append", "(", "bs", ".", "ContextURI", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "swarming", ".", "GetHostname", "(", ")", ",", "swarming", ".", "GetTaskId", "(", ")", ")", ")", "\n", "}", "\n", "return", "bs", ",", "nil", "\n", "}" ]
// getSummary returns a model.BuildSummary representing a buildbucket build.
[ "getSummary", "returns", "a", "model", ".", "BuildSummary", "representing", "a", "buildbucket", "build", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/pubsub.go#L104-L148
7,046
luci/luci-go
milo/buildsource/buildbucket/pubsub.go
pubSubHandlerImpl
func pubSubHandlerImpl(c context.Context, r *http.Request) error { // This is the default action. The code below will modify the values of some // or all of these parameters. isLUCI, bucket, status, action := false, "UNKNOWN", "UNKNOWN", "Rejected" defer func() { // closure for late binding buildCounter.Add(c, 1, bucket, isLUCI, status, action) }() msg := common.PubSubSubscription{} if err := json.NewDecoder(r.Body).Decode(&msg); err != nil { // This might be a transient error, e.g. when the json format changes // and Milo isn't updated yet. return errors.Annotate(err, "could not decode message").Tag(transient.Tag).Err() } if v, ok := msg.Message.Attributes["version"].(string); ok && v != "v1" { // TODO(nodir): switch to v2, crbug.com/826006 logging.Debugf(c, "unsupported pubsub message version %q. Ignoring", v) return nil } bData, err := msg.GetData() if err != nil { return errors.Annotate(err, "could not parse pubsub message string").Err() } event := struct { Build bbv1.ApiCommonBuildMessage `json:"build"` Hostname string `json:"hostname"` }{} if err := json.Unmarshal(bData, &event); err != nil { return errors.Annotate(err, "could not parse pubsub message data").Err() } build := deprecated.Build{} if err := build.ParseMessage(&event.Build); err != nil { return errors.Annotate(err, "could not parse deprecated.Build").Err() } bucket = build.Bucket status = build.Status.String() isLUCI = strings.HasPrefix(bucket, "luci.") logging.Debugf(c, "Received from %s: build %s/%s (%s)\n%v", event.Hostname, bucket, build.Builder, status, build) if !isLUCI || build.Builder == "" { logging.Infof(c, "This is not an ingestable build, ignoring") return nil } // TODO(iannucci,nodir): get the bot context too // TODO(iannucci,nodir): support manifests/got_revision bs, err := getSummary(c, event.Hostname, build.Project, build.ID) if err != nil { return err } if err := bs.AddManifestKeysFromBuildSets(c); err != nil { return err } return transient.Tag.Apply(datastore.RunInTransaction(c, func(c context.Context) error { curBS := &model.BuildSummary{BuildKey: bs.BuildKey} switch err := datastore.Get(c, curBS); err { case datastore.ErrNoSuchEntity: action = "Created" case nil: action = "Modified" default: return errors.Annotate(err, "reading current BuildSummary").Err() } if bs.Version <= curBS.Version { logging.Warningf(c, "current BuildSummary is newer: %d <= %d", bs.Version, curBS.Version) return nil } if err := datastore.Put(c, bs); err != nil { return err } return model.UpdateBuilderForBuild(c, bs) }, &datastore.TransactionOptions{XG: true})) }
go
func pubSubHandlerImpl(c context.Context, r *http.Request) error { // This is the default action. The code below will modify the values of some // or all of these parameters. isLUCI, bucket, status, action := false, "UNKNOWN", "UNKNOWN", "Rejected" defer func() { // closure for late binding buildCounter.Add(c, 1, bucket, isLUCI, status, action) }() msg := common.PubSubSubscription{} if err := json.NewDecoder(r.Body).Decode(&msg); err != nil { // This might be a transient error, e.g. when the json format changes // and Milo isn't updated yet. return errors.Annotate(err, "could not decode message").Tag(transient.Tag).Err() } if v, ok := msg.Message.Attributes["version"].(string); ok && v != "v1" { // TODO(nodir): switch to v2, crbug.com/826006 logging.Debugf(c, "unsupported pubsub message version %q. Ignoring", v) return nil } bData, err := msg.GetData() if err != nil { return errors.Annotate(err, "could not parse pubsub message string").Err() } event := struct { Build bbv1.ApiCommonBuildMessage `json:"build"` Hostname string `json:"hostname"` }{} if err := json.Unmarshal(bData, &event); err != nil { return errors.Annotate(err, "could not parse pubsub message data").Err() } build := deprecated.Build{} if err := build.ParseMessage(&event.Build); err != nil { return errors.Annotate(err, "could not parse deprecated.Build").Err() } bucket = build.Bucket status = build.Status.String() isLUCI = strings.HasPrefix(bucket, "luci.") logging.Debugf(c, "Received from %s: build %s/%s (%s)\n%v", event.Hostname, bucket, build.Builder, status, build) if !isLUCI || build.Builder == "" { logging.Infof(c, "This is not an ingestable build, ignoring") return nil } // TODO(iannucci,nodir): get the bot context too // TODO(iannucci,nodir): support manifests/got_revision bs, err := getSummary(c, event.Hostname, build.Project, build.ID) if err != nil { return err } if err := bs.AddManifestKeysFromBuildSets(c); err != nil { return err } return transient.Tag.Apply(datastore.RunInTransaction(c, func(c context.Context) error { curBS := &model.BuildSummary{BuildKey: bs.BuildKey} switch err := datastore.Get(c, curBS); err { case datastore.ErrNoSuchEntity: action = "Created" case nil: action = "Modified" default: return errors.Annotate(err, "reading current BuildSummary").Err() } if bs.Version <= curBS.Version { logging.Warningf(c, "current BuildSummary is newer: %d <= %d", bs.Version, curBS.Version) return nil } if err := datastore.Put(c, bs); err != nil { return err } return model.UpdateBuilderForBuild(c, bs) }, &datastore.TransactionOptions{XG: true})) }
[ "func", "pubSubHandlerImpl", "(", "c", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ")", "error", "{", "// This is the default action. The code below will modify the values of some", "// or all of these parameters.", "isLUCI", ",", "bucket", ",", "status", ",", "action", ":=", "false", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "\n\n", "defer", "func", "(", ")", "{", "// closure for late binding", "buildCounter", ".", "Add", "(", "c", ",", "1", ",", "bucket", ",", "isLUCI", ",", "status", ",", "action", ")", "\n", "}", "(", ")", "\n\n", "msg", ":=", "common", ".", "PubSubSubscription", "{", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "r", ".", "Body", ")", ".", "Decode", "(", "&", "msg", ")", ";", "err", "!=", "nil", "{", "// This might be a transient error, e.g. when the json format changes", "// and Milo isn't updated yet.", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Tag", "(", "transient", ".", "Tag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "msg", ".", "Message", ".", "Attributes", "[", "\"", "\"", "]", ".", "(", "string", ")", ";", "ok", "&&", "v", "!=", "\"", "\"", "{", "// TODO(nodir): switch to v2, crbug.com/826006", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "v", ")", "\n", "return", "nil", "\n", "}", "\n", "bData", ",", "err", ":=", "msg", ".", "GetData", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "event", ":=", "struct", "{", "Build", "bbv1", ".", "ApiCommonBuildMessage", "`json:\"build\"`", "\n", "Hostname", "string", "`json:\"hostname\"`", "\n", "}", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "bData", ",", "&", "event", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "build", ":=", "deprecated", ".", "Build", "{", "}", "\n", "if", "err", ":=", "build", ".", "ParseMessage", "(", "&", "event", ".", "Build", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "bucket", "=", "build", ".", "Bucket", "\n", "status", "=", "build", ".", "Status", ".", "String", "(", ")", "\n", "isLUCI", "=", "strings", ".", "HasPrefix", "(", "bucket", ",", "\"", "\"", ")", "\n\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\\n", "\"", ",", "event", ".", "Hostname", ",", "bucket", ",", "build", ".", "Builder", ",", "status", ",", "build", ")", "\n\n", "if", "!", "isLUCI", "||", "build", ".", "Builder", "==", "\"", "\"", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// TODO(iannucci,nodir): get the bot context too", "// TODO(iannucci,nodir): support manifests/got_revision", "bs", ",", "err", ":=", "getSummary", "(", "c", ",", "event", ".", "Hostname", ",", "build", ".", "Project", ",", "build", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "bs", ".", "AddManifestKeysFromBuildSets", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "transient", ".", "Tag", ".", "Apply", "(", "datastore", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "curBS", ":=", "&", "model", ".", "BuildSummary", "{", "BuildKey", ":", "bs", ".", "BuildKey", "}", "\n", "switch", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "curBS", ")", ";", "err", "{", "case", "datastore", ".", "ErrNoSuchEntity", ":", "action", "=", "\"", "\"", "\n", "case", "nil", ":", "action", "=", "\"", "\"", "\n", "default", ":", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "bs", ".", "Version", "<=", "curBS", ".", "Version", "{", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "bs", ".", "Version", ",", "curBS", ".", "Version", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "datastore", ".", "Put", "(", "c", ",", "bs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "model", ".", "UpdateBuilderForBuild", "(", "c", ",", "bs", ")", "\n", "}", ",", "&", "datastore", ".", "TransactionOptions", "{", "XG", ":", "true", "}", ")", ")", "\n", "}" ]
// pubSubHandlerImpl takes the http.Request, expects to find // a common.PubSubSubscription JSON object in the Body, containing a bbPSEvent, // and handles the contents with generateSummary.
[ "pubSubHandlerImpl", "takes", "the", "http", ".", "Request", "expects", "to", "find", "a", "common", ".", "PubSubSubscription", "JSON", "object", "in", "the", "Body", "containing", "a", "bbPSEvent", "and", "handles", "the", "contents", "with", "generateSummary", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/pubsub.go#L153-L237
7,047
luci/luci-go
milo/buildsource/buildbucket/pubsub.go
MakeBuildKey
func MakeBuildKey(c context.Context, host, buildAddress string) *datastore.Key { return datastore.MakeKey(c, "buildbucket.Build", fmt.Sprintf("%s:%s", host, buildAddress)) }
go
func MakeBuildKey(c context.Context, host, buildAddress string) *datastore.Key { return datastore.MakeKey(c, "buildbucket.Build", fmt.Sprintf("%s:%s", host, buildAddress)) }
[ "func", "MakeBuildKey", "(", "c", "context", ".", "Context", ",", "host", ",", "buildAddress", "string", ")", "*", "datastore", ".", "Key", "{", "return", "datastore", ".", "MakeKey", "(", "c", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "host", ",", "buildAddress", ")", ")", "\n", "}" ]
// MakeBuildKey returns a new datastore Key for a buildbucket.Build. // // There's currently no model associated with this key, but it's used as // a parent for a model.BuildSummary.
[ "MakeBuildKey", "returns", "a", "new", "datastore", "Key", "for", "a", "buildbucket", ".", "Build", ".", "There", "s", "currently", "no", "model", "associated", "with", "this", "key", "but", "it", "s", "used", "as", "a", "parent", "for", "a", "model", ".", "BuildSummary", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/pubsub.go#L243-L246
7,048
luci/luci-go
logdog/appengine/coordinator/context.go
WithConfigProvider
func WithConfigProvider(c context.Context, s ConfigProvider) context.Context { return context.WithValue(c, &configProviderKey, s) }
go
func WithConfigProvider(c context.Context, s ConfigProvider) context.Context { return context.WithValue(c, &configProviderKey, s) }
[ "func", "WithConfigProvider", "(", "c", "context", ".", "Context", ",", "s", "ConfigProvider", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "&", "configProviderKey", ",", "s", ")", "\n", "}" ]
// WithConfigProvider installs the supplied ConfigProvider instance into a // Context.
[ "WithConfigProvider", "installs", "the", "supplied", "ConfigProvider", "instance", "into", "a", "Context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/context.go#L66-L68
7,049
luci/luci-go
logdog/appengine/coordinator/context.go
Project
func Project(c context.Context) types.ProjectName { ns := info.GetNamespace(c) project := ProjectFromNamespace(ns) if project != "" { return project } panic(fmt.Errorf("current namespace %q does not begin with project namespace prefix (%q)", ns, ProjectNamespacePrefix)) }
go
func Project(c context.Context) types.ProjectName { ns := info.GetNamespace(c) project := ProjectFromNamespace(ns) if project != "" { return project } panic(fmt.Errorf("current namespace %q does not begin with project namespace prefix (%q)", ns, ProjectNamespacePrefix)) }
[ "func", "Project", "(", "c", "context", ".", "Context", ")", "types", ".", "ProjectName", "{", "ns", ":=", "info", ".", "GetNamespace", "(", "c", ")", "\n", "project", ":=", "ProjectFromNamespace", "(", "ns", ")", "\n", "if", "project", "!=", "\"", "\"", "{", "return", "project", "\n", "}", "\n", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ns", ",", "ProjectNamespacePrefix", ")", ")", "\n", "}" ]
// Project returns the current project installed in the supplied Context's // namespace. // // This function is called with the expectation that the Context is in a // namespace conforming to ProjectNamespace. If this is not the case, this // method will panic.
[ "Project", "returns", "the", "current", "project", "installed", "in", "the", "supplied", "Context", "s", "namespace", ".", "This", "function", "is", "called", "with", "the", "expectation", "that", "the", "Context", "is", "in", "a", "namespace", "conforming", "to", "ProjectNamespace", ".", "If", "this", "is", "not", "the", "case", "this", "method", "will", "panic", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/context.go#L237-L244
7,050
luci/luci-go
logdog/client/annotee/executor/executor.go
Run
func (e *Executor) Run(ctx context.Context, command []string) error { // Clear any previous state. e.executed = false e.returnCode = 0 e.step = nil if len(command) == 0 { return errors.New("no command") } ctx, cancelFunc := context.WithCancel(ctx) cmd := exec.CommandContext(ctx, command[0], command[1:]...) // STDOUT stdoutRC, err := cmd.StdoutPipe() if err != nil { return fmt.Errorf("failed to create STDOUT pipe: %s", err) } defer stdoutRC.Close() stdout := e.configStream(stdoutRC, annotee.STDOUT, e.TeeStdout, true) stderrRC, err := cmd.StderrPipe() if err != nil { return fmt.Errorf("failed to create STDERR pipe: %s", err) } defer stderrRC.Close() stderr := e.configStream(stderrRC, annotee.STDERR, e.TeeStderr, false) // Start our process. if err := cmd.Start(); err != nil { return fmt.Errorf("failed to start bootstrapped process: %s", err) } // Cleanup the process on exit, and record its status and return code. defer func() { if err := cmd.Wait(); err != nil { var ok bool if e.returnCode, ok = exitcode.Get(err); ok { e.executed = true } else { log.WithError(err).Errorf(ctx, "Failed to Wait() for bootstrapped process.") } } else { e.returnCode = 0 e.executed = true } }() // Probe our execution information. options := e.Options if options.Execution == nil { options.Execution = annotation.ProbeExecution(command, nil, "") } // Configure our Processor. streams := []*annotee.Stream{ stdout, stderr, } // Process the bootstrapped I/O. We explicitly defer a Finish here to ensure // that we clean up any internal streams if our Processor fails/panics. // // If we fail to process the I/O, terminate the bootstrapped process // immediately, since it may otherwise block forever on I/O. proc := annotee.New(ctx, options) defer proc.Finish() if err := proc.RunStreams(streams); err != nil { cancelFunc() return fmt.Errorf("failed to process bootstrapped I/O: %v", err) } // Finish and record our annotation steps on completion. if e.step, err = proto.Marshal(proc.Finish().RootStep().Proto()); err != nil { log.WithError(err).Errorf(ctx, "Failed to Marshal final Step protobuf on completion.") return err } return nil }
go
func (e *Executor) Run(ctx context.Context, command []string) error { // Clear any previous state. e.executed = false e.returnCode = 0 e.step = nil if len(command) == 0 { return errors.New("no command") } ctx, cancelFunc := context.WithCancel(ctx) cmd := exec.CommandContext(ctx, command[0], command[1:]...) // STDOUT stdoutRC, err := cmd.StdoutPipe() if err != nil { return fmt.Errorf("failed to create STDOUT pipe: %s", err) } defer stdoutRC.Close() stdout := e.configStream(stdoutRC, annotee.STDOUT, e.TeeStdout, true) stderrRC, err := cmd.StderrPipe() if err != nil { return fmt.Errorf("failed to create STDERR pipe: %s", err) } defer stderrRC.Close() stderr := e.configStream(stderrRC, annotee.STDERR, e.TeeStderr, false) // Start our process. if err := cmd.Start(); err != nil { return fmt.Errorf("failed to start bootstrapped process: %s", err) } // Cleanup the process on exit, and record its status and return code. defer func() { if err := cmd.Wait(); err != nil { var ok bool if e.returnCode, ok = exitcode.Get(err); ok { e.executed = true } else { log.WithError(err).Errorf(ctx, "Failed to Wait() for bootstrapped process.") } } else { e.returnCode = 0 e.executed = true } }() // Probe our execution information. options := e.Options if options.Execution == nil { options.Execution = annotation.ProbeExecution(command, nil, "") } // Configure our Processor. streams := []*annotee.Stream{ stdout, stderr, } // Process the bootstrapped I/O. We explicitly defer a Finish here to ensure // that we clean up any internal streams if our Processor fails/panics. // // If we fail to process the I/O, terminate the bootstrapped process // immediately, since it may otherwise block forever on I/O. proc := annotee.New(ctx, options) defer proc.Finish() if err := proc.RunStreams(streams); err != nil { cancelFunc() return fmt.Errorf("failed to process bootstrapped I/O: %v", err) } // Finish and record our annotation steps on completion. if e.step, err = proto.Marshal(proc.Finish().RootStep().Proto()); err != nil { log.WithError(err).Errorf(ctx, "Failed to Marshal final Step protobuf on completion.") return err } return nil }
[ "func", "(", "e", "*", "Executor", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "command", "[", "]", "string", ")", "error", "{", "// Clear any previous state.", "e", ".", "executed", "=", "false", "\n", "e", ".", "returnCode", "=", "0", "\n", "e", ".", "step", "=", "nil", "\n\n", "if", "len", "(", "command", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "ctx", ",", "cancelFunc", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "cmd", ":=", "exec", ".", "CommandContext", "(", "ctx", ",", "command", "[", "0", "]", ",", "command", "[", "1", ":", "]", "...", ")", "\n\n", "// STDOUT", "stdoutRC", ",", "err", ":=", "cmd", ".", "StdoutPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "stdoutRC", ".", "Close", "(", ")", "\n", "stdout", ":=", "e", ".", "configStream", "(", "stdoutRC", ",", "annotee", ".", "STDOUT", ",", "e", ".", "TeeStdout", ",", "true", ")", "\n\n", "stderrRC", ",", "err", ":=", "cmd", ".", "StderrPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "stderrRC", ".", "Close", "(", ")", "\n", "stderr", ":=", "e", ".", "configStream", "(", "stderrRC", ",", "annotee", ".", "STDERR", ",", "e", ".", "TeeStderr", ",", "false", ")", "\n\n", "// Start our process.", "if", "err", ":=", "cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Cleanup the process on exit, and record its status and return code.", "defer", "func", "(", ")", "{", "if", "err", ":=", "cmd", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "{", "var", "ok", "bool", "\n", "if", "e", ".", "returnCode", ",", "ok", "=", "exitcode", ".", "Get", "(", "err", ")", ";", "ok", "{", "e", ".", "executed", "=", "true", "\n", "}", "else", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "ctx", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "e", ".", "returnCode", "=", "0", "\n", "e", ".", "executed", "=", "true", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Probe our execution information.", "options", ":=", "e", ".", "Options", "\n", "if", "options", ".", "Execution", "==", "nil", "{", "options", ".", "Execution", "=", "annotation", ".", "ProbeExecution", "(", "command", ",", "nil", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Configure our Processor.", "streams", ":=", "[", "]", "*", "annotee", ".", "Stream", "{", "stdout", ",", "stderr", ",", "}", "\n\n", "// Process the bootstrapped I/O. We explicitly defer a Finish here to ensure", "// that we clean up any internal streams if our Processor fails/panics.", "//", "// If we fail to process the I/O, terminate the bootstrapped process", "// immediately, since it may otherwise block forever on I/O.", "proc", ":=", "annotee", ".", "New", "(", "ctx", ",", "options", ")", "\n", "defer", "proc", ".", "Finish", "(", ")", "\n\n", "if", "err", ":=", "proc", ".", "RunStreams", "(", "streams", ")", ";", "err", "!=", "nil", "{", "cancelFunc", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Finish and record our annotation steps on completion.", "if", "e", ".", "step", ",", "err", "=", "proto", ".", "Marshal", "(", "proc", ".", "Finish", "(", ")", ".", "RootStep", "(", ")", ".", "Proto", "(", ")", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "ctx", ",", "\"", "\"", ")", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Run executes the bootstrapped process, blocking until it completes.
[ "Run", "executes", "the", "bootstrapped", "process", "blocking", "until", "it", "completes", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/executor/executor.go#L57-L136
7,051
luci/luci-go
common/errors/wrap.go
Unwrap
func Unwrap(err error) error { for { wrap, ok := err.(Wrapped) if !ok { return err } inner := wrap.InnerError() if inner == nil { break } err = inner } return err }
go
func Unwrap(err error) error { for { wrap, ok := err.(Wrapped) if !ok { return err } inner := wrap.InnerError() if inner == nil { break } err = inner } return err }
[ "func", "Unwrap", "(", "err", "error", ")", "error", "{", "for", "{", "wrap", ",", "ok", ":=", "err", ".", "(", "Wrapped", ")", "\n", "if", "!", "ok", "{", "return", "err", "\n", "}", "\n\n", "inner", ":=", "wrap", ".", "InnerError", "(", ")", "\n", "if", "inner", "==", "nil", "{", "break", "\n", "}", "\n", "err", "=", "inner", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Unwrap unwraps a wrapped error recursively, returning its inner error. // // If the supplied error is not nil, Unwrap will never return nil. If a // wrapped error reports that its InnerError is nil, that error will be // returned.
[ "Unwrap", "unwraps", "a", "wrapped", "error", "recursively", "returning", "its", "inner", "error", ".", "If", "the", "supplied", "error", "is", "not", "nil", "Unwrap", "will", "never", "return", "nil", ".", "If", "a", "wrapped", "error", "reports", "that", "its", "InnerError", "is", "nil", "that", "error", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/wrap.go#L28-L42
7,052
luci/luci-go
machine-db/appengine/database/database.go
getDatabaseConnection
func getDatabaseConnection(c context.Context) (*sql.DB, error) { // Update the database pointer if the database settings have changed. This operation is costly, but should be rare. // Done here to ensure that a connection established with an outdated connection string is closed as soon as possible. settings, err := settings.Get(c) if err != nil { return nil, err } connectionString := fmt.Sprintf("%s:%s@cloudsql(%s)/%s", settings.Username, settings.Password, settings.Server, settings.Database) // If the connection string matches what we expect, the current pointer is correct so just return it. dbLock.RLock() if connectionString == dbConnectionString { defer dbLock.RUnlock() return db, nil } dbLock.RUnlock() // The connection string doesn't match so the db pointer needs to be created or updated. dbLock.Lock() defer dbLock.Unlock() // Releasing the read lock may have allowed another concurrent request to grab the write lock first so it's // possible we no longer need to do anything. Check again while holding the write lock. if connectionString == dbConnectionString { return db, nil } if db != nil { if err := db.Close(); err != nil { logging.Warningf(c, "Failed to close the previous database connection: %s", err.Error()) } } db, err = sql.Open("mysql", connectionString) if err != nil { return nil, fmt.Errorf("failed to open a new database connection: %s", err.Error()) } // AppEngine limit. db.SetMaxOpenConns(12) dbConnectionString = connectionString return db, nil }
go
func getDatabaseConnection(c context.Context) (*sql.DB, error) { // Update the database pointer if the database settings have changed. This operation is costly, but should be rare. // Done here to ensure that a connection established with an outdated connection string is closed as soon as possible. settings, err := settings.Get(c) if err != nil { return nil, err } connectionString := fmt.Sprintf("%s:%s@cloudsql(%s)/%s", settings.Username, settings.Password, settings.Server, settings.Database) // If the connection string matches what we expect, the current pointer is correct so just return it. dbLock.RLock() if connectionString == dbConnectionString { defer dbLock.RUnlock() return db, nil } dbLock.RUnlock() // The connection string doesn't match so the db pointer needs to be created or updated. dbLock.Lock() defer dbLock.Unlock() // Releasing the read lock may have allowed another concurrent request to grab the write lock first so it's // possible we no longer need to do anything. Check again while holding the write lock. if connectionString == dbConnectionString { return db, nil } if db != nil { if err := db.Close(); err != nil { logging.Warningf(c, "Failed to close the previous database connection: %s", err.Error()) } } db, err = sql.Open("mysql", connectionString) if err != nil { return nil, fmt.Errorf("failed to open a new database connection: %s", err.Error()) } // AppEngine limit. db.SetMaxOpenConns(12) dbConnectionString = connectionString return db, nil }
[ "func", "getDatabaseConnection", "(", "c", "context", ".", "Context", ")", "(", "*", "sql", ".", "DB", ",", "error", ")", "{", "// Update the database pointer if the database settings have changed. This operation is costly, but should be rare.", "// Done here to ensure that a connection established with an outdated connection string is closed as soon as possible.", "settings", ",", "err", ":=", "settings", ".", "Get", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "connectionString", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "settings", ".", "Username", ",", "settings", ".", "Password", ",", "settings", ".", "Server", ",", "settings", ".", "Database", ")", "\n\n", "// If the connection string matches what we expect, the current pointer is correct so just return it.", "dbLock", ".", "RLock", "(", ")", "\n", "if", "connectionString", "==", "dbConnectionString", "{", "defer", "dbLock", ".", "RUnlock", "(", ")", "\n", "return", "db", ",", "nil", "\n", "}", "\n", "dbLock", ".", "RUnlock", "(", ")", "\n\n", "// The connection string doesn't match so the db pointer needs to be created or updated.", "dbLock", ".", "Lock", "(", ")", "\n", "defer", "dbLock", ".", "Unlock", "(", ")", "\n\n", "// Releasing the read lock may have allowed another concurrent request to grab the write lock first so it's", "// possible we no longer need to do anything. Check again while holding the write lock.", "if", "connectionString", "==", "dbConnectionString", "{", "return", "db", ",", "nil", "\n", "}", "\n\n", "if", "db", "!=", "nil", "{", "if", "err", ":=", "db", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "db", ",", "err", "=", "sql", ".", "Open", "(", "\"", "\"", ",", "connectionString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "// AppEngine limit.", "db", ".", "SetMaxOpenConns", "(", "12", ")", "\n", "dbConnectionString", "=", "connectionString", "\n", "return", "db", ",", "nil", "\n", "}" ]
// getDatabaseConnection returns a pointer to the open database connection, creating it if necessary.
[ "getDatabaseConnection", "returns", "a", "pointer", "to", "the", "open", "database", "connection", "creating", "it", "if", "necessary", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/database/database.go#L51-L92
7,053
luci/luci-go
machine-db/appengine/database/database.go
Begin
func Begin(c context.Context) (*RollbackTx, error) { tx, err := Get(c).BeginTx(c, nil) return &RollbackTx{Tx: tx}, err }
go
func Begin(c context.Context) (*RollbackTx, error) { tx, err := Get(c).BeginTx(c, nil) return &RollbackTx{Tx: tx}, err }
[ "func", "Begin", "(", "c", "context", ".", "Context", ")", "(", "*", "RollbackTx", ",", "error", ")", "{", "tx", ",", "err", ":=", "Get", "(", "c", ")", ".", "BeginTx", "(", "c", ",", "nil", ")", "\n", "return", "&", "RollbackTx", "{", "Tx", ":", "tx", "}", ",", "err", "\n", "}" ]
// Begin begins a transaction using the database pointer embedded in the current context.
[ "Begin", "begins", "a", "transaction", "using", "the", "database", "pointer", "embedded", "in", "the", "current", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/database/database.go#L95-L98
7,054
luci/luci-go
machine-db/appengine/database/database.go
Get
func Get(c context.Context) *sql.DB { return c.Value(&dbKey).(*sql.DB) }
go
func Get(c context.Context) *sql.DB { return c.Value(&dbKey).(*sql.DB) }
[ "func", "Get", "(", "c", "context", ".", "Context", ")", "*", "sql", ".", "DB", "{", "return", "c", ".", "Value", "(", "&", "dbKey", ")", ".", "(", "*", "sql", ".", "DB", ")", "\n", "}" ]
// Get returns the database pointer embedded in the current context. // The database pointer can be embedded in the current context using With.
[ "Get", "returns", "the", "database", "pointer", "embedded", "in", "the", "current", "context", ".", "The", "database", "pointer", "can", "be", "embedded", "in", "the", "current", "context", "using", "With", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/database/database.go#L102-L104
7,055
luci/luci-go
machine-db/appengine/database/database.go
With
func With(c context.Context, database *sql.DB) context.Context { return context.WithValue(c, &dbKey, database) }
go
func With(c context.Context, database *sql.DB) context.Context { return context.WithValue(c, &dbKey, database) }
[ "func", "With", "(", "c", "context", ".", "Context", ",", "database", "*", "sql", ".", "DB", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "&", "dbKey", ",", "database", ")", "\n", "}" ]
// With installs a database pointer into the given context. // It can be retrieved later using Get.
[ "With", "installs", "a", "database", "pointer", "into", "the", "given", "context", ".", "It", "can", "be", "retrieved", "later", "using", "Get", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/database/database.go#L108-L110
7,056
luci/luci-go
machine-db/appengine/database/database.go
WithMiddleware
func WithMiddleware(c *router.Context, next router.Handler) { database, err := getDatabaseConnection(c.Context) if err != nil { logging.Errorf(c.Context, "Failed to retrieve a database connection: %s", err.Error()) c.Writer.Header().Set("Content-Type", "text/plain") c.Writer.WriteHeader(http.StatusInternalServerError) return } c.Context = With(c.Context, database) next(c) }
go
func WithMiddleware(c *router.Context, next router.Handler) { database, err := getDatabaseConnection(c.Context) if err != nil { logging.Errorf(c.Context, "Failed to retrieve a database connection: %s", err.Error()) c.Writer.Header().Set("Content-Type", "text/plain") c.Writer.WriteHeader(http.StatusInternalServerError) return } c.Context = With(c.Context, database) next(c) }
[ "func", "WithMiddleware", "(", "c", "*", "router", ".", "Context", ",", "next", "router", ".", "Handler", ")", "{", "database", ",", "err", ":=", "getDatabaseConnection", "(", "c", ".", "Context", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "c", ".", "Context", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "c", ".", "Writer", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Writer", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "c", ".", "Context", "=", "With", "(", "c", ".", "Context", ",", "database", ")", "\n", "next", "(", "c", ")", "\n", "}" ]
// WithMiddleware is middleware which installs a database pointer into the given context. // It can be retrieved later in the middleware chain using Get.
[ "WithMiddleware", "is", "middleware", "which", "installs", "a", "database", "pointer", "into", "the", "given", "context", ".", "It", "can", "be", "retrieved", "later", "in", "the", "middleware", "chain", "using", "Get", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/database/database.go#L114-L124
7,057
luci/luci-go
buildbucket/luciexe/main.go
RunnerMain
func RunnerMain(args []string) int { if err := mainErr(args); err != nil { fmt.Fprintln(os.Stderr, err) return 1 } return 0 }
go
func RunnerMain(args []string) int { if err := mainErr(args); err != nil { fmt.Fprintln(os.Stderr, err) return 1 } return 0 }
[ "func", "RunnerMain", "(", "args", "[", "]", "string", ")", "int", "{", "if", "err", ":=", "mainErr", "(", "args", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "return", "0", "\n", "}" ]
// RunnerMain runs LUCI runner, a program that runs a LUCI executable.
[ "RunnerMain", "runs", "LUCI", "runner", "a", "program", "that", "runs", "a", "LUCI", "executable", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/main.go#L77-L83
7,058
luci/luci-go
milo/buildsource/rawpresentation/build.go
Normalize
func (as *AnnotationStream) Normalize() error { if err := as.Project.Validate(); err != nil { return errors.Annotate(err, "Invalid project name: %s", as.Project).Tag(grpcutil.InvalidArgumentTag).Err() } if err := as.Path.Validate(); err != nil { return errors.Annotate(err, "Invalid log stream path %q", as.Path).Tag(grpcutil.InvalidArgumentTag).Err() } return nil }
go
func (as *AnnotationStream) Normalize() error { if err := as.Project.Validate(); err != nil { return errors.Annotate(err, "Invalid project name: %s", as.Project).Tag(grpcutil.InvalidArgumentTag).Err() } if err := as.Path.Validate(); err != nil { return errors.Annotate(err, "Invalid log stream path %q", as.Path).Tag(grpcutil.InvalidArgumentTag).Err() } return nil }
[ "func", "(", "as", "*", "AnnotationStream", ")", "Normalize", "(", ")", "error", "{", "if", "err", ":=", "as", ".", "Project", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "as", ".", "Project", ")", ".", "Tag", "(", "grpcutil", ".", "InvalidArgumentTag", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "err", ":=", "as", ".", "Path", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "as", ".", "Path", ")", ".", "Tag", "(", "grpcutil", ".", "InvalidArgumentTag", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Normalize validates and normalizes the stream's parameters.
[ "Normalize", "validates", "and", "normalizes", "the", "stream", "s", "parameters", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/rawpresentation/build.go#L62-L72
7,059
luci/luci-go
milo/buildsource/rawpresentation/build.go
Fetch
func (as *AnnotationStream) Fetch(c context.Context) (*miloProto.Step, error) { // Cached? if as.cs.Step != nil { return as.cs.Step, nil } // Load from LogDog directly. log.Fields{ "host": as.Client.Host, "project": as.Project, "path": as.Path, }.Infof(c, "Making tail request to LogDog to fetch annotation stream.") var ( state coordinator.LogStream stream = as.Client.Stream(as.Project, as.Path) ) le, err := stream.Tail(c, coordinator.WithState(&state), coordinator.Complete()) if err != nil { log.WithError(err).Errorf(c, "Failed to load stream.") return nil, err } // Make sure that this is an annotation stream. switch { case state.Desc.ContentType != miloProto.ContentTypeAnnotations: return nil, errNotMilo case state.Desc.StreamType != logpb.StreamType_DATAGRAM: return nil, errNotDatagram case le == nil: // No annotation stream data, so render a minimal page. return nil, errNoEntries } // Get the last log entry in the stream. In reality, this will be index 0, // since the "Tail" call should only return one log entry. // // Because we supplied the "Complete" flag to Tail and suceeded, this datagram // will be complete even if its source datagram(s) are fragments. dg := le.GetDatagram() if dg == nil { return nil, errors.New("Datagram stream does not have datagram data") } // Attempt to decode the Step protobuf. var step miloProto.Step if err := proto.Unmarshal(dg.Data, &step); err != nil { return nil, err } var latestEndedTime time.Time for _, sub := range step.Substep { switch t := sub.Substep.(type) { case *miloProto.Step_Substep_AnnotationStream: // TODO(hinoka,dnj): Implement recursive / embedded substream fetching if // specified. log.Warningf(c, "Annotation stream links LogDog substream [%+v], not supported!", t.AnnotationStream) case *miloProto.Step_Substep_Step: endedTime := google.TimeFromProto(t.Step.Ended) if t.Step.Ended != nil && endedTime.After(latestEndedTime) { latestEndedTime = endedTime } } } if latestEndedTime.IsZero() { // No substep had an ended time :( latestEndedTime = google.TimeFromProto(step.Started) } // Build our CachedStep. as.cs = internal.CachedStep{ Step: &step, Finished: (state.State.TerminalIndex >= 0 && le.StreamIndex == uint64(state.State.TerminalIndex)), } return as.cs.Step, nil }
go
func (as *AnnotationStream) Fetch(c context.Context) (*miloProto.Step, error) { // Cached? if as.cs.Step != nil { return as.cs.Step, nil } // Load from LogDog directly. log.Fields{ "host": as.Client.Host, "project": as.Project, "path": as.Path, }.Infof(c, "Making tail request to LogDog to fetch annotation stream.") var ( state coordinator.LogStream stream = as.Client.Stream(as.Project, as.Path) ) le, err := stream.Tail(c, coordinator.WithState(&state), coordinator.Complete()) if err != nil { log.WithError(err).Errorf(c, "Failed to load stream.") return nil, err } // Make sure that this is an annotation stream. switch { case state.Desc.ContentType != miloProto.ContentTypeAnnotations: return nil, errNotMilo case state.Desc.StreamType != logpb.StreamType_DATAGRAM: return nil, errNotDatagram case le == nil: // No annotation stream data, so render a minimal page. return nil, errNoEntries } // Get the last log entry in the stream. In reality, this will be index 0, // since the "Tail" call should only return one log entry. // // Because we supplied the "Complete" flag to Tail and suceeded, this datagram // will be complete even if its source datagram(s) are fragments. dg := le.GetDatagram() if dg == nil { return nil, errors.New("Datagram stream does not have datagram data") } // Attempt to decode the Step protobuf. var step miloProto.Step if err := proto.Unmarshal(dg.Data, &step); err != nil { return nil, err } var latestEndedTime time.Time for _, sub := range step.Substep { switch t := sub.Substep.(type) { case *miloProto.Step_Substep_AnnotationStream: // TODO(hinoka,dnj): Implement recursive / embedded substream fetching if // specified. log.Warningf(c, "Annotation stream links LogDog substream [%+v], not supported!", t.AnnotationStream) case *miloProto.Step_Substep_Step: endedTime := google.TimeFromProto(t.Step.Ended) if t.Step.Ended != nil && endedTime.After(latestEndedTime) { latestEndedTime = endedTime } } } if latestEndedTime.IsZero() { // No substep had an ended time :( latestEndedTime = google.TimeFromProto(step.Started) } // Build our CachedStep. as.cs = internal.CachedStep{ Step: &step, Finished: (state.State.TerminalIndex >= 0 && le.StreamIndex == uint64(state.State.TerminalIndex)), } return as.cs.Step, nil }
[ "func", "(", "as", "*", "AnnotationStream", ")", "Fetch", "(", "c", "context", ".", "Context", ")", "(", "*", "miloProto", ".", "Step", ",", "error", ")", "{", "// Cached?", "if", "as", ".", "cs", ".", "Step", "!=", "nil", "{", "return", "as", ".", "cs", ".", "Step", ",", "nil", "\n", "}", "\n\n", "// Load from LogDog directly.", "log", ".", "Fields", "{", "\"", "\"", ":", "as", ".", "Client", ".", "Host", ",", "\"", "\"", ":", "as", ".", "Project", ",", "\"", "\"", ":", "as", ".", "Path", ",", "}", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n\n", "var", "(", "state", "coordinator", ".", "LogStream", "\n", "stream", "=", "as", ".", "Client", ".", "Stream", "(", "as", ".", "Project", ",", "as", ".", "Path", ")", "\n", ")", "\n\n", "le", ",", "err", ":=", "stream", ".", "Tail", "(", "c", ",", "coordinator", ".", "WithState", "(", "&", "state", ")", ",", "coordinator", ".", "Complete", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Make sure that this is an annotation stream.", "switch", "{", "case", "state", ".", "Desc", ".", "ContentType", "!=", "miloProto", ".", "ContentTypeAnnotations", ":", "return", "nil", ",", "errNotMilo", "\n\n", "case", "state", ".", "Desc", ".", "StreamType", "!=", "logpb", ".", "StreamType_DATAGRAM", ":", "return", "nil", ",", "errNotDatagram", "\n\n", "case", "le", "==", "nil", ":", "// No annotation stream data, so render a minimal page.", "return", "nil", ",", "errNoEntries", "\n", "}", "\n\n", "// Get the last log entry in the stream. In reality, this will be index 0,", "// since the \"Tail\" call should only return one log entry.", "//", "// Because we supplied the \"Complete\" flag to Tail and suceeded, this datagram", "// will be complete even if its source datagram(s) are fragments.", "dg", ":=", "le", ".", "GetDatagram", "(", ")", "\n", "if", "dg", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Attempt to decode the Step protobuf.", "var", "step", "miloProto", ".", "Step", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "dg", ".", "Data", ",", "&", "step", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "latestEndedTime", "time", ".", "Time", "\n", "for", "_", ",", "sub", ":=", "range", "step", ".", "Substep", "{", "switch", "t", ":=", "sub", ".", "Substep", ".", "(", "type", ")", "{", "case", "*", "miloProto", ".", "Step_Substep_AnnotationStream", ":", "// TODO(hinoka,dnj): Implement recursive / embedded substream fetching if", "// specified.", "log", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "t", ".", "AnnotationStream", ")", "\n\n", "case", "*", "miloProto", ".", "Step_Substep_Step", ":", "endedTime", ":=", "google", ".", "TimeFromProto", "(", "t", ".", "Step", ".", "Ended", ")", "\n", "if", "t", ".", "Step", ".", "Ended", "!=", "nil", "&&", "endedTime", ".", "After", "(", "latestEndedTime", ")", "{", "latestEndedTime", "=", "endedTime", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "latestEndedTime", ".", "IsZero", "(", ")", "{", "// No substep had an ended time :(", "latestEndedTime", "=", "google", ".", "TimeFromProto", "(", "step", ".", "Started", ")", "\n", "}", "\n\n", "// Build our CachedStep.", "as", ".", "cs", "=", "internal", ".", "CachedStep", "{", "Step", ":", "&", "step", ",", "Finished", ":", "(", "state", ".", "State", ".", "TerminalIndex", ">=", "0", "&&", "le", ".", "StreamIndex", "==", "uint64", "(", "state", ".", "State", ".", "TerminalIndex", ")", ")", ",", "}", "\n", "return", "as", ".", "cs", ".", "Step", ",", "nil", "\n", "}" ]
// Fetch loads the annotation stream from LogDog. // // If the stream does not exist, or is invalid, Fetch will return a Milo error. // Otherwise, it will return the Step that was loaded. // // Fetch caches the step, so multiple calls to Fetch will return the same Step // value.
[ "Fetch", "loads", "the", "annotation", "stream", "from", "LogDog", ".", "If", "the", "stream", "does", "not", "exist", "or", "is", "invalid", "Fetch", "will", "return", "a", "Milo", "error", ".", "Otherwise", "it", "will", "return", "the", "Step", "that", "was", "loaded", ".", "Fetch", "caches", "the", "step", "so", "multiple", "calls", "to", "Fetch", "will", "return", "the", "same", "Step", "value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/rawpresentation/build.go#L85-L164
7,060
luci/luci-go
milo/buildsource/rawpresentation/build.go
NewURLBuilder
func NewURLBuilder(addr *types.StreamAddr) *ViewerURLBuilder { prefix, _ := addr.Path.Split() return &ViewerURLBuilder{ Host: addr.Host, Prefix: prefix, Project: addr.Project, } }
go
func NewURLBuilder(addr *types.StreamAddr) *ViewerURLBuilder { prefix, _ := addr.Path.Split() return &ViewerURLBuilder{ Host: addr.Host, Prefix: prefix, Project: addr.Project, } }
[ "func", "NewURLBuilder", "(", "addr", "*", "types", ".", "StreamAddr", ")", "*", "ViewerURLBuilder", "{", "prefix", ",", "_", ":=", "addr", ".", "Path", ".", "Split", "(", ")", "\n", "return", "&", "ViewerURLBuilder", "{", "Host", ":", "addr", ".", "Host", ",", "Prefix", ":", "prefix", ",", "Project", ":", "addr", ".", "Project", ",", "}", "\n", "}" ]
// NewURLBuilder creates a new URLBuilder that can generate links to LogDog // pages given a LogDog StreamAddr.
[ "NewURLBuilder", "creates", "a", "new", "URLBuilder", "that", "can", "generate", "links", "to", "LogDog", "pages", "given", "a", "LogDog", "StreamAddr", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/rawpresentation/build.go#L202-L209
7,061
luci/luci-go
milo/buildsource/rawpresentation/build.go
BuildLink
func (b *ViewerURLBuilder) BuildLink(l *miloProto.Link) *ui.Link { switch t := l.Value.(type) { case *miloProto.Link_LogdogStream: ls := t.LogdogStream server := ls.Server if server == "" { server = b.Host } prefix := types.StreamName(ls.Prefix) if prefix == "" { prefix = b.Prefix } u := viewer.GetURL(server, b.Project, prefix.Join(types.StreamName(ls.Name))) link := ui.NewLink(l.Label, u, fmt.Sprintf("logdog link for %s", l.Label)) if link.Label == "" { link.Label = ls.Name } return link case *miloProto.Link_Url: link := ui.NewLink(l.Label, t.Url, fmt.Sprintf("step link for %s", l.Label)) if link.Label == "" { link.Label = "unnamed" } return link default: // Don't know how to render. return nil } }
go
func (b *ViewerURLBuilder) BuildLink(l *miloProto.Link) *ui.Link { switch t := l.Value.(type) { case *miloProto.Link_LogdogStream: ls := t.LogdogStream server := ls.Server if server == "" { server = b.Host } prefix := types.StreamName(ls.Prefix) if prefix == "" { prefix = b.Prefix } u := viewer.GetURL(server, b.Project, prefix.Join(types.StreamName(ls.Name))) link := ui.NewLink(l.Label, u, fmt.Sprintf("logdog link for %s", l.Label)) if link.Label == "" { link.Label = ls.Name } return link case *miloProto.Link_Url: link := ui.NewLink(l.Label, t.Url, fmt.Sprintf("step link for %s", l.Label)) if link.Label == "" { link.Label = "unnamed" } return link default: // Don't know how to render. return nil } }
[ "func", "(", "b", "*", "ViewerURLBuilder", ")", "BuildLink", "(", "l", "*", "miloProto", ".", "Link", ")", "*", "ui", ".", "Link", "{", "switch", "t", ":=", "l", ".", "Value", ".", "(", "type", ")", "{", "case", "*", "miloProto", ".", "Link_LogdogStream", ":", "ls", ":=", "t", ".", "LogdogStream", "\n\n", "server", ":=", "ls", ".", "Server", "\n", "if", "server", "==", "\"", "\"", "{", "server", "=", "b", ".", "Host", "\n", "}", "\n\n", "prefix", ":=", "types", ".", "StreamName", "(", "ls", ".", "Prefix", ")", "\n", "if", "prefix", "==", "\"", "\"", "{", "prefix", "=", "b", ".", "Prefix", "\n", "}", "\n\n", "u", ":=", "viewer", ".", "GetURL", "(", "server", ",", "b", ".", "Project", ",", "prefix", ".", "Join", "(", "types", ".", "StreamName", "(", "ls", ".", "Name", ")", ")", ")", "\n", "link", ":=", "ui", ".", "NewLink", "(", "l", ".", "Label", ",", "u", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "l", ".", "Label", ")", ")", "\n", "if", "link", ".", "Label", "==", "\"", "\"", "{", "link", ".", "Label", "=", "ls", ".", "Name", "\n", "}", "\n", "return", "link", "\n\n", "case", "*", "miloProto", ".", "Link_Url", ":", "link", ":=", "ui", ".", "NewLink", "(", "l", ".", "Label", ",", "t", ".", "Url", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "l", ".", "Label", ")", ")", "\n", "if", "link", ".", "Label", "==", "\"", "\"", "{", "link", ".", "Label", "=", "\"", "\"", "\n", "}", "\n", "return", "link", "\n\n", "default", ":", "// Don't know how to render.", "return", "nil", "\n", "}", "\n", "}" ]
// BuildLink implements URLBuilder.
[ "BuildLink", "implements", "URLBuilder", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/rawpresentation/build.go#L212-L245
7,062
luci/luci-go
milo/buildsource/rawpresentation/build.go
GetBuild
func GetBuild(c context.Context, host string, project types.ProjectName, path types.StreamPath) (*ui.MiloBuildLegacy, error) { as := AnnotationStream{ Project: project, Path: path, } if err := as.Normalize(); err != nil { return nil, err } // Setup our LogDog client. var err error if as.Client, err = NewClient(c, host); err != nil { return nil, errors.Annotate(err, "generating LogDog Client").Err() } // Load the Milo annotation protobuf from the annotation stream. switch _, err := as.Fetch(c); errors.Unwrap(err) { case nil, errNoEntries: case coordinator.ErrNoSuchStream: return nil, grpcutil.NotFoundTag.Apply(err) case coordinator.ErrNoAccess: return nil, grpcutil.PermissionDeniedTag.Apply(err) case errNotMilo, errNotDatagram: // The user requested a LogDog url that isn't a Milo annotation. return nil, grpcutil.InvalidArgumentTag.Apply(err) default: return nil, errors.Annotate(err, "failed to load stream").Err() } return as.toMiloBuild(c), nil }
go
func GetBuild(c context.Context, host string, project types.ProjectName, path types.StreamPath) (*ui.MiloBuildLegacy, error) { as := AnnotationStream{ Project: project, Path: path, } if err := as.Normalize(); err != nil { return nil, err } // Setup our LogDog client. var err error if as.Client, err = NewClient(c, host); err != nil { return nil, errors.Annotate(err, "generating LogDog Client").Err() } // Load the Milo annotation protobuf from the annotation stream. switch _, err := as.Fetch(c); errors.Unwrap(err) { case nil, errNoEntries: case coordinator.ErrNoSuchStream: return nil, grpcutil.NotFoundTag.Apply(err) case coordinator.ErrNoAccess: return nil, grpcutil.PermissionDeniedTag.Apply(err) case errNotMilo, errNotDatagram: // The user requested a LogDog url that isn't a Milo annotation. return nil, grpcutil.InvalidArgumentTag.Apply(err) default: return nil, errors.Annotate(err, "failed to load stream").Err() } return as.toMiloBuild(c), nil }
[ "func", "GetBuild", "(", "c", "context", ".", "Context", ",", "host", "string", ",", "project", "types", ".", "ProjectName", ",", "path", "types", ".", "StreamPath", ")", "(", "*", "ui", ".", "MiloBuildLegacy", ",", "error", ")", "{", "as", ":=", "AnnotationStream", "{", "Project", ":", "project", ",", "Path", ":", "path", ",", "}", "\n", "if", "err", ":=", "as", ".", "Normalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Setup our LogDog client.", "var", "err", "error", "\n", "if", "as", ".", "Client", ",", "err", "=", "NewClient", "(", "c", ",", "host", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Load the Milo annotation protobuf from the annotation stream.", "switch", "_", ",", "err", ":=", "as", ".", "Fetch", "(", "c", ")", ";", "errors", ".", "Unwrap", "(", "err", ")", "{", "case", "nil", ",", "errNoEntries", ":", "case", "coordinator", ".", "ErrNoSuchStream", ":", "return", "nil", ",", "grpcutil", ".", "NotFoundTag", ".", "Apply", "(", "err", ")", "\n\n", "case", "coordinator", ".", "ErrNoAccess", ":", "return", "nil", ",", "grpcutil", ".", "PermissionDeniedTag", ".", "Apply", "(", "err", ")", "\n\n", "case", "errNotMilo", ",", "errNotDatagram", ":", "// The user requested a LogDog url that isn't a Milo annotation.", "return", "nil", ",", "grpcutil", ".", "InvalidArgumentTag", ".", "Apply", "(", "err", ")", "\n\n", "default", ":", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "return", "as", ".", "toMiloBuild", "(", "c", ")", ",", "nil", "\n", "}" ]
// GetBuild returns a build from a raw annotation stream.
[ "GetBuild", "returns", "a", "build", "from", "a", "raw", "annotation", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/rawpresentation/build.go#L248-L282
7,063
luci/luci-go
milo/buildsource/rawpresentation/build.go
ReadAnnotations
func ReadAnnotations(c context.Context, addr *types.StreamAddr) (*miloProto.Step, error) { log.Infof(c, "Loading build from LogDog stream at: %s", addr) client, err := NewClient(c, addr.Host) if err != nil { return nil, errors.Annotate(err, "failed to create LogDog client").Err() } as := AnnotationStream{ Client: client, Project: addr.Project, Path: addr.Path, } if err := as.Normalize(); err != nil { return nil, errors.Annotate(err, "failed to normalize annotation stream parameters").Err() } return as.Fetch(c) }
go
func ReadAnnotations(c context.Context, addr *types.StreamAddr) (*miloProto.Step, error) { log.Infof(c, "Loading build from LogDog stream at: %s", addr) client, err := NewClient(c, addr.Host) if err != nil { return nil, errors.Annotate(err, "failed to create LogDog client").Err() } as := AnnotationStream{ Client: client, Project: addr.Project, Path: addr.Path, } if err := as.Normalize(); err != nil { return nil, errors.Annotate(err, "failed to normalize annotation stream parameters").Err() } return as.Fetch(c) }
[ "func", "ReadAnnotations", "(", "c", "context", ".", "Context", ",", "addr", "*", "types", ".", "StreamAddr", ")", "(", "*", "miloProto", ".", "Step", ",", "error", ")", "{", "log", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "addr", ")", "\n\n", "client", ",", "err", ":=", "NewClient", "(", "c", ",", "addr", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "as", ":=", "AnnotationStream", "{", "Client", ":", "client", ",", "Project", ":", "addr", ".", "Project", ",", "Path", ":", "addr", ".", "Path", ",", "}", "\n", "if", "err", ":=", "as", ".", "Normalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "return", "as", ".", "Fetch", "(", "c", ")", "\n", "}" ]
// ReadAnnotations synchronously reads and decodes the latest Step information // from the provided StreamAddr.
[ "ReadAnnotations", "synchronously", "reads", "and", "decodes", "the", "latest", "Step", "information", "from", "the", "provided", "StreamAddr", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/rawpresentation/build.go#L286-L304
7,064
luci/luci-go
common/runtime/tracer/tracer.go
Stop
func Stop() { // Wait for on-going traces. globals.wg.Wait() globals.lockWriter.Lock() defer globals.lockWriter.Unlock() globals.lockContexts.Lock() defer globals.lockContexts.Unlock() if globals.out != nil { // TODO(maruel): Dump all the stack frames. _, _ = globals.out.Write(footerEvents) } globals.lockID.Lock() defer globals.lockID.Unlock() globals.out = nil globals.contexts = nil globals.nextPID = 0 globals.nextID = 0 // Lower back clock frequency once we're done. lowerClockFrequency() }
go
func Stop() { // Wait for on-going traces. globals.wg.Wait() globals.lockWriter.Lock() defer globals.lockWriter.Unlock() globals.lockContexts.Lock() defer globals.lockContexts.Unlock() if globals.out != nil { // TODO(maruel): Dump all the stack frames. _, _ = globals.out.Write(footerEvents) } globals.lockID.Lock() defer globals.lockID.Unlock() globals.out = nil globals.contexts = nil globals.nextPID = 0 globals.nextID = 0 // Lower back clock frequency once we're done. lowerClockFrequency() }
[ "func", "Stop", "(", ")", "{", "// Wait for on-going traces.", "globals", ".", "wg", ".", "Wait", "(", ")", "\n", "globals", ".", "lockWriter", ".", "Lock", "(", ")", "\n", "defer", "globals", ".", "lockWriter", ".", "Unlock", "(", ")", "\n", "globals", ".", "lockContexts", ".", "Lock", "(", ")", "\n", "defer", "globals", ".", "lockContexts", ".", "Unlock", "(", ")", "\n", "if", "globals", ".", "out", "!=", "nil", "{", "// TODO(maruel): Dump all the stack frames.", "_", ",", "_", "=", "globals", ".", "out", ".", "Write", "(", "footerEvents", ")", "\n", "}", "\n", "globals", ".", "lockID", ".", "Lock", "(", ")", "\n", "defer", "globals", ".", "lockID", ".", "Unlock", "(", ")", "\n", "globals", ".", "out", "=", "nil", "\n", "globals", ".", "contexts", "=", "nil", "\n", "globals", ".", "nextPID", "=", "0", "\n", "globals", ".", "nextID", "=", "0", "\n\n", "// Lower back clock frequency once we're done.", "lowerClockFrequency", "(", ")", "\n", "}" ]
// Stop stops the trace. // // It is important to call it so the trace file is properly formatted. Tracing // events after this call are ignored.
[ "Stop", "stops", "the", "trace", ".", "It", "is", "important", "to", "call", "it", "so", "the", "trace", "file", "is", "properly", "formatted", ".", "Tracing", "events", "after", "this", "call", "are", "ignored", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/tracer/tracer.go#L116-L136
7,065
luci/luci-go
common/runtime/tracer/tracer.go
Span
func Span(marker interface{}, name string, args Args) func(args Args) { c := getContext(marker) if c == nil { return dummy } tsStart := time.Since(consts.start) return func(argsEnd Args) { tsEnd := time.Since(consts.start) if tsEnd == tsStart { // Make sure a duration event lasts at least one nanosecond. // It is a problem on systems with very low resolution clock // like Windows where the clock is so coarse that a large // number of events would not show up on the UI. tsEnd++ } // Use a pair of eventBegin/eventEnd. // getID() is a locking call. id := getID() // Remove once https://github.com/google/trace-viewer/issues/963 is rolled // into Chrome stable. if args == nil { args = consts.fakeArgs } if argsEnd == nil { argsEnd = consts.fakeArgs } c.emit(&event{ Type: eventNestableBegin, Category: "ignored", Name: name, Args: args, Timestamp: fromDuration(tsStart), ID: id, }) c.emit(&event{ Type: eventNestableEnd, Category: "ignored", Name: name, Args: argsEnd, Timestamp: fromDuration(tsEnd), ID: id, }) } }
go
func Span(marker interface{}, name string, args Args) func(args Args) { c := getContext(marker) if c == nil { return dummy } tsStart := time.Since(consts.start) return func(argsEnd Args) { tsEnd := time.Since(consts.start) if tsEnd == tsStart { // Make sure a duration event lasts at least one nanosecond. // It is a problem on systems with very low resolution clock // like Windows where the clock is so coarse that a large // number of events would not show up on the UI. tsEnd++ } // Use a pair of eventBegin/eventEnd. // getID() is a locking call. id := getID() // Remove once https://github.com/google/trace-viewer/issues/963 is rolled // into Chrome stable. if args == nil { args = consts.fakeArgs } if argsEnd == nil { argsEnd = consts.fakeArgs } c.emit(&event{ Type: eventNestableBegin, Category: "ignored", Name: name, Args: args, Timestamp: fromDuration(tsStart), ID: id, }) c.emit(&event{ Type: eventNestableEnd, Category: "ignored", Name: name, Args: argsEnd, Timestamp: fromDuration(tsEnd), ID: id, }) } }
[ "func", "Span", "(", "marker", "interface", "{", "}", ",", "name", "string", ",", "args", "Args", ")", "func", "(", "args", "Args", ")", "{", "c", ":=", "getContext", "(", "marker", ")", "\n", "if", "c", "==", "nil", "{", "return", "dummy", "\n", "}", "\n", "tsStart", ":=", "time", ".", "Since", "(", "consts", ".", "start", ")", "\n", "return", "func", "(", "argsEnd", "Args", ")", "{", "tsEnd", ":=", "time", ".", "Since", "(", "consts", ".", "start", ")", "\n", "if", "tsEnd", "==", "tsStart", "{", "// Make sure a duration event lasts at least one nanosecond.", "// It is a problem on systems with very low resolution clock", "// like Windows where the clock is so coarse that a large", "// number of events would not show up on the UI.", "tsEnd", "++", "\n", "}", "\n", "// Use a pair of eventBegin/eventEnd.", "// getID() is a locking call.", "id", ":=", "getID", "(", ")", "\n", "// Remove once https://github.com/google/trace-viewer/issues/963 is rolled", "// into Chrome stable.", "if", "args", "==", "nil", "{", "args", "=", "consts", ".", "fakeArgs", "\n", "}", "\n", "if", "argsEnd", "==", "nil", "{", "argsEnd", "=", "consts", ".", "fakeArgs", "\n", "}", "\n", "c", ".", "emit", "(", "&", "event", "{", "Type", ":", "eventNestableBegin", ",", "Category", ":", "\"", "\"", ",", "Name", ":", "name", ",", "Args", ":", "args", ",", "Timestamp", ":", "fromDuration", "(", "tsStart", ")", ",", "ID", ":", "id", ",", "}", ")", "\n", "c", ".", "emit", "(", "&", "event", "{", "Type", ":", "eventNestableEnd", ",", "Category", ":", "\"", "\"", ",", "Name", ":", "name", ",", "Args", ":", "argsEnd", ",", "Timestamp", ":", "fromDuration", "(", "tsEnd", ")", ",", "ID", ":", "id", ",", "}", ")", "\n", "}", "\n", "}" ]
// Span defines an event with a duration. // // The caller MUST call the returned callback to 'close' the event. The // callback doesn't need to be called from the same goroutine as the initial // caller.
[ "Span", "defines", "an", "event", "with", "a", "duration", ".", "The", "caller", "MUST", "call", "the", "returned", "callback", "to", "close", "the", "event", ".", "The", "callback", "doesn", "t", "need", "to", "be", "called", "from", "the", "same", "goroutine", "as", "the", "initial", "caller", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/tracer/tracer.go#L143-L186
7,066
luci/luci-go
common/runtime/tracer/tracer.go
Instant
func Instant(marker interface{}, name string, s Scope, args Args) { if c := getContext(marker); c != nil { if args == nil { args = consts.fakeArgs } // getID() is a locking call. c.emit(&event{ Type: eventNestableInstant, Category: "ignored", Name: name, Scope: s, Args: args, ID: getID(), }) } }
go
func Instant(marker interface{}, name string, s Scope, args Args) { if c := getContext(marker); c != nil { if args == nil { args = consts.fakeArgs } // getID() is a locking call. c.emit(&event{ Type: eventNestableInstant, Category: "ignored", Name: name, Scope: s, Args: args, ID: getID(), }) } }
[ "func", "Instant", "(", "marker", "interface", "{", "}", ",", "name", "string", ",", "s", "Scope", ",", "args", "Args", ")", "{", "if", "c", ":=", "getContext", "(", "marker", ")", ";", "c", "!=", "nil", "{", "if", "args", "==", "nil", "{", "args", "=", "consts", ".", "fakeArgs", "\n", "}", "\n", "// getID() is a locking call.", "c", ".", "emit", "(", "&", "event", "{", "Type", ":", "eventNestableInstant", ",", "Category", ":", "\"", "\"", ",", "Name", ":", "name", ",", "Scope", ":", "s", ",", "Args", ":", "args", ",", "ID", ":", "getID", "(", ")", ",", "}", ")", "\n", "}", "\n", "}" ]
// Instant registers an intantaneous event that has no duration.
[ "Instant", "registers", "an", "intantaneous", "event", "that", "has", "no", "duration", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/tracer/tracer.go#L189-L204
7,067
luci/luci-go
common/runtime/tracer/tracer.go
CounterSet
func CounterSet(marker interface{}, name string, value float64) { if c := getContext(marker); c != nil { // Sets ID so operations can be ordered. c.lock.Lock() c.counters[name] = value c.lock.Unlock() c.emit(&event{ Type: eventCounter, Name: name, Args: Args{"value": value}, ID: getID(), }) } }
go
func CounterSet(marker interface{}, name string, value float64) { if c := getContext(marker); c != nil { // Sets ID so operations can be ordered. c.lock.Lock() c.counters[name] = value c.lock.Unlock() c.emit(&event{ Type: eventCounter, Name: name, Args: Args{"value": value}, ID: getID(), }) } }
[ "func", "CounterSet", "(", "marker", "interface", "{", "}", ",", "name", "string", ",", "value", "float64", ")", "{", "if", "c", ":=", "getContext", "(", "marker", ")", ";", "c", "!=", "nil", "{", "// Sets ID so operations can be ordered.", "c", ".", "lock", ".", "Lock", "(", ")", "\n", "c", ".", "counters", "[", "name", "]", "=", "value", "\n", "c", ".", "lock", ".", "Unlock", "(", ")", "\n", "c", ".", "emit", "(", "&", "event", "{", "Type", ":", "eventCounter", ",", "Name", ":", "name", ",", "Args", ":", "Args", "{", "\"", "\"", ":", "value", "}", ",", "ID", ":", "getID", "(", ")", ",", "}", ")", "\n", "}", "\n", "}" ]
// CounterSet registers a new value for a counter. // // The values will be grouped inside the PID and each name displayed as a // separate line.
[ "CounterSet", "registers", "a", "new", "value", "for", "a", "counter", ".", "The", "values", "will", "be", "grouped", "inside", "the", "PID", "and", "each", "name", "displayed", "as", "a", "separate", "line", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/tracer/tracer.go#L210-L223
7,068
luci/luci-go
common/runtime/tracer/tracer.go
NewPID
func NewPID(marker interface{}, pname string) { globals.lockContexts.Lock() defer globals.lockContexts.Unlock() if globals.contexts == nil { return } newPID := globals.nextPID globals.nextPID++ c := &context{pid: newPID, counters: map[string]float64{}} globals.contexts[marker] = c if pname != "" { c.metadata(processName, Args{"name": pname}) } }
go
func NewPID(marker interface{}, pname string) { globals.lockContexts.Lock() defer globals.lockContexts.Unlock() if globals.contexts == nil { return } newPID := globals.nextPID globals.nextPID++ c := &context{pid: newPID, counters: map[string]float64{}} globals.contexts[marker] = c if pname != "" { c.metadata(processName, Args{"name": pname}) } }
[ "func", "NewPID", "(", "marker", "interface", "{", "}", ",", "pname", "string", ")", "{", "globals", ".", "lockContexts", ".", "Lock", "(", ")", "\n", "defer", "globals", ".", "lockContexts", ".", "Unlock", "(", ")", "\n", "if", "globals", ".", "contexts", "==", "nil", "{", "return", "\n", "}", "\n", "newPID", ":=", "globals", ".", "nextPID", "\n", "globals", ".", "nextPID", "++", "\n", "c", ":=", "&", "context", "{", "pid", ":", "newPID", ",", "counters", ":", "map", "[", "string", "]", "float64", "{", "}", "}", "\n", "globals", ".", "contexts", "[", "marker", "]", "=", "c", "\n", "if", "pname", "!=", "\"", "\"", "{", "c", ".", "metadata", "(", "processName", ",", "Args", "{", "\"", "\"", ":", "pname", "}", ")", "\n", "}", "\n", "}" ]
// NewPID assigns a pseudo-process ID for this marker and TID 1. // // Optionally assigns name to the 'process'. The main use is to create a // logical group for events.
[ "NewPID", "assigns", "a", "pseudo", "-", "process", "ID", "for", "this", "marker", "and", "TID", "1", ".", "Optionally", "assigns", "name", "to", "the", "process", ".", "The", "main", "use", "is", "to", "create", "a", "logical", "group", "for", "events", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/tracer/tracer.go#L249-L262
7,069
luci/luci-go
common/runtime/tracer/tracer.go
Discard
func Discard(marker interface{}) { globals.lockContexts.Lock() defer globals.lockContexts.Unlock() delete(globals.contexts, marker) }
go
func Discard(marker interface{}) { globals.lockContexts.Lock() defer globals.lockContexts.Unlock() delete(globals.contexts, marker) }
[ "func", "Discard", "(", "marker", "interface", "{", "}", ")", "{", "globals", ".", "lockContexts", ".", "Lock", "(", ")", "\n", "defer", "globals", ".", "lockContexts", ".", "Unlock", "(", ")", "\n", "delete", "(", "globals", ".", "contexts", ",", "marker", ")", "\n", "}" ]
// Discard forgets a context association created with NewPID. // // If not called, contexts accumulates and form a memory leak.
[ "Discard", "forgets", "a", "context", "association", "created", "with", "NewPID", ".", "If", "not", "called", "contexts", "accumulates", "and", "form", "a", "memory", "leak", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/tracer/tracer.go#L267-L271
7,070
luci/luci-go
common/runtime/tracer/tracer.go
emit
func (c *context) emit(e *event) { if e.Timestamp == 0 { e.Timestamp = fromDuration(time.Since(consts.start)) } // sync.WaitGroup.Add() use atomic.AddUint64(). globals.wg.Add(1) go func() { defer globals.wg.Done() e.Pid = c.pid e.Tid = 1 // Locking is done in a goroutine to not create implicit synchronization // when tracing. globals.lockWriter.Lock() defer globals.lockWriter.Unlock() if globals.out != nil { if globals.first { globals.first = false } else { // Writing is done in a goroutine to reduce cost. if _, err := globals.out.Write([]byte(",")); err != nil { log.Printf("failed writing to trace: %s", err) go Stop() return } } if err := globals.encoder.Encode(e); err != nil { log.Printf("failed writing to trace: %s", err) go Stop() } } }() }
go
func (c *context) emit(e *event) { if e.Timestamp == 0 { e.Timestamp = fromDuration(time.Since(consts.start)) } // sync.WaitGroup.Add() use atomic.AddUint64(). globals.wg.Add(1) go func() { defer globals.wg.Done() e.Pid = c.pid e.Tid = 1 // Locking is done in a goroutine to not create implicit synchronization // when tracing. globals.lockWriter.Lock() defer globals.lockWriter.Unlock() if globals.out != nil { if globals.first { globals.first = false } else { // Writing is done in a goroutine to reduce cost. if _, err := globals.out.Write([]byte(",")); err != nil { log.Printf("failed writing to trace: %s", err) go Stop() return } } if err := globals.encoder.Encode(e); err != nil { log.Printf("failed writing to trace: %s", err) go Stop() } } }() }
[ "func", "(", "c", "*", "context", ")", "emit", "(", "e", "*", "event", ")", "{", "if", "e", ".", "Timestamp", "==", "0", "{", "e", ".", "Timestamp", "=", "fromDuration", "(", "time", ".", "Since", "(", "consts", ".", "start", ")", ")", "\n", "}", "\n", "// sync.WaitGroup.Add() use atomic.AddUint64().", "globals", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "globals", ".", "wg", ".", "Done", "(", ")", "\n", "e", ".", "Pid", "=", "c", ".", "pid", "\n", "e", ".", "Tid", "=", "1", "\n", "// Locking is done in a goroutine to not create implicit synchronization", "// when tracing.", "globals", ".", "lockWriter", ".", "Lock", "(", ")", "\n", "defer", "globals", ".", "lockWriter", ".", "Unlock", "(", ")", "\n", "if", "globals", ".", "out", "!=", "nil", "{", "if", "globals", ".", "first", "{", "globals", ".", "first", "=", "false", "\n", "}", "else", "{", "// Writing is done in a goroutine to reduce cost.", "if", "_", ",", "err", ":=", "globals", ".", "out", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "go", "Stop", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "globals", ".", "encoder", ".", "Encode", "(", "e", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "go", "Stop", "(", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// emit asynchronously emits a trace event.
[ "emit", "asynchronously", "emits", "a", "trace", "event", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/tracer/tracer.go#L456-L487
7,071
luci/luci-go
common/runtime/tracer/tracer.go
metadata
func (c *context) metadata(m metadataType, args Args) { c.emit(&event{Type: eventMetadata, Name: string(m), Args: args}) }
go
func (c *context) metadata(m metadataType, args Args) { c.emit(&event{Type: eventMetadata, Name: string(m), Args: args}) }
[ "func", "(", "c", "*", "context", ")", "metadata", "(", "m", "metadataType", ",", "args", "Args", ")", "{", "c", ".", "emit", "(", "&", "event", "{", "Type", ":", "eventMetadata", ",", "Name", ":", "string", "(", "m", ")", ",", "Args", ":", "args", "}", ")", "\n", "}" ]
// metadata registers metadata in the trace. For example putting a name on the // current pseudo process id or pseudo thread id.
[ "metadata", "registers", "metadata", "in", "the", "trace", ".", "For", "example", "putting", "a", "name", "on", "the", "current", "pseudo", "process", "id", "or", "pseudo", "thread", "id", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/tracer/tracer.go#L491-L493
7,072
luci/luci-go
vpython/python/find.go
Find
func Find(c context.Context, vers Version, lookPath LookPathFunc) (*Interpreter, error) { // pythonM.m, pythonM, python searches := make([]string, 0, 3) pv := vers pv.Patch = 0 if pv.Minor > 0 { searches = append(searches, pv.PythonBase()) pv.Minor = 0 } if pv.Major > 0 { searches = append(searches, pv.PythonBase()) pv.Major = 0 } searches = append(searches, pv.PythonBase()) lookErrs := errors.NewLazyMultiError(len(searches)) for i, s := range searches { interp, err := findInterpreter(c, s, vers, lookPath) if err == nil { // Resolve to absolute path. if err := filesystem.AbsPath(&interp.Python); err != nil { return nil, errors.Annotate(err, "could not get absolute path for: %q", interp.Python).Err() } return interp, nil } logging.WithError(err).Debugf(c, "Could not find Python for: %q.", s) lookErrs.Assign(i, err) } // No Python interpreter could be identified. return nil, errors.Annotate(lookErrs.Get(), "no Python found").Err() }
go
func Find(c context.Context, vers Version, lookPath LookPathFunc) (*Interpreter, error) { // pythonM.m, pythonM, python searches := make([]string, 0, 3) pv := vers pv.Patch = 0 if pv.Minor > 0 { searches = append(searches, pv.PythonBase()) pv.Minor = 0 } if pv.Major > 0 { searches = append(searches, pv.PythonBase()) pv.Major = 0 } searches = append(searches, pv.PythonBase()) lookErrs := errors.NewLazyMultiError(len(searches)) for i, s := range searches { interp, err := findInterpreter(c, s, vers, lookPath) if err == nil { // Resolve to absolute path. if err := filesystem.AbsPath(&interp.Python); err != nil { return nil, errors.Annotate(err, "could not get absolute path for: %q", interp.Python).Err() } return interp, nil } logging.WithError(err).Debugf(c, "Could not find Python for: %q.", s) lookErrs.Assign(i, err) } // No Python interpreter could be identified. return nil, errors.Annotate(lookErrs.Get(), "no Python found").Err() }
[ "func", "Find", "(", "c", "context", ".", "Context", ",", "vers", "Version", ",", "lookPath", "LookPathFunc", ")", "(", "*", "Interpreter", ",", "error", ")", "{", "// pythonM.m, pythonM, python", "searches", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "3", ")", "\n", "pv", ":=", "vers", "\n", "pv", ".", "Patch", "=", "0", "\n", "if", "pv", ".", "Minor", ">", "0", "{", "searches", "=", "append", "(", "searches", ",", "pv", ".", "PythonBase", "(", ")", ")", "\n", "pv", ".", "Minor", "=", "0", "\n", "}", "\n", "if", "pv", ".", "Major", ">", "0", "{", "searches", "=", "append", "(", "searches", ",", "pv", ".", "PythonBase", "(", ")", ")", "\n", "pv", ".", "Major", "=", "0", "\n", "}", "\n", "searches", "=", "append", "(", "searches", ",", "pv", ".", "PythonBase", "(", ")", ")", "\n\n", "lookErrs", ":=", "errors", ".", "NewLazyMultiError", "(", "len", "(", "searches", ")", ")", "\n", "for", "i", ",", "s", ":=", "range", "searches", "{", "interp", ",", "err", ":=", "findInterpreter", "(", "c", ",", "s", ",", "vers", ",", "lookPath", ")", "\n", "if", "err", "==", "nil", "{", "// Resolve to absolute path.", "if", "err", ":=", "filesystem", ".", "AbsPath", "(", "&", "interp", ".", "Python", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "interp", ".", "Python", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "return", "interp", ",", "nil", "\n", "}", "\n\n", "logging", ".", "WithError", "(", "err", ")", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "s", ")", "\n", "lookErrs", ".", "Assign", "(", "i", ",", "err", ")", "\n", "}", "\n\n", "// No Python interpreter could be identified.", "return", "nil", ",", "errors", ".", "Annotate", "(", "lookErrs", ".", "Get", "(", ")", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}" ]
// Find attempts to find a Python interpreter matching the supplied version // using PATH. // // In order to accommodate multiple configurations on operating systems, Find // will attempt to identify versions that appear on the path
[ "Find", "attempts", "to", "find", "a", "Python", "interpreter", "matching", "the", "supplied", "version", "using", "PATH", ".", "In", "order", "to", "accommodate", "multiple", "configurations", "on", "operating", "systems", "Find", "will", "attempt", "to", "identify", "versions", "that", "appear", "on", "the", "path" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/find.go#L61-L94
7,073
luci/luci-go
lucicfg/meta.go
Log
func (m *Meta) Log(ctx context.Context) { logging.Debugf(ctx, "Meta config:") logging.Debugf(ctx, " config_service_host = %q", m.ConfigServiceHost) logging.Debugf(ctx, " config_dir = %q", m.ConfigDir) logging.Debugf(ctx, " tracked_files = %v", m.TrackedFiles) logging.Debugf(ctx, " fail_on_warnings = %v", m.FailOnWarnings) }
go
func (m *Meta) Log(ctx context.Context) { logging.Debugf(ctx, "Meta config:") logging.Debugf(ctx, " config_service_host = %q", m.ConfigServiceHost) logging.Debugf(ctx, " config_dir = %q", m.ConfigDir) logging.Debugf(ctx, " tracked_files = %v", m.TrackedFiles) logging.Debugf(ctx, " fail_on_warnings = %v", m.FailOnWarnings) }
[ "func", "(", "m", "*", "Meta", ")", "Log", "(", "ctx", "context", ".", "Context", ")", "{", "logging", ".", "Debugf", "(", "ctx", ",", "\"", "\"", ")", "\n", "logging", ".", "Debugf", "(", "ctx", ",", "\"", "\"", ",", "m", ".", "ConfigServiceHost", ")", "\n", "logging", ".", "Debugf", "(", "ctx", ",", "\"", "\"", ",", "m", ".", "ConfigDir", ")", "\n", "logging", ".", "Debugf", "(", "ctx", ",", "\"", "\"", ",", "m", ".", "TrackedFiles", ")", "\n", "logging", ".", "Debugf", "(", "ctx", ",", "\"", "\"", ",", "m", ".", "FailOnWarnings", ")", "\n", "}" ]
// Log logs the values of the meta parameters to Debug logger.
[ "Log", "logs", "the", "values", "of", "the", "meta", "parameters", "to", "Debug", "logger", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/meta.go#L52-L58
7,074
luci/luci-go
lucicfg/meta.go
RebaseConfigDir
func (m *Meta) RebaseConfigDir(root string) { if m.ConfigDir != "" && m.ConfigDir != "-" { m.ConfigDir = filepath.Join(root, filepath.FromSlash(m.ConfigDir)) } }
go
func (m *Meta) RebaseConfigDir(root string) { if m.ConfigDir != "" && m.ConfigDir != "-" { m.ConfigDir = filepath.Join(root, filepath.FromSlash(m.ConfigDir)) } }
[ "func", "(", "m", "*", "Meta", ")", "RebaseConfigDir", "(", "root", "string", ")", "{", "if", "m", ".", "ConfigDir", "!=", "\"", "\"", "&&", "m", ".", "ConfigDir", "!=", "\"", "\"", "{", "m", ".", "ConfigDir", "=", "filepath", ".", "Join", "(", "root", ",", "filepath", ".", "FromSlash", "(", "m", ".", "ConfigDir", ")", ")", "\n", "}", "\n", "}" ]
// RebaseConfigDir changes ConfigDir, if it is set, to be absolute by appending // it to the given root. // // Doesn't touch "-", which indicates "stdout".
[ "RebaseConfigDir", "changes", "ConfigDir", "if", "it", "is", "set", "to", "be", "absolute", "by", "appending", "it", "to", "the", "given", "root", ".", "Doesn", "t", "touch", "-", "which", "indicates", "stdout", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/meta.go#L64-L68
7,075
luci/luci-go
lucicfg/meta.go
AddFlags
func (m *Meta) AddFlags(fs *flag.FlagSet) { m.fs = fs fs.StringVar(&m.ConfigServiceHost, "config-service-host", m.ConfigServiceHost, "Hostname of a LUCI config service to use for validation.") fs.StringVar(&m.ConfigDir, "config-dir", m.ConfigDir, `A directory to place generated configs into (relative to cwd if given as a flag otherwise relative to the main script). If '-', generated configs are just printed to stdout in a format useful for debugging.`) fs.Var(luciflag.CommaList(&m.TrackedFiles), "tracked-files", "Globs for files considered generated, see lucicfg.config(...) doc for more info.") fs.BoolVar(&m.FailOnWarnings, "fail-on-warnings", m.FailOnWarnings, "Treat validation warnings as errors.") }
go
func (m *Meta) AddFlags(fs *flag.FlagSet) { m.fs = fs fs.StringVar(&m.ConfigServiceHost, "config-service-host", m.ConfigServiceHost, "Hostname of a LUCI config service to use for validation.") fs.StringVar(&m.ConfigDir, "config-dir", m.ConfigDir, `A directory to place generated configs into (relative to cwd if given as a flag otherwise relative to the main script). If '-', generated configs are just printed to stdout in a format useful for debugging.`) fs.Var(luciflag.CommaList(&m.TrackedFiles), "tracked-files", "Globs for files considered generated, see lucicfg.config(...) doc for more info.") fs.BoolVar(&m.FailOnWarnings, "fail-on-warnings", m.FailOnWarnings, "Treat validation warnings as errors.") }
[ "func", "(", "m", "*", "Meta", ")", "AddFlags", "(", "fs", "*", "flag", ".", "FlagSet", ")", "{", "m", ".", "fs", "=", "fs", "\n", "fs", ".", "StringVar", "(", "&", "m", ".", "ConfigServiceHost", ",", "\"", "\"", ",", "m", ".", "ConfigServiceHost", ",", "\"", "\"", ")", "\n", "fs", ".", "StringVar", "(", "&", "m", ".", "ConfigDir", ",", "\"", "\"", ",", "m", ".", "ConfigDir", ",", "`A directory to place generated configs into (relative to cwd if given as a\nflag otherwise relative to the main script). If '-', generated configs are just\nprinted to stdout in a format useful for debugging.`", ")", "\n", "fs", ".", "Var", "(", "luciflag", ".", "CommaList", "(", "&", "m", ".", "TrackedFiles", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "fs", ".", "BoolVar", "(", "&", "m", ".", "FailOnWarnings", ",", "\"", "\"", ",", "m", ".", "FailOnWarnings", ",", "\"", "\"", ")", "\n", "}" ]
// AddFlags registers command line flags that correspond to Meta fields.
[ "AddFlags", "registers", "command", "line", "flags", "that", "correspond", "to", "Meta", "fields", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/meta.go#L71-L80
7,076
luci/luci-go
lucicfg/meta.go
detectTouchedFlags
func (m *Meta) detectTouchedFlags() { switch { case m.fs == nil: return // not using CLI flags at all case m.detectedTouchedFlags: return // already did this case !m.fs.Parsed(): panic("detectTouchedFlags should be called after flags are parsed") } m.detectedTouchedFlags = true fields := m.fieldsMap() m.fs.Visit(func(f *flag.Flag) { if ptr := fields[strings.Replace(f.Name, "-", "_", -1)]; ptr != nil { m.touch(ptr) } }) }
go
func (m *Meta) detectTouchedFlags() { switch { case m.fs == nil: return // not using CLI flags at all case m.detectedTouchedFlags: return // already did this case !m.fs.Parsed(): panic("detectTouchedFlags should be called after flags are parsed") } m.detectedTouchedFlags = true fields := m.fieldsMap() m.fs.Visit(func(f *flag.Flag) { if ptr := fields[strings.Replace(f.Name, "-", "_", -1)]; ptr != nil { m.touch(ptr) } }) }
[ "func", "(", "m", "*", "Meta", ")", "detectTouchedFlags", "(", ")", "{", "switch", "{", "case", "m", ".", "fs", "==", "nil", ":", "return", "// not using CLI flags at all", "\n", "case", "m", ".", "detectedTouchedFlags", ":", "return", "// already did this", "\n", "case", "!", "m", ".", "fs", ".", "Parsed", "(", ")", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "m", ".", "detectedTouchedFlags", "=", "true", "\n\n", "fields", ":=", "m", ".", "fieldsMap", "(", ")", "\n\n", "m", ".", "fs", ".", "Visit", "(", "func", "(", "f", "*", "flag", ".", "Flag", ")", "{", "if", "ptr", ":=", "fields", "[", "strings", ".", "Replace", "(", "f", ".", "Name", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "]", ";", "ptr", "!=", "nil", "{", "m", ".", "touch", "(", "ptr", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// detectTouchedFlags is called after flags are parsed to figure out what flags // were explicitly set and what were left at their defaults. // // It updates Meta with information about touched flags which is later used // by PopulateFromTouchedIn and WasTouched functions.
[ "detectTouchedFlags", "is", "called", "after", "flags", "are", "parsed", "to", "figure", "out", "what", "flags", "were", "explicitly", "set", "and", "what", "were", "left", "at", "their", "defaults", ".", "It", "updates", "Meta", "with", "information", "about", "touched", "flags", "which", "is", "later", "used", "by", "PopulateFromTouchedIn", "and", "WasTouched", "functions", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/meta.go#L87-L105
7,077
luci/luci-go
lucicfg/meta.go
PopulateFromTouchedIn
func (m *Meta) PopulateFromTouchedIn(t *Meta) { t.detectTouchedFlags() left := m.fieldsMap() right := t.fieldsMap() for k, l := range left { r := right[k] if _, yes := t.touched[r]; yes { // Do *l = *r. switch l.(type) { case *string: *(l.(*string)) = *(r.(*string)) case *bool: *(l.(*bool)) = *(r.(*bool)) case *[]string: *(l.(*[]string)) = append([]string(nil), *(r.(*[]string))...) default: panic("impossible") } } } }
go
func (m *Meta) PopulateFromTouchedIn(t *Meta) { t.detectTouchedFlags() left := m.fieldsMap() right := t.fieldsMap() for k, l := range left { r := right[k] if _, yes := t.touched[r]; yes { // Do *l = *r. switch l.(type) { case *string: *(l.(*string)) = *(r.(*string)) case *bool: *(l.(*bool)) = *(r.(*bool)) case *[]string: *(l.(*[]string)) = append([]string(nil), *(r.(*[]string))...) default: panic("impossible") } } } }
[ "func", "(", "m", "*", "Meta", ")", "PopulateFromTouchedIn", "(", "t", "*", "Meta", ")", "{", "t", ".", "detectTouchedFlags", "(", ")", "\n", "left", ":=", "m", ".", "fieldsMap", "(", ")", "\n", "right", ":=", "t", ".", "fieldsMap", "(", ")", "\n", "for", "k", ",", "l", ":=", "range", "left", "{", "r", ":=", "right", "[", "k", "]", "\n", "if", "_", ",", "yes", ":=", "t", ".", "touched", "[", "r", "]", ";", "yes", "{", "// Do *l = *r.", "switch", "l", ".", "(", "type", ")", "{", "case", "*", "string", ":", "*", "(", "l", ".", "(", "*", "string", ")", ")", "=", "*", "(", "r", ".", "(", "*", "string", ")", ")", "\n", "case", "*", "bool", ":", "*", "(", "l", ".", "(", "*", "bool", ")", ")", "=", "*", "(", "r", ".", "(", "*", "bool", ")", ")", "\n", "case", "*", "[", "]", "string", ":", "*", "(", "l", ".", "(", "*", "[", "]", "string", ")", ")", "=", "append", "(", "[", "]", "string", "(", "nil", ")", ",", "*", "(", "r", ".", "(", "*", "[", "]", "string", ")", ")", "...", ")", "\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// PopulateFromTouchedIn takes all touched values in `t` and copies them to // `m`, overriding what's in `m`.
[ "PopulateFromTouchedIn", "takes", "all", "touched", "values", "in", "t", "and", "copies", "them", "to", "m", "overriding", "what", "s", "in", "m", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/meta.go#L109-L129
7,078
luci/luci-go
lucicfg/meta.go
fieldsMap
func (m *Meta) fieldsMap() map[string]interface{} { return map[string]interface{}{ "config_service_host": &m.ConfigServiceHost, "config_dir": &m.ConfigDir, "tracked_files": &m.TrackedFiles, "fail_on_warnings": &m.FailOnWarnings, } }
go
func (m *Meta) fieldsMap() map[string]interface{} { return map[string]interface{}{ "config_service_host": &m.ConfigServiceHost, "config_dir": &m.ConfigDir, "tracked_files": &m.TrackedFiles, "fail_on_warnings": &m.FailOnWarnings, } }
[ "func", "(", "m", "*", "Meta", ")", "fieldsMap", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "return", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "&", "m", ".", "ConfigServiceHost", ",", "\"", "\"", ":", "&", "m", ".", "ConfigDir", ",", "\"", "\"", ":", "&", "m", ".", "TrackedFiles", ",", "\"", "\"", ":", "&", "m", ".", "FailOnWarnings", ",", "}", "\n", "}" ]
// fieldsMap returns a mapping from a snake_case name of a field to a pointer to // this field inside 'm'. // // This is used by both Starlark accessors and for processing CLI flags.
[ "fieldsMap", "returns", "a", "mapping", "from", "a", "snake_case", "name", "of", "a", "field", "to", "a", "pointer", "to", "this", "field", "inside", "m", ".", "This", "is", "used", "by", "both", "Starlark", "accessors", "and", "for", "processing", "CLI", "flags", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/meta.go#L159-L166
7,079
luci/luci-go
lucicfg/meta.go
setField
func (m *Meta) setField(k string, v starlark.Value) (err error) { ptr := m.fieldsMap()[k] if ptr == nil { return fmt.Errorf("set_meta: no such meta key %q", k) } // On success, mark the field as modified. defer func() { if err == nil { m.touch(ptr) } }() switch ptr := ptr.(type) { case *string: if str, ok := v.(starlark.String); ok { *ptr = str.GoString() return nil } return fmt.Errorf("set_meta: got %s, expecting string", v.Type()) case *bool: if b, ok := v.(starlark.Bool); ok { *ptr = bool(b) return nil } return fmt.Errorf("set_meta: got %s, expecting bool", v.Type()) case *[]string: if iterable, ok := v.(starlark.Iterable); ok { iter := iterable.Iterate() defer iter.Done() var vals []string for x := starlark.Value(nil); iter.Next(&x); { if str, ok := x.(starlark.String); ok { vals = append(vals, str.GoString()) } else { return fmt.Errorf("set_meta: got %s, expecting string", x.Type()) } } *ptr = vals return nil } return fmt.Errorf("set_meta: got %s, expecting an iterable", v.Type()) default: panic("impossible") } }
go
func (m *Meta) setField(k string, v starlark.Value) (err error) { ptr := m.fieldsMap()[k] if ptr == nil { return fmt.Errorf("set_meta: no such meta key %q", k) } // On success, mark the field as modified. defer func() { if err == nil { m.touch(ptr) } }() switch ptr := ptr.(type) { case *string: if str, ok := v.(starlark.String); ok { *ptr = str.GoString() return nil } return fmt.Errorf("set_meta: got %s, expecting string", v.Type()) case *bool: if b, ok := v.(starlark.Bool); ok { *ptr = bool(b) return nil } return fmt.Errorf("set_meta: got %s, expecting bool", v.Type()) case *[]string: if iterable, ok := v.(starlark.Iterable); ok { iter := iterable.Iterate() defer iter.Done() var vals []string for x := starlark.Value(nil); iter.Next(&x); { if str, ok := x.(starlark.String); ok { vals = append(vals, str.GoString()) } else { return fmt.Errorf("set_meta: got %s, expecting string", x.Type()) } } *ptr = vals return nil } return fmt.Errorf("set_meta: got %s, expecting an iterable", v.Type()) default: panic("impossible") } }
[ "func", "(", "m", "*", "Meta", ")", "setField", "(", "k", "string", ",", "v", "starlark", ".", "Value", ")", "(", "err", "error", ")", "{", "ptr", ":=", "m", ".", "fieldsMap", "(", ")", "[", "k", "]", "\n", "if", "ptr", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n\n", "// On success, mark the field as modified.", "defer", "func", "(", ")", "{", "if", "err", "==", "nil", "{", "m", ".", "touch", "(", "ptr", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "switch", "ptr", ":=", "ptr", ".", "(", "type", ")", "{", "case", "*", "string", ":", "if", "str", ",", "ok", ":=", "v", ".", "(", "starlark", ".", "String", ")", ";", "ok", "{", "*", "ptr", "=", "str", ".", "GoString", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ".", "Type", "(", ")", ")", "\n\n", "case", "*", "bool", ":", "if", "b", ",", "ok", ":=", "v", ".", "(", "starlark", ".", "Bool", ")", ";", "ok", "{", "*", "ptr", "=", "bool", "(", "b", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ".", "Type", "(", ")", ")", "\n\n", "case", "*", "[", "]", "string", ":", "if", "iterable", ",", "ok", ":=", "v", ".", "(", "starlark", ".", "Iterable", ")", ";", "ok", "{", "iter", ":=", "iterable", ".", "Iterate", "(", ")", "\n", "defer", "iter", ".", "Done", "(", ")", "\n\n", "var", "vals", "[", "]", "string", "\n", "for", "x", ":=", "starlark", ".", "Value", "(", "nil", ")", ";", "iter", ".", "Next", "(", "&", "x", ")", ";", "{", "if", "str", ",", "ok", ":=", "x", ".", "(", "starlark", ".", "String", ")", ";", "ok", "{", "vals", "=", "append", "(", "vals", ",", "str", ".", "GoString", "(", ")", ")", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "x", ".", "Type", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "*", "ptr", "=", "vals", "\n", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ".", "Type", "(", ")", ")", "\n\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// setField sets the field k to v.
[ "setField", "sets", "the", "field", "k", "to", "v", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/meta.go#L169-L219
7,080
luci/luci-go
dm/api/service/v1/graph_query_normalize.go
Normalize
func (g *GraphQuery) Normalize() error { if err := g.AttemptList.Normalize(); err != nil { return err } if len(g.AttemptRange) > 0 { lme := errors.NewLazyMultiError(len(g.AttemptRange)) for i, rng := range g.AttemptRange { lme.Assign(i, rng.Normalize()) } if err := lme.Get(); err != nil { return err } } if len(g.Search) > 0 { lme := errors.NewLazyMultiError(len(g.Search)) for i, s := range g.Search { lme.Assign(i, s.Normalize()) } if err := lme.Get(); err != nil { return err } } return nil }
go
func (g *GraphQuery) Normalize() error { if err := g.AttemptList.Normalize(); err != nil { return err } if len(g.AttemptRange) > 0 { lme := errors.NewLazyMultiError(len(g.AttemptRange)) for i, rng := range g.AttemptRange { lme.Assign(i, rng.Normalize()) } if err := lme.Get(); err != nil { return err } } if len(g.Search) > 0 { lme := errors.NewLazyMultiError(len(g.Search)) for i, s := range g.Search { lme.Assign(i, s.Normalize()) } if err := lme.Get(); err != nil { return err } } return nil }
[ "func", "(", "g", "*", "GraphQuery", ")", "Normalize", "(", ")", "error", "{", "if", "err", ":=", "g", ".", "AttemptList", ".", "Normalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "g", ".", "AttemptRange", ")", ">", "0", "{", "lme", ":=", "errors", ".", "NewLazyMultiError", "(", "len", "(", "g", ".", "AttemptRange", ")", ")", "\n", "for", "i", ",", "rng", ":=", "range", "g", ".", "AttemptRange", "{", "lme", ".", "Assign", "(", "i", ",", "rng", ".", "Normalize", "(", ")", ")", "\n", "}", "\n", "if", "err", ":=", "lme", ".", "Get", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "len", "(", "g", ".", "Search", ")", ">", "0", "{", "lme", ":=", "errors", ".", "NewLazyMultiError", "(", "len", "(", "g", ".", "Search", ")", ")", "\n", "for", "i", ",", "s", ":=", "range", "g", ".", "Search", "{", "lme", ".", "Assign", "(", "i", ",", "s", ".", "Normalize", "(", ")", ")", "\n", "}", "\n", "if", "err", ":=", "lme", ".", "Get", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize returns an error iff this GraphQuery is not valid.
[ "Normalize", "returns", "an", "error", "iff", "this", "GraphQuery", "is", "not", "valid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_query_normalize.go#L24-L47
7,081
luci/luci-go
dm/api/service/v1/graph_query_normalize.go
Normalize
func (al *GraphQuery_AttemptRange) Normalize() error { if al.Quest == "" { return fmt.Errorf("must specify quest") } if al.Low == 0 { return fmt.Errorf("must specify low") } if al.High <= al.Low { return fmt.Errorf("high must be > low") } return nil }
go
func (al *GraphQuery_AttemptRange) Normalize() error { if al.Quest == "" { return fmt.Errorf("must specify quest") } if al.Low == 0 { return fmt.Errorf("must specify low") } if al.High <= al.Low { return fmt.Errorf("high must be > low") } return nil }
[ "func", "(", "al", "*", "GraphQuery_AttemptRange", ")", "Normalize", "(", ")", "error", "{", "if", "al", ".", "Quest", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "al", ".", "Low", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "al", ".", "High", "<=", "al", ".", "Low", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize returns nil iff this AttemptRange is in a bad state.
[ "Normalize", "returns", "nil", "iff", "this", "AttemptRange", "is", "in", "a", "bad", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_query_normalize.go#L50-L61
7,082
luci/luci-go
dm/api/service/v1/graph_query_normalize.go
Normalize
func (s *GraphQuery_Search) Normalize() error { // for now, start and end MUST be timestamp values. switch s.Start.Value.(type) { case *PropertyValue_Time: default: return fmt.Errorf("invalid Start type: %T", s.Start.Value) } switch s.End.Value.(type) { case *PropertyValue_Time: default: return fmt.Errorf("invalid End type: %T", s.End.Value) } return nil }
go
func (s *GraphQuery_Search) Normalize() error { // for now, start and end MUST be timestamp values. switch s.Start.Value.(type) { case *PropertyValue_Time: default: return fmt.Errorf("invalid Start type: %T", s.Start.Value) } switch s.End.Value.(type) { case *PropertyValue_Time: default: return fmt.Errorf("invalid End type: %T", s.End.Value) } return nil }
[ "func", "(", "s", "*", "GraphQuery_Search", ")", "Normalize", "(", ")", "error", "{", "// for now, start and end MUST be timestamp values.", "switch", "s", ".", "Start", ".", "Value", ".", "(", "type", ")", "{", "case", "*", "PropertyValue_Time", ":", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "Start", ".", "Value", ")", "\n", "}", "\n", "switch", "s", ".", "End", ".", "Value", ".", "(", "type", ")", "{", "case", "*", "PropertyValue_Time", ":", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "End", ".", "Value", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize returns nil iff this Search is in a bad state.
[ "Normalize", "returns", "nil", "iff", "this", "Search", "is", "in", "a", "bad", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_query_normalize.go#L64-L77
7,083
luci/luci-go
dm/appengine/deps/service.go
tumbleNow
func tumbleNow(c context.Context, m tumble.Mutation) error { err := tumble.RunMutation(c, m) if grpc.Code(err) == codes.Unknown { logging.WithError(err).Errorf(c, "unknown error while applying mutation %v", m) err = grpcutil.Internal } logging.Fields{"root": m.Root(c)}.Infof(c, "tumbleNow success") return err }
go
func tumbleNow(c context.Context, m tumble.Mutation) error { err := tumble.RunMutation(c, m) if grpc.Code(err) == codes.Unknown { logging.WithError(err).Errorf(c, "unknown error while applying mutation %v", m) err = grpcutil.Internal } logging.Fields{"root": m.Root(c)}.Infof(c, "tumbleNow success") return err }
[ "func", "tumbleNow", "(", "c", "context", ".", "Context", ",", "m", "tumble", ".", "Mutation", ")", "error", "{", "err", ":=", "tumble", ".", "RunMutation", "(", "c", ",", "m", ")", "\n", "if", "grpc", ".", "Code", "(", "err", ")", "==", "codes", ".", "Unknown", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "m", ")", "\n", "err", "=", "grpcutil", ".", "Internal", "\n", "}", "\n", "logging", ".", "Fields", "{", "\"", "\"", ":", "m", ".", "Root", "(", "c", ")", "}", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "err", "\n", "}" ]
// tumbleNow will run the mutation immediately, converting any non grpc errors // to codes.Internal.
[ "tumbleNow", "will", "run", "the", "mutation", "immediately", "converting", "any", "non", "grpc", "errors", "to", "codes", ".", "Internal", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/deps/service.go#L102-L110
7,084
luci/luci-go
config/validation/validation.go
Errorf
func (v *Context) Errorf(format string, args ...interface{}) { v.Error(errors.Reason(format, args...).Err()) }
go
func (v *Context) Errorf(format string, args ...interface{}) { v.Error(errors.Reason(format, args...).Err()) }
[ "func", "(", "v", "*", "Context", ")", "Errorf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "v", ".", "Error", "(", "errors", ".", "Reason", "(", "format", ",", "args", "...", ")", ".", "Err", "(", ")", ")", "\n", "}" ]
// Errorf records the given format string and args as a validation error.
[ "Errorf", "records", "the", "given", "format", "string", "and", "args", "as", "a", "validation", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/validation.go#L87-L89
7,085
luci/luci-go
config/validation/validation.go
Error
func (v *Context) Error(err error) { ctx := "" if v.file != "" { ctx = fmt.Sprintf("in %q", v.file) } else { ctx = "in <unspecified file>" } if len(v.element) != 0 { ctx += " (" + strings.Join(v.element, " / ") + ")" } // Make the file and the logical path also usable through error inspection. err = errors.Annotate(err, "%s", ctx).Tag(fileTag.With(v.file), elementTag.With(v.element)).Err() v.errors = append(v.errors, err) }
go
func (v *Context) Error(err error) { ctx := "" if v.file != "" { ctx = fmt.Sprintf("in %q", v.file) } else { ctx = "in <unspecified file>" } if len(v.element) != 0 { ctx += " (" + strings.Join(v.element, " / ") + ")" } // Make the file and the logical path also usable through error inspection. err = errors.Annotate(err, "%s", ctx).Tag(fileTag.With(v.file), elementTag.With(v.element)).Err() v.errors = append(v.errors, err) }
[ "func", "(", "v", "*", "Context", ")", "Error", "(", "err", "error", ")", "{", "ctx", ":=", "\"", "\"", "\n", "if", "v", ".", "file", "!=", "\"", "\"", "{", "ctx", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "v", ".", "file", ")", "\n", "}", "else", "{", "ctx", "=", "\"", "\"", "\n", "}", "\n", "if", "len", "(", "v", ".", "element", ")", "!=", "0", "{", "ctx", "+=", "\"", "\"", "+", "strings", ".", "Join", "(", "v", ".", "element", ",", "\"", "\"", ")", "+", "\"", "\"", "\n", "}", "\n", "// Make the file and the logical path also usable through error inspection.", "err", "=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "ctx", ")", ".", "Tag", "(", "fileTag", ".", "With", "(", "v", ".", "file", ")", ",", "elementTag", ".", "With", "(", "v", ".", "element", ")", ")", ".", "Err", "(", ")", "\n", "v", ".", "errors", "=", "append", "(", "v", ".", "errors", ",", "err", ")", "\n", "}" ]
// Error records the given error as a validation error.
[ "Error", "records", "the", "given", "error", "as", "a", "validation", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/validation.go#L92-L105
7,086
luci/luci-go
config/validation/validation.go
Enter
func (v *Context) Enter(title string, args ...interface{}) { e := fmt.Sprintf(title, args...) v.element = append(v.element, e) }
go
func (v *Context) Enter(title string, args ...interface{}) { e := fmt.Sprintf(title, args...) v.element = append(v.element, e) }
[ "func", "(", "v", "*", "Context", ")", "Enter", "(", "title", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "e", ":=", "fmt", ".", "Sprintf", "(", "title", ",", "args", "...", ")", "\n", "v", ".", "element", "=", "append", "(", "v", ".", "element", ",", "e", ")", "\n", "}" ]
// Enter descends into a sub-element when validating a nested structure. // // Useful for defining context. A current path of elements shows up in // validation messages. // // The reverse is Exit.
[ "Enter", "descends", "into", "a", "sub", "-", "element", "when", "validating", "a", "nested", "structure", ".", "Useful", "for", "defining", "context", ".", "A", "current", "path", "of", "elements", "shows", "up", "in", "validation", "messages", ".", "The", "reverse", "is", "Exit", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/validation.go#L123-L126
7,087
luci/luci-go
config/validation/validation.go
Exit
func (v *Context) Exit() { if len(v.element) != 0 { v.element = v.element[:len(v.element)-1] } }
go
func (v *Context) Exit() { if len(v.element) != 0 { v.element = v.element[:len(v.element)-1] } }
[ "func", "(", "v", "*", "Context", ")", "Exit", "(", ")", "{", "if", "len", "(", "v", ".", "element", ")", "!=", "0", "{", "v", ".", "element", "=", "v", ".", "element", "[", ":", "len", "(", "v", ".", "element", ")", "-", "1", "]", "\n", "}", "\n", "}" ]
// Exit pops the current element we are visiting from the stack. // // This is the reverse of Enter. Each Enter must have corresponding Exit. Use // functions and defers to ensure this, if it's otherwise hard to track.
[ "Exit", "pops", "the", "current", "element", "we", "are", "visiting", "from", "the", "stack", ".", "This", "is", "the", "reverse", "of", "Enter", ".", "Each", "Enter", "must", "have", "corresponding", "Exit", ".", "Use", "functions", "and", "defers", "to", "ensure", "this", "if", "it", "s", "otherwise", "hard", "to", "track", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/validation.go#L132-L136
7,088
luci/luci-go
gce/api/config/v1/timeofday.go
toTime
func (t *TimeOfDay) toTime() (time.Time, error) { now := time.Time{} loc, err := time.LoadLocation(t.GetLocation()) if err != nil { return now, errors.Reason("invalid location").Err() } now = now.In(loc) // Decompose the time into a slice of [time, <hour>, <minute>]. m := regexp.MustCompile(timeRegex).FindStringSubmatch(t.GetTime()) if len(m) != 3 { return now, errors.Reason("time must match regex %q", timeRegex).Err() } hr, err := strconv.Atoi(m[1]) if err != nil || hr > 23 { return now, errors.Reason("time must not exceed 23:xx").Err() } min, err := strconv.Atoi(m[2]) if err != nil || min > 59 { return now, errors.Reason("time must not exceed xx:59").Err() } return time.Date(now.Year(), now.Month(), now.Day(), hr, min, 0, 0, loc), nil }
go
func (t *TimeOfDay) toTime() (time.Time, error) { now := time.Time{} loc, err := time.LoadLocation(t.GetLocation()) if err != nil { return now, errors.Reason("invalid location").Err() } now = now.In(loc) // Decompose the time into a slice of [time, <hour>, <minute>]. m := regexp.MustCompile(timeRegex).FindStringSubmatch(t.GetTime()) if len(m) != 3 { return now, errors.Reason("time must match regex %q", timeRegex).Err() } hr, err := strconv.Atoi(m[1]) if err != nil || hr > 23 { return now, errors.Reason("time must not exceed 23:xx").Err() } min, err := strconv.Atoi(m[2]) if err != nil || min > 59 { return now, errors.Reason("time must not exceed xx:59").Err() } return time.Date(now.Year(), now.Month(), now.Day(), hr, min, 0, 0, loc), nil }
[ "func", "(", "t", "*", "TimeOfDay", ")", "toTime", "(", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "now", ":=", "time", ".", "Time", "{", "}", "\n", "loc", ",", "err", ":=", "time", ".", "LoadLocation", "(", "t", ".", "GetLocation", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "now", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "now", "=", "now", ".", "In", "(", "loc", ")", "\n", "// Decompose the time into a slice of [time, <hour>, <minute>].", "m", ":=", "regexp", ".", "MustCompile", "(", "timeRegex", ")", ".", "FindStringSubmatch", "(", "t", ".", "GetTime", "(", ")", ")", "\n", "if", "len", "(", "m", ")", "!=", "3", "{", "return", "now", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "timeRegex", ")", ".", "Err", "(", ")", "\n", "}", "\n", "hr", ",", "err", ":=", "strconv", ".", "Atoi", "(", "m", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "||", "hr", ">", "23", "{", "return", "now", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "min", ",", "err", ":=", "strconv", ".", "Atoi", "(", "m", "[", "2", "]", ")", "\n", "if", "err", "!=", "nil", "||", "min", ">", "59", "{", "return", "now", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "time", ".", "Date", "(", "now", ".", "Year", "(", ")", ",", "now", ".", "Month", "(", ")", ",", "now", ".", "Day", "(", ")", ",", "hr", ",", "min", ",", "0", ",", "0", ",", "loc", ")", ",", "nil", "\n", "}" ]
// toTime returns the time.Time representation of the time referenced by this // time of day.
[ "toTime", "returns", "the", "time", ".", "Time", "representation", "of", "the", "time", "referenced", "by", "this", "time", "of", "day", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/timeofday.go#L33-L54
7,089
luci/luci-go
gce/api/config/v1/timeofday.go
Validate
func (t *TimeOfDay) Validate(c *validation.Context) { if t.GetDay() == dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED { c.Errorf("day must be specified") } _, err := t.toTime() if err != nil { c.Errorf("%s", err) } }
go
func (t *TimeOfDay) Validate(c *validation.Context) { if t.GetDay() == dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED { c.Errorf("day must be specified") } _, err := t.toTime() if err != nil { c.Errorf("%s", err) } }
[ "func", "(", "t", "*", "TimeOfDay", ")", "Validate", "(", "c", "*", "validation", ".", "Context", ")", "{", "if", "t", ".", "GetDay", "(", ")", "==", "dayofweek", ".", "DayOfWeek_DAY_OF_WEEK_UNSPECIFIED", "{", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "_", ",", "err", ":=", "t", ".", "toTime", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// Validate validates this time of day.
[ "Validate", "validates", "this", "time", "of", "day", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/timeofday.go#L57-L65
7,090
luci/luci-go
vpython/spec/load.go
Load
func Load(path string, spec *vpython.Spec) error { content, err := ioutil.ReadFile(path) if err != nil { return errors.Annotate(err, "failed to load file from: %s", path).Err() } return Parse(string(content), spec) }
go
func Load(path string, spec *vpython.Spec) error { content, err := ioutil.ReadFile(path) if err != nil { return errors.Annotate(err, "failed to load file from: %s", path).Err() } return Parse(string(content), spec) }
[ "func", "Load", "(", "path", "string", ",", "spec", "*", "vpython", ".", "Spec", ")", "error", "{", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "path", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "return", "Parse", "(", "string", "(", "content", ")", ",", "spec", ")", "\n", "}" ]
// Load loads an specification file text protobuf from the supplied path.
[ "Load", "loads", "an", "specification", "file", "text", "protobuf", "from", "the", "supplied", "path", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/spec/load.go#L56-L63
7,091
luci/luci-go
vpython/spec/load.go
Parse
func Parse(content string, spec *vpython.Spec) error { if err := cproto.UnmarshalTextML(content, spec); err != nil { return errors.Annotate(err, "failed to unmarshal vpython.Spec").Err() } return nil }
go
func Parse(content string, spec *vpython.Spec) error { if err := cproto.UnmarshalTextML(content, spec); err != nil { return errors.Annotate(err, "failed to unmarshal vpython.Spec").Err() } return nil }
[ "func", "Parse", "(", "content", "string", ",", "spec", "*", "vpython", ".", "Spec", ")", "error", "{", "if", "err", ":=", "cproto", ".", "UnmarshalTextML", "(", "content", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Parse loads a specification message from a content string.
[ "Parse", "loads", "a", "specification", "message", "from", "a", "content", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/spec/load.go#L66-L71
7,092
luci/luci-go
buildbucket/protoutil/common.go
IsEnded
func IsEnded(s pb.Status) bool { return s&pb.Status_ENDED_MASK == pb.Status_ENDED_MASK }
go
func IsEnded(s pb.Status) bool { return s&pb.Status_ENDED_MASK == pb.Status_ENDED_MASK }
[ "func", "IsEnded", "(", "s", "pb", ".", "Status", ")", "bool", "{", "return", "s", "&", "pb", ".", "Status_ENDED_MASK", "==", "pb", ".", "Status_ENDED_MASK", "\n", "}" ]
// IsEnded returns true if s is final.
[ "IsEnded", "returns", "true", "if", "s", "is", "final", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/common.go#L22-L24
7,093
luci/luci-go
auth/integration/internal/localsrv/localsrv.go
serve
func (s *Server) serve(cb ServeFunc) error { s.l.Lock() if s.listener == nil { s.l.Unlock() return errors.New("already closed") } listener := s.listener // accessed outside the lock ctx := s.ctx s.l.Unlock() err := cb(ctx, listener, &s.wg) // blocks until killServe() is called s.wg.Wait() // waits for all pending requests // If it was a planned shutdown with killServe(), ignore the error. It says // that the listening socket was closed. s.l.Lock() if s.listener == nil { err = nil } s.l.Unlock() if err != nil { return errors.Annotate(err, "error in the serving loop").Err() } return nil }
go
func (s *Server) serve(cb ServeFunc) error { s.l.Lock() if s.listener == nil { s.l.Unlock() return errors.New("already closed") } listener := s.listener // accessed outside the lock ctx := s.ctx s.l.Unlock() err := cb(ctx, listener, &s.wg) // blocks until killServe() is called s.wg.Wait() // waits for all pending requests // If it was a planned shutdown with killServe(), ignore the error. It says // that the listening socket was closed. s.l.Lock() if s.listener == nil { err = nil } s.l.Unlock() if err != nil { return errors.Annotate(err, "error in the serving loop").Err() } return nil }
[ "func", "(", "s", "*", "Server", ")", "serve", "(", "cb", "ServeFunc", ")", "error", "{", "s", ".", "l", ".", "Lock", "(", ")", "\n", "if", "s", ".", "listener", "==", "nil", "{", "s", ".", "l", ".", "Unlock", "(", ")", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "listener", ":=", "s", ".", "listener", "// accessed outside the lock", "\n", "ctx", ":=", "s", ".", "ctx", "\n", "s", ".", "l", ".", "Unlock", "(", ")", "\n\n", "err", ":=", "cb", "(", "ctx", ",", "listener", ",", "&", "s", ".", "wg", ")", "// blocks until killServe() is called", "\n", "s", ".", "wg", ".", "Wait", "(", ")", "// waits for all pending requests", "\n\n", "// If it was a planned shutdown with killServe(), ignore the error. It says", "// that the listening socket was closed.", "s", ".", "l", ".", "Lock", "(", ")", "\n", "if", "s", ".", "listener", "==", "nil", "{", "err", "=", "nil", "\n", "}", "\n", "s", ".", "l", ".", "Unlock", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// serve runs the serving loop. // // It unblocks once killServe is called and all pending requests are served. // // Returns nil if serving was stopped by killServe or non-nil if it failed for // some other reason.
[ "serve", "runs", "the", "serving", "loop", ".", "It", "unblocks", "once", "killServe", "is", "called", "and", "all", "pending", "requests", "are", "served", ".", "Returns", "nil", "if", "serving", "was", "stopped", "by", "killServe", "or", "non", "-", "nil", "if", "it", "failed", "for", "some", "other", "reason", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/integration/internal/localsrv/localsrv.go#L123-L148
7,094
luci/luci-go
appengine/tsmon/housekeeping.go
InstallHandlers
func InstallHandlers(r *router.Router, base router.MiddlewareChain) { r.GET( "/internal/cron/ts_mon/housekeeping", base.Extend(gaemiddleware.RequireCron), housekeepingHandler) }
go
func InstallHandlers(r *router.Router, base router.MiddlewareChain) { r.GET( "/internal/cron/ts_mon/housekeeping", base.Extend(gaemiddleware.RequireCron), housekeepingHandler) }
[ "func", "InstallHandlers", "(", "r", "*", "router", ".", "Router", ",", "base", "router", ".", "MiddlewareChain", ")", "{", "r", ".", "GET", "(", "\"", "\"", ",", "base", ".", "Extend", "(", "gaemiddleware", ".", "RequireCron", ")", ",", "housekeepingHandler", ")", "\n", "}" ]
// InstallHandlers installs HTTP handlers for tsmon routes.
[ "InstallHandlers", "installs", "HTTP", "handlers", "for", "tsmon", "routes", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/tsmon/housekeeping.go#L27-L32
7,095
luci/luci-go
appengine/tsmon/housekeeping.go
housekeepingHandler
func housekeepingHandler(c *router.Context) { tsmon.GetState(c.Context).RunGlobalCallbacks(c.Context) if err := AssignTaskNumbers(c.Context); err != nil { logging.WithError(err).Errorf(c.Context, "Task number assigner failed") c.Writer.WriteHeader(http.StatusInternalServerError) } }
go
func housekeepingHandler(c *router.Context) { tsmon.GetState(c.Context).RunGlobalCallbacks(c.Context) if err := AssignTaskNumbers(c.Context); err != nil { logging.WithError(err).Errorf(c.Context, "Task number assigner failed") c.Writer.WriteHeader(http.StatusInternalServerError) } }
[ "func", "housekeepingHandler", "(", "c", "*", "router", ".", "Context", ")", "{", "tsmon", ".", "GetState", "(", "c", ".", "Context", ")", ".", "RunGlobalCallbacks", "(", "c", ".", "Context", ")", "\n", "if", "err", ":=", "AssignTaskNumbers", "(", "c", ".", "Context", ")", ";", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ".", "Context", ",", "\"", "\"", ")", "\n", "c", ".", "Writer", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "}" ]
// housekeepingHandler performs task number assignments and runs global metric // callbacks. // // See DatastoreTaskNumAllocator and AssignTaskNumbers.
[ "housekeepingHandler", "performs", "task", "number", "assignments", "and", "runs", "global", "metric", "callbacks", ".", "See", "DatastoreTaskNumAllocator", "and", "AssignTaskNumbers", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/tsmon/housekeeping.go#L38-L44
7,096
luci/luci-go
mp/cmd/snapshot/create.go
validateFlags
func (cmd *createSnapshotCmd) validateFlags(c context.Context) (map[string]string, error) { if cmd.disk == "" { return nil, errors.New("-disk is required") } labels := make(map[string]string, len(cmd.labels)) for _, label := range cmd.labels { parts := strings.SplitN(label, ":", 2) if len(parts) != 2 { return nil, errors.New(fmt.Sprintf("-label %q must be in key:value form", label)) } if _, ok := labels[parts[0]]; ok { return nil, errors.New(fmt.Sprintf("-label %q has duplicate key", label)) } labels[parts[0]] = parts[1] } if cmd.name == "" { return nil, errors.New("-name is required") } if cmd.project == "" { return nil, errors.New("-project is required") } if cmd.zone == "" { return nil, errors.New("-zone is required") } return labels, nil }
go
func (cmd *createSnapshotCmd) validateFlags(c context.Context) (map[string]string, error) { if cmd.disk == "" { return nil, errors.New("-disk is required") } labels := make(map[string]string, len(cmd.labels)) for _, label := range cmd.labels { parts := strings.SplitN(label, ":", 2) if len(parts) != 2 { return nil, errors.New(fmt.Sprintf("-label %q must be in key:value form", label)) } if _, ok := labels[parts[0]]; ok { return nil, errors.New(fmt.Sprintf("-label %q has duplicate key", label)) } labels[parts[0]] = parts[1] } if cmd.name == "" { return nil, errors.New("-name is required") } if cmd.project == "" { return nil, errors.New("-project is required") } if cmd.zone == "" { return nil, errors.New("-zone is required") } return labels, nil }
[ "func", "(", "cmd", "*", "createSnapshotCmd", ")", "validateFlags", "(", "c", "context", ".", "Context", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "if", "cmd", ".", "disk", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "labels", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "cmd", ".", "labels", ")", ")", "\n", "for", "_", ",", "label", ":=", "range", "cmd", ".", "labels", "{", "parts", ":=", "strings", ".", "SplitN", "(", "label", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "parts", ")", "!=", "2", "{", "return", "nil", ",", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "label", ")", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "labels", "[", "parts", "[", "0", "]", "]", ";", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "label", ")", ")", "\n", "}", "\n", "labels", "[", "parts", "[", "0", "]", "]", "=", "parts", "[", "1", "]", "\n", "}", "\n", "if", "cmd", ".", "name", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cmd", ".", "project", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cmd", ".", "zone", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "labels", ",", "nil", "\n", "}" ]
// validateFlags validates parsed command line flags and returns a map of parsed labels.
[ "validateFlags", "validates", "parsed", "command", "line", "flags", "and", "returns", "a", "map", "of", "parsed", "labels", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/snapshot/create.go#L50-L75
7,097
luci/luci-go
mp/cmd/snapshot/create.go
Run
func (cmd *createSnapshotCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { c := cli.GetContext(app, cmd, env) labels, err := cmd.validateFlags(c) if err != nil { logging.Errorf(c, "%s", err.Error()) return 1 } srv := getService(c) logging.Infof(c, "Creating snapshot.") snapshot := &compute.Snapshot{ Labels: labels, Name: cmd.name, } op, err := compute.NewDisksService(srv).CreateSnapshot(cmd.project, cmd.zone, cmd.disk, snapshot).Context(c).Do() for { if err != nil { for _, err := range err.(*googleapi.Error).Errors { logging.Errorf(c, "%s", err.Message) } return 1 } if op.Status == "DONE" { break } logging.Infof(c, "Waiting for snapshot to be created...") time.Sleep(2 * time.Second) op, err = compute.NewZoneOperationsService(srv).Get(cmd.project, cmd.zone, op.Name).Context(c).Do() } if op.Error != nil { for _, err := range op.Error.Errors { logging.Errorf(c, "%s", err.Message) } return 1 } logging.Infof(c, "Created snapshot.") return 0 }
go
func (cmd *createSnapshotCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { c := cli.GetContext(app, cmd, env) labels, err := cmd.validateFlags(c) if err != nil { logging.Errorf(c, "%s", err.Error()) return 1 } srv := getService(c) logging.Infof(c, "Creating snapshot.") snapshot := &compute.Snapshot{ Labels: labels, Name: cmd.name, } op, err := compute.NewDisksService(srv).CreateSnapshot(cmd.project, cmd.zone, cmd.disk, snapshot).Context(c).Do() for { if err != nil { for _, err := range err.(*googleapi.Error).Errors { logging.Errorf(c, "%s", err.Message) } return 1 } if op.Status == "DONE" { break } logging.Infof(c, "Waiting for snapshot to be created...") time.Sleep(2 * time.Second) op, err = compute.NewZoneOperationsService(srv).Get(cmd.project, cmd.zone, op.Name).Context(c).Do() } if op.Error != nil { for _, err := range op.Error.Errors { logging.Errorf(c, "%s", err.Message) } return 1 } logging.Infof(c, "Created snapshot.") return 0 }
[ "func", "(", "cmd", "*", "createSnapshotCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "c", ":=", "cli", ".", "GetContext", "(", "app", ",", "cmd", ",", "env", ")", "\n", "labels", ",", "err", ":=", "cmd", ".", "validateFlags", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "1", "\n", "}", "\n\n", "srv", ":=", "getService", "(", "c", ")", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "snapshot", ":=", "&", "compute", ".", "Snapshot", "{", "Labels", ":", "labels", ",", "Name", ":", "cmd", ".", "name", ",", "}", "\n", "op", ",", "err", ":=", "compute", ".", "NewDisksService", "(", "srv", ")", ".", "CreateSnapshot", "(", "cmd", ".", "project", ",", "cmd", ".", "zone", ",", "cmd", ".", "disk", ",", "snapshot", ")", ".", "Context", "(", "c", ")", ".", "Do", "(", ")", "\n", "for", "{", "if", "err", "!=", "nil", "{", "for", "_", ",", "err", ":=", "range", "err", ".", "(", "*", "googleapi", ".", "Error", ")", ".", "Errors", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Message", ")", "\n", "}", "\n", "return", "1", "\n", "}", "\n", "if", "op", ".", "Status", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "time", ".", "Sleep", "(", "2", "*", "time", ".", "Second", ")", "\n", "op", ",", "err", "=", "compute", ".", "NewZoneOperationsService", "(", "srv", ")", ".", "Get", "(", "cmd", ".", "project", ",", "cmd", ".", "zone", ",", "op", ".", "Name", ")", ".", "Context", "(", "c", ")", ".", "Do", "(", ")", "\n", "}", "\n", "if", "op", ".", "Error", "!=", "nil", "{", "for", "_", ",", "err", ":=", "range", "op", ".", "Error", ".", "Errors", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Message", ")", "\n", "}", "\n", "return", "1", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "0", "\n", "}" ]
// Run runs the command to create a disk snapshot.
[ "Run", "runs", "the", "command", "to", "create", "a", "disk", "snapshot", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/snapshot/create.go#L78-L115
7,098
luci/luci-go
mp/cmd/snapshot/create.go
getCreateSnapshotCmd
func getCreateSnapshotCmd() *subcommands.Command { return &subcommands.Command{ UsageLine: "create -disk <disk> -name <name> -project <project> -zone <zone> [-label <key>:<value>]...", ShortDesc: "creates a snapshot", LongDesc: "Creates a disk snapshot.", CommandRun: func() subcommands.CommandRun { cmd := &createSnapshotCmd{} cmd.Initialize() cmd.Flags.StringVar(&cmd.disk, "disk", "", "Disk to create a snapshot of.") cmd.Flags.Var(flag.StringSlice(&cmd.labels), "label", "Label to attach to a snapshot.") cmd.Flags.StringVar(&cmd.name, "name", "", "Name to give the created snapshot.") cmd.Flags.StringVar(&cmd.project, "project", "", "Project where the disk exists, and to create the snapshot in.") cmd.Flags.StringVar(&cmd.zone, "zone", "", "Zone where the disk exists.") return cmd }, } }
go
func getCreateSnapshotCmd() *subcommands.Command { return &subcommands.Command{ UsageLine: "create -disk <disk> -name <name> -project <project> -zone <zone> [-label <key>:<value>]...", ShortDesc: "creates a snapshot", LongDesc: "Creates a disk snapshot.", CommandRun: func() subcommands.CommandRun { cmd := &createSnapshotCmd{} cmd.Initialize() cmd.Flags.StringVar(&cmd.disk, "disk", "", "Disk to create a snapshot of.") cmd.Flags.Var(flag.StringSlice(&cmd.labels), "label", "Label to attach to a snapshot.") cmd.Flags.StringVar(&cmd.name, "name", "", "Name to give the created snapshot.") cmd.Flags.StringVar(&cmd.project, "project", "", "Project where the disk exists, and to create the snapshot in.") cmd.Flags.StringVar(&cmd.zone, "zone", "", "Zone where the disk exists.") return cmd }, } }
[ "func", "getCreateSnapshotCmd", "(", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "cmd", ":=", "&", "createSnapshotCmd", "{", "}", "\n", "cmd", ".", "Initialize", "(", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "disk", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "labels", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "name", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "project", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "zone", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}", ",", "}", "\n", "}" ]
// getCreateSnapshotCmd returns a new command to create a snapshot.
[ "getCreateSnapshotCmd", "returns", "a", "new", "command", "to", "create", "a", "snapshot", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/snapshot/create.go#L118-L134
7,099
luci/luci-go
dm/appengine/mutate/finish_execution.go
shouldRetry
func shouldRetry(c context.Context, a *model.Attempt, stat dm.AbnormalFinish_Status) (retry bool, err error) { if !stat.CouldRetry() { return } q := model.QuestFromID(a.ID.Quest) if err = ds.Get(ds.WithoutTransaction(c), q); err != nil { return } var cur, max uint32 switch stat { case dm.AbnormalFinish_FAILED: cur, max = a.RetryState.Failed, q.Desc.Meta.Retry.Failed a.RetryState.Failed++ case dm.AbnormalFinish_CRASHED: cur, max = a.RetryState.Crashed, q.Desc.Meta.Retry.Crashed a.RetryState.Crashed++ case dm.AbnormalFinish_EXPIRED: cur, max = a.RetryState.Expired, q.Desc.Meta.Retry.Expired a.RetryState.Expired++ case dm.AbnormalFinish_TIMED_OUT: cur, max = a.RetryState.TimedOut, q.Desc.Meta.Retry.TimedOut a.RetryState.TimedOut++ default: panic(fmt.Errorf("do not know how to retry %q", stat)) } retry = cur < max return }
go
func shouldRetry(c context.Context, a *model.Attempt, stat dm.AbnormalFinish_Status) (retry bool, err error) { if !stat.CouldRetry() { return } q := model.QuestFromID(a.ID.Quest) if err = ds.Get(ds.WithoutTransaction(c), q); err != nil { return } var cur, max uint32 switch stat { case dm.AbnormalFinish_FAILED: cur, max = a.RetryState.Failed, q.Desc.Meta.Retry.Failed a.RetryState.Failed++ case dm.AbnormalFinish_CRASHED: cur, max = a.RetryState.Crashed, q.Desc.Meta.Retry.Crashed a.RetryState.Crashed++ case dm.AbnormalFinish_EXPIRED: cur, max = a.RetryState.Expired, q.Desc.Meta.Retry.Expired a.RetryState.Expired++ case dm.AbnormalFinish_TIMED_OUT: cur, max = a.RetryState.TimedOut, q.Desc.Meta.Retry.TimedOut a.RetryState.TimedOut++ default: panic(fmt.Errorf("do not know how to retry %q", stat)) } retry = cur < max return }
[ "func", "shouldRetry", "(", "c", "context", ".", "Context", ",", "a", "*", "model", ".", "Attempt", ",", "stat", "dm", ".", "AbnormalFinish_Status", ")", "(", "retry", "bool", ",", "err", "error", ")", "{", "if", "!", "stat", ".", "CouldRetry", "(", ")", "{", "return", "\n", "}", "\n", "q", ":=", "model", ".", "QuestFromID", "(", "a", ".", "ID", ".", "Quest", ")", "\n\n", "if", "err", "=", "ds", ".", "Get", "(", "ds", ".", "WithoutTransaction", "(", "c", ")", ",", "q", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "cur", ",", "max", "uint32", "\n", "switch", "stat", "{", "case", "dm", ".", "AbnormalFinish_FAILED", ":", "cur", ",", "max", "=", "a", ".", "RetryState", ".", "Failed", ",", "q", ".", "Desc", ".", "Meta", ".", "Retry", ".", "Failed", "\n", "a", ".", "RetryState", ".", "Failed", "++", "\n", "case", "dm", ".", "AbnormalFinish_CRASHED", ":", "cur", ",", "max", "=", "a", ".", "RetryState", ".", "Crashed", ",", "q", ".", "Desc", ".", "Meta", ".", "Retry", ".", "Crashed", "\n", "a", ".", "RetryState", ".", "Crashed", "++", "\n", "case", "dm", ".", "AbnormalFinish_EXPIRED", ":", "cur", ",", "max", "=", "a", ".", "RetryState", ".", "Expired", ",", "q", ".", "Desc", ".", "Meta", ".", "Retry", ".", "Expired", "\n", "a", ".", "RetryState", ".", "Expired", "++", "\n", "case", "dm", ".", "AbnormalFinish_TIMED_OUT", ":", "cur", ",", "max", "=", "a", ".", "RetryState", ".", "TimedOut", ",", "q", ".", "Desc", ".", "Meta", ".", "Retry", ".", "TimedOut", "\n", "a", ".", "RetryState", ".", "TimedOut", "++", "\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "stat", ")", ")", "\n", "}", "\n", "retry", "=", "cur", "<", "max", "\n", "return", "\n", "}" ]
// shouldRetry loads the quest for this attempt, to determine if the attempt can // be retried. As a side-effect, it increments the RetryState counter for the // indicated failure type. // // If stat is not a retryable AbnormalFinish_Status, this will panic.
[ "shouldRetry", "loads", "the", "quest", "for", "this", "attempt", "to", "determine", "if", "the", "attempt", "can", "be", "retried", ".", "As", "a", "side", "-", "effect", "it", "increments", "the", "RetryState", "counter", "for", "the", "indicated", "failure", "type", ".", "If", "stat", "is", "not", "a", "retryable", "AbnormalFinish_Status", "this", "will", "panic", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/mutate/finish_execution.go#L46-L74