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,700
luci/luci-go
cipd/appengine/impl/cas/signer.go
defaultSigner
func defaultSigner(c context.Context) (*signer, error) { s := auth.GetSigner(c) if s == nil { return nil, errors.Reason("a default signer is not available").Err() } info, err := s.ServiceInfo(c) if err != nil { return nil, errors.Annotate(err, "failed to grab the signer info").Err() } return &signer{ Email: info.ServiceAccountName, SignBytes: s.SignBytes, }, nil }
go
func defaultSigner(c context.Context) (*signer, error) { s := auth.GetSigner(c) if s == nil { return nil, errors.Reason("a default signer is not available").Err() } info, err := s.ServiceInfo(c) if err != nil { return nil, errors.Annotate(err, "failed to grab the signer info").Err() } return &signer{ Email: info.ServiceAccountName, SignBytes: s.SignBytes, }, nil }
[ "func", "defaultSigner", "(", "c", "context", ".", "Context", ")", "(", "*", "signer", ",", "error", ")", "{", "s", ":=", "auth", ".", "GetSigner", "(", "c", ")", "\n", "if", "s", "==", "nil", "{", "return", "nil", ",", "errors", ".", "Reason", "...
// defaultSigner uses the default app account for signing.
[ "defaultSigner", "uses", "the", "default", "app", "account", "for", "signing", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/signer.go#L36-L49
7,701
luci/luci-go
cipd/appengine/impl/cas/signer.go
iamSigner
func iamSigner(c context.Context, actAs string) (*signer, error) { t, err := auth.GetRPCTransport(c, auth.AsSelf, auth.WithScopes(iam.OAuthScope)) if err != nil { return nil, errors.Annotate(err, "failed to grab RPC transport").Err() } s := &iam.Signer{ Client: &iam.Client{Client: &http.Client{Transport: t}}, ServiceAccount: actAs, } return &signer{ Email: actAs, SignBytes: s.SignBytes, }, nil }
go
func iamSigner(c context.Context, actAs string) (*signer, error) { t, err := auth.GetRPCTransport(c, auth.AsSelf, auth.WithScopes(iam.OAuthScope)) if err != nil { return nil, errors.Annotate(err, "failed to grab RPC transport").Err() } s := &iam.Signer{ Client: &iam.Client{Client: &http.Client{Transport: t}}, ServiceAccount: actAs, } return &signer{ Email: actAs, SignBytes: s.SignBytes, }, nil }
[ "func", "iamSigner", "(", "c", "context", ".", "Context", ",", "actAs", "string", ")", "(", "*", "signer", ",", "error", ")", "{", "t", ",", "err", ":=", "auth", ".", "GetRPCTransport", "(", "c", ",", "auth", ".", "AsSelf", ",", "auth", ".", "WithS...
// iamSigner uses SignBytes IAM API for signing.
[ "iamSigner", "uses", "SignBytes", "IAM", "API", "for", "signing", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/signer.go#L52-L65
7,702
luci/luci-go
dm/api/service/v1/attempt_list.go
Normalize
func (a *AttemptList) Normalize() error { for q, vals := range a.GetTo() { if vals == nil { a.To[q] = &AttemptList_Nums{} } else { if err := vals.Normalize(); err != nil { return err } } } return nil }
go
func (a *AttemptList) Normalize() error { for q, vals := range a.GetTo() { if vals == nil { a.To[q] = &AttemptList_Nums{} } else { if err := vals.Normalize(); err != nil { return err } } } return nil }
[ "func", "(", "a", "*", "AttemptList", ")", "Normalize", "(", ")", "error", "{", "for", "q", ",", "vals", ":=", "range", "a", ".", "GetTo", "(", ")", "{", "if", "vals", "==", "nil", "{", "a", ".", "To", "[", "q", "]", "=", "&", "AttemptList_Nums...
// Normalize sorts and uniq's attempt nums
[ "Normalize", "sorts", "and", "uniq", "s", "attempt", "nums" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_list.go#L25-L36
7,703
luci/luci-go
dm/api/service/v1/attempt_list.go
AddAIDs
func (a *AttemptList) AddAIDs(aids ...*Attempt_ID) { for _, aid := range aids { if a.To == nil { a.To = map[string]*AttemptList_Nums{} } atmptNums := a.To[aid.Quest] if atmptNums == nil { atmptNums = &AttemptList_Nums{} a.To[aid.Quest] = atmptNums } atmptNums.Nums = append(atmptNums.Nums, aid.Id) } }
go
func (a *AttemptList) AddAIDs(aids ...*Attempt_ID) { for _, aid := range aids { if a.To == nil { a.To = map[string]*AttemptList_Nums{} } atmptNums := a.To[aid.Quest] if atmptNums == nil { atmptNums = &AttemptList_Nums{} a.To[aid.Quest] = atmptNums } atmptNums.Nums = append(atmptNums.Nums, aid.Id) } }
[ "func", "(", "a", "*", "AttemptList", ")", "AddAIDs", "(", "aids", "...", "*", "Attempt_ID", ")", "{", "for", "_", ",", "aid", ":=", "range", "aids", "{", "if", "a", ".", "To", "==", "nil", "{", "a", ".", "To", "=", "map", "[", "string", "]", ...
// AddAIDs adds the given Attempt_ID to the AttemptList
[ "AddAIDs", "adds", "the", "given", "Attempt_ID", "to", "the", "AttemptList" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_list.go#L81-L93
7,704
luci/luci-go
dm/api/service/v1/attempt_list.go
Dup
func (a *AttemptList) Dup() *AttemptList { ret := &AttemptList{} for k, v := range a.To { if ret.To == nil { ret.To = make(map[string]*AttemptList_Nums, len(a.To)) } vals := &AttemptList_Nums{Nums: make([]uint32, len(v.Nums))} copy(vals.Nums, v.Nums) ret.To[k] = vals } return ret }
go
func (a *AttemptList) Dup() *AttemptList { ret := &AttemptList{} for k, v := range a.To { if ret.To == nil { ret.To = make(map[string]*AttemptList_Nums, len(a.To)) } vals := &AttemptList_Nums{Nums: make([]uint32, len(v.Nums))} copy(vals.Nums, v.Nums) ret.To[k] = vals } return ret }
[ "func", "(", "a", "*", "AttemptList", ")", "Dup", "(", ")", "*", "AttemptList", "{", "ret", ":=", "&", "AttemptList", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "a", ".", "To", "{", "if", "ret", ".", "To", "==", "nil", "{", "ret", "...
// Dup does a deep copy of this AttemptList.
[ "Dup", "does", "a", "deep", "copy", "of", "this", "AttemptList", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_list.go#L96-L107
7,705
luci/luci-go
dm/api/service/v1/attempt_list.go
UpdateWith
func (a *AttemptList) UpdateWith(o *AttemptList) { for qid, atmpts := range o.To { if curAtmpts, ok := a.To[qid]; !ok { a.To[qid] = atmpts } else { curAtmpts.Nums = append(curAtmpts.Nums, atmpts.Nums...) curAtmpts.Normalize() } } }
go
func (a *AttemptList) UpdateWith(o *AttemptList) { for qid, atmpts := range o.To { if curAtmpts, ok := a.To[qid]; !ok { a.To[qid] = atmpts } else { curAtmpts.Nums = append(curAtmpts.Nums, atmpts.Nums...) curAtmpts.Normalize() } } }
[ "func", "(", "a", "*", "AttemptList", ")", "UpdateWith", "(", "o", "*", "AttemptList", ")", "{", "for", "qid", ",", "atmpts", ":=", "range", "o", ".", "To", "{", "if", "curAtmpts", ",", "ok", ":=", "a", ".", "To", "[", "qid", "]", ";", "!", "ok...
// UpdateWith updates this AttemptList with all the entries in the other // AttemptList.
[ "UpdateWith", "updates", "this", "AttemptList", "with", "all", "the", "entries", "in", "the", "other", "AttemptList", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/attempt_list.go#L111-L120
7,706
luci/luci-go
cipd/client/cipd/builder/pkgdef.go
VersionFile
func (def *PackageDef) VersionFile() string { // It is already validated by LoadPackageDef, so just return it. for _, chunk := range def.Data { if chunk.VersionFile != "" { return chunk.VersionFile } } return "" }
go
func (def *PackageDef) VersionFile() string { // It is already validated by LoadPackageDef, so just return it. for _, chunk := range def.Data { if chunk.VersionFile != "" { return chunk.VersionFile } } return "" }
[ "func", "(", "def", "*", "PackageDef", ")", "VersionFile", "(", ")", "string", "{", "// It is already validated by LoadPackageDef, so just return it.", "for", "_", ",", "chunk", ":=", "range", "def", ".", "Data", "{", "if", "chunk", ".", "VersionFile", "!=", "\"...
// VersionFile defines where to drop JSON file with package version.
[ "VersionFile", "defines", "where", "to", "drop", "JSON", "file", "with", "package", "version", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/builder/pkgdef.go#L236-L244
7,707
luci/luci-go
cipd/client/cipd/builder/pkgdef.go
makeExclusionFilter
func makeExclusionFilter(startDir string, patterns []string) (fs.ScanFilter, error) { if len(patterns) == 0 { return nil, nil } // Compile regular expressions. exps := []*regexp.Regexp{} for _, expr := range patterns { if expr == "" { continue } if expr[0] != '^' { expr = "^" + expr } if expr[len(expr)-1] != '$' { expr = expr + "$" } re, err := regexp.Compile(expr) if err != nil { return nil, err } exps = append(exps, re) } return func(abs string) bool { rel, err := filepath.Rel(startDir, abs) if err != nil { return true } // Do not evaluate paths outside of startDir or startDir itself. rel = filepath.ToSlash(rel) if rel == "." || strings.HasPrefix(rel, "../") { return false } for _, exp := range exps { if exp.MatchString(rel) { return true } } return false }, nil }
go
func makeExclusionFilter(startDir string, patterns []string) (fs.ScanFilter, error) { if len(patterns) == 0 { return nil, nil } // Compile regular expressions. exps := []*regexp.Regexp{} for _, expr := range patterns { if expr == "" { continue } if expr[0] != '^' { expr = "^" + expr } if expr[len(expr)-1] != '$' { expr = expr + "$" } re, err := regexp.Compile(expr) if err != nil { return nil, err } exps = append(exps, re) } return func(abs string) bool { rel, err := filepath.Rel(startDir, abs) if err != nil { return true } // Do not evaluate paths outside of startDir or startDir itself. rel = filepath.ToSlash(rel) if rel == "." || strings.HasPrefix(rel, "../") { return false } for _, exp := range exps { if exp.MatchString(rel) { return true } } return false }, nil }
[ "func", "makeExclusionFilter", "(", "startDir", "string", ",", "patterns", "[", "]", "string", ")", "(", "fs", ".", "ScanFilter", ",", "error", ")", "{", "if", "len", "(", "patterns", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n...
// makeExclusionFilter produces a predicate that checks an absolute file path // against a list of regexps. // // Regexps are defined against slash separated paths relative to 'startDir'. // The predicate takes absolute native path, converts it to slash separated path // relative to 'startDir' and checks against list of regexps in 'patterns'. // Returns true to exclude a path.
[ "makeExclusionFilter", "produces", "a", "predicate", "that", "checks", "an", "absolute", "file", "path", "against", "a", "list", "of", "regexps", ".", "Regexps", "are", "defined", "against", "slash", "separated", "paths", "relative", "to", "startDir", ".", "The"...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/builder/pkgdef.go#L253-L294
7,708
luci/luci-go
server/auth/state.go
WithState
func WithState(c context.Context, s State) context.Context { return context.WithValue(c, stateContextKey(0), s) }
go
func WithState(c context.Context, s State) context.Context { return context.WithValue(c, stateContextKey(0), s) }
[ "func", "WithState", "(", "c", "context", ".", "Context", ",", "s", "State", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "stateContextKey", "(", "0", ")", ",", "s", ")", "\n", "}" ]
// WithState injects State into the context. // // Mostly useful from tests. Must not be normally used from production code, // 'Authenticate' sets the state itself.
[ "WithState", "injects", "State", "into", "the", "context", ".", "Mostly", "useful", "from", "tests", ".", "Must", "not", "be", "normally", "used", "from", "production", "code", "Authenticate", "sets", "the", "state", "itself", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/state.go#L71-L73
7,709
luci/luci-go
grpc/cmd/prpc/main.go
done
func (r *cmdRun) done(err error) int { if err != nil { fmt.Fprintln(os.Stderr, err) if err, ok := err.(*exitCode); ok { return err.code } return ecOtherError } return 0 }
go
func (r *cmdRun) done(err error) int { if err != nil { fmt.Fprintln(os.Stderr, err) if err, ok := err.(*exitCode); ok { return err.code } return ecOtherError } return 0 }
[ "func", "(", "r", "*", "cmdRun", ")", "done", "(", "err", "error", ")", "int", "{", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n", "if", "err", ",", "ok", ":=", "err", ".", "(", "*", ...
// done prints err to stderr if it is not nil and returns an exit code.
[ "done", "prints", "err", "to", "stderr", "if", "it", "is", "not", "nil", "and", "returns", "an", "exit", "code", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/main.go#L114-L123
7,710
luci/luci-go
common/api/gitiles/log.go
PagingLog
func PagingLog(ctx context.Context, client gitiles.GitilesClient, req gitiles.LogRequest, limit int, opts ...grpc.CallOption) ([]*git.Commit, error) { // Note: we intentionally receive req as struct (not pointer) // because we need to mutate it. switch { case limit < 0: return nil, errors.New("limit must not be negative") case limit == 0: limit = DefaultLimit } var combinedLog []*git.Commit for { remaining := limit - len(combinedLog) if remaining <= 0 { break } if req.PageSize == 0 || remaining < int(req.PageSize) { // Do not fetch more than we need. req.PageSize = int32(remaining) } res, err := client.Log(ctx, &req, opts...) if err != nil { return combinedLog, err } // req was capped, so this should not exceed limit. combinedLog = append(combinedLog, res.Log...) // There may be fewer commits in the log than the limit given, // if so, NextPageToken should be missing. if res.NextPageToken == "" { break } req.PageToken = res.NextPageToken } return combinedLog, nil }
go
func PagingLog(ctx context.Context, client gitiles.GitilesClient, req gitiles.LogRequest, limit int, opts ...grpc.CallOption) ([]*git.Commit, error) { // Note: we intentionally receive req as struct (not pointer) // because we need to mutate it. switch { case limit < 0: return nil, errors.New("limit must not be negative") case limit == 0: limit = DefaultLimit } var combinedLog []*git.Commit for { remaining := limit - len(combinedLog) if remaining <= 0 { break } if req.PageSize == 0 || remaining < int(req.PageSize) { // Do not fetch more than we need. req.PageSize = int32(remaining) } res, err := client.Log(ctx, &req, opts...) if err != nil { return combinedLog, err } // req was capped, so this should not exceed limit. combinedLog = append(combinedLog, res.Log...) // There may be fewer commits in the log than the limit given, // if so, NextPageToken should be missing. if res.NextPageToken == "" { break } req.PageToken = res.NextPageToken } return combinedLog, nil }
[ "func", "PagingLog", "(", "ctx", "context", ".", "Context", ",", "client", "gitiles", ".", "GitilesClient", ",", "req", "gitiles", ".", "LogRequest", ",", "limit", "int", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "[", "]", "*", "git", "....
// Helper functions for Gitiles.Log RPC. // PagingLog is a wrapper around Gitiles.Log RPC that pages though commits. // If req.PageToken is not empty, paging will continue from there. // // req.PageSize specifies maximum number of commits to load in each page. // // Limit specifies the maximum number of commits to load. // 0 means use DefaultLimit.
[ "Helper", "functions", "for", "Gitiles", ".", "Log", "RPC", ".", "PagingLog", "is", "a", "wrapper", "around", "Gitiles", ".", "Log", "RPC", "that", "pages", "though", "commits", ".", "If", "req", ".", "PageToken", "is", "not", "empty", "paging", "will", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/log.go#L40-L77
7,711
luci/luci-go
milo/api/buildbot/result.go
Status
func (r Result) Status() model.Status { switch r { case NoResult: return model.Running case Success: return model.Success case Warning: return model.Warning case Failure: return model.Failure case Skipped: return model.NotRun case Exception, Retry: return model.Exception default: panic(fmt.Errorf("unknown status %d", r)) } }
go
func (r Result) Status() model.Status { switch r { case NoResult: return model.Running case Success: return model.Success case Warning: return model.Warning case Failure: return model.Failure case Skipped: return model.NotRun case Exception, Retry: return model.Exception default: panic(fmt.Errorf("unknown status %d", r)) } }
[ "func", "(", "r", "Result", ")", "Status", "(", ")", "model", ".", "Status", "{", "switch", "r", "{", "case", "NoResult", ":", "return", "model", ".", "Running", "\n", "case", "Success", ":", "return", "model", ".", "Success", "\n", "case", "Warning", ...
// Status converts r into a model.Status.
[ "Status", "converts", "r", "into", "a", "model", ".", "Status", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/api/buildbot/result.go#L42-L59
7,712
luci/luci-go
common/flag/flagenum/flagenum.go
GetKey
func (e Enum) GetKey(value interface{}) string { for k, v := range e { if reflect.DeepEqual(v, value) { return k } } return "" }
go
func (e Enum) GetKey(value interface{}) string { for k, v := range e { if reflect.DeepEqual(v, value) { return k } } return "" }
[ "func", "(", "e", "Enum", ")", "GetKey", "(", "value", "interface", "{", "}", ")", "string", "{", "for", "k", ",", "v", ":=", "range", "e", "{", "if", "reflect", ".", "DeepEqual", "(", "v", ",", "value", ")", "{", "return", "k", "\n", "}", "\n"...
// GetKey performs reverse lookup of the enumeration value, returning the // key that corresponds to the value. // // If multiple keys correspond to the same value, the result is undefined.
[ "GetKey", "performs", "reverse", "lookup", "of", "the", "enumeration", "value", "returning", "the", "key", "that", "corresponds", "to", "the", "value", ".", "If", "multiple", "keys", "correspond", "to", "the", "same", "value", "the", "result", "is", "undefined...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/flagenum/flagenum.go#L39-L46
7,713
luci/luci-go
common/flag/flagenum/flagenum.go
GetValue
func (e Enum) GetValue(key string) (interface{}, error) { for k, v := range e { if k == key { return v, nil } } return nil, fmt.Errorf("flagenum: Invalid value; must be one of [%s]", e.Choices()) }
go
func (e Enum) GetValue(key string) (interface{}, error) { for k, v := range e { if k == key { return v, nil } } return nil, fmt.Errorf("flagenum: Invalid value; must be one of [%s]", e.Choices()) }
[ "func", "(", "e", "Enum", ")", "GetValue", "(", "key", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "for", "k", ",", "v", ":=", "range", "e", "{", "if", "k", "==", "key", "{", "return", "v", ",", "nil", "\n", "}", "\n", ...
// GetValue returns the mapped enumeration value associated with a key.
[ "GetValue", "returns", "the", "mapped", "enumeration", "value", "associated", "with", "a", "key", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/flagenum/flagenum.go#L49-L56
7,714
luci/luci-go
common/flag/flagenum/flagenum.go
Choices
func (e Enum) Choices() string { keys := make([]string, 0, len(e)) for k := range e { if k == "" { k = `""` } keys = append(keys, k) } sort.Strings(keys) return strings.Join(keys, ", ") }
go
func (e Enum) Choices() string { keys := make([]string, 0, len(e)) for k := range e { if k == "" { k = `""` } keys = append(keys, k) } sort.Strings(keys) return strings.Join(keys, ", ") }
[ "func", "(", "e", "Enum", ")", "Choices", "(", ")", "string", "{", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "e", ")", ")", "\n", "for", "k", ":=", "range", "e", "{", "if", "k", "==", "\"", "\"", "{", "k", ...
// Choices returns a comma-separated string listing sorted enumeration choices.
[ "Choices", "returns", "a", "comma", "-", "separated", "string", "listing", "sorted", "enumeration", "choices", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/flagenum/flagenum.go#L59-L69
7,715
luci/luci-go
common/flag/flagenum/flagenum.go
setValue
func (e Enum) setValue(v interface{}, key string) error { i, err := e.GetValue(key) if err != nil { return err } vValue := reflect.ValueOf(v).Elem() if !vValue.CanSet() { panic(fmt.Errorf("flagenum: Cannot set supplied value, %v", vValue)) } iValue := reflect.ValueOf(i) if !vValue.Type().AssignableTo(iValue.Type()) { panic(fmt.Errorf("flagenum: Enumeration type (%v) is incompatible with supplied value (%v)", vValue.Type(), iValue.Type())) } vValue.Set(iValue) return nil }
go
func (e Enum) setValue(v interface{}, key string) error { i, err := e.GetValue(key) if err != nil { return err } vValue := reflect.ValueOf(v).Elem() if !vValue.CanSet() { panic(fmt.Errorf("flagenum: Cannot set supplied value, %v", vValue)) } iValue := reflect.ValueOf(i) if !vValue.Type().AssignableTo(iValue.Type()) { panic(fmt.Errorf("flagenum: Enumeration type (%v) is incompatible with supplied value (%v)", vValue.Type(), iValue.Type())) } vValue.Set(iValue) return nil }
[ "func", "(", "e", "Enum", ")", "setValue", "(", "v", "interface", "{", "}", ",", "key", "string", ")", "error", "{", "i", ",", "err", ":=", "e", ".", "GetValue", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", ...
// Sets the value v to the enumeration value mapped to the supplied key.
[ "Sets", "the", "value", "v", "to", "the", "enumeration", "value", "mapped", "to", "the", "supplied", "key", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/flagenum/flagenum.go#L72-L91
7,716
luci/luci-go
common/flag/flagenum/flagenum.go
FlagSet
func (e Enum) FlagSet(v interface{}, key string) error { return e.setValue(v, key) }
go
func (e Enum) FlagSet(v interface{}, key string) error { return e.setValue(v, key) }
[ "func", "(", "e", "Enum", ")", "FlagSet", "(", "v", "interface", "{", "}", ",", "key", "string", ")", "error", "{", "return", "e", ".", "setValue", "(", "v", ",", "key", ")", "\n", "}" ]
// FlagSet implements flag.Value's Set semantics. It identifies the mapped value // associated with the supplied key and stores it in the supplied interface. // // The interface, v, must be a valid pointer to the mapped enumeration type.
[ "FlagSet", "implements", "flag", ".", "Value", "s", "Set", "semantics", ".", "It", "identifies", "the", "mapped", "value", "associated", "with", "the", "supplied", "key", "and", "stores", "it", "in", "the", "supplied", "interface", ".", "The", "interface", "...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/flagenum/flagenum.go#L97-L99
7,717
luci/luci-go
common/flag/flagenum/flagenum.go
JSONUnmarshal
func (e Enum) JSONUnmarshal(v interface{}, data []byte) error { s := "" if err := json.Unmarshal(data, &s); err != nil { return err } return e.FlagSet(v, s) }
go
func (e Enum) JSONUnmarshal(v interface{}, data []byte) error { s := "" if err := json.Unmarshal(data, &s); err != nil { return err } return e.FlagSet(v, s) }
[ "func", "(", "e", "Enum", ")", "JSONUnmarshal", "(", "v", "interface", "{", "}", ",", "data", "[", "]", "byte", ")", "error", "{", "s", ":=", "\"", "\"", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ")", ";", ...
// JSONUnmarshal implements json.Unmarshaler's UnmarshalJSON semantics. It // parses data containing a quoted string, identifies the enumeration value // associated with that string, and stores it in the supplied interface. // // The interface, v, must be a valid pointer to the mapped enumeration type. // a string corresponding to one of the enum's keys.
[ "JSONUnmarshal", "implements", "json", ".", "Unmarshaler", "s", "UnmarshalJSON", "semantics", ".", "It", "parses", "data", "containing", "a", "quoted", "string", "identifies", "the", "enumeration", "value", "associated", "with", "that", "string", "and", "stores", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/flagenum/flagenum.go#L112-L118
7,718
luci/luci-go
common/flag/flagenum/flagenum.go
JSONMarshal
func (e Enum) JSONMarshal(v interface{}) ([]byte, error) { key := e.GetKey(v) data, err := json.Marshal(&key) if err != nil { return nil, err } return data, nil }
go
func (e Enum) JSONMarshal(v interface{}) ([]byte, error) { key := e.GetKey(v) data, err := json.Marshal(&key) if err != nil { return nil, err } return data, nil }
[ "func", "(", "e", "Enum", ")", "JSONMarshal", "(", "v", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "key", ":=", "e", ".", "GetKey", "(", "v", ")", "\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "&...
// JSONMarshal implements json.Marshaler's MarshalJSON semantics. It marshals // the value in the supplied interface to its associated key and emits a quoted // string containing that key. // // The interface, v, must be a valid pointer to the mapped enumeration type.
[ "JSONMarshal", "implements", "json", ".", "Marshaler", "s", "MarshalJSON", "semantics", ".", "It", "marshals", "the", "value", "in", "the", "supplied", "interface", "to", "its", "associated", "key", "and", "emits", "a", "quoted", "string", "containing", "that", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/flagenum/flagenum.go#L125-L132
7,719
luci/luci-go
logdog/client/butlerlib/streamclient/client_namedPipe_windows.go
newNamedPipeClient
func newNamedPipeClient(path string, ns types.StreamName) (Client, error) { if path == "" { return nil, errors.New("streamclient: cannot have empty named pipe path") } return &clientImpl{ factory: func() (io.WriteCloser, error) { return winio.DialPipe(LocalNamedPipePath(path), nil) }, ns: ns, }, nil }
go
func newNamedPipeClient(path string, ns types.StreamName) (Client, error) { if path == "" { return nil, errors.New("streamclient: cannot have empty named pipe path") } return &clientImpl{ factory: func() (io.WriteCloser, error) { return winio.DialPipe(LocalNamedPipePath(path), nil) }, ns: ns, }, nil }
[ "func", "newNamedPipeClient", "(", "path", "string", ",", "ns", "types", ".", "StreamName", ")", "(", "Client", ",", "error", ")", "{", "if", "path", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}"...
// newNamedPipeClient creates a new Client instance bound to a named pipe stream // server.
[ "newNamedPipeClient", "creates", "a", "new", "Client", "instance", "bound", "to", "a", "named", "pipe", "stream", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamclient/client_namedPipe_windows.go#L31-L42
7,720
luci/luci-go
tokenserver/appengine/backend/main.go
statusFromErrs
func statusFromErrs(errs []error) int { for _, err := range errs { if grpc.Code(err) == codes.Internal { return http.StatusInternalServerError } } return http.StatusOK }
go
func statusFromErrs(errs []error) int { for _, err := range errs { if grpc.Code(err) == codes.Internal { return http.StatusInternalServerError } } return http.StatusOK }
[ "func", "statusFromErrs", "(", "errs", "[", "]", "error", ")", "int", "{", "for", "_", ",", "err", ":=", "range", "errs", "{", "if", "grpc", ".", "Code", "(", "err", ")", "==", "codes", ".", "Internal", "{", "return", "http", ".", "StatusInternalServ...
// statusFromErrs returns 500 if any of gRPC errors is codes.Internal.
[ "statusFromErrs", "returns", "500", "if", "any", "of", "gRPC", "errors", "is", "codes", ".", "Internal", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/backend/main.go#L188-L195
7,721
luci/luci-go
milo/buildsource/buildbot/build.go
getBanner
func getBanner(c context.Context, b *buildbot.Build) *ui.LogoBanner { osLogo := func() *ui.Logo { result := &ui.Logo{} switch b.OSFamily { case "windows": result.LogoBase = ui.Windows case "Darwin": result.LogoBase = ui.OSX case "Debian": result.LogoBase = ui.Ubuntu default: return nil } result.Subtitle = b.OSVersion return result }() if osLogo != nil { return &ui.LogoBanner{ OS: []ui.Logo{*osLogo}, } } return nil }
go
func getBanner(c context.Context, b *buildbot.Build) *ui.LogoBanner { osLogo := func() *ui.Logo { result := &ui.Logo{} switch b.OSFamily { case "windows": result.LogoBase = ui.Windows case "Darwin": result.LogoBase = ui.OSX case "Debian": result.LogoBase = ui.Ubuntu default: return nil } result.Subtitle = b.OSVersion return result }() if osLogo != nil { return &ui.LogoBanner{ OS: []ui.Logo{*osLogo}, } } return nil }
[ "func", "getBanner", "(", "c", "context", ".", "Context", ",", "b", "*", "buildbot", ".", "Build", ")", "*", "ui", ".", "LogoBanner", "{", "osLogo", ":=", "func", "(", ")", "*", "ui", ".", "Logo", "{", "result", ":=", "&", "ui", ".", "Logo", "{",...
// getBanner parses the OS information from the build and maybe returns a banner.
[ "getBanner", "parses", "the", "OS", "information", "from", "the", "build", "and", "maybe", "returns", "a", "banner", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/build.go#L41-L63
7,722
luci/luci-go
milo/buildsource/buildbot/build.go
summary
func summary(c context.Context, b *buildbot.Build) ui.BuildComponent { // TODO(hinoka): use b.toStatus() // Status var status model.Status if b.Currentstep != nil { status = model.Running } else { status = b.Results.Status() } // Link to bot and original build. host := "build.chromium.org/p" if b.Internal { host = "uberchromegw.corp.google.com/i" } bot := ui.NewLink( b.Slave, fmt.Sprintf("https://%s/%s/buildslaves/%s", host, b.Master, b.Slave), fmt.Sprintf("Buildbot buildslave %s", b.Slave)) var source *ui.Link if !b.Emulated { source = ui.NewLink( fmt.Sprintf("%s/%s/%d", b.Master, b.Buildername, b.Number), fmt.Sprintf("https://%s/%s/builders/%s/builds/%d", host, b.Master, b.Buildername, b.Number), fmt.Sprintf("Original build number %d on master %s builder %s", b.Number, b.Master, b.Buildername)) } // The link to this page and the builder page. label := ui.NewLink( fmt.Sprintf("#%d", b.Number), fmt.Sprintf("/buildbot/%s/%s/%d", b.Master, b.Buildername, b.Number), fmt.Sprintf("Build number %d on master %s builder %s", b.Number, b.Master, b.Buildername)) // Perpetuate emulation mode, if it is currently on. if buildstore.EmulationEnabled(c) { label.URL += "?emulation=1" } parent := ui.NewLink(b.Buildername, ".", fmt.Sprintf("Parent builder %s", b.Buildername)) // Do a best effort lookup for the bot information to fill in OS/Platform info. banner := getBanner(c, b) sum := ui.BuildComponent{ ParentLabel: parent, Label: label, Banner: banner, Status: status, ExecutionTime: ui.NewInterval(c, b.Times.Start.Time, b.Times.Finish.Time), Bot: bot, Source: source, Type: ui.Summary, // This is more or less ignored. Text: mergeText(b.Text), // Status messages. Eg "This build failed on..xyz" } return sum }
go
func summary(c context.Context, b *buildbot.Build) ui.BuildComponent { // TODO(hinoka): use b.toStatus() // Status var status model.Status if b.Currentstep != nil { status = model.Running } else { status = b.Results.Status() } // Link to bot and original build. host := "build.chromium.org/p" if b.Internal { host = "uberchromegw.corp.google.com/i" } bot := ui.NewLink( b.Slave, fmt.Sprintf("https://%s/%s/buildslaves/%s", host, b.Master, b.Slave), fmt.Sprintf("Buildbot buildslave %s", b.Slave)) var source *ui.Link if !b.Emulated { source = ui.NewLink( fmt.Sprintf("%s/%s/%d", b.Master, b.Buildername, b.Number), fmt.Sprintf("https://%s/%s/builders/%s/builds/%d", host, b.Master, b.Buildername, b.Number), fmt.Sprintf("Original build number %d on master %s builder %s", b.Number, b.Master, b.Buildername)) } // The link to this page and the builder page. label := ui.NewLink( fmt.Sprintf("#%d", b.Number), fmt.Sprintf("/buildbot/%s/%s/%d", b.Master, b.Buildername, b.Number), fmt.Sprintf("Build number %d on master %s builder %s", b.Number, b.Master, b.Buildername)) // Perpetuate emulation mode, if it is currently on. if buildstore.EmulationEnabled(c) { label.URL += "?emulation=1" } parent := ui.NewLink(b.Buildername, ".", fmt.Sprintf("Parent builder %s", b.Buildername)) // Do a best effort lookup for the bot information to fill in OS/Platform info. banner := getBanner(c, b) sum := ui.BuildComponent{ ParentLabel: parent, Label: label, Banner: banner, Status: status, ExecutionTime: ui.NewInterval(c, b.Times.Start.Time, b.Times.Finish.Time), Bot: bot, Source: source, Type: ui.Summary, // This is more or less ignored. Text: mergeText(b.Text), // Status messages. Eg "This build failed on..xyz" } return sum }
[ "func", "summary", "(", "c", "context", ".", "Context", ",", "b", "*", "buildbot", ".", "Build", ")", "ui", ".", "BuildComponent", "{", "// TODO(hinoka): use b.toStatus()", "// Status", "var", "status", "model", ".", "Status", "\n", "if", "b", ".", "Currents...
// summary extracts the top level summary from a buildbot build as a // BuildComponent
[ "summary", "extracts", "the", "top", "level", "summary", "from", "a", "buildbot", "build", "as", "a", "BuildComponent" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/build.go#L67-L123
7,723
luci/luci-go
milo/buildsource/buildbot/build.go
parseProp
func parseProp(v interface{}) string { // if v is a whole number, force it into an int. json.Marshal() would turn // it into what looks like a float instead. We want this to remain and // int instead of a number. if vf, ok := v.(float64); ok { if math.Floor(vf) == vf { return fmt.Sprintf("%d", int64(vf)) } } // return the json representation of the value. b, err := json.Marshal(v) if err == nil { return string(b) } return fmt.Sprintf("%v", v) }
go
func parseProp(v interface{}) string { // if v is a whole number, force it into an int. json.Marshal() would turn // it into what looks like a float instead. We want this to remain and // int instead of a number. if vf, ok := v.(float64); ok { if math.Floor(vf) == vf { return fmt.Sprintf("%d", int64(vf)) } } // return the json representation of the value. b, err := json.Marshal(v) if err == nil { return string(b) } return fmt.Sprintf("%v", v) }
[ "func", "parseProp", "(", "v", "interface", "{", "}", ")", "string", "{", "// if v is a whole number, force it into an int. json.Marshal() would turn", "// it into what looks like a float instead. We want this to remain and", "// int instead of a number.", "if", "vf", ",", "ok", ...
// parseProp returns a string representation of v.
[ "parseProp", "returns", "a", "string", "representation", "of", "v", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/build.go#L240-L255
7,724
luci/luci-go
milo/buildsource/buildbot/build.go
properties
func properties(b *buildbot.Build) (result []*ui.PropertyGroup) { groups := map[string]*ui.PropertyGroup{} allProps := map[string]Prop{} for _, prop := range b.Properties { allProps[prop.Name] = Prop{ Value: prop.Value, Group: prop.Source, } } for key, prop := range allProps { value := prop.Value groupName := prop.Group if _, ok := groups[groupName]; !ok { groups[groupName] = &ui.PropertyGroup{GroupName: groupName} } vs := parseProp(value) groups[groupName].Property = append(groups[groupName].Property, &ui.Property{ Key: key, Value: vs, }) } // Insert the groups into a list in alphabetical order. // You have to make a separate sorting data structure because Go doesn't like // sorting things for you. groupNames := make([]string, 0, len(groups)) for n := range groups { groupNames = append(groupNames, n) } sort.Strings(groupNames) for _, k := range groupNames { group := groups[k] // Also take this oppertunity to sort the properties within the groups. sort.Sort(group) result = append(result, group) } return }
go
func properties(b *buildbot.Build) (result []*ui.PropertyGroup) { groups := map[string]*ui.PropertyGroup{} allProps := map[string]Prop{} for _, prop := range b.Properties { allProps[prop.Name] = Prop{ Value: prop.Value, Group: prop.Source, } } for key, prop := range allProps { value := prop.Value groupName := prop.Group if _, ok := groups[groupName]; !ok { groups[groupName] = &ui.PropertyGroup{GroupName: groupName} } vs := parseProp(value) groups[groupName].Property = append(groups[groupName].Property, &ui.Property{ Key: key, Value: vs, }) } // Insert the groups into a list in alphabetical order. // You have to make a separate sorting data structure because Go doesn't like // sorting things for you. groupNames := make([]string, 0, len(groups)) for n := range groups { groupNames = append(groupNames, n) } sort.Strings(groupNames) for _, k := range groupNames { group := groups[k] // Also take this oppertunity to sort the properties within the groups. sort.Sort(group) result = append(result, group) } return }
[ "func", "properties", "(", "b", "*", "buildbot", ".", "Build", ")", "(", "result", "[", "]", "*", "ui", ".", "PropertyGroup", ")", "{", "groups", ":=", "map", "[", "string", "]", "*", "ui", ".", "PropertyGroup", "{", "}", "\n", "allProps", ":=", "m...
// properties extracts all properties from buildbot builds and groups them into // property groups.
[ "properties", "extracts", "all", "properties", "from", "buildbot", "builds", "and", "groups", "them", "into", "property", "groups", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/build.go#L267-L303
7,725
luci/luci-go
milo/buildsource/buildbot/build.go
blame
func blame(b *buildbot.Build) (result []*ui.Commit) { if b.Sourcestamp != nil { for _, c := range b.Sourcestamp.Changes { files := c.GetFiles() result = append(result, &ui.Commit{ AuthorEmail: c.Who, Repo: c.Repository, CommitTime: time.Unix(int64(c.When), 0).UTC(), Revision: ui.NewLink(c.Revision, c.Revlink, fmt.Sprintf("commit by %s", c.Who)), Description: c.Comments, File: files, }) } } return }
go
func blame(b *buildbot.Build) (result []*ui.Commit) { if b.Sourcestamp != nil { for _, c := range b.Sourcestamp.Changes { files := c.GetFiles() result = append(result, &ui.Commit{ AuthorEmail: c.Who, Repo: c.Repository, CommitTime: time.Unix(int64(c.When), 0).UTC(), Revision: ui.NewLink(c.Revision, c.Revlink, fmt.Sprintf("commit by %s", c.Who)), Description: c.Comments, File: files, }) } } return }
[ "func", "blame", "(", "b", "*", "buildbot", ".", "Build", ")", "(", "result", "[", "]", "*", "ui", ".", "Commit", ")", "{", "if", "b", ".", "Sourcestamp", "!=", "nil", "{", "for", "_", ",", "c", ":=", "range", "b", ".", "Sourcestamp", ".", "Cha...
// blame extracts the commit and blame information from a buildbot build and // returns it as a list of Commits.
[ "blame", "extracts", "the", "commit", "and", "blame", "information", "from", "a", "buildbot", "build", "and", "returns", "it", "as", "a", "list", "of", "Commits", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/build.go#L307-L322
7,726
luci/luci-go
milo/buildsource/buildbot/build.go
sourcestamp
func sourcestamp(c context.Context, b *buildbot.Build) *ui.Trigger { ss := &ui.Trigger{} var rietveld url.URL var gerrit url.URL gotRevision := "" repository := "" issue := int64(-1) patchset := int64(-1) for _, prop := range b.Properties { setIfIntOrStr := func(dst *int64) { switch v := prop.Value.(type) { case float64: *dst = int64(v) case string: if v != "" { if vi, err := strconv.ParseInt(v, 10, 64); err == nil { *dst = int64(vi) } else { logging.Warningf(c, "Could not decode field %s: %q - %s", prop.Name, v, err) } } default: logging.Warningf(c, "Field %s is not a string or float64: %#v", prop.Name, v) } } setIfStr := func(dst *string) { if v, ok := prop.Value.(string); ok { *dst = v } else { logging.Warningf(c, "Field %s is not a string: %#v", prop.Name, prop.Value) } } setIfURL := func(dst *url.URL) { if v, ok := prop.Value.(string); ok { if u, err := url.Parse(v); err == nil { *dst = *u return } } logging.Warningf(c, "Field %s is not a string URL: %#v", prop.Name, prop.Value) } switch prop.Name { case "rietveld": setIfURL(&rietveld) case "issue", "patch_issue": setIfIntOrStr(&issue) case "got_revision": setIfStr(&gotRevision) case "patch_gerrit_url": setIfURL(&gerrit) case "patch_set", "patchset": setIfIntOrStr(&patchset) case "repository": setIfStr(&repository) } } if gerrit.Host != "" && issue != -1 && patchset != -1 { cl := &buildbucketpb.GerritChange{ Host: gerrit.Host, Change: issue, Patchset: patchset, } ss.Changelist = ui.NewPatchLink(cl) } if gotRevision != "" { ss.Revision = ui.NewLink(gotRevision, "", fmt.Sprintf("got revision %s", gotRevision)) if repository != "" { ss.Revision.URL = repository + "/+/" + gotRevision } } return ss }
go
func sourcestamp(c context.Context, b *buildbot.Build) *ui.Trigger { ss := &ui.Trigger{} var rietveld url.URL var gerrit url.URL gotRevision := "" repository := "" issue := int64(-1) patchset := int64(-1) for _, prop := range b.Properties { setIfIntOrStr := func(dst *int64) { switch v := prop.Value.(type) { case float64: *dst = int64(v) case string: if v != "" { if vi, err := strconv.ParseInt(v, 10, 64); err == nil { *dst = int64(vi) } else { logging.Warningf(c, "Could not decode field %s: %q - %s", prop.Name, v, err) } } default: logging.Warningf(c, "Field %s is not a string or float64: %#v", prop.Name, v) } } setIfStr := func(dst *string) { if v, ok := prop.Value.(string); ok { *dst = v } else { logging.Warningf(c, "Field %s is not a string: %#v", prop.Name, prop.Value) } } setIfURL := func(dst *url.URL) { if v, ok := prop.Value.(string); ok { if u, err := url.Parse(v); err == nil { *dst = *u return } } logging.Warningf(c, "Field %s is not a string URL: %#v", prop.Name, prop.Value) } switch prop.Name { case "rietveld": setIfURL(&rietveld) case "issue", "patch_issue": setIfIntOrStr(&issue) case "got_revision": setIfStr(&gotRevision) case "patch_gerrit_url": setIfURL(&gerrit) case "patch_set", "patchset": setIfIntOrStr(&patchset) case "repository": setIfStr(&repository) } } if gerrit.Host != "" && issue != -1 && patchset != -1 { cl := &buildbucketpb.GerritChange{ Host: gerrit.Host, Change: issue, Patchset: patchset, } ss.Changelist = ui.NewPatchLink(cl) } if gotRevision != "" { ss.Revision = ui.NewLink(gotRevision, "", fmt.Sprintf("got revision %s", gotRevision)) if repository != "" { ss.Revision.URL = repository + "/+/" + gotRevision } } return ss }
[ "func", "sourcestamp", "(", "c", "context", ".", "Context", ",", "b", "*", "buildbot", ".", "Build", ")", "*", "ui", ".", "Trigger", "{", "ss", ":=", "&", "ui", ".", "Trigger", "{", "}", "\n", "var", "rietveld", "url", ".", "URL", "\n", "var", "g...
// sourcestamp extracts the source stamp from various parts of a buildbot build, // including the properties.
[ "sourcestamp", "extracts", "the", "source", "stamp", "from", "various", "parts", "of", "a", "buildbot", "build", "including", "the", "properties", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/build.go#L326-L400
7,727
luci/luci-go
milo/buildsource/buildbot/build.go
DebugBuild
func DebugBuild(c context.Context, relBuildbotDir string, builder string, buildNum int) (*ui.MiloBuildLegacy, error) { fname := fmt.Sprintf("%s.%d.json", builder, buildNum) // ../buildbot below assumes that // - this code is not executed by tests outside of this dir // - this dir is a sibling of frontend dir path := filepath.Join(relBuildbotDir, "testdata", fname) raw, err := ioutil.ReadFile(path) if err != nil { return nil, err } b := &buildbot.Build{} if err := json.Unmarshal(raw, b); err != nil { return nil, err } return renderBuild(c, b, true), nil }
go
func DebugBuild(c context.Context, relBuildbotDir string, builder string, buildNum int) (*ui.MiloBuildLegacy, error) { fname := fmt.Sprintf("%s.%d.json", builder, buildNum) // ../buildbot below assumes that // - this code is not executed by tests outside of this dir // - this dir is a sibling of frontend dir path := filepath.Join(relBuildbotDir, "testdata", fname) raw, err := ioutil.ReadFile(path) if err != nil { return nil, err } b := &buildbot.Build{} if err := json.Unmarshal(raw, b); err != nil { return nil, err } return renderBuild(c, b, true), nil }
[ "func", "DebugBuild", "(", "c", "context", ".", "Context", ",", "relBuildbotDir", "string", ",", "builder", "string", ",", "buildNum", "int", ")", "(", "*", "ui", ".", "MiloBuildLegacy", ",", "error", ")", "{", "fname", ":=", "fmt", ".", "Sprintf", "(", ...
// DebugBuild fetches a debugging build for testing.
[ "DebugBuild", "fetches", "a", "debugging", "build", "for", "testing", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/build.go#L416-L431
7,728
luci/luci-go
milo/buildsource/buildbot/build.go
GetBuild
func GetBuild(c context.Context, id buildbot.BuildID) (*ui.MiloBuildLegacy, error) { if err := id.Validate(); err != nil { return nil, err } if err := buildstore.CanAccessMaster(c, id.Master); err != nil { return nil, err } switch b, err := buildstore.GetBuild(c, id); { case err != nil: return nil, err case b == nil: return nil, errors.Reason("build %s not found", &id).Tag(grpcutil.NotFoundTag).Err() default: return renderBuild(c, b, true), nil } }
go
func GetBuild(c context.Context, id buildbot.BuildID) (*ui.MiloBuildLegacy, error) { if err := id.Validate(); err != nil { return nil, err } if err := buildstore.CanAccessMaster(c, id.Master); err != nil { return nil, err } switch b, err := buildstore.GetBuild(c, id); { case err != nil: return nil, err case b == nil: return nil, errors.Reason("build %s not found", &id).Tag(grpcutil.NotFoundTag).Err() default: return renderBuild(c, b, true), nil } }
[ "func", "GetBuild", "(", "c", "context", ".", "Context", ",", "id", "buildbot", ".", "BuildID", ")", "(", "*", "ui", ".", "MiloBuildLegacy", ",", "error", ")", "{", "if", "err", ":=", "id", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", ...
// GetBuild fetches a buildbot build and translates it into a MiloBuildLegacy.
[ "GetBuild", "fetches", "a", "buildbot", "build", "and", "translates", "it", "into", "a", "MiloBuildLegacy", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/build.go#L434-L450
7,729
luci/luci-go
common/proto/google/util.go
LoadTimestamp
func LoadTimestamp(t *timestamp.Timestamp, v time.Time) *timestamp.Timestamp { if t == nil { if v.IsZero() { return nil } t = &timestamp.Timestamp{} } t.Seconds = v.Unix() t.Nanos = int32(v.Nanosecond()) return t }
go
func LoadTimestamp(t *timestamp.Timestamp, v time.Time) *timestamp.Timestamp { if t == nil { if v.IsZero() { return nil } t = &timestamp.Timestamp{} } t.Seconds = v.Unix() t.Nanos = int32(v.Nanosecond()) return t }
[ "func", "LoadTimestamp", "(", "t", "*", "timestamp", ".", "Timestamp", ",", "v", "time", ".", "Time", ")", "*", "timestamp", ".", "Timestamp", "{", "if", "t", "==", "nil", "{", "if", "v", ".", "IsZero", "(", ")", "{", "return", "nil", "\n", "}", ...
// LoadTimestamp replaces the value in the supplied Timestamp with the specified // time. // // If the supplied Timestamp is nil and the time is non-zero, a new Timestamp // will be generated. The populated Timestamp will be returned.
[ "LoadTimestamp", "replaces", "the", "value", "in", "the", "supplied", "Timestamp", "with", "the", "specified", "time", ".", "If", "the", "supplied", "Timestamp", "is", "nil", "and", "the", "time", "is", "non", "-", "zero", "a", "new", "Timestamp", "will", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/util.go#L38-L50
7,730
luci/luci-go
common/proto/google/util.go
TimeFromProto
func TimeFromProto(t *timestamp.Timestamp) time.Time { if t == nil { return time.Time{} } return time.Unix(t.Seconds, int64(t.Nanos)).UTC() }
go
func TimeFromProto(t *timestamp.Timestamp) time.Time { if t == nil { return time.Time{} } return time.Unix(t.Seconds, int64(t.Nanos)).UTC() }
[ "func", "TimeFromProto", "(", "t", "*", "timestamp", ".", "Timestamp", ")", "time", ".", "Time", "{", "if", "t", "==", "nil", "{", "return", "time", ".", "Time", "{", "}", "\n", "}", "\n", "return", "time", ".", "Unix", "(", "t", ".", "Seconds", ...
// TimeFromProto returns the time.Time associated with a Timestamp protobuf.
[ "TimeFromProto", "returns", "the", "time", ".", "Time", "associated", "with", "a", "Timestamp", "protobuf", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/util.go#L53-L58
7,731
luci/luci-go
common/proto/google/util.go
LoadDuration
func LoadDuration(d *duration.Duration, v time.Duration) *duration.Duration { if d == nil { if v == 0 { return nil } d = &duration.Duration{} } nanos := v.Nanoseconds() d.Seconds = nanos / nanosecondsInASecond d.Nanos = int32(nanos % nanosecondsInASecond) return d }
go
func LoadDuration(d *duration.Duration, v time.Duration) *duration.Duration { if d == nil { if v == 0 { return nil } d = &duration.Duration{} } nanos := v.Nanoseconds() d.Seconds = nanos / nanosecondsInASecond d.Nanos = int32(nanos % nanosecondsInASecond) return d }
[ "func", "LoadDuration", "(", "d", "*", "duration", ".", "Duration", ",", "v", "time", ".", "Duration", ")", "*", "duration", ".", "Duration", "{", "if", "d", "==", "nil", "{", "if", "v", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "d", "=...
// LoadDuration replaces the value in the supplied Duration with the specified // value. // // If the supplied Duration is nil and the value is non-zero, a new Duration // will be generated. The populated Duration will be returned.
[ "LoadDuration", "replaces", "the", "value", "in", "the", "supplied", "Duration", "with", "the", "specified", "value", ".", "If", "the", "supplied", "Duration", "is", "nil", "and", "the", "value", "is", "non", "-", "zero", "a", "new", "Duration", "will", "b...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/google/util.go#L70-L84
7,732
luci/luci-go
config/server/cfgclient/backend/caching/lru.go
LRUBackend
func LRUBackend(b backend.B, cache *lru.Cache, exp time.Duration) backend.B { // If our parameters are disabled, just return the underlying Backend. if exp <= 0 { return b } // mp is used to block concurrent accesses to the same cache key. return &Backend{ B: b, CacheGet: func(c context.Context, key Key, l Loader) (ret *Value, err error) { // Generate the identity component of our cache key. // // For AsAnonymous and AsService access, we cache based on a singleton // identity. For AsUser, however, we cache on a per-user basis. var id identity.Identity if key.Authority == backend.AsUser { id = auth.CurrentIdentity(c) } cacheKey := mkLRUCacheKey(&key, id) // Lock around this key. This will ensure that concurrent accesses to the // same key will not result in multiple redundant fetches. v, err := cache.GetOrCreate(c, cacheKey, func() (interface{}, time.Duration, error) { // The value wasn't in the cache. Resolve and cache it. ret, err := l(c, key, nil) if err != nil { return nil, 0, err } return ret, exp, nil }) if err != nil { return nil, err } return v.(*Value), nil }, } }
go
func LRUBackend(b backend.B, cache *lru.Cache, exp time.Duration) backend.B { // If our parameters are disabled, just return the underlying Backend. if exp <= 0 { return b } // mp is used to block concurrent accesses to the same cache key. return &Backend{ B: b, CacheGet: func(c context.Context, key Key, l Loader) (ret *Value, err error) { // Generate the identity component of our cache key. // // For AsAnonymous and AsService access, we cache based on a singleton // identity. For AsUser, however, we cache on a per-user basis. var id identity.Identity if key.Authority == backend.AsUser { id = auth.CurrentIdentity(c) } cacheKey := mkLRUCacheKey(&key, id) // Lock around this key. This will ensure that concurrent accesses to the // same key will not result in multiple redundant fetches. v, err := cache.GetOrCreate(c, cacheKey, func() (interface{}, time.Duration, error) { // The value wasn't in the cache. Resolve and cache it. ret, err := l(c, key, nil) if err != nil { return nil, 0, err } return ret, exp, nil }) if err != nil { return nil, err } return v.(*Value), nil }, } }
[ "func", "LRUBackend", "(", "b", "backend", ".", "B", ",", "cache", "*", "lru", ".", "Cache", ",", "exp", "time", ".", "Duration", ")", "backend", ".", "B", "{", "// If our parameters are disabled, just return the underlying Backend.", "if", "exp", "<=", "0", "...
// LRUBackend wraps b, applying the additional cache to its results. // // Do NOT chain multiple LRUBackend in the same backend chain. An LRUBackend // holds a LRU-wide lock on its cache key when it looks up its value, and if // a second entity attempts to lock that same key during its lookup chain, the // lookup will deadlock. // // If the supplied expiration is <= 0, no additional caching will be performed.
[ "LRUBackend", "wraps", "b", "applying", "the", "additional", "cache", "to", "its", "results", ".", "Do", "NOT", "chain", "multiple", "LRUBackend", "in", "the", "same", "backend", "chain", ".", "An", "LRUBackend", "holds", "a", "LRU", "-", "wide", "lock", "...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/lru.go#L37-L74
7,733
luci/luci-go
server/auth/openid/protocol.go
signingKeys
func (d *discoveryDoc) signingKeys(c context.Context) (*JSONWebKeySet, error) { fetcher := func() (interface{}, time.Duration, error) { raw := &JSONWebKeySetStruct{} req := internal.Request{ Method: "GET", URL: d.JwksURI, Out: raw, } if err := req.Do(c); err != nil { return nil, 0, err } keys, err := NewJSONWebKeySet(raw) if err != nil { return nil, 0, err } return keys, time.Hour * 6, nil } cached, err := signingKeysCache.LRU(c).GetOrCreate(c, d.JwksURI, fetcher) if err != nil { return nil, err } return cached.(*JSONWebKeySet), nil }
go
func (d *discoveryDoc) signingKeys(c context.Context) (*JSONWebKeySet, error) { fetcher := func() (interface{}, time.Duration, error) { raw := &JSONWebKeySetStruct{} req := internal.Request{ Method: "GET", URL: d.JwksURI, Out: raw, } if err := req.Do(c); err != nil { return nil, 0, err } keys, err := NewJSONWebKeySet(raw) if err != nil { return nil, 0, err } return keys, time.Hour * 6, nil } cached, err := signingKeysCache.LRU(c).GetOrCreate(c, d.JwksURI, fetcher) if err != nil { return nil, err } return cached.(*JSONWebKeySet), nil }
[ "func", "(", "d", "*", "discoveryDoc", ")", "signingKeys", "(", "c", "context", ".", "Context", ")", "(", "*", "JSONWebKeySet", ",", "error", ")", "{", "fetcher", ":=", "func", "(", ")", "(", "interface", "{", "}", ",", "time", ".", "Duration", ",", ...
// signingKeys returns a JSON Web Key set fetched from the location specified // in the discovery document. // // It fetches them on the first use and then keeps them cached in the process // cache for 6h. // // May return both fatal and transient errors.
[ "signingKeys", "returns", "a", "JSON", "Web", "Key", "set", "fetched", "from", "the", "location", "specified", "in", "the", "discovery", "document", ".", "It", "fetches", "them", "on", "the", "first", "use", "and", "then", "keeps", "them", "cached", "in", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/protocol.go#L61-L84
7,734
luci/luci-go
server/auth/openid/protocol.go
fetchDiscoveryDoc
func fetchDiscoveryDoc(c context.Context, url string) (*discoveryDoc, error) { if url == "" { return nil, ErrNotConfigured } fetcher := func() (interface{}, time.Duration, error) { doc := &discoveryDoc{} req := internal.Request{ Method: "GET", URL: url, Out: doc, } if err := req.Do(c); err != nil { return nil, 0, err } return doc, time.Hour * 24, nil } // Cache the document in the process cache. cached, err := discoveryDocCache.LRU(c).GetOrCreate(c, url, fetcher) if err != nil { return nil, err } return cached.(*discoveryDoc), nil }
go
func fetchDiscoveryDoc(c context.Context, url string) (*discoveryDoc, error) { if url == "" { return nil, ErrNotConfigured } fetcher := func() (interface{}, time.Duration, error) { doc := &discoveryDoc{} req := internal.Request{ Method: "GET", URL: url, Out: doc, } if err := req.Do(c); err != nil { return nil, 0, err } return doc, time.Hour * 24, nil } // Cache the document in the process cache. cached, err := discoveryDocCache.LRU(c).GetOrCreate(c, url, fetcher) if err != nil { return nil, err } return cached.(*discoveryDoc), nil }
[ "func", "fetchDiscoveryDoc", "(", "c", "context", ".", "Context", ",", "url", "string", ")", "(", "*", "discoveryDoc", ",", "error", ")", "{", "if", "url", "==", "\"", "\"", "{", "return", "nil", ",", "ErrNotConfigured", "\n", "}", "\n\n", "fetcher", "...
// fetchDiscoveryDoc fetches discovery document from given URL. It is cached in // the process cache for 24 hours.
[ "fetchDiscoveryDoc", "fetches", "discovery", "document", "from", "given", "URL", ".", "It", "is", "cached", "in", "the", "process", "cache", "for", "24", "hours", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/protocol.go#L88-L112
7,735
luci/luci-go
server/auth/openid/protocol.go
validateStateToken
func validateStateToken(c context.Context, stateTok string) (map[string]string, error) { return openIDStateToken.Validate(c, stateTok, nil) }
go
func validateStateToken(c context.Context, stateTok string) (map[string]string, error) { return openIDStateToken.Validate(c, stateTok, nil) }
[ "func", "validateStateToken", "(", "c", "context", ".", "Context", ",", "stateTok", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "openIDStateToken", ".", "Validate", "(", "c", ",", "stateTok", ",", "nil", ")"...
// validateStateToken validates 'state' token passed to redirect_uri. Returns // whatever `state` was passed to authenticationURI.
[ "validateStateToken", "validates", "state", "token", "passed", "to", "redirect_uri", ".", "Returns", "whatever", "state", "was", "passed", "to", "authenticationURI", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/protocol.go#L154-L156
7,736
luci/luci-go
server/auth/openid/protocol.go
handleAuthorizationCode
func handleAuthorizationCode(c context.Context, cfg *Settings, code string) (uid string, u *auth.User, err error) { if cfg.ClientID == "" || cfg.ClientSecret == "" || cfg.RedirectURI == "" { return "", nil, ErrNotConfigured } // Validate the discover doc has necessary fields to proceed. discovery, err := fetchDiscoveryDoc(c, cfg.DiscoveryURL) switch { case err != nil: return "", nil, err case discovery.TokenEndpoint == "": return "", nil, errors.New("openid: bad discovery doc, empty token_endpoint") } // Prepare a request to exchange authorization code for the ID token. v := url.Values{} v.Set("code", code) v.Set("client_id", cfg.ClientID) v.Set("client_secret", cfg.ClientSecret) v.Set("redirect_uri", cfg.RedirectURI) v.Set("grant_type", "authorization_code") payload := v.Encode() // Send POST to the token endpoint with URL-encoded parameters to get back the // ID token. There's more stuff in the reply, we don't need it. var token struct { IDToken string `json:"id_token"` } req := internal.Request{ Method: "POST", URL: discovery.TokenEndpoint, Body: []byte(payload), Headers: map[string]string{ "Content-Type": "application/x-www-form-urlencoded", }, Out: &token, } if err := req.Do(c); err != nil { return "", nil, err } // Unpack the ID token to grab the user information from it. return userFromIDToken(c, token.IDToken, cfg, discovery) }
go
func handleAuthorizationCode(c context.Context, cfg *Settings, code string) (uid string, u *auth.User, err error) { if cfg.ClientID == "" || cfg.ClientSecret == "" || cfg.RedirectURI == "" { return "", nil, ErrNotConfigured } // Validate the discover doc has necessary fields to proceed. discovery, err := fetchDiscoveryDoc(c, cfg.DiscoveryURL) switch { case err != nil: return "", nil, err case discovery.TokenEndpoint == "": return "", nil, errors.New("openid: bad discovery doc, empty token_endpoint") } // Prepare a request to exchange authorization code for the ID token. v := url.Values{} v.Set("code", code) v.Set("client_id", cfg.ClientID) v.Set("client_secret", cfg.ClientSecret) v.Set("redirect_uri", cfg.RedirectURI) v.Set("grant_type", "authorization_code") payload := v.Encode() // Send POST to the token endpoint with URL-encoded parameters to get back the // ID token. There's more stuff in the reply, we don't need it. var token struct { IDToken string `json:"id_token"` } req := internal.Request{ Method: "POST", URL: discovery.TokenEndpoint, Body: []byte(payload), Headers: map[string]string{ "Content-Type": "application/x-www-form-urlencoded", }, Out: &token, } if err := req.Do(c); err != nil { return "", nil, err } // Unpack the ID token to grab the user information from it. return userFromIDToken(c, token.IDToken, cfg, discovery) }
[ "func", "handleAuthorizationCode", "(", "c", "context", ".", "Context", ",", "cfg", "*", "Settings", ",", "code", "string", ")", "(", "uid", "string", ",", "u", "*", "auth", ".", "User", ",", "err", "error", ")", "{", "if", "cfg", ".", "ClientID", "=...
// handleAuthorizationCode exchange `code` for user ID token and user profile.
[ "handleAuthorizationCode", "exchange", "code", "for", "user", "ID", "token", "and", "user", "profile", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/protocol.go#L159-L202
7,737
luci/luci-go
server/auth/openid/protocol.go
userFromIDToken
func userFromIDToken(c context.Context, token string, cfg *Settings, discovery *discoveryDoc) (uid string, u *auth.User, err error) { // Validate the discovery doc has necessary fields to proceed. switch { case discovery.Issuer == "": return "", nil, errors.New("openid: bad discovery doc, empty issuer") case discovery.JwksURI == "": return "", nil, errors.New("openid: bad discovery doc, empty jwks_uri") } // Grab the signing keys needed to verify the token. This is almost always // hitting the local process cache and thus must be fast. signingKeys, err := discovery.signingKeys(c) if err != nil { return "", nil, err } // Unpack the ID token to grab the user information from it. verifiedToken, err := VerifyIDToken(c, token, signingKeys, discovery.Issuer, cfg.ClientID) if err != nil { return "", nil, err } // Ignore non https:// URLs for pictures. We serve all pages over HTTPS and // don't want to break this rule just for a pretty picture. picture := verifiedToken.Picture if picture != "" && !strings.HasPrefix(picture, "https://") { picture = "" } // Build the identity string from the email. This essentially validates it. id, err := identity.MakeIdentity("user:" + verifiedToken.Email) if err != nil { return "", nil, err } return verifiedToken.Sub, &auth.User{ Identity: id, Email: verifiedToken.Email, Name: verifiedToken.Name, Picture: picture, }, nil }
go
func userFromIDToken(c context.Context, token string, cfg *Settings, discovery *discoveryDoc) (uid string, u *auth.User, err error) { // Validate the discovery doc has necessary fields to proceed. switch { case discovery.Issuer == "": return "", nil, errors.New("openid: bad discovery doc, empty issuer") case discovery.JwksURI == "": return "", nil, errors.New("openid: bad discovery doc, empty jwks_uri") } // Grab the signing keys needed to verify the token. This is almost always // hitting the local process cache and thus must be fast. signingKeys, err := discovery.signingKeys(c) if err != nil { return "", nil, err } // Unpack the ID token to grab the user information from it. verifiedToken, err := VerifyIDToken(c, token, signingKeys, discovery.Issuer, cfg.ClientID) if err != nil { return "", nil, err } // Ignore non https:// URLs for pictures. We serve all pages over HTTPS and // don't want to break this rule just for a pretty picture. picture := verifiedToken.Picture if picture != "" && !strings.HasPrefix(picture, "https://") { picture = "" } // Build the identity string from the email. This essentially validates it. id, err := identity.MakeIdentity("user:" + verifiedToken.Email) if err != nil { return "", nil, err } return verifiedToken.Sub, &auth.User{ Identity: id, Email: verifiedToken.Email, Name: verifiedToken.Name, Picture: picture, }, nil }
[ "func", "userFromIDToken", "(", "c", "context", ".", "Context", ",", "token", "string", ",", "cfg", "*", "Settings", ",", "discovery", "*", "discoveryDoc", ")", "(", "uid", "string", ",", "u", "*", "auth", ".", "User", ",", "err", "error", ")", "{", ...
// userFromIDToken validates the ID token and extracts user information from it.
[ "userFromIDToken", "validates", "the", "ID", "token", "and", "extracts", "user", "information", "from", "it", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/protocol.go#L205-L246
7,738
luci/luci-go
lucicfg/output.go
ConfigSets
func (o Output) ConfigSets() []ConfigSet { names := make([]string, 0, len(o.Roots)) for name := range o.Roots { names = append(names, name) } sort.Strings(names) // order is important for logs cs := make([]ConfigSet, len(names)) for i, nm := range names { root := o.Roots[nm] // Normalize in preparation for prefix matching. root = path.Clean(root) if root == "." { root = "" // match EVERYTHING } else { root = root + "/" // match only what's under 'root/...' } files := map[string][]byte{} for f, body := range o.Data { f = path.Clean(f) if strings.HasPrefix(f, root) { files[f[len(root):]] = body } } cs[i] = ConfigSet{Name: nm, Data: files} } return cs }
go
func (o Output) ConfigSets() []ConfigSet { names := make([]string, 0, len(o.Roots)) for name := range o.Roots { names = append(names, name) } sort.Strings(names) // order is important for logs cs := make([]ConfigSet, len(names)) for i, nm := range names { root := o.Roots[nm] // Normalize in preparation for prefix matching. root = path.Clean(root) if root == "." { root = "" // match EVERYTHING } else { root = root + "/" // match only what's under 'root/...' } files := map[string][]byte{} for f, body := range o.Data { f = path.Clean(f) if strings.HasPrefix(f, root) { files[f[len(root):]] = body } } cs[i] = ConfigSet{Name: nm, Data: files} } return cs }
[ "func", "(", "o", "Output", ")", "ConfigSets", "(", ")", "[", "]", "ConfigSet", "{", "names", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "o", ".", "Roots", ")", ")", "\n", "for", "name", ":=", "range", "o", ".", "Roots", ...
// ConfigSets partitions this output into 0 or more config sets based on Roots.
[ "ConfigSets", "partitions", "this", "output", "into", "0", "or", "more", "config", "sets", "based", "on", "Roots", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/output.go#L57-L88
7,739
luci/luci-go
lucicfg/output.go
Write
func (o Output) Write(dir string) (changed, unchanged []string, err error) { // First pass: populate 'changed' and 'unchanged', so we have a valid result // even when failing midway through writes. changed, unchanged = o.Compare(dir) // Second pass: update changed files. for _, name := range changed { path := filepath.Join(dir, filepath.FromSlash(name)) if err = os.MkdirAll(filepath.Dir(path), 0777); err != nil { return } if err = ioutil.WriteFile(path, o.Data[name], 0666); err != nil { return } } return }
go
func (o Output) Write(dir string) (changed, unchanged []string, err error) { // First pass: populate 'changed' and 'unchanged', so we have a valid result // even when failing midway through writes. changed, unchanged = o.Compare(dir) // Second pass: update changed files. for _, name := range changed { path := filepath.Join(dir, filepath.FromSlash(name)) if err = os.MkdirAll(filepath.Dir(path), 0777); err != nil { return } if err = ioutil.WriteFile(path, o.Data[name], 0666); err != nil { return } } return }
[ "func", "(", "o", "Output", ")", "Write", "(", "dir", "string", ")", "(", "changed", ",", "unchanged", "[", "]", "string", ",", "err", "error", ")", "{", "// First pass: populate 'changed' and 'unchanged', so we have a valid result", "// even when failing midway through...
// Write updates files on disk to match the output. // // Returns a list of updated files and a list of files that are already // up-to-date, same as Compare. // // Creates missing directories. Not atomic. All files have mode 0666.
[ "Write", "updates", "files", "on", "disk", "to", "match", "the", "output", ".", "Returns", "a", "list", "of", "updated", "files", "and", "a", "list", "of", "files", "that", "are", "already", "up", "-", "to", "-", "date", "same", "as", "Compare", ".", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/output.go#L114-L131
7,740
luci/luci-go
lucicfg/output.go
Digests
func (o Output) Digests() map[string]string { out := make(map[string]string, len(o.Data)) for file, body := range o.Data { out[file] = hex.EncodeToString(blobDigest(body)) } return out }
go
func (o Output) Digests() map[string]string { out := make(map[string]string, len(o.Data)) for file, body := range o.Data { out[file] = hex.EncodeToString(blobDigest(body)) } return out }
[ "func", "(", "o", "Output", ")", "Digests", "(", ")", "map", "[", "string", "]", "string", "{", "out", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "o", ".", "Data", ")", ")", "\n", "for", "file", ",", "body", ":=", ...
// Digests returns a map "file name -> hex SHA256 of its body".
[ "Digests", "returns", "a", "map", "file", "name", "-", ">", "hex", "SHA256", "of", "its", "body", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/output.go#L134-L140
7,741
luci/luci-go
lucicfg/output.go
Files
func (o Output) Files() []string { f := make([]string, 0, len(o.Data)) for k := range o.Data { f = append(f, k) } sort.Strings(f) return f }
go
func (o Output) Files() []string { f := make([]string, 0, len(o.Data)) for k := range o.Data { f = append(f, k) } sort.Strings(f) return f }
[ "func", "(", "o", "Output", ")", "Files", "(", ")", "[", "]", "string", "{", "f", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "o", ".", "Data", ")", ")", "\n", "for", "k", ":=", "range", "o", ".", "Data", "{", "f", "...
// Files returns a sorted list of file names in the output.
[ "Files", "returns", "a", "sorted", "list", "of", "file", "names", "in", "the", "output", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/output.go#L143-L150
7,742
luci/luci-go
lucicfg/output.go
DebugDump
func (o Output) DebugDump() { for _, f := range o.Files() { fmt.Println("--------------------------------------------------") fmt.Println(f) fmt.Println("--------------------------------------------------") fmt.Print(string(o.Data[f])) fmt.Println("--------------------------------------------------") } }
go
func (o Output) DebugDump() { for _, f := range o.Files() { fmt.Println("--------------------------------------------------") fmt.Println(f) fmt.Println("--------------------------------------------------") fmt.Print(string(o.Data[f])) fmt.Println("--------------------------------------------------") } }
[ "func", "(", "o", "Output", ")", "DebugDump", "(", ")", "{", "for", "_", ",", "f", ":=", "range", "o", ".", "Files", "(", ")", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "fmt", ".", "Println", "(", "f", ")", "\n", "fmt", ".", "...
// DebugDump writes the output to stdout in a format useful for debugging.
[ "DebugDump", "writes", "the", "output", "to", "stdout", "in", "a", "format", "useful", "for", "debugging", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/output.go#L153-L161
7,743
luci/luci-go
lucicfg/generator.go
Generate
func Generate(ctx context.Context, in Inputs) (*State, error) { state := &State{Inputs: in} ctx = withState(ctx, state) // All available functions implemented in go. predeclared := starlark.StringDict{ // Part of public API of the generator. "fail": builtins.Fail, "proto": starlarkproto.ProtoLib()["proto"], "stacktrace": builtins.Stacktrace, "struct": builtins.Struct, "to_json": builtins.ToJSON, // '__native__' is NOT public API. It should be used only through public // @stdlib functions. "__native__": native(starlark.StringDict{ "ctor": builtins.Ctor, "genstruct": builtins.GenStruct, "re_submatches": builtins.RegexpMatcher("submatches"), }), } for k, v := range in.testPredeclared { predeclared[k] = v } // Expose @stdlib, @proto and __main__ package. All have no externally // observable state of their own, but they call low-level __native__.* // functions that manipulate 'state' by getting it through the context. pkgs := embeddedPackages() pkgs[interpreter.MainPkg] = in.Code pkgs["proto"] = protoLoader() // see protos.go // Capture details of fail(...) calls happening inside Starlark code. failures := builtins.FailureCollector{} // Execute the config script in this environment. Return errors unwrapped so // that callers can sniff out various sorts of Starlark errors. intr := interpreter.Interpreter{ Predeclared: predeclared, Packages: pkgs, PreExec: func(th *starlark.Thread, pkg, mod string) { state.vars.OpenScope(th) }, PostExec: func(th *starlark.Thread, pkg, mod string) { state.vars.CloseScope(th) }, ThreadModifier: func(th *starlark.Thread) { if !in.testDisableFailureCollector { failures.Install(th) } if in.testThreadModifier != nil { in.testThreadModifier(th) } }, } // Load builtins.star, and then execute the user-supplied script. var err error if err = intr.Init(ctx); err == nil { _, err = intr.ExecModule(ctx, interpreter.MainPkg, in.Entry) } if err != nil { if f := failures.LatestFailure(); f != nil { err = f // prefer this error, it has custom stack trace } return nil, state.err(err) } // Executing the script (with all its dependencies) populated the graph. // Finalize it. This checks there are no dangling edges, freezes the graph, // and makes it queryable, so generator callbacks can traverse it. if errs := state.graph.Finalize(); len(errs) != 0 { return nil, state.err(errs...) } // The script registered a bunch of callbacks that take the graph and // transform it into actual output config files. Run these callbacks now. genCtx := newGenCtx() if errs := state.generators.call(intr.Thread(ctx), genCtx); len(errs) != 0 { return nil, state.err(errs...) } output, err := genCtx.assembleOutput(!in.testOmitHeader) if err != nil { return nil, state.err(err) } state.Output = output if len(state.errors) != 0 { return nil, state.errors } return state, nil }
go
func Generate(ctx context.Context, in Inputs) (*State, error) { state := &State{Inputs: in} ctx = withState(ctx, state) // All available functions implemented in go. predeclared := starlark.StringDict{ // Part of public API of the generator. "fail": builtins.Fail, "proto": starlarkproto.ProtoLib()["proto"], "stacktrace": builtins.Stacktrace, "struct": builtins.Struct, "to_json": builtins.ToJSON, // '__native__' is NOT public API. It should be used only through public // @stdlib functions. "__native__": native(starlark.StringDict{ "ctor": builtins.Ctor, "genstruct": builtins.GenStruct, "re_submatches": builtins.RegexpMatcher("submatches"), }), } for k, v := range in.testPredeclared { predeclared[k] = v } // Expose @stdlib, @proto and __main__ package. All have no externally // observable state of their own, but they call low-level __native__.* // functions that manipulate 'state' by getting it through the context. pkgs := embeddedPackages() pkgs[interpreter.MainPkg] = in.Code pkgs["proto"] = protoLoader() // see protos.go // Capture details of fail(...) calls happening inside Starlark code. failures := builtins.FailureCollector{} // Execute the config script in this environment. Return errors unwrapped so // that callers can sniff out various sorts of Starlark errors. intr := interpreter.Interpreter{ Predeclared: predeclared, Packages: pkgs, PreExec: func(th *starlark.Thread, pkg, mod string) { state.vars.OpenScope(th) }, PostExec: func(th *starlark.Thread, pkg, mod string) { state.vars.CloseScope(th) }, ThreadModifier: func(th *starlark.Thread) { if !in.testDisableFailureCollector { failures.Install(th) } if in.testThreadModifier != nil { in.testThreadModifier(th) } }, } // Load builtins.star, and then execute the user-supplied script. var err error if err = intr.Init(ctx); err == nil { _, err = intr.ExecModule(ctx, interpreter.MainPkg, in.Entry) } if err != nil { if f := failures.LatestFailure(); f != nil { err = f // prefer this error, it has custom stack trace } return nil, state.err(err) } // Executing the script (with all its dependencies) populated the graph. // Finalize it. This checks there are no dangling edges, freezes the graph, // and makes it queryable, so generator callbacks can traverse it. if errs := state.graph.Finalize(); len(errs) != 0 { return nil, state.err(errs...) } // The script registered a bunch of callbacks that take the graph and // transform it into actual output config files. Run these callbacks now. genCtx := newGenCtx() if errs := state.generators.call(intr.Thread(ctx), genCtx); len(errs) != 0 { return nil, state.err(errs...) } output, err := genCtx.assembleOutput(!in.testOmitHeader) if err != nil { return nil, state.err(err) } state.Output = output if len(state.errors) != 0 { return nil, state.errors } return state, nil }
[ "func", "Generate", "(", "ctx", "context", ".", "Context", ",", "in", "Inputs", ")", "(", "*", "State", ",", "error", ")", "{", "state", ":=", "&", "State", "{", "Inputs", ":", "in", "}", "\n", "ctx", "=", "withState", "(", "ctx", ",", "state", "...
// Generate interprets the high-level config. // // Returns a multi-error with all captured errors. Some of them may implement // BacktracableError interface.
[ "Generate", "interprets", "the", "high", "-", "level", "config", ".", "Returns", "a", "multi", "-", "error", "with", "all", "captured", "errors", ".", "Some", "of", "them", "may", "implement", "BacktracableError", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/generator.go#L54-L143
7,744
luci/luci-go
logdog/client/butlerlib/streamproto/tag.go
SortedKeys
func (t TagMap) SortedKeys() []string { if len(t) == 0 { return nil } keys := make([]string, 0, len(t)) for k := range t { keys = append(keys, k) } sort.Strings(keys) return keys }
go
func (t TagMap) SortedKeys() []string { if len(t) == 0 { return nil } keys := make([]string, 0, len(t)) for k := range t { keys = append(keys, k) } sort.Strings(keys) return keys }
[ "func", "(", "t", "TagMap", ")", "SortedKeys", "(", ")", "[", "]", "string", "{", "if", "len", "(", "t", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "t", ...
// SortedKeys returns a sorted slice of the keys in a TagMap.
[ "SortedKeys", "returns", "a", "sorted", "slice", "of", "the", "keys", "in", "a", "TagMap", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamproto/tag.go#L46-L57
7,745
luci/luci-go
common/proto/gitiles/gitiles.mock.pb.go
NewMockGitilesClient
func NewMockGitilesClient(ctrl *gomock.Controller) *MockGitilesClient { mock := &MockGitilesClient{ctrl: ctrl} mock.recorder = &MockGitilesClientMockRecorder{mock} return mock }
go
func NewMockGitilesClient(ctrl *gomock.Controller) *MockGitilesClient { mock := &MockGitilesClient{ctrl: ctrl} mock.recorder = &MockGitilesClientMockRecorder{mock} return mock }
[ "func", "NewMockGitilesClient", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockGitilesClient", "{", "mock", ":=", "&", "MockGitilesClient", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockGitilesClientMockRecorder", ...
// NewMockGitilesClient creates a new mock instance
[ "NewMockGitilesClient", "creates", "a", "new", "mock", "instance" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/gitiles/gitiles.mock.pb.go#L26-L30
7,746
luci/luci-go
common/proto/gitiles/gitiles.mock.pb.go
NewMockGitilesServer
func NewMockGitilesServer(ctrl *gomock.Controller) *MockGitilesServer { mock := &MockGitilesServer{ctrl: ctrl} mock.recorder = &MockGitilesServerMockRecorder{mock} return mock }
go
func NewMockGitilesServer(ctrl *gomock.Controller) *MockGitilesServer { mock := &MockGitilesServer{ctrl: ctrl} mock.recorder = &MockGitilesServerMockRecorder{mock} return mock }
[ "func", "NewMockGitilesServer", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockGitilesServer", "{", "mock", ":=", "&", "MockGitilesServer", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockGitilesServerMockRecorder", ...
// NewMockGitilesServer creates a new mock instance
[ "NewMockGitilesServer", "creates", "a", "new", "mock", "instance" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/gitiles/gitiles.mock.pb.go#L103-L107
7,747
luci/luci-go
client/flagpb/unmarshal.go
UnmarshalUntyped
func UnmarshalUntyped(flags []string, desc *descriptor.DescriptorProto, resolver Resolver) (map[string]interface{}, error) { p := parser{resolver} return p.parse(flags, desc) }
go
func UnmarshalUntyped(flags []string, desc *descriptor.DescriptorProto, resolver Resolver) (map[string]interface{}, error) { p := parser{resolver} return p.parse(flags, desc) }
[ "func", "UnmarshalUntyped", "(", "flags", "[", "]", "string", ",", "desc", "*", "descriptor", ".", "DescriptorProto", ",", "resolver", "Resolver", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "p", ":=", "parser", ...
// UnmarshalUntyped unmarshals a key-value map from flags // using a protobuf message descriptor.
[ "UnmarshalUntyped", "unmarshals", "a", "key", "-", "value", "map", "from", "flags", "using", "a", "protobuf", "message", "descriptor", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/flagpb/unmarshal.go#L62-L65
7,748
luci/luci-go
client/flagpb/unmarshal.go
splitKeyValuePair
func (p *parser) splitKeyValuePair(s string) (key, value string, hasValue bool) { parts := strings.SplitN(s, "=", 2) switch len(parts) { case 1: key = s case 2: key = parts[0] value = parts[1] hasValue = true } return }
go
func (p *parser) splitKeyValuePair(s string) (key, value string, hasValue bool) { parts := strings.SplitN(s, "=", 2) switch len(parts) { case 1: key = s case 2: key = parts[0] value = parts[1] hasValue = true } return }
[ "func", "(", "p", "*", "parser", ")", "splitKeyValuePair", "(", "s", "string", ")", "(", "key", ",", "value", "string", ",", "hasValue", "bool", ")", "{", "parts", ":=", "strings", ".", "SplitN", "(", "s", ",", "\"", "\"", ",", "2", ")", "\n", "s...
// splitKeyValuePair splits a key value pair key=value if there is equals sign.
[ "splitKeyValuePair", "splits", "a", "key", "value", "pair", "key", "=", "value", "if", "there", "is", "equals", "sign", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/flagpb/unmarshal.go#L361-L372
7,749
luci/luci-go
client/flagpb/unmarshal.go
parseEnum
func parseEnum(enum *descriptor.EnumDescriptorProto, member string) (int32, error) { i := descutil.FindEnumValue(enum, member) if i < 0 { // Is member the number? if number, err := strconv.ParseInt(member, 10, 32); err == nil { i = descutil.FindValueByNumber(enum, int32(number)) } } if i < 0 { return 0, fmt.Errorf("invalid value %q for enum %s", member, enum.GetName()) } return enum.Value[i].GetNumber(), nil }
go
func parseEnum(enum *descriptor.EnumDescriptorProto, member string) (int32, error) { i := descutil.FindEnumValue(enum, member) if i < 0 { // Is member the number? if number, err := strconv.ParseInt(member, 10, 32); err == nil { i = descutil.FindValueByNumber(enum, int32(number)) } } if i < 0 { return 0, fmt.Errorf("invalid value %q for enum %s", member, enum.GetName()) } return enum.Value[i].GetNumber(), nil }
[ "func", "parseEnum", "(", "enum", "*", "descriptor", ".", "EnumDescriptorProto", ",", "member", "string", ")", "(", "int32", ",", "error", ")", "{", "i", ":=", "descutil", ".", "FindEnumValue", "(", "enum", ",", "member", ")", "\n", "if", "i", "<", "0"...
// parseEnum returns the number of an enum member, which can be name or number.
[ "parseEnum", "returns", "the", "number", "of", "an", "enum", "member", "which", "can", "be", "name", "or", "number", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/flagpb/unmarshal.go#L375-L387
7,750
luci/luci-go
buildbucket/cli/log.go
getSteps
func (r *logRun) getSteps(ctx context.Context) ([]*pb.Step, error) { r.getBuild.Fields = &field_mask.FieldMask{Paths: []string{"steps"}} build, err := r.client.GetBuild(ctx, r.getBuild, prpc.ExpectedCode(codes.NotFound)) switch status.Code(err) { case codes.OK: return build.Steps, nil case codes.NotFound: return nil, fmt.Errorf("build not found") default: return nil, err } }
go
func (r *logRun) getSteps(ctx context.Context) ([]*pb.Step, error) { r.getBuild.Fields = &field_mask.FieldMask{Paths: []string{"steps"}} build, err := r.client.GetBuild(ctx, r.getBuild, prpc.ExpectedCode(codes.NotFound)) switch status.Code(err) { case codes.OK: return build.Steps, nil case codes.NotFound: return nil, fmt.Errorf("build not found") default: return nil, err } }
[ "func", "(", "r", "*", "logRun", ")", "getSteps", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "*", "pb", ".", "Step", ",", "error", ")", "{", "r", ".", "getBuild", ".", "Fields", "=", "&", "field_mask", ".", "FieldMask", "{", "Path...
// getSteps fetches steps of the build.
[ "getSteps", "fetches", "steps", "of", "the", "build", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/log.go#L161-L172
7,751
luci/luci-go
buildbucket/cli/log.go
Next
func (m *logMultiplexer) Next() (chanIndex int, log *logpb.LogEntry, err error) { if m.heads == nil { // initialization m.heads = make([]logAndErr, len(m.Chans)) for i := range m.heads { m.heads[i] = <-m.Chans[i].c } } // Choose the earliest one. // Note: using heap is overkill here. // Most of the time we deal with only two logs. earliest := -1 earliestTime := time.Time{} for i, h := range m.heads { if h.err == io.EOF { continue } if h.err != nil { return 0, nil, h.err } curTime := m.Chans[i].start if h.TimeOffset != nil { offset, err := ptypes.Duration(h.TimeOffset) if err != nil { return 0, nil, err } curTime = curTime.Add(offset) } isEarlier := earliest == -1 || curTime.Before(earliestTime) || (curTime.Equal(earliestTime) && h.PrefixIndex < m.heads[earliest].PrefixIndex) if isEarlier { earliest = i earliestTime = curTime } } if earliest == -1 { // all finished return 0, nil, io.EOF } // Call f and replace the entry with the freshest one from the same // channel. earliestEntry := m.heads[earliest].LogEntry m.heads[earliest] = <-m.Chans[earliest].c return earliest, earliestEntry, nil }
go
func (m *logMultiplexer) Next() (chanIndex int, log *logpb.LogEntry, err error) { if m.heads == nil { // initialization m.heads = make([]logAndErr, len(m.Chans)) for i := range m.heads { m.heads[i] = <-m.Chans[i].c } } // Choose the earliest one. // Note: using heap is overkill here. // Most of the time we deal with only two logs. earliest := -1 earliestTime := time.Time{} for i, h := range m.heads { if h.err == io.EOF { continue } if h.err != nil { return 0, nil, h.err } curTime := m.Chans[i].start if h.TimeOffset != nil { offset, err := ptypes.Duration(h.TimeOffset) if err != nil { return 0, nil, err } curTime = curTime.Add(offset) } isEarlier := earliest == -1 || curTime.Before(earliestTime) || (curTime.Equal(earliestTime) && h.PrefixIndex < m.heads[earliest].PrefixIndex) if isEarlier { earliest = i earliestTime = curTime } } if earliest == -1 { // all finished return 0, nil, io.EOF } // Call f and replace the entry with the freshest one from the same // channel. earliestEntry := m.heads[earliest].LogEntry m.heads[earliest] = <-m.Chans[earliest].c return earliest, earliestEntry, nil }
[ "func", "(", "m", "*", "logMultiplexer", ")", "Next", "(", ")", "(", "chanIndex", "int", ",", "log", "*", "logpb", ".", "LogEntry", ",", "err", "error", ")", "{", "if", "m", ".", "heads", "==", "nil", "{", "// initialization", "m", ".", "heads", "=...
// Next returns the next log entry. // Returns io.EOF if there is no next log entry.
[ "Next", "returns", "the", "next", "log", "entry", ".", "Returns", "io", ".", "EOF", "if", "there", "is", "no", "next", "log", "entry", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/log.go#L287-L336
7,752
luci/luci-go
scheduler/appengine/engine/controller.go
controllerForInvocation
func controllerForInvocation(c context.Context, e *engineImpl, inv *Invocation) (*taskController, error) { ctl := &taskController{ ctx: c, eng: e, saved: *inv, } var err error if ctl.task, err = e.cfg.Catalog.UnmarshalTask(c, inv.Task); err != nil { return ctl, fmt.Errorf("failed to unmarshal the task - %s", err) } if ctl.manager = e.cfg.Catalog.GetTaskManager(ctl.task); ctl.manager == nil { return ctl, fmt.Errorf("TaskManager is unexpectedly missing") } if err = ctl.populateState(); err != nil { return ctl, fmt.Errorf("failed to construct task.State - %s", err) } if ctl.request, err = getRequestFromInv(&ctl.saved); err != nil { return ctl, fmt.Errorf("failed to construct task.Request - %s", err) } return ctl, nil }
go
func controllerForInvocation(c context.Context, e *engineImpl, inv *Invocation) (*taskController, error) { ctl := &taskController{ ctx: c, eng: e, saved: *inv, } var err error if ctl.task, err = e.cfg.Catalog.UnmarshalTask(c, inv.Task); err != nil { return ctl, fmt.Errorf("failed to unmarshal the task - %s", err) } if ctl.manager = e.cfg.Catalog.GetTaskManager(ctl.task); ctl.manager == nil { return ctl, fmt.Errorf("TaskManager is unexpectedly missing") } if err = ctl.populateState(); err != nil { return ctl, fmt.Errorf("failed to construct task.State - %s", err) } if ctl.request, err = getRequestFromInv(&ctl.saved); err != nil { return ctl, fmt.Errorf("failed to construct task.Request - %s", err) } return ctl, nil }
[ "func", "controllerForInvocation", "(", "c", "context", ".", "Context", ",", "e", "*", "engineImpl", ",", "inv", "*", "Invocation", ")", "(", "*", "taskController", ",", "error", ")", "{", "ctl", ":=", "&", "taskController", "{", "ctx", ":", "c", ",", ...
// controllerForInvocation returns new instance of taskController configured // to work with given invocation. // // If task definition can't be deserialized, returns both controller and error.
[ "controllerForInvocation", "returns", "new", "instance", "of", "taskController", "configured", "to", "work", "with", "given", "invocation", ".", "If", "task", "definition", "can", "t", "be", "deserialized", "returns", "both", "controller", "and", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/controller.go#L88-L108
7,753
luci/luci-go
scheduler/appengine/engine/controller.go
populateState
func (ctl *taskController) populateState() error { ctl.state = task.State{ Status: ctl.saved.Status, ViewURL: ctl.saved.ViewURL, TaskData: append([]byte(nil), ctl.saved.TaskData...), // copy } return nil }
go
func (ctl *taskController) populateState() error { ctl.state = task.State{ Status: ctl.saved.Status, ViewURL: ctl.saved.ViewURL, TaskData: append([]byte(nil), ctl.saved.TaskData...), // copy } return nil }
[ "func", "(", "ctl", "*", "taskController", ")", "populateState", "(", ")", "error", "{", "ctl", ".", "state", "=", "task", ".", "State", "{", "Status", ":", "ctl", ".", "saved", ".", "Status", ",", "ViewURL", ":", "ctl", ".", "saved", ".", "ViewURL",...
// populateState populates 'state' using data in 'saved'.
[ "populateState", "populates", "state", "using", "data", "in", "saved", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/controller.go#L111-L118
7,754
luci/luci-go
scheduler/appengine/engine/controller.go
DebugLog
func (ctl *taskController) DebugLog(format string, args ...interface{}) { logging.Infof(ctl.ctx, format, args...) debugLog(ctl.ctx, &ctl.debugLog, format, args...) }
go
func (ctl *taskController) DebugLog(format string, args ...interface{}) { logging.Infof(ctl.ctx, format, args...) debugLog(ctl.ctx, &ctl.debugLog, format, args...) }
[ "func", "(", "ctl", "*", "taskController", ")", "DebugLog", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "logging", ".", "Infof", "(", "ctl", ".", "ctx", ",", "format", ",", "args", "...", ")", "\n", "debugLog", "(", ...
// DebugLog is part of task.Controller interface.
[ "DebugLog", "is", "part", "of", "task", ".", "Controller", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/controller.go#L174-L177
7,755
luci/luci-go
scheduler/appengine/engine/controller.go
AddTimer
func (ctl *taskController) AddTimer(ctx context.Context, delay time.Duration, title string, payload []byte) { // ID for the new timer. It is guaranteed to be unique when we land the // transaction because all ctl.saved modifications are serialized in time (see // MutationsCount checks in Save), and we include serial number of such // modification into the timer id (and suffix it with the index of the timer // emitted by this particular modification). If two modification happen // concurrently, they may temporary get same timer ID, but only one will // actually land. timerID := fmt.Sprintf("%s:%d:%d:%d", ctl.JobID(), ctl.InvocationID(), ctl.saved.MutationsCount, len(ctl.timers)) ctl.DebugLog("Scheduling timer %q (%s) after %s", title, timerID, delay) now := clock.Now(ctx) ctl.timers = append(ctl.timers, &internal.Timer{ Id: timerID, Created: google.NewTimestamp(now), Eta: google.NewTimestamp(now.Add(delay)), Title: title, Payload: payload, }) }
go
func (ctl *taskController) AddTimer(ctx context.Context, delay time.Duration, title string, payload []byte) { // ID for the new timer. It is guaranteed to be unique when we land the // transaction because all ctl.saved modifications are serialized in time (see // MutationsCount checks in Save), and we include serial number of such // modification into the timer id (and suffix it with the index of the timer // emitted by this particular modification). If two modification happen // concurrently, they may temporary get same timer ID, but only one will // actually land. timerID := fmt.Sprintf("%s:%d:%d:%d", ctl.JobID(), ctl.InvocationID(), ctl.saved.MutationsCount, len(ctl.timers)) ctl.DebugLog("Scheduling timer %q (%s) after %s", title, timerID, delay) now := clock.Now(ctx) ctl.timers = append(ctl.timers, &internal.Timer{ Id: timerID, Created: google.NewTimestamp(now), Eta: google.NewTimestamp(now.Add(delay)), Title: title, Payload: payload, }) }
[ "func", "(", "ctl", "*", "taskController", ")", "AddTimer", "(", "ctx", "context", ".", "Context", ",", "delay", "time", ".", "Duration", ",", "title", "string", ",", "payload", "[", "]", "byte", ")", "{", "// ID for the new timer. It is guaranteed to be unique ...
// AddTimer is part of Controller interface.
[ "AddTimer", "is", "part", "of", "Controller", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/controller.go#L180-L202
7,756
luci/luci-go
scheduler/appengine/engine/controller.go
PrepareTopic
func (ctl *taskController) PrepareTopic(ctx context.Context, publisher string) (topic string, token string, err error) { return ctl.eng.prepareTopic(ctx, &topicParams{ jobID: ctl.JobID(), invID: ctl.InvocationID(), manager: ctl.manager, publisher: publisher, }) }
go
func (ctl *taskController) PrepareTopic(ctx context.Context, publisher string) (topic string, token string, err error) { return ctl.eng.prepareTopic(ctx, &topicParams{ jobID: ctl.JobID(), invID: ctl.InvocationID(), manager: ctl.manager, publisher: publisher, }) }
[ "func", "(", "ctl", "*", "taskController", ")", "PrepareTopic", "(", "ctx", "context", ".", "Context", ",", "publisher", "string", ")", "(", "topic", "string", ",", "token", "string", ",", "err", "error", ")", "{", "return", "ctl", ".", "eng", ".", "pr...
// PrepareTopic is part of task.Controller interface.
[ "PrepareTopic", "is", "part", "of", "task", ".", "Controller", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/controller.go#L205-L212
7,757
luci/luci-go
scheduler/appengine/engine/controller.go
GetClient
func (ctl *taskController) GetClient(ctx context.Context, opts ...auth.RPCOption) (*http.Client, error) { opts = append(opts, auth.WithProject(ctl.saved.GetProjectID())) t, err := auth.GetRPCTransport(ctx, auth.AsProject, opts...) if err != nil { return nil, err } return &http.Client{Transport: t}, nil }
go
func (ctl *taskController) GetClient(ctx context.Context, opts ...auth.RPCOption) (*http.Client, error) { opts = append(opts, auth.WithProject(ctl.saved.GetProjectID())) t, err := auth.GetRPCTransport(ctx, auth.AsProject, opts...) if err != nil { return nil, err } return &http.Client{Transport: t}, nil }
[ "func", "(", "ctl", "*", "taskController", ")", "GetClient", "(", "ctx", "context", ".", "Context", ",", "opts", "...", "auth", ".", "RPCOption", ")", "(", "*", "http", ".", "Client", ",", "error", ")", "{", "opts", "=", "append", "(", "opts", ",", ...
// GetClient is part of task.Controller interface
[ "GetClient", "is", "part", "of", "task", ".", "Controller", "interface" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/controller.go#L215-L222
7,758
luci/luci-go
scheduler/appengine/engine/controller.go
EmitTrigger
func (ctl *taskController) EmitTrigger(ctx context.Context, trigger *internal.Trigger) { ctl.DebugLog("Emitting a trigger %s", trigger.Id) trigger.JobId = ctl.JobID() trigger.InvocationId = ctl.InvocationID() // See docs for internal.Trigger proto. Tuple (created, order_in_batch) used // for casual ordering of triggers emitted by an invocation. Callers of // EmitTrigger are free to override this by supplying their own timestamp. In // such case they also should provide order_in_batch. Otherwise we build the // tuple for them based on the order of EmitTrigger calls. if trigger.Created == nil { trigger.Created = google.NewTimestamp(clock.Now(ctx)) trigger.OrderInBatch = ctl.triggerIndex } ctl.triggers = append(ctl.triggers, trigger) ctl.triggerIndex++ // note: this is NOT reset in Save, unlike ctl.triggers. }
go
func (ctl *taskController) EmitTrigger(ctx context.Context, trigger *internal.Trigger) { ctl.DebugLog("Emitting a trigger %s", trigger.Id) trigger.JobId = ctl.JobID() trigger.InvocationId = ctl.InvocationID() // See docs for internal.Trigger proto. Tuple (created, order_in_batch) used // for casual ordering of triggers emitted by an invocation. Callers of // EmitTrigger are free to override this by supplying their own timestamp. In // such case they also should provide order_in_batch. Otherwise we build the // tuple for them based on the order of EmitTrigger calls. if trigger.Created == nil { trigger.Created = google.NewTimestamp(clock.Now(ctx)) trigger.OrderInBatch = ctl.triggerIndex } ctl.triggers = append(ctl.triggers, trigger) ctl.triggerIndex++ // note: this is NOT reset in Save, unlike ctl.triggers. }
[ "func", "(", "ctl", "*", "taskController", ")", "EmitTrigger", "(", "ctx", "context", ".", "Context", ",", "trigger", "*", "internal", ".", "Trigger", ")", "{", "ctl", ".", "DebugLog", "(", "\"", "\"", ",", "trigger", ".", "Id", ")", "\n", "trigger", ...
// EmitTrigger is part of task.Controller interface.
[ "EmitTrigger", "is", "part", "of", "task", ".", "Controller", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/controller.go#L225-L242
7,759
luci/luci-go
common/tsmon/metric/http_transport.go
RoundTrip
func (t *instrumentedHTTPRoundTripper) RoundTrip(origReq *http.Request) (*http.Response, error) { req := *origReq // If a request body was provided, wrap it in a CountingReader so we can see // how big it was after it's been sent. var requestBodyReader *iotools.CountingReader if req.Body != nil { requestBodyReader = &iotools.CountingReader{Reader: req.Body} req.Body = struct { io.Reader io.Closer }{requestBodyReader, req.Body} } start := clock.Now(t.ctx) resp, err := t.base.RoundTrip(&req) duration := clock.Now(t.ctx).Sub(start) var requestBytes int64 if requestBodyReader != nil { requestBytes = requestBodyReader.Count } var code int var responseBytes int64 if resp != nil { code = resp.StatusCode responseBytes = resp.ContentLength } UpdateHTTPMetrics(t.ctx, req.URL.Host, t.client, code, duration, requestBytes, responseBytes) return resp, err }
go
func (t *instrumentedHTTPRoundTripper) RoundTrip(origReq *http.Request) (*http.Response, error) { req := *origReq // If a request body was provided, wrap it in a CountingReader so we can see // how big it was after it's been sent. var requestBodyReader *iotools.CountingReader if req.Body != nil { requestBodyReader = &iotools.CountingReader{Reader: req.Body} req.Body = struct { io.Reader io.Closer }{requestBodyReader, req.Body} } start := clock.Now(t.ctx) resp, err := t.base.RoundTrip(&req) duration := clock.Now(t.ctx).Sub(start) var requestBytes int64 if requestBodyReader != nil { requestBytes = requestBodyReader.Count } var code int var responseBytes int64 if resp != nil { code = resp.StatusCode responseBytes = resp.ContentLength } UpdateHTTPMetrics(t.ctx, req.URL.Host, t.client, code, duration, requestBytes, responseBytes) return resp, err }
[ "func", "(", "t", "*", "instrumentedHTTPRoundTripper", ")", "RoundTrip", "(", "origReq", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "req", ":=", "*", "origReq", "\n\n", "// If a request body was provided, wrap ...
// RoundTrip implements http.RoundTripper.
[ "RoundTrip", "implements", "http", ".", "RoundTripper", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/metric/http_transport.go#L38-L71
7,760
luci/luci-go
logdog/server/service/config/cache.go
Get
func (mc *MessageCache) Get(c context.Context, cset config.Set, path string, msg proto.Message) ( proto.Message, error) { // If no Lifetime is configured, bypass the cache layer. if mc.Lifetime <= 0 { err := mc.GetUncached(c, cset, path, msg) return msg, err } key := messageCacheKey{cset, path} // Load the value from our cache. First, though, take out a lock on this // specific config key. This will prevent multiple concurrent accesses from // slamming the config service, particularly at startup. var v interface{} var err error v, err = messageCache.LRU(c).GetOrCreate(c, key, func() (interface{}, time.Duration, error) { // Not in cache or expired. Reload... if err := mc.GetUncached(c, cset, path, msg); err != nil { return nil, 0, err } return proto.Clone(msg), mc.Lifetime, nil }) if err != nil { return nil, err } return v.(proto.Message), nil }
go
func (mc *MessageCache) Get(c context.Context, cset config.Set, path string, msg proto.Message) ( proto.Message, error) { // If no Lifetime is configured, bypass the cache layer. if mc.Lifetime <= 0 { err := mc.GetUncached(c, cset, path, msg) return msg, err } key := messageCacheKey{cset, path} // Load the value from our cache. First, though, take out a lock on this // specific config key. This will prevent multiple concurrent accesses from // slamming the config service, particularly at startup. var v interface{} var err error v, err = messageCache.LRU(c).GetOrCreate(c, key, func() (interface{}, time.Duration, error) { // Not in cache or expired. Reload... if err := mc.GetUncached(c, cset, path, msg); err != nil { return nil, 0, err } return proto.Clone(msg), mc.Lifetime, nil }) if err != nil { return nil, err } return v.(proto.Message), nil }
[ "func", "(", "mc", "*", "MessageCache", ")", "Get", "(", "c", "context", ".", "Context", ",", "cset", "config", ".", "Set", ",", "path", "string", ",", "msg", "proto", ".", "Message", ")", "(", "proto", ".", "Message", ",", "error", ")", "{", "// I...
// Get returns an unmarshalled configuration service text protobuf message. // // If the message is not currently in the process cache, it will be fetched from // the config service and cached prior to being returned.
[ "Get", "returns", "an", "unmarshalled", "configuration", "service", "text", "protobuf", "message", ".", "If", "the", "message", "is", "not", "currently", "in", "the", "process", "cache", "it", "will", "be", "fetched", "from", "the", "config", "service", "and",...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/config/cache.go#L49-L76
7,761
luci/luci-go
logdog/server/service/config/cache.go
GetUncached
func (mc *MessageCache) GetUncached(c context.Context, cset config.Set, path string, msg proto.Message) error { return cfgclient.Get(c, cfgclient.AsService, cset, path, textproto.Message(msg), nil) }
go
func (mc *MessageCache) GetUncached(c context.Context, cset config.Set, path string, msg proto.Message) error { return cfgclient.Get(c, cfgclient.AsService, cset, path, textproto.Message(msg), nil) }
[ "func", "(", "mc", "*", "MessageCache", ")", "GetUncached", "(", "c", "context", ".", "Context", ",", "cset", "config", ".", "Set", ",", "path", "string", ",", "msg", "proto", ".", "Message", ")", "error", "{", "return", "cfgclient", ".", "Get", "(", ...
// GetUncached returns an unmarshalled configuration service text protobuf // message. This bypasses the cache, and, on success, does not cache the // resulting value.
[ "GetUncached", "returns", "an", "unmarshalled", "configuration", "service", "text", "protobuf", "message", ".", "This", "bypasses", "the", "cache", "and", "on", "success", "does", "not", "cache", "the", "resulting", "value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/config/cache.go#L81-L85
7,762
luci/luci-go
logdog/common/renderer/source.go
NextLogEntry
func (s *StaticSource) NextLogEntry() (le *logpb.LogEntry, err error) { // Pop the next entry, mutating s. if len(*s) > 0 { le, *s = (*s)[0], (*s)[1:] } if len(*s) == 0 { err = io.EOF } return }
go
func (s *StaticSource) NextLogEntry() (le *logpb.LogEntry, err error) { // Pop the next entry, mutating s. if len(*s) > 0 { le, *s = (*s)[0], (*s)[1:] } if len(*s) == 0 { err = io.EOF } return }
[ "func", "(", "s", "*", "StaticSource", ")", "NextLogEntry", "(", ")", "(", "le", "*", "logpb", ".", "LogEntry", ",", "err", "error", ")", "{", "// Pop the next entry, mutating s.", "if", "len", "(", "*", "s", ")", ">", "0", "{", "le", ",", "*", "s", ...
// NextLogEntry implements Source.
[ "NextLogEntry", "implements", "Source", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/renderer/source.go#L43-L52
7,763
luci/luci-go
common/data/cmpbin/number.go
WriteInt
func WriteInt(w io.ByteWriter, val int64) (int, error) { var inv byte if val < 0 { inv = 0xff } mag := uint64(val) if inv != 0 { mag = -mag } return writeSignMag(w, mag, inv) }
go
func WriteInt(w io.ByteWriter, val int64) (int, error) { var inv byte if val < 0 { inv = 0xff } mag := uint64(val) if inv != 0 { mag = -mag } return writeSignMag(w, mag, inv) }
[ "func", "WriteInt", "(", "w", "io", ".", "ByteWriter", ",", "val", "int64", ")", "(", "int", ",", "error", ")", "{", "var", "inv", "byte", "\n", "if", "val", "<", "0", "{", "inv", "=", "0xff", "\n", "}", "\n", "mag", ":=", "uint64", "(", "val",...
// WriteInt val as a cmpbin Int to the ByteWriter. Returns the number of bytes // written. Only returns an error if the underlying ByteWriter returns an error.
[ "WriteInt", "val", "as", "a", "cmpbin", "Int", "to", "the", "ByteWriter", ".", "Returns", "the", "number", "of", "bytes", "written", ".", "Only", "returns", "an", "error", "if", "the", "underlying", "ByteWriter", "returns", "an", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/cmpbin/number.go#L69-L79
7,764
luci/luci-go
common/data/cmpbin/number.go
WriteUint
func WriteUint(w io.ByteWriter, mag uint64) (int, error) { return writeSignMag(w, mag, 0) }
go
func WriteUint(w io.ByteWriter, mag uint64) (int, error) { return writeSignMag(w, mag, 0) }
[ "func", "WriteUint", "(", "w", "io", ".", "ByteWriter", ",", "mag", "uint64", ")", "(", "int", ",", "error", ")", "{", "return", "writeSignMag", "(", "w", ",", "mag", ",", "0", ")", "\n", "}" ]
// WriteUint writes mag to the ByteWriter. Returns the number of bytes written. // Only returns an error if the underlying ByteWriter returns an error.
[ "WriteUint", "writes", "mag", "to", "the", "ByteWriter", ".", "Returns", "the", "number", "of", "bytes", "written", ".", "Only", "returns", "an", "error", "if", "the", "underlying", "ByteWriter", "returns", "an", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/cmpbin/number.go#L83-L85
7,765
luci/luci-go
server/middleware/paniccatcher.go
WithPanicCatcher
func WithPanicCatcher(c *router.Context, next router.Handler) { ctx := c.Context w := c.Writer req := c.Request defer paniccatcher.Catch(func(p *paniccatcher.Panic) { // Log the reason before the stack in case appengine cuts entire log // message due to size limitations. log.Fields{ "panic.error": p.Reason, }.Errorf(ctx, "Caught panic during handling of %q: %s\n%s", req.RequestURI, p.Reason, p.Stack) // Note: it may be too late to send HTTP 500 if `next` already sent // headers. But there's nothing else we can do at this point anyway. http.Error(w, "Internal Server Error. See logs.", http.StatusInternalServerError) }) next(c) }
go
func WithPanicCatcher(c *router.Context, next router.Handler) { ctx := c.Context w := c.Writer req := c.Request defer paniccatcher.Catch(func(p *paniccatcher.Panic) { // Log the reason before the stack in case appengine cuts entire log // message due to size limitations. log.Fields{ "panic.error": p.Reason, }.Errorf(ctx, "Caught panic during handling of %q: %s\n%s", req.RequestURI, p.Reason, p.Stack) // Note: it may be too late to send HTTP 500 if `next` already sent // headers. But there's nothing else we can do at this point anyway. http.Error(w, "Internal Server Error. See logs.", http.StatusInternalServerError) }) next(c) }
[ "func", "WithPanicCatcher", "(", "c", "*", "router", ".", "Context", ",", "next", "router", ".", "Handler", ")", "{", "ctx", ":=", "c", ".", "Context", "\n", "w", ":=", "c", ".", "Writer", "\n", "req", ":=", "c", ".", "Request", "\n", "defer", "pan...
// WithPanicCatcher is a middleware that catches panics, dumps stack trace to // logging and returns HTTP 500.
[ "WithPanicCatcher", "is", "a", "middleware", "that", "catches", "panics", "dumps", "stack", "trace", "to", "logging", "and", "returns", "HTTP", "500", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/middleware/paniccatcher.go#L27-L43
7,766
luci/luci-go
common/gcloud/iam/signer.go
SignBytes
func (s *Signer) SignBytes(c context.Context, blob []byte) (string, []byte, error) { return s.Client.SignBlob(c, s.ServiceAccount, blob) }
go
func (s *Signer) SignBytes(c context.Context, blob []byte) (string, []byte, error) { return s.Client.SignBlob(c, s.ServiceAccount, blob) }
[ "func", "(", "s", "*", "Signer", ")", "SignBytes", "(", "c", "context", ".", "Context", ",", "blob", "[", "]", "byte", ")", "(", "string", ",", "[", "]", "byte", ",", "error", ")", "{", "return", "s", ".", "Client", ".", "SignBlob", "(", "c", "...
// SignBytes signs the blob with some active private key. // // Hashes the blob using SHA256 and then calculates RSASSA-PKCS1-v1_5 signature // using the currently active signing key. // // Returns the signature and name of the key used.
[ "SignBytes", "signs", "the", "blob", "with", "some", "active", "private", "key", ".", "Hashes", "the", "blob", "using", "SHA256", "and", "then", "calculates", "RSASSA", "-", "PKCS1", "-", "v1_5", "signature", "using", "the", "currently", "active", "signing", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/iam/signer.go#L34-L36
7,767
luci/luci-go
server/auth/authdb/cache.go
NewDBCache
func NewDBCache(updater DBCacheUpdater) func(c context.Context) (DB, error) { cacheSlot := lazyslot.Slot{} return func(c context.Context) (DB, error) { val, err := cacheSlot.Get(c, func(prev interface{}) (db interface{}, exp time.Duration, err error) { prevDB, _ := prev.(DB) if db, err = updater(c, prevDB); err == nil { exp = 5*time.Second + time.Duration(mathrand.Get(c).Intn(5000))*time.Millisecond } return }) if err != nil { return nil, err } return val.(DB), nil } }
go
func NewDBCache(updater DBCacheUpdater) func(c context.Context) (DB, error) { cacheSlot := lazyslot.Slot{} return func(c context.Context) (DB, error) { val, err := cacheSlot.Get(c, func(prev interface{}) (db interface{}, exp time.Duration, err error) { prevDB, _ := prev.(DB) if db, err = updater(c, prevDB); err == nil { exp = 5*time.Second + time.Duration(mathrand.Get(c).Intn(5000))*time.Millisecond } return }) if err != nil { return nil, err } return val.(DB), nil } }
[ "func", "NewDBCache", "(", "updater", "DBCacheUpdater", ")", "func", "(", "c", "context", ".", "Context", ")", "(", "DB", ",", "error", ")", "{", "cacheSlot", ":=", "lazyslot", ".", "Slot", "{", "}", "\n", "return", "func", "(", "c", "context", ".", ...
// NewDBCache returns a provider of DB instances that uses local memory to // cache DB instances for 5-10 seconds. It uses supplied callback to refetch DB // from some permanent storage when cache expires. // // Even though the return value is technically a function, treat it as a heavy // stateful object, since it has the cache of DB in its closure.
[ "NewDBCache", "returns", "a", "provider", "of", "DB", "instances", "that", "uses", "local", "memory", "to", "cache", "DB", "instances", "for", "5", "-", "10", "seconds", ".", "It", "uses", "supplied", "callback", "to", "refetch", "DB", "from", "some", "per...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/authdb/cache.go#L36-L51
7,768
luci/luci-go
machine-db/appengine/model/kvms.go
fetch
func (t *KVMsTable) fetch(c context.Context) error { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT k.id, h.id, h.name, i.ipv4, k.description, k.mac_address, k.state, k.platform_id, k.rack_id FROM kvms k, hostnames h, ips i WHERE k.hostname_id = h.id AND i.hostname_id = h.id `) if err != nil { return errors.Annotate(err, "failed to select KVMs").Err() } defer rows.Close() for rows.Next() { kvm := &KVM{} if err := rows.Scan(&kvm.Id, &kvm.HostnameId, &kvm.Name, &kvm.IPv4, &kvm.Description, &kvm.MacAddress, &kvm.State, &kvm.PlatformId, &kvm.RackId); err != nil { return errors.Annotate(err, "failed to scan KVM").Err() } t.current = append(t.current, kvm) } return nil }
go
func (t *KVMsTable) fetch(c context.Context) error { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT k.id, h.id, h.name, i.ipv4, k.description, k.mac_address, k.state, k.platform_id, k.rack_id FROM kvms k, hostnames h, ips i WHERE k.hostname_id = h.id AND i.hostname_id = h.id `) if err != nil { return errors.Annotate(err, "failed to select KVMs").Err() } defer rows.Close() for rows.Next() { kvm := &KVM{} if err := rows.Scan(&kvm.Id, &kvm.HostnameId, &kvm.Name, &kvm.IPv4, &kvm.Description, &kvm.MacAddress, &kvm.State, &kvm.PlatformId, &kvm.RackId); err != nil { return errors.Annotate(err, "failed to scan KVM").Err() } t.current = append(t.current, kvm) } return nil }
[ "func", "(", "t", "*", "KVMsTable", ")", "fetch", "(", "c", "context", ".", "Context", ")", "error", "{", "db", ":=", "database", ".", "Get", "(", "c", ")", "\n", "rows", ",", "err", ":=", "db", ".", "QueryContext", "(", "c", ",", "`\n\t\tSELECT k....
// fetch fetches the KVMs from the database.
[ "fetch", "fetches", "the", "KVMs", "from", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/kvms.go#L57-L76
7,769
luci/luci-go
machine-db/appengine/model/kvms.go
computeChanges
func (t *KVMsTable) computeChanges(c context.Context, datacenters []*config.Datacenter) error { cfgs := make(map[string]*KVM, len(datacenters)) for _, dc := range datacenters { for _, cfg := range dc.Kvm { ipv4, err := common.ParseIPv4(cfg.Ipv4) if err != nil { return errors.Reason("failed to determine IP address for KVM %q: invalid IPv4 address %q", cfg.Name, cfg.Ipv4).Err() } mac48, err := common.ParseMAC48(cfg.MacAddress) if err != nil { return errors.Reason("failed to determine MAC address for KVM %q: invalid MAC-48 address %q", cfg.Name, cfg.MacAddress).Err() } pId, ok := t.platforms[cfg.Platform] if !ok { return errors.Reason("failed to determine platform ID for KVM %q: platform %q does not exist", cfg.Name, cfg.Platform).Err() } rId, ok := t.racks[cfg.Rack] if !ok { return errors.Reason("failed to determine rack ID for KVM %q: rack %q does not exist", cfg.Name, cfg.Rack).Err() } cfgs[cfg.Name] = &KVM{ KVM: config.KVM{ Name: cfg.Name, Description: cfg.Description, State: cfg.State, }, IPv4: ipv4, MacAddress: mac48, PlatformId: pId, RackId: rId, } } } for _, kvm := range t.current { if cfg, ok := cfgs[kvm.Name]; ok { // KVM found in the config. if t.needsUpdate(kvm, cfg) { // KVM doesn't match the config. cfg.Id = kvm.Id t.updates = append(t.updates, cfg) } // Record that the KVM config has been seen. delete(cfgs, cfg.Name) } else { // KVM not found in the config. t.removals = append(t.removals, kvm) } } // KVMs remaining in the map are present in the config but not the database. // Iterate deterministically over the slices to determine which KVMs need to be added. for _, dc := range datacenters { for _, cfg := range dc.Kvm { if kvm, ok := cfgs[cfg.Name]; ok { t.additions = append(t.additions, kvm) } } } return nil }
go
func (t *KVMsTable) computeChanges(c context.Context, datacenters []*config.Datacenter) error { cfgs := make(map[string]*KVM, len(datacenters)) for _, dc := range datacenters { for _, cfg := range dc.Kvm { ipv4, err := common.ParseIPv4(cfg.Ipv4) if err != nil { return errors.Reason("failed to determine IP address for KVM %q: invalid IPv4 address %q", cfg.Name, cfg.Ipv4).Err() } mac48, err := common.ParseMAC48(cfg.MacAddress) if err != nil { return errors.Reason("failed to determine MAC address for KVM %q: invalid MAC-48 address %q", cfg.Name, cfg.MacAddress).Err() } pId, ok := t.platforms[cfg.Platform] if !ok { return errors.Reason("failed to determine platform ID for KVM %q: platform %q does not exist", cfg.Name, cfg.Platform).Err() } rId, ok := t.racks[cfg.Rack] if !ok { return errors.Reason("failed to determine rack ID for KVM %q: rack %q does not exist", cfg.Name, cfg.Rack).Err() } cfgs[cfg.Name] = &KVM{ KVM: config.KVM{ Name: cfg.Name, Description: cfg.Description, State: cfg.State, }, IPv4: ipv4, MacAddress: mac48, PlatformId: pId, RackId: rId, } } } for _, kvm := range t.current { if cfg, ok := cfgs[kvm.Name]; ok { // KVM found in the config. if t.needsUpdate(kvm, cfg) { // KVM doesn't match the config. cfg.Id = kvm.Id t.updates = append(t.updates, cfg) } // Record that the KVM config has been seen. delete(cfgs, cfg.Name) } else { // KVM not found in the config. t.removals = append(t.removals, kvm) } } // KVMs remaining in the map are present in the config but not the database. // Iterate deterministically over the slices to determine which KVMs need to be added. for _, dc := range datacenters { for _, cfg := range dc.Kvm { if kvm, ok := cfgs[cfg.Name]; ok { t.additions = append(t.additions, kvm) } } } return nil }
[ "func", "(", "t", "*", "KVMsTable", ")", "computeChanges", "(", "c", "context", ".", "Context", ",", "datacenters", "[", "]", "*", "config", ".", "Datacenter", ")", "error", "{", "cfgs", ":=", "make", "(", "map", "[", "string", "]", "*", "KVM", ",", ...
// computeChanges computes the changes that need to be made to the KVMs in the database.
[ "computeChanges", "computes", "the", "changes", "that", "need", "to", "be", "made", "to", "the", "KVMs", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/kvms.go#L85-L145
7,770
luci/luci-go
machine-db/appengine/model/kvms.go
add
func (t *KVMsTable) add(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.additions) == 0 { return nil } tx, err := database.Begin(c) if err != nil { return errors.Annotate(err, "failed to begin transaction").Err() } defer tx.MaybeRollback(c) stmt, err := tx.PrepareContext(c, ` INSERT INTO kvms (hostname_id, description, mac_address, state, platform_id, rack_id) VALUES (?, ?, ?, ?, ?, ?) `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Add each KVM to the database, and update the slice of KVMs with each addition. for len(t.additions) > 0 { kvm := t.additions[0] hostnameId, err := AssignHostnameAndIP(c, tx, kvm.Name, kvm.IPv4) if err != nil { return errors.Annotate(err, "failed to add KVM %q", kvm.Name).Err() } result, err := stmt.ExecContext(c, hostnameId, kvm.Description, kvm.MacAddress, kvm.State, kvm.PlatformId, kvm.RackId) if err != nil { return errors.Annotate(err, "failed to add KVM %q", kvm.Name).Err() } t.current = append(t.current, kvm) t.additions = t.additions[1:] logging.Infof(c, "Added KVM %q", kvm.Name) kvm.Id, err = result.LastInsertId() if err != nil { return errors.Annotate(err, "failed to get KVM ID %q", kvm.Name).Err() } } if err := tx.Commit(); err != nil { return errors.Annotate(err, "failed to commit transaction").Err() } return nil }
go
func (t *KVMsTable) add(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.additions) == 0 { return nil } tx, err := database.Begin(c) if err != nil { return errors.Annotate(err, "failed to begin transaction").Err() } defer tx.MaybeRollback(c) stmt, err := tx.PrepareContext(c, ` INSERT INTO kvms (hostname_id, description, mac_address, state, platform_id, rack_id) VALUES (?, ?, ?, ?, ?, ?) `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Add each KVM to the database, and update the slice of KVMs with each addition. for len(t.additions) > 0 { kvm := t.additions[0] hostnameId, err := AssignHostnameAndIP(c, tx, kvm.Name, kvm.IPv4) if err != nil { return errors.Annotate(err, "failed to add KVM %q", kvm.Name).Err() } result, err := stmt.ExecContext(c, hostnameId, kvm.Description, kvm.MacAddress, kvm.State, kvm.PlatformId, kvm.RackId) if err != nil { return errors.Annotate(err, "failed to add KVM %q", kvm.Name).Err() } t.current = append(t.current, kvm) t.additions = t.additions[1:] logging.Infof(c, "Added KVM %q", kvm.Name) kvm.Id, err = result.LastInsertId() if err != nil { return errors.Annotate(err, "failed to get KVM ID %q", kvm.Name).Err() } } if err := tx.Commit(); err != nil { return errors.Annotate(err, "failed to commit transaction").Err() } return nil }
[ "func", "(", "t", "*", "KVMsTable", ")", "add", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "additions", ")", "==", "0", "{", "return", "nil", ...
// add adds all KVMs pending addition to the database, clearing pending additions. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "add", "adds", "all", "KVMs", "pending", "addition", "to", "the", "database", "clearing", "pending", "additions", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called", "again", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/kvms.go#L149-L193
7,771
luci/luci-go
machine-db/appengine/model/kvms.go
remove
func (t *KVMsTable) remove(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.removals) == 0 { return nil } db := database.Get(c) // By setting kvms.hostname_id ON DELETE CASCADE when setting up the database, we can avoid // having to explicitly delete the KVM here. MySQL will cascade the deletion to the KVM. stmt, err := db.PrepareContext(c, ` DELETE FROM hostnames WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Remove each KVM from the table. It's more efficient to update the slice of // KVMs once at the end rather than for each removal, so use a defer. removed := make(map[int64]struct{}, len(t.removals)) defer func() { var kvms []*KVM for _, kvm := range t.current { if _, ok := removed[kvm.Id]; !ok { kvms = append(kvms, kvm) } } t.current = kvms }() for len(t.removals) > 0 { kvm := t.removals[0] if _, err := stmt.ExecContext(c, kvm.HostnameId); err != nil { // Defer ensures the slice of KVMs is updated even if we exit early. return errors.Annotate(err, "failed to remove KVM %q", kvm.Name).Err() } removed[kvm.Id] = struct{}{} t.removals = t.removals[1:] logging.Infof(c, "Removed KVM %q", kvm.Name) } return nil }
go
func (t *KVMsTable) remove(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.removals) == 0 { return nil } db := database.Get(c) // By setting kvms.hostname_id ON DELETE CASCADE when setting up the database, we can avoid // having to explicitly delete the KVM here. MySQL will cascade the deletion to the KVM. stmt, err := db.PrepareContext(c, ` DELETE FROM hostnames WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Remove each KVM from the table. It's more efficient to update the slice of // KVMs once at the end rather than for each removal, so use a defer. removed := make(map[int64]struct{}, len(t.removals)) defer func() { var kvms []*KVM for _, kvm := range t.current { if _, ok := removed[kvm.Id]; !ok { kvms = append(kvms, kvm) } } t.current = kvms }() for len(t.removals) > 0 { kvm := t.removals[0] if _, err := stmt.ExecContext(c, kvm.HostnameId); err != nil { // Defer ensures the slice of KVMs is updated even if we exit early. return errors.Annotate(err, "failed to remove KVM %q", kvm.Name).Err() } removed[kvm.Id] = struct{}{} t.removals = t.removals[1:] logging.Infof(c, "Removed KVM %q", kvm.Name) } return nil }
[ "func", "(", "t", "*", "KVMsTable", ")", "remove", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "removals", ")", "==", "0", "{", "return", "nil", ...
// remove removes all KVMs pending removal from the database, clearing pending removals. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "remove", "removes", "all", "KVMs", "pending", "removal", "from", "the", "database", "clearing", "pending", "removals", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called", "aga...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/kvms.go#L197-L238
7,772
luci/luci-go
machine-db/appengine/model/kvms.go
update
func (t *KVMsTable) update(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.updates) == 0 { return nil } db := database.Get(c) // TODO(smut): Update IP address. stmt, err := db.PrepareContext(c, ` UPDATE kvms SET description = ?, mac_address = ?, state = ?, platform_id = ?, rack_id = ? WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Update each KVM in the table. It's more efficient to update the slice of // KVMs once at the end rather than for each update, so use a defer. updated := make(map[int64]*KVM, len(t.updates)) defer func() { for _, kvm := range t.current { if u, ok := updated[kvm.Id]; ok { kvm.MacAddress = u.MacAddress kvm.Description = u.Description kvm.State = u.State kvm.PlatformId = u.PlatformId kvm.RackId = u.RackId } } }() for len(t.updates) > 0 { kvm := t.updates[0] if _, err := stmt.ExecContext(c, kvm.Description, kvm.MacAddress, kvm.State, kvm.PlatformId, kvm.RackId, kvm.Id); err != nil { return errors.Annotate(err, "failed to update KVM %q", kvm.Name).Err() } updated[kvm.Id] = kvm t.updates = t.updates[1:] logging.Infof(c, "Updated KVM %q", kvm.Name) } return nil }
go
func (t *KVMsTable) update(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.updates) == 0 { return nil } db := database.Get(c) // TODO(smut): Update IP address. stmt, err := db.PrepareContext(c, ` UPDATE kvms SET description = ?, mac_address = ?, state = ?, platform_id = ?, rack_id = ? WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Update each KVM in the table. It's more efficient to update the slice of // KVMs once at the end rather than for each update, so use a defer. updated := make(map[int64]*KVM, len(t.updates)) defer func() { for _, kvm := range t.current { if u, ok := updated[kvm.Id]; ok { kvm.MacAddress = u.MacAddress kvm.Description = u.Description kvm.State = u.State kvm.PlatformId = u.PlatformId kvm.RackId = u.RackId } } }() for len(t.updates) > 0 { kvm := t.updates[0] if _, err := stmt.ExecContext(c, kvm.Description, kvm.MacAddress, kvm.State, kvm.PlatformId, kvm.RackId, kvm.Id); err != nil { return errors.Annotate(err, "failed to update KVM %q", kvm.Name).Err() } updated[kvm.Id] = kvm t.updates = t.updates[1:] logging.Infof(c, "Updated KVM %q", kvm.Name) } return nil }
[ "func", "(", "t", "*", "KVMsTable", ")", "update", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "updates", ")", "==", "0", "{", "return", "nil", ...
// update updates all KVMs pending update in the database, clearing pending updates. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "update", "updates", "all", "KVMs", "pending", "update", "in", "the", "database", "clearing", "pending", "updates", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called", "again",...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/kvms.go#L242-L284
7,773
luci/luci-go
machine-db/appengine/model/kvms.go
ids
func (t *KVMsTable) ids(c context.Context) map[string]int64 { KVMs := make(map[string]int64, len(t.current)) for _, s := range t.current { KVMs[s.Name] = s.Id } return KVMs }
go
func (t *KVMsTable) ids(c context.Context) map[string]int64 { KVMs := make(map[string]int64, len(t.current)) for _, s := range t.current { KVMs[s.Name] = s.Id } return KVMs }
[ "func", "(", "t", "*", "KVMsTable", ")", "ids", "(", "c", "context", ".", "Context", ")", "map", "[", "string", "]", "int64", "{", "KVMs", ":=", "make", "(", "map", "[", "string", "]", "int64", ",", "len", "(", "t", ".", "current", ")", ")", "\...
// ids returns a map of KVM names to IDs.
[ "ids", "returns", "a", "map", "of", "KVM", "names", "to", "IDs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/kvms.go#L287-L293
7,774
luci/luci-go
machine-db/appengine/model/kvms.go
EnsureKVMs
func EnsureKVMs(c context.Context, cfgs []*config.Datacenter, platformIds, rackIds map[string]int64) (map[string]int64, error) { t := &KVMsTable{} t.platforms = platformIds t.racks = rackIds if err := t.fetch(c); err != nil { return nil, errors.Annotate(err, "failed to fetch KVMs").Err() } if err := t.computeChanges(c, cfgs); err != nil { return nil, errors.Annotate(err, "failed to compute changes").Err() } if err := t.add(c); err != nil { return nil, errors.Annotate(err, "failed to add KVMs").Err() } if err := t.remove(c); err != nil { return nil, errors.Annotate(err, "failed to remove KVMs").Err() } if err := t.update(c); err != nil { return nil, errors.Annotate(err, "failed to update KVMs").Err() } return t.ids(c), nil }
go
func EnsureKVMs(c context.Context, cfgs []*config.Datacenter, platformIds, rackIds map[string]int64) (map[string]int64, error) { t := &KVMsTable{} t.platforms = platformIds t.racks = rackIds if err := t.fetch(c); err != nil { return nil, errors.Annotate(err, "failed to fetch KVMs").Err() } if err := t.computeChanges(c, cfgs); err != nil { return nil, errors.Annotate(err, "failed to compute changes").Err() } if err := t.add(c); err != nil { return nil, errors.Annotate(err, "failed to add KVMs").Err() } if err := t.remove(c); err != nil { return nil, errors.Annotate(err, "failed to remove KVMs").Err() } if err := t.update(c); err != nil { return nil, errors.Annotate(err, "failed to update KVMs").Err() } return t.ids(c), nil }
[ "func", "EnsureKVMs", "(", "c", "context", ".", "Context", ",", "cfgs", "[", "]", "*", "config", ".", "Datacenter", ",", "platformIds", ",", "rackIds", "map", "[", "string", "]", "int64", ")", "(", "map", "[", "string", "]", "int64", ",", "error", ")...
// EnsureKVMs ensures the database contains exactly the given KVMs. // Returns a map of KVM names to IDs in the database.
[ "EnsureKVMs", "ensures", "the", "database", "contains", "exactly", "the", "given", "KVMs", ".", "Returns", "a", "map", "of", "KVM", "names", "to", "IDs", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/kvms.go#L297-L317
7,775
luci/luci-go
milo/buildsource/buildbot/buildstore/encoding.go
encode
func encode(src interface{}) ([]byte, error) { jsoninsh, err := json.Marshal(src) if err != nil { return nil, err } var buf bytes.Buffer gsw := gzip.NewWriter(&buf) _, err = gsw.Write(jsoninsh) if err != nil { return nil, err } err = gsw.Close() if err != nil { return nil, err } return buf.Bytes(), nil }
go
func encode(src interface{}) ([]byte, error) { jsoninsh, err := json.Marshal(src) if err != nil { return nil, err } var buf bytes.Buffer gsw := gzip.NewWriter(&buf) _, err = gsw.Write(jsoninsh) if err != nil { return nil, err } err = gsw.Close() if err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "encode", "(", "src", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "jsoninsh", ",", "err", ":=", "json", ".", "Marshal", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\...
// encode marshals src to JSON and compresses it.
[ "encode", "marshals", "src", "to", "JSON", "and", "compresses", "it", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/encoding.go#L24-L41
7,776
luci/luci-go
milo/buildsource/buildbot/buildstore/encoding.go
decode
func decode(dest interface{}, data []byte) error { reader, err := gzip.NewReader(bytes.NewReader(data)) if err != nil { return err } err = json.NewDecoder(reader).Decode(dest) if err != nil { return err } return reader.Close() }
go
func decode(dest interface{}, data []byte) error { reader, err := gzip.NewReader(bytes.NewReader(data)) if err != nil { return err } err = json.NewDecoder(reader).Decode(dest) if err != nil { return err } return reader.Close() }
[ "func", "decode", "(", "dest", "interface", "{", "}", ",", "data", "[", "]", "byte", ")", "error", "{", "reader", ",", "err", ":=", "gzip", ".", "NewReader", "(", "bytes", ".", "NewReader", "(", "data", ")", ")", "\n", "if", "err", "!=", "nil", "...
// decode decompresses data and unmarshals into dest as JSON.
[ "decode", "decompresses", "data", "and", "unmarshals", "into", "dest", "as", "JSON", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/encoding.go#L44-L54
7,777
luci/luci-go
lucicfg/docgen/ast/parser.go
ParseModule
func ParseModule(filename, body string) (*Module, error) { ast, err := syntax.Parse(filename, body, syntax.RetainComments) if err != nil { return nil, err } m := &Module{docstring: extractDocstring(ast.Stmts)} m.populateFromAST(filename, ast) // emit adds a node to the module. emit := func(name string, ast syntax.Node, n Node) { n.populateFromAST(name, ast) m.Nodes = append(m.Nodes, n) } // Walk over top-level statements and match them against patterns we recognize // as relevant. for _, stmt := range ast.Stmts { switch st := stmt.(type) { case *syntax.LoadStmt: // A load(...) statement. Each imported symbol ends up in the module's // namespace, so add corresponding ExternalReference nodes. for i, nm := range st.To { emit(nm.Name, st, &ExternalReference{ ExternalName: st.From[i].Name, Module: st.Module.Value.(string), }) } case *syntax.DefStmt: // A function declaration: "def name(...)". emit(st.Name.Name, st, &Function{ docstring: extractDocstring(st.Body), }) case *syntax.AssignStmt: // A top level assignment. We care only about <var> = ... (i.e. when LHS // is a simple variable, not a tuple or anything like that). if st.Op != syntax.EQ { continue } lhs := matchSingleIdent(st.LHS) if lhs == "" { continue } if n := parseAssignmentRHS(st.RHS); n != nil { emit(lhs, st, n) } } } return m, nil }
go
func ParseModule(filename, body string) (*Module, error) { ast, err := syntax.Parse(filename, body, syntax.RetainComments) if err != nil { return nil, err } m := &Module{docstring: extractDocstring(ast.Stmts)} m.populateFromAST(filename, ast) // emit adds a node to the module. emit := func(name string, ast syntax.Node, n Node) { n.populateFromAST(name, ast) m.Nodes = append(m.Nodes, n) } // Walk over top-level statements and match them against patterns we recognize // as relevant. for _, stmt := range ast.Stmts { switch st := stmt.(type) { case *syntax.LoadStmt: // A load(...) statement. Each imported symbol ends up in the module's // namespace, so add corresponding ExternalReference nodes. for i, nm := range st.To { emit(nm.Name, st, &ExternalReference{ ExternalName: st.From[i].Name, Module: st.Module.Value.(string), }) } case *syntax.DefStmt: // A function declaration: "def name(...)". emit(st.Name.Name, st, &Function{ docstring: extractDocstring(st.Body), }) case *syntax.AssignStmt: // A top level assignment. We care only about <var> = ... (i.e. when LHS // is a simple variable, not a tuple or anything like that). if st.Op != syntax.EQ { continue } lhs := matchSingleIdent(st.LHS) if lhs == "" { continue } if n := parseAssignmentRHS(st.RHS); n != nil { emit(lhs, st, n) } } } return m, nil }
[ "func", "ParseModule", "(", "filename", ",", "body", "string", ")", "(", "*", "Module", ",", "error", ")", "{", "ast", ",", "err", ":=", "syntax", ".", "Parse", "(", "filename", ",", "body", ",", "syntax", ".", "RetainComments", ")", "\n", "if", "err...
// ParseModule parses a single Starlark module. // // Filename is only used when recording position information.
[ "ParseModule", "parses", "a", "single", "Starlark", "module", ".", "Filename", "is", "only", "used", "when", "recording", "position", "information", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/ast/parser.go#L207-L259
7,778
luci/luci-go
lucicfg/docgen/ast/parser.go
extractDocstring
func extractDocstring(body []syntax.Stmt) string { if len(body) == 0 { return "" } expr, ok := body[0].(*syntax.ExprStmt) if !ok { return "" } literal, ok := expr.X.(*syntax.Literal) if !ok || literal.Token != syntax.STRING { return "" } return literal.Value.(string) }
go
func extractDocstring(body []syntax.Stmt) string { if len(body) == 0 { return "" } expr, ok := body[0].(*syntax.ExprStmt) if !ok { return "" } literal, ok := expr.X.(*syntax.Literal) if !ok || literal.Token != syntax.STRING { return "" } return literal.Value.(string) }
[ "func", "extractDocstring", "(", "body", "[", "]", "syntax", ".", "Stmt", ")", "string", "{", "if", "len", "(", "body", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "expr", ",", "ok", ":=", "body", "[", "0", "]", ".", "(", "*", ...
// extractDocstring returns a doc string for the given body. // // A docstring is a string literal that comes first in the body, if any.
[ "extractDocstring", "returns", "a", "doc", "string", "for", "the", "given", "body", ".", "A", "docstring", "is", "a", "string", "literal", "that", "comes", "first", "in", "the", "body", "if", "any", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/ast/parser.go#L310-L323
7,779
luci/luci-go
milo/buildsource/buildbucket/pools.go
processBuilders
func processBuilders(c context.Context, r *swarmbucketAPI.LegacySwarmbucketApiGetBuildersResponseMessage) ([]model.PoolDescriptor, error) { var builderPools []model.BuilderPool var descriptors []model.PoolDescriptor seen := stringset.New(0) for _, bucket := range r.Buckets { for _, builder := range bucket.Builders { bid := NewBuilderID(bucket.Name, builder.Name) if bid.Project == "" { // This may happen if the bucket or builder does not fulfill the LUCI // naming convention. logging.Warningf(c, "invalid bucket/builder %q/%q, skipping", bucket.Name, builder.Name) continue } id := bid.String() dimensions := stripEmptyDimensions(builder.SwarmingDimensions) descriptor := model.NewPoolDescriptor(builder.SwarmingHostname, dimensions) dID := descriptor.PoolID() builderPools = append(builderPools, model.BuilderPool{ BuilderID: datastore.MakeKey(c, model.BuilderSummaryKind, id), PoolKey: datastore.MakeKey(c, model.BotPoolKind, dID), }) if added := seen.Add(dID); added { descriptors = append(descriptors, descriptor) } } } return descriptors, datastore.Put(c, builderPools) }
go
func processBuilders(c context.Context, r *swarmbucketAPI.LegacySwarmbucketApiGetBuildersResponseMessage) ([]model.PoolDescriptor, error) { var builderPools []model.BuilderPool var descriptors []model.PoolDescriptor seen := stringset.New(0) for _, bucket := range r.Buckets { for _, builder := range bucket.Builders { bid := NewBuilderID(bucket.Name, builder.Name) if bid.Project == "" { // This may happen if the bucket or builder does not fulfill the LUCI // naming convention. logging.Warningf(c, "invalid bucket/builder %q/%q, skipping", bucket.Name, builder.Name) continue } id := bid.String() dimensions := stripEmptyDimensions(builder.SwarmingDimensions) descriptor := model.NewPoolDescriptor(builder.SwarmingHostname, dimensions) dID := descriptor.PoolID() builderPools = append(builderPools, model.BuilderPool{ BuilderID: datastore.MakeKey(c, model.BuilderSummaryKind, id), PoolKey: datastore.MakeKey(c, model.BotPoolKind, dID), }) if added := seen.Add(dID); added { descriptors = append(descriptors, descriptor) } } } return descriptors, datastore.Put(c, builderPools) }
[ "func", "processBuilders", "(", "c", "context", ".", "Context", ",", "r", "*", "swarmbucketAPI", ".", "LegacySwarmbucketApiGetBuildersResponseMessage", ")", "(", "[", "]", "model", ".", "PoolDescriptor", ",", "error", ")", "{", "var", "builderPools", "[", "]", ...
// processBuilders parses out all of the builder pools from the Swarmbucket get_builders response, // and saves the BuilderPool information into the datastore. // It returns a list of PoolDescriptors that needs to be fetched and saved.
[ "processBuilders", "parses", "out", "all", "of", "the", "builder", "pools", "from", "the", "Swarmbucket", "get_builders", "response", "and", "saves", "the", "BuilderPool", "information", "into", "the", "datastore", ".", "It", "returns", "a", "list", "of", "PoolD...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/pools.go#L80-L107
7,780
luci/luci-go
milo/buildsource/buildbucket/pools.go
processBot
func processBot(c context.Context, desc model.PoolDescriptor) error { t, err := auth.GetRPCTransport(c, auth.AsSelf) if err != nil { return err } sc, err := swarmingAPI.New(&http.Client{Transport: t}) if err != nil { return err } sc.BasePath = fmt.Sprintf("https://%s/_ah/api/swarming/v1/", desc.Host()) var bots []model.Bot bl := sc.Bots.List().Dimensions(desc.Dimensions().Format()...) // Keep fetching until the cursor is empty. for { botList, err := bl.Do() if err != nil { return err } for _, botInfo := range botList.Items { // Ignore deleted bots. if botInfo.Deleted { continue } bot, err := parseBot(c, desc.Host(), botInfo) if err != nil { return err } bots = append(bots, *bot) } if botList.Cursor == "" { break } bl = bl.Cursor(botList.Cursor) } // If there are too many bots, then it won't fit in datastore. // Only store a subset of the bots. // TODO(hinoka): This is inaccurate, but will only affect few builders. // Instead of chopping this list off, just store the statistics. if len(bots) > 1000 { bots = bots[:1000] } // This is a large RPC, don't try to batch it. return datastore.Put(c, &model.BotPool{ PoolID: desc.PoolID(), Descriptor: desc, Bots: bots, LastUpdate: clock.Now(c), }) }
go
func processBot(c context.Context, desc model.PoolDescriptor) error { t, err := auth.GetRPCTransport(c, auth.AsSelf) if err != nil { return err } sc, err := swarmingAPI.New(&http.Client{Transport: t}) if err != nil { return err } sc.BasePath = fmt.Sprintf("https://%s/_ah/api/swarming/v1/", desc.Host()) var bots []model.Bot bl := sc.Bots.List().Dimensions(desc.Dimensions().Format()...) // Keep fetching until the cursor is empty. for { botList, err := bl.Do() if err != nil { return err } for _, botInfo := range botList.Items { // Ignore deleted bots. if botInfo.Deleted { continue } bot, err := parseBot(c, desc.Host(), botInfo) if err != nil { return err } bots = append(bots, *bot) } if botList.Cursor == "" { break } bl = bl.Cursor(botList.Cursor) } // If there are too many bots, then it won't fit in datastore. // Only store a subset of the bots. // TODO(hinoka): This is inaccurate, but will only affect few builders. // Instead of chopping this list off, just store the statistics. if len(bots) > 1000 { bots = bots[:1000] } // This is a large RPC, don't try to batch it. return datastore.Put(c, &model.BotPool{ PoolID: desc.PoolID(), Descriptor: desc, Bots: bots, LastUpdate: clock.Now(c), }) }
[ "func", "processBot", "(", "c", "context", ".", "Context", ",", "desc", "model", ".", "PoolDescriptor", ")", "error", "{", "t", ",", "err", ":=", "auth", ".", "GetRPCTransport", "(", "c", ",", "auth", ".", "AsSelf", ")", "\n", "if", "err", "!=", "nil...
// processBot retrieves the Bot pool details from Swarming for a given set of // dimensions for its respective Swarming host, and saves the data into datastore.
[ "processBot", "retrieves", "the", "Bot", "pool", "details", "from", "Swarming", "for", "a", "given", "set", "of", "dimensions", "for", "its", "respective", "Swarming", "host", "and", "saves", "the", "data", "into", "datastore", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/pools.go#L139-L189
7,781
luci/luci-go
common/clock/timer.go
Incomplete
func (tr TimerResult) Incomplete() bool { switch tr.Err { case nil: return false case context.Canceled, context.DeadlineExceeded: return true default: panic(fmt.Errorf("unknown TimerResult error value: %v", tr.Err)) } }
go
func (tr TimerResult) Incomplete() bool { switch tr.Err { case nil: return false case context.Canceled, context.DeadlineExceeded: return true default: panic(fmt.Errorf("unknown TimerResult error value: %v", tr.Err)) } }
[ "func", "(", "tr", "TimerResult", ")", "Incomplete", "(", ")", "bool", "{", "switch", "tr", ".", "Err", "{", "case", "nil", ":", "return", "false", "\n", "case", "context", ".", "Canceled", ",", "context", ".", "DeadlineExceeded", ":", "return", "true", ...
// Incomplete will return true if the timer result indicates that the timer // operation was canceled prematurely due to Context cancellation or deadline // expiration.
[ "Incomplete", "will", "return", "true", "if", "the", "timer", "result", "indicates", "that", "the", "timer", "operation", "was", "canceled", "prematurely", "due", "to", "Context", "cancellation", "or", "deadline", "expiration", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/clock/timer.go#L68-L77
7,782
luci/luci-go
common/data/bit_field/bf.go
MarshalBinary
func (bf *BitField) MarshalBinary() ([]byte, error) { ret := make([]byte, binary.MaxVarintLen32+len(bf.data)) n := binary.PutUvarint(ret, uint64(bf.size)) n += copy(ret[n:], bf.data) return ret[:n], nil }
go
func (bf *BitField) MarshalBinary() ([]byte, error) { ret := make([]byte, binary.MaxVarintLen32+len(bf.data)) n := binary.PutUvarint(ret, uint64(bf.size)) n += copy(ret[n:], bf.data) return ret[:n], nil }
[ "func", "(", "bf", "*", "BitField", ")", "MarshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "ret", ":=", "make", "(", "[", "]", "byte", ",", "binary", ".", "MaxVarintLen32", "+", "len", "(", "bf", ".", "data", ")", ")", "...
// MarshalBinary implements encoding.BinaryMarshaller
[ "MarshalBinary", "implements", "encoding", ".", "BinaryMarshaller" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/bit_field/bf.go#L50-L55
7,783
luci/luci-go
common/data/bit_field/bf.go
UnmarshalBinary
func (bf *BitField) UnmarshalBinary(bs []byte) error { buf := bytes.NewBuffer(bs) n, err := binary.ReadUvarint(buf) if err != nil { return err } if n > math.MaxUint32 { return fmt.Errorf("encoded number is out of range: %d > %d", n, uint32(math.MaxUint32)) } size := uint32(n) if size == 0 { bf.size = 0 bf.data = nil return nil } data := buf.Bytes() if uint32(len(data)) != (size+8-1)>>3 { return fmt.Errorf("mismatched size (%d) v. byte count (%d)", size, len(data)) } bf.size = size bf.data = data return nil }
go
func (bf *BitField) UnmarshalBinary(bs []byte) error { buf := bytes.NewBuffer(bs) n, err := binary.ReadUvarint(buf) if err != nil { return err } if n > math.MaxUint32 { return fmt.Errorf("encoded number is out of range: %d > %d", n, uint32(math.MaxUint32)) } size := uint32(n) if size == 0 { bf.size = 0 bf.data = nil return nil } data := buf.Bytes() if uint32(len(data)) != (size+8-1)>>3 { return fmt.Errorf("mismatched size (%d) v. byte count (%d)", size, len(data)) } bf.size = size bf.data = data return nil }
[ "func", "(", "bf", "*", "BitField", ")", "UnmarshalBinary", "(", "bs", "[", "]", "byte", ")", "error", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "bs", ")", "\n", "n", ",", "err", ":=", "binary", ".", "ReadUvarint", "(", "buf", ")", "\n", ...
// UnmarshalBinary implements encoding.BinaryUnmarshaler
[ "UnmarshalBinary", "implements", "encoding", ".", "BinaryUnmarshaler" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/bit_field/bf.go#L58-L82
7,784
luci/luci-go
common/data/bit_field/bf.go
ToProperty
func (bf *BitField) ToProperty() (datastore.Property, error) { bs, err := bf.MarshalBinary() return datastore.MkPropertyNI(bs), err }
go
func (bf *BitField) ToProperty() (datastore.Property, error) { bs, err := bf.MarshalBinary() return datastore.MkPropertyNI(bs), err }
[ "func", "(", "bf", "*", "BitField", ")", "ToProperty", "(", ")", "(", "datastore", ".", "Property", ",", "error", ")", "{", "bs", ",", "err", ":=", "bf", ".", "MarshalBinary", "(", ")", "\n", "return", "datastore", ".", "MkPropertyNI", "(", "bs", ")"...
// ToProperty implements datastore.PropertyConverter
[ "ToProperty", "implements", "datastore", ".", "PropertyConverter" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/bit_field/bf.go#L85-L88
7,785
luci/luci-go
common/data/bit_field/bf.go
Make
func Make(size uint32) BitField { if size == 0 { return BitField{} } return BitField{ data: make([]byte, (size+8-1)>>3), size: size, } }
go
func Make(size uint32) BitField { if size == 0 { return BitField{} } return BitField{ data: make([]byte, (size+8-1)>>3), size: size, } }
[ "func", "Make", "(", "size", "uint32", ")", "BitField", "{", "if", "size", "==", "0", "{", "return", "BitField", "{", "}", "\n", "}", "\n", "return", "BitField", "{", "data", ":", "make", "(", "[", "]", "byte", ",", "(", "size", "+", "8", "-", ...
// Make creates a new BitField.
[ "Make", "creates", "a", "new", "BitField", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/bit_field/bf.go#L106-L114
7,786
luci/luci-go
common/data/bit_field/bf.go
All
func (bf BitField) All(val bool) bool { targ := bf.size if !val { targ = 0 } return bf.CountSet() == targ }
go
func (bf BitField) All(val bool) bool { targ := bf.size if !val { targ = 0 } return bf.CountSet() == targ }
[ "func", "(", "bf", "BitField", ")", "All", "(", "val", "bool", ")", "bool", "{", "targ", ":=", "bf", ".", "size", "\n", "if", "!", "val", "{", "targ", "=", "0", "\n", "}", "\n", "return", "bf", ".", "CountSet", "(", ")", "==", "targ", "\n", "...
// All returns true iff all of the bits are equal to `val`.
[ "All", "returns", "true", "iff", "all", "of", "the", "bits", "are", "equal", "to", "val", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/bit_field/bf.go#L140-L146
7,787
luci/luci-go
common/data/bit_field/bf.go
CountSet
func (bf BitField) CountSet() (ret uint32) { for _, b := range bf.data { if b != 0 { ret += uint32(bitCount[b]) } } return ret }
go
func (bf BitField) CountSet() (ret uint32) { for _, b := range bf.data { if b != 0 { ret += uint32(bitCount[b]) } } return ret }
[ "func", "(", "bf", "BitField", ")", "CountSet", "(", ")", "(", "ret", "uint32", ")", "{", "for", "_", ",", "b", ":=", "range", "bf", ".", "data", "{", "if", "b", "!=", "0", "{", "ret", "+=", "uint32", "(", "bitCount", "[", "b", "]", ")", "\n"...
// CountSet returns the number of true bits.
[ "CountSet", "returns", "the", "number", "of", "true", "bits", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/bit_field/bf.go#L149-L156
7,788
luci/luci-go
common/data/bit_field/bf.go
IsSet
func (bf BitField) IsSet(idx uint32) bool { return idx < bf.size && ((bf.data[idx>>3] & (1 << (idx % 8))) != 0) }
go
func (bf BitField) IsSet(idx uint32) bool { return idx < bf.size && ((bf.data[idx>>3] & (1 << (idx % 8))) != 0) }
[ "func", "(", "bf", "BitField", ")", "IsSet", "(", "idx", "uint32", ")", "bool", "{", "return", "idx", "<", "bf", ".", "size", "&&", "(", "(", "bf", ".", "data", "[", "idx", ">>", "3", "]", "&", "(", "1", "<<", "(", "idx", "%", "8", ")", ")"...
// IsSet returns the value of a given bit.
[ "IsSet", "returns", "the", "value", "of", "a", "given", "bit", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/bit_field/bf.go#L159-L161
7,789
luci/luci-go
appengine/mapper/controller.go
tq
func (ctl *Controller) tq() *tq.Dispatcher { ctl.m.RLock() defer ctl.m.RUnlock() if ctl.disp == nil { panic("mapper.Controller wasn't installed into tq.Dispatcher yet") } return ctl.disp }
go
func (ctl *Controller) tq() *tq.Dispatcher { ctl.m.RLock() defer ctl.m.RUnlock() if ctl.disp == nil { panic("mapper.Controller wasn't installed into tq.Dispatcher yet") } return ctl.disp }
[ "func", "(", "ctl", "*", "Controller", ")", "tq", "(", ")", "*", "tq", ".", "Dispatcher", "{", "ctl", ".", "m", ".", "RLock", "(", ")", "\n", "defer", "ctl", ".", "m", ".", "RUnlock", "(", ")", "\n", "if", "ctl", ".", "disp", "==", "nil", "{"...
// tq returns a dispatcher set in Install or panics if not set yet. // // Grabs the reader lock inside.
[ "tq", "returns", "a", "dispatcher", "set", "in", "Install", "or", "panics", "if", "not", "set", "yet", ".", "Grabs", "the", "reader", "lock", "inside", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/mapper/controller.go#L148-L155
7,790
luci/luci-go
appengine/mapper/controller.go
getFactory
func (ctl *Controller) getFactory(id ID) (Factory, error) { ctl.m.RLock() defer ctl.m.RUnlock() if m, ok := ctl.mappers[id]; ok { return m, nil } return nil, errors.Reason("no mapper factory with ID %q registered", id).Err() }
go
func (ctl *Controller) getFactory(id ID) (Factory, error) { ctl.m.RLock() defer ctl.m.RUnlock() if m, ok := ctl.mappers[id]; ok { return m, nil } return nil, errors.Reason("no mapper factory with ID %q registered", id).Err() }
[ "func", "(", "ctl", "*", "Controller", ")", "getFactory", "(", "id", "ID", ")", "(", "Factory", ",", "error", ")", "{", "ctl", ".", "m", ".", "RLock", "(", ")", "\n", "defer", "ctl", ".", "m", ".", "RUnlock", "(", ")", "\n", "if", "m", ",", "...
// getFactory returns a registered mapper factory or an error. // // Grabs the reader lock inside. Can return only fatal errors.
[ "getFactory", "returns", "a", "registered", "mapper", "factory", "or", "an", "error", ".", "Grabs", "the", "reader", "lock", "inside", ".", "Can", "return", "only", "fatal", "errors", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/mapper/controller.go#L183-L190
7,791
luci/luci-go
appengine/mapper/controller.go
initMapper
func (ctl *Controller) initMapper(c context.Context, j *Job, shardIdx int) (Mapper, error) { f, err := ctl.getFactory(j.Config.Mapper) if err != nil { return nil, errors.Annotate(err, "when initializing mapper").Err() } m, err := f(c, j, shardIdx) if err != nil { return nil, errors.Annotate(err, "error from mapper factory %q", j.Config.Mapper).Err() } return m, nil }
go
func (ctl *Controller) initMapper(c context.Context, j *Job, shardIdx int) (Mapper, error) { f, err := ctl.getFactory(j.Config.Mapper) if err != nil { return nil, errors.Annotate(err, "when initializing mapper").Err() } m, err := f(c, j, shardIdx) if err != nil { return nil, errors.Annotate(err, "error from mapper factory %q", j.Config.Mapper).Err() } return m, nil }
[ "func", "(", "ctl", "*", "Controller", ")", "initMapper", "(", "c", "context", ".", "Context", ",", "j", "*", "Job", ",", "shardIdx", "int", ")", "(", "Mapper", ",", "error", ")", "{", "f", ",", "err", ":=", "ctl", ".", "getFactory", "(", "j", "....
// initMapper instantiates a Mapper through a registered factory. // // May return fatal and transient errors.
[ "initMapper", "instantiates", "a", "Mapper", "through", "a", "registered", "factory", ".", "May", "return", "fatal", "and", "transient", "errors", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/mapper/controller.go#L195-L205
7,792
luci/luci-go
appengine/mapper/controller.go
GetJob
func (ctl *Controller) GetJob(c context.Context, id JobID) (*Job, error) { // Even though we could have made getJob public, we want to force API users // to use Controller as a single facade. return getJob(c, id) }
go
func (ctl *Controller) GetJob(c context.Context, id JobID) (*Job, error) { // Even though we could have made getJob public, we want to force API users // to use Controller as a single facade. return getJob(c, id) }
[ "func", "(", "ctl", "*", "Controller", ")", "GetJob", "(", "c", "context", ".", "Context", ",", "id", "JobID", ")", "(", "*", "Job", ",", "error", ")", "{", "// Even though we could have made getJob public, we want to force API users", "// to use Controller as a singl...
// GetJob fetches a previously launched job given its ID. // // Returns ErrNoSuchJob if not found. All other possible errors are transient // and they are marked as such.
[ "GetJob", "fetches", "a", "previously", "launched", "job", "given", "its", "ID", ".", "Returns", "ErrNoSuchJob", "if", "not", "found", ".", "All", "other", "possible", "errors", "are", "transient", "and", "they", "are", "marked", "as", "such", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/mapper/controller.go#L254-L258
7,793
luci/luci-go
appengine/mapper/controller.go
AbortJob
func (ctl *Controller) AbortJob(c context.Context, id JobID) (job *Job, err error) { err = runTxn(c, func(c context.Context) error { var err error switch job, err = getJob(c, id); { case err != nil: return err case isFinalState(job.State) || job.State == State_ABORTING: return nil // nothing to abort, already done case job.State == State_STARTING: // Shards haven't been launched yet. Kill the job right away. job.State = State_ABORTED case job.State == State_RUNNING: // Running shards will discover that the job is aborting and will // eventually move into ABORTED state (notifying the job about it). Once // all shards report they are done, the job itself will switch into // ABORTED state. job.State = State_ABORTING } job.Updated = clock.Now(c).UTC() return errors.Annotate(datastore.Put(c, job), "failed to store Job entity").Tag(transient.Tag).Err() }) if err != nil { job = nil // don't return bogus data in case txn failed to land } return }
go
func (ctl *Controller) AbortJob(c context.Context, id JobID) (job *Job, err error) { err = runTxn(c, func(c context.Context) error { var err error switch job, err = getJob(c, id); { case err != nil: return err case isFinalState(job.State) || job.State == State_ABORTING: return nil // nothing to abort, already done case job.State == State_STARTING: // Shards haven't been launched yet. Kill the job right away. job.State = State_ABORTED case job.State == State_RUNNING: // Running shards will discover that the job is aborting and will // eventually move into ABORTED state (notifying the job about it). Once // all shards report they are done, the job itself will switch into // ABORTED state. job.State = State_ABORTING } job.Updated = clock.Now(c).UTC() return errors.Annotate(datastore.Put(c, job), "failed to store Job entity").Tag(transient.Tag).Err() }) if err != nil { job = nil // don't return bogus data in case txn failed to land } return }
[ "func", "(", "ctl", "*", "Controller", ")", "AbortJob", "(", "c", "context", ".", "Context", ",", "id", "JobID", ")", "(", "job", "*", "Job", ",", "err", "error", ")", "{", "err", "=", "runTxn", "(", "c", ",", "func", "(", "c", "context", ".", ...
// AbortJob aborts a job and returns its most recent state. // // Silently does nothing if the job is finished or already aborted. // // Returns ErrNoSuchJob is there's no such job at all. All other possible errors // are transient and they are marked as such.
[ "AbortJob", "aborts", "a", "job", "and", "returns", "its", "most", "recent", "state", ".", "Silently", "does", "nothing", "if", "the", "job", "is", "finished", "or", "already", "aborted", ".", "Returns", "ErrNoSuchJob", "is", "there", "s", "no", "such", "j...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/mapper/controller.go#L266-L291
7,794
luci/luci-go
appengine/mapper/controller.go
fanOutShardsHandler
func (ctl *Controller) fanOutShardsHandler(c context.Context, payload proto.Message) error { msg := payload.(*tasks.FanOutShards) // Make sure the job is still present. If it is aborted, we still need to // launch the shards, so they notice they are being aborted. We could try // to abort all shards right here and now, but it basically means implementing // an alternative shard abort flow. Seems simpler just to let the regular flow // to proceed. job, err := getJobInState(c, JobID(msg.JobId), State_RUNNING, State_ABORTING) if err != nil || job == nil { return errors.Annotate(err, "in FanOutShards").Err() } // Grab the list of shards created in SplitAndLaunch. It must exist at this // point, since the job is in Running state. shardIDs, err := job.fetchShardIDs(c) if err != nil { return errors.Annotate(err, "in FanOutShards").Err() } // Enqueue a bunch of named ProcessShard tasks (one per shard) to actually // launch shard processing. This is idempotent operation, so if FanOutShards // crashes midway and later retried, nothing bad happens. tsks := make([]*tq.Task, len(shardIDs)) for idx, sid := range shardIDs { tsks[idx] = makeProcessShardTask(job.ID, sid, 0, true) } return ctl.tq().AddTask(c, tsks...) }
go
func (ctl *Controller) fanOutShardsHandler(c context.Context, payload proto.Message) error { msg := payload.(*tasks.FanOutShards) // Make sure the job is still present. If it is aborted, we still need to // launch the shards, so they notice they are being aborted. We could try // to abort all shards right here and now, but it basically means implementing // an alternative shard abort flow. Seems simpler just to let the regular flow // to proceed. job, err := getJobInState(c, JobID(msg.JobId), State_RUNNING, State_ABORTING) if err != nil || job == nil { return errors.Annotate(err, "in FanOutShards").Err() } // Grab the list of shards created in SplitAndLaunch. It must exist at this // point, since the job is in Running state. shardIDs, err := job.fetchShardIDs(c) if err != nil { return errors.Annotate(err, "in FanOutShards").Err() } // Enqueue a bunch of named ProcessShard tasks (one per shard) to actually // launch shard processing. This is idempotent operation, so if FanOutShards // crashes midway and later retried, nothing bad happens. tsks := make([]*tq.Task, len(shardIDs)) for idx, sid := range shardIDs { tsks[idx] = makeProcessShardTask(job.ID, sid, 0, true) } return ctl.tq().AddTask(c, tsks...) }
[ "func", "(", "ctl", "*", "Controller", ")", "fanOutShardsHandler", "(", "c", "context", ".", "Context", ",", "payload", "proto", ".", "Message", ")", "error", "{", "msg", ":=", "payload", ".", "(", "*", "tasks", ".", "FanOutShards", ")", "\n\n", "// Make...
// fanOutShardsHandler fetches a list of shards from the job and launches // named ProcessShard tasks, one per shard.
[ "fanOutShardsHandler", "fetches", "a", "list", "of", "shards", "from", "the", "job", "and", "launches", "named", "ProcessShard", "tasks", "one", "per", "shard", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/mapper/controller.go#L442-L470
7,795
luci/luci-go
appengine/mapper/controller.go
requestJobStateUpdate
func (ctl *Controller) requestJobStateUpdate(c context.Context, jobID JobID, shardID int64) error { return ctl.tq().AddTask(c, &tq.Task{ Title: fmt.Sprintf("notify:job-%d-shard-%d", jobID, shardID), Payload: &tasks.RequestJobStateUpdate{ JobId: int64(jobID), ShardId: shardID, }, }) }
go
func (ctl *Controller) requestJobStateUpdate(c context.Context, jobID JobID, shardID int64) error { return ctl.tq().AddTask(c, &tq.Task{ Title: fmt.Sprintf("notify:job-%d-shard-%d", jobID, shardID), Payload: &tasks.RequestJobStateUpdate{ JobId: int64(jobID), ShardId: shardID, }, }) }
[ "func", "(", "ctl", "*", "Controller", ")", "requestJobStateUpdate", "(", "c", "context", ".", "Context", ",", "jobID", "JobID", ",", "shardID", "int64", ")", "error", "{", "return", "ctl", ".", "tq", "(", ")", ".", "AddTask", "(", "c", ",", "&", "tq...
// requestJobStateUpdate submits RequestJobStateUpdate task, which eventually // causes updateJobStateHandler to execute.
[ "requestJobStateUpdate", "submits", "RequestJobStateUpdate", "task", "which", "eventually", "causes", "updateJobStateHandler", "to", "execute", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/mapper/controller.go#L702-L710
7,796
luci/luci-go
appengine/mapper/controller.go
updateJobStateHandler
func (ctl *Controller) updateJobStateHandler(c context.Context, payload proto.Message) error { msg := payload.(*tasks.UpdateJobState) // Get the job and all its shards in their most recent state. job, err := getJobInState(c, JobID(msg.JobId), State_RUNNING, State_ABORTING) if err != nil || job == nil { return errors.Annotate(err, "in UpdateJobState").Err() } shards, err := job.fetchShards(c) if err != nil { return errors.Annotate(err, "failed to fetch shards").Err() } // Switch the job into a final state only when all shards are done running. perState := make(map[State]int, len(State_name)) finished := 0 for _, sh := range shards { logging.Infof(c, "Shard #%d (%d) is in state %s", sh.Index, sh.ID, sh.State) perState[sh.State]++ if isFinalState(sh.State) { finished++ } } if finished != len(shards) { return nil } jobState := State_SUCCESS switch { case perState[State_ABORTED] != 0: jobState = State_ABORTED case perState[State_FAIL] != 0: jobState = State_FAIL } return runTxn(c, func(c context.Context) error { job, err := getJobInState(c, JobID(msg.JobId), State_RUNNING, State_ABORTING) if err != nil || job == nil { return errors.Annotate(err, "in UpdateJobState txn").Err() } // Make sure an aborting job ends up in aborted state, even if all its // shards manged to finish. It looks weird when an ABORTING job moves // into e.g. SUCCESS state. if job.State == State_ABORTING { job.State = State_ABORTED } else { job.State = jobState } job.Updated = clock.Now(c).UTC() runtime := job.Updated.Sub(job.Created) switch job.State { case State_SUCCESS: logging.Infof(c, "The job finished successfully in %s", runtime) case State_FAIL: logging.Errorf(c, "The job finished with %d shards failing in %s", perState[State_FAIL], runtime) for _, sh := range shards { if sh.State == State_FAIL { logging.Errorf(c, "Shard #%d (%d) error - %s", sh.Index, sh.ID, sh.Error) } } case State_ABORTED: logging.Warningf(c, "The job has been aborted after %s: %d shards succeeded, %d shards failed, %d shards aborted", runtime, perState[State_SUCCESS], perState[State_FAIL], perState[State_ABORTED]) } return transient.Tag.Apply(datastore.Put(c, job)) }) }
go
func (ctl *Controller) updateJobStateHandler(c context.Context, payload proto.Message) error { msg := payload.(*tasks.UpdateJobState) // Get the job and all its shards in their most recent state. job, err := getJobInState(c, JobID(msg.JobId), State_RUNNING, State_ABORTING) if err != nil || job == nil { return errors.Annotate(err, "in UpdateJobState").Err() } shards, err := job.fetchShards(c) if err != nil { return errors.Annotate(err, "failed to fetch shards").Err() } // Switch the job into a final state only when all shards are done running. perState := make(map[State]int, len(State_name)) finished := 0 for _, sh := range shards { logging.Infof(c, "Shard #%d (%d) is in state %s", sh.Index, sh.ID, sh.State) perState[sh.State]++ if isFinalState(sh.State) { finished++ } } if finished != len(shards) { return nil } jobState := State_SUCCESS switch { case perState[State_ABORTED] != 0: jobState = State_ABORTED case perState[State_FAIL] != 0: jobState = State_FAIL } return runTxn(c, func(c context.Context) error { job, err := getJobInState(c, JobID(msg.JobId), State_RUNNING, State_ABORTING) if err != nil || job == nil { return errors.Annotate(err, "in UpdateJobState txn").Err() } // Make sure an aborting job ends up in aborted state, even if all its // shards manged to finish. It looks weird when an ABORTING job moves // into e.g. SUCCESS state. if job.State == State_ABORTING { job.State = State_ABORTED } else { job.State = jobState } job.Updated = clock.Now(c).UTC() runtime := job.Updated.Sub(job.Created) switch job.State { case State_SUCCESS: logging.Infof(c, "The job finished successfully in %s", runtime) case State_FAIL: logging.Errorf(c, "The job finished with %d shards failing in %s", perState[State_FAIL], runtime) for _, sh := range shards { if sh.State == State_FAIL { logging.Errorf(c, "Shard #%d (%d) error - %s", sh.Index, sh.ID, sh.Error) } } case State_ABORTED: logging.Warningf(c, "The job has been aborted after %s: %d shards succeeded, %d shards failed, %d shards aborted", runtime, perState[State_SUCCESS], perState[State_FAIL], perState[State_ABORTED]) } return transient.Tag.Apply(datastore.Put(c, job)) }) }
[ "func", "(", "ctl", "*", "Controller", ")", "updateJobStateHandler", "(", "c", "context", ".", "Context", ",", "payload", "proto", ".", "Message", ")", "error", "{", "msg", ":=", "payload", ".", "(", "*", "tasks", ".", "UpdateJobState", ")", "\n\n", "// ...
// updateJobStateHandler is called some time later after one or more shards have // changed state. // // It calculates overall job state based on the state of its shards.
[ "updateJobStateHandler", "is", "called", "some", "time", "later", "after", "one", "or", "more", "shards", "have", "changed", "state", ".", "It", "calculates", "overall", "job", "state", "based", "on", "the", "state", "of", "its", "shards", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/mapper/controller.go#L739-L808
7,797
luci/luci-go
starlark/starlarkproto/loader.go
injectEnumValues
func injectEnumValues(d starlark.StringDict, enum *descpb.EnumDescriptorProto) { for _, val := range enum.Value { d[val.GetName()] = starlark.MakeInt(int(val.GetNumber())) } }
go
func injectEnumValues(d starlark.StringDict, enum *descpb.EnumDescriptorProto) { for _, val := range enum.Value { d[val.GetName()] = starlark.MakeInt(int(val.GetNumber())) } }
[ "func", "injectEnumValues", "(", "d", "starlark", ".", "StringDict", ",", "enum", "*", "descpb", ".", "EnumDescriptorProto", ")", "{", "for", "_", ",", "val", ":=", "range", "enum", ".", "Value", "{", "d", "[", "val", ".", "GetName", "(", ")", "]", "...
// injectEnumValues takes enum constants defined in 'enum' and puts them // directly into the given dict as integers.
[ "injectEnumValues", "takes", "enum", "constants", "defined", "in", "enum", "and", "puts", "them", "directly", "into", "the", "given", "dict", "as", "integers", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/loader.go#L121-L125
7,798
luci/luci-go
starlark/starlarkproto/loader.go
loadFileDesc
func loadFileDesc(name string) (*descpb.FileDescriptorProto, error) { gzblob := proto.FileDescriptor(name) if gzblob == nil { return nil, fmt.Errorf("no such proto file registered") } r, err := gzip.NewReader(bytes.NewReader(gzblob)) if err != nil { return nil, fmt.Errorf("failed to open gzip reader - %s", err) } defer r.Close() b, err := ioutil.ReadAll(r) if err != nil { return nil, fmt.Errorf("failed to uncompress descriptor - %s", err) } fd := &descpb.FileDescriptorProto{} if err := proto.Unmarshal(b, fd); err != nil { return nil, fmt.Errorf("malformed FileDescriptorProto - %s", err) } return fd, nil }
go
func loadFileDesc(name string) (*descpb.FileDescriptorProto, error) { gzblob := proto.FileDescriptor(name) if gzblob == nil { return nil, fmt.Errorf("no such proto file registered") } r, err := gzip.NewReader(bytes.NewReader(gzblob)) if err != nil { return nil, fmt.Errorf("failed to open gzip reader - %s", err) } defer r.Close() b, err := ioutil.ReadAll(r) if err != nil { return nil, fmt.Errorf("failed to uncompress descriptor - %s", err) } fd := &descpb.FileDescriptorProto{} if err := proto.Unmarshal(b, fd); err != nil { return nil, fmt.Errorf("malformed FileDescriptorProto - %s", err) } return fd, nil }
[ "func", "loadFileDesc", "(", "name", "string", ")", "(", "*", "descpb", ".", "FileDescriptorProto", ",", "error", ")", "{", "gzblob", ":=", "proto", ".", "FileDescriptor", "(", "name", ")", "\n", "if", "gzblob", "==", "nil", "{", "return", "nil", ",", ...
// loadFileDesc loads a FileDescriptorProto for a given proto module, specified // by its full path. // // The module should be registered in the process's protobuf descriptors set.
[ "loadFileDesc", "loads", "a", "FileDescriptorProto", "for", "a", "given", "proto", "module", "specified", "by", "its", "full", "path", ".", "The", "module", "should", "be", "registered", "in", "the", "process", "s", "protobuf", "descriptors", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/loader.go#L131-L154
7,799
luci/luci-go
cipd/appengine/impl/cas/signed_urls.go
signURL
func signURL(c context.Context, gsPath string, signer *signer, expiry time.Duration) (string, error) { // See https://cloud.google.com/storage/docs/access-control/signed-urls. // // Basically, we sign a specially crafted multi-line string that encodes // expected parameters of the request. During the actual request, Google // Storage backend will construct the same string and verify that the provided // signature matches it. expires := fmt.Sprintf("%d", clock.Now(c).Add(expiry).Unix()) buf := &bytes.Buffer{} fmt.Fprintf(buf, "GET\n") fmt.Fprintf(buf, "\n") // expected value of 'Content-MD5' header, not used fmt.Fprintf(buf, "\n") // expected value of 'Content-Type' header, not used fmt.Fprintf(buf, "%s\n", expires) fmt.Fprintf(buf, "%s", gsPath) _, sig, err := signer.SignBytes(c, buf.Bytes()) if err != nil { return "", errors.Annotate(err, "signBytes call failed").Err() } u := url.URL{ Scheme: "https", Host: "storage.googleapis.com", Path: gsPath, RawQuery: (url.Values{ "GoogleAccessId": {signer.Email}, "Expires": {expires}, "Signature": {base64.StdEncoding.EncodeToString(sig)}, }).Encode(), } return u.String(), nil }
go
func signURL(c context.Context, gsPath string, signer *signer, expiry time.Duration) (string, error) { // See https://cloud.google.com/storage/docs/access-control/signed-urls. // // Basically, we sign a specially crafted multi-line string that encodes // expected parameters of the request. During the actual request, Google // Storage backend will construct the same string and verify that the provided // signature matches it. expires := fmt.Sprintf("%d", clock.Now(c).Add(expiry).Unix()) buf := &bytes.Buffer{} fmt.Fprintf(buf, "GET\n") fmt.Fprintf(buf, "\n") // expected value of 'Content-MD5' header, not used fmt.Fprintf(buf, "\n") // expected value of 'Content-Type' header, not used fmt.Fprintf(buf, "%s\n", expires) fmt.Fprintf(buf, "%s", gsPath) _, sig, err := signer.SignBytes(c, buf.Bytes()) if err != nil { return "", errors.Annotate(err, "signBytes call failed").Err() } u := url.URL{ Scheme: "https", Host: "storage.googleapis.com", Path: gsPath, RawQuery: (url.Values{ "GoogleAccessId": {signer.Email}, "Expires": {expires}, "Signature": {base64.StdEncoding.EncodeToString(sig)}, }).Encode(), } return u.String(), nil }
[ "func", "signURL", "(", "c", "context", ".", "Context", ",", "gsPath", "string", ",", "signer", "*", "signer", ",", "expiry", "time", ".", "Duration", ")", "(", "string", ",", "error", ")", "{", "// See https://cloud.google.com/storage/docs/access-control/signed-u...
// signURL generates a signed GS URL using the signer.
[ "signURL", "generates", "a", "signed", "GS", "URL", "using", "the", "signer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/signed_urls.go#L117-L150