id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
7,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....
// 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", "...
// 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 ...
// 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", "ove...
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", ".", "ProjectN...
// 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", ...
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"...
// 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", ...
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", ")...
// 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", "...
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", ")", "...
// 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", ",", "r...
// 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", ",", "r...
// 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", "(",...
// 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", ".", ...
// 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", ",...
// 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", "(...
// 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", ",", "\"",...
// 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", ":...
// 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...
// 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", ...
// 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", ...
// 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 resp...
// 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", "=",...
// 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", ...
// 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", "\"...
// 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", ...
// 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", ...
// 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"...
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", ...
// 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", ".", "Cou...
// 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", ...
// 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", "(", ...
// 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", ...
// 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", "....
// 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", ...
// 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...
// 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", ")...
// 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", "plac...
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", ")", ...
// 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", ")", ...
// 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", ")",...
// 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", ...
// 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...
// 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",...
// 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", ...
// 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", "!=", "...
// 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", ...
// 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", "(", "...
// 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", ",", "sta...
// 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", "(", "\"", ...
// 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", "....
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", "!=", "\"", "\"...
// 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", "...
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...
// 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", "(", ")", ...
// 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", ...
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 con...
// 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", ":...
// 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", "....
// 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", ...
// 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", ",", "\"", "\""...
// 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", ".",...
// 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", ...
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", ".", "Ho...
// 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_LogdogS...
// 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", ":=", "Anno...
// 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",...
// 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", ...
// 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", ...
// 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", "gor...
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...
// 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...
// 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", ".", "contex...
// 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", ",", "mar...
// 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", "}...
// 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...
// 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"...
// 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", "iden...
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...
// 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", "(", "...
// 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...
// 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", ...
// 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"...
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",...
// 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", ",", "\"", "\"...
// 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", ...
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", "{", "ret...
// 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", ".", "...
// 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"...
// 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",...
// 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", ...
// 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", "(", ")", ")", "...
// 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...
// 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", "(", ...
// 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", ...
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", ...
// 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",...
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", ...
// 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", "(", "\"", "\"", ")", ...
// 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", ...
// 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", ".", "Ann...
// 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", "error...
// 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...
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", ")", ",", "housekeepingHan...
// 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", ...
// 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", ",", "...
// 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", ",", "c...
// 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", ":...
// 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", "(", ...
// 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", "failur...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/mutate/finish_execution.go#L46-L74