id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
7,500
luci/luci-go
common/data/rand/mathrand/mathrand.go
getGlobalRand
func getGlobalRand() (*Locking, *rand.Rand) { globalOnce.Do(func() { globalRandBase = newRand() globalRand = &Locking{R: wrapped{globalRandBase}} }) return globalRand, globalRandBase }
go
func getGlobalRand() (*Locking, *rand.Rand) { globalOnce.Do(func() { globalRandBase = newRand() globalRand = &Locking{R: wrapped{globalRandBase}} }) return globalRand, globalRandBase }
[ "func", "getGlobalRand", "(", ")", "(", "*", "Locking", ",", "*", "rand", ".", "Rand", ")", "{", "globalOnce", ".", "Do", "(", "func", "(", ")", "{", "globalRandBase", "=", "newRand", "(", ")", "\n", "globalRand", "=", "&", "Locking", "{", "R", ":", "wrapped", "{", "globalRandBase", "}", "}", "\n", "}", ")", "\n", "return", "globalRand", ",", "globalRandBase", "\n", "}" ]
// getGlobalRand returns globalRand and its Locking wrapper. This must be used // instead of direct variable access in order to ensure that everything is // initialized. // // We use a Once to perform this initialization so that we can enable // applications to set the seed via rand.Seed if they wish.
[ "getGlobalRand", "returns", "globalRand", "and", "its", "Locking", "wrapper", ".", "This", "must", "be", "used", "instead", "of", "direct", "variable", "access", "in", "order", "to", "ensure", "that", "everything", "is", "initialized", ".", "We", "use", "a", "Once", "to", "perform", "this", "initialization", "so", "that", "we", "can", "enable", "applications", "to", "set", "the", "seed", "via", "rand", ".", "Seed", "if", "they", "wish", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/mathrand.go#L53-L59
7,501
luci/luci-go
common/data/rand/mathrand/mathrand.go
getRand
func getRand(c context.Context) Rand { if r, ok := c.Value(&key).(Rand); ok { return r } return nil }
go
func getRand(c context.Context) Rand { if r, ok := c.Value(&key).(Rand); ok { return r } return nil }
[ "func", "getRand", "(", "c", "context", ".", "Context", ")", "Rand", "{", "if", "r", ",", "ok", ":=", "c", ".", "Value", "(", "&", "key", ")", ".", "(", "Rand", ")", ";", "ok", "{", "return", "r", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// getRand returns the Rand installed in c, or nil if no Rand is installed.
[ "getRand", "returns", "the", "Rand", "installed", "in", "c", "or", "nil", "if", "no", "Rand", "is", "installed", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/mathrand.go#L64-L69
7,502
luci/luci-go
tokenserver/cmd/luci_machine_tokend/token_file.go
readTokenFile
func readTokenFile(ctx context.Context, path string) (*tokenserver.TokenFile, *stateInToken) { blob, err := ioutil.ReadFile(path) if err != nil { if !os.IsNotExist(err) { logging.Warningf(ctx, "Failed to read token file from %q - %s", path, err) } return &tokenserver.TokenFile{}, &stateInToken{} } out := &tokenserver.TokenFile{} if err = jsonpb.Unmarshal(bytes.NewReader(blob), out); err != nil { logging.Warningf(ctx, "Failed to unmarshal token file %q - %s", path, err) return &tokenserver.TokenFile{}, &stateInToken{} } // Attempt to decode stateInToken. Ignore if doesn't work, no big deal. state := &stateInToken{} if err = json.Unmarshal(out.TokendState, state); err != nil { logging.Warningf(ctx, "Failed to unmarshal tokend_state - %s", err) *state = stateInToken{} } return out, state }
go
func readTokenFile(ctx context.Context, path string) (*tokenserver.TokenFile, *stateInToken) { blob, err := ioutil.ReadFile(path) if err != nil { if !os.IsNotExist(err) { logging.Warningf(ctx, "Failed to read token file from %q - %s", path, err) } return &tokenserver.TokenFile{}, &stateInToken{} } out := &tokenserver.TokenFile{} if err = jsonpb.Unmarshal(bytes.NewReader(blob), out); err != nil { logging.Warningf(ctx, "Failed to unmarshal token file %q - %s", path, err) return &tokenserver.TokenFile{}, &stateInToken{} } // Attempt to decode stateInToken. Ignore if doesn't work, no big deal. state := &stateInToken{} if err = json.Unmarshal(out.TokendState, state); err != nil { logging.Warningf(ctx, "Failed to unmarshal tokend_state - %s", err) *state = stateInToken{} } return out, state }
[ "func", "readTokenFile", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "*", "tokenserver", ".", "TokenFile", ",", "*", "stateInToken", ")", "{", "blob", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "return", "&", "tokenserver", ".", "TokenFile", "{", "}", ",", "&", "stateInToken", "{", "}", "\n", "}", "\n", "out", ":=", "&", "tokenserver", ".", "TokenFile", "{", "}", "\n", "if", "err", "=", "jsonpb", ".", "Unmarshal", "(", "bytes", ".", "NewReader", "(", "blob", ")", ",", "out", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "path", ",", "err", ")", "\n", "return", "&", "tokenserver", ".", "TokenFile", "{", "}", ",", "&", "stateInToken", "{", "}", "\n", "}", "\n", "// Attempt to decode stateInToken. Ignore if doesn't work, no big deal.", "state", ":=", "&", "stateInToken", "{", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "out", ".", "TokendState", ",", "state", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "err", ")", "\n", "*", "state", "=", "stateInToken", "{", "}", "\n", "}", "\n", "return", "out", ",", "state", "\n", "}" ]
// readTokenFile reads the token file from disk. // // In case of problems, logs errors and returns default structs.
[ "readTokenFile", "reads", "the", "token", "file", "from", "disk", ".", "In", "case", "of", "problems", "logs", "errors", "and", "returns", "default", "structs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/cmd/luci_machine_tokend/token_file.go#L43-L63
7,503
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
viewerURL
func (ld *logData) viewerURL() string { for _, s := range ld.logStreams { desc, err := s.DescriptorValue() if err != nil { continue } if u, ok := desc.Tags["logdog.viewer_url"]; ok { return u } } return "" }
go
func (ld *logData) viewerURL() string { for _, s := range ld.logStreams { desc, err := s.DescriptorValue() if err != nil { continue } if u, ok := desc.Tags["logdog.viewer_url"]; ok { return u } } return "" }
[ "func", "(", "ld", "*", "logData", ")", "viewerURL", "(", ")", "string", "{", "for", "_", ",", "s", ":=", "range", "ld", ".", "logStreams", "{", "desc", ",", "err", ":=", "s", ".", "DescriptorValue", "(", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "if", "u", ",", "ok", ":=", "desc", ".", "Tags", "[", "\"", "\"", "]", ";", "ok", "{", "return", "u", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// viewerURL is a convenience function to extract the logdog.viewer_url tag // out of a logStream, if available. // If given multiple streams, it will return the first one found with the viewer_url tag.
[ "viewerURL", "is", "a", "convenience", "function", "to", "extract", "the", "logdog", ".", "viewer_url", "tag", "out", "of", "a", "logStream", "if", "available", ".", "If", "given", "multiple", "streams", "it", "will", "return", "the", "first", "one", "found", "with", "the", "viewer_url", "tag", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L146-L157
7,504
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
resolveStreams
func resolveStreams(c context.Context, options userOptions) ([]*coordinator.LogStream, error) { prefix, name := options.path.Split() streams := []*coordinator.LogStream{} var err error if options.wildcard { q := datastore.NewQuery("LogStream").Eq("Prefix", prefix.String()).Eq("Purged", false) err = datastore.GetAll(c, q, &streams) } else { streams = append(streams, &coordinator.LogStream{ID: coordinator.LogStreamID(options.path)}) err = datastore.Get(c, streams[0]) } switch { case len(streams) == 0, datastore.IsErrNoSuchEntity(err): return nil, coordinator.ErrPathNotFound case err != nil: return nil, err case !options.wildcard: // If the user requested HTML format, check to see if the stream is a binary or datagram stream. // If so, then this mode is not supported, and instead just render a link to the supported mode. if options.isHTML() && streams[0].StreamType != logpb.StreamType_TEXT { err = errRawRedirect } return streams, err } result := matchStreams(streams, name.String()) if len(result) == 0 { return nil, coordinator.ErrPathNotFound } return result, nil }
go
func resolveStreams(c context.Context, options userOptions) ([]*coordinator.LogStream, error) { prefix, name := options.path.Split() streams := []*coordinator.LogStream{} var err error if options.wildcard { q := datastore.NewQuery("LogStream").Eq("Prefix", prefix.String()).Eq("Purged", false) err = datastore.GetAll(c, q, &streams) } else { streams = append(streams, &coordinator.LogStream{ID: coordinator.LogStreamID(options.path)}) err = datastore.Get(c, streams[0]) } switch { case len(streams) == 0, datastore.IsErrNoSuchEntity(err): return nil, coordinator.ErrPathNotFound case err != nil: return nil, err case !options.wildcard: // If the user requested HTML format, check to see if the stream is a binary or datagram stream. // If so, then this mode is not supported, and instead just render a link to the supported mode. if options.isHTML() && streams[0].StreamType != logpb.StreamType_TEXT { err = errRawRedirect } return streams, err } result := matchStreams(streams, name.String()) if len(result) == 0 { return nil, coordinator.ErrPathNotFound } return result, nil }
[ "func", "resolveStreams", "(", "c", "context", ".", "Context", ",", "options", "userOptions", ")", "(", "[", "]", "*", "coordinator", ".", "LogStream", ",", "error", ")", "{", "prefix", ",", "name", ":=", "options", ".", "path", ".", "Split", "(", ")", "\n", "streams", ":=", "[", "]", "*", "coordinator", ".", "LogStream", "{", "}", "\n", "var", "err", "error", "\n", "if", "options", ".", "wildcard", "{", "q", ":=", "datastore", ".", "NewQuery", "(", "\"", "\"", ")", ".", "Eq", "(", "\"", "\"", ",", "prefix", ".", "String", "(", ")", ")", ".", "Eq", "(", "\"", "\"", ",", "false", ")", "\n", "err", "=", "datastore", ".", "GetAll", "(", "c", ",", "q", ",", "&", "streams", ")", "\n", "}", "else", "{", "streams", "=", "append", "(", "streams", ",", "&", "coordinator", ".", "LogStream", "{", "ID", ":", "coordinator", ".", "LogStreamID", "(", "options", ".", "path", ")", "}", ")", "\n", "err", "=", "datastore", ".", "Get", "(", "c", ",", "streams", "[", "0", "]", ")", "\n", "}", "\n\n", "switch", "{", "case", "len", "(", "streams", ")", "==", "0", ",", "datastore", ".", "IsErrNoSuchEntity", "(", "err", ")", ":", "return", "nil", ",", "coordinator", ".", "ErrPathNotFound", "\n", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "case", "!", "options", ".", "wildcard", ":", "// If the user requested HTML format, check to see if the stream is a binary or datagram stream.", "// If so, then this mode is not supported, and instead just render a link to the supported mode.", "if", "options", ".", "isHTML", "(", ")", "&&", "streams", "[", "0", "]", ".", "StreamType", "!=", "logpb", ".", "StreamType_TEXT", "{", "err", "=", "errRawRedirect", "\n", "}", "\n", "return", "streams", ",", "err", "\n", "}", "\n\n", "result", ":=", "matchStreams", "(", "streams", ",", "name", ".", "String", "(", ")", ")", "\n", "if", "len", "(", "result", ")", "==", "0", "{", "return", "nil", ",", "coordinator", ".", "ErrPathNotFound", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// resolveStreams takes a path containing a wildcard and resolves it to the list // of all known paths. Purge checks are also performed here.
[ "resolveStreams", "takes", "a", "path", "containing", "a", "wildcard", "and", "resolves", "it", "to", "the", "list", "of", "all", "known", "paths", ".", "Purge", "checks", "are", "also", "performed", "here", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L297-L328
7,505
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
initParams
func initParams(c context.Context, streams []*coordinator.LogStream, project types.ProjectName) ([]fetchParams, error) { states := make([]*coordinator.LogStreamState, len(streams)) for i, stream := range streams { states[i] = stream.State(c) } // Get the log states, which we use to fetch the backend storage. switch err := datastore.Get(c, states); { case datastore.IsErrNoSuchEntity(err): return nil, coordinator.ErrPathNotFound case err != nil: return nil, err } // Get the backend storage instances. These will be closed in fetch. params := make([]fetchParams, len(streams)) for i, stream := range streams { st, err := flex.GetServices(c).StorageForStream(c, states[i], project) if err != nil { return nil, err } params[i] = fetchParams{ storage: st, stream: stream, state: states[i], } } return params, nil }
go
func initParams(c context.Context, streams []*coordinator.LogStream, project types.ProjectName) ([]fetchParams, error) { states := make([]*coordinator.LogStreamState, len(streams)) for i, stream := range streams { states[i] = stream.State(c) } // Get the log states, which we use to fetch the backend storage. switch err := datastore.Get(c, states); { case datastore.IsErrNoSuchEntity(err): return nil, coordinator.ErrPathNotFound case err != nil: return nil, err } // Get the backend storage instances. These will be closed in fetch. params := make([]fetchParams, len(streams)) for i, stream := range streams { st, err := flex.GetServices(c).StorageForStream(c, states[i], project) if err != nil { return nil, err } params[i] = fetchParams{ storage: st, stream: stream, state: states[i], } } return params, nil }
[ "func", "initParams", "(", "c", "context", ".", "Context", ",", "streams", "[", "]", "*", "coordinator", ".", "LogStream", ",", "project", "types", ".", "ProjectName", ")", "(", "[", "]", "fetchParams", ",", "error", ")", "{", "states", ":=", "make", "(", "[", "]", "*", "coordinator", ".", "LogStreamState", ",", "len", "(", "streams", ")", ")", "\n", "for", "i", ",", "stream", ":=", "range", "streams", "{", "states", "[", "i", "]", "=", "stream", ".", "State", "(", "c", ")", "\n", "}", "\n", "// Get the log states, which we use to fetch the backend storage.", "switch", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "states", ")", ";", "{", "case", "datastore", ".", "IsErrNoSuchEntity", "(", "err", ")", ":", "return", "nil", ",", "coordinator", ".", "ErrPathNotFound", "\n", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Get the backend storage instances. These will be closed in fetch.", "params", ":=", "make", "(", "[", "]", "fetchParams", ",", "len", "(", "streams", ")", ")", "\n", "for", "i", ",", "stream", ":=", "range", "streams", "{", "st", ",", "err", ":=", "flex", ".", "GetServices", "(", "c", ")", ".", "StorageForStream", "(", "c", ",", "states", "[", "i", "]", ",", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "params", "[", "i", "]", "=", "fetchParams", "{", "storage", ":", "st", ",", "stream", ":", "stream", ",", "state", ":", "states", "[", "i", "]", ",", "}", "\n", "}", "\n\n", "return", "params", ",", "nil", "\n", "}" ]
// initParams generates a set of params for each LogStream given.
[ "initParams", "generates", "a", "set", "of", "params", "for", "each", "LogStream", "given", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L331-L359
7,506
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
fetch
func fetch(c context.Context, ch chan<- logResp, allParams []fetchParams) { defer close(ch) // Close the channel when we're done fetching. // TODO(hinoka): Remove this check once multistream view is supported. if len(allParams) > 1 { streamPaths := make([]string, len(allParams)) for i, p := range allParams { streamPaths[i] = string(p.stream.Path()) p.storage.Close() } ch <- logResp{nil, nil, fmt.Errorf("Only single stream supported, found %d: %s", len(allParams), strings.Join(streamPaths, "\n"))} return } // Extract the params we need. params := allParams[0] state := params.state st := params.storage defer st.Close() // Close the connection to the backend when we're done. index := types.MessageIndex(0) backoff := time.Second // How long to wait between fetch requests from storage. var err error for { // Get the terminal index from the LogStreamState again if we need to. // This is useful when the log stream terminated after the user request started. if !state.Terminated() { if err = datastore.Get(c, state); err != nil { ch <- logResp{nil, nil, err} return } } // Do the actual work. nextIndex, err := fetchOnce(c, ch, index, params) // Signal regardless of error. Server will bail on error and flush otherwise. // Important: if fetchOnce errors out, we still expect nextIndex to increment regardless, // otherwise this may get stuck in an infinite loop. ch <- logResp{nil, nil, err} // Check if the log has finished streaming and if we're done. if state.Terminated() && nextIndex > types.MessageIndex(state.TerminalIndex) { logging.Fields{ "terminalIndex": state.TerminalIndex, "currentIndex": index, }.Debugf(c, "Finished streaming") return } if err != nil { index = nextIndex continue } // Log is still streaming. Set the next index, sleep a bit and try again. backoff = backoff * 2 if backoff > maxBackoff { backoff = maxBackoff } if index != nextIndex { if err != nil { // An error on one log entry means we want to try the next one asap. backoff = 0 } else { // If its a relatively active log stream, don't sleep too long. backoff = time.Second } } if tr := clock.Sleep(c, backoff); tr.Err != nil { // If the user cancelled the request, bail out instead. ch <- logResp{nil, nil, tr.Err} return } index = nextIndex } }
go
func fetch(c context.Context, ch chan<- logResp, allParams []fetchParams) { defer close(ch) // Close the channel when we're done fetching. // TODO(hinoka): Remove this check once multistream view is supported. if len(allParams) > 1 { streamPaths := make([]string, len(allParams)) for i, p := range allParams { streamPaths[i] = string(p.stream.Path()) p.storage.Close() } ch <- logResp{nil, nil, fmt.Errorf("Only single stream supported, found %d: %s", len(allParams), strings.Join(streamPaths, "\n"))} return } // Extract the params we need. params := allParams[0] state := params.state st := params.storage defer st.Close() // Close the connection to the backend when we're done. index := types.MessageIndex(0) backoff := time.Second // How long to wait between fetch requests from storage. var err error for { // Get the terminal index from the LogStreamState again if we need to. // This is useful when the log stream terminated after the user request started. if !state.Terminated() { if err = datastore.Get(c, state); err != nil { ch <- logResp{nil, nil, err} return } } // Do the actual work. nextIndex, err := fetchOnce(c, ch, index, params) // Signal regardless of error. Server will bail on error and flush otherwise. // Important: if fetchOnce errors out, we still expect nextIndex to increment regardless, // otherwise this may get stuck in an infinite loop. ch <- logResp{nil, nil, err} // Check if the log has finished streaming and if we're done. if state.Terminated() && nextIndex > types.MessageIndex(state.TerminalIndex) { logging.Fields{ "terminalIndex": state.TerminalIndex, "currentIndex": index, }.Debugf(c, "Finished streaming") return } if err != nil { index = nextIndex continue } // Log is still streaming. Set the next index, sleep a bit and try again. backoff = backoff * 2 if backoff > maxBackoff { backoff = maxBackoff } if index != nextIndex { if err != nil { // An error on one log entry means we want to try the next one asap. backoff = 0 } else { // If its a relatively active log stream, don't sleep too long. backoff = time.Second } } if tr := clock.Sleep(c, backoff); tr.Err != nil { // If the user cancelled the request, bail out instead. ch <- logResp{nil, nil, tr.Err} return } index = nextIndex } }
[ "func", "fetch", "(", "c", "context", ".", "Context", ",", "ch", "chan", "<-", "logResp", ",", "allParams", "[", "]", "fetchParams", ")", "{", "defer", "close", "(", "ch", ")", "// Close the channel when we're done fetching.", "\n\n", "// TODO(hinoka): Remove this check once multistream view is supported.", "if", "len", "(", "allParams", ")", ">", "1", "{", "streamPaths", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "allParams", ")", ")", "\n", "for", "i", ",", "p", ":=", "range", "allParams", "{", "streamPaths", "[", "i", "]", "=", "string", "(", "p", ".", "stream", ".", "Path", "(", ")", ")", "\n", "p", ".", "storage", ".", "Close", "(", ")", "\n", "}", "\n", "ch", "<-", "logResp", "{", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "allParams", ")", ",", "strings", ".", "Join", "(", "streamPaths", ",", "\"", "\\n", "\"", ")", ")", "}", "\n", "return", "\n", "}", "\n\n", "// Extract the params we need.", "params", ":=", "allParams", "[", "0", "]", "\n", "state", ":=", "params", ".", "state", "\n", "st", ":=", "params", ".", "storage", "\n", "defer", "st", ".", "Close", "(", ")", "// Close the connection to the backend when we're done.", "\n\n", "index", ":=", "types", ".", "MessageIndex", "(", "0", ")", "\n", "backoff", ":=", "time", ".", "Second", "// How long to wait between fetch requests from storage.", "\n", "var", "err", "error", "\n", "for", "{", "// Get the terminal index from the LogStreamState again if we need to.", "// This is useful when the log stream terminated after the user request started.", "if", "!", "state", ".", "Terminated", "(", ")", "{", "if", "err", "=", "datastore", ".", "Get", "(", "c", ",", "state", ")", ";", "err", "!=", "nil", "{", "ch", "<-", "logResp", "{", "nil", ",", "nil", ",", "err", "}", "\n", "return", "\n", "}", "\n", "}", "\n\n", "// Do the actual work.", "nextIndex", ",", "err", ":=", "fetchOnce", "(", "c", ",", "ch", ",", "index", ",", "params", ")", "\n", "// Signal regardless of error. Server will bail on error and flush otherwise.", "// Important: if fetchOnce errors out, we still expect nextIndex to increment regardless,", "// otherwise this may get stuck in an infinite loop.", "ch", "<-", "logResp", "{", "nil", ",", "nil", ",", "err", "}", "\n\n", "// Check if the log has finished streaming and if we're done.", "if", "state", ".", "Terminated", "(", ")", "&&", "nextIndex", ">", "types", ".", "MessageIndex", "(", "state", ".", "TerminalIndex", ")", "{", "logging", ".", "Fields", "{", "\"", "\"", ":", "state", ".", "TerminalIndex", ",", "\"", "\"", ":", "index", ",", "}", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "index", "=", "nextIndex", "\n", "continue", "\n", "}", "\n\n", "// Log is still streaming. Set the next index, sleep a bit and try again.", "backoff", "=", "backoff", "*", "2", "\n", "if", "backoff", ">", "maxBackoff", "{", "backoff", "=", "maxBackoff", "\n", "}", "\n", "if", "index", "!=", "nextIndex", "{", "if", "err", "!=", "nil", "{", "// An error on one log entry means we want to try the next one asap.", "backoff", "=", "0", "\n", "}", "else", "{", "// If its a relatively active log stream, don't sleep too long.", "backoff", "=", "time", ".", "Second", "\n", "}", "\n", "}", "\n", "if", "tr", ":=", "clock", ".", "Sleep", "(", "c", ",", "backoff", ")", ";", "tr", ".", "Err", "!=", "nil", "{", "// If the user cancelled the request, bail out instead.", "ch", "<-", "logResp", "{", "nil", ",", "nil", ",", "tr", ".", "Err", "}", "\n", "return", "\n", "}", "\n", "index", "=", "nextIndex", "\n", "}", "\n", "}" ]
// fetch is a goroutine that fetches log entries from all storage layers and // sends it through ch in the order of prefix index. // The LogStreamState is used purely for checking Terminal Indices.
[ "fetch", "is", "a", "goroutine", "that", "fetches", "log", "entries", "from", "all", "storage", "layers", "and", "sends", "it", "through", "ch", "in", "the", "order", "of", "prefix", "index", ".", "The", "LogStreamState", "is", "used", "purely", "for", "checking", "Terminal", "Indices", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L417-L492
7,507
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
fetchOnce
func fetchOnce(c context.Context, ch chan<- logResp, index types.MessageIndex, params fetchParams) (types.MessageIndex, error) { // Extract just the parameters we need. st := params.storage // This is the backend storage instance. archived := params.state.ArchivalState().Archived() path := params.stream.Path() req := storage.GetRequest{ Project: coordinator.Project(c), Path: path, Index: index, } var ierr error // Get as many log entries as we can. The storage layer is responsible for low level retries. err := st.Get(c, req, func(e *storage.Entry) bool { var le *logpb.LogEntry if le, ierr = e.GetLogEntry(); ierr != nil { // This log entry is bad, just try the next one blindly. index++ return false } sidx, _ := e.GetStreamIndex() // GetLogEntry succeeded, so this must. // Check for a non-continguous stream index. This could mean a couple things: // Still streaming: The backend probably needs to catch up. Return false and retry the fetch. // Archived: We permanently lost the log entries, just skip over them. if sidx != index && !archived { if archived { logging.Fields{"lostLogs": true}.Errorf(c, "Oh no we lost some logs.") } else { logging.Debugf(c, "Got a non-contiguous stream index, backend needs to catch up.") } return false } // Send the log entry over! This may block if the channel buffer is full. ch <- logResp{params.stream, le, nil} index = sidx + 1 return true }) if err != nil { index++ logging.WithError(err).Debugf(c, "got some error while fetching, incrementing index to %d", index) } // TODO(hinoka): Handle not found case. if err == nil && ierr != nil { err = ierr } return index, err }
go
func fetchOnce(c context.Context, ch chan<- logResp, index types.MessageIndex, params fetchParams) (types.MessageIndex, error) { // Extract just the parameters we need. st := params.storage // This is the backend storage instance. archived := params.state.ArchivalState().Archived() path := params.stream.Path() req := storage.GetRequest{ Project: coordinator.Project(c), Path: path, Index: index, } var ierr error // Get as many log entries as we can. The storage layer is responsible for low level retries. err := st.Get(c, req, func(e *storage.Entry) bool { var le *logpb.LogEntry if le, ierr = e.GetLogEntry(); ierr != nil { // This log entry is bad, just try the next one blindly. index++ return false } sidx, _ := e.GetStreamIndex() // GetLogEntry succeeded, so this must. // Check for a non-continguous stream index. This could mean a couple things: // Still streaming: The backend probably needs to catch up. Return false and retry the fetch. // Archived: We permanently lost the log entries, just skip over them. if sidx != index && !archived { if archived { logging.Fields{"lostLogs": true}.Errorf(c, "Oh no we lost some logs.") } else { logging.Debugf(c, "Got a non-contiguous stream index, backend needs to catch up.") } return false } // Send the log entry over! This may block if the channel buffer is full. ch <- logResp{params.stream, le, nil} index = sidx + 1 return true }) if err != nil { index++ logging.WithError(err).Debugf(c, "got some error while fetching, incrementing index to %d", index) } // TODO(hinoka): Handle not found case. if err == nil && ierr != nil { err = ierr } return index, err }
[ "func", "fetchOnce", "(", "c", "context", ".", "Context", ",", "ch", "chan", "<-", "logResp", ",", "index", "types", ".", "MessageIndex", ",", "params", "fetchParams", ")", "(", "types", ".", "MessageIndex", ",", "error", ")", "{", "// Extract just the parameters we need.", "st", ":=", "params", ".", "storage", "// This is the backend storage instance.", "\n", "archived", ":=", "params", ".", "state", ".", "ArchivalState", "(", ")", ".", "Archived", "(", ")", "\n", "path", ":=", "params", ".", "stream", ".", "Path", "(", ")", "\n\n", "req", ":=", "storage", ".", "GetRequest", "{", "Project", ":", "coordinator", ".", "Project", "(", "c", ")", ",", "Path", ":", "path", ",", "Index", ":", "index", ",", "}", "\n", "var", "ierr", "error", "\n", "// Get as many log entries as we can. The storage layer is responsible for low level retries.", "err", ":=", "st", ".", "Get", "(", "c", ",", "req", ",", "func", "(", "e", "*", "storage", ".", "Entry", ")", "bool", "{", "var", "le", "*", "logpb", ".", "LogEntry", "\n", "if", "le", ",", "ierr", "=", "e", ".", "GetLogEntry", "(", ")", ";", "ierr", "!=", "nil", "{", "// This log entry is bad, just try the next one blindly.", "index", "++", "\n", "return", "false", "\n", "}", "\n", "sidx", ",", "_", ":=", "e", ".", "GetStreamIndex", "(", ")", "// GetLogEntry succeeded, so this must.", "\n", "// Check for a non-continguous stream index. This could mean a couple things:", "// Still streaming: The backend probably needs to catch up. Return false and retry the fetch.", "// Archived: We permanently lost the log entries, just skip over them.", "if", "sidx", "!=", "index", "&&", "!", "archived", "{", "if", "archived", "{", "logging", ".", "Fields", "{", "\"", "\"", ":", "true", "}", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "else", "{", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "false", "\n", "}", "\n", "// Send the log entry over! This may block if the channel buffer is full.", "ch", "<-", "logResp", "{", "params", ".", "stream", ",", "le", ",", "nil", "}", "\n", "index", "=", "sidx", "+", "1", "\n", "return", "true", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "index", "++", "\n", "logging", ".", "WithError", "(", "err", ")", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "index", ")", "\n", "}", "\n", "// TODO(hinoka): Handle not found case.", "if", "err", "==", "nil", "&&", "ierr", "!=", "nil", "{", "err", "=", "ierr", "\n", "}", "\n", "return", "index", ",", "err", "\n", "}" ]
// fetchOnce does one backend storage request for logs, which may produce multiple log entries. // // Log entries are pushed into ch. // Returns the next stream index to fetch. // It is possible for the next index to be the terminal index + 1, so the calling // code has to test for that.
[ "fetchOnce", "does", "one", "backend", "storage", "request", "for", "logs", "which", "may", "produce", "multiple", "log", "entries", ".", "Log", "entries", "are", "pushed", "into", "ch", ".", "Returns", "the", "next", "stream", "index", "to", "fetch", ".", "It", "is", "possible", "for", "the", "next", "index", "to", "be", "the", "terminal", "index", "+", "1", "so", "the", "calling", "code", "has", "to", "test", "for", "that", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L500-L546
7,508
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
writeOKHeaders
func writeOKHeaders(ctx *router.Context, data logData) { // Tell nginx not to buffer anything. ctx.Writer.Header().Set("X-Accel-Buffering", "no") // Tell the browser to prefer https. ctx.Writer.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") // Set the correct content type based off the log stream and format. contentType := data.logStreams[0].ContentType if data.options.isHTML() { // Only text/html is supported for HTML mode. contentType = "text/html" } ctx.Writer.Header().Set("Content-Type", contentType) ctx.Writer.WriteHeader(http.StatusOK) if data.options.isHTML() { writeHTMLHeader(ctx, data) } }
go
func writeOKHeaders(ctx *router.Context, data logData) { // Tell nginx not to buffer anything. ctx.Writer.Header().Set("X-Accel-Buffering", "no") // Tell the browser to prefer https. ctx.Writer.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") // Set the correct content type based off the log stream and format. contentType := data.logStreams[0].ContentType if data.options.isHTML() { // Only text/html is supported for HTML mode. contentType = "text/html" } ctx.Writer.Header().Set("Content-Type", contentType) ctx.Writer.WriteHeader(http.StatusOK) if data.options.isHTML() { writeHTMLHeader(ctx, data) } }
[ "func", "writeOKHeaders", "(", "ctx", "*", "router", ".", "Context", ",", "data", "logData", ")", "{", "// Tell nginx not to buffer anything.", "ctx", ".", "Writer", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "// Tell the browser to prefer https.", "ctx", ".", "Writer", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "// Set the correct content type based off the log stream and format.", "contentType", ":=", "data", ".", "logStreams", "[", "0", "]", ".", "ContentType", "\n", "if", "data", ".", "options", ".", "isHTML", "(", ")", "{", "// Only text/html is supported for HTML mode.", "contentType", "=", "\"", "\"", "\n", "}", "\n", "ctx", ".", "Writer", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "contentType", ")", "\n", "ctx", ".", "Writer", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "if", "data", ".", "options", ".", "isHTML", "(", ")", "{", "writeHTMLHeader", "(", "ctx", ",", "data", ")", "\n", "}", "\n", "}" ]
// writeOKHeaders writes the http response headers in accordence with the // log stream type and user options. The error is passed through.
[ "writeOKHeaders", "writes", "the", "http", "response", "headers", "in", "accordence", "with", "the", "log", "stream", "type", "and", "user", "options", ".", "The", "error", "is", "passed", "through", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L583-L599
7,509
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
writeErrorPage
func writeErrorPage(ctx *router.Context, err error, data logData) { ierr := errors.New("LogDog encountered an internal error") switch code := grpcutil.Code(err); code { case codes.Unauthenticated: // Redirect to login screen. var u string u, ierr = auth.LoginURL(ctx.Context, ctx.Request.URL.RequestURI()) if ierr == nil { http.Redirect(ctx.Writer, ctx.Request, u, http.StatusFound) return } logging.WithError(ierr).Errorf(ctx.Context, "Error getting Login URL") fallthrough case codes.Internal: // Hide internal errors, expose all other errors. ctx.Writer.WriteHeader(http.StatusInternalServerError) default: ierr = err ctx.Writer.WriteHeader(grpcutil.CodeStatus(code)) } if data.options.isHTML() { writeHTMLHeader(ctx, data) } writeFooter(ctx, clock.Now(ctx.Context), ierr, data.options.isHTML()) }
go
func writeErrorPage(ctx *router.Context, err error, data logData) { ierr := errors.New("LogDog encountered an internal error") switch code := grpcutil.Code(err); code { case codes.Unauthenticated: // Redirect to login screen. var u string u, ierr = auth.LoginURL(ctx.Context, ctx.Request.URL.RequestURI()) if ierr == nil { http.Redirect(ctx.Writer, ctx.Request, u, http.StatusFound) return } logging.WithError(ierr).Errorf(ctx.Context, "Error getting Login URL") fallthrough case codes.Internal: // Hide internal errors, expose all other errors. ctx.Writer.WriteHeader(http.StatusInternalServerError) default: ierr = err ctx.Writer.WriteHeader(grpcutil.CodeStatus(code)) } if data.options.isHTML() { writeHTMLHeader(ctx, data) } writeFooter(ctx, clock.Now(ctx.Context), ierr, data.options.isHTML()) }
[ "func", "writeErrorPage", "(", "ctx", "*", "router", ".", "Context", ",", "err", "error", ",", "data", "logData", ")", "{", "ierr", ":=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "switch", "code", ":=", "grpcutil", ".", "Code", "(", "err", ")", ";", "code", "{", "case", "codes", ".", "Unauthenticated", ":", "// Redirect to login screen.", "var", "u", "string", "\n", "u", ",", "ierr", "=", "auth", ".", "LoginURL", "(", "ctx", ".", "Context", ",", "ctx", ".", "Request", ".", "URL", ".", "RequestURI", "(", ")", ")", "\n", "if", "ierr", "==", "nil", "{", "http", ".", "Redirect", "(", "ctx", ".", "Writer", ",", "ctx", ".", "Request", ",", "u", ",", "http", ".", "StatusFound", ")", "\n", "return", "\n", "}", "\n", "logging", ".", "WithError", "(", "ierr", ")", ".", "Errorf", "(", "ctx", ".", "Context", ",", "\"", "\"", ")", "\n", "fallthrough", "\n", "case", "codes", ".", "Internal", ":", "// Hide internal errors, expose all other errors.", "ctx", ".", "Writer", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "default", ":", "ierr", "=", "err", "\n", "ctx", ".", "Writer", ".", "WriteHeader", "(", "grpcutil", ".", "CodeStatus", "(", "code", ")", ")", "\n", "}", "\n", "if", "data", ".", "options", ".", "isHTML", "(", ")", "{", "writeHTMLHeader", "(", "ctx", ",", "data", ")", "\n", "}", "\n", "writeFooter", "(", "ctx", ",", "clock", ".", "Now", "(", "ctx", ".", "Context", ")", ",", "ierr", ",", "data", ".", "options", ".", "isHTML", "(", ")", ")", "\n", "}" ]
// writeErrorPage renders an error page.
[ "writeErrorPage", "renders", "an", "error", "page", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L602-L626
7,510
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
gradient
func gradient(from, to color.RGBA, scale float64) (result color.RGBA) { scale = math.Max(math.Min(scale, 1.0), 0.0) result.R = linearScale(from.R, to.R, scale) result.G = linearScale(from.G, to.G, scale) result.B = linearScale(from.B, to.B, scale) return }
go
func gradient(from, to color.RGBA, scale float64) (result color.RGBA) { scale = math.Max(math.Min(scale, 1.0), 0.0) result.R = linearScale(from.R, to.R, scale) result.G = linearScale(from.G, to.G, scale) result.B = linearScale(from.B, to.B, scale) return }
[ "func", "gradient", "(", "from", ",", "to", "color", ".", "RGBA", ",", "scale", "float64", ")", "(", "result", "color", ".", "RGBA", ")", "{", "scale", "=", "math", ".", "Max", "(", "math", ".", "Min", "(", "scale", ",", "1.0", ")", ",", "0.0", ")", "\n", "result", ".", "R", "=", "linearScale", "(", "from", ".", "R", ",", "to", ".", "R", ",", "scale", ")", "\n", "result", ".", "G", "=", "linearScale", "(", "from", ".", "G", ",", "to", ".", "G", ",", "scale", ")", "\n", "result", ".", "B", "=", "linearScale", "(", "from", ".", "B", ",", "to", ".", "B", ",", "scale", ")", "\n", "return", "\n", "}" ]
// gradient produces a color between from and to colors // given a scale between 0.0 to 1.0, with each of the color // components multiplied.
[ "gradient", "produces", "a", "color", "between", "from", "and", "to", "colors", "given", "a", "scale", "between", "0", ".", "0", "to", "1", ".", "0", "with", "each", "of", "the", "color", "components", "multiplied", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L690-L696
7,511
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
serve
func serve(c context.Context, data logData, w http.ResponseWriter) (err error) { // Note: Always put errors in merr instead of returning err. // The following defer will drop whatever err is in the named return // and replace it with merr. // This is done so that all errors can be aggregated. merr := errors.MultiError{} defer func() { if merr.First() == nil { err = nil } else { err = merr } }() flusher, ok := w.(http.Flusher) if !ok { logging.Errorf(c, "Could not obtain the flusher from the http.ResponseWriter. "+ "The ResponseWriter was probably overriden by a middleware. "+ "Logs will not stream correctly until this is fixed.") flusher = &nopFlusher{} } prevDuration := time.Duration(0) // Serve the logs. for logResp := range data.ch { log, ierr := logResp.log, logResp.err if ierr != nil { merr = append(merr, ierr) if ierr := errorTemplate.Execute(w, ierr); ierr != nil { merr = append(merr, ierr) } continue } for i, line := range log.GetText().GetLines() { // For html full mode, we escape and wrap each line with a div. // For html lite mode, just escape the line. // For raw mode, we just regurgitate the line. var ierr error switch data.options.format { case formatHTMLFull: lt := logLineStruct{ // Note: We want to use PrefixIndex because we might be viewing more than 1 stream. ID: fmt.Sprintf("L%d_%d", log.PrefixIndex, i), // The templating engine below escapes the lines for us. Text: string(line.GetValue()), } // Add in timestamp information, if available. duration, perr := ptypes.Duration(log.GetTimeOffset()) if perr != nil { logging.WithError(perr).Debugf(c, "Got error while converting duration") duration = prevDuration } lt.DataTimestamp = logResp.stream.Timestamp.Add(duration).UnixNano() / 1e6 lt.DurationInfo = durationInfo(prevDuration, duration) prevDuration = duration ierr = lineTemplate.Execute(w, lt) case formatHTMLLite: text := template.HTMLEscapeString(string(line.GetValue())) _, ierr = fmt.Fprintf(w, "%s\n", text) case formatRAW: _, ierr = fmt.Fprintf(w, "%s%s", line.GetValue(), line.GetDelimiter()) default: panic("Impossible") } if ierr != nil { merr = append(merr, ierr) } } if log == nil { // Nil log is a signal that the fetcher completed a cycle of fetches // and is sleeping. Flush out all the data in the ResponseWriter so that // the user can see it. // The go ResponseWriter will not flush until it reaches its threshold. flusher.Flush() } } return }
go
func serve(c context.Context, data logData, w http.ResponseWriter) (err error) { // Note: Always put errors in merr instead of returning err. // The following defer will drop whatever err is in the named return // and replace it with merr. // This is done so that all errors can be aggregated. merr := errors.MultiError{} defer func() { if merr.First() == nil { err = nil } else { err = merr } }() flusher, ok := w.(http.Flusher) if !ok { logging.Errorf(c, "Could not obtain the flusher from the http.ResponseWriter. "+ "The ResponseWriter was probably overriden by a middleware. "+ "Logs will not stream correctly until this is fixed.") flusher = &nopFlusher{} } prevDuration := time.Duration(0) // Serve the logs. for logResp := range data.ch { log, ierr := logResp.log, logResp.err if ierr != nil { merr = append(merr, ierr) if ierr := errorTemplate.Execute(w, ierr); ierr != nil { merr = append(merr, ierr) } continue } for i, line := range log.GetText().GetLines() { // For html full mode, we escape and wrap each line with a div. // For html lite mode, just escape the line. // For raw mode, we just regurgitate the line. var ierr error switch data.options.format { case formatHTMLFull: lt := logLineStruct{ // Note: We want to use PrefixIndex because we might be viewing more than 1 stream. ID: fmt.Sprintf("L%d_%d", log.PrefixIndex, i), // The templating engine below escapes the lines for us. Text: string(line.GetValue()), } // Add in timestamp information, if available. duration, perr := ptypes.Duration(log.GetTimeOffset()) if perr != nil { logging.WithError(perr).Debugf(c, "Got error while converting duration") duration = prevDuration } lt.DataTimestamp = logResp.stream.Timestamp.Add(duration).UnixNano() / 1e6 lt.DurationInfo = durationInfo(prevDuration, duration) prevDuration = duration ierr = lineTemplate.Execute(w, lt) case formatHTMLLite: text := template.HTMLEscapeString(string(line.GetValue())) _, ierr = fmt.Fprintf(w, "%s\n", text) case formatRAW: _, ierr = fmt.Fprintf(w, "%s%s", line.GetValue(), line.GetDelimiter()) default: panic("Impossible") } if ierr != nil { merr = append(merr, ierr) } } if log == nil { // Nil log is a signal that the fetcher completed a cycle of fetches // and is sleeping. Flush out all the data in the ResponseWriter so that // the user can see it. // The go ResponseWriter will not flush until it reaches its threshold. flusher.Flush() } } return }
[ "func", "serve", "(", "c", "context", ".", "Context", ",", "data", "logData", ",", "w", "http", ".", "ResponseWriter", ")", "(", "err", "error", ")", "{", "// Note: Always put errors in merr instead of returning err.", "// The following defer will drop whatever err is in the named return", "// and replace it with merr.", "// This is done so that all errors can be aggregated.", "merr", ":=", "errors", ".", "MultiError", "{", "}", "\n", "defer", "func", "(", ")", "{", "if", "merr", ".", "First", "(", ")", "==", "nil", "{", "err", "=", "nil", "\n", "}", "else", "{", "err", "=", "merr", "\n", "}", "\n", "}", "(", ")", "\n\n", "flusher", ",", "ok", ":=", "w", ".", "(", "http", ".", "Flusher", ")", "\n", "if", "!", "ok", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "flusher", "=", "&", "nopFlusher", "{", "}", "\n", "}", "\n", "prevDuration", ":=", "time", ".", "Duration", "(", "0", ")", "\n", "// Serve the logs.", "for", "logResp", ":=", "range", "data", ".", "ch", "{", "log", ",", "ierr", ":=", "logResp", ".", "log", ",", "logResp", ".", "err", "\n", "if", "ierr", "!=", "nil", "{", "merr", "=", "append", "(", "merr", ",", "ierr", ")", "\n", "if", "ierr", ":=", "errorTemplate", ".", "Execute", "(", "w", ",", "ierr", ")", ";", "ierr", "!=", "nil", "{", "merr", "=", "append", "(", "merr", ",", "ierr", ")", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "for", "i", ",", "line", ":=", "range", "log", ".", "GetText", "(", ")", ".", "GetLines", "(", ")", "{", "// For html full mode, we escape and wrap each line with a div.", "// For html lite mode, just escape the line.", "// For raw mode, we just regurgitate the line.", "var", "ierr", "error", "\n", "switch", "data", ".", "options", ".", "format", "{", "case", "formatHTMLFull", ":", "lt", ":=", "logLineStruct", "{", "// Note: We want to use PrefixIndex because we might be viewing more than 1 stream.", "ID", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "log", ".", "PrefixIndex", ",", "i", ")", ",", "// The templating engine below escapes the lines for us.", "Text", ":", "string", "(", "line", ".", "GetValue", "(", ")", ")", ",", "}", "\n", "// Add in timestamp information, if available.", "duration", ",", "perr", ":=", "ptypes", ".", "Duration", "(", "log", ".", "GetTimeOffset", "(", ")", ")", "\n", "if", "perr", "!=", "nil", "{", "logging", ".", "WithError", "(", "perr", ")", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "duration", "=", "prevDuration", "\n", "}", "\n", "lt", ".", "DataTimestamp", "=", "logResp", ".", "stream", ".", "Timestamp", ".", "Add", "(", "duration", ")", ".", "UnixNano", "(", ")", "/", "1e6", "\n", "lt", ".", "DurationInfo", "=", "durationInfo", "(", "prevDuration", ",", "duration", ")", "\n", "prevDuration", "=", "duration", "\n", "ierr", "=", "lineTemplate", ".", "Execute", "(", "w", ",", "lt", ")", "\n", "case", "formatHTMLLite", ":", "text", ":=", "template", ".", "HTMLEscapeString", "(", "string", "(", "line", ".", "GetValue", "(", ")", ")", ")", "\n", "_", ",", "ierr", "=", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "text", ")", "\n", "case", "formatRAW", ":", "_", ",", "ierr", "=", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\"", ",", "line", ".", "GetValue", "(", ")", ",", "line", ".", "GetDelimiter", "(", ")", ")", "\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "ierr", "!=", "nil", "{", "merr", "=", "append", "(", "merr", ",", "ierr", ")", "\n", "}", "\n", "}", "\n\n", "if", "log", "==", "nil", "{", "// Nil log is a signal that the fetcher completed a cycle of fetches", "// and is sleeping. Flush out all the data in the ResponseWriter so that", "// the user can see it.", "// The go ResponseWriter will not flush until it reaches its threshold.", "flusher", ".", "Flush", "(", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// serve reads log entries from data.ch and writes into w.
[ "serve", "reads", "log", "entries", "from", "data", ".", "ch", "and", "writes", "into", "w", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L762-L841
7,512
luci/luci-go
logdog/appengine/coordinator/flex/logs/http.go
GetHandler
func GetHandler(ctx *router.Context) { start := clock.Now(ctx.Context) // Start the fetcher and wait for fetched logs to arrive into ch. data, err := startFetch(ctx.Context, ctx.Request, ctx.Params.ByName("path")) if err != nil { logging.WithError(err).Errorf(ctx.Context, "failed to start fetch") writeErrorPage(ctx, err, data) return } writeOKHeaders(ctx, data) // Write the log contents and then the footer. err = serve(ctx.Context, data, ctx.Writer) if err != nil { logging.WithError(err).Errorf(ctx.Context, "failed to serve logs") } writeFooter(ctx, start, err, data.options.isHTML()) }
go
func GetHandler(ctx *router.Context) { start := clock.Now(ctx.Context) // Start the fetcher and wait for fetched logs to arrive into ch. data, err := startFetch(ctx.Context, ctx.Request, ctx.Params.ByName("path")) if err != nil { logging.WithError(err).Errorf(ctx.Context, "failed to start fetch") writeErrorPage(ctx, err, data) return } writeOKHeaders(ctx, data) // Write the log contents and then the footer. err = serve(ctx.Context, data, ctx.Writer) if err != nil { logging.WithError(err).Errorf(ctx.Context, "failed to serve logs") } writeFooter(ctx, start, err, data.options.isHTML()) }
[ "func", "GetHandler", "(", "ctx", "*", "router", ".", "Context", ")", "{", "start", ":=", "clock", ".", "Now", "(", "ctx", ".", "Context", ")", "\n", "// Start the fetcher and wait for fetched logs to arrive into ch.", "data", ",", "err", ":=", "startFetch", "(", "ctx", ".", "Context", ",", "ctx", ".", "Request", ",", "ctx", ".", "Params", ".", "ByName", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "ctx", ".", "Context", ",", "\"", "\"", ")", "\n", "writeErrorPage", "(", "ctx", ",", "err", ",", "data", ")", "\n", "return", "\n", "}", "\n", "writeOKHeaders", "(", "ctx", ",", "data", ")", "\n\n", "// Write the log contents and then the footer.", "err", "=", "serve", "(", "ctx", ".", "Context", ",", "data", ",", "ctx", ".", "Writer", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "ctx", ".", "Context", ",", "\"", "\"", ")", "\n", "}", "\n", "writeFooter", "(", "ctx", ",", "start", ",", "err", ",", "data", ".", "options", ".", "isHTML", "(", ")", ")", "\n", "}" ]
// GetHandler is an HTTP handler for retrieving logs.
[ "GetHandler", "is", "an", "HTTP", "handler", "for", "retrieving", "logs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/http.go#L844-L861
7,513
luci/luci-go
grpc/internal/svctool/parser.go
parsePackage
func (p *parser) parsePackage(fileNames []string) error { if len(fileNames) == 0 { return fmt.Errorf("fileNames is empty") } for i, name := range fileNames { if i > 0 && filepath.Dir(name) != filepath.Dir(fileNames[0]) { return fmt.Errorf("Go files belong to different directories") } if !strings.HasSuffix(name, ".go") { continue } file, err := goparser.ParseFile(p.fileSet, name, nil, 0) if err != nil { return fmt.Errorf("parsing %s: %s", name, err) } if len(p.files) > 0 && file.Name.Name != p.files[0].Name.Name { return fmt.Errorf("Go files belong to different packages") } p.files = append(p.files, file) } if len(p.files) == 0 { return fmt.Errorf("no buildable Go files") } return nil }
go
func (p *parser) parsePackage(fileNames []string) error { if len(fileNames) == 0 { return fmt.Errorf("fileNames is empty") } for i, name := range fileNames { if i > 0 && filepath.Dir(name) != filepath.Dir(fileNames[0]) { return fmt.Errorf("Go files belong to different directories") } if !strings.HasSuffix(name, ".go") { continue } file, err := goparser.ParseFile(p.fileSet, name, nil, 0) if err != nil { return fmt.Errorf("parsing %s: %s", name, err) } if len(p.files) > 0 && file.Name.Name != p.files[0].Name.Name { return fmt.Errorf("Go files belong to different packages") } p.files = append(p.files, file) } if len(p.files) == 0 { return fmt.Errorf("no buildable Go files") } return nil }
[ "func", "(", "p", "*", "parser", ")", "parsePackage", "(", "fileNames", "[", "]", "string", ")", "error", "{", "if", "len", "(", "fileNames", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ",", "name", ":=", "range", "fileNames", "{", "if", "i", ">", "0", "&&", "filepath", ".", "Dir", "(", "name", ")", "!=", "filepath", ".", "Dir", "(", "fileNames", "[", "0", "]", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "name", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "file", ",", "err", ":=", "goparser", ".", "ParseFile", "(", "p", ".", "fileSet", ",", "name", ",", "nil", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "p", ".", "files", ")", ">", "0", "&&", "file", ".", "Name", ".", "Name", "!=", "p", ".", "files", "[", "0", "]", ".", "Name", ".", "Name", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "files", "=", "append", "(", "p", ".", "files", ",", "file", ")", "\n", "}", "\n", "if", "len", "(", "p", ".", "files", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// parsePackage parses .go files and fills in p.files with the ASTs. // Files must be in the same directory and have the same package name.
[ "parsePackage", "parses", ".", "go", "files", "and", "fills", "in", "p", ".", "files", "with", "the", "ASTs", ".", "Files", "must", "be", "in", "the", "same", "directory", "and", "have", "the", "same", "package", "name", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/internal/svctool/parser.go#L50-L74
7,514
luci/luci-go
grpc/internal/svctool/parser.go
recordImport
func (p *parser) recordImport(f *ast.File, typ ast.Expr) error { if star, ok := typ.(*ast.StarExpr); ok { typ = star.X } sel, ok := typ.(*ast.SelectorExpr) if !ok { return nil } pkgID, ok := sel.X.(*ast.Ident) if !ok { return nil } if _, ok := p.extraImports[pkgID.Name]; ok { return nil } path := "" for _, i := range f.Imports { if i.Name.Name == pkgID.Name { path = strings.Trim(i.Path.Value, `"`) break } } if path == "" { return fmt.Errorf("could not resolve package %s", pkgID.Name) } if p.extraImports == nil { p.extraImports = make(map[string]string) } p.extraImports[pkgID.Name] = path return nil }
go
func (p *parser) recordImport(f *ast.File, typ ast.Expr) error { if star, ok := typ.(*ast.StarExpr); ok { typ = star.X } sel, ok := typ.(*ast.SelectorExpr) if !ok { return nil } pkgID, ok := sel.X.(*ast.Ident) if !ok { return nil } if _, ok := p.extraImports[pkgID.Name]; ok { return nil } path := "" for _, i := range f.Imports { if i.Name.Name == pkgID.Name { path = strings.Trim(i.Path.Value, `"`) break } } if path == "" { return fmt.Errorf("could not resolve package %s", pkgID.Name) } if p.extraImports == nil { p.extraImports = make(map[string]string) } p.extraImports[pkgID.Name] = path return nil }
[ "func", "(", "p", "*", "parser", ")", "recordImport", "(", "f", "*", "ast", ".", "File", ",", "typ", "ast", ".", "Expr", ")", "error", "{", "if", "star", ",", "ok", ":=", "typ", ".", "(", "*", "ast", ".", "StarExpr", ")", ";", "ok", "{", "typ", "=", "star", ".", "X", "\n", "}", "\n\n", "sel", ",", "ok", ":=", "typ", ".", "(", "*", "ast", ".", "SelectorExpr", ")", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "pkgID", ",", "ok", ":=", "sel", ".", "X", ".", "(", "*", "ast", ".", "Ident", ")", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "p", ".", "extraImports", "[", "pkgID", ".", "Name", "]", ";", "ok", "{", "return", "nil", "\n", "}", "\n\n", "path", ":=", "\"", "\"", "\n", "for", "_", ",", "i", ":=", "range", "f", ".", "Imports", "{", "if", "i", ".", "Name", ".", "Name", "==", "pkgID", ".", "Name", "{", "path", "=", "strings", ".", "Trim", "(", "i", ".", "Path", ".", "Value", ",", "`\"`", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "path", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pkgID", ".", "Name", ")", "\n", "}", "\n", "if", "p", ".", "extraImports", "==", "nil", "{", "p", ".", "extraImports", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "p", ".", "extraImports", "[", "pkgID", ".", "Name", "]", "=", "path", "\n", "return", "nil", "\n", "}" ]
// recordImport extracts the package referenced by type expression typ, // resolves its path and saves to p.extraImports.
[ "recordImport", "extracts", "the", "package", "referenced", "by", "type", "expression", "typ", "resolves", "its", "path", "and", "saves", "to", "p", ".", "extraImports", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/internal/svctool/parser.go#L89-L122
7,515
luci/luci-go
grpc/internal/svctool/parser.go
exprString
func (p *parser) exprString(expr ast.Expr) (string, error) { p.exprStrBuf.Reset() err := printer.Fprint(&p.exprStrBuf, p.fileSet, expr) return p.exprStrBuf.String(), err }
go
func (p *parser) exprString(expr ast.Expr) (string, error) { p.exprStrBuf.Reset() err := printer.Fprint(&p.exprStrBuf, p.fileSet, expr) return p.exprStrBuf.String(), err }
[ "func", "(", "p", "*", "parser", ")", "exprString", "(", "expr", "ast", ".", "Expr", ")", "(", "string", ",", "error", ")", "{", "p", ".", "exprStrBuf", ".", "Reset", "(", ")", "\n", "err", ":=", "printer", ".", "Fprint", "(", "&", "p", ".", "exprStrBuf", ",", "p", ".", "fileSet", ",", "expr", ")", "\n", "return", "p", ".", "exprStrBuf", ".", "String", "(", ")", ",", "err", "\n", "}" ]
// exprString renders expr to string.
[ "exprString", "renders", "expr", "to", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/internal/svctool/parser.go#L237-L241
7,516
luci/luci-go
dm/appengine/mutate/timeout_execution.go
ResetExecutionTimeout
func ResetExecutionTimeout(c context.Context, e *model.Execution) error { howLong := time.Duration(0) switch e.State { case dm.Execution_SCHEDULING: howLong = e.TimeToStart case dm.Execution_RUNNING: howLong = e.TimeToRun case dm.Execution_STOPPING: howLong = e.TimeToStop } eid := e.GetEID() key := model.ExecutionKeyFromID(c, eid) if howLong == 0 { return tumble.CancelNamedMutations(c, key, "timeout") } return tumble.PutNamedMutations(c, key, map[string]tumble.Mutation{ "timeout": &TimeoutExecution{eid, e.State, 0, clock.Now(c).UTC().Add(howLong)}, }) }
go
func ResetExecutionTimeout(c context.Context, e *model.Execution) error { howLong := time.Duration(0) switch e.State { case dm.Execution_SCHEDULING: howLong = e.TimeToStart case dm.Execution_RUNNING: howLong = e.TimeToRun case dm.Execution_STOPPING: howLong = e.TimeToStop } eid := e.GetEID() key := model.ExecutionKeyFromID(c, eid) if howLong == 0 { return tumble.CancelNamedMutations(c, key, "timeout") } return tumble.PutNamedMutations(c, key, map[string]tumble.Mutation{ "timeout": &TimeoutExecution{eid, e.State, 0, clock.Now(c).UTC().Add(howLong)}, }) }
[ "func", "ResetExecutionTimeout", "(", "c", "context", ".", "Context", ",", "e", "*", "model", ".", "Execution", ")", "error", "{", "howLong", ":=", "time", ".", "Duration", "(", "0", ")", "\n", "switch", "e", ".", "State", "{", "case", "dm", ".", "Execution_SCHEDULING", ":", "howLong", "=", "e", ".", "TimeToStart", "\n", "case", "dm", ".", "Execution_RUNNING", ":", "howLong", "=", "e", ".", "TimeToRun", "\n", "case", "dm", ".", "Execution_STOPPING", ":", "howLong", "=", "e", ".", "TimeToStop", "\n", "}", "\n", "eid", ":=", "e", ".", "GetEID", "(", ")", "\n", "key", ":=", "model", ".", "ExecutionKeyFromID", "(", "c", ",", "eid", ")", "\n", "if", "howLong", "==", "0", "{", "return", "tumble", ".", "CancelNamedMutations", "(", "c", ",", "key", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "tumble", ".", "PutNamedMutations", "(", "c", ",", "key", ",", "map", "[", "string", "]", "tumble", ".", "Mutation", "{", "\"", "\"", ":", "&", "TimeoutExecution", "{", "eid", ",", "e", ".", "State", ",", "0", ",", "clock", ".", "Now", "(", "c", ")", ".", "UTC", "(", ")", ".", "Add", "(", "howLong", ")", "}", ",", "}", ")", "\n", "}" ]
// ResetExecutionTimeout schedules a Timeout for this Execution. It inspects the // Execution's State to determine which timeout should be set, if any. If no // timeout should be active, this will cancel any existing timeouts for this // Execution.
[ "ResetExecutionTimeout", "schedules", "a", "Timeout", "for", "this", "Execution", ".", "It", "inspects", "the", "Execution", "s", "State", "to", "determine", "which", "timeout", "should", "be", "set", "if", "any", ".", "If", "no", "timeout", "should", "be", "active", "this", "will", "cancel", "any", "existing", "timeouts", "for", "this", "Execution", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/mutate/timeout_execution.go#L143-L161
7,517
luci/luci-go
lucicfg/cli/cmds/generate/generate.go
Cmd
func Cmd(params base.Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "generate SCRIPT", ShortDesc: "interprets a high-level config, generating *.cfg files", LongDesc: `Interprets a high-level config, generating *.cfg files. Writes generated configs to the directory given via -config-dir or via lucicfg.config(config_dir=...) statement in the script. If it is '-', just prints them to stdout. If -validate is given, sends the generated config to LUCI Config service for validation. This can also be done separately via 'validate' subcommand. If the generation stage fails, doesn't overwrite any files on disk. If the generation succeeds, but the validation fails, the new generated files are kept on disk, so they can be manually examined for reasons they are invalid. `, CommandRun: func() subcommands.CommandRun { gr := &generateRun{} gr.Init(params) gr.AddMetaFlags() gr.Flags.BoolVar(&gr.validate, "validate", false, "Validate the generate configs by sending them to LUCI Config") return gr }, } }
go
func Cmd(params base.Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "generate SCRIPT", ShortDesc: "interprets a high-level config, generating *.cfg files", LongDesc: `Interprets a high-level config, generating *.cfg files. Writes generated configs to the directory given via -config-dir or via lucicfg.config(config_dir=...) statement in the script. If it is '-', just prints them to stdout. If -validate is given, sends the generated config to LUCI Config service for validation. This can also be done separately via 'validate' subcommand. If the generation stage fails, doesn't overwrite any files on disk. If the generation succeeds, but the validation fails, the new generated files are kept on disk, so they can be manually examined for reasons they are invalid. `, CommandRun: func() subcommands.CommandRun { gr := &generateRun{} gr.Init(params) gr.AddMetaFlags() gr.Flags.BoolVar(&gr.validate, "validate", false, "Validate the generate configs by sending them to LUCI Config") return gr }, } }
[ "func", "Cmd", "(", "params", "base", ".", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "`Interprets a high-level config, generating *.cfg files.\n\nWrites generated configs to the directory given via -config-dir or via\nlucicfg.config(config_dir=...) statement in the script. If it is '-', just\nprints them to stdout.\n\nIf -validate is given, sends the generated config to LUCI Config service for\nvalidation. This can also be done separately via 'validate' subcommand.\n\nIf the generation stage fails, doesn't overwrite any files on disk. If the\ngeneration succeeds, but the validation fails, the new generated files are kept\non disk, so they can be manually examined for reasons they are invalid.\n`", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "gr", ":=", "&", "generateRun", "{", "}", "\n", "gr", ".", "Init", "(", "params", ")", "\n", "gr", ".", "AddMetaFlags", "(", ")", "\n", "gr", ".", "Flags", ".", "BoolVar", "(", "&", "gr", ".", "validate", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "return", "gr", "\n", "}", ",", "}", "\n", "}" ]
// Cmd is 'generate' subcommand.
[ "Cmd", "is", "generate", "subcommand", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/cli/cmds/generate/generate.go#L33-L58
7,518
luci/luci-go
logdog/appengine/coordinator/flex/logs/get.go
Get
func (s *server) Get(c context.Context, req *logdog.GetRequest) (*logdog.GetResponse, error) { return s.getImpl(c, req, false) }
go
func (s *server) Get(c context.Context, req *logdog.GetRequest) (*logdog.GetResponse, error) { return s.getImpl(c, req, false) }
[ "func", "(", "s", "*", "server", ")", "Get", "(", "c", "context", ".", "Context", ",", "req", "*", "logdog", ".", "GetRequest", ")", "(", "*", "logdog", ".", "GetResponse", ",", "error", ")", "{", "return", "s", ".", "getImpl", "(", "c", ",", "req", ",", "false", ")", "\n", "}" ]
// Get returns state and log data for a single log stream.
[ "Get", "returns", "state", "and", "log", "data", "for", "a", "single", "log", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/get.go#L57-L59
7,519
luci/luci-go
logdog/appengine/coordinator/flex/logs/get.go
Tail
func (s *server) Tail(c context.Context, req *logdog.TailRequest) (*logdog.GetResponse, error) { r := logdog.GetRequest{ Project: req.Project, Path: req.Path, State: req.State, } return s.getImpl(c, &r, true) }
go
func (s *server) Tail(c context.Context, req *logdog.TailRequest) (*logdog.GetResponse, error) { r := logdog.GetRequest{ Project: req.Project, Path: req.Path, State: req.State, } return s.getImpl(c, &r, true) }
[ "func", "(", "s", "*", "server", ")", "Tail", "(", "c", "context", ".", "Context", ",", "req", "*", "logdog", ".", "TailRequest", ")", "(", "*", "logdog", ".", "GetResponse", ",", "error", ")", "{", "r", ":=", "logdog", ".", "GetRequest", "{", "Project", ":", "req", ".", "Project", ",", "Path", ":", "req", ".", "Path", ",", "State", ":", "req", ".", "State", ",", "}", "\n", "return", "s", ".", "getImpl", "(", "c", ",", "&", "r", ",", "true", ")", "\n", "}" ]
// Tail returns the last log entry for a given log stream.
[ "Tail", "returns", "the", "last", "log", "entry", "for", "a", "given", "log", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/get.go#L62-L69
7,520
luci/luci-go
logdog/appengine/coordinator/flex/logs/get.go
getImpl
func (s *server) getImpl(c context.Context, req *logdog.GetRequest, tail bool) (*logdog.GetResponse, error) { log.Fields{ "project": req.Project, "path": req.Path, "index": req.Index, "tail": tail, }.Debugf(c, "Received get request.") path := types.StreamPath(req.Path) if err := path.Validate(); err != nil { log.WithError(err).Errorf(c, "Invalid path supplied.") return nil, grpcutil.Errf(codes.InvalidArgument, "invalid path value") } ls := &coordinator.LogStream{ID: coordinator.LogStreamID(path)} lst := ls.State(c) log.Fields{ "id": ls.ID, }.Debugf(c, "Loading stream.") if err := ds.Get(c, ls, lst); err != nil { if ds.IsErrNoSuchEntity(err) { log.Warningf(c, "Log stream does not exist.") return nil, grpcutil.Errf(codes.NotFound, "path not found") } log.WithError(err).Errorf(c, "Failed to look up log stream.") return nil, grpcutil.Internal } // If this log entry is Purged and we're not admin, pretend it doesn't exist. if ls.Purged { if authErr := coordinator.IsAdminUser(c); authErr != nil { log.Fields{ log.ErrorKey: authErr, }.Warningf(c, "Non-superuser requested purged log.") return nil, grpcutil.Errf(codes.NotFound, "path not found") } } resp := logdog.GetResponse{} if req.State { resp.State = buildLogStreamState(ls, lst) var err error resp.Desc, err = ls.DescriptorValue() if err != nil { log.WithError(err).Errorf(c, "Failed to deserialize descriptor protobuf.") return nil, grpcutil.Internal } } // Retrieve requested logs from storage, if requested. startTime := clock.Now(c) if err := s.getLogs(c, req, &resp, tail, ls, lst); err != nil { log.WithError(err).Errorf(c, "Failed to get logs.") return nil, grpcutil.Internal } log.Fields{ "duration": clock.Now(c).Sub(startTime).String(), "logCount": len(resp.Logs), }.Debugf(c, "Get request completed successfully.") return &resp, nil }
go
func (s *server) getImpl(c context.Context, req *logdog.GetRequest, tail bool) (*logdog.GetResponse, error) { log.Fields{ "project": req.Project, "path": req.Path, "index": req.Index, "tail": tail, }.Debugf(c, "Received get request.") path := types.StreamPath(req.Path) if err := path.Validate(); err != nil { log.WithError(err).Errorf(c, "Invalid path supplied.") return nil, grpcutil.Errf(codes.InvalidArgument, "invalid path value") } ls := &coordinator.LogStream{ID: coordinator.LogStreamID(path)} lst := ls.State(c) log.Fields{ "id": ls.ID, }.Debugf(c, "Loading stream.") if err := ds.Get(c, ls, lst); err != nil { if ds.IsErrNoSuchEntity(err) { log.Warningf(c, "Log stream does not exist.") return nil, grpcutil.Errf(codes.NotFound, "path not found") } log.WithError(err).Errorf(c, "Failed to look up log stream.") return nil, grpcutil.Internal } // If this log entry is Purged and we're not admin, pretend it doesn't exist. if ls.Purged { if authErr := coordinator.IsAdminUser(c); authErr != nil { log.Fields{ log.ErrorKey: authErr, }.Warningf(c, "Non-superuser requested purged log.") return nil, grpcutil.Errf(codes.NotFound, "path not found") } } resp := logdog.GetResponse{} if req.State { resp.State = buildLogStreamState(ls, lst) var err error resp.Desc, err = ls.DescriptorValue() if err != nil { log.WithError(err).Errorf(c, "Failed to deserialize descriptor protobuf.") return nil, grpcutil.Internal } } // Retrieve requested logs from storage, if requested. startTime := clock.Now(c) if err := s.getLogs(c, req, &resp, tail, ls, lst); err != nil { log.WithError(err).Errorf(c, "Failed to get logs.") return nil, grpcutil.Internal } log.Fields{ "duration": clock.Now(c).Sub(startTime).String(), "logCount": len(resp.Logs), }.Debugf(c, "Get request completed successfully.") return &resp, nil }
[ "func", "(", "s", "*", "server", ")", "getImpl", "(", "c", "context", ".", "Context", ",", "req", "*", "logdog", ".", "GetRequest", ",", "tail", "bool", ")", "(", "*", "logdog", ".", "GetResponse", ",", "error", ")", "{", "log", ".", "Fields", "{", "\"", "\"", ":", "req", ".", "Project", ",", "\"", "\"", ":", "req", ".", "Path", ",", "\"", "\"", ":", "req", ".", "Index", ",", "\"", "\"", ":", "tail", ",", "}", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n\n", "path", ":=", "types", ".", "StreamPath", "(", "req", ".", "Path", ")", "\n", "if", "err", ":=", "path", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "Errf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "ls", ":=", "&", "coordinator", ".", "LogStream", "{", "ID", ":", "coordinator", ".", "LogStreamID", "(", "path", ")", "}", "\n", "lst", ":=", "ls", ".", "State", "(", "c", ")", "\n", "log", ".", "Fields", "{", "\"", "\"", ":", "ls", ".", "ID", ",", "}", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n\n", "if", "err", ":=", "ds", ".", "Get", "(", "c", ",", "ls", ",", "lst", ")", ";", "err", "!=", "nil", "{", "if", "ds", ".", "IsErrNoSuchEntity", "(", "err", ")", "{", "log", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "Errf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ")", "\n", "}", "\n\n", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "Internal", "\n", "}", "\n\n", "// If this log entry is Purged and we're not admin, pretend it doesn't exist.", "if", "ls", ".", "Purged", "{", "if", "authErr", ":=", "coordinator", ".", "IsAdminUser", "(", "c", ")", ";", "authErr", "!=", "nil", "{", "log", ".", "Fields", "{", "log", ".", "ErrorKey", ":", "authErr", ",", "}", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "Errf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "resp", ":=", "logdog", ".", "GetResponse", "{", "}", "\n", "if", "req", ".", "State", "{", "resp", ".", "State", "=", "buildLogStreamState", "(", "ls", ",", "lst", ")", "\n\n", "var", "err", "error", "\n", "resp", ".", "Desc", ",", "err", "=", "ls", ".", "DescriptorValue", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "Internal", "\n", "}", "\n", "}", "\n\n", "// Retrieve requested logs from storage, if requested.", "startTime", ":=", "clock", ".", "Now", "(", "c", ")", "\n", "if", "err", ":=", "s", ".", "getLogs", "(", "c", ",", "req", ",", "&", "resp", ",", "tail", ",", "ls", ",", "lst", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "grpcutil", ".", "Internal", "\n", "}", "\n\n", "log", ".", "Fields", "{", "\"", "\"", ":", "clock", ".", "Now", "(", "c", ")", ".", "Sub", "(", "startTime", ")", ".", "String", "(", ")", ",", "\"", "\"", ":", "len", "(", "resp", ".", "Logs", ")", ",", "}", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "&", "resp", ",", "nil", "\n", "}" ]
// getImpl is common code shared between Get and Tail endpoints.
[ "getImpl", "is", "common", "code", "shared", "between", "Get", "and", "Tail", "endpoints", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/logs/get.go#L72-L136
7,521
luci/luci-go
buildbucket/luciexe/listen.go
StreamRegistrationCallback
func (l *buildListener) StreamRegistrationCallback(desc *logpb.LogStreamDescriptor) bundler.StreamChunkCallback { if desc.Name == l.buildStreamName { switch { case desc.ContentType != protoutil.BuildMediaType: l.report(errors.Reason("stream %q has content type %q, expected %q", desc.Name, desc.ContentType, protoutil.BuildMediaType).Err()) case desc.StreamType != logpb.StreamType_DATAGRAM: l.report(errors.Reason("stream %q has type %q, expected %q", desc.Name, desc.StreamType, logpb.StreamType_DATAGRAM).Err()) default: return buffered_callback.GetWrappedDatagramCallback(l.onBuildChunk) } } // TODO(nodir): add support for sub-builds. return nil }
go
func (l *buildListener) StreamRegistrationCallback(desc *logpb.LogStreamDescriptor) bundler.StreamChunkCallback { if desc.Name == l.buildStreamName { switch { case desc.ContentType != protoutil.BuildMediaType: l.report(errors.Reason("stream %q has content type %q, expected %q", desc.Name, desc.ContentType, protoutil.BuildMediaType).Err()) case desc.StreamType != logpb.StreamType_DATAGRAM: l.report(errors.Reason("stream %q has type %q, expected %q", desc.Name, desc.StreamType, logpb.StreamType_DATAGRAM).Err()) default: return buffered_callback.GetWrappedDatagramCallback(l.onBuildChunk) } } // TODO(nodir): add support for sub-builds. return nil }
[ "func", "(", "l", "*", "buildListener", ")", "StreamRegistrationCallback", "(", "desc", "*", "logpb", ".", "LogStreamDescriptor", ")", "bundler", ".", "StreamChunkCallback", "{", "if", "desc", ".", "Name", "==", "l", ".", "buildStreamName", "{", "switch", "{", "case", "desc", ".", "ContentType", "!=", "protoutil", ".", "BuildMediaType", ":", "l", ".", "report", "(", "errors", ".", "Reason", "(", "\"", "\"", ",", "desc", ".", "Name", ",", "desc", ".", "ContentType", ",", "protoutil", ".", "BuildMediaType", ")", ".", "Err", "(", ")", ")", "\n", "case", "desc", ".", "StreamType", "!=", "logpb", ".", "StreamType_DATAGRAM", ":", "l", ".", "report", "(", "errors", ".", "Reason", "(", "\"", "\"", ",", "desc", ".", "Name", ",", "desc", ".", "StreamType", ",", "logpb", ".", "StreamType_DATAGRAM", ")", ".", "Err", "(", ")", ")", "\n", "default", ":", "return", "buffered_callback", ".", "GetWrappedDatagramCallback", "(", "l", ".", "onBuildChunk", ")", "\n", "}", "\n", "}", "\n\n", "// TODO(nodir): add support for sub-builds.", "return", "nil", "\n", "}" ]
// StreamRegistrationCallback can be used as logdogServer.StreamRegistrationCallback.
[ "StreamRegistrationCallback", "can", "be", "used", "as", "logdogServer", ".", "StreamRegistrationCallback", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/listen.go#L67-L82
7,522
luci/luci-go
buildbucket/luciexe/listen.go
Build
func (l *buildListener) Build() *pb.Build { l.buildMU.Lock() defer l.buildMU.Unlock() if l.build == nil { return nil } return proto.Clone(l.build).(*pb.Build) }
go
func (l *buildListener) Build() *pb.Build { l.buildMU.Lock() defer l.buildMU.Unlock() if l.build == nil { return nil } return proto.Clone(l.build).(*pb.Build) }
[ "func", "(", "l", "*", "buildListener", ")", "Build", "(", ")", "*", "pb", ".", "Build", "{", "l", ".", "buildMU", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "buildMU", ".", "Unlock", "(", ")", "\n\n", "if", "l", ".", "build", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "proto", ".", "Clone", "(", "l", ".", "build", ")", ".", "(", "*", "pb", ".", "Build", ")", "\n", "}" ]
// Build returns most recently retrieved Build message.
[ "Build", "returns", "most", "recently", "retrieved", "Build", "message", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/listen.go#L118-L126
7,523
luci/luci-go
buildbucket/luciexe/listen.go
report
func (l *buildListener) report(err error) { l.onErr(errors.Annotate(err, "LUCI executable protocol violation").Err()) }
go
func (l *buildListener) report(err error) { l.onErr(errors.Annotate(err, "LUCI executable protocol violation").Err()) }
[ "func", "(", "l", "*", "buildListener", ")", "report", "(", "err", "error", ")", "{", "l", ".", "onErr", "(", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", ")", "\n", "}" ]
// report reports a LUCI executable protocol violation via l.onErr.
[ "report", "reports", "a", "LUCI", "executable", "protocol", "violation", "via", "l", ".", "onErr", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/listen.go#L149-L151
7,524
luci/luci-go
milo/buildsource/buildbucket/builder.go
NewBuilderID
func NewBuilderID(v1Bucket, builder string) (bid BuilderID) { bid.Project, bid.Bucket = deprecated.BucketNameToV2(v1Bucket) bid.Builder = builder return }
go
func NewBuilderID(v1Bucket, builder string) (bid BuilderID) { bid.Project, bid.Bucket = deprecated.BucketNameToV2(v1Bucket) bid.Builder = builder return }
[ "func", "NewBuilderID", "(", "v1Bucket", ",", "builder", "string", ")", "(", "bid", "BuilderID", ")", "{", "bid", ".", "Project", ",", "bid", ".", "Bucket", "=", "deprecated", ".", "BucketNameToV2", "(", "v1Bucket", ")", "\n", "bid", ".", "Builder", "=", "builder", "\n", "return", "\n", "}" ]
// NewBuilderID does what it says.
[ "NewBuilderID", "does", "what", "it", "says", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/builder.go#L55-L59
7,525
luci/luci-go
milo/buildsource/buildbucket/builder.go
V1Bucket
func (b BuilderID) V1Bucket() string { return fmt.Sprintf("luci.%s.%s", b.Project, b.Bucket) }
go
func (b BuilderID) V1Bucket() string { return fmt.Sprintf("luci.%s.%s", b.Project, b.Bucket) }
[ "func", "(", "b", "BuilderID", ")", "V1Bucket", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "Project", ",", "b", ".", "Bucket", ")", "\n", "}" ]
// V1Bucket returns the buildbucket v1 representation of the bucket name, which // is what we use in Milo.
[ "V1Bucket", "returns", "the", "buildbucket", "v1", "representation", "of", "the", "bucket", "name", "which", "is", "what", "we", "use", "in", "Milo", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/builder.go#L63-L65
7,526
luci/luci-go
milo/buildsource/buildbucket/builder.go
String
func (b BuilderID) String() string { return fmt.Sprintf("buildbucket/%s/%s", b.V1Bucket(), b.Builder) }
go
func (b BuilderID) String() string { return fmt.Sprintf("buildbucket/%s/%s", b.V1Bucket(), b.Builder) }
[ "func", "(", "b", "BuilderID", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "V1Bucket", "(", ")", ",", "b", ".", "Builder", ")", "\n", "}" ]
// String returns the canonical format of BuilderID.
[ "String", "returns", "the", "canonical", "format", "of", "BuilderID", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/builder.go#L68-L70
7,527
luci/luci-go
milo/buildsource/buildbucket/builder.go
fetchBuilds
func fetchBuilds(c context.Context, client *bbv1.Service, bid BuilderID, status string, limit int, cursor string) ([]*bbv1.ApiCommonBuildMessage, string, error) { c, _ = context.WithTimeout(c, bbRPCTimeout) search := client.Search() search.Context(c) search.Bucket(bid.V1Bucket()) search.Status(status) search.Tag(strpair.Format(bbv1.TagBuilder, bid.Builder)) search.IncludeExperimental(true) search.StartCursor(cursor) if limit < 0 { limit = 100 } start := clock.Now(c) msgs, cursor, err := search.Fetch(limit, nil) if err != nil { return nil, "", err } logging.Infof(c, "Fetched %d %s builds in %s", len(msgs), status, clock.Since(c, start)) return msgs, cursor, nil }
go
func fetchBuilds(c context.Context, client *bbv1.Service, bid BuilderID, status string, limit int, cursor string) ([]*bbv1.ApiCommonBuildMessage, string, error) { c, _ = context.WithTimeout(c, bbRPCTimeout) search := client.Search() search.Context(c) search.Bucket(bid.V1Bucket()) search.Status(status) search.Tag(strpair.Format(bbv1.TagBuilder, bid.Builder)) search.IncludeExperimental(true) search.StartCursor(cursor) if limit < 0 { limit = 100 } start := clock.Now(c) msgs, cursor, err := search.Fetch(limit, nil) if err != nil { return nil, "", err } logging.Infof(c, "Fetched %d %s builds in %s", len(msgs), status, clock.Since(c, start)) return msgs, cursor, nil }
[ "func", "fetchBuilds", "(", "c", "context", ".", "Context", ",", "client", "*", "bbv1", ".", "Service", ",", "bid", "BuilderID", ",", "status", "string", ",", "limit", "int", ",", "cursor", "string", ")", "(", "[", "]", "*", "bbv1", ".", "ApiCommonBuildMessage", ",", "string", ",", "error", ")", "{", "c", ",", "_", "=", "context", ".", "WithTimeout", "(", "c", ",", "bbRPCTimeout", ")", "\n", "search", ":=", "client", ".", "Search", "(", ")", "\n", "search", ".", "Context", "(", "c", ")", "\n", "search", ".", "Bucket", "(", "bid", ".", "V1Bucket", "(", ")", ")", "\n", "search", ".", "Status", "(", "status", ")", "\n", "search", ".", "Tag", "(", "strpair", ".", "Format", "(", "bbv1", ".", "TagBuilder", ",", "bid", ".", "Builder", ")", ")", "\n", "search", ".", "IncludeExperimental", "(", "true", ")", "\n", "search", ".", "StartCursor", "(", "cursor", ")", "\n\n", "if", "limit", "<", "0", "{", "limit", "=", "100", "\n", "}", "\n\n", "start", ":=", "clock", ".", "Now", "(", "c", ")", "\n", "msgs", ",", "cursor", ",", "err", ":=", "search", ".", "Fetch", "(", "limit", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "len", "(", "msgs", ")", ",", "status", ",", "clock", ".", "Since", "(", "c", ",", "start", ")", ")", "\n", "return", "msgs", ",", "cursor", ",", "nil", "\n", "}" ]
// fetchBuilds fetches builds given a criteria. // The returned builds are sorted by build creation descending. // count defines maximum number of builds to fetch; if <0, defaults to 100.
[ "fetchBuilds", "fetches", "builds", "given", "a", "criteria", ".", "The", "returned", "builds", "are", "sorted", "by", "build", "creation", "descending", ".", "count", "defines", "maximum", "number", "of", "builds", "to", "fetch", ";", "if", "<0", "defaults", "to", "100", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/builder.go#L75-L98
7,528
luci/luci-go
milo/buildsource/buildbucket/builder.go
ensureDefined
func ensureDefined(c context.Context, host string, bid BuilderID) error { client, err := newSwarmbucketClient(c, host) if err != nil { return err } getBuilders := client.GetBuilders() getBuilders.Bucket(bid.V1Bucket()) getBuilders.Fields(googleapi.Field("buckets/(builders/name,name)")) res, err := getBuilders.Do() if err != nil { return err } for _, bucket := range res.Buckets { if bucket.Name != bid.V1Bucket() { continue // defensive programming; shouldn't happen in practice. } for _, builder := range bucket.Builders { if builder.Name == bid.Builder { return nil } } } return errors.Reason("builder %q not found", bid.Builder).Tag(grpcutil.NotFoundTag).Err() }
go
func ensureDefined(c context.Context, host string, bid BuilderID) error { client, err := newSwarmbucketClient(c, host) if err != nil { return err } getBuilders := client.GetBuilders() getBuilders.Bucket(bid.V1Bucket()) getBuilders.Fields(googleapi.Field("buckets/(builders/name,name)")) res, err := getBuilders.Do() if err != nil { return err } for _, bucket := range res.Buckets { if bucket.Name != bid.V1Bucket() { continue // defensive programming; shouldn't happen in practice. } for _, builder := range bucket.Builders { if builder.Name == bid.Builder { return nil } } } return errors.Reason("builder %q not found", bid.Builder).Tag(grpcutil.NotFoundTag).Err() }
[ "func", "ensureDefined", "(", "c", "context", ".", "Context", ",", "host", "string", ",", "bid", "BuilderID", ")", "error", "{", "client", ",", "err", ":=", "newSwarmbucketClient", "(", "c", ",", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "getBuilders", ":=", "client", ".", "GetBuilders", "(", ")", "\n", "getBuilders", ".", "Bucket", "(", "bid", ".", "V1Bucket", "(", ")", ")", "\n", "getBuilders", ".", "Fields", "(", "googleapi", ".", "Field", "(", "\"", "\"", ")", ")", "\n", "res", ",", "err", ":=", "getBuilders", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "bucket", ":=", "range", "res", ".", "Buckets", "{", "if", "bucket", ".", "Name", "!=", "bid", ".", "V1Bucket", "(", ")", "{", "continue", "// defensive programming; shouldn't happen in practice.", "\n", "}", "\n", "for", "_", ",", "builder", ":=", "range", "bucket", ".", "Builders", "{", "if", "builder", ".", "Name", "==", "bid", ".", "Builder", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "bid", ".", "Builder", ")", ".", "Tag", "(", "grpcutil", ".", "NotFoundTag", ")", ".", "Err", "(", ")", "\n", "}" ]
// ensureDefined returns grpcutil.NotFoundTag tagged error if a builder is not // defined in its swarmbucket.
[ "ensureDefined", "returns", "grpcutil", ".", "NotFoundTag", "tagged", "error", "if", "a", "builder", "is", "not", "defined", "in", "its", "swarmbucket", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/builder.go#L102-L126
7,529
luci/luci-go
milo/buildsource/buildbucket/builder.go
backCursor
func backCursor(c context.Context, bid BuilderID, limit int, thisCursor, nextCursor string) string { memcacheKey := func(cursor string) string { key := fmt.Sprintf("%s:%d:%s", bid.String(), limit, cursor) blob := sha1.Sum([]byte(key)) encoded := base64.StdEncoding.EncodeToString(blob[:]) return "cursors:buildbucket_builders:" + encoded } prevCursor := "" if thisCursor != "" { if item, err := memcache.GetKey(c, memcacheKey(thisCursor)); err == nil { prevCursor = string(item.Value()) } } if nextCursor != "" { item := memcache.NewItem(c, memcacheKey(nextCursor)) if thisCursor == "" { item.SetValue([]byte("EMPTY")) } else { item.SetValue([]byte(thisCursor)) } item.SetExpiration(24 * time.Hour) memcache.Set(c, item) } return prevCursor }
go
func backCursor(c context.Context, bid BuilderID, limit int, thisCursor, nextCursor string) string { memcacheKey := func(cursor string) string { key := fmt.Sprintf("%s:%d:%s", bid.String(), limit, cursor) blob := sha1.Sum([]byte(key)) encoded := base64.StdEncoding.EncodeToString(blob[:]) return "cursors:buildbucket_builders:" + encoded } prevCursor := "" if thisCursor != "" { if item, err := memcache.GetKey(c, memcacheKey(thisCursor)); err == nil { prevCursor = string(item.Value()) } } if nextCursor != "" { item := memcache.NewItem(c, memcacheKey(nextCursor)) if thisCursor == "" { item.SetValue([]byte("EMPTY")) } else { item.SetValue([]byte(thisCursor)) } item.SetExpiration(24 * time.Hour) memcache.Set(c, item) } return prevCursor }
[ "func", "backCursor", "(", "c", "context", ".", "Context", ",", "bid", "BuilderID", ",", "limit", "int", ",", "thisCursor", ",", "nextCursor", "string", ")", "string", "{", "memcacheKey", ":=", "func", "(", "cursor", "string", ")", "string", "{", "key", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "bid", ".", "String", "(", ")", ",", "limit", ",", "cursor", ")", "\n", "blob", ":=", "sha1", ".", "Sum", "(", "[", "]", "byte", "(", "key", ")", ")", "\n", "encoded", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "blob", "[", ":", "]", ")", "\n", "return", "\"", "\"", "+", "encoded", "\n", "}", "\n\n", "prevCursor", ":=", "\"", "\"", "\n", "if", "thisCursor", "!=", "\"", "\"", "{", "if", "item", ",", "err", ":=", "memcache", ".", "GetKey", "(", "c", ",", "memcacheKey", "(", "thisCursor", ")", ")", ";", "err", "==", "nil", "{", "prevCursor", "=", "string", "(", "item", ".", "Value", "(", ")", ")", "\n", "}", "\n", "}", "\n", "if", "nextCursor", "!=", "\"", "\"", "{", "item", ":=", "memcache", ".", "NewItem", "(", "c", ",", "memcacheKey", "(", "nextCursor", ")", ")", "\n", "if", "thisCursor", "==", "\"", "\"", "{", "item", ".", "SetValue", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", "}", "else", "{", "item", ".", "SetValue", "(", "[", "]", "byte", "(", "thisCursor", ")", ")", "\n", "}", "\n", "item", ".", "SetExpiration", "(", "24", "*", "time", ".", "Hour", ")", "\n", "memcache", ".", "Set", "(", "c", ",", "item", ")", "\n", "}", "\n", "return", "prevCursor", "\n", "}" ]
// backCursor implements bidirectional cursors with forward-only datastore // cursors by storing a map for cursor -> prevCursor in memcache. // backCursor returns a previous cursor given thisCursor, and caches thisCursor // to be the previous cursor of nextCursor.
[ "backCursor", "implements", "bidirectional", "cursors", "with", "forward", "-", "only", "datastore", "cursors", "by", "storing", "a", "map", "for", "cursor", "-", ">", "prevCursor", "in", "memcache", ".", "backCursor", "returns", "a", "previous", "cursor", "given", "thisCursor", "and", "caches", "thisCursor", "to", "be", "the", "previous", "cursor", "of", "nextCursor", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/builder.go#L181-L206
7,530
luci/luci-go
milo/buildsource/buildbucket/builder.go
toMiloBuildsSummaries
func toMiloBuildsSummaries(c context.Context, msgs []*bbv1.ApiCommonBuildMessage) []*ui.BuildSummary { result := make([]*ui.BuildSummary, len(msgs)) // For each build, toMiloBuild may query Gerrit to fetch associated CL's // author email. Unfortunately, as of June 2018 Gerrit is often taking >5s to // report back. From UX PoV, author's email isn't the most important of // builder's page, so limit waiting time. c, _ = context.WithTimeout(c, 5*time.Second) // This does not error. parallel.WorkPool(50, func(work chan<- func() error) { for i, m := range msgs { i := i m := m work <- func() error { // HACK(hinoka): For malformed builds (eg builder name and builder name tag don't match) // We can drop them silently or display an error. We choose the latter. // Once we switch to the V2 we should be more resilient to these classes of issues. mb, err := ToMiloBuild(c, m, false) if err == nil { result[i] = mb.BuildSummary() return nil } msg := fmt.Sprintf("failed to convert build %d to milo build: %s", m.Id, err) logging.Errorf(c, msg) result[i] = &ui.BuildSummary{ Link: ui.NewEmptyLink("N/A - Error"), Status: model.InfraFailure, Text: []string{msg}, } return nil } } }) return result }
go
func toMiloBuildsSummaries(c context.Context, msgs []*bbv1.ApiCommonBuildMessage) []*ui.BuildSummary { result := make([]*ui.BuildSummary, len(msgs)) // For each build, toMiloBuild may query Gerrit to fetch associated CL's // author email. Unfortunately, as of June 2018 Gerrit is often taking >5s to // report back. From UX PoV, author's email isn't the most important of // builder's page, so limit waiting time. c, _ = context.WithTimeout(c, 5*time.Second) // This does not error. parallel.WorkPool(50, func(work chan<- func() error) { for i, m := range msgs { i := i m := m work <- func() error { // HACK(hinoka): For malformed builds (eg builder name and builder name tag don't match) // We can drop them silently or display an error. We choose the latter. // Once we switch to the V2 we should be more resilient to these classes of issues. mb, err := ToMiloBuild(c, m, false) if err == nil { result[i] = mb.BuildSummary() return nil } msg := fmt.Sprintf("failed to convert build %d to milo build: %s", m.Id, err) logging.Errorf(c, msg) result[i] = &ui.BuildSummary{ Link: ui.NewEmptyLink("N/A - Error"), Status: model.InfraFailure, Text: []string{msg}, } return nil } } }) return result }
[ "func", "toMiloBuildsSummaries", "(", "c", "context", ".", "Context", ",", "msgs", "[", "]", "*", "bbv1", ".", "ApiCommonBuildMessage", ")", "[", "]", "*", "ui", ".", "BuildSummary", "{", "result", ":=", "make", "(", "[", "]", "*", "ui", ".", "BuildSummary", ",", "len", "(", "msgs", ")", ")", "\n", "// For each build, toMiloBuild may query Gerrit to fetch associated CL's", "// author email. Unfortunately, as of June 2018 Gerrit is often taking >5s to", "// report back. From UX PoV, author's email isn't the most important of", "// builder's page, so limit waiting time.", "c", ",", "_", "=", "context", ".", "WithTimeout", "(", "c", ",", "5", "*", "time", ".", "Second", ")", "\n", "// This does not error.", "parallel", ".", "WorkPool", "(", "50", ",", "func", "(", "work", "chan", "<-", "func", "(", ")", "error", ")", "{", "for", "i", ",", "m", ":=", "range", "msgs", "{", "i", ":=", "i", "\n", "m", ":=", "m", "\n", "work", "<-", "func", "(", ")", "error", "{", "// HACK(hinoka): For malformed builds (eg builder name and builder name tag don't match)", "// We can drop them silently or display an error. We choose the latter.", "// Once we switch to the V2 we should be more resilient to these classes of issues.", "mb", ",", "err", ":=", "ToMiloBuild", "(", "c", ",", "m", ",", "false", ")", "\n", "if", "err", "==", "nil", "{", "result", "[", "i", "]", "=", "mb", ".", "BuildSummary", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "m", ".", "Id", ",", "err", ")", "\n", "logging", ".", "Errorf", "(", "c", ",", "msg", ")", "\n", "result", "[", "i", "]", "=", "&", "ui", ".", "BuildSummary", "{", "Link", ":", "ui", ".", "NewEmptyLink", "(", "\"", "\"", ")", ",", "Status", ":", "model", ".", "InfraFailure", ",", "Text", ":", "[", "]", "string", "{", "msg", "}", ",", "}", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "return", "result", "\n", "}" ]
// toMiloBuildsSummaries computes summary for each build in parallel.
[ "toMiloBuildsSummaries", "computes", "summary", "for", "each", "build", "in", "parallel", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/builder.go#L209-L242
7,531
luci/luci-go
milo/buildsource/buildbucket/builder.go
GetBuilder
func GetBuilder(c context.Context, bid BuilderID, limit int, cursor string) (*ui.Builder, error) { host, err := getHost(c) if err != nil { return nil, err } if limit < 0 { limit = 20 } result := &ui.Builder{ Name: bid.Builder, } if host == "debug" { return result, getDebugBuilds(c, bid, limit, result) } client, err := newBuildbucketClient(c, host) if err != nil { return nil, err } fetch := func(statusFilter string, limit int, cursor string) (result []*ui.BuildSummary, nextCursor string, err error) { msgs, nextCursor, err := fetchBuilds(c, client, bid, statusFilter, limit, cursor) if err != nil { logging.WithError(err).Errorf(c, "Could not fetch %s builds", statusFilter) return } result = toMiloBuildsSummaries(c, msgs) return } return result, parallel.FanOutIn(func(work chan<- func() error) { work <- func() error { return ensureDefined(c, host, bid) } work <- func() (err error) { result.MachinePool, err = getPool(c, bid) return } work <- func() (err error) { result.PendingBuilds, _, err = fetch(bbv1.StatusScheduled, -1, "") return } work <- func() (err error) { result.CurrentBuilds, _, err = fetch(bbv1.StatusStarted, -1, "") return } work <- func() (err error) { result.FinishedBuilds, result.NextCursor, err = fetch(bbv1.StatusCompleted, limit, cursor) result.PrevCursor = backCursor(c, bid, limit, cursor, result.NextCursor) // Safe to do even with error. return } }) }
go
func GetBuilder(c context.Context, bid BuilderID, limit int, cursor string) (*ui.Builder, error) { host, err := getHost(c) if err != nil { return nil, err } if limit < 0 { limit = 20 } result := &ui.Builder{ Name: bid.Builder, } if host == "debug" { return result, getDebugBuilds(c, bid, limit, result) } client, err := newBuildbucketClient(c, host) if err != nil { return nil, err } fetch := func(statusFilter string, limit int, cursor string) (result []*ui.BuildSummary, nextCursor string, err error) { msgs, nextCursor, err := fetchBuilds(c, client, bid, statusFilter, limit, cursor) if err != nil { logging.WithError(err).Errorf(c, "Could not fetch %s builds", statusFilter) return } result = toMiloBuildsSummaries(c, msgs) return } return result, parallel.FanOutIn(func(work chan<- func() error) { work <- func() error { return ensureDefined(c, host, bid) } work <- func() (err error) { result.MachinePool, err = getPool(c, bid) return } work <- func() (err error) { result.PendingBuilds, _, err = fetch(bbv1.StatusScheduled, -1, "") return } work <- func() (err error) { result.CurrentBuilds, _, err = fetch(bbv1.StatusStarted, -1, "") return } work <- func() (err error) { result.FinishedBuilds, result.NextCursor, err = fetch(bbv1.StatusCompleted, limit, cursor) result.PrevCursor = backCursor(c, bid, limit, cursor, result.NextCursor) // Safe to do even with error. return } }) }
[ "func", "GetBuilder", "(", "c", "context", ".", "Context", ",", "bid", "BuilderID", ",", "limit", "int", ",", "cursor", "string", ")", "(", "*", "ui", ".", "Builder", ",", "error", ")", "{", "host", ",", "err", ":=", "getHost", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "limit", "<", "0", "{", "limit", "=", "20", "\n", "}", "\n\n", "result", ":=", "&", "ui", ".", "Builder", "{", "Name", ":", "bid", ".", "Builder", ",", "}", "\n", "if", "host", "==", "\"", "\"", "{", "return", "result", ",", "getDebugBuilds", "(", "c", ",", "bid", ",", "limit", ",", "result", ")", "\n", "}", "\n", "client", ",", "err", ":=", "newBuildbucketClient", "(", "c", ",", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fetch", ":=", "func", "(", "statusFilter", "string", ",", "limit", "int", ",", "cursor", "string", ")", "(", "result", "[", "]", "*", "ui", ".", "BuildSummary", ",", "nextCursor", "string", ",", "err", "error", ")", "{", "msgs", ",", "nextCursor", ",", "err", ":=", "fetchBuilds", "(", "c", ",", "client", ",", "bid", ",", "statusFilter", ",", "limit", ",", "cursor", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "statusFilter", ")", "\n", "return", "\n", "}", "\n", "result", "=", "toMiloBuildsSummaries", "(", "c", ",", "msgs", ")", "\n", "return", "\n", "}", "\n", "return", "result", ",", "parallel", ".", "FanOutIn", "(", "func", "(", "work", "chan", "<-", "func", "(", ")", "error", ")", "{", "work", "<-", "func", "(", ")", "error", "{", "return", "ensureDefined", "(", "c", ",", "host", ",", "bid", ")", "\n", "}", "\n", "work", "<-", "func", "(", ")", "(", "err", "error", ")", "{", "result", ".", "MachinePool", ",", "err", "=", "getPool", "(", "c", ",", "bid", ")", "\n", "return", "\n", "}", "\n", "work", "<-", "func", "(", ")", "(", "err", "error", ")", "{", "result", ".", "PendingBuilds", ",", "_", ",", "err", "=", "fetch", "(", "bbv1", ".", "StatusScheduled", ",", "-", "1", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "work", "<-", "func", "(", ")", "(", "err", "error", ")", "{", "result", ".", "CurrentBuilds", ",", "_", ",", "err", "=", "fetch", "(", "bbv1", ".", "StatusStarted", ",", "-", "1", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "work", "<-", "func", "(", ")", "(", "err", "error", ")", "{", "result", ".", "FinishedBuilds", ",", "result", ".", "NextCursor", ",", "err", "=", "fetch", "(", "bbv1", ".", "StatusCompleted", ",", "limit", ",", "cursor", ")", "\n", "result", ".", "PrevCursor", "=", "backCursor", "(", "c", ",", "bid", ",", "limit", ",", "cursor", ",", "result", ".", "NextCursor", ")", "// Safe to do even with error.", "\n", "return", "\n", "}", "\n", "}", ")", "\n", "}" ]
// GetBuilder is used by buildsource.BuilderID.Get to obtain the resp.Builder.
[ "GetBuilder", "is", "used", "by", "buildsource", ".", "BuilderID", ".", "Get", "to", "obtain", "the", "resp", ".", "Builder", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/builder.go#L245-L297
7,532
luci/luci-go
gce/api/config/v1/config.go
Validate
func (cfg *Config) Validate(c *validation.Context) { c.Enter("amount") cfg.GetAmount().Validate(c) c.Exit() c.Enter("attributes") cfg.GetAttributes().Validate(c) c.Exit() c.Enter("lifetime") cfg.GetLifetime().Validate(c) switch n, err := cfg.Lifetime.ToSeconds(); { case err != nil: c.Errorf("%s", err) case n == 0: c.Errorf("duration or seconds is required") } c.Exit() if cfg.GetPrefix() == "" { c.Errorf("prefix is required") } if cfg.GetRevision() != "" { c.Errorf("revision must not be specified") } c.Enter("timeout") cfg.GetTimeout().Validate(c) c.Exit() }
go
func (cfg *Config) Validate(c *validation.Context) { c.Enter("amount") cfg.GetAmount().Validate(c) c.Exit() c.Enter("attributes") cfg.GetAttributes().Validate(c) c.Exit() c.Enter("lifetime") cfg.GetLifetime().Validate(c) switch n, err := cfg.Lifetime.ToSeconds(); { case err != nil: c.Errorf("%s", err) case n == 0: c.Errorf("duration or seconds is required") } c.Exit() if cfg.GetPrefix() == "" { c.Errorf("prefix is required") } if cfg.GetRevision() != "" { c.Errorf("revision must not be specified") } c.Enter("timeout") cfg.GetTimeout().Validate(c) c.Exit() }
[ "func", "(", "cfg", "*", "Config", ")", "Validate", "(", "c", "*", "validation", ".", "Context", ")", "{", "c", ".", "Enter", "(", "\"", "\"", ")", "\n", "cfg", ".", "GetAmount", "(", ")", ".", "Validate", "(", "c", ")", "\n", "c", ".", "Exit", "(", ")", "\n", "c", ".", "Enter", "(", "\"", "\"", ")", "\n", "cfg", ".", "GetAttributes", "(", ")", ".", "Validate", "(", "c", ")", "\n", "c", ".", "Exit", "(", ")", "\n", "c", ".", "Enter", "(", "\"", "\"", ")", "\n", "cfg", ".", "GetLifetime", "(", ")", ".", "Validate", "(", "c", ")", "\n", "switch", "n", ",", "err", ":=", "cfg", ".", "Lifetime", ".", "ToSeconds", "(", ")", ";", "{", "case", "err", "!=", "nil", ":", "c", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "case", "n", "==", "0", ":", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "Exit", "(", ")", "\n", "if", "cfg", ".", "GetPrefix", "(", ")", "==", "\"", "\"", "{", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "GetRevision", "(", ")", "!=", "\"", "\"", "{", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "Enter", "(", "\"", "\"", ")", "\n", "cfg", ".", "GetTimeout", "(", ")", ".", "Validate", "(", "c", ")", "\n", "c", ".", "Exit", "(", ")", "\n", "}" ]
// Validate validates this config. Kind must already be applied.
[ "Validate", "validates", "this", "config", ".", "Kind", "must", "already", "be", "applied", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/config.go#L41-L66
7,533
luci/luci-go
appengine/gaeauth/server/oauth.go
GetUserCredentials
func (m *OAuth2Method) GetUserCredentials(c context.Context, r *http.Request) (*oauth2.Token, error) { chunks := strings.SplitN(r.Header.Get("Authorization"), " ", 2) if len(chunks) != 2 || (chunks[0] != "OAuth" && chunks[0] != "Bearer") { return nil, errBadAuthHeader } return &oauth2.Token{ AccessToken: chunks[1], TokenType: "Bearer", }, nil }
go
func (m *OAuth2Method) GetUserCredentials(c context.Context, r *http.Request) (*oauth2.Token, error) { chunks := strings.SplitN(r.Header.Get("Authorization"), " ", 2) if len(chunks) != 2 || (chunks[0] != "OAuth" && chunks[0] != "Bearer") { return nil, errBadAuthHeader } return &oauth2.Token{ AccessToken: chunks[1], TokenType: "Bearer", }, nil }
[ "func", "(", "m", "*", "OAuth2Method", ")", "GetUserCredentials", "(", "c", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ")", "(", "*", "oauth2", ".", "Token", ",", "error", ")", "{", "chunks", ":=", "strings", ".", "SplitN", "(", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "chunks", ")", "!=", "2", "||", "(", "chunks", "[", "0", "]", "!=", "\"", "\"", "&&", "chunks", "[", "0", "]", "!=", "\"", "\"", ")", "{", "return", "nil", ",", "errBadAuthHeader", "\n", "}", "\n", "return", "&", "oauth2", ".", "Token", "{", "AccessToken", ":", "chunks", "[", "1", "]", ",", "TokenType", ":", "\"", "\"", ",", "}", ",", "nil", "\n", "}" ]
// GetUserCredentials implements auth.UserCredentialsGetter.
[ "GetUserCredentials", "implements", "auth", ".", "UserCredentialsGetter", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/oauth.go#L99-L108
7,534
luci/luci-go
logdog/client/butlerlib/streamclient/stream.go
WriteDatagram
func (s *BaseStream) WriteDatagram(dg []byte) error { if !s.isDatagramStream() { return errors.New("not a datagram stream") } return s.writeRecord(dg) }
go
func (s *BaseStream) WriteDatagram(dg []byte) error { if !s.isDatagramStream() { return errors.New("not a datagram stream") } return s.writeRecord(dg) }
[ "func", "(", "s", "*", "BaseStream", ")", "WriteDatagram", "(", "dg", "[", "]", "byte", ")", "error", "{", "if", "!", "s", ".", "isDatagramStream", "(", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "s", ".", "writeRecord", "(", "dg", ")", "\n", "}" ]
// WriteDatagram implements StreamClient.
[ "WriteDatagram", "implements", "StreamClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamclient/stream.go#L54-L60
7,535
luci/luci-go
logdog/client/butlerlib/streamclient/stream.go
Write
func (s *BaseStream) Write(data []byte) (int, error) { if s.isDatagramStream() { return 0, errors.New("cannot use Write with datagram stream") } return s.writeRaw(data) }
go
func (s *BaseStream) Write(data []byte) (int, error) { if s.isDatagramStream() { return 0, errors.New("cannot use Write with datagram stream") } return s.writeRaw(data) }
[ "func", "(", "s", "*", "BaseStream", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "s", ".", "isDatagramStream", "(", ")", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "s", ".", "writeRaw", "(", "data", ")", "\n", "}" ]
// Write implements StreamClient.
[ "Write", "implements", "StreamClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamclient/stream.go#L63-L69
7,536
luci/luci-go
common/logging/memlogger/memory.go
Debugf
func (m *MemLogger) Debugf(format string, args ...interface{}) { m.LogCall(logging.Debug, 1, format, args) }
go
func (m *MemLogger) Debugf(format string, args ...interface{}) { m.LogCall(logging.Debug, 1, format, args) }
[ "func", "(", "m", "*", "MemLogger", ")", "Debugf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "m", ".", "LogCall", "(", "logging", ".", "Debug", ",", "1", ",", "format", ",", "args", ")", "\n", "}" ]
// Debugf implements the logging.Logger interface.
[ "Debugf", "implements", "the", "logging", ".", "Logger", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L48-L50
7,537
luci/luci-go
common/logging/memlogger/memory.go
Infof
func (m *MemLogger) Infof(format string, args ...interface{}) { m.LogCall(logging.Info, 1, format, args) }
go
func (m *MemLogger) Infof(format string, args ...interface{}) { m.LogCall(logging.Info, 1, format, args) }
[ "func", "(", "m", "*", "MemLogger", ")", "Infof", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "m", ".", "LogCall", "(", "logging", ".", "Info", ",", "1", ",", "format", ",", "args", ")", "\n", "}" ]
// Infof implements the logging.Logger interface.
[ "Infof", "implements", "the", "logging", ".", "Logger", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L53-L55
7,538
luci/luci-go
common/logging/memlogger/memory.go
Warningf
func (m *MemLogger) Warningf(format string, args ...interface{}) { m.LogCall(logging.Warning, 1, format, args) }
go
func (m *MemLogger) Warningf(format string, args ...interface{}) { m.LogCall(logging.Warning, 1, format, args) }
[ "func", "(", "m", "*", "MemLogger", ")", "Warningf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "m", ".", "LogCall", "(", "logging", ".", "Warning", ",", "1", ",", "format", ",", "args", ")", "\n", "}" ]
// Warningf implements the logging.Logger interface.
[ "Warningf", "implements", "the", "logging", ".", "Logger", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L58-L60
7,539
luci/luci-go
common/logging/memlogger/memory.go
Errorf
func (m *MemLogger) Errorf(format string, args ...interface{}) { m.LogCall(logging.Error, 1, format, args) }
go
func (m *MemLogger) Errorf(format string, args ...interface{}) { m.LogCall(logging.Error, 1, format, args) }
[ "func", "(", "m", "*", "MemLogger", ")", "Errorf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "m", ".", "LogCall", "(", "logging", ".", "Error", ",", "1", ",", "format", ",", "args", ")", "\n", "}" ]
// Errorf implements the logging.Logger interface.
[ "Errorf", "implements", "the", "logging", ".", "Logger", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L63-L65
7,540
luci/luci-go
common/logging/memlogger/memory.go
LogCall
func (m *MemLogger) LogCall(lvl logging.Level, calldepth int, format string, args []interface{}) { if m.lock != nil { m.lock.Lock() defer m.lock.Unlock() } if m.data == nil { m.data = new([]LogEntry) } *m.data = append(*m.data, LogEntry{lvl, fmt.Sprintf(format, args...), m.fields, calldepth + 1}) }
go
func (m *MemLogger) LogCall(lvl logging.Level, calldepth int, format string, args []interface{}) { if m.lock != nil { m.lock.Lock() defer m.lock.Unlock() } if m.data == nil { m.data = new([]LogEntry) } *m.data = append(*m.data, LogEntry{lvl, fmt.Sprintf(format, args...), m.fields, calldepth + 1}) }
[ "func", "(", "m", "*", "MemLogger", ")", "LogCall", "(", "lvl", "logging", ".", "Level", ",", "calldepth", "int", ",", "format", "string", ",", "args", "[", "]", "interface", "{", "}", ")", "{", "if", "m", ".", "lock", "!=", "nil", "{", "m", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "lock", ".", "Unlock", "(", ")", "\n", "}", "\n", "if", "m", ".", "data", "==", "nil", "{", "m", ".", "data", "=", "new", "(", "[", "]", "LogEntry", ")", "\n", "}", "\n", "*", "m", ".", "data", "=", "append", "(", "*", "m", ".", "data", ",", "LogEntry", "{", "lvl", ",", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", ",", "m", ".", "fields", ",", "calldepth", "+", "1", "}", ")", "\n", "}" ]
// LogCall implements the logging.Logger interface.
[ "LogCall", "implements", "the", "logging", ".", "Logger", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L68-L77
7,541
luci/luci-go
common/logging/memlogger/memory.go
Messages
func (m *MemLogger) Messages() []LogEntry { if m.lock != nil { m.lock.Lock() defer m.lock.Unlock() } if m.data == nil || len(*m.data) == 0 { return nil } ret := make([]LogEntry, len(*m.data)) copy(ret, *m.data) return ret }
go
func (m *MemLogger) Messages() []LogEntry { if m.lock != nil { m.lock.Lock() defer m.lock.Unlock() } if m.data == nil || len(*m.data) == 0 { return nil } ret := make([]LogEntry, len(*m.data)) copy(ret, *m.data) return ret }
[ "func", "(", "m", "*", "MemLogger", ")", "Messages", "(", ")", "[", "]", "LogEntry", "{", "if", "m", ".", "lock", "!=", "nil", "{", "m", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "lock", ".", "Unlock", "(", ")", "\n", "}", "\n", "if", "m", ".", "data", "==", "nil", "||", "len", "(", "*", "m", ".", "data", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "ret", ":=", "make", "(", "[", "]", "LogEntry", ",", "len", "(", "*", "m", ".", "data", ")", ")", "\n", "copy", "(", "ret", ",", "*", "m", ".", "data", ")", "\n", "return", "ret", "\n", "}" ]
// Messages returns all of the log messages that this memory logger has // recorded.
[ "Messages", "returns", "all", "of", "the", "log", "messages", "that", "this", "memory", "logger", "has", "recorded", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L81-L92
7,542
luci/luci-go
common/logging/memlogger/memory.go
Reset
func (m *MemLogger) Reset() { if m.lock != nil { m.lock.Lock() defer m.lock.Unlock() } if m.data != nil { *m.data = nil } }
go
func (m *MemLogger) Reset() { if m.lock != nil { m.lock.Lock() defer m.lock.Unlock() } if m.data != nil { *m.data = nil } }
[ "func", "(", "m", "*", "MemLogger", ")", "Reset", "(", ")", "{", "if", "m", ".", "lock", "!=", "nil", "{", "m", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "lock", ".", "Unlock", "(", ")", "\n", "}", "\n", "if", "m", ".", "data", "!=", "nil", "{", "*", "m", ".", "data", "=", "nil", "\n", "}", "\n", "}" ]
// Reset resets the logged messages recorded so far.
[ "Reset", "resets", "the", "logged", "messages", "recorded", "so", "far", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L95-L103
7,543
luci/luci-go
common/logging/memlogger/memory.go
GetFunc
func (m *MemLogger) GetFunc(f func(*LogEntry) bool) *LogEntry { if m.lock != nil { m.lock.Lock() defer m.lock.Unlock() } if m.data == nil { return nil } for _, ent := range *m.data { if f(&ent) { clone := ent return &clone } } return nil }
go
func (m *MemLogger) GetFunc(f func(*LogEntry) bool) *LogEntry { if m.lock != nil { m.lock.Lock() defer m.lock.Unlock() } if m.data == nil { return nil } for _, ent := range *m.data { if f(&ent) { clone := ent return &clone } } return nil }
[ "func", "(", "m", "*", "MemLogger", ")", "GetFunc", "(", "f", "func", "(", "*", "LogEntry", ")", "bool", ")", "*", "LogEntry", "{", "if", "m", ".", "lock", "!=", "nil", "{", "m", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "lock", ".", "Unlock", "(", ")", "\n", "}", "\n", "if", "m", ".", "data", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "ent", ":=", "range", "*", "m", ".", "data", "{", "if", "f", "(", "&", "ent", ")", "{", "clone", ":=", "ent", "\n", "return", "&", "clone", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetFunc returns the first matching log entry.
[ "GetFunc", "returns", "the", "first", "matching", "log", "entry", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L106-L121
7,544
luci/luci-go
common/logging/memlogger/memory.go
Get
func (m *MemLogger) Get(lvl logging.Level, msg string, data map[string]interface{}) *LogEntry { return m.GetFunc(func(ent *LogEntry) bool { return ent.Level == lvl && ent.Msg == msg && reflect.DeepEqual(data, ent.Data) }) }
go
func (m *MemLogger) Get(lvl logging.Level, msg string, data map[string]interface{}) *LogEntry { return m.GetFunc(func(ent *LogEntry) bool { return ent.Level == lvl && ent.Msg == msg && reflect.DeepEqual(data, ent.Data) }) }
[ "func", "(", "m", "*", "MemLogger", ")", "Get", "(", "lvl", "logging", ".", "Level", ",", "msg", "string", ",", "data", "map", "[", "string", "]", "interface", "{", "}", ")", "*", "LogEntry", "{", "return", "m", ".", "GetFunc", "(", "func", "(", "ent", "*", "LogEntry", ")", "bool", "{", "return", "ent", ".", "Level", "==", "lvl", "&&", "ent", ".", "Msg", "==", "msg", "&&", "reflect", ".", "DeepEqual", "(", "data", ",", "ent", ".", "Data", ")", "\n", "}", ")", "\n", "}" ]
// Get returns the first matching log entry. // Note that lvl, msg and data have to match the entry precisely.
[ "Get", "returns", "the", "first", "matching", "log", "entry", ".", "Note", "that", "lvl", "msg", "and", "data", "have", "to", "match", "the", "entry", "precisely", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L125-L129
7,545
luci/luci-go
common/logging/memlogger/memory.go
HasFunc
func (m *MemLogger) HasFunc(f func(*LogEntry) bool) bool { return m.GetFunc(f) != nil }
go
func (m *MemLogger) HasFunc(f func(*LogEntry) bool) bool { return m.GetFunc(f) != nil }
[ "func", "(", "m", "*", "MemLogger", ")", "HasFunc", "(", "f", "func", "(", "*", "LogEntry", ")", "bool", ")", "bool", "{", "return", "m", ".", "GetFunc", "(", "f", ")", "!=", "nil", "\n", "}" ]
// HasFunc returns true iff the MemLogger contains a matching log message.
[ "HasFunc", "returns", "true", "iff", "the", "MemLogger", "contains", "a", "matching", "log", "message", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L132-L134
7,546
luci/luci-go
common/logging/memlogger/memory.go
Has
func (m *MemLogger) Has(lvl logging.Level, msg string, data map[string]interface{}) bool { return m.Get(lvl, msg, data) != nil }
go
func (m *MemLogger) Has(lvl logging.Level, msg string, data map[string]interface{}) bool { return m.Get(lvl, msg, data) != nil }
[ "func", "(", "m", "*", "MemLogger", ")", "Has", "(", "lvl", "logging", ".", "Level", ",", "msg", "string", ",", "data", "map", "[", "string", "]", "interface", "{", "}", ")", "bool", "{", "return", "m", ".", "Get", "(", "lvl", ",", "msg", ",", "data", ")", "!=", "nil", "\n", "}" ]
// Has returns true iff the MemLogger contains the specified log message. // Note that lvl, msg and data have to match the entry precisely.
[ "Has", "returns", "true", "iff", "the", "MemLogger", "contains", "the", "specified", "log", "message", ".", "Note", "that", "lvl", "msg", "and", "data", "have", "to", "match", "the", "entry", "precisely", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L138-L140
7,547
luci/luci-go
common/logging/memlogger/memory.go
Dump
func (m *MemLogger) Dump(w io.Writer) (n int, err error) { amt := 0 for i, msg := range m.Messages() { if i == 0 { amt, err = fmt.Fprintf(w, "\nDUMP LOG:\n") n += amt if err != nil { return } } if msg.Data == nil { amt, err = fmt.Fprintf(w, " %s: %s\n", msg.Level, msg.Msg) n += amt if err != nil { return } } else { amt, err = fmt.Fprintf(w, " %s: %s: %s\n", msg.Level, msg.Msg, logging.Fields(msg.Data)) n += amt if err != nil { return } } } return }
go
func (m *MemLogger) Dump(w io.Writer) (n int, err error) { amt := 0 for i, msg := range m.Messages() { if i == 0 { amt, err = fmt.Fprintf(w, "\nDUMP LOG:\n") n += amt if err != nil { return } } if msg.Data == nil { amt, err = fmt.Fprintf(w, " %s: %s\n", msg.Level, msg.Msg) n += amt if err != nil { return } } else { amt, err = fmt.Fprintf(w, " %s: %s: %s\n", msg.Level, msg.Msg, logging.Fields(msg.Data)) n += amt if err != nil { return } } } return }
[ "func", "(", "m", "*", "MemLogger", ")", "Dump", "(", "w", "io", ".", "Writer", ")", "(", "n", "int", ",", "err", "error", ")", "{", "amt", ":=", "0", "\n", "for", "i", ",", "msg", ":=", "range", "m", ".", "Messages", "(", ")", "{", "if", "i", "==", "0", "{", "amt", ",", "err", "=", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\\n", "\"", ")", "\n", "n", "+=", "amt", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "if", "msg", ".", "Data", "==", "nil", "{", "amt", ",", "err", "=", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "msg", ".", "Level", ",", "msg", ".", "Msg", ")", "\n", "n", "+=", "amt", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "else", "{", "amt", ",", "err", "=", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "msg", ".", "Level", ",", "msg", ".", "Msg", ",", "logging", ".", "Fields", "(", "msg", ".", "Data", ")", ")", "\n", "n", "+=", "amt", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Dump dumps the current memory logger contents to the given writer in a // human-readable format.
[ "Dump", "dumps", "the", "current", "memory", "logger", "contents", "to", "the", "given", "writer", "in", "a", "human", "-", "readable", "format", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L144-L169
7,548
luci/luci-go
common/logging/memlogger/memory.go
Dump
func Dump(c context.Context, w io.Writer) (n int, err error) { return logging.Get(c).(*MemLogger).Dump(w) }
go
func Dump(c context.Context, w io.Writer) (n int, err error) { return logging.Get(c).(*MemLogger).Dump(w) }
[ "func", "Dump", "(", "c", "context", ".", "Context", ",", "w", "io", ".", "Writer", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "logging", ".", "Get", "(", "c", ")", ".", "(", "*", "MemLogger", ")", ".", "Dump", "(", "w", ")", "\n", "}" ]
// Dump is a convenience function to dump the current contents of the memory // logger to the writer. // // This will panic if the current logger is not a memory logger.
[ "Dump", "is", "a", "convenience", "function", "to", "dump", "the", "current", "contents", "of", "the", "memory", "logger", "to", "the", "writer", ".", "This", "will", "panic", "if", "the", "current", "logger", "is", "not", "a", "memory", "logger", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L193-L195
7,549
luci/luci-go
common/logging/memlogger/memory.go
MustDumpStdout
func MustDumpStdout(c context.Context) { _, err := logging.Get(c).(*MemLogger).Dump(os.Stdout) if err != nil { panic(err) } }
go
func MustDumpStdout(c context.Context) { _, err := logging.Get(c).(*MemLogger).Dump(os.Stdout) if err != nil { panic(err) } }
[ "func", "MustDumpStdout", "(", "c", "context", ".", "Context", ")", "{", "_", ",", "err", ":=", "logging", ".", "Get", "(", "c", ")", ".", "(", "*", "MemLogger", ")", ".", "Dump", "(", "os", ".", "Stdout", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// MustDumpStdout is a convenience function to dump the current contents of the // memory logger to stdout. // // This will panic if the current logger is not a memory logger.
[ "MustDumpStdout", "is", "a", "convenience", "function", "to", "dump", "the", "current", "contents", "of", "the", "memory", "logger", "to", "stdout", ".", "This", "will", "panic", "if", "the", "current", "logger", "is", "not", "a", "memory", "logger", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/memlogger/memory.go#L201-L206
7,550
luci/luci-go
mp/cmd/mpagent/agent_windows.go
configureAutoMount
func (WindowsStrategy) configureAutoMount(ctx context.Context, disk string) error { // TODO(smut): Mount the specified disk. return errors.New("mounting disks is unsupported on Windows") }
go
func (WindowsStrategy) configureAutoMount(ctx context.Context, disk string) error { // TODO(smut): Mount the specified disk. return errors.New("mounting disks is unsupported on Windows") }
[ "func", "(", "WindowsStrategy", ")", "configureAutoMount", "(", "ctx", "context", ".", "Context", ",", "disk", "string", ")", "error", "{", "// TODO(smut): Mount the specified disk.", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// configureAutoMount mounts the specified disk and configures mount on startup. // // Assumes the disk is already formatted as ntfs.
[ "configureAutoMount", "mounts", "the", "specified", "disk", "and", "configures", "mount", "on", "startup", ".", "Assumes", "the", "disk", "is", "already", "formatted", "as", "ntfs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/agent_windows.go#L43-L46
7,551
luci/luci-go
mp/cmd/mpagent/agent_windows.go
getAgent
func getAgent(ctx context.Context) (*Agent, error) { agent := Agent{ agentAutoStartPath: "C:\\Users\\{{.User}}\\Start Menu\\Programs\\Startup\\machine-provider-agent.bat", agentAutoStartTemplate: "machine-provider-agent.bat.tmpl", logsDir: "C:\\logs", swarmingAutoStartPath: "C:\\Users\\{{.User}}\\Start Menu\\Programs\\Startup\\swarming-start-bot.bat", swarmingAutoStartTemplate: "swarming-start-bot.bat.tmpl", swarmingBotDir: "C:\\b\\s", strategy: WindowsStrategy{}, } logging.Infof(ctx, "Using Windows agent.") return &agent, nil }
go
func getAgent(ctx context.Context) (*Agent, error) { agent := Agent{ agentAutoStartPath: "C:\\Users\\{{.User}}\\Start Menu\\Programs\\Startup\\machine-provider-agent.bat", agentAutoStartTemplate: "machine-provider-agent.bat.tmpl", logsDir: "C:\\logs", swarmingAutoStartPath: "C:\\Users\\{{.User}}\\Start Menu\\Programs\\Startup\\swarming-start-bot.bat", swarmingAutoStartTemplate: "swarming-start-bot.bat.tmpl", swarmingBotDir: "C:\\b\\s", strategy: WindowsStrategy{}, } logging.Infof(ctx, "Using Windows agent.") return &agent, nil }
[ "func", "getAgent", "(", "ctx", "context", ".", "Context", ")", "(", "*", "Agent", ",", "error", ")", "{", "agent", ":=", "Agent", "{", "agentAutoStartPath", ":", "\"", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\"", ",", "agentAutoStartTemplate", ":", "\"", "\"", ",", "logsDir", ":", "\"", "\\\\", "\"", ",", "swarmingAutoStartPath", ":", "\"", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\"", ",", "swarmingAutoStartTemplate", ":", "\"", "\"", ",", "swarmingBotDir", ":", "\"", "\\\\", "\\\\", "\"", ",", "strategy", ":", "WindowsStrategy", "{", "}", ",", "}", "\n", "logging", ".", "Infof", "(", "ctx", ",", "\"", "\"", ")", "\n", "return", "&", "agent", ",", "nil", "\n", "}" ]
// getAgent returns an agent which runs on Windows.
[ "getAgent", "returns", "an", "agent", "which", "runs", "on", "Windows", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/agent_windows.go#L72-L84
7,552
luci/luci-go
auth/internal/user.go
NewUserAuthTokenProvider
func NewUserAuthTokenProvider(ctx context.Context, clientID, clientSecret string, scopes []string) (TokenProvider, error) { return &userAuthTokenProvider{ config: &oauth2.Config{ ClientID: clientID, ClientSecret: clientSecret, Endpoint: oauth2.Endpoint{ AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", }, RedirectURL: "urn:ietf:wg:oauth:2.0:oob", Scopes: scopes, }, cacheKey: CacheKey{ Key: fmt.Sprintf("user/%s", clientID), Scopes: scopes, }, }, nil }
go
func NewUserAuthTokenProvider(ctx context.Context, clientID, clientSecret string, scopes []string) (TokenProvider, error) { return &userAuthTokenProvider{ config: &oauth2.Config{ ClientID: clientID, ClientSecret: clientSecret, Endpoint: oauth2.Endpoint{ AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", }, RedirectURL: "urn:ietf:wg:oauth:2.0:oob", Scopes: scopes, }, cacheKey: CacheKey{ Key: fmt.Sprintf("user/%s", clientID), Scopes: scopes, }, }, nil }
[ "func", "NewUserAuthTokenProvider", "(", "ctx", "context", ".", "Context", ",", "clientID", ",", "clientSecret", "string", ",", "scopes", "[", "]", "string", ")", "(", "TokenProvider", ",", "error", ")", "{", "return", "&", "userAuthTokenProvider", "{", "config", ":", "&", "oauth2", ".", "Config", "{", "ClientID", ":", "clientID", ",", "ClientSecret", ":", "clientSecret", ",", "Endpoint", ":", "oauth2", ".", "Endpoint", "{", "AuthURL", ":", "\"", "\"", ",", "TokenURL", ":", "\"", "\"", ",", "}", ",", "RedirectURL", ":", "\"", "\"", ",", "Scopes", ":", "scopes", ",", "}", ",", "cacheKey", ":", "CacheKey", "{", "Key", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "clientID", ")", ",", "Scopes", ":", "scopes", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// NewUserAuthTokenProvider returns TokenProvider that can perform 3-legged // OAuth flow involving interaction with a user.
[ "NewUserAuthTokenProvider", "returns", "TokenProvider", "that", "can", "perform", "3", "-", "legged", "OAuth", "flow", "involving", "interaction", "with", "a", "user", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/internal/user.go#L36-L53
7,553
luci/luci-go
logdog/appengine/coordinator/endpoints/context.go
WithServices
func WithServices(c context.Context, s Services) context.Context { return context.WithValue(c, &servicesKey, s) }
go
func WithServices(c context.Context, s Services) context.Context { return context.WithValue(c, &servicesKey, s) }
[ "func", "WithServices", "(", "c", "context", ".", "Context", ",", "s", "Services", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "&", "servicesKey", ",", "s", ")", "\n", "}" ]
// WithServices installs the supplied Services instance into a Context.
[ "WithServices", "installs", "the", "supplied", "Services", "instance", "into", "a", "Context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/context.go#L22-L24
7,554
luci/luci-go
common/system/filesystem/tempdir.go
With
func (td *TempDir) With(fn func(string) error) error { tdir, err := ioutil.TempDir(td.Dir, td.Prefix) if err != nil { return err } defer func() { if rmErr := RemoveAll(tdir); rmErr != nil { if cef := td.CleanupErrFunc; cef != nil { cef(tdir, rmErr) } } }() return fn(tdir) }
go
func (td *TempDir) With(fn func(string) error) error { tdir, err := ioutil.TempDir(td.Dir, td.Prefix) if err != nil { return err } defer func() { if rmErr := RemoveAll(tdir); rmErr != nil { if cef := td.CleanupErrFunc; cef != nil { cef(tdir, rmErr) } } }() return fn(tdir) }
[ "func", "(", "td", "*", "TempDir", ")", "With", "(", "fn", "func", "(", "string", ")", "error", ")", "error", "{", "tdir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "td", ".", "Dir", ",", "td", ".", "Prefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "rmErr", ":=", "RemoveAll", "(", "tdir", ")", ";", "rmErr", "!=", "nil", "{", "if", "cef", ":=", "td", ".", "CleanupErrFunc", ";", "cef", "!=", "nil", "{", "cef", "(", "tdir", ",", "rmErr", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "fn", "(", "tdir", ")", "\n", "}" ]
// With creates a temporary directory and passes it to fn. After fn exits, the // directory and all of its contents is deleted. // // Any error that happens during setup or execution of the callback is returned. // If an error occurs during cleanup, the optional CleanupErrFunc will be // called.
[ "With", "creates", "a", "temporary", "directory", "and", "passes", "it", "to", "fn", ".", "After", "fn", "exits", "the", "directory", "and", "all", "of", "its", "contents", "is", "deleted", ".", "Any", "error", "that", "happens", "during", "setup", "or", "execution", "of", "the", "callback", "is", "returned", ".", "If", "an", "error", "occurs", "during", "cleanup", "the", "optional", "CleanupErrFunc", "will", "be", "called", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/filesystem/tempdir.go#L43-L56
7,555
luci/luci-go
cipd/appengine/impl/admin/mappers.go
initMapper
func initMapper(d mapperDef) { if _, ok := mappers[d.Kind]; ok { panic(fmt.Sprintf("mapper with kind %s has already been initialized", d.Kind)) } mappers[d.Kind] = &d }
go
func initMapper(d mapperDef) { if _, ok := mappers[d.Kind]; ok { panic(fmt.Sprintf("mapper with kind %s has already been initialized", d.Kind)) } mappers[d.Kind] = &d }
[ "func", "initMapper", "(", "d", "mapperDef", ")", "{", "if", "_", ",", "ok", ":=", "mappers", "[", "d", ".", "Kind", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "d", ".", "Kind", ")", ")", "\n", "}", "\n", "mappers", "[", "d", ".", "Kind", "]", "=", "&", "d", "\n", "}" ]
// initMapper is called during init time to register some mapper kind.
[ "initMapper", "is", "called", "during", "init", "time", "to", "register", "some", "mapper", "kind", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/admin/mappers.go#L36-L41
7,556
luci/luci-go
cipd/appengine/impl/admin/mappers.go
newMapper
func (m *mapperDef) newMapper(c context.Context, j *mapper.Job, shardIdx int) (mapper.Mapper, error) { cfg := &api.JobConfig{} if err := proto.Unmarshal(j.Config.Params, cfg); err != nil { return nil, errors.Annotate(err, "failed to unmarshal JobConfig").Err() } return func(c context.Context, keys []*datastore.Key) error { return m.Func(c, j.ID, cfg, keys) }, nil }
go
func (m *mapperDef) newMapper(c context.Context, j *mapper.Job, shardIdx int) (mapper.Mapper, error) { cfg := &api.JobConfig{} if err := proto.Unmarshal(j.Config.Params, cfg); err != nil { return nil, errors.Annotate(err, "failed to unmarshal JobConfig").Err() } return func(c context.Context, keys []*datastore.Key) error { return m.Func(c, j.ID, cfg, keys) }, nil }
[ "func", "(", "m", "*", "mapperDef", ")", "newMapper", "(", "c", "context", ".", "Context", ",", "j", "*", "mapper", ".", "Job", ",", "shardIdx", "int", ")", "(", "mapper", ".", "Mapper", ",", "error", ")", "{", "cfg", ":=", "&", "api", ".", "JobConfig", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "j", ".", "Config", ".", "Params", ",", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "func", "(", "c", "context", ".", "Context", ",", "keys", "[", "]", "*", "datastore", ".", "Key", ")", "error", "{", "return", "m", ".", "Func", "(", "c", ",", "j", ".", "ID", ",", "cfg", ",", "keys", ")", "\n", "}", ",", "nil", "\n", "}" ]
// newMapper creates new instance of a mapping function.
[ "newMapper", "creates", "new", "instance", "of", "a", "mapping", "function", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/admin/mappers.go#L59-L67
7,557
luci/luci-go
logdog/common/storage/bigtable/bigtable.go
getReadItem
func getReadItem(row bigtable.Row, family, column string) *bigtable.ReadItem { // Get the row for our family. items, ok := row[logColumnFamily] if !ok { return nil } // Get the specific ReadItem for our column colName := fmt.Sprintf("%s:%s", family, column) for _, item := range items { if item.Column == colName { return &item } } return nil }
go
func getReadItem(row bigtable.Row, family, column string) *bigtable.ReadItem { // Get the row for our family. items, ok := row[logColumnFamily] if !ok { return nil } // Get the specific ReadItem for our column colName := fmt.Sprintf("%s:%s", family, column) for _, item := range items { if item.Column == colName { return &item } } return nil }
[ "func", "getReadItem", "(", "row", "bigtable", ".", "Row", ",", "family", ",", "column", "string", ")", "*", "bigtable", ".", "ReadItem", "{", "// Get the row for our family.", "items", ",", "ok", ":=", "row", "[", "logColumnFamily", "]", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n\n", "// Get the specific ReadItem for our column", "colName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "family", ",", "column", ")", "\n", "for", "_", ",", "item", ":=", "range", "items", "{", "if", "item", ".", "Column", "==", "colName", "{", "return", "&", "item", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// getReadItem retrieves a specific RowItem from the supplied Row.
[ "getReadItem", "retrieves", "a", "specific", "RowItem", "from", "the", "supplied", "Row", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/bigtable/bigtable.go#L209-L224
7,558
luci/luci-go
scheduler/appengine/task/urlfetch/urlfetch.go
isTextContent
func isTextContent(h http.Header) bool { for _, header := range h["Content-Type"] { for _, good := range textContentTypes { if strings.HasPrefix(header, good) { return true } } } return false }
go
func isTextContent(h http.Header) bool { for _, header := range h["Content-Type"] { for _, good := range textContentTypes { if strings.HasPrefix(header, good) { return true } } } return false }
[ "func", "isTextContent", "(", "h", "http", ".", "Header", ")", "bool", "{", "for", "_", ",", "header", ":=", "range", "h", "[", "\"", "\"", "]", "{", "for", "_", ",", "good", ":=", "range", "textContentTypes", "{", "if", "strings", ".", "HasPrefix", "(", "header", ",", "good", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isTextContent returns True if Content-Type header corresponds to some // readable text type.
[ "isTextContent", "returns", "True", "if", "Content", "-", "Type", "header", "corresponds", "to", "some", "readable", "text", "type", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/urlfetch/urlfetch.go#L240-L249
7,559
luci/luci-go
vpython/venv/config.go
WithoutWheels
func (cfg *Config) WithoutWheels() *Config { if !cfg.HasWheels() { return cfg } clone := *cfg clone.OverrideName = "" clone.Spec = clone.Spec.Clone() clone.Spec.Wheel = nil return &clone }
go
func (cfg *Config) WithoutWheels() *Config { if !cfg.HasWheels() { return cfg } clone := *cfg clone.OverrideName = "" clone.Spec = clone.Spec.Clone() clone.Spec.Wheel = nil return &clone }
[ "func", "(", "cfg", "*", "Config", ")", "WithoutWheels", "(", ")", "*", "Config", "{", "if", "!", "cfg", ".", "HasWheels", "(", ")", "{", "return", "cfg", "\n", "}", "\n\n", "clone", ":=", "*", "cfg", "\n", "clone", ".", "OverrideName", "=", "\"", "\"", "\n", "clone", ".", "Spec", "=", "clone", ".", "Spec", ".", "Clone", "(", ")", "\n", "clone", ".", "Spec", ".", "Wheel", "=", "nil", "\n", "return", "&", "clone", "\n", "}" ]
// WithoutWheels returns a clone of cfg that depends on no additional packages. // // If cfg is already an empty it will be returned directly.
[ "WithoutWheels", "returns", "a", "clone", "of", "cfg", "that", "depends", "on", "no", "additional", "packages", ".", "If", "cfg", "is", "already", "an", "empty", "it", "will", "be", "returned", "directly", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/config.go#L127-L137
7,560
luci/luci-go
vpython/venv/config.go
HasWheels
func (cfg *Config) HasWheels() bool { return cfg.Spec != nil && len(cfg.Spec.Wheel) > 0 }
go
func (cfg *Config) HasWheels() bool { return cfg.Spec != nil && len(cfg.Spec.Wheel) > 0 }
[ "func", "(", "cfg", "*", "Config", ")", "HasWheels", "(", ")", "bool", "{", "return", "cfg", ".", "Spec", "!=", "nil", "&&", "len", "(", "cfg", ".", "Spec", ".", "Wheel", ")", ">", "0", "\n", "}" ]
// HasWheels returns true if this environment declares wheel dependencies.
[ "HasWheels", "returns", "true", "if", "this", "environment", "declares", "wheel", "dependencies", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/config.go#L140-L142
7,561
luci/luci-go
vpython/venv/config.go
makeEnv
func (cfg *Config) makeEnv(c context.Context, e *vpython.Environment) (*Env, error) { // We MUST have a package loader. if cfg.Loader == nil { return nil, errors.New("no package loader provided") } // Resolve our base directory, if one is not supplied. if cfg.BaseDir == "" { // Use one in a temporary directory. cfg.BaseDir = filepath.Join(os.TempDir(), "vpython") logging.Debugf(c, "Using tempdir-relative environment root: %s", cfg.BaseDir) } if err := filesystem.AbsPath(&cfg.BaseDir); err != nil { return nil, errors.Annotate(err, "failed to resolve absolute path of base directory").Err() } // Construct a new, independent Environment for this Env. e = e.Clone() if cfg.Spec != nil { e.Spec = cfg.Spec.Clone() } if err := spec.NormalizeEnvironment(e); err != nil { return nil, errors.Annotate(err, "invalid environment").Err() } // If the environment doesn't specify a VirtualEnv package (expected), use // our default. if e.Spec.Virtualenv == nil { e.Spec.Virtualenv = &cfg.Package } if err := cfg.Loader.Resolve(c, e); err != nil { return nil, errors.Annotate(err, "failed to resolve packages").Err() } if err := cfg.resolvePythonInterpreter(c, e.Spec); err != nil { return nil, errors.Annotate(err, "failed to resolve system Python interpreter").Err() } e.Runtime = &vpython.Runtime{ Version: e.Spec.PythonVersion, } if err := fillRuntime(c, cfg.si, e.Runtime); err != nil { return nil, err } logging.Debugf(c, "Resolved system Python runtime: %#s", e.Runtime) // Ensure that our base directory exists. if err := filesystem.MakeDirs(cfg.BaseDir); err != nil { return nil, errors.Annotate(err, "could not create environment root: %s", cfg.BaseDir).Err() } // Generate our environment name based on the deterministic hash of its // fully-resolved specification. envName := cfg.OverrideName if envName == "" { envName = cfg.envNameForSpec(c, e.Spec, e.Runtime) } env := cfg.envForName(envName, e) return env, nil }
go
func (cfg *Config) makeEnv(c context.Context, e *vpython.Environment) (*Env, error) { // We MUST have a package loader. if cfg.Loader == nil { return nil, errors.New("no package loader provided") } // Resolve our base directory, if one is not supplied. if cfg.BaseDir == "" { // Use one in a temporary directory. cfg.BaseDir = filepath.Join(os.TempDir(), "vpython") logging.Debugf(c, "Using tempdir-relative environment root: %s", cfg.BaseDir) } if err := filesystem.AbsPath(&cfg.BaseDir); err != nil { return nil, errors.Annotate(err, "failed to resolve absolute path of base directory").Err() } // Construct a new, independent Environment for this Env. e = e.Clone() if cfg.Spec != nil { e.Spec = cfg.Spec.Clone() } if err := spec.NormalizeEnvironment(e); err != nil { return nil, errors.Annotate(err, "invalid environment").Err() } // If the environment doesn't specify a VirtualEnv package (expected), use // our default. if e.Spec.Virtualenv == nil { e.Spec.Virtualenv = &cfg.Package } if err := cfg.Loader.Resolve(c, e); err != nil { return nil, errors.Annotate(err, "failed to resolve packages").Err() } if err := cfg.resolvePythonInterpreter(c, e.Spec); err != nil { return nil, errors.Annotate(err, "failed to resolve system Python interpreter").Err() } e.Runtime = &vpython.Runtime{ Version: e.Spec.PythonVersion, } if err := fillRuntime(c, cfg.si, e.Runtime); err != nil { return nil, err } logging.Debugf(c, "Resolved system Python runtime: %#s", e.Runtime) // Ensure that our base directory exists. if err := filesystem.MakeDirs(cfg.BaseDir); err != nil { return nil, errors.Annotate(err, "could not create environment root: %s", cfg.BaseDir).Err() } // Generate our environment name based on the deterministic hash of its // fully-resolved specification. envName := cfg.OverrideName if envName == "" { envName = cfg.envNameForSpec(c, e.Spec, e.Runtime) } env := cfg.envForName(envName, e) return env, nil }
[ "func", "(", "cfg", "*", "Config", ")", "makeEnv", "(", "c", "context", ".", "Context", ",", "e", "*", "vpython", ".", "Environment", ")", "(", "*", "Env", ",", "error", ")", "{", "// We MUST have a package loader.", "if", "cfg", ".", "Loader", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Resolve our base directory, if one is not supplied.", "if", "cfg", ".", "BaseDir", "==", "\"", "\"", "{", "// Use one in a temporary directory.", "cfg", ".", "BaseDir", "=", "filepath", ".", "Join", "(", "os", ".", "TempDir", "(", ")", ",", "\"", "\"", ")", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "cfg", ".", "BaseDir", ")", "\n", "}", "\n", "if", "err", ":=", "filesystem", ".", "AbsPath", "(", "&", "cfg", ".", "BaseDir", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Construct a new, independent Environment for this Env.", "e", "=", "e", ".", "Clone", "(", ")", "\n", "if", "cfg", ".", "Spec", "!=", "nil", "{", "e", ".", "Spec", "=", "cfg", ".", "Spec", ".", "Clone", "(", ")", "\n", "}", "\n", "if", "err", ":=", "spec", ".", "NormalizeEnvironment", "(", "e", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// If the environment doesn't specify a VirtualEnv package (expected), use", "// our default.", "if", "e", ".", "Spec", ".", "Virtualenv", "==", "nil", "{", "e", ".", "Spec", ".", "Virtualenv", "=", "&", "cfg", ".", "Package", "\n", "}", "\n\n", "if", "err", ":=", "cfg", ".", "Loader", ".", "Resolve", "(", "c", ",", "e", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "err", ":=", "cfg", ".", "resolvePythonInterpreter", "(", "c", ",", "e", ".", "Spec", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "e", ".", "Runtime", "=", "&", "vpython", ".", "Runtime", "{", "Version", ":", "e", ".", "Spec", ".", "PythonVersion", ",", "}", "\n", "if", "err", ":=", "fillRuntime", "(", "c", ",", "cfg", ".", "si", ",", "e", ".", "Runtime", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "e", ".", "Runtime", ")", "\n\n", "// Ensure that our base directory exists.", "if", "err", ":=", "filesystem", ".", "MakeDirs", "(", "cfg", ".", "BaseDir", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "cfg", ".", "BaseDir", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Generate our environment name based on the deterministic hash of its", "// fully-resolved specification.", "envName", ":=", "cfg", ".", "OverrideName", "\n", "if", "envName", "==", "\"", "\"", "{", "envName", "=", "cfg", ".", "envNameForSpec", "(", "c", ",", "e", ".", "Spec", ",", "e", ".", "Runtime", ")", "\n", "}", "\n", "env", ":=", "cfg", ".", "envForName", "(", "envName", ",", "e", ")", "\n", "return", "env", ",", "nil", "\n", "}" ]
// makeEnv processes the config, validating and, where appropriate, populating // any components. Upon success, it returns a configured Env instance. // // The supplied vpython.Environment is derived externally, and may be nil if // this is a bootstrapped Environment. // // The returned Env instance may or may not actually exist. Setup must be called // prior to using it.
[ "makeEnv", "processes", "the", "config", "validating", "and", "where", "appropriate", "populating", "any", "components", ".", "Upon", "success", "it", "returns", "a", "configured", "Env", "instance", ".", "The", "supplied", "vpython", ".", "Environment", "is", "derived", "externally", "and", "may", "be", "nil", "if", "this", "is", "a", "bootstrapped", "Environment", ".", "The", "returned", "Env", "instance", "may", "or", "may", "not", "actually", "exist", ".", "Setup", "must", "be", "called", "prior", "to", "using", "it", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/config.go#L152-L212
7,562
luci/luci-go
vpython/venv/config.go
envNameForSpec
func (cfg *Config) envNameForSpec(c context.Context, s *vpython.Spec, rt *vpython.Runtime) string { uid := "<unknown>" if user, err := user.Current(); err == nil { uid = user.Uid } else { logging.Warningf(c, "Unable to find current user ID: %s", err) } name := spec.Hash(s, rt, EnvironmentVersion, string(assets.GetAssetSHA256(siteCustomizePy)), uid) if cfg.MaxHashLen > 0 && len(name) > cfg.MaxHashLen { name = name[:cfg.MaxHashLen] } return name }
go
func (cfg *Config) envNameForSpec(c context.Context, s *vpython.Spec, rt *vpython.Runtime) string { uid := "<unknown>" if user, err := user.Current(); err == nil { uid = user.Uid } else { logging.Warningf(c, "Unable to find current user ID: %s", err) } name := spec.Hash(s, rt, EnvironmentVersion, string(assets.GetAssetSHA256(siteCustomizePy)), uid) if cfg.MaxHashLen > 0 && len(name) > cfg.MaxHashLen { name = name[:cfg.MaxHashLen] } return name }
[ "func", "(", "cfg", "*", "Config", ")", "envNameForSpec", "(", "c", "context", ".", "Context", ",", "s", "*", "vpython", ".", "Spec", ",", "rt", "*", "vpython", ".", "Runtime", ")", "string", "{", "uid", ":=", "\"", "\"", "\n", "if", "user", ",", "err", ":=", "user", ".", "Current", "(", ")", ";", "err", "==", "nil", "{", "uid", "=", "user", ".", "Uid", "\n", "}", "else", "{", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "name", ":=", "spec", ".", "Hash", "(", "s", ",", "rt", ",", "EnvironmentVersion", ",", "string", "(", "assets", ".", "GetAssetSHA256", "(", "siteCustomizePy", ")", ")", ",", "uid", ")", "\n", "if", "cfg", ".", "MaxHashLen", ">", "0", "&&", "len", "(", "name", ")", ">", "cfg", ".", "MaxHashLen", "{", "name", "=", "name", "[", ":", "cfg", ".", "MaxHashLen", "]", "\n", "}", "\n", "return", "name", "\n", "}" ]
// EnvName returns the VirtualEnv environment name for the environment that cfg // describes.
[ "EnvName", "returns", "the", "VirtualEnv", "environment", "name", "for", "the", "environment", "that", "cfg", "describes", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/config.go#L216-L230
7,563
luci/luci-go
vpython/venv/config.go
Prune
func (cfg *Config) Prune(c context.Context) error { if err := prune(c, cfg, nil); err != nil { return errors.Annotate(err, "").Err() } return nil }
go
func (cfg *Config) Prune(c context.Context) error { if err := prune(c, cfg, nil); err != nil { return errors.Annotate(err, "").Err() } return nil }
[ "func", "(", "cfg", "*", "Config", ")", "Prune", "(", "c", "context", ".", "Context", ")", "error", "{", "if", "err", ":=", "prune", "(", "c", ",", "cfg", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Prune performs a pruning round on the environment set described by this // Config.
[ "Prune", "performs", "a", "pruning", "round", "on", "the", "environment", "set", "described", "by", "this", "Config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/config.go#L234-L239
7,564
luci/luci-go
vpython/venv/config.go
envForName
func (cfg *Config) envForName(name string, e *vpython.Environment) *Env { // Env-specific root directory: <BaseDir>/<name> venvRoot := filepath.Join(cfg.BaseDir, name) binDir := venvBinDir(venvRoot) return &Env{ Config: cfg, Root: venvRoot, Name: name, Python: filepath.Join(binDir, "python"), Environment: e, BinDir: binDir, EnvironmentStampPath: filepath.Join(venvRoot, fmt.Sprintf("environment.%s.pb.txt", vpython.Version)), lockPath: filepath.Join(cfg.BaseDir, fmt.Sprintf(".%s.lock", name)), completeFlagPath: filepath.Join(venvRoot, "complete.flag"), } }
go
func (cfg *Config) envForName(name string, e *vpython.Environment) *Env { // Env-specific root directory: <BaseDir>/<name> venvRoot := filepath.Join(cfg.BaseDir, name) binDir := venvBinDir(venvRoot) return &Env{ Config: cfg, Root: venvRoot, Name: name, Python: filepath.Join(binDir, "python"), Environment: e, BinDir: binDir, EnvironmentStampPath: filepath.Join(venvRoot, fmt.Sprintf("environment.%s.pb.txt", vpython.Version)), lockPath: filepath.Join(cfg.BaseDir, fmt.Sprintf(".%s.lock", name)), completeFlagPath: filepath.Join(venvRoot, "complete.flag"), } }
[ "func", "(", "cfg", "*", "Config", ")", "envForName", "(", "name", "string", ",", "e", "*", "vpython", ".", "Environment", ")", "*", "Env", "{", "// Env-specific root directory: <BaseDir>/<name>", "venvRoot", ":=", "filepath", ".", "Join", "(", "cfg", ".", "BaseDir", ",", "name", ")", "\n", "binDir", ":=", "venvBinDir", "(", "venvRoot", ")", "\n", "return", "&", "Env", "{", "Config", ":", "cfg", ",", "Root", ":", "venvRoot", ",", "Name", ":", "name", ",", "Python", ":", "filepath", ".", "Join", "(", "binDir", ",", "\"", "\"", ")", ",", "Environment", ":", "e", ",", "BinDir", ":", "binDir", ",", "EnvironmentStampPath", ":", "filepath", ".", "Join", "(", "venvRoot", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "vpython", ".", "Version", ")", ")", ",", "lockPath", ":", "filepath", ".", "Join", "(", "cfg", ".", "BaseDir", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", ",", "completeFlagPath", ":", "filepath", ".", "Join", "(", "venvRoot", ",", "\"", "\"", ")", ",", "}", "\n", "}" ]
// envForName creates an Env for a named directory. // // The Environment, e, can be nil; however, code paths that require it may not // be called.
[ "envForName", "creates", "an", "Env", "for", "a", "named", "directory", ".", "The", "Environment", "e", "can", "be", "nil", ";", "however", "code", "paths", "that", "require", "it", "may", "not", "be", "called", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/config.go#L245-L261
7,565
luci/luci-go
vpython/venv/config.go
fillRuntime
func fillRuntime(c context.Context, i *python.Interpreter, r *vpython.Runtime) error { // JSON fields correspond to "vpython.Runtime" fields. const script = `` + `import json, sys;` + `json.dump({` + `'path': sys.executable,` + `'prefix': sys.prefix,` + `}, sys.stdout)` // Probe the runtime information. var stdout, stderr bytes.Buffer cmd := i.IsolatedCommand(c, python.CommandTarget{Command: script}) cmd.Stdout = &stdout if err := cmd.Run(); err != nil { logging.WithError(err).Errorf(c, "Failed to get runtime information:\n%s", stderr.Bytes()) return errors.Annotate(err, "failed to get runtime information").Err() } if err := json.Unmarshal(stdout.Bytes(), r); err != nil { return errors.Annotate(err, "could not unmarshal output: %q", stdout.Bytes()).Err() } // "sys.executable" is allowed to be None. If it is, use the Python // interpreter path. // // Resolve it to an absolute path. "sys.executable" says that it must be one, // but we'll enforce it just to be sure. if r.Path == "" { r.Path = i.Python } if err := filesystem.AbsPath(&r.Path); err != nil { return err } var err error if r.Hash, err = hashPath(r.Path); err != nil { return err } return nil }
go
func fillRuntime(c context.Context, i *python.Interpreter, r *vpython.Runtime) error { // JSON fields correspond to "vpython.Runtime" fields. const script = `` + `import json, sys;` + `json.dump({` + `'path': sys.executable,` + `'prefix': sys.prefix,` + `}, sys.stdout)` // Probe the runtime information. var stdout, stderr bytes.Buffer cmd := i.IsolatedCommand(c, python.CommandTarget{Command: script}) cmd.Stdout = &stdout if err := cmd.Run(); err != nil { logging.WithError(err).Errorf(c, "Failed to get runtime information:\n%s", stderr.Bytes()) return errors.Annotate(err, "failed to get runtime information").Err() } if err := json.Unmarshal(stdout.Bytes(), r); err != nil { return errors.Annotate(err, "could not unmarshal output: %q", stdout.Bytes()).Err() } // "sys.executable" is allowed to be None. If it is, use the Python // interpreter path. // // Resolve it to an absolute path. "sys.executable" says that it must be one, // but we'll enforce it just to be sure. if r.Path == "" { r.Path = i.Python } if err := filesystem.AbsPath(&r.Path); err != nil { return err } var err error if r.Hash, err = hashPath(r.Path); err != nil { return err } return nil }
[ "func", "fillRuntime", "(", "c", "context", ".", "Context", ",", "i", "*", "python", ".", "Interpreter", ",", "r", "*", "vpython", ".", "Runtime", ")", "error", "{", "// JSON fields correspond to \"vpython.Runtime\" fields.", "const", "script", "=", "``", "+", "`import json, sys;`", "+", "`json.dump({`", "+", "`'path': sys.executable,`", "+", "`'prefix': sys.prefix,`", "+", "`}, sys.stdout)`", "\n\n", "// Probe the runtime information.", "var", "stdout", ",", "stderr", "bytes", ".", "Buffer", "\n", "cmd", ":=", "i", ".", "IsolatedCommand", "(", "c", ",", "python", ".", "CommandTarget", "{", "Command", ":", "script", "}", ")", "\n", "cmd", ".", "Stdout", "=", "&", "stdout", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\\n", "\"", ",", "stderr", ".", "Bytes", "(", ")", ")", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "stdout", ".", "Bytes", "(", ")", ",", "r", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "stdout", ".", "Bytes", "(", ")", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// \"sys.executable\" is allowed to be None. If it is, use the Python", "// interpreter path.", "//", "// Resolve it to an absolute path. \"sys.executable\" says that it must be one,", "// but we'll enforce it just to be sure.", "if", "r", ".", "Path", "==", "\"", "\"", "{", "r", ".", "Path", "=", "i", ".", "Python", "\n", "}", "\n", "if", "err", ":=", "filesystem", ".", "AbsPath", "(", "&", "r", ".", "Path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "err", "error", "\n", "if", "r", ".", "Hash", ",", "err", "=", "hashPath", "(", "r", ".", "Path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// fillRuntime returns the runtime information of the specified interpreter. // // Identifying this information requires the interpreter to be run.
[ "fillRuntime", "returns", "the", "runtime", "information", "of", "the", "specified", "interpreter", ".", "Identifying", "this", "information", "requires", "the", "interpreter", "to", "be", "run", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/config.go#L303-L343
7,566
luci/luci-go
grpc/cmd/cproto/discovery.go
gofmt
func gofmt(blob []byte) ([]byte, error) { out := bytes.Buffer{} cmd := exec.Command("gofmt", "-s") cmd.Stdin = bytes.NewReader(blob) cmd.Stdout = &out cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return nil, err } return out.Bytes(), nil }
go
func gofmt(blob []byte) ([]byte, error) { out := bytes.Buffer{} cmd := exec.Command("gofmt", "-s") cmd.Stdin = bytes.NewReader(blob) cmd.Stdout = &out cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return nil, err } return out.Bytes(), nil }
[ "func", "gofmt", "(", "blob", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "out", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Stdin", "=", "bytes", ".", "NewReader", "(", "blob", ")", "\n", "cmd", ".", "Stdout", "=", "&", "out", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "out", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// gofmt applies "gofmt -s" to the content of the buffer.
[ "gofmt", "applies", "gofmt", "-", "s", "to", "the", "content", "of", "the", "buffer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/cproto/discovery.go#L143-L153
7,567
luci/luci-go
grpc/cmd/cproto/discovery.go
compress
func compress(data []byte) ([]byte, error) { var buf bytes.Buffer w := gzip.NewWriter(&buf) if _, err := w.Write(data); err != nil { return nil, err } if err := w.Close(); err != nil { return nil, err } return buf.Bytes(), nil }
go
func compress(data []byte) ([]byte, error) { var buf bytes.Buffer w := gzip.NewWriter(&buf) if _, err := w.Write(data); err != nil { return nil, err } if err := w.Close(); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "compress", "(", "data", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "w", ":=", "gzip", ".", "NewWriter", "(", "&", "buf", ")", "\n", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "data", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "w", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// compress compresses data with gzip.
[ "compress", "compresses", "data", "with", "gzip", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/cproto/discovery.go#L156-L166
7,568
luci/luci-go
tokenserver/cmd/luci_machine_tokend/main.go
calcDigest
func calcDigest(inputs map[string][]byte) string { keys := make([]string, 0, len(inputs)) for k := range inputs { keys = append(keys, k) } sort.Strings(keys) h := sha1.New() for _, k := range keys { v := inputs[k] fmt.Fprintf(h, "%s\n%d\n", k, len(v)) h.Write(v) } blob := h.Sum(nil) return hex.EncodeToString(blob[:]) }
go
func calcDigest(inputs map[string][]byte) string { keys := make([]string, 0, len(inputs)) for k := range inputs { keys = append(keys, k) } sort.Strings(keys) h := sha1.New() for _, k := range keys { v := inputs[k] fmt.Fprintf(h, "%s\n%d\n", k, len(v)) h.Write(v) } blob := h.Sum(nil) return hex.EncodeToString(blob[:]) }
[ "func", "calcDigest", "(", "inputs", "map", "[", "string", "]", "[", "]", "byte", ")", "string", "{", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "inputs", ")", ")", "\n", "for", "k", ":=", "range", "inputs", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "h", ":=", "sha1", ".", "New", "(", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "v", ":=", "inputs", "[", "k", "]", "\n", "fmt", ".", "Fprintf", "(", "h", ",", "\"", "\\n", "\\n", "\"", ",", "k", ",", "len", "(", "v", ")", ")", "\n", "h", ".", "Write", "(", "v", ")", "\n", "}", "\n", "blob", ":=", "h", ".", "Sum", "(", "nil", ")", "\n", "return", "hex", ".", "EncodeToString", "(", "blob", "[", ":", "]", ")", "\n", "}" ]
// calcDigest produces a digest of a given map using some stable serialization.
[ "calcDigest", "produces", "a", "digest", "of", "a", "given", "map", "using", "some", "stable", "serialization", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/cmd/luci_machine_tokend/main.go#L314-L328
7,569
luci/luci-go
scheduler/appengine/engine/policy/policy.go
Default
func Default() Func { f, err := New(&defaultPolicy) if err != nil { panic(fmt.Errorf("failed to instantiate default triggering policy - %s", err)) } return f }
go
func Default() Func { f, err := New(&defaultPolicy) if err != nil { panic(fmt.Errorf("failed to instantiate default triggering policy - %s", err)) } return f }
[ "func", "Default", "(", ")", "Func", "{", "f", ",", "err", ":=", "New", "(", "&", "defaultPolicy", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "f", "\n", "}" ]
// Default instantiates default triggering policy function. // // Is is used if jobs do not define a triggering policy or it can't be // understood.
[ "Default", "instantiates", "default", "triggering", "policy", "function", ".", "Is", "is", "used", "if", "jobs", "do", "not", "define", "a", "triggering", "policy", "or", "it", "can", "t", "be", "understood", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/policy.go#L106-L112
7,570
luci/luci-go
scheduler/appengine/engine/policy/policy.go
UnmarshalDefinition
func UnmarshalDefinition(b []byte) (*messages.TriggeringPolicy, error) { msg := &messages.TriggeringPolicy{} if len(b) != 0 { if err := proto.Unmarshal(b, msg); err != nil { return nil, errors.Annotate(err, "failed to unmarshal TriggeringPolicy").Err() } } if msg.Kind == 0 { msg.Kind = defaultPolicy.Kind } if msg.MaxConcurrentInvocations == 0 { msg.MaxConcurrentInvocations = defaultPolicy.MaxConcurrentInvocations } if msg.MaxBatchSize == 0 { msg.MaxBatchSize = defaultPolicy.MaxBatchSize } return msg, nil }
go
func UnmarshalDefinition(b []byte) (*messages.TriggeringPolicy, error) { msg := &messages.TriggeringPolicy{} if len(b) != 0 { if err := proto.Unmarshal(b, msg); err != nil { return nil, errors.Annotate(err, "failed to unmarshal TriggeringPolicy").Err() } } if msg.Kind == 0 { msg.Kind = defaultPolicy.Kind } if msg.MaxConcurrentInvocations == 0 { msg.MaxConcurrentInvocations = defaultPolicy.MaxConcurrentInvocations } if msg.MaxBatchSize == 0 { msg.MaxBatchSize = defaultPolicy.MaxBatchSize } return msg, nil }
[ "func", "UnmarshalDefinition", "(", "b", "[", "]", "byte", ")", "(", "*", "messages", ".", "TriggeringPolicy", ",", "error", ")", "{", "msg", ":=", "&", "messages", ".", "TriggeringPolicy", "{", "}", "\n", "if", "len", "(", "b", ")", "!=", "0", "{", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "b", ",", "msg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "if", "msg", ".", "Kind", "==", "0", "{", "msg", ".", "Kind", "=", "defaultPolicy", ".", "Kind", "\n", "}", "\n", "if", "msg", ".", "MaxConcurrentInvocations", "==", "0", "{", "msg", ".", "MaxConcurrentInvocations", "=", "defaultPolicy", ".", "MaxConcurrentInvocations", "\n", "}", "\n", "if", "msg", ".", "MaxBatchSize", "==", "0", "{", "msg", ".", "MaxBatchSize", "=", "defaultPolicy", ".", "MaxBatchSize", "\n", "}", "\n", "return", "msg", ",", "nil", "\n", "}" ]
// UnmarshalDefinition deserializes TriggeringPolicy, filling in defaults.
[ "UnmarshalDefinition", "deserializes", "TriggeringPolicy", "filling", "in", "defaults", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/policy.go#L115-L132
7,571
luci/luci-go
server/templates/loaders.go
readFilesInDir
func readFilesInDir(dir string, out map[string]string) error { _, err := os.Stat(dir) if os.IsNotExist(err) { return nil } return filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() { return err } body, err := ioutil.ReadFile(path) if err == nil { out[path] = string(body) } return err }) }
go
func readFilesInDir(dir string, out map[string]string) error { _, err := os.Stat(dir) if os.IsNotExist(err) { return nil } return filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() { return err } body, err := ioutil.ReadFile(path) if err == nil { out[path] = string(body) } return err }) }
[ "func", "readFilesInDir", "(", "dir", "string", ",", "out", "map", "[", "string", "]", "string", ")", "error", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "dir", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "filepath", ".", "Walk", "(", "dir", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "||", "info", ".", "IsDir", "(", ")", "{", "return", "err", "\n", "}", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "==", "nil", "{", "out", "[", "path", "]", "=", "string", "(", "body", ")", "\n", "}", "\n", "return", "err", "\n", "}", ")", "\n", "}" ]
// readFilesInDir loads content of files into a map "file path" => content. // // Used only for small HTML templates, and thus it's fine to load them // in memory. // // Does nothing is 'dir' is missing.
[ "readFilesInDir", "loads", "content", "of", "files", "into", "a", "map", "file", "path", "=", ">", "content", ".", "Used", "only", "for", "small", "HTML", "templates", "and", "thus", "it", "s", "fine", "to", "load", "them", "in", "memory", ".", "Does", "nothing", "is", "dir", "is", "missing", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/templates/loaders.go#L111-L126
7,572
luci/luci-go
tokenserver/appengine/impl/services/admin/adminsrv/service.go
NewServer
func NewServer() *AdminServer { signer := gaesigner.Signer{} return &AdminServer{ ImportDelegationConfigsRPC: delegation.ImportDelegationConfigsRPC{ RulesCache: delegation.GlobalRulesCache, }, InspectDelegationTokenRPC: delegation.InspectDelegationTokenRPC{ Signer: signer, }, InspectMachineTokenRPC: machinetoken.InspectMachineTokenRPC{ Signer: signer, }, ImportServiceAccountsConfigsRPC: serviceaccounts.ImportServiceAccountsConfigsRPC{ RulesCache: serviceaccounts.GlobalRulesCache, }, InspectOAuthTokenGrantRPC: serviceaccounts.InspectOAuthTokenGrantRPC{ Signer: signer, Rules: serviceaccounts.GlobalRulesCache.Rules, }, ImportProjectIdentityConfigsRPC: projectscope.ImportProjectIdentityConfigsRPC{}, } }
go
func NewServer() *AdminServer { signer := gaesigner.Signer{} return &AdminServer{ ImportDelegationConfigsRPC: delegation.ImportDelegationConfigsRPC{ RulesCache: delegation.GlobalRulesCache, }, InspectDelegationTokenRPC: delegation.InspectDelegationTokenRPC{ Signer: signer, }, InspectMachineTokenRPC: machinetoken.InspectMachineTokenRPC{ Signer: signer, }, ImportServiceAccountsConfigsRPC: serviceaccounts.ImportServiceAccountsConfigsRPC{ RulesCache: serviceaccounts.GlobalRulesCache, }, InspectOAuthTokenGrantRPC: serviceaccounts.InspectOAuthTokenGrantRPC{ Signer: signer, Rules: serviceaccounts.GlobalRulesCache.Rules, }, ImportProjectIdentityConfigsRPC: projectscope.ImportProjectIdentityConfigsRPC{}, } }
[ "func", "NewServer", "(", ")", "*", "AdminServer", "{", "signer", ":=", "gaesigner", ".", "Signer", "{", "}", "\n", "return", "&", "AdminServer", "{", "ImportDelegationConfigsRPC", ":", "delegation", ".", "ImportDelegationConfigsRPC", "{", "RulesCache", ":", "delegation", ".", "GlobalRulesCache", ",", "}", ",", "InspectDelegationTokenRPC", ":", "delegation", ".", "InspectDelegationTokenRPC", "{", "Signer", ":", "signer", ",", "}", ",", "InspectMachineTokenRPC", ":", "machinetoken", ".", "InspectMachineTokenRPC", "{", "Signer", ":", "signer", ",", "}", ",", "ImportServiceAccountsConfigsRPC", ":", "serviceaccounts", ".", "ImportServiceAccountsConfigsRPC", "{", "RulesCache", ":", "serviceaccounts", ".", "GlobalRulesCache", ",", "}", ",", "InspectOAuthTokenGrantRPC", ":", "serviceaccounts", ".", "InspectOAuthTokenGrantRPC", "{", "Signer", ":", "signer", ",", "Rules", ":", "serviceaccounts", ".", "GlobalRulesCache", ".", "Rules", ",", "}", ",", "ImportProjectIdentityConfigsRPC", ":", "projectscope", ".", "ImportProjectIdentityConfigsRPC", "{", "}", ",", "}", "\n", "}" ]
// NewServer returns prod AdminServer implementation. // // It assumes authorization has happened already.
[ "NewServer", "returns", "prod", "AdminServer", "implementation", ".", "It", "assumes", "authorization", "has", "happened", "already", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/services/admin/adminsrv/service.go#L44-L65
7,573
luci/luci-go
gce/appengine/rpc/common.go
isReadOnly
func isReadOnly(methodName string) bool { return strings.HasPrefix(methodName, "Get") || strings.HasPrefix(methodName, "List") }
go
func isReadOnly(methodName string) bool { return strings.HasPrefix(methodName, "Get") || strings.HasPrefix(methodName, "List") }
[ "func", "isReadOnly", "(", "methodName", "string", ")", "bool", "{", "return", "strings", ".", "HasPrefix", "(", "methodName", ",", "\"", "\"", ")", "||", "strings", ".", "HasPrefix", "(", "methodName", ",", "\"", "\"", ")", "\n", "}" ]
// isReadOnly returns whether the given method name is for a read-only method.
[ "isReadOnly", "returns", "whether", "the", "given", "method", "name", "is", "for", "a", "read", "-", "only", "method", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/common.go#L40-L42
7,574
luci/luci-go
gce/appengine/rpc/common.go
readOnlyAuthPrelude
func readOnlyAuthPrelude(c context.Context, methodName string, req proto.Message) (context.Context, error) { if !isReadOnly(methodName) { return c, status.Errorf(codes.PermissionDenied, "unauthorized user") } switch is, err := auth.IsMember(c, admins, writers, readers); { case err != nil: return c, err case is: logging.Debugf(c, "%s called %q:\n%s", auth.CurrentIdentity(c), methodName, req) return c, nil } return c, status.Errorf(codes.PermissionDenied, "unauthorized user") }
go
func readOnlyAuthPrelude(c context.Context, methodName string, req proto.Message) (context.Context, error) { if !isReadOnly(methodName) { return c, status.Errorf(codes.PermissionDenied, "unauthorized user") } switch is, err := auth.IsMember(c, admins, writers, readers); { case err != nil: return c, err case is: logging.Debugf(c, "%s called %q:\n%s", auth.CurrentIdentity(c), methodName, req) return c, nil } return c, status.Errorf(codes.PermissionDenied, "unauthorized user") }
[ "func", "readOnlyAuthPrelude", "(", "c", "context", ".", "Context", ",", "methodName", "string", ",", "req", "proto", ".", "Message", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "if", "!", "isReadOnly", "(", "methodName", ")", "{", "return", "c", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n", "switch", "is", ",", "err", ":=", "auth", ".", "IsMember", "(", "c", ",", "admins", ",", "writers", ",", "readers", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "c", ",", "err", "\n", "case", "is", ":", "logging", ".", "Debugf", "(", "c", ",", "\"", "\\n", "\"", ",", "auth", ".", "CurrentIdentity", "(", "c", ")", ",", "methodName", ",", "req", ")", "\n", "return", "c", ",", "nil", "\n", "}", "\n", "return", "c", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}" ]
// readOnlyAuthPrelude ensures the user is authorized to use read API methods. // Always returns permission denied for write API methods.
[ "readOnlyAuthPrelude", "ensures", "the", "user", "is", "authorized", "to", "use", "read", "API", "methods", ".", "Always", "returns", "permission", "denied", "for", "write", "API", "methods", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/common.go#L46-L58
7,575
luci/luci-go
gce/appengine/rpc/common.go
vmAccessPrelude
func vmAccessPrelude(c context.Context, methodName string, req proto.Message) (context.Context, error) { groups := []string{admins, writers} if isReadOnly(methodName) { groups = append(groups, readers) } switch is, err := auth.IsMember(c, groups...); { case err != nil: return c, err case is: logging.Debugf(c, "%s called %q:\n%s", auth.CurrentIdentity(c), methodName, req) // Remove the VM token to avoid restricting the user's broad access. return vmtoken.Clear(c), nil case isVMAccessible(methodName) && vmtoken.Has(c): logging.Debugf(c, "%s called %q:\n%s", vmtoken.CurrentIdentity(c), methodName, req) return c, nil } return c, status.Errorf(codes.PermissionDenied, "unauthorized user") }
go
func vmAccessPrelude(c context.Context, methodName string, req proto.Message) (context.Context, error) { groups := []string{admins, writers} if isReadOnly(methodName) { groups = append(groups, readers) } switch is, err := auth.IsMember(c, groups...); { case err != nil: return c, err case is: logging.Debugf(c, "%s called %q:\n%s", auth.CurrentIdentity(c), methodName, req) // Remove the VM token to avoid restricting the user's broad access. return vmtoken.Clear(c), nil case isVMAccessible(methodName) && vmtoken.Has(c): logging.Debugf(c, "%s called %q:\n%s", vmtoken.CurrentIdentity(c), methodName, req) return c, nil } return c, status.Errorf(codes.PermissionDenied, "unauthorized user") }
[ "func", "vmAccessPrelude", "(", "c", "context", ".", "Context", ",", "methodName", "string", ",", "req", "proto", ".", "Message", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "groups", ":=", "[", "]", "string", "{", "admins", ",", "writers", "}", "\n", "if", "isReadOnly", "(", "methodName", ")", "{", "groups", "=", "append", "(", "groups", ",", "readers", ")", "\n", "}", "\n", "switch", "is", ",", "err", ":=", "auth", ".", "IsMember", "(", "c", ",", "groups", "...", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "c", ",", "err", "\n", "case", "is", ":", "logging", ".", "Debugf", "(", "c", ",", "\"", "\\n", "\"", ",", "auth", ".", "CurrentIdentity", "(", "c", ")", ",", "methodName", ",", "req", ")", "\n", "// Remove the VM token to avoid restricting the user's broad access.", "return", "vmtoken", ".", "Clear", "(", "c", ")", ",", "nil", "\n", "case", "isVMAccessible", "(", "methodName", ")", "&&", "vmtoken", ".", "Has", "(", "c", ")", ":", "logging", ".", "Debugf", "(", "c", ",", "\"", "\\n", "\"", ",", "vmtoken", ".", "CurrentIdentity", "(", "c", ")", ",", "methodName", ",", "req", ")", "\n", "return", "c", ",", "nil", "\n", "}", "\n", "return", "c", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}" ]
// vmAccessPrelude ensures the user is authorized to use the API or has // presented a valid GCE VM token and is attempting to use VM-accessible API. // Users of this prelude must perform additional authorization checks in methods // accepted by isVMAccessible.
[ "vmAccessPrelude", "ensures", "the", "user", "is", "authorized", "to", "use", "the", "API", "or", "has", "presented", "a", "valid", "GCE", "VM", "token", "and", "is", "attempting", "to", "use", "VM", "-", "accessible", "API", ".", "Users", "of", "this", "prelude", "must", "perform", "additional", "authorization", "checks", "in", "methods", "accepted", "by", "isVMAccessible", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/common.go#L71-L88
7,576
luci/luci-go
common/errors/filter.go
Filter
func Filter(err error, exclude error, others ...error) error { return FilterFunc(err, func(e error) bool { if e == exclude { return true } for _, v := range others { if e == v { return true } } return false }) }
go
func Filter(err error, exclude error, others ...error) error { return FilterFunc(err, func(e error) bool { if e == exclude { return true } for _, v := range others { if e == v { return true } } return false }) }
[ "func", "Filter", "(", "err", "error", ",", "exclude", "error", ",", "others", "...", "error", ")", "error", "{", "return", "FilterFunc", "(", "err", ",", "func", "(", "e", "error", ")", "bool", "{", "if", "e", "==", "exclude", "{", "return", "true", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "others", "{", "if", "e", "==", "v", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n", "}" ]
// Filter examines a supplied error and removes instances of excluded errors // from it. If the entire supplied error is excluded, Filter will return nil. // // If a MultiError is supplied to Filter, it will be recursively traversed, and // its child errors will be turned into nil if they match the supplied filter. // If a MultiError has all of its children converted to nil as a result of the // filter, it will itself be reduced to nil.
[ "Filter", "examines", "a", "supplied", "error", "and", "removes", "instances", "of", "excluded", "errors", "from", "it", ".", "If", "the", "entire", "supplied", "error", "is", "excluded", "Filter", "will", "return", "nil", ".", "If", "a", "MultiError", "is", "supplied", "to", "Filter", "it", "will", "be", "recursively", "traversed", "and", "its", "child", "errors", "will", "be", "turned", "into", "nil", "if", "they", "match", "the", "supplied", "filter", ".", "If", "a", "MultiError", "has", "all", "of", "its", "children", "converted", "to", "nil", "as", "a", "result", "of", "the", "filter", "it", "will", "itself", "be", "reduced", "to", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/filter.go#L24-L36
7,577
luci/luci-go
common/errors/filter.go
FilterFunc
func FilterFunc(err error, shouldFilter func(error) bool) error { switch { case shouldFilter == nil: return err case err == nil: return nil case shouldFilter(err): return nil } if merr, ok := err.(MultiError); ok { var lme MultiError for i, e := range merr { if e != nil { e = FilterFunc(e, shouldFilter) if e != nil { if lme == nil { lme = make(MultiError, len(merr)) } lme[i] = e } } } if lme == nil { return nil } return lme } return err }
go
func FilterFunc(err error, shouldFilter func(error) bool) error { switch { case shouldFilter == nil: return err case err == nil: return nil case shouldFilter(err): return nil } if merr, ok := err.(MultiError); ok { var lme MultiError for i, e := range merr { if e != nil { e = FilterFunc(e, shouldFilter) if e != nil { if lme == nil { lme = make(MultiError, len(merr)) } lme[i] = e } } } if lme == nil { return nil } return lme } return err }
[ "func", "FilterFunc", "(", "err", "error", ",", "shouldFilter", "func", "(", "error", ")", "bool", ")", "error", "{", "switch", "{", "case", "shouldFilter", "==", "nil", ":", "return", "err", "\n", "case", "err", "==", "nil", ":", "return", "nil", "\n", "case", "shouldFilter", "(", "err", ")", ":", "return", "nil", "\n", "}", "\n\n", "if", "merr", ",", "ok", ":=", "err", ".", "(", "MultiError", ")", ";", "ok", "{", "var", "lme", "MultiError", "\n", "for", "i", ",", "e", ":=", "range", "merr", "{", "if", "e", "!=", "nil", "{", "e", "=", "FilterFunc", "(", "e", ",", "shouldFilter", ")", "\n", "if", "e", "!=", "nil", "{", "if", "lme", "==", "nil", "{", "lme", "=", "make", "(", "MultiError", ",", "len", "(", "merr", ")", ")", "\n", "}", "\n", "lme", "[", "i", "]", "=", "e", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "lme", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "lme", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// FilterFunc examines a supplied error and removes instances of errors that // match the supplied filter function. If the entire supplied error is removed, // FilterFunc will return nil. // // If a MultiError is supplied to FilterFunc, it will be recursively traversed, // and its child errors will be turned into nil if they match the supplied // filter function. If a MultiError has all of its children converted to nil as // a result of the filter, it will itself be reduced to nil. // // Consqeuently, if err is a MultiError, shouldFilter will be called once with // err as its value and once for every non-nil error that it contains.
[ "FilterFunc", "examines", "a", "supplied", "error", "and", "removes", "instances", "of", "errors", "that", "match", "the", "supplied", "filter", "function", ".", "If", "the", "entire", "supplied", "error", "is", "removed", "FilterFunc", "will", "return", "nil", ".", "If", "a", "MultiError", "is", "supplied", "to", "FilterFunc", "it", "will", "be", "recursively", "traversed", "and", "its", "child", "errors", "will", "be", "turned", "into", "nil", "if", "they", "match", "the", "supplied", "filter", "function", ".", "If", "a", "MultiError", "has", "all", "of", "its", "children", "converted", "to", "nil", "as", "a", "result", "of", "the", "filter", "it", "will", "itself", "be", "reduced", "to", "nil", ".", "Consqeuently", "if", "err", "is", "a", "MultiError", "shouldFilter", "will", "be", "called", "once", "with", "err", "as", "its", "value", "and", "once", "for", "every", "non", "-", "nil", "error", "that", "it", "contains", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/filter.go#L49-L79
7,578
luci/luci-go
cipd/appengine/impl/cas/upload/operation.go
ToProto
func (op *Operation) ToProto(wrappedID string) *api.UploadOperation { var ref *api.ObjectRef if op.Status == api.UploadStatus_PUBLISHED { ref = &api.ObjectRef{ HashAlgo: op.HashAlgo, HexDigest: op.HexDigest, } } return &api.UploadOperation{ OperationId: wrappedID, UploadUrl: op.UploadURL, Status: op.Status, Object: ref, ErrorMessage: op.Error, } }
go
func (op *Operation) ToProto(wrappedID string) *api.UploadOperation { var ref *api.ObjectRef if op.Status == api.UploadStatus_PUBLISHED { ref = &api.ObjectRef{ HashAlgo: op.HashAlgo, HexDigest: op.HexDigest, } } return &api.UploadOperation{ OperationId: wrappedID, UploadUrl: op.UploadURL, Status: op.Status, Object: ref, ErrorMessage: op.Error, } }
[ "func", "(", "op", "*", "Operation", ")", "ToProto", "(", "wrappedID", "string", ")", "*", "api", ".", "UploadOperation", "{", "var", "ref", "*", "api", ".", "ObjectRef", "\n", "if", "op", ".", "Status", "==", "api", ".", "UploadStatus_PUBLISHED", "{", "ref", "=", "&", "api", ".", "ObjectRef", "{", "HashAlgo", ":", "op", ".", "HashAlgo", ",", "HexDigest", ":", "op", ".", "HexDigest", ",", "}", "\n", "}", "\n", "return", "&", "api", ".", "UploadOperation", "{", "OperationId", ":", "wrappedID", ",", "UploadUrl", ":", "op", ".", "UploadURL", ",", "Status", ":", "op", ".", "Status", ",", "Object", ":", "ref", ",", "ErrorMessage", ":", "op", ".", "Error", ",", "}", "\n", "}" ]
// ToProto constructs UploadOperation proto message. // // The caller must prepare the ID in advance using WrapOpID.
[ "ToProto", "constructs", "UploadOperation", "proto", "message", ".", "The", "caller", "must", "prepare", "the", "ID", "in", "advance", "using", "WrapOpID", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/upload/operation.go#L54-L69
7,579
luci/luci-go
logdog/appengine/coordinator/config/config.go
ServiceConfigPath
func ServiceConfigPath(c context.Context) (config.Set, string) { return cfgclient.CurrentServiceConfigSet(c), svcconfig.ServiceConfigPath }
go
func ServiceConfigPath(c context.Context) (config.Set, string) { return cfgclient.CurrentServiceConfigSet(c), svcconfig.ServiceConfigPath }
[ "func", "ServiceConfigPath", "(", "c", "context", ".", "Context", ")", "(", "config", ".", "Set", ",", "string", ")", "{", "return", "cfgclient", ".", "CurrentServiceConfigSet", "(", "c", ")", ",", "svcconfig", ".", "ServiceConfigPath", "\n", "}" ]
// ServiceConfigPath returns the config set and path for this application's // service configuration.
[ "ServiceConfigPath", "returns", "the", "config", "set", "and", "path", "for", "this", "application", "s", "service", "configuration", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/config/config.go#L51-L53
7,580
luci/luci-go
logdog/appengine/coordinator/config/config.go
validateServiceConfig
func validateServiceConfig(cc *svcconfig.Config) error { switch { case cc == nil: return errors.New("configuration is nil") case cc.GetCoordinator() == nil: return errors.New("no Coordinator configuration") default: return nil } }
go
func validateServiceConfig(cc *svcconfig.Config) error { switch { case cc == nil: return errors.New("configuration is nil") case cc.GetCoordinator() == nil: return errors.New("no Coordinator configuration") default: return nil } }
[ "func", "validateServiceConfig", "(", "cc", "*", "svcconfig", ".", "Config", ")", "error", "{", "switch", "{", "case", "cc", "==", "nil", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "cc", ".", "GetCoordinator", "(", ")", "==", "nil", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "}" ]
// validateServiceConfig checks the supplied service config object to ensure // that it meets a minimum configuration standard expected by our endpoitns and // handlers.
[ "validateServiceConfig", "checks", "the", "supplied", "service", "config", "object", "to", "ensure", "that", "it", "meets", "a", "minimum", "configuration", "standard", "expected", "by", "our", "endpoitns", "and", "handlers", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/config/config.go#L98-L107
7,581
luci/luci-go
milo/common/acl.go
IsAllowed
func IsAllowed(c context.Context, project string) (bool, error) { switch admin, err := IsAdmin(c); { case err != nil: return false, err case admin: return true, nil } // Get the project, because that's where the ACLs lie. err := access.Check(c, backend.AsUser, config.ProjectSet(project)) innerError := errors.Unwrap(err) switch { case err == nil: return true, nil case err == access.ErrNoAccess: return false, nil case innerError == config.ErrNoConfig: return false, grpcutil.NotFoundTag.Apply(err) default: return false, err } }
go
func IsAllowed(c context.Context, project string) (bool, error) { switch admin, err := IsAdmin(c); { case err != nil: return false, err case admin: return true, nil } // Get the project, because that's where the ACLs lie. err := access.Check(c, backend.AsUser, config.ProjectSet(project)) innerError := errors.Unwrap(err) switch { case err == nil: return true, nil case err == access.ErrNoAccess: return false, nil case innerError == config.ErrNoConfig: return false, grpcutil.NotFoundTag.Apply(err) default: return false, err } }
[ "func", "IsAllowed", "(", "c", "context", ".", "Context", ",", "project", "string", ")", "(", "bool", ",", "error", ")", "{", "switch", "admin", ",", "err", ":=", "IsAdmin", "(", "c", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "false", ",", "err", "\n", "case", "admin", ":", "return", "true", ",", "nil", "\n", "}", "\n\n", "// Get the project, because that's where the ACLs lie.", "err", ":=", "access", ".", "Check", "(", "c", ",", "backend", ".", "AsUser", ",", "config", ".", "ProjectSet", "(", "project", ")", ")", "\n", "innerError", ":=", "errors", ".", "Unwrap", "(", "err", ")", "\n\n", "switch", "{", "case", "err", "==", "nil", ":", "return", "true", ",", "nil", "\n", "case", "err", "==", "access", ".", "ErrNoAccess", ":", "return", "false", ",", "nil", "\n", "case", "innerError", "==", "config", ".", "ErrNoConfig", ":", "return", "false", ",", "grpcutil", ".", "NotFoundTag", ".", "Apply", "(", "err", ")", "\n", "default", ":", "return", "false", ",", "err", "\n", "}", "\n", "}" ]
// Helper functions for ACL checking. // IsAllowed checks to see if the user in the context is allowed to access // the given project.
[ "Helper", "functions", "for", "ACL", "checking", ".", "IsAllowed", "checks", "to", "see", "if", "the", "user", "in", "the", "context", "is", "allowed", "to", "access", "the", "given", "project", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/acl.go#L40-L62
7,582
luci/luci-go
milo/common/acl.go
NewAccessClient
func NewAccessClient(c context.Context) (*AccessClient, error) { settings := GetSettings(c) if settings.Buildbucket.GetHost() == "" { return nil, errors.Reason("no buildbucket host found").Err() } t, err := auth.GetRPCTransport(c, auth.AsUser) if err != nil { return nil, errors.Annotate(err, "getting RPC Transport").Err() } return &AccessClient{ AccessClient: bbAccess.NewClient(settings.Buildbucket.Host, &http.Client{Transport: t}), Host: settings.Buildbucket.Host, }, nil }
go
func NewAccessClient(c context.Context) (*AccessClient, error) { settings := GetSettings(c) if settings.Buildbucket.GetHost() == "" { return nil, errors.Reason("no buildbucket host found").Err() } t, err := auth.GetRPCTransport(c, auth.AsUser) if err != nil { return nil, errors.Annotate(err, "getting RPC Transport").Err() } return &AccessClient{ AccessClient: bbAccess.NewClient(settings.Buildbucket.Host, &http.Client{Transport: t}), Host: settings.Buildbucket.Host, }, nil }
[ "func", "NewAccessClient", "(", "c", "context", ".", "Context", ")", "(", "*", "AccessClient", ",", "error", ")", "{", "settings", ":=", "GetSettings", "(", "c", ")", "\n", "if", "settings", ".", "Buildbucket", ".", "GetHost", "(", ")", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "t", ",", "err", ":=", "auth", ".", "GetRPCTransport", "(", "c", ",", "auth", ".", "AsUser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "&", "AccessClient", "{", "AccessClient", ":", "bbAccess", ".", "NewClient", "(", "settings", ".", "Buildbucket", ".", "Host", ",", "&", "http", ".", "Client", "{", "Transport", ":", "t", "}", ")", ",", "Host", ":", "settings", ".", "Buildbucket", ".", "Host", ",", "}", ",", "nil", "\n", "}" ]
// NewAccessClient creates a new AccessClient for talking to this milo instance's buildbucket instance.
[ "NewAccessClient", "creates", "a", "new", "AccessClient", "for", "talking", "to", "this", "milo", "instance", "s", "buildbucket", "instance", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/acl.go#L79-L92
7,583
luci/luci-go
milo/common/acl.go
WithAccessClient
func WithAccessClient(c context.Context, a *AccessClient) context.Context { return context.WithValue(c, &accessClientKey, a) }
go
func WithAccessClient(c context.Context, a *AccessClient) context.Context { return context.WithValue(c, &accessClientKey, a) }
[ "func", "WithAccessClient", "(", "c", "context", ".", "Context", ",", "a", "*", "AccessClient", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "&", "accessClientKey", ",", "a", ")", "\n", "}" ]
// WithAccessClient attaches an AccessClient to the given context.
[ "WithAccessClient", "attaches", "an", "AccessClient", "to", "the", "given", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/acl.go#L95-L97
7,584
luci/luci-go
milo/common/acl.go
GetAccessClient
func GetAccessClient(c context.Context) *AccessClient { if client, ok := c.Value(&accessClientKey).(*AccessClient); !ok { panic("access client not found in context") } else { return client } }
go
func GetAccessClient(c context.Context) *AccessClient { if client, ok := c.Value(&accessClientKey).(*AccessClient); !ok { panic("access client not found in context") } else { return client } }
[ "func", "GetAccessClient", "(", "c", "context", ".", "Context", ")", "*", "AccessClient", "{", "if", "client", ",", "ok", ":=", "c", ".", "Value", "(", "&", "accessClientKey", ")", ".", "(", "*", "AccessClient", ")", ";", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "else", "{", "return", "client", "\n", "}", "\n", "}" ]
// GetAccessClient retrieves an AccessClient from the given context.
[ "GetAccessClient", "retrieves", "an", "AccessClient", "from", "the", "given", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/acl.go#L100-L106
7,585
luci/luci-go
tokenserver/appengine/frontend/main.go
adminPrelude
func adminPrelude(serviceName string) func(context.Context, string, proto.Message) (context.Context, error) { return func(c context.Context, method string, _ proto.Message) (context.Context, error) { logging.Infof(c, "%s: %q is calling %q", serviceName, auth.CurrentIdentity(c), method) switch admin, err := auth.IsMember(c, "administrators"); { case err != nil: return nil, status.Errorf(codes.Internal, "can't check ACL - %s", err) case !admin: return nil, status.Errorf(codes.PermissionDenied, "not an admin") } return c, nil } }
go
func adminPrelude(serviceName string) func(context.Context, string, proto.Message) (context.Context, error) { return func(c context.Context, method string, _ proto.Message) (context.Context, error) { logging.Infof(c, "%s: %q is calling %q", serviceName, auth.CurrentIdentity(c), method) switch admin, err := auth.IsMember(c, "administrators"); { case err != nil: return nil, status.Errorf(codes.Internal, "can't check ACL - %s", err) case !admin: return nil, status.Errorf(codes.PermissionDenied, "not an admin") } return c, nil } }
[ "func", "adminPrelude", "(", "serviceName", "string", ")", "func", "(", "context", ".", "Context", ",", "string", ",", "proto", ".", "Message", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "return", "func", "(", "c", "context", ".", "Context", ",", "method", "string", ",", "_", "proto", ".", "Message", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "serviceName", ",", "auth", ".", "CurrentIdentity", "(", "c", ")", ",", "method", ")", "\n", "switch", "admin", ",", "err", ":=", "auth", ".", "IsMember", "(", "c", ",", "\"", "\"", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "err", ")", "\n", "case", "!", "admin", ":", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ",", "nil", "\n", "}", "\n", "}" ]
// adminPrelude returns a prelude that authorizes only administrators.
[ "adminPrelude", "returns", "a", "prelude", "that", "authorizes", "only", "administrators", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/frontend/main.go#L47-L58
7,586
luci/luci-go
common/data/text/templateproto/normalize.go
Normalize
func (t *File_Template) Normalize() error { if t.Body == "" { return errors.New("body is empty") } defaultParams := make(map[string]*Value, len(t.Param)) for k, param := range t.Param { if k == "" { return fmt.Errorf("param %q: invalid name", k) } if !ParamRegex.MatchString(k) { return fmt.Errorf("param %q: malformed name", k) } if !strings.Contains(t.Body, k) { return fmt.Errorf("param %q: not present in body", k) } if err := param.Normalize(); err != nil { return fmt.Errorf("param %q: %s", k, err) } if param.Default != nil { defaultParams[k] = param.Default } else { defaultParams[k] = param.Schema.Zero() } } maybeJSON, err := t.Render(defaultParams) if err != nil { return fmt.Errorf("rendering: %s", err) } err = json.Unmarshal([]byte(maybeJSON), &map[string]interface{}{}) if err != nil { return fmt.Errorf("parsing rendered body: %s", err) } return nil }
go
func (t *File_Template) Normalize() error { if t.Body == "" { return errors.New("body is empty") } defaultParams := make(map[string]*Value, len(t.Param)) for k, param := range t.Param { if k == "" { return fmt.Errorf("param %q: invalid name", k) } if !ParamRegex.MatchString(k) { return fmt.Errorf("param %q: malformed name", k) } if !strings.Contains(t.Body, k) { return fmt.Errorf("param %q: not present in body", k) } if err := param.Normalize(); err != nil { return fmt.Errorf("param %q: %s", k, err) } if param.Default != nil { defaultParams[k] = param.Default } else { defaultParams[k] = param.Schema.Zero() } } maybeJSON, err := t.Render(defaultParams) if err != nil { return fmt.Errorf("rendering: %s", err) } err = json.Unmarshal([]byte(maybeJSON), &map[string]interface{}{}) if err != nil { return fmt.Errorf("parsing rendered body: %s", err) } return nil }
[ "func", "(", "t", "*", "File_Template", ")", "Normalize", "(", ")", "error", "{", "if", "t", ".", "Body", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "defaultParams", ":=", "make", "(", "map", "[", "string", "]", "*", "Value", ",", "len", "(", "t", ".", "Param", ")", ")", "\n", "for", "k", ",", "param", ":=", "range", "t", ".", "Param", "{", "if", "k", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "if", "!", "ParamRegex", ".", "MatchString", "(", "k", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "if", "!", "strings", ".", "Contains", "(", "t", ".", "Body", ",", "k", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "if", "err", ":=", "param", ".", "Normalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ",", "err", ")", "\n", "}", "\n", "if", "param", ".", "Default", "!=", "nil", "{", "defaultParams", "[", "k", "]", "=", "param", ".", "Default", "\n", "}", "else", "{", "defaultParams", "[", "k", "]", "=", "param", ".", "Schema", ".", "Zero", "(", ")", "\n", "}", "\n", "}", "\n\n", "maybeJSON", ",", "err", ":=", "t", ".", "Render", "(", "defaultParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "maybeJSON", ")", ",", "&", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize will normalize the Template message, returning an error if it is // invalid.
[ "Normalize", "will", "normalize", "the", "Template", "message", "returning", "an", "error", "if", "it", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L50-L86
7,587
luci/luci-go
common/data/text/templateproto/normalize.go
Normalize
func (p *File_Template_Parameter) Normalize() error { if p == nil { return errors.New("is nil") } if err := p.Schema.Normalize(); err != nil { return fmt.Errorf("schema: %s", err) } if p.Default != nil { if err := p.Default.Normalize(); err != nil { return fmt.Errorf("default value: %s", err) } if err := p.Accepts(p.Default); err != nil { return fmt.Errorf("default value: %s", err) } } return nil }
go
func (p *File_Template_Parameter) Normalize() error { if p == nil { return errors.New("is nil") } if err := p.Schema.Normalize(); err != nil { return fmt.Errorf("schema: %s", err) } if p.Default != nil { if err := p.Default.Normalize(); err != nil { return fmt.Errorf("default value: %s", err) } if err := p.Accepts(p.Default); err != nil { return fmt.Errorf("default value: %s", err) } } return nil }
[ "func", "(", "p", "*", "File_Template_Parameter", ")", "Normalize", "(", ")", "error", "{", "if", "p", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "p", ".", "Schema", ".", "Normalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "p", ".", "Default", "!=", "nil", "{", "if", "err", ":=", "p", ".", "Default", ".", "Normalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "p", ".", "Accepts", "(", "p", ".", "Default", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize will normalize the Parameter, returning an error if it is invalid.
[ "Normalize", "will", "normalize", "the", "Parameter", "returning", "an", "error", "if", "it", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L89-L105
7,588
luci/luci-go
common/data/text/templateproto/normalize.go
Accepts
func (p *File_Template_Parameter) Accepts(v *Value) error { if v.IsNull() { if !p.Nullable { return errors.New("not nullable") } } else if err := p.Schema.Accepts(v); err != nil { return err } else if err := v.Check(p.Schema); err != nil { return err } return nil }
go
func (p *File_Template_Parameter) Accepts(v *Value) error { if v.IsNull() { if !p.Nullable { return errors.New("not nullable") } } else if err := p.Schema.Accepts(v); err != nil { return err } else if err := v.Check(p.Schema); err != nil { return err } return nil }
[ "func", "(", "p", "*", "File_Template_Parameter", ")", "Accepts", "(", "v", "*", "Value", ")", "error", "{", "if", "v", ".", "IsNull", "(", ")", "{", "if", "!", "p", ".", "Nullable", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "if", "err", ":=", "p", ".", "Schema", ".", "Accepts", "(", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "err", ":=", "v", ".", "Check", "(", "p", ".", "Schema", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Accepts returns nil if this Parameter can accept the Value.
[ "Accepts", "returns", "nil", "if", "this", "Parameter", "can", "accept", "the", "Value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L108-L119
7,589
luci/luci-go
common/data/text/templateproto/normalize.go
Normalize
func (s *Schema) Normalize() error { if s == nil { return errors.New("is nil") } if s.Schema == nil { return errors.New("has no type") } if enum := s.GetEnum(); enum != nil { return enum.Normalize() } return nil }
go
func (s *Schema) Normalize() error { if s == nil { return errors.New("is nil") } if s.Schema == nil { return errors.New("has no type") } if enum := s.GetEnum(); enum != nil { return enum.Normalize() } return nil }
[ "func", "(", "s", "*", "Schema", ")", "Normalize", "(", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "Schema", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "enum", ":=", "s", ".", "GetEnum", "(", ")", ";", "enum", "!=", "nil", "{", "return", "enum", ".", "Normalize", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize will normalize the Schema, returning an error if it is invalid.
[ "Normalize", "will", "normalize", "the", "Schema", "returning", "an", "error", "if", "it", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L122-L133
7,590
luci/luci-go
common/data/text/templateproto/normalize.go
Normalize
func (s *Schema_Set) Normalize() error { if len(s.Entry) == 0 { return errors.New("set requires entries") } set := stringset.New(len(s.Entry)) for _, entry := range s.Entry { if entry.Token == "" { return errors.New("blank token") } if !set.Add(entry.Token) { return fmt.Errorf("duplicate token %q", entry.Token) } } return nil }
go
func (s *Schema_Set) Normalize() error { if len(s.Entry) == 0 { return errors.New("set requires entries") } set := stringset.New(len(s.Entry)) for _, entry := range s.Entry { if entry.Token == "" { return errors.New("blank token") } if !set.Add(entry.Token) { return fmt.Errorf("duplicate token %q", entry.Token) } } return nil }
[ "func", "(", "s", "*", "Schema_Set", ")", "Normalize", "(", ")", "error", "{", "if", "len", "(", "s", ".", "Entry", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "set", ":=", "stringset", ".", "New", "(", "len", "(", "s", ".", "Entry", ")", ")", "\n", "for", "_", ",", "entry", ":=", "range", "s", ".", "Entry", "{", "if", "entry", ".", "Token", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "set", ".", "Add", "(", "entry", ".", "Token", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "entry", ".", "Token", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize will normalize the Schema_Set, returning an error if it is // invalid.
[ "Normalize", "will", "normalize", "the", "Schema_Set", "returning", "an", "error", "if", "it", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L137-L151
7,591
luci/luci-go
common/data/text/templateproto/normalize.go
Has
func (s *Schema_Set) Has(token string) bool { for _, tok := range s.Entry { if tok.Token == token { return true } } return false }
go
func (s *Schema_Set) Has(token string) bool { for _, tok := range s.Entry { if tok.Token == token { return true } } return false }
[ "func", "(", "s", "*", "Schema_Set", ")", "Has", "(", "token", "string", ")", "bool", "{", "for", "_", ",", "tok", ":=", "range", "s", ".", "Entry", "{", "if", "tok", ".", "Token", "==", "token", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Has returns true iff the given token is a valid value for this enumeration.
[ "Has", "returns", "true", "iff", "the", "given", "token", "is", "a", "valid", "value", "for", "this", "enumeration", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L154-L161
7,592
luci/luci-go
common/data/text/templateproto/normalize.go
IsNull
func (v *Value) IsNull() bool { _, ret := v.Value.(*Value_Null) return ret }
go
func (v *Value) IsNull() bool { _, ret := v.Value.(*Value_Null) return ret }
[ "func", "(", "v", "*", "Value", ")", "IsNull", "(", ")", "bool", "{", "_", ",", "ret", ":=", "v", ".", "Value", ".", "(", "*", "Value_Null", ")", "\n", "return", "ret", "\n", "}" ]
// IsNull returns true if this Value is the null value.
[ "IsNull", "returns", "true", "if", "this", "Value", "is", "the", "null", "value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L164-L167
7,593
luci/luci-go
common/data/text/templateproto/normalize.go
Check
func (v *Value) Check(s *Schema) error { check, needsCheck := v.Value.(interface { Check(*Schema) error }) if !needsCheck { return nil } return check.Check(s) }
go
func (v *Value) Check(s *Schema) error { check, needsCheck := v.Value.(interface { Check(*Schema) error }) if !needsCheck { return nil } return check.Check(s) }
[ "func", "(", "v", "*", "Value", ")", "Check", "(", "s", "*", "Schema", ")", "error", "{", "check", ",", "needsCheck", ":=", "v", ".", "Value", ".", "(", "interface", "{", "Check", "(", "*", "Schema", ")", "error", "\n", "}", ")", "\n", "if", "!", "needsCheck", "{", "return", "nil", "\n", "}", "\n", "return", "check", ".", "Check", "(", "s", ")", "\n", "}" ]
// Check ensures that this value conforms to the given schema.
[ "Check", "ensures", "that", "this", "value", "conforms", "to", "the", "given", "schema", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L170-L178
7,594
luci/luci-go
common/data/text/templateproto/normalize.go
Normalize
func (v *Value) Normalize() error { norm, needsNormalization := v.Value.(interface { Normalize() error }) if !needsNormalization { return nil } return norm.Normalize() }
go
func (v *Value) Normalize() error { norm, needsNormalization := v.Value.(interface { Normalize() error }) if !needsNormalization { return nil } return norm.Normalize() }
[ "func", "(", "v", "*", "Value", ")", "Normalize", "(", ")", "error", "{", "norm", ",", "needsNormalization", ":=", "v", ".", "Value", ".", "(", "interface", "{", "Normalize", "(", ")", "error", "\n", "}", ")", "\n", "if", "!", "needsNormalization", "{", "return", "nil", "\n", "}", "\n", "return", "norm", ".", "Normalize", "(", ")", "\n", "}" ]
// Normalize returns a non-nil error if the Value is invalid for its nominal type.
[ "Normalize", "returns", "a", "non", "-", "nil", "error", "if", "the", "Value", "is", "invalid", "for", "its", "nominal", "type", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L181-L189
7,595
luci/luci-go
common/data/text/templateproto/normalize.go
Check
func (v *Value_Bytes) Check(schema *Schema) error { s := schema.GetBytes() if s.MaxLength > 0 && uint32(len(v.Bytes)) > s.MaxLength { return fmt.Errorf("value is too large: %d > %d", len(v.Bytes), s.MaxLength) } return nil }
go
func (v *Value_Bytes) Check(schema *Schema) error { s := schema.GetBytes() if s.MaxLength > 0 && uint32(len(v.Bytes)) > s.MaxLength { return fmt.Errorf("value is too large: %d > %d", len(v.Bytes), s.MaxLength) } return nil }
[ "func", "(", "v", "*", "Value_Bytes", ")", "Check", "(", "schema", "*", "Schema", ")", "error", "{", "s", ":=", "schema", ".", "GetBytes", "(", ")", "\n", "if", "s", ".", "MaxLength", ">", "0", "&&", "uint32", "(", "len", "(", "v", ".", "Bytes", ")", ")", ">", "s", ".", "MaxLength", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "v", ".", "Bytes", ")", ",", "s", ".", "MaxLength", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check returns nil iff this Value meets the max length criteria.
[ "Check", "returns", "nil", "iff", "this", "Value", "meets", "the", "max", "length", "criteria", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L192-L198
7,596
luci/luci-go
common/data/text/templateproto/normalize.go
Check
func (v *Value_Object) Check(schema *Schema) error { s := schema.GetObject() if s.MaxLength > 0 && uint32(len(v.Object)) > s.MaxLength { return fmt.Errorf("value is too large: %d > %d", len(v.Object), s.MaxLength) } return nil }
go
func (v *Value_Object) Check(schema *Schema) error { s := schema.GetObject() if s.MaxLength > 0 && uint32(len(v.Object)) > s.MaxLength { return fmt.Errorf("value is too large: %d > %d", len(v.Object), s.MaxLength) } return nil }
[ "func", "(", "v", "*", "Value_Object", ")", "Check", "(", "schema", "*", "Schema", ")", "error", "{", "s", ":=", "schema", ".", "GetObject", "(", ")", "\n", "if", "s", ".", "MaxLength", ">", "0", "&&", "uint32", "(", "len", "(", "v", ".", "Object", ")", ")", ">", "s", ".", "MaxLength", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "v", ".", "Object", ")", ",", "s", ".", "MaxLength", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check returns nil iff this Value correctly parses as a JSON object.
[ "Check", "returns", "nil", "iff", "this", "Value", "correctly", "parses", "as", "a", "JSON", "object", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L223-L229
7,597
luci/luci-go
common/data/text/templateproto/normalize.go
Normalize
func (v *Value_Object) Normalize() error { newObj, err := NormalizeJSON(v.Object, true) if err != nil { return err } v.Object = newObj return nil }
go
func (v *Value_Object) Normalize() error { newObj, err := NormalizeJSON(v.Object, true) if err != nil { return err } v.Object = newObj return nil }
[ "func", "(", "v", "*", "Value_Object", ")", "Normalize", "(", ")", "error", "{", "newObj", ",", "err", ":=", "NormalizeJSON", "(", "v", ".", "Object", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "v", ".", "Object", "=", "newObj", "\n", "return", "nil", "\n", "}" ]
// Normalize returns nil iff this Value correctly parses as a JSON object.
[ "Normalize", "returns", "nil", "iff", "this", "Value", "correctly", "parses", "as", "a", "JSON", "object", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L232-L239
7,598
luci/luci-go
common/data/text/templateproto/normalize.go
Check
func (v *Value_Array) Check(schema *Schema) error { s := schema.GetArray() if s.MaxLength > 0 && uint32(len(v.Array)) > s.MaxLength { return fmt.Errorf("value is too large: %d > %d", len(v.Array), s.MaxLength) } return nil }
go
func (v *Value_Array) Check(schema *Schema) error { s := schema.GetArray() if s.MaxLength > 0 && uint32(len(v.Array)) > s.MaxLength { return fmt.Errorf("value is too large: %d > %d", len(v.Array), s.MaxLength) } return nil }
[ "func", "(", "v", "*", "Value_Array", ")", "Check", "(", "schema", "*", "Schema", ")", "error", "{", "s", ":=", "schema", ".", "GetArray", "(", ")", "\n", "if", "s", ".", "MaxLength", ">", "0", "&&", "uint32", "(", "len", "(", "v", ".", "Array", ")", ")", ">", "s", ".", "MaxLength", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "v", ".", "Array", ")", ",", "s", ".", "MaxLength", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check returns nil iff this Value correctly parses as a JSON array.
[ "Check", "returns", "nil", "iff", "this", "Value", "correctly", "parses", "as", "a", "JSON", "array", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L242-L248
7,599
luci/luci-go
common/data/text/templateproto/normalize.go
Normalize
func (v *Value_Array) Normalize() error { newAry, err := NormalizeJSON(v.Array, false) if err != nil { return err } v.Array = newAry return nil }
go
func (v *Value_Array) Normalize() error { newAry, err := NormalizeJSON(v.Array, false) if err != nil { return err } v.Array = newAry return nil }
[ "func", "(", "v", "*", "Value_Array", ")", "Normalize", "(", ")", "error", "{", "newAry", ",", "err", ":=", "NormalizeJSON", "(", "v", ".", "Array", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "v", ".", "Array", "=", "newAry", "\n", "return", "nil", "\n", "}" ]
// Normalize returns nil iff this Value correctly parses as a JSON array.
[ "Normalize", "returns", "nil", "iff", "this", "Value", "correctly", "parses", "as", "a", "JSON", "array", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L251-L258