id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
8,300
luci/luci-go
cipd/appengine/ui/cursors.go
storePrevCursor
func (k cursorKind) storePrevCursor(c context.Context, pkg, cursor, prev string) { itm := memcache.NewItem(c, k.cursorKey(pkg, cursor)) itm.SetValue([]byte(prev)) itm.SetExpiration(24 * time.Hour) if err := memcache.Set(c, itm); err != nil { logging.WithError(err).Errorf(c, "Failed to store prev cursor %q in memcache", k) } }
go
func (k cursorKind) storePrevCursor(c context.Context, pkg, cursor, prev string) { itm := memcache.NewItem(c, k.cursorKey(pkg, cursor)) itm.SetValue([]byte(prev)) itm.SetExpiration(24 * time.Hour) if err := memcache.Set(c, itm); err != nil { logging.WithError(err).Errorf(c, "Failed to store prev cursor %q in memcache", k) } }
[ "func", "(", "k", "cursorKind", ")", "storePrevCursor", "(", "c", "context", ".", "Context", ",", "pkg", ",", "cursor", ",", "prev", "string", ")", "{", "itm", ":=", "memcache", ".", "NewItem", "(", "c", ",", "k", ".", "cursorKey", "(", "pkg", ",", ...
// storePrevCursor stores mapping cursor => prev, so that prev can be fetched // later by fetchPrevCursor. // // Logs and ignores errors. Cursor mapping is non-essential functionality.
[ "storePrevCursor", "stores", "mapping", "cursor", "=", ">", "prev", "so", "that", "prev", "can", "be", "fetched", "later", "by", "fetchPrevCursor", ".", "Logs", "and", "ignores", "errors", ".", "Cursor", "mapping", "is", "non", "-", "essential", "functionality...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/ui/cursors.go#L41-L48
8,301
luci/luci-go
cipd/appengine/ui/cursors.go
fetchPrevCursor
func (k cursorKind) fetchPrevCursor(c context.Context, pkg, cursor string) string { itm, err := memcache.GetKey(c, k.cursorKey(pkg, cursor)) if err != nil { if err != memcache.ErrCacheMiss { logging.WithError(err).Errorf(c, "Failed to fetch prev cursor %q from memcache", k) } return "" } return string(itm.Value()) }
go
func (k cursorKind) fetchPrevCursor(c context.Context, pkg, cursor string) string { itm, err := memcache.GetKey(c, k.cursorKey(pkg, cursor)) if err != nil { if err != memcache.ErrCacheMiss { logging.WithError(err).Errorf(c, "Failed to fetch prev cursor %q from memcache", k) } return "" } return string(itm.Value()) }
[ "func", "(", "k", "cursorKind", ")", "fetchPrevCursor", "(", "c", "context", ".", "Context", ",", "pkg", ",", "cursor", "string", ")", "string", "{", "itm", ",", "err", ":=", "memcache", ".", "GetKey", "(", "c", ",", "k", ".", "cursorKey", "(", "pkg"...
// fetchPrevCursor returns a cursor stored by storePrevCursor. // // Logs and ignores errors. Cursor mapping is non-essential functionality.
[ "fetchPrevCursor", "returns", "a", "cursor", "stored", "by", "storePrevCursor", ".", "Logs", "and", "ignores", "errors", ".", "Cursor", "mapping", "is", "non", "-", "essential", "functionality", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/ui/cursors.go#L53-L62
8,302
luci/luci-go
logdog/client/butler/streamserver/tcp.go
newTCPServerImpl
func newTCPServerImpl(ctx context.Context, netType, spec string, loopback net.IP) (StreamServer, error) { tcpAddr, err := net.ResolveTCPAddr(netType, spec) if err != nil { return nil, errors.Annotate(err, "could not resolve %q address %q", netType, spec).Err() } if tcpAddr.IP == nil { tcpAddr.IP = loopback } return &listenerStreamServer{ Context: ctx, address: fmt.Sprintf("%s:%s", netType, tcpAddr.String()), gen: func() (net.Listener, string, error) { l, err := net.ListenTCP(netType, tcpAddr) if err != nil { return nil, "", errors.Annotate(err, "failed to listen to %q address %q", netType, tcpAddr).Err() } addr := fmt.Sprintf("%s:%s", netType, l.Addr().String()) log.Fields{ "addr": addr, }.Debugf(ctx, "Listening on %q stream server...", netType) return l, addr, nil }, }, nil }
go
func newTCPServerImpl(ctx context.Context, netType, spec string, loopback net.IP) (StreamServer, error) { tcpAddr, err := net.ResolveTCPAddr(netType, spec) if err != nil { return nil, errors.Annotate(err, "could not resolve %q address %q", netType, spec).Err() } if tcpAddr.IP == nil { tcpAddr.IP = loopback } return &listenerStreamServer{ Context: ctx, address: fmt.Sprintf("%s:%s", netType, tcpAddr.String()), gen: func() (net.Listener, string, error) { l, err := net.ListenTCP(netType, tcpAddr) if err != nil { return nil, "", errors.Annotate(err, "failed to listen to %q address %q", netType, tcpAddr).Err() } addr := fmt.Sprintf("%s:%s", netType, l.Addr().String()) log.Fields{ "addr": addr, }.Debugf(ctx, "Listening on %q stream server...", netType) return l, addr, nil }, }, nil }
[ "func", "newTCPServerImpl", "(", "ctx", "context", ".", "Context", ",", "netType", ",", "spec", "string", ",", "loopback", "net", ".", "IP", ")", "(", "StreamServer", ",", "error", ")", "{", "tcpAddr", ",", "err", ":=", "net", ".", "ResolveTCPAddr", "(",...
// Listen implements StreamServer.
[ "Listen", "implements", "StreamServer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/streamserver/tcp.go#L66-L92
8,303
luci/luci-go
dm/appengine/model/attempt.go
MakeAttempt
func MakeAttempt(c context.Context, aid *dm.Attempt_ID) *Attempt { now := clock.Now(c).UTC() return &Attempt{ ID: *aid, Created: now, Modified: now, } }
go
func MakeAttempt(c context.Context, aid *dm.Attempt_ID) *Attempt { now := clock.Now(c).UTC() return &Attempt{ ID: *aid, Created: now, Modified: now, } }
[ "func", "MakeAttempt", "(", "c", "context", ".", "Context", ",", "aid", "*", "dm", ".", "Attempt_ID", ")", "*", "Attempt", "{", "now", ":=", "clock", ".", "Now", "(", "c", ")", ".", "UTC", "(", ")", "\n", "return", "&", "Attempt", "{", "ID", ":",...
// MakeAttempt is a convenience function to create a new Attempt model in // the NeedsExecution state.
[ "MakeAttempt", "is", "a", "convenience", "function", "to", "create", "a", "new", "Attempt", "model", "in", "the", "NeedsExecution", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/attempt.go#L103-L110
8,304
luci/luci-go
dm/appengine/model/attempt.go
ModifyState
func (a *Attempt) ModifyState(c context.Context, newState dm.Attempt_State) error { if a.State == newState { return nil } if err := a.State.Evolve(newState); err != nil { return err } now := clock.Now(c).UTC() if now.After(a.Modified) { a.Modified = now } else { // Microsecond is the smallest granularity that datastore can store // timestamps, so use that to disambiguate: the goal here is that any // modification always increments the modified time, and never decrements // it. a.Modified = a.Modified.Add(time.Microsecond) } return nil }
go
func (a *Attempt) ModifyState(c context.Context, newState dm.Attempt_State) error { if a.State == newState { return nil } if err := a.State.Evolve(newState); err != nil { return err } now := clock.Now(c).UTC() if now.After(a.Modified) { a.Modified = now } else { // Microsecond is the smallest granularity that datastore can store // timestamps, so use that to disambiguate: the goal here is that any // modification always increments the modified time, and never decrements // it. a.Modified = a.Modified.Add(time.Microsecond) } return nil }
[ "func", "(", "a", "*", "Attempt", ")", "ModifyState", "(", "c", "context", ".", "Context", ",", "newState", "dm", ".", "Attempt_State", ")", "error", "{", "if", "a", ".", "State", "==", "newState", "{", "return", "nil", "\n", "}", "\n", "if", "err", ...
// ModifyState changes the current state of this Attempt and updates its // Modified timestamp.
[ "ModifyState", "changes", "the", "current", "state", "of", "this", "Attempt", "and", "updates", "its", "Modified", "timestamp", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/attempt.go#L114-L132
8,305
luci/luci-go
dm/appengine/model/attempt.go
ToProto
func (a *Attempt) ToProto(withData bool) *dm.Attempt { ret := dm.Attempt{Id: &a.ID} if withData { ret.Data = a.DataProto() } return &ret }
go
func (a *Attempt) ToProto(withData bool) *dm.Attempt { ret := dm.Attempt{Id: &a.ID} if withData { ret.Data = a.DataProto() } return &ret }
[ "func", "(", "a", "*", "Attempt", ")", "ToProto", "(", "withData", "bool", ")", "*", "dm", ".", "Attempt", "{", "ret", ":=", "dm", ".", "Attempt", "{", "Id", ":", "&", "a", ".", "ID", "}", "\n", "if", "withData", "{", "ret", ".", "Data", "=", ...
// ToProto returns a dm proto version of this Attempt.
[ "ToProto", "returns", "a", "dm", "proto", "version", "of", "this", "Attempt", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/attempt.go#L135-L141
8,306
luci/luci-go
dm/appengine/model/attempt.go
DataProto
func (a *Attempt) DataProto() (ret *dm.Attempt_Data) { switch a.State { case dm.Attempt_SCHEDULING: ret = dm.NewAttemptScheduling().Data case dm.Attempt_EXECUTING: ret = dm.NewAttemptExecuting(a.CurExecution).Data case dm.Attempt_WAITING: ret = dm.NewAttemptWaiting(a.DepMap.Size() - a.DepMap.CountSet()).Data case dm.Attempt_FINISHED: ret = dm.NewAttemptFinished(a.Result.Data).Data case dm.Attempt_ABNORMAL_FINISHED: ret = dm.NewAttemptAbnormalFinish(a.Result.AbnormalFinish).Data default: panic(fmt.Errorf("unknown Attempt_State: %s", a.State)) } ret.Created = google_pb.NewTimestamp(a.Created) ret.Modified = google_pb.NewTimestamp(a.Modified) ret.NumExecutions = a.CurExecution return ret }
go
func (a *Attempt) DataProto() (ret *dm.Attempt_Data) { switch a.State { case dm.Attempt_SCHEDULING: ret = dm.NewAttemptScheduling().Data case dm.Attempt_EXECUTING: ret = dm.NewAttemptExecuting(a.CurExecution).Data case dm.Attempt_WAITING: ret = dm.NewAttemptWaiting(a.DepMap.Size() - a.DepMap.CountSet()).Data case dm.Attempt_FINISHED: ret = dm.NewAttemptFinished(a.Result.Data).Data case dm.Attempt_ABNORMAL_FINISHED: ret = dm.NewAttemptAbnormalFinish(a.Result.AbnormalFinish).Data default: panic(fmt.Errorf("unknown Attempt_State: %s", a.State)) } ret.Created = google_pb.NewTimestamp(a.Created) ret.Modified = google_pb.NewTimestamp(a.Modified) ret.NumExecutions = a.CurExecution return ret }
[ "func", "(", "a", "*", "Attempt", ")", "DataProto", "(", ")", "(", "ret", "*", "dm", ".", "Attempt_Data", ")", "{", "switch", "a", ".", "State", "{", "case", "dm", ".", "Attempt_SCHEDULING", ":", "ret", "=", "dm", ".", "NewAttemptScheduling", "(", ")...
// DataProto returns an Attempt.Data message for this Attempt.
[ "DataProto", "returns", "an", "Attempt", ".", "Data", "message", "for", "this", "Attempt", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/attempt.go#L144-L163
8,307
luci/luci-go
logdog/client/coordinator/stream.go
State
func (s *Stream) State(ctx context.Context) (*LogStream, error) { req := logdog.GetRequest{ Project: string(s.project), Path: string(s.path), State: true, LogCount: -1, // Don't fetch any logs. } resp, err := s.c.C.Get(ctx, &req) if err != nil { return nil, normalizeError(err) } path := types.StreamPath(req.Path) if desc := resp.Desc; desc != nil { path = desc.Path() } return loadLogStream(resp.Project, path, resp.State, resp.Desc), nil }
go
func (s *Stream) State(ctx context.Context) (*LogStream, error) { req := logdog.GetRequest{ Project: string(s.project), Path: string(s.path), State: true, LogCount: -1, // Don't fetch any logs. } resp, err := s.c.C.Get(ctx, &req) if err != nil { return nil, normalizeError(err) } path := types.StreamPath(req.Path) if desc := resp.Desc; desc != nil { path = desc.Path() } return loadLogStream(resp.Project, path, resp.State, resp.Desc), nil }
[ "func", "(", "s", "*", "Stream", ")", "State", "(", "ctx", "context", ".", "Context", ")", "(", "*", "LogStream", ",", "error", ")", "{", "req", ":=", "logdog", ".", "GetRequest", "{", "Project", ":", "string", "(", "s", ".", "project", ")", ",", ...
// State fetches the LogStreamDescriptor for a given log stream.
[ "State", "fetches", "the", "LogStreamDescriptor", "for", "a", "given", "log", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/coordinator/stream.go#L116-L135
8,308
luci/luci-go
logdog/client/coordinator/stream.go
Get
func (s *Stream) Get(ctx context.Context, params ...GetParam) ([]*logpb.LogEntry, error) { p := getParamsInst{ r: logdog.GetRequest{ Project: string(s.project), Path: string(s.path), }, } for _, param := range params { param.applyGet(&p) } if p.stateP != nil { p.r.State = true } resp, err := s.c.C.Get(ctx, &p.r) if err != nil { return nil, normalizeError(err) } if err := loadStatePointer(p.stateP, resp); err != nil { return nil, err } return resp.Logs, nil }
go
func (s *Stream) Get(ctx context.Context, params ...GetParam) ([]*logpb.LogEntry, error) { p := getParamsInst{ r: logdog.GetRequest{ Project: string(s.project), Path: string(s.path), }, } for _, param := range params { param.applyGet(&p) } if p.stateP != nil { p.r.State = true } resp, err := s.c.C.Get(ctx, &p.r) if err != nil { return nil, normalizeError(err) } if err := loadStatePointer(p.stateP, resp); err != nil { return nil, err } return resp.Logs, nil }
[ "func", "(", "s", "*", "Stream", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "params", "...", "GetParam", ")", "(", "[", "]", "*", "logpb", ".", "LogEntry", ",", "error", ")", "{", "p", ":=", "getParamsInst", "{", "r", ":", "logdog", ...
// Get retrieves log stream entries from the Coordinator. The supplied // parameters shape which entries are requested and what information is // returned.
[ "Get", "retrieves", "log", "stream", "entries", "from", "the", "Coordinator", ".", "The", "supplied", "parameters", "shape", "which", "entries", "are", "requested", "and", "what", "information", "is", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/coordinator/stream.go#L140-L163
8,309
luci/luci-go
logdog/client/coordinator/stream.go
Tail
func (s *Stream) Tail(ctx context.Context, params ...TailParam) (*logpb.LogEntry, error) { p := tailParamsInst{ r: logdog.TailRequest{ Project: string(s.project), Path: string(s.path), }, } for _, param := range params { param.applyTail(&p) } resp, err := s.c.C.Tail(ctx, &p.r) if err != nil { return nil, normalizeError(err) } if err := loadStatePointer(p.stateP, resp); err != nil { return nil, err } switch len(resp.Logs) { case 0: return nil, nil case 1: le := resp.Logs[0] if p.complete { if dg := le.GetDatagram(); dg != nil && dg.Partial != nil { // This is a partial; datagram. Fetch and assemble the full datagram. return s.fetchFullDatagram(ctx, le, true) } } return le, nil default: return nil, fmt.Errorf("tail call returned %d logs", len(resp.Logs)) } }
go
func (s *Stream) Tail(ctx context.Context, params ...TailParam) (*logpb.LogEntry, error) { p := tailParamsInst{ r: logdog.TailRequest{ Project: string(s.project), Path: string(s.path), }, } for _, param := range params { param.applyTail(&p) } resp, err := s.c.C.Tail(ctx, &p.r) if err != nil { return nil, normalizeError(err) } if err := loadStatePointer(p.stateP, resp); err != nil { return nil, err } switch len(resp.Logs) { case 0: return nil, nil case 1: le := resp.Logs[0] if p.complete { if dg := le.GetDatagram(); dg != nil && dg.Partial != nil { // This is a partial; datagram. Fetch and assemble the full datagram. return s.fetchFullDatagram(ctx, le, true) } } return le, nil default: return nil, fmt.Errorf("tail call returned %d logs", len(resp.Logs)) } }
[ "func", "(", "s", "*", "Stream", ")", "Tail", "(", "ctx", "context", ".", "Context", ",", "params", "...", "TailParam", ")", "(", "*", "logpb", ".", "LogEntry", ",", "error", ")", "{", "p", ":=", "tailParamsInst", "{", "r", ":", "logdog", ".", "Tai...
// Tail performs a tail call, returning the last log entry in the stream. If // stateP is not nil, the stream's state will be requested and loaded into the // variable.
[ "Tail", "performs", "a", "tail", "call", "returning", "the", "last", "log", "entry", "in", "the", "stream", ".", "If", "stateP", "is", "not", "nil", "the", "stream", "s", "state", "will", "be", "requested", "and", "loaded", "into", "the", "variable", "."...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/coordinator/stream.go#L168-L204
8,310
luci/luci-go
machine-db/appengine/model/vlans.go
fetch
func (t *VLANsTable) fetch(c context.Context) error { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT id, alias, state, cidr_block FROM vlans `) if err != nil { return errors.Annotate(err, "failed to select VLANs").Err() } defer rows.Close() for rows.Next() { vlan := &VLAN{} if err := rows.Scan(&vlan.Id, &vlan.Alias, &vlan.State, &vlan.CidrBlock); err != nil { return errors.Annotate(err, "failed to scan VLAN").Err() } t.current = append(t.current, vlan) } return nil }
go
func (t *VLANsTable) fetch(c context.Context) error { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT id, alias, state, cidr_block FROM vlans `) if err != nil { return errors.Annotate(err, "failed to select VLANs").Err() } defer rows.Close() for rows.Next() { vlan := &VLAN{} if err := rows.Scan(&vlan.Id, &vlan.Alias, &vlan.State, &vlan.CidrBlock); err != nil { return errors.Annotate(err, "failed to scan VLAN").Err() } t.current = append(t.current, vlan) } return nil }
[ "func", "(", "t", "*", "VLANsTable", ")", "fetch", "(", "c", "context", ".", "Context", ")", "error", "{", "db", ":=", "database", ".", "Get", "(", "c", ")", "\n", "rows", ",", "err", ":=", "db", ".", "QueryContext", "(", "c", ",", "`\n\t\tSELECT i...
// fetch fetches the VLANs from the database.
[ "fetch", "fetches", "the", "VLANs", "from", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/vlans.go#L46-L64
8,311
luci/luci-go
machine-db/appengine/model/vlans.go
computeChanges
func (t *VLANsTable) computeChanges(c context.Context, vlans []*config.VLAN) { cfgs := make(map[int64]*VLAN, len(vlans)) for _, cfg := range vlans { cfgs[cfg.Id] = &VLAN{ VLAN: config.VLAN{ Id: cfg.Id, Alias: cfg.Alias, State: cfg.State, CidrBlock: cfg.CidrBlock, }, } } for _, vlan := range t.current { if cfg, ok := cfgs[vlan.Id]; ok { // VLAN found in the config. if t.needsUpdate(vlan, cfg) { // VLAN doesn't match the config. t.updates = append(t.updates, cfg) } // Record that the VLAN config has been seen. delete(cfgs, cfg.Id) } else { // VLAN not found in the config. t.removals = append(t.removals, vlan) } } // VLANs remaining in the map are present in the config but not the database. // Iterate deterministically over the slice to determine which VLANs need to be added. for _, cfg := range vlans { if p, ok := cfgs[cfg.Id]; ok { t.additions = append(t.additions, p) } } }
go
func (t *VLANsTable) computeChanges(c context.Context, vlans []*config.VLAN) { cfgs := make(map[int64]*VLAN, len(vlans)) for _, cfg := range vlans { cfgs[cfg.Id] = &VLAN{ VLAN: config.VLAN{ Id: cfg.Id, Alias: cfg.Alias, State: cfg.State, CidrBlock: cfg.CidrBlock, }, } } for _, vlan := range t.current { if cfg, ok := cfgs[vlan.Id]; ok { // VLAN found in the config. if t.needsUpdate(vlan, cfg) { // VLAN doesn't match the config. t.updates = append(t.updates, cfg) } // Record that the VLAN config has been seen. delete(cfgs, cfg.Id) } else { // VLAN not found in the config. t.removals = append(t.removals, vlan) } } // VLANs remaining in the map are present in the config but not the database. // Iterate deterministically over the slice to determine which VLANs need to be added. for _, cfg := range vlans { if p, ok := cfgs[cfg.Id]; ok { t.additions = append(t.additions, p) } } }
[ "func", "(", "t", "*", "VLANsTable", ")", "computeChanges", "(", "c", "context", ".", "Context", ",", "vlans", "[", "]", "*", "config", ".", "VLAN", ")", "{", "cfgs", ":=", "make", "(", "map", "[", "int64", "]", "*", "VLAN", ",", "len", "(", "vla...
// computeChanges computes the changes that need to be made to the VLANs in the database.
[ "computeChanges", "computes", "the", "changes", "that", "need", "to", "be", "made", "to", "the", "VLANs", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/vlans.go#L72-L107
8,312
luci/luci-go
machine-db/appengine/model/vlans.go
add
func (t *VLANsTable) add(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.additions) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` INSERT INTO vlans (id, alias, state, cidr_block) VALUES (?, ?, ?, ?) `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Add each VLAN to the database, and update the slice of VLANs with each addition. for len(t.additions) > 0 { vlan := t.additions[0] _, err := stmt.ExecContext(c, vlan.Id, vlan.Alias, vlan.State, vlan.CidrBlock) if err != nil { return errors.Annotate(err, "failed to add VLAN %d", vlan.Id).Err() } t.current = append(t.current, vlan) t.additions = t.additions[1:] logging.Infof(c, "Added VLAN %d", vlan.Id) } return nil }
go
func (t *VLANsTable) add(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.additions) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` INSERT INTO vlans (id, alias, state, cidr_block) VALUES (?, ?, ?, ?) `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Add each VLAN to the database, and update the slice of VLANs with each addition. for len(t.additions) > 0 { vlan := t.additions[0] _, err := stmt.ExecContext(c, vlan.Id, vlan.Alias, vlan.State, vlan.CidrBlock) if err != nil { return errors.Annotate(err, "failed to add VLAN %d", vlan.Id).Err() } t.current = append(t.current, vlan) t.additions = t.additions[1:] logging.Infof(c, "Added VLAN %d", vlan.Id) } return nil }
[ "func", "(", "t", "*", "VLANsTable", ")", "add", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "additions", ")", "==", "0", "{", "return", "nil", ...
// add adds all VLANs pending addition to the database, clearing pending additions. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "add", "adds", "all", "VLANs", "pending", "addition", "to", "the", "database", "clearing", "pending", "additions", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called", "again", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/vlans.go#L111-L139
8,313
luci/luci-go
machine-db/appengine/model/vlans.go
remove
func (t *VLANsTable) remove(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.removals) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` DELETE FROM vlans WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Remove each VLAN from the table. It's more efficient to update the slice of // VLANs once at the end rather than for each removal, so use a defer. removed := make(map[int64]struct{}, len(t.removals)) defer func() { var vlans []*VLAN for _, vlan := range t.current { if _, ok := removed[vlan.Id]; !ok { vlans = append(vlans, vlan) } } t.current = vlans }() for len(t.removals) > 0 { vlan := t.removals[0] if _, err := stmt.ExecContext(c, vlan.Id); err != nil { // Defer ensures the slice of VLANs is updated even if we exit early. return errors.Annotate(err, "failed to remove VLAN %d", vlan.Id).Err() } removed[vlan.Id] = struct{}{} t.removals = t.removals[1:] logging.Infof(c, "Removed VLAN %d", vlan.Id) } return nil }
go
func (t *VLANsTable) remove(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.removals) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` DELETE FROM vlans WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Remove each VLAN from the table. It's more efficient to update the slice of // VLANs once at the end rather than for each removal, so use a defer. removed := make(map[int64]struct{}, len(t.removals)) defer func() { var vlans []*VLAN for _, vlan := range t.current { if _, ok := removed[vlan.Id]; !ok { vlans = append(vlans, vlan) } } t.current = vlans }() for len(t.removals) > 0 { vlan := t.removals[0] if _, err := stmt.ExecContext(c, vlan.Id); err != nil { // Defer ensures the slice of VLANs is updated even if we exit early. return errors.Annotate(err, "failed to remove VLAN %d", vlan.Id).Err() } removed[vlan.Id] = struct{}{} t.removals = t.removals[1:] logging.Infof(c, "Removed VLAN %d", vlan.Id) } return nil }
[ "func", "(", "t", "*", "VLANsTable", ")", "remove", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "removals", ")", "==", "0", "{", "return", "nil",...
// remove removes all VLANs pending removal from the database, clearing pending removals. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "remove", "removes", "all", "VLANs", "pending", "removal", "from", "the", "database", "clearing", "pending", "removals", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called", "ag...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/vlans.go#L143-L182
8,314
luci/luci-go
machine-db/appengine/model/vlans.go
update
func (t *VLANsTable) update(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.updates) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` UPDATE vlans SET alias = ?, state = ?, cidr_block = ? WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Update each VLAN in the table. It's more efficient to update the slice of // VLANs once at the end rather than for each update, so use a defer. updated := make(map[int64]*VLAN, len(t.updates)) defer func() { for _, vlan := range t.current { if u, ok := updated[vlan.Id]; ok { vlan.Alias = u.Alias vlan.State = u.State vlan.CidrBlock = u.CidrBlock } } }() for len(t.updates) > 0 { vlan := t.updates[0] if _, err := stmt.ExecContext(c, vlan.Alias, vlan.State, vlan.CidrBlock, vlan.Id); err != nil { return errors.Annotate(err, "failed to update VLAN %d", vlan.Id).Err() } updated[vlan.Id] = vlan t.updates = t.updates[1:] logging.Infof(c, "Updated VLAN %d", vlan.Id) } return nil }
go
func (t *VLANsTable) update(c context.Context) error { // Avoid using the database connection to prepare unnecessary statements. if len(t.updates) == 0 { return nil } db := database.Get(c) stmt, err := db.PrepareContext(c, ` UPDATE vlans SET alias = ?, state = ?, cidr_block = ? WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Update each VLAN in the table. It's more efficient to update the slice of // VLANs once at the end rather than for each update, so use a defer. updated := make(map[int64]*VLAN, len(t.updates)) defer func() { for _, vlan := range t.current { if u, ok := updated[vlan.Id]; ok { vlan.Alias = u.Alias vlan.State = u.State vlan.CidrBlock = u.CidrBlock } } }() for len(t.updates) > 0 { vlan := t.updates[0] if _, err := stmt.ExecContext(c, vlan.Alias, vlan.State, vlan.CidrBlock, vlan.Id); err != nil { return errors.Annotate(err, "failed to update VLAN %d", vlan.Id).Err() } updated[vlan.Id] = vlan t.updates = t.updates[1:] logging.Infof(c, "Updated VLAN %d", vlan.Id) } return nil }
[ "func", "(", "t", "*", "VLANsTable", ")", "update", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "updates", ")", "==", "0", "{", "return", "nil", ...
// update updates all VLANs pending update in the database, clearing pending updates. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "update", "updates", "all", "VLANs", "pending", "update", "in", "the", "database", "clearing", "pending", "updates", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called", "again"...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/vlans.go#L186-L225
8,315
luci/luci-go
machine-db/appengine/model/vlans.go
EnsureVLANs
func EnsureVLANs(c context.Context, cfgs []*config.VLAN) error { t := &VLANsTable{} if err := t.fetch(c); err != nil { return errors.Annotate(err, "failed to fetch VLANs").Err() } t.computeChanges(c, cfgs) if err := t.add(c); err != nil { return errors.Annotate(err, "failed to add VLANs").Err() } if err := t.remove(c); err != nil { return errors.Annotate(err, "failed to remove VLANs").Err() } if err := t.update(c); err != nil { return errors.Annotate(err, "failed to update VLANs").Err() } return nil }
go
func EnsureVLANs(c context.Context, cfgs []*config.VLAN) error { t := &VLANsTable{} if err := t.fetch(c); err != nil { return errors.Annotate(err, "failed to fetch VLANs").Err() } t.computeChanges(c, cfgs) if err := t.add(c); err != nil { return errors.Annotate(err, "failed to add VLANs").Err() } if err := t.remove(c); err != nil { return errors.Annotate(err, "failed to remove VLANs").Err() } if err := t.update(c); err != nil { return errors.Annotate(err, "failed to update VLANs").Err() } return nil }
[ "func", "EnsureVLANs", "(", "c", "context", ".", "Context", ",", "cfgs", "[", "]", "*", "config", ".", "VLAN", ")", "error", "{", "t", ":=", "&", "VLANsTable", "{", "}", "\n", "if", "err", ":=", "t", ".", "fetch", "(", "c", ")", ";", "err", "!=...
// EnsureVLANs ensures the database contains exactly the given VLANs.
[ "EnsureVLANs", "ensures", "the", "database", "contains", "exactly", "the", "given", "VLANs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/vlans.go#L228-L244
8,316
luci/luci-go
lucicfg/normalize/milo.go
Milo
func Milo(c context.Context, cfg *pb.Project) error { // Sort consoles by ID. sort.Slice(cfg.Consoles, func(i, j int) bool { return cfg.Consoles[i].Id < cfg.Consoles[j].Id }) // Inline headers. headers := make(map[string]*pb.Header) for _, h := range cfg.Headers { headers[h.Id] = h h.Id = "" } for _, c := range cfg.Consoles { switch { case c.HeaderId == "": continue case c.Header != nil: return fmt.Errorf("bad console %q - has both 'header' and 'header_id' fields", c.Id) default: c.Header = headers[c.HeaderId] c.HeaderId = "" } } cfg.Headers = nil // Normalize and sort refs. for _, c := range cfg.Consoles { for i, r := range c.Refs { if !strings.HasPrefix(r, "regexp:") { c.Refs[i] = "regexp:" + regexp.QuoteMeta(r) } } sort.Strings(c.Refs) } // Sort alternative builder names, but not builders themselves! Their order is // significant for Milo UI. for _, c := range cfg.Consoles { for _, b := range c.Builders { sort.Strings(b.Name) } } return nil }
go
func Milo(c context.Context, cfg *pb.Project) error { // Sort consoles by ID. sort.Slice(cfg.Consoles, func(i, j int) bool { return cfg.Consoles[i].Id < cfg.Consoles[j].Id }) // Inline headers. headers := make(map[string]*pb.Header) for _, h := range cfg.Headers { headers[h.Id] = h h.Id = "" } for _, c := range cfg.Consoles { switch { case c.HeaderId == "": continue case c.Header != nil: return fmt.Errorf("bad console %q - has both 'header' and 'header_id' fields", c.Id) default: c.Header = headers[c.HeaderId] c.HeaderId = "" } } cfg.Headers = nil // Normalize and sort refs. for _, c := range cfg.Consoles { for i, r := range c.Refs { if !strings.HasPrefix(r, "regexp:") { c.Refs[i] = "regexp:" + regexp.QuoteMeta(r) } } sort.Strings(c.Refs) } // Sort alternative builder names, but not builders themselves! Their order is // significant for Milo UI. for _, c := range cfg.Consoles { for _, b := range c.Builders { sort.Strings(b.Name) } } return nil }
[ "func", "Milo", "(", "c", "context", ".", "Context", ",", "cfg", "*", "pb", ".", "Project", ")", "error", "{", "// Sort consoles by ID.", "sort", ".", "Slice", "(", "cfg", ".", "Consoles", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "...
// Milo normalizes luci-milo.cfg config.
[ "Milo", "normalizes", "luci", "-", "milo", ".", "cfg", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/normalize/milo.go#L28-L72
8,317
luci/luci-go
milo/frontend/view_search.go
searchXMLHandler
func searchXMLHandler(c *router.Context) { c.Writer.Header().Set("Content-Type", "application/opensearchdescription+xml") c.Writer.WriteHeader(http.StatusOK) fmt.Fprintf(c.Writer, openSearchXML, c.Request.URL.Host) }
go
func searchXMLHandler(c *router.Context) { c.Writer.Header().Set("Content-Type", "application/opensearchdescription+xml") c.Writer.WriteHeader(http.StatusOK) fmt.Fprintf(c.Writer, openSearchXML, c.Request.URL.Host) }
[ "func", "searchXMLHandler", "(", "c", "*", "router", ".", "Context", ")", "{", "c", ".", "Writer", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Writer", ".", "WriteHeader", "(", "http", ".", "Status...
// searchXMLHandler returns the opensearch document for this domain.
[ "searchXMLHandler", "returns", "the", "opensearch", "document", "for", "this", "domain", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_search.go#L74-L78
8,318
luci/luci-go
tokenserver/appengine/impl/utils/identityset/identityset.go
AddIdentity
func (s *Set) AddIdentity(id identity.Identity) { if !s.All { if s.IDs == nil { s.IDs = make(identSet, 1) } s.IDs[id] = struct{}{} } }
go
func (s *Set) AddIdentity(id identity.Identity) { if !s.All { if s.IDs == nil { s.IDs = make(identSet, 1) } s.IDs[id] = struct{}{} } }
[ "func", "(", "s", "*", "Set", ")", "AddIdentity", "(", "id", "identity", ".", "Identity", ")", "{", "if", "!", "s", ".", "All", "{", "if", "s", ".", "IDs", "==", "nil", "{", "s", ".", "IDs", "=", "make", "(", "identSet", ",", "1", ")", "\n", ...
// AddIdentity adds a single identity to the set. // // The receiver must not be nil.
[ "AddIdentity", "adds", "a", "single", "identity", "to", "the", "set", ".", "The", "receiver", "must", "not", "be", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/identityset/identityset.go#L46-L53
8,319
luci/luci-go
tokenserver/appengine/impl/utils/identityset/identityset.go
AddGroup
func (s *Set) AddGroup(group string) { if !s.All { if s.Groups == nil { s.Groups = make(groupSet, 1) } s.Groups[group] = struct{}{} } }
go
func (s *Set) AddGroup(group string) { if !s.All { if s.Groups == nil { s.Groups = make(groupSet, 1) } s.Groups[group] = struct{}{} } }
[ "func", "(", "s", "*", "Set", ")", "AddGroup", "(", "group", "string", ")", "{", "if", "!", "s", ".", "All", "{", "if", "s", ".", "Groups", "==", "nil", "{", "s", ".", "Groups", "=", "make", "(", "groupSet", ",", "1", ")", "\n", "}", "\n", ...
// AddGroup adds a single group to the set. // // The receiver must not be nil.
[ "AddGroup", "adds", "a", "single", "group", "to", "the", "set", ".", "The", "receiver", "must", "not", "be", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/identityset/identityset.go#L58-L65
8,320
luci/luci-go
tokenserver/appengine/impl/utils/identityset/identityset.go
IsEmpty
func (s *Set) IsEmpty() bool { return s == nil || (!s.All && len(s.IDs) == 0 && len(s.Groups) == 0) }
go
func (s *Set) IsEmpty() bool { return s == nil || (!s.All && len(s.IDs) == 0 && len(s.Groups) == 0) }
[ "func", "(", "s", "*", "Set", ")", "IsEmpty", "(", ")", "bool", "{", "return", "s", "==", "nil", "||", "(", "!", "s", ".", "All", "&&", "len", "(", "s", ".", "IDs", ")", "==", "0", "&&", "len", "(", "s", ".", "Groups", ")", "==", "0", ")"...
// IsEmpty returns true if this set is empty. // // 'nil' receiver value is valid and represents an empty set.
[ "IsEmpty", "returns", "true", "if", "this", "set", "is", "empty", ".", "nil", "receiver", "value", "is", "valid", "and", "represents", "an", "empty", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/identityset/identityset.go#L70-L72
8,321
luci/luci-go
tokenserver/appengine/impl/utils/identityset/identityset.go
IsMember
func (s *Set) IsMember(c context.Context, id identity.Identity) (bool, error) { if s == nil { return false, nil } if s.All { return true, nil } if _, ok := s.IDs[id]; ok { return true, nil } if len(s.Groups) != 0 { groups := make([]string, 0, len(s.Groups)) for gr := range s.Groups { groups = append(groups, gr) } return auth.GetState(c).DB().IsMember(c, id, groups) } return false, nil }
go
func (s *Set) IsMember(c context.Context, id identity.Identity) (bool, error) { if s == nil { return false, nil } if s.All { return true, nil } if _, ok := s.IDs[id]; ok { return true, nil } if len(s.Groups) != 0 { groups := make([]string, 0, len(s.Groups)) for gr := range s.Groups { groups = append(groups, gr) } return auth.GetState(c).DB().IsMember(c, id, groups) } return false, nil }
[ "func", "(", "s", "*", "Set", ")", "IsMember", "(", "c", "context", ".", "Context", ",", "id", "identity", ".", "Identity", ")", "(", "bool", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", ...
// IsMember returns true if the given identity is in the set. // // It looks inside the groups too. // // 'nil' receiver value is valid and represents an empty set.
[ "IsMember", "returns", "true", "if", "the", "given", "identity", "is", "in", "the", "set", ".", "It", "looks", "inside", "the", "groups", "too", ".", "nil", "receiver", "value", "is", "valid", "and", "represents", "an", "empty", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/identityset/identityset.go#L79-L101
8,322
luci/luci-go
tokenserver/appengine/impl/utils/identityset/identityset.go
IsSubset
func (s *Set) IsSubset(superset *Set) bool { // An empty set is subset of any other set (including empty sets). if s.IsEmpty() { return true } // An empty set is not a superset of any non-empty set. if superset.IsEmpty() { return false } // The universal set is subset of only itself. if s.All { return superset.All } // The universal set is superset of any other set. if superset.All { return true } // Is s.IDs a subset of superset.IDs? if len(superset.IDs) < len(s.IDs) { return false } for id := range s.IDs { if _, ok := superset.IDs[id]; !ok { return false } } // Is s.Groups a subset of superset.Groups? if len(superset.Groups) < len(s.Groups) { return false } for group := range s.Groups { if _, ok := superset.Groups[group]; !ok { return false } } return true }
go
func (s *Set) IsSubset(superset *Set) bool { // An empty set is subset of any other set (including empty sets). if s.IsEmpty() { return true } // An empty set is not a superset of any non-empty set. if superset.IsEmpty() { return false } // The universal set is subset of only itself. if s.All { return superset.All } // The universal set is superset of any other set. if superset.All { return true } // Is s.IDs a subset of superset.IDs? if len(superset.IDs) < len(s.IDs) { return false } for id := range s.IDs { if _, ok := superset.IDs[id]; !ok { return false } } // Is s.Groups a subset of superset.Groups? if len(superset.Groups) < len(s.Groups) { return false } for group := range s.Groups { if _, ok := superset.Groups[group]; !ok { return false } } return true }
[ "func", "(", "s", "*", "Set", ")", "IsSubset", "(", "superset", "*", "Set", ")", "bool", "{", "// An empty set is subset of any other set (including empty sets).", "if", "s", ".", "IsEmpty", "(", ")", "{", "return", "true", "\n", "}", "\n\n", "// An empty set is...
// IsSubset returns true if this set if a subset of another set. // // Two equal sets are considered subsets of each other. // // It doesn't attempt to expand groups. Compares IDs and Groups sets separately, // as independent kinds of entities. // // 'nil' receiver and argument values are valid and represent empty sets.
[ "IsSubset", "returns", "true", "if", "this", "set", "if", "a", "subset", "of", "another", "set", ".", "Two", "equal", "sets", "are", "considered", "subsets", "of", "each", "other", ".", "It", "doesn", "t", "attempt", "to", "expand", "groups", ".", "Compa...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/identityset/identityset.go#L111-L153
8,323
luci/luci-go
tokenserver/appengine/impl/utils/identityset/identityset.go
ToStrings
func (s *Set) ToStrings() []string { if s.IsEmpty() { return nil } if s.All { return []string{"*"} } out := make([]string, 0, len(s.IDs)+len(s.Groups)) for ident := range s.IDs { out = append(out, string(ident)) } for group := range s.Groups { out = append(out, "group:"+group) } sort.Strings(out) return out }
go
func (s *Set) ToStrings() []string { if s.IsEmpty() { return nil } if s.All { return []string{"*"} } out := make([]string, 0, len(s.IDs)+len(s.Groups)) for ident := range s.IDs { out = append(out, string(ident)) } for group := range s.Groups { out = append(out, "group:"+group) } sort.Strings(out) return out }
[ "func", "(", "s", "*", "Set", ")", "ToStrings", "(", ")", "[", "]", "string", "{", "if", "s", ".", "IsEmpty", "(", ")", "{", "return", "nil", "\n", "}", "\n", "if", "s", ".", "All", "{", "return", "[", "]", "string", "{", "\"", "\"", "}", "...
// ToStrings returns a sorted list of strings representing this set. // // See 'FromStrings' for the format of this list.
[ "ToStrings", "returns", "a", "sorted", "list", "of", "strings", "representing", "this", "set", ".", "See", "FromStrings", "for", "the", "format", "of", "this", "list", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/identityset/identityset.go#L167-L183
8,324
luci/luci-go
tokenserver/appengine/impl/utils/identityset/identityset.go
Union
func Union(sets ...*Set) *Set { estimateIDs := 0 estimateGroups := 0 for _, s := range sets { if s == nil { continue } if s.All { return &Set{All: true} } if len(s.IDs) > estimateIDs { estimateIDs = len(s.IDs) } if len(s.Groups) > estimateGroups { estimateGroups = len(s.Groups) } } union := &Set{} if estimateIDs != 0 { union.IDs = make(identSet, estimateIDs) } if estimateGroups != 0 { union.Groups = make(groupSet, estimateGroups) } for _, s := range sets { if s == nil { continue } for ident := range s.IDs { union.IDs[ident] = struct{}{} } for group := range s.Groups { union.Groups[group] = struct{}{} } } return union }
go
func Union(sets ...*Set) *Set { estimateIDs := 0 estimateGroups := 0 for _, s := range sets { if s == nil { continue } if s.All { return &Set{All: true} } if len(s.IDs) > estimateIDs { estimateIDs = len(s.IDs) } if len(s.Groups) > estimateGroups { estimateGroups = len(s.Groups) } } union := &Set{} if estimateIDs != 0 { union.IDs = make(identSet, estimateIDs) } if estimateGroups != 0 { union.Groups = make(groupSet, estimateGroups) } for _, s := range sets { if s == nil { continue } for ident := range s.IDs { union.IDs[ident] = struct{}{} } for group := range s.Groups { union.Groups[group] = struct{}{} } } return union }
[ "func", "Union", "(", "sets", "...", "*", "Set", ")", "*", "Set", "{", "estimateIDs", ":=", "0", "\n", "estimateGroups", ":=", "0", "\n\n", "for", "_", ",", "s", ":=", "range", "sets", "{", "if", "s", "==", "nil", "{", "continue", "\n", "}", "\n"...
// Union returns a union of a list of sets.
[ "Union", "returns", "a", "union", "of", "a", "list", "of", "sets", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/identityset/identityset.go#L225-L265
8,325
luci/luci-go
buildbucket/cmd/run_annotations/main.go
check
func check(err error) { if err == nil { return } buildMU.Lock() defer buildMU.Unlock() build.Status = pb.Status_INFRA_FAILURE build.SummaryMarkdown = fmt.Sprintf("run_annotations failure: `%s`", err) client.WriteBuild(build) fmt.Fprintln(os.Stderr, err) os.Exit(1) }
go
func check(err error) { if err == nil { return } buildMU.Lock() defer buildMU.Unlock() build.Status = pb.Status_INFRA_FAILURE build.SummaryMarkdown = fmt.Sprintf("run_annotations failure: `%s`", err) client.WriteBuild(build) fmt.Fprintln(os.Stderr, err) os.Exit(1) }
[ "func", "check", "(", "err", "error", ")", "{", "if", "err", "==", "nil", "{", "return", "\n", "}", "\n\n", "buildMU", ".", "Lock", "(", ")", "\n", "defer", "buildMU", ".", "Unlock", "(", ")", "\n", "build", ".", "Status", "=", "pb", ".", "Status...
// check marks the build as INFRA_FAILURE and exits with code 1 if err is not nil.
[ "check", "marks", "the", "build", "as", "INFRA_FAILURE", "and", "exits", "with", "code", "1", "if", "err", "is", "not", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cmd/run_annotations/main.go#L46-L58
8,326
luci/luci-go
buildbucket/cmd/run_annotations/main.go
sendAnnotations
func sendAnnotations(ctx context.Context, ann *milo.Step) error { fullPrefix := fmt.Sprintf("%s/%s", client.Logdog.Prefix, client.Logdog.Namespace) steps, err := deprecated.ConvertBuildSteps(ctx, ann.Substep, client.Logdog.CoordinatorHost, fullPrefix) if err != nil { return errors.Annotate(err, "failed to extra steps from annotations").Err() } props, err := milo.ExtractProperties(ann) if err != nil { return errors.Annotate(err, "failed to extract properties from annotations").Err() } buildMU.Lock() defer buildMU.Unlock() build.Steps = steps build.Output.Properties = props return errors.Annotate(client.WriteBuild(build), "failed to write build message").Err() }
go
func sendAnnotations(ctx context.Context, ann *milo.Step) error { fullPrefix := fmt.Sprintf("%s/%s", client.Logdog.Prefix, client.Logdog.Namespace) steps, err := deprecated.ConvertBuildSteps(ctx, ann.Substep, client.Logdog.CoordinatorHost, fullPrefix) if err != nil { return errors.Annotate(err, "failed to extra steps from annotations").Err() } props, err := milo.ExtractProperties(ann) if err != nil { return errors.Annotate(err, "failed to extract properties from annotations").Err() } buildMU.Lock() defer buildMU.Unlock() build.Steps = steps build.Output.Properties = props return errors.Annotate(client.WriteBuild(build), "failed to write build message").Err() }
[ "func", "sendAnnotations", "(", "ctx", "context", ".", "Context", ",", "ann", "*", "milo", ".", "Step", ")", "error", "{", "fullPrefix", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "client", ".", "Logdog", ".", "Prefix", ",", "client", ".", "L...
// sendAnnotations parses steps and properties from ann, updates build and sends // to the caller.
[ "sendAnnotations", "parses", "steps", "and", "properties", "from", "ann", "updates", "build", "and", "sends", "to", "the", "caller", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cmd/run_annotations/main.go#L62-L79
8,327
luci/luci-go
machine-db/appengine/rpc/switches.go
ListSwitches
func (*Service) ListSwitches(c context.Context, req *crimson.ListSwitchesRequest) (*crimson.ListSwitchesResponse, error) { switches, err := listSwitches(c, stringset.NewFromSlice(req.Names...), stringset.NewFromSlice(req.Racks...), stringset.NewFromSlice(req.Datacenters...)) if err != nil { return nil, err } return &crimson.ListSwitchesResponse{ Switches: switches, }, nil }
go
func (*Service) ListSwitches(c context.Context, req *crimson.ListSwitchesRequest) (*crimson.ListSwitchesResponse, error) { switches, err := listSwitches(c, stringset.NewFromSlice(req.Names...), stringset.NewFromSlice(req.Racks...), stringset.NewFromSlice(req.Datacenters...)) if err != nil { return nil, err } return &crimson.ListSwitchesResponse{ Switches: switches, }, nil }
[ "func", "(", "*", "Service", ")", "ListSwitches", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "ListSwitchesRequest", ")", "(", "*", "crimson", ".", "ListSwitchesResponse", ",", "error", ")", "{", "switches", ",", "err", ":=", "l...
// ListSwitches handles a request to retrieve switches.
[ "ListSwitches", "handles", "a", "request", "to", "retrieve", "switches", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/switches.go#L28-L36
8,328
luci/luci-go
machine-db/appengine/rpc/switches.go
listSwitches
func listSwitches(c context.Context, names, racks, datacenters stringset.Set) ([]*crimson.Switch, error) { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT s.name, s.description, s.ports, s.state, r.name, d.name FROM switches s, racks r, datacenters d WHERE s.rack_id = r.id AND r.datacenter_id = d.id `) if err != nil { return nil, errors.Annotate(err, "failed to fetch switches").Err() } defer rows.Close() var switches []*crimson.Switch for rows.Next() { s := &crimson.Switch{} if err = rows.Scan(&s.Name, &s.Description, &s.Ports, &s.State, &s.Rack, &s.Datacenter); err != nil { return nil, errors.Annotate(err, "failed to fetch switch").Err() } if matches(s.Name, names) && matches(s.Rack, racks) && matches(s.Datacenter, datacenters) { switches = append(switches, s) } } return switches, nil }
go
func listSwitches(c context.Context, names, racks, datacenters stringset.Set) ([]*crimson.Switch, error) { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT s.name, s.description, s.ports, s.state, r.name, d.name FROM switches s, racks r, datacenters d WHERE s.rack_id = r.id AND r.datacenter_id = d.id `) if err != nil { return nil, errors.Annotate(err, "failed to fetch switches").Err() } defer rows.Close() var switches []*crimson.Switch for rows.Next() { s := &crimson.Switch{} if err = rows.Scan(&s.Name, &s.Description, &s.Ports, &s.State, &s.Rack, &s.Datacenter); err != nil { return nil, errors.Annotate(err, "failed to fetch switch").Err() } if matches(s.Name, names) && matches(s.Rack, racks) && matches(s.Datacenter, datacenters) { switches = append(switches, s) } } return switches, nil }
[ "func", "listSwitches", "(", "c", "context", ".", "Context", ",", "names", ",", "racks", ",", "datacenters", "stringset", ".", "Set", ")", "(", "[", "]", "*", "crimson", ".", "Switch", ",", "error", ")", "{", "db", ":=", "database", ".", "Get", "(", ...
// listSwitches returns a slice of switches in the database.
[ "listSwitches", "returns", "a", "slice", "of", "switches", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/switches.go#L39-L63
8,329
luci/luci-go
server/caching/layered/layered.go
GetOrCreate
func (c *Cache) GetOrCreate(ctx context.Context, key string, fn lru.Maker, opts ...Option) (interface{}, error) { if c.GlobalNamespace == "" { panic("empty namespace is forbidden, please specify GlobalNamespace") } o := options{} for _, opt := range opts { opt.apply(&o) } now := clock.Now(ctx) lru := c.ProcessLRUCache.LRU(ctx) // Check that the item is in the local cache, its TTL is acceptable and we // don't want to randomly prematurely expire it, see WithRandomizedExpiration. var ignored *itemWithExp if v, ok := lru.Get(ctx, key); ok { item := v.(*itemWithExp) if item.isAcceptableTTL(now, o.minTTL) && !item.randomlyExpired(ctx, now, o.expRandThreshold) { return item.val, nil } ignored = item } // Either the item is not in the local cache, or the cached copy expires too // soon or we randomly decided that we want to prematurely refresh it. Attempt // to fetch from the global cache or create a new one. Disable expiration // randomization at this point, it has served its purpose already, since only // unlucky callers will reach this code path. v, err := lru.Create(ctx, key, func() (interface{}, time.Duration, error) { // Now that we have the lock, recheck that the item still needs a refresh. // Purposely ignore an item we decided we want to prematurely expire. if v, ok := lru.Get(ctx, key); ok { if item := v.(*itemWithExp); item != ignored && item.isAcceptableTTL(now, o.minTTL) { return item, item.expiration(now), nil } } // Attempt to grab it from the global cache, verifying TTL is acceptable. if item := c.maybeFetchItem(ctx, key); item != nil && item.isAcceptableTTL(now, o.minTTL) { return item, item.expiration(now), nil } // Either a cache miss, problems with the cached item or its TTL is not // acceptable. Need a to make a new item. var item itemWithExp val, exp, err := fn() item.val = val switch { case err != nil: return nil, 0, err case exp < 0: panic("the expiration time must be non-negative") case exp > 0: // note: if exp == 0 we want item.exp to be zero item.exp = now.Add(exp) if !item.isAcceptableTTL(now, o.minTTL) { // If 'fn' is incapable of generating an item with sufficient TTL there's // nothing else we can do. return nil, 0, ErrCantSatisfyMinTTL } } // Store the new item in the global cache. We may accidentally override // an item here if someone else refreshed it already. But this is // unavoidable given GlobalCache semantics and generally rare and harmless // (given Cache guarantees or rather lack of there of). if err := c.maybeStoreItem(ctx, key, &item, now); err != nil { return nil, 0, err } return &item, item.expiration(now), nil }) if err != nil { return nil, err } return v.(*itemWithExp).val, nil }
go
func (c *Cache) GetOrCreate(ctx context.Context, key string, fn lru.Maker, opts ...Option) (interface{}, error) { if c.GlobalNamespace == "" { panic("empty namespace is forbidden, please specify GlobalNamespace") } o := options{} for _, opt := range opts { opt.apply(&o) } now := clock.Now(ctx) lru := c.ProcessLRUCache.LRU(ctx) // Check that the item is in the local cache, its TTL is acceptable and we // don't want to randomly prematurely expire it, see WithRandomizedExpiration. var ignored *itemWithExp if v, ok := lru.Get(ctx, key); ok { item := v.(*itemWithExp) if item.isAcceptableTTL(now, o.minTTL) && !item.randomlyExpired(ctx, now, o.expRandThreshold) { return item.val, nil } ignored = item } // Either the item is not in the local cache, or the cached copy expires too // soon or we randomly decided that we want to prematurely refresh it. Attempt // to fetch from the global cache or create a new one. Disable expiration // randomization at this point, it has served its purpose already, since only // unlucky callers will reach this code path. v, err := lru.Create(ctx, key, func() (interface{}, time.Duration, error) { // Now that we have the lock, recheck that the item still needs a refresh. // Purposely ignore an item we decided we want to prematurely expire. if v, ok := lru.Get(ctx, key); ok { if item := v.(*itemWithExp); item != ignored && item.isAcceptableTTL(now, o.minTTL) { return item, item.expiration(now), nil } } // Attempt to grab it from the global cache, verifying TTL is acceptable. if item := c.maybeFetchItem(ctx, key); item != nil && item.isAcceptableTTL(now, o.minTTL) { return item, item.expiration(now), nil } // Either a cache miss, problems with the cached item or its TTL is not // acceptable. Need a to make a new item. var item itemWithExp val, exp, err := fn() item.val = val switch { case err != nil: return nil, 0, err case exp < 0: panic("the expiration time must be non-negative") case exp > 0: // note: if exp == 0 we want item.exp to be zero item.exp = now.Add(exp) if !item.isAcceptableTTL(now, o.minTTL) { // If 'fn' is incapable of generating an item with sufficient TTL there's // nothing else we can do. return nil, 0, ErrCantSatisfyMinTTL } } // Store the new item in the global cache. We may accidentally override // an item here if someone else refreshed it already. But this is // unavoidable given GlobalCache semantics and generally rare and harmless // (given Cache guarantees or rather lack of there of). if err := c.maybeStoreItem(ctx, key, &item, now); err != nil { return nil, 0, err } return &item, item.expiration(now), nil }) if err != nil { return nil, err } return v.(*itemWithExp).val, nil }
[ "func", "(", "c", "*", "Cache", ")", "GetOrCreate", "(", "ctx", "context", ".", "Context", ",", "key", "string", ",", "fn", "lru", ".", "Maker", ",", "opts", "...", "Option", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "c", "."...
// GetOrCreate attempts to grab an item from process or global cache, or create // it if it's not cached yet. // // Fetching an item from the global cache or instantiating a new item happens // under a per-key lock. // // Expiration time is used with seconds precision. Zero expiration time means // the item doesn't expire on its own.
[ "GetOrCreate", "attempts", "to", "grab", "an", "item", "from", "process", "or", "global", "cache", "or", "create", "it", "if", "it", "s", "not", "cached", "yet", ".", "Fetching", "an", "item", "from", "the", "global", "cache", "or", "instantiating", "a", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/layered/layered.go#L102-L178
8,330
luci/luci-go
server/caching/layered/layered.go
isAcceptableTTL
func (i *itemWithExp) isAcceptableTTL(now time.Time, minTTL time.Duration) bool { if i.exp.IsZero() { return true // never expires } // Note: '>=' must not be used here, since minTTL may be 0, and we don't want // to return true on zero expiration. return i.exp.Sub(now) > minTTL }
go
func (i *itemWithExp) isAcceptableTTL(now time.Time, minTTL time.Duration) bool { if i.exp.IsZero() { return true // never expires } // Note: '>=' must not be used here, since minTTL may be 0, and we don't want // to return true on zero expiration. return i.exp.Sub(now) > minTTL }
[ "func", "(", "i", "*", "itemWithExp", ")", "isAcceptableTTL", "(", "now", "time", ".", "Time", ",", "minTTL", "time", ".", "Duration", ")", "bool", "{", "if", "i", ".", "exp", ".", "IsZero", "(", ")", "{", "return", "true", "// never expires", "\n", ...
// isAcceptableTTL returns true if item's TTL is large enough.
[ "isAcceptableTTL", "returns", "true", "if", "item", "s", "TTL", "is", "large", "enough", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/layered/layered.go#L210-L217
8,331
luci/luci-go
server/caching/layered/layered.go
randomlyExpired
func (i *itemWithExp) randomlyExpired(ctx context.Context, now time.Time, threshold time.Duration) bool { if i.exp.IsZero() { return false // never expires } ttl := i.exp.Sub(now) if ttl > threshold { return false // far from expiration, no need to enable randomization } // TODO(vadimsh): The choice of distribution here was made arbitrary. Some // literature suggests to use exponential distribution instead, but it's not // clear how to pick parameters for it. In practice what we do here seems good // enough. On each check we randomly expire the item with probability // p = (threshold - ttl) / threshold. Closer the item to its true expiration // (ttl is smaller), higher the probability. rnd := time.Duration(mathrand.Int63n(ctx, int64(threshold))) return rnd > ttl }
go
func (i *itemWithExp) randomlyExpired(ctx context.Context, now time.Time, threshold time.Duration) bool { if i.exp.IsZero() { return false // never expires } ttl := i.exp.Sub(now) if ttl > threshold { return false // far from expiration, no need to enable randomization } // TODO(vadimsh): The choice of distribution here was made arbitrary. Some // literature suggests to use exponential distribution instead, but it's not // clear how to pick parameters for it. In practice what we do here seems good // enough. On each check we randomly expire the item with probability // p = (threshold - ttl) / threshold. Closer the item to its true expiration // (ttl is smaller), higher the probability. rnd := time.Duration(mathrand.Int63n(ctx, int64(threshold))) return rnd > ttl }
[ "func", "(", "i", "*", "itemWithExp", ")", "randomlyExpired", "(", "ctx", "context", ".", "Context", ",", "now", "time", ".", "Time", ",", "threshold", "time", ".", "Duration", ")", "bool", "{", "if", "i", ".", "exp", ".", "IsZero", "(", ")", "{", ...
// randomlyExpired returns true if the item must be considered already expired. // // See WithRandomizedExpiration for the rationale. The context is used only to // grab RNG.
[ "randomlyExpired", "returns", "true", "if", "the", "item", "must", "be", "considered", "already", "expired", ".", "See", "WithRandomizedExpiration", "for", "the", "rationale", ".", "The", "context", "is", "used", "only", "to", "grab", "RNG", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/layered/layered.go#L223-L241
8,332
luci/luci-go
server/caching/layered/layered.go
maybeFetchItem
func (c *Cache) maybeFetchItem(ctx context.Context, key string) *itemWithExp { g := caching.GlobalCache(ctx, c.GlobalNamespace) if g == nil { return nil } blob, err := g.Get(ctx, key) if err != nil { if err != caching.ErrCacheMiss { logging.WithError(err).Errorf(ctx, "Failed to read item %q from the global cache", key) } return nil } item, err := c.deserializeItem(blob) if err != nil { logging.WithError(err).Errorf(ctx, "Failed to deserialize item %q", key) return nil } return item }
go
func (c *Cache) maybeFetchItem(ctx context.Context, key string) *itemWithExp { g := caching.GlobalCache(ctx, c.GlobalNamespace) if g == nil { return nil } blob, err := g.Get(ctx, key) if err != nil { if err != caching.ErrCacheMiss { logging.WithError(err).Errorf(ctx, "Failed to read item %q from the global cache", key) } return nil } item, err := c.deserializeItem(blob) if err != nil { logging.WithError(err).Errorf(ctx, "Failed to deserialize item %q", key) return nil } return item }
[ "func", "(", "c", "*", "Cache", ")", "maybeFetchItem", "(", "ctx", "context", ".", "Context", ",", "key", "string", ")", "*", "itemWithExp", "{", "g", ":=", "caching", ".", "GlobalCache", "(", "ctx", ",", "c", ".", "GlobalNamespace", ")", "\n", "if", ...
// maybeFetchItem attempts to fetch the item from the global cache. // // If the global cache is not available or the cached item there is broken // returns nil. Logs errors inside.
[ "maybeFetchItem", "attempts", "to", "fetch", "the", "item", "from", "the", "global", "cache", ".", "If", "the", "global", "cache", "is", "not", "available", "or", "the", "cached", "item", "there", "is", "broken", "returns", "nil", ".", "Logs", "errors", "i...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/layered/layered.go#L263-L283
8,333
luci/luci-go
server/caching/layered/layered.go
maybeStoreItem
func (c *Cache) maybeStoreItem(ctx context.Context, key string, item *itemWithExp, now time.Time) error { g := caching.GlobalCache(ctx, c.GlobalNamespace) if g == nil { return nil } blob, err := c.serializeItem(item) if err != nil { return err } if err = g.Set(ctx, key, blob, item.expiration(now)); err != nil { logging.WithError(err).Errorf(ctx, "Failed to store item %q in the global cache", key) } return nil }
go
func (c *Cache) maybeStoreItem(ctx context.Context, key string, item *itemWithExp, now time.Time) error { g := caching.GlobalCache(ctx, c.GlobalNamespace) if g == nil { return nil } blob, err := c.serializeItem(item) if err != nil { return err } if err = g.Set(ctx, key, blob, item.expiration(now)); err != nil { logging.WithError(err).Errorf(ctx, "Failed to store item %q in the global cache", key) } return nil }
[ "func", "(", "c", "*", "Cache", ")", "maybeStoreItem", "(", "ctx", "context", ".", "Context", ",", "key", "string", ",", "item", "*", "itemWithExp", ",", "now", "time", ".", "Time", ")", "error", "{", "g", ":=", "caching", ".", "GlobalCache", "(", "c...
// maybeStoreItem puts the item in the global cache, if possible. // // It returns an error only if the serialization fails. It generally means the // serialization code is buggy and should be adjusted. // // Global cache errors are logged and ignored.
[ "maybeStoreItem", "puts", "the", "item", "in", "the", "global", "cache", "if", "possible", ".", "It", "returns", "an", "error", "only", "if", "the", "serialization", "fails", ".", "It", "generally", "means", "the", "serialization", "code", "is", "buggy", "an...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/layered/layered.go#L291-L306
8,334
luci/luci-go
server/caching/layered/layered.go
serializeItem
func (c *Cache) serializeItem(item *itemWithExp) ([]byte, error) { blob, err := c.Marshal(item.val) if err != nil { return nil, err } var deadline uint64 if !item.exp.IsZero() { deadline = uint64(item.exp.Unix()) } // <version_byte> + <uint64 deadline timestamp> + <blob> output := make([]byte, 9+len(blob)) output[0] = formatVersionByte binary.LittleEndian.PutUint64(output[1:], deadline) copy(output[9:], blob) return output, nil }
go
func (c *Cache) serializeItem(item *itemWithExp) ([]byte, error) { blob, err := c.Marshal(item.val) if err != nil { return nil, err } var deadline uint64 if !item.exp.IsZero() { deadline = uint64(item.exp.Unix()) } // <version_byte> + <uint64 deadline timestamp> + <blob> output := make([]byte, 9+len(blob)) output[0] = formatVersionByte binary.LittleEndian.PutUint64(output[1:], deadline) copy(output[9:], blob) return output, nil }
[ "func", "(", "c", "*", "Cache", ")", "serializeItem", "(", "item", "*", "itemWithExp", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "blob", ",", "err", ":=", "c", ".", "Marshal", "(", "item", ".", "val", ")", "\n", "if", "err", "!=", "ni...
// serializeItem packs item and its expiration time into a byte blob.
[ "serializeItem", "packs", "item", "and", "its", "expiration", "time", "into", "a", "byte", "blob", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/layered/layered.go#L309-L326
8,335
luci/luci-go
server/caching/layered/layered.go
deserializeItem
func (c *Cache) deserializeItem(blob []byte) (item *itemWithExp, err error) { if len(blob) < 9 { err = fmt.Errorf("the received buffer is too small") return } if blob[0] != formatVersionByte { err = fmt.Errorf("bad format version, expecting %d, got %d", formatVersionByte, blob[0]) return } item = &itemWithExp{} deadline := binary.LittleEndian.Uint64(blob[1:]) if deadline != 0 { item.exp = time.Unix(int64(deadline), 0) } item.val, err = c.Unmarshal(blob[9:]) return }
go
func (c *Cache) deserializeItem(blob []byte) (item *itemWithExp, err error) { if len(blob) < 9 { err = fmt.Errorf("the received buffer is too small") return } if blob[0] != formatVersionByte { err = fmt.Errorf("bad format version, expecting %d, got %d", formatVersionByte, blob[0]) return } item = &itemWithExp{} deadline := binary.LittleEndian.Uint64(blob[1:]) if deadline != 0 { item.exp = time.Unix(int64(deadline), 0) } item.val, err = c.Unmarshal(blob[9:]) return }
[ "func", "(", "c", "*", "Cache", ")", "deserializeItem", "(", "blob", "[", "]", "byte", ")", "(", "item", "*", "itemWithExp", ",", "err", "error", ")", "{", "if", "len", "(", "blob", ")", "<", "9", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"...
// deserializeItem is reverse of serializeItem.
[ "deserializeItem", "is", "reverse", "of", "serializeItem", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/layered/layered.go#L329-L345
8,336
luci/luci-go
tokenserver/cmd/luci_machine_tokend/signals.go
catchInterrupt
func catchInterrupt(handler func()) { sig := make(chan os.Signal, 1) signal.Notify(sig, interruptSignals()...) go func() { stopCalled := false for range sig { if !stopCalled { stopCalled = true handler() } else { os.Exit(2) } } }() }
go
func catchInterrupt(handler func()) { sig := make(chan os.Signal, 1) signal.Notify(sig, interruptSignals()...) go func() { stopCalled := false for range sig { if !stopCalled { stopCalled = true handler() } else { os.Exit(2) } } }() }
[ "func", "catchInterrupt", "(", "handler", "func", "(", ")", ")", "{", "sig", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "sig", ",", "interruptSignals", "(", ")", "...", ")", "\n", "go", "func"...
// catchInterrupt handles SIGINT and SIGTERM signals. // // When caught for the first time, it calls the `handler`, assuming it will // gracefully shutdown the process. // // If called for the second time, it just kills the process right away.
[ "catchInterrupt", "handles", "SIGINT", "and", "SIGTERM", "signals", ".", "When", "caught", "for", "the", "first", "time", "it", "calls", "the", "handler", "assuming", "it", "will", "gracefully", "shutdown", "the", "process", ".", "If", "called", "for", "the", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/cmd/luci_machine_tokend/signals.go#L28-L42
8,337
luci/luci-go
cipd/appengine/impl/cas/upload/id.go
NewOpID
func NewOpID(c context.Context) (int64, error) { // Note: AllocateIDs modifies passed slice in place, by replacing the keys // there. keys := []*datastore.Key{ datastore.NewKey(c, "cas.UploadOperation", "", 0, nil), } if err := datastore.AllocateIDs(c, keys); err != nil { return 0, errors.Annotate(err, "failed to generate upload operation ID"). Tag(transient.Tag).Err() } return keys[0].IntID(), nil }
go
func NewOpID(c context.Context) (int64, error) { // Note: AllocateIDs modifies passed slice in place, by replacing the keys // there. keys := []*datastore.Key{ datastore.NewKey(c, "cas.UploadOperation", "", 0, nil), } if err := datastore.AllocateIDs(c, keys); err != nil { return 0, errors.Annotate(err, "failed to generate upload operation ID"). Tag(transient.Tag).Err() } return keys[0].IntID(), nil }
[ "func", "NewOpID", "(", "c", "context", ".", "Context", ")", "(", "int64", ",", "error", ")", "{", "// Note: AllocateIDs modifies passed slice in place, by replacing the keys", "// there.", "keys", ":=", "[", "]", "*", "datastore", ".", "Key", "{", "datastore", "....
// NewOpID returns new unique upload operation ID.
[ "NewOpID", "returns", "new", "unique", "upload", "operation", "ID", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/upload/id.go#L39-L50
8,338
luci/luci-go
cipd/appengine/impl/cas/upload/id.go
WrapOpID
func WrapOpID(c context.Context, id int64, caller identity.Identity) (string, error) { return opToken.Generate(c, []byte(caller), map[string]string{ "id": strconv.FormatInt(id, 10), }, 0) }
go
func WrapOpID(c context.Context, id int64, caller identity.Identity) (string, error) { return opToken.Generate(c, []byte(caller), map[string]string{ "id": strconv.FormatInt(id, 10), }, 0) }
[ "func", "WrapOpID", "(", "c", "context", ".", "Context", ",", "id", "int64", ",", "caller", "identity", ".", "Identity", ")", "(", "string", ",", "error", ")", "{", "return", "opToken", ".", "Generate", "(", "c", ",", "[", "]", "byte", "(", "caller",...
// WrapOpID returns HMAC-protected string that embeds upload operation ID. // // The string is bound to the given caller, i.e UnwrapOpID will correctly // validate HMAC only if it receives the exact same caller.
[ "WrapOpID", "returns", "HMAC", "-", "protected", "string", "that", "embeds", "upload", "operation", "ID", ".", "The", "string", "is", "bound", "to", "the", "given", "caller", "i", ".", "e", "UnwrapOpID", "will", "correctly", "validate", "HMAC", "only", "if",...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/upload/id.go#L56-L60
8,339
luci/luci-go
cipd/appengine/impl/cas/upload/id.go
UnwrapOpID
func UnwrapOpID(c context.Context, token string, caller identity.Identity) (int64, error) { body, err := opToken.Validate(c, token, []byte(caller)) if err != nil { return 0, errors.Annotate(err, "failed to validate upload operation ID token").Err() } id, err := strconv.ParseInt(body["id"], 10, 64) if err != nil { return 0, errors.Annotate(err, "invalid upload operation ID %q", body["id"]).Err() } return id, nil }
go
func UnwrapOpID(c context.Context, token string, caller identity.Identity) (int64, error) { body, err := opToken.Validate(c, token, []byte(caller)) if err != nil { return 0, errors.Annotate(err, "failed to validate upload operation ID token").Err() } id, err := strconv.ParseInt(body["id"], 10, 64) if err != nil { return 0, errors.Annotate(err, "invalid upload operation ID %q", body["id"]).Err() } return id, nil }
[ "func", "UnwrapOpID", "(", "c", "context", ".", "Context", ",", "token", "string", ",", "caller", "identity", ".", "Identity", ")", "(", "int64", ",", "error", ")", "{", "body", ",", "err", ":=", "opToken", ".", "Validate", "(", "c", ",", "token", ",...
// UnwrapOpID extracts upload operation ID from a HMAC-protected string.
[ "UnwrapOpID", "extracts", "upload", "operation", "ID", "from", "a", "HMAC", "-", "protected", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/upload/id.go#L63-L73
8,340
luci/luci-go
common/bq/insertid.go
Generate
func (id *InsertIDGenerator) Generate() string { prefix := id.Prefix if prefix == "" { prefix = defaultPrefix } c := atomic.AddInt64(&id.Counter, 1) return fmt.Sprintf("%s:%d", prefix, c) }
go
func (id *InsertIDGenerator) Generate() string { prefix := id.Prefix if prefix == "" { prefix = defaultPrefix } c := atomic.AddInt64(&id.Counter, 1) return fmt.Sprintf("%s:%d", prefix, c) }
[ "func", "(", "id", "*", "InsertIDGenerator", ")", "Generate", "(", ")", "string", "{", "prefix", ":=", "id", ".", "Prefix", "\n", "if", "prefix", "==", "\"", "\"", "{", "prefix", "=", "defaultPrefix", "\n", "}", "\n", "c", ":=", "atomic", ".", "AddIn...
// Generate returns a unique Insert ID.
[ "Generate", "returns", "a", "unique", "Insert", "ID", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/bq/insertid.go#L56-L63
8,341
luci/luci-go
common/tsmon/store/inmemory.go
NewInMemory
func NewInMemory(defaultTarget types.Target) Store { return &inMemoryStore{ defaultTarget: defaultTarget, data: map[string]*metricData{}, } }
go
func NewInMemory(defaultTarget types.Target) Store { return &inMemoryStore{ defaultTarget: defaultTarget, data: map[string]*metricData{}, } }
[ "func", "NewInMemory", "(", "defaultTarget", "types", ".", "Target", ")", "Store", "{", "return", "&", "inMemoryStore", "{", "defaultTarget", ":", "defaultTarget", ",", "data", ":", "map", "[", "string", "]", "*", "metricData", "{", "}", ",", "}", "\n", ...
// NewInMemory creates a new metric store that holds metric data in this // process' memory.
[ "NewInMemory", "creates", "a", "new", "metric", "store", "that", "holds", "metric", "data", "in", "this", "process", "memory", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/store/inmemory.go#L80-L85
8,342
luci/luci-go
common/tsmon/store/inmemory.go
Get
func (s *inMemoryStore) Get(ctx context.Context, h types.Metric, resetTime time.Time, fieldVals []interface{}) interface{} { if resetTime.IsZero() { resetTime = clock.Now(ctx) } m := s.getOrCreateData(h) m.lock.Lock() defer m.lock.Unlock() return m.get(fieldVals, target.Get(ctx), resetTime).Value }
go
func (s *inMemoryStore) Get(ctx context.Context, h types.Metric, resetTime time.Time, fieldVals []interface{}) interface{} { if resetTime.IsZero() { resetTime = clock.Now(ctx) } m := s.getOrCreateData(h) m.lock.Lock() defer m.lock.Unlock() return m.get(fieldVals, target.Get(ctx), resetTime).Value }
[ "func", "(", "s", "*", "inMemoryStore", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "h", "types", ".", "Metric", ",", "resetTime", "time", ".", "Time", ",", "fieldVals", "[", "]", "interface", "{", "}", ")", "interface", "{", "}", "{", ...
// Get returns the value for a given metric cell.
[ "Get", "returns", "the", "value", "for", "a", "given", "metric", "cell", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/store/inmemory.go#L127-L137
8,343
luci/luci-go
common/tsmon/store/inmemory.go
Set
func (s *inMemoryStore) Set(ctx context.Context, h types.Metric, resetTime time.Time, fieldVals []interface{}, value interface{}) { if resetTime.IsZero() { resetTime = clock.Now(ctx) } t := target.Get(ctx) m := s.getOrCreateData(h) m.lock.Lock() defer m.lock.Unlock() c := m.get(fieldVals, t, resetTime) if m.ValueType.IsCumulative() && isLessThan(value, c.Value) { logging.Errorf(ctx, "Attempted to set cumulative metric %q to %v, which is lower than the previous value %v", h.Info().Name, value, c.Value) return } c.Value = value }
go
func (s *inMemoryStore) Set(ctx context.Context, h types.Metric, resetTime time.Time, fieldVals []interface{}, value interface{}) { if resetTime.IsZero() { resetTime = clock.Now(ctx) } t := target.Get(ctx) m := s.getOrCreateData(h) m.lock.Lock() defer m.lock.Unlock() c := m.get(fieldVals, t, resetTime) if m.ValueType.IsCumulative() && isLessThan(value, c.Value) { logging.Errorf(ctx, "Attempted to set cumulative metric %q to %v, which is lower than the previous value %v", h.Info().Name, value, c.Value) return } c.Value = value }
[ "func", "(", "s", "*", "inMemoryStore", ")", "Set", "(", "ctx", "context", ".", "Context", ",", "h", "types", ".", "Metric", ",", "resetTime", "time", ".", "Time", ",", "fieldVals", "[", "]", "interface", "{", "}", ",", "value", "interface", "{", "}"...
// Set writes the value into the given metric cell.
[ "Set", "writes", "the", "value", "into", "the", "given", "metric", "cell", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/store/inmemory.go#L153-L173
8,344
luci/luci-go
common/tsmon/store/inmemory.go
Incr
func (s *inMemoryStore) Incr(ctx context.Context, h types.Metric, resetTime time.Time, fieldVals []interface{}, delta interface{}) { if resetTime.IsZero() { resetTime = clock.Now(ctx) } t := target.Get(ctx) m := s.getOrCreateData(h) m.lock.Lock() defer m.lock.Unlock() c := m.get(fieldVals, t, resetTime) switch m.ValueType { case types.CumulativeDistributionType: d, ok := delta.(float64) if !ok { panic(fmt.Errorf("Incr got a delta of unsupported type (%v)", delta)) } v, ok := c.Value.(*distribution.Distribution) if !ok { v = distribution.New(h.(types.DistributionMetric).Bucketer()) c.Value = v } v.Add(float64(d)) case types.CumulativeIntType: if v, ok := c.Value.(int64); ok { c.Value = v + delta.(int64) } else { c.Value = delta.(int64) } case types.CumulativeFloatType: if v, ok := c.Value.(float64); ok { c.Value = v + delta.(float64) } else { c.Value = delta.(float64) } default: panic(fmt.Errorf("attempted to increment non-cumulative metric %s by %v", m.Name, delta)) } }
go
func (s *inMemoryStore) Incr(ctx context.Context, h types.Metric, resetTime time.Time, fieldVals []interface{}, delta interface{}) { if resetTime.IsZero() { resetTime = clock.Now(ctx) } t := target.Get(ctx) m := s.getOrCreateData(h) m.lock.Lock() defer m.lock.Unlock() c := m.get(fieldVals, t, resetTime) switch m.ValueType { case types.CumulativeDistributionType: d, ok := delta.(float64) if !ok { panic(fmt.Errorf("Incr got a delta of unsupported type (%v)", delta)) } v, ok := c.Value.(*distribution.Distribution) if !ok { v = distribution.New(h.(types.DistributionMetric).Bucketer()) c.Value = v } v.Add(float64(d)) case types.CumulativeIntType: if v, ok := c.Value.(int64); ok { c.Value = v + delta.(int64) } else { c.Value = delta.(int64) } case types.CumulativeFloatType: if v, ok := c.Value.(float64); ok { c.Value = v + delta.(float64) } else { c.Value = delta.(float64) } default: panic(fmt.Errorf("attempted to increment non-cumulative metric %s by %v", m.Name, delta)) } }
[ "func", "(", "s", "*", "inMemoryStore", ")", "Incr", "(", "ctx", "context", ".", "Context", ",", "h", "types", ".", "Metric", ",", "resetTime", "time", ".", "Time", ",", "fieldVals", "[", "]", "interface", "{", "}", ",", "delta", "interface", "{", "}...
// Incr increments the value in a given metric cell by the given delta.
[ "Incr", "increments", "the", "value", "in", "a", "given", "metric", "cell", "by", "the", "given", "delta", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/store/inmemory.go#L176-L218
8,345
luci/luci-go
common/tsmon/store/inmemory.go
GetAll
func (s *inMemoryStore) GetAll(ctx context.Context) []types.Cell { s.dataLock.Lock() defer s.dataLock.Unlock() defaultTarget := s.DefaultTarget() ret := []types.Cell{} for _, m := range s.data { m.lock.Lock() for _, cells := range m.cells { for _, cell := range cells { // Add the default target to the cell if it doesn't have one set. cellCopy := *cell if cellCopy.Target == nil { cellCopy.Target = defaultTarget } ret = append(ret, types.Cell{m.MetricInfo, m.MetricMetadata, cellCopy}) } } m.lock.Unlock() } return ret }
go
func (s *inMemoryStore) GetAll(ctx context.Context) []types.Cell { s.dataLock.Lock() defer s.dataLock.Unlock() defaultTarget := s.DefaultTarget() ret := []types.Cell{} for _, m := range s.data { m.lock.Lock() for _, cells := range m.cells { for _, cell := range cells { // Add the default target to the cell if it doesn't have one set. cellCopy := *cell if cellCopy.Target == nil { cellCopy.Target = defaultTarget } ret = append(ret, types.Cell{m.MetricInfo, m.MetricMetadata, cellCopy}) } } m.lock.Unlock() } return ret }
[ "func", "(", "s", "*", "inMemoryStore", ")", "GetAll", "(", "ctx", "context", ".", "Context", ")", "[", "]", "types", ".", "Cell", "{", "s", ".", "dataLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "dataLock", ".", "Unlock", "(", ")", "\n...
// GetAll efficiently returns all cells in the store.
[ "GetAll", "efficiently", "returns", "all", "cells", "in", "the", "store", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/store/inmemory.go#L221-L243
8,346
luci/luci-go
client/cmd/isolate/batch_archive.go
batchArchive
func batchArchive(ctx context.Context, client *isolatedclient.Client, al archiveLogger, dumpJSONPath string, concurrentChecks, concurrentUploads int, genJSONPaths []string, blacklistStrings []string) error { // Set up a checker and uploader. We limit the uploader to one concurrent // upload, since the uploads are all coming from disk (with the exception of // the isolated JSON itself) and we only want a single goroutine reading from // disk at once. checker := archiver.NewChecker(ctx, client, concurrentChecks) uploader := archiver.NewUploader(ctx, client, concurrentUploads) a := archiver.NewTarringArchiver(checker, uploader) var errArchive error var isolSummaries []archiver.IsolatedSummary for _, genJSONPath := range genJSONPaths { opts, err := processGenJSON(genJSONPath) if err != nil { return err } // Parse the incoming isolate file. deps, rootDir, isol, err := isolate.ProcessIsolate(opts) if err != nil { return fmt.Errorf("isolate %s: failed to process: %v", opts.Isolate, err) } log.Printf("Isolate %s referenced %d deps", opts.Isolate, len(deps)) // Use the explicit blacklist if it's provided. if len(blacklistStrings) > 0 { opts.Blacklist = blacklistStrings } isolSummary, err := a.Archive(deps, rootDir, isol, opts.Blacklist, opts.Isolated) if err != nil && errArchive == nil { errArchive = fmt.Errorf("isolate %s: %v", opts.Isolate, err) } else { printSummary(al, isolSummary) isolSummaries = append(isolSummaries, isolSummary) } } if errArchive != nil { return errArchive } // Make sure that all pending items have been checked. if err := checker.Close(); err != nil { return err } // Make sure that all the uploads have completed successfully. if err := uploader.Close(); err != nil { return err } if err := dumpSummaryJSON(dumpJSONPath, isolSummaries...); err != nil { return err } al.LogSummary(ctx, int64(checker.Hit.Count()), int64(checker.Miss.Count()), units.Size(checker.Hit.Bytes()), units.Size(checker.Miss.Bytes()), digests(isolSummaries)) return nil }
go
func batchArchive(ctx context.Context, client *isolatedclient.Client, al archiveLogger, dumpJSONPath string, concurrentChecks, concurrentUploads int, genJSONPaths []string, blacklistStrings []string) error { // Set up a checker and uploader. We limit the uploader to one concurrent // upload, since the uploads are all coming from disk (with the exception of // the isolated JSON itself) and we only want a single goroutine reading from // disk at once. checker := archiver.NewChecker(ctx, client, concurrentChecks) uploader := archiver.NewUploader(ctx, client, concurrentUploads) a := archiver.NewTarringArchiver(checker, uploader) var errArchive error var isolSummaries []archiver.IsolatedSummary for _, genJSONPath := range genJSONPaths { opts, err := processGenJSON(genJSONPath) if err != nil { return err } // Parse the incoming isolate file. deps, rootDir, isol, err := isolate.ProcessIsolate(opts) if err != nil { return fmt.Errorf("isolate %s: failed to process: %v", opts.Isolate, err) } log.Printf("Isolate %s referenced %d deps", opts.Isolate, len(deps)) // Use the explicit blacklist if it's provided. if len(blacklistStrings) > 0 { opts.Blacklist = blacklistStrings } isolSummary, err := a.Archive(deps, rootDir, isol, opts.Blacklist, opts.Isolated) if err != nil && errArchive == nil { errArchive = fmt.Errorf("isolate %s: %v", opts.Isolate, err) } else { printSummary(al, isolSummary) isolSummaries = append(isolSummaries, isolSummary) } } if errArchive != nil { return errArchive } // Make sure that all pending items have been checked. if err := checker.Close(); err != nil { return err } // Make sure that all the uploads have completed successfully. if err := uploader.Close(); err != nil { return err } if err := dumpSummaryJSON(dumpJSONPath, isolSummaries...); err != nil { return err } al.LogSummary(ctx, int64(checker.Hit.Count()), int64(checker.Miss.Count()), units.Size(checker.Hit.Bytes()), units.Size(checker.Miss.Bytes()), digests(isolSummaries)) return nil }
[ "func", "batchArchive", "(", "ctx", "context", ".", "Context", ",", "client", "*", "isolatedclient", ".", "Client", ",", "al", "archiveLogger", ",", "dumpJSONPath", "string", ",", "concurrentChecks", ",", "concurrentUploads", "int", ",", "genJSONPaths", "[", "]"...
// batchArchive archives a series of isolates specified by genJSONPaths.
[ "batchArchive", "archives", "a", "series", "of", "isolates", "specified", "by", "genJSONPaths", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/isolate/batch_archive.go#L166-L220
8,347
luci/luci-go
client/cmd/isolate/batch_archive.go
digests
func digests(summaries []archiver.IsolatedSummary) []string { var result []string for _, summary := range summaries { result = append(result, string(summary.Digest)) } return result }
go
func digests(summaries []archiver.IsolatedSummary) []string { var result []string for _, summary := range summaries { result = append(result, string(summary.Digest)) } return result }
[ "func", "digests", "(", "summaries", "[", "]", "archiver", ".", "IsolatedSummary", ")", "[", "]", "string", "{", "var", "result", "[", "]", "string", "\n", "for", "_", ",", "summary", ":=", "range", "summaries", "{", "result", "=", "append", "(", "resu...
// digests extracts the digests from the supplied IsolatedSummarys.
[ "digests", "extracts", "the", "digests", "from", "the", "supplied", "IsolatedSummarys", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/isolate/batch_archive.go#L223-L229
8,348
luci/luci-go
client/cmd/isolate/batch_archive.go
processGenJSON
func processGenJSON(genJSONPath string) (*isolate.ArchiveOptions, error) { f, err := os.Open(genJSONPath) if err != nil { return nil, fmt.Errorf("opening %s: %s", genJSONPath, err) } defer f.Close() opts, err := processGenJSONData(f) if err != nil { return nil, fmt.Errorf("processing %s: %s", genJSONPath, err) } return opts, nil }
go
func processGenJSON(genJSONPath string) (*isolate.ArchiveOptions, error) { f, err := os.Open(genJSONPath) if err != nil { return nil, fmt.Errorf("opening %s: %s", genJSONPath, err) } defer f.Close() opts, err := processGenJSONData(f) if err != nil { return nil, fmt.Errorf("processing %s: %s", genJSONPath, err) } return opts, nil }
[ "func", "processGenJSON", "(", "genJSONPath", "string", ")", "(", "*", "isolate", ".", "ArchiveOptions", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "genJSONPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ...
// processGenJSON validates a genJSON file and returns the contents.
[ "processGenJSON", "validates", "a", "genJSON", "file", "and", "returns", "the", "contents", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/isolate/batch_archive.go#L232-L244
8,349
luci/luci-go
client/cmd/isolate/batch_archive.go
processGenJSONData
func processGenJSONData(r io.Reader) (*isolate.ArchiveOptions, error) { data := &struct { Args []string Dir string Version int }{} if err := json.NewDecoder(r).Decode(data); err != nil { return nil, fmt.Errorf("failed to decode: %s", err) } if data.Version != isolate.IsolatedGenJSONVersion { return nil, fmt.Errorf("invalid version %d", data.Version) } if fileInfo, err := os.Stat(data.Dir); err != nil || !fileInfo.IsDir() { return nil, fmt.Errorf("invalid dir %s", data.Dir) } opts, err := parseArchiveCMD(data.Args, data.Dir) if err != nil { return nil, fmt.Errorf("invalid archive command: %s", err) } return opts, nil }
go
func processGenJSONData(r io.Reader) (*isolate.ArchiveOptions, error) { data := &struct { Args []string Dir string Version int }{} if err := json.NewDecoder(r).Decode(data); err != nil { return nil, fmt.Errorf("failed to decode: %s", err) } if data.Version != isolate.IsolatedGenJSONVersion { return nil, fmt.Errorf("invalid version %d", data.Version) } if fileInfo, err := os.Stat(data.Dir); err != nil || !fileInfo.IsDir() { return nil, fmt.Errorf("invalid dir %s", data.Dir) } opts, err := parseArchiveCMD(data.Args, data.Dir) if err != nil { return nil, fmt.Errorf("invalid archive command: %s", err) } return opts, nil }
[ "func", "processGenJSONData", "(", "r", "io", ".", "Reader", ")", "(", "*", "isolate", ".", "ArchiveOptions", ",", "error", ")", "{", "data", ":=", "&", "struct", "{", "Args", "[", "]", "string", "\n", "Dir", "string", "\n", "Version", "int", "\n", "...
// processGenJSONData performs the function of processGenJSON, but operates on an io.Reader.
[ "processGenJSONData", "performs", "the", "function", "of", "processGenJSON", "but", "operates", "on", "an", "io", ".", "Reader", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/isolate/batch_archive.go#L247-L270
8,350
luci/luci-go
client/cmd/isolate/batch_archive.go
writeFile
func writeFile(filePath string, data []byte) error { f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("opening %s: %s", filePath, err) } // NOTE: We don't defer f.Close here, because it may return an error. _, writeErr := f.Write(data) closeErr := f.Close() if writeErr != nil { return fmt.Errorf("writing %s: %s", filePath, writeErr) } else if closeErr != nil { return fmt.Errorf("closing %s: %s", filePath, closeErr) } return nil }
go
func writeFile(filePath string, data []byte) error { f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("opening %s: %s", filePath, err) } // NOTE: We don't defer f.Close here, because it may return an error. _, writeErr := f.Write(data) closeErr := f.Close() if writeErr != nil { return fmt.Errorf("writing %s: %s", filePath, writeErr) } else if closeErr != nil { return fmt.Errorf("closing %s: %s", filePath, closeErr) } return nil }
[ "func", "writeFile", "(", "filePath", "string", ",", "data", "[", "]", "byte", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "filePath", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", ...
// writeFile writes data to filePath. File permission is set to user only.
[ "writeFile", "writes", "data", "to", "filePath", ".", "File", "permission", "is", "set", "to", "user", "only", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/isolate/batch_archive.go#L291-L306
8,351
luci/luci-go
milo/common/model/build_summary.go
GetBuildName
func (bs *BuildSummary) GetBuildName() string { if bs == nil { return "" } li := strings.LastIndex(bs.BuildID, "/") if li == -1 { return "" } // Don't include the "/", therefore li+1. return bs.BuildID[li+1:] }
go
func (bs *BuildSummary) GetBuildName() string { if bs == nil { return "" } li := strings.LastIndex(bs.BuildID, "/") if li == -1 { return "" } // Don't include the "/", therefore li+1. return bs.BuildID[li+1:] }
[ "func", "(", "bs", "*", "BuildSummary", ")", "GetBuildName", "(", ")", "string", "{", "if", "bs", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "li", ":=", "strings", ".", "LastIndex", "(", "bs", ".", "BuildID", ",", "\"", "\"", ")", "...
// GetBuildName returns an abridged version of the BuildID meant for human // consumption. Currently, this is always the last token of the BuildID.
[ "GetBuildName", "returns", "an", "abridged", "version", "of", "the", "BuildID", "meant", "for", "human", "consumption", ".", "Currently", "this", "is", "always", "the", "last", "token", "of", "the", "BuildID", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/build_summary.go#L164-L174
8,352
luci/luci-go
milo/common/model/build_summary.go
AddManifestKey
func (bs *BuildSummary) AddManifestKey(project, console, manifest, repoURL string, revision []byte) { bs.ManifestKeys = append(bs.ManifestKeys, NewPartialManifestKey(project, console, manifest, repoURL).AddRevision(revision)) }
go
func (bs *BuildSummary) AddManifestKey(project, console, manifest, repoURL string, revision []byte) { bs.ManifestKeys = append(bs.ManifestKeys, NewPartialManifestKey(project, console, manifest, repoURL).AddRevision(revision)) }
[ "func", "(", "bs", "*", "BuildSummary", ")", "AddManifestKey", "(", "project", ",", "console", ",", "manifest", ",", "repoURL", "string", ",", "revision", "[", "]", "byte", ")", "{", "bs", ".", "ManifestKeys", "=", "append", "(", "bs", ".", "ManifestKeys...
// AddManifestKey adds a new entry to ManifestKey. // // `revision` should be the hex-decoded git revision. // // It's up to the caller to ensure that entries in ManifestKey aren't // duplicated.
[ "AddManifestKey", "adds", "a", "new", "entry", "to", "ManifestKey", ".", "revision", "should", "be", "the", "hex", "-", "decoded", "git", "revision", ".", "It", "s", "up", "to", "the", "caller", "to", "ensure", "that", "entries", "in", "ManifestKey", "aren...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/build_summary.go#L207-L210
8,353
luci/luci-go
milo/common/model/build_summary.go
NewPartialManifestKey
func NewPartialManifestKey(project, console, manifest, repoURL string) PartialManifestKey { var buf bytes.Buffer cmpbin.WriteUint(&buf, currentManifestKeyVersion) // version cmpbin.WriteString(&buf, project) cmpbin.WriteString(&buf, console) cmpbin.WriteString(&buf, manifest) cmpbin.WriteString(&buf, repoURL) return PartialManifestKey(buf.Bytes()) }
go
func NewPartialManifestKey(project, console, manifest, repoURL string) PartialManifestKey { var buf bytes.Buffer cmpbin.WriteUint(&buf, currentManifestKeyVersion) // version cmpbin.WriteString(&buf, project) cmpbin.WriteString(&buf, console) cmpbin.WriteString(&buf, manifest) cmpbin.WriteString(&buf, repoURL) return PartialManifestKey(buf.Bytes()) }
[ "func", "NewPartialManifestKey", "(", "project", ",", "console", ",", "manifest", ",", "repoURL", "string", ")", "PartialManifestKey", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "cmpbin", ".", "WriteUint", "(", "&", "buf", ",", "currentManifestKeyVersion",...
// NewPartialManifestKey generates a ManifestKey prefix corresponding to // the given parameters.
[ "NewPartialManifestKey", "generates", "a", "ManifestKey", "prefix", "corresponding", "to", "the", "given", "parameters", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/build_summary.go#L227-L235
8,354
luci/luci-go
milo/common/model/build_summary.go
AddManifestKeysFromBuildSets
func (bs *BuildSummary) AddManifestKeysFromBuildSets(c context.Context) error { if bs.BuilderID == "" { return errors.New("BuilderID is empty") } for _, bsetRaw := range bs.BuildSet { commit, ok := protoutil.ParseBuildSet(bsetRaw).(*buildbucketpb.GitilesCommit) if !ok { continue } revision, err := hex.DecodeString(commit.Id) switch { case err != nil: logging.WithError(err).Warningf(c, "failed to decode revision: %v", commit.Id) case len(revision) != sha1.Size: logging.Warningf(c, "wrong revision size %d v %d: %q", len(revision), sha1.Size, commit.Id) default: consoles, err := common.GetAllConsoles(c, bs.BuilderID) if err != nil { return err } // HACK(iannucci): Until we have real manifest support, console definitions // will specify their manifest as "REVISION", and we'll do lookups with null // URL fields. for _, con := range consoles { bs.AddManifestKey(con.ProjectID(), con.ID, "REVISION", "", revision) bs.AddManifestKey(con.ProjectID(), con.ID, "BUILD_SET/GitilesCommit", protoutil.GitilesCommitURL(commit), revision) } } } return nil }
go
func (bs *BuildSummary) AddManifestKeysFromBuildSets(c context.Context) error { if bs.BuilderID == "" { return errors.New("BuilderID is empty") } for _, bsetRaw := range bs.BuildSet { commit, ok := protoutil.ParseBuildSet(bsetRaw).(*buildbucketpb.GitilesCommit) if !ok { continue } revision, err := hex.DecodeString(commit.Id) switch { case err != nil: logging.WithError(err).Warningf(c, "failed to decode revision: %v", commit.Id) case len(revision) != sha1.Size: logging.Warningf(c, "wrong revision size %d v %d: %q", len(revision), sha1.Size, commit.Id) default: consoles, err := common.GetAllConsoles(c, bs.BuilderID) if err != nil { return err } // HACK(iannucci): Until we have real manifest support, console definitions // will specify their manifest as "REVISION", and we'll do lookups with null // URL fields. for _, con := range consoles { bs.AddManifestKey(con.ProjectID(), con.ID, "REVISION", "", revision) bs.AddManifestKey(con.ProjectID(), con.ID, "BUILD_SET/GitilesCommit", protoutil.GitilesCommitURL(commit), revision) } } } return nil }
[ "func", "(", "bs", "*", "BuildSummary", ")", "AddManifestKeysFromBuildSets", "(", "c", "context", ".", "Context", ")", "error", "{", "if", "bs", ".", "BuilderID", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", ...
// AddManifestKeysFromBuildSets potentially adds one or more ManifestKey's to // the BuildSummary for any defined BuildSets. // // This assumes that bs.BuilderID and bs.BuildSet have already been populated. // If BuilderID is not populated, this will return an error.
[ "AddManifestKeysFromBuildSets", "potentially", "adds", "one", "or", "more", "ManifestKey", "s", "to", "the", "BuildSummary", "for", "any", "defined", "BuildSets", ".", "This", "assumes", "that", "bs", ".", "BuilderID", "and", "bs", ".", "BuildSet", "have", "alre...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/build_summary.go#L242-L279
8,355
luci/luci-go
milo/common/model/build_summary.go
GitilesCommit
func (bs *BuildSummary) GitilesCommit() *buildbucketpb.GitilesCommit { for _, bset := range bs.BuildSet { if gc, ok := protoutil.ParseBuildSet(bset).(*buildbucketpb.GitilesCommit); ok { return gc } } return nil }
go
func (bs *BuildSummary) GitilesCommit() *buildbucketpb.GitilesCommit { for _, bset := range bs.BuildSet { if gc, ok := protoutil.ParseBuildSet(bset).(*buildbucketpb.GitilesCommit); ok { return gc } } return nil }
[ "func", "(", "bs", "*", "BuildSummary", ")", "GitilesCommit", "(", ")", "*", "buildbucketpb", ".", "GitilesCommit", "{", "for", "_", ",", "bset", ":=", "range", "bs", ".", "BuildSet", "{", "if", "gc", ",", "ok", ":=", "protoutil", ".", "ParseBuildSet", ...
// GitilesCommit extracts the first BuildSet which is a valid GitilesCommit. // // If no such BuildSet is found, this returns nil.
[ "GitilesCommit", "extracts", "the", "first", "BuildSet", "which", "is", "a", "valid", "GitilesCommit", ".", "If", "no", "such", "BuildSet", "is", "found", "this", "returns", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/build_summary.go#L284-L291
8,356
luci/luci-go
milo/common/model/build_summary.go
filterBuilds
func filterBuilds(builds []*BuildSummary, without ...Status) []*BuildSummary { filtered := builds[:0] outer: for _, build := range builds { for _, status := range without { if status == build.Summary.Status { continue outer } } filtered = append(filtered, build) } return filtered }
go
func filterBuilds(builds []*BuildSummary, without ...Status) []*BuildSummary { filtered := builds[:0] outer: for _, build := range builds { for _, status := range without { if status == build.Summary.Status { continue outer } } filtered = append(filtered, build) } return filtered }
[ "func", "filterBuilds", "(", "builds", "[", "]", "*", "BuildSummary", ",", "without", "...", "Status", ")", "[", "]", "*", "BuildSummary", "{", "filtered", ":=", "builds", "[", ":", "0", "]", "\n", "outer", ":", "for", "_", ",", "build", ":=", "range...
// filterBuilds returns a truncated slice, filtering out builds with the given // statuses.
[ "filterBuilds", "returns", "a", "truncated", "slice", "filtering", "out", "builds", "with", "the", "given", "statuses", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/build_summary.go#L403-L415
8,357
luci/luci-go
logdog/client/butler/streamserver/base.go
Close
func (s *listenerStreamServer) Close() { if s.l == nil { panic("server is not currently serving") } // Mark that we've been closed. atomic.StoreInt32(&s.closed, 1) // Close our Listener. This will cause our 'Accept' goroutine to terminate. s.l.Close() close(s.closedC) <-s.acceptFinishedC // Close our streamParamsC to signal that we're closed. Any blocking Next will // drain the channel, then return with nil. close(s.streamParamsC) s.l = nil }
go
func (s *listenerStreamServer) Close() { if s.l == nil { panic("server is not currently serving") } // Mark that we've been closed. atomic.StoreInt32(&s.closed, 1) // Close our Listener. This will cause our 'Accept' goroutine to terminate. s.l.Close() close(s.closedC) <-s.acceptFinishedC // Close our streamParamsC to signal that we're closed. Any blocking Next will // drain the channel, then return with nil. close(s.streamParamsC) s.l = nil }
[ "func", "(", "s", "*", "listenerStreamServer", ")", "Close", "(", ")", "{", "if", "s", ".", "l", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Mark that we've been closed.", "atomic", ".", "StoreInt32", "(", "&", "s", ".", "...
// Implements StreamServer.Close
[ "Implements", "StreamServer", ".", "Close" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/streamserver/base.go#L110-L127
8,358
luci/luci-go
logdog/client/butler/streamserver/base.go
handle
func (c *streamClient) handle() (*streamParams, error) { log.Infof(c, "Received new connection.") // Close the connection as a failsafe. If we have already decoupled it, this // will end up being a no-op. defer c.closeConn() // Perform our handshake. We pass the connection explicitly into this method // because it can get decoupled during operation. p, err := handshake(c, c.conn) if err != nil { return nil, err } // Successful handshake. Forward our properties. return &streamParams{c.decoupleConn(), p}, nil }
go
func (c *streamClient) handle() (*streamParams, error) { log.Infof(c, "Received new connection.") // Close the connection as a failsafe. If we have already decoupled it, this // will end up being a no-op. defer c.closeConn() // Perform our handshake. We pass the connection explicitly into this method // because it can get decoupled during operation. p, err := handshake(c, c.conn) if err != nil { return nil, err } // Successful handshake. Forward our properties. return &streamParams{c.decoupleConn(), p}, nil }
[ "func", "(", "c", "*", "streamClient", ")", "handle", "(", ")", "(", "*", "streamParams", ",", "error", ")", "{", "log", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n\n", "// Close the connection as a failsafe. If we have already decoupled it, this", "// wil...
// handle initializes the supplied connection. On success, it will prepare // the connection as a Butler stream and pass its parameters through the // supplied channel. // // On failure, the connection will be closed. // // This method returns the negotiated stream parameters, or nil if the // negotitation failed and the client was closed.
[ "handle", "initializes", "the", "supplied", "connection", ".", "On", "success", "it", "will", "prepare", "the", "connection", "as", "a", "Butler", "stream", "and", "pass", "its", "parameters", "through", "the", "supplied", "channel", ".", "On", "failure", "the...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/streamserver/base.go#L232-L248
8,359
luci/luci-go
logdog/client/butler/streamserver/base.go
handshake
func handshake(ctx context.Context, conn net.Conn) (*streamproto.Properties, error) { log.Infof(ctx, "Beginning handshake.") hs := handshakeProtocol{} return hs.Handshake(ctx, conn) }
go
func handshake(ctx context.Context, conn net.Conn) (*streamproto.Properties, error) { log.Infof(ctx, "Beginning handshake.") hs := handshakeProtocol{} return hs.Handshake(ctx, conn) }
[ "func", "handshake", "(", "ctx", "context", ".", "Context", ",", "conn", "net", ".", "Conn", ")", "(", "*", "streamproto", ".", "Properties", ",", "error", ")", "{", "log", ".", "Infof", "(", "ctx", ",", "\"", "\"", ")", "\n", "hs", ":=", "handshak...
// handshake handles the handshaking and registration of a single connection. If // the connection successfully handshakes, it will be registered as a stream and // supplied to the local streamParamsC; otherwise, it will be closed. // // The client connection opens with a handshake protocol. Once complete, the // connection itself becomes the stream.
[ "handshake", "handles", "the", "handshaking", "and", "registration", "of", "a", "single", "connection", ".", "If", "the", "connection", "successfully", "handshakes", "it", "will", "be", "registered", "as", "a", "stream", "and", "supplied", "to", "the", "local", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/streamserver/base.go#L256-L260
8,360
luci/luci-go
logdog/client/butler/streamserver/base.go
closeConn
func (c *streamClient) closeConn() { conn := c.decoupleConn() if conn != nil { if err := conn.Close(); err != nil { log.Fields{ log.ErrorKey: err, }.Warningf(c, "Error on connection close.") } } }
go
func (c *streamClient) closeConn() { conn := c.decoupleConn() if conn != nil { if err := conn.Close(); err != nil { log.Fields{ log.ErrorKey: err, }.Warningf(c, "Error on connection close.") } } }
[ "func", "(", "c", "*", "streamClient", ")", "closeConn", "(", ")", "{", "conn", ":=", "c", ".", "decoupleConn", "(", ")", "\n", "if", "conn", "!=", "nil", "{", "if", "err", ":=", "conn", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "lo...
// Closes the underlying connection.
[ "Closes", "the", "underlying", "connection", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/streamserver/base.go#L263-L272
8,361
luci/luci-go
logdog/client/butler/streamserver/base.go
decoupleConn
func (c *streamClient) decoupleConn() (conn net.Conn) { c.decoupleMu.Lock() defer c.decoupleMu.Unlock() conn, c.conn = c.conn, nil return }
go
func (c *streamClient) decoupleConn() (conn net.Conn) { c.decoupleMu.Lock() defer c.decoupleMu.Unlock() conn, c.conn = c.conn, nil return }
[ "func", "(", "c", "*", "streamClient", ")", "decoupleConn", "(", ")", "(", "conn", "net", ".", "Conn", ")", "{", "c", ".", "decoupleMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "decoupleMu", ".", "Unlock", "(", ")", "\n\n", "conn", ",", "...
// Decouples the active connection, returning it and setting the connection to // nil.
[ "Decouples", "the", "active", "connection", "returning", "it", "and", "setting", "the", "connection", "to", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/streamserver/base.go#L276-L282
8,362
luci/luci-go
appengine/gaemiddleware/flex/env.go
WithGlobal
func WithGlobal(c context.Context) context.Context { return ReadOnlyFlex.With(c, &http.Request{}) }
go
func WithGlobal(c context.Context) context.Context { return ReadOnlyFlex.With(c, &http.Request{}) }
[ "func", "WithGlobal", "(", "c", "context", ".", "Context", ")", "context", ".", "Context", "{", "return", "ReadOnlyFlex", ".", "With", "(", "c", ",", "&", "http", ".", "Request", "{", "}", ")", "\n", "}" ]
// WithGlobal returns a Context that is not attached to a specific request.
[ "WithGlobal", "returns", "a", "Context", "that", "is", "not", "attached", "to", "a", "specific", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaemiddleware/flex/env.go#L165-L167
8,363
luci/luci-go
tokenserver/appengine/impl/delegation/rpc_import_delegation_configs.go
ImportDelegationConfigs
func (r *ImportDelegationConfigsRPC) ImportDelegationConfigs(c context.Context, _ *empty.Empty) (*admin.ImportedConfigs, error) { rev, err := r.RulesCache.ImportConfigs(c) if err != nil { logging.WithError(err).Errorf(c, "Failed to fetch delegation configs") return nil, status.Errorf(codes.Internal, err.Error()) } return &admin.ImportedConfigs{Revision: rev}, nil }
go
func (r *ImportDelegationConfigsRPC) ImportDelegationConfigs(c context.Context, _ *empty.Empty) (*admin.ImportedConfigs, error) { rev, err := r.RulesCache.ImportConfigs(c) if err != nil { logging.WithError(err).Errorf(c, "Failed to fetch delegation configs") return nil, status.Errorf(codes.Internal, err.Error()) } return &admin.ImportedConfigs{Revision: rev}, nil }
[ "func", "(", "r", "*", "ImportDelegationConfigsRPC", ")", "ImportDelegationConfigs", "(", "c", "context", ".", "Context", ",", "_", "*", "empty", ".", "Empty", ")", "(", "*", "admin", ".", "ImportedConfigs", ",", "error", ")", "{", "rev", ",", "err", ":=...
// ImportDelegationConfigs fetches configs from from luci-config right now.
[ "ImportDelegationConfigs", "fetches", "configs", "from", "from", "luci", "-", "config", "right", "now", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/rpc_import_delegation_configs.go#L36-L43
8,364
luci/luci-go
machine-db/client/cli/ips.go
printIPs
func printIPs(tsv bool, ips ...*crimson.IP) { if len(ips) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("IPv4", "VLAN", "Hostname") } for _, ip := range ips { p.Row(ip.Ipv4, ip.Vlan, ip.Hostname) } } }
go
func printIPs(tsv bool, ips ...*crimson.IP) { if len(ips) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("IPv4", "VLAN", "Hostname") } for _, ip := range ips { p.Row(ip.Ipv4, ip.Vlan, ip.Hostname) } } }
[ "func", "printIPs", "(", "tsv", "bool", ",", "ips", "...", "*", "crimson", ".", "IP", ")", "{", "if", "len", "(", "ips", ")", ">", "0", "{", "p", ":=", "newStdoutPrinter", "(", "tsv", ")", "\n", "defer", "p", ".", "Flush", "(", ")", "\n", "if",...
// printIPs prints IP address data to stdout in tab-separated columns.
[ "printIPs", "prints", "IP", "address", "data", "to", "stdout", "in", "tab", "-", "separated", "columns", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/ips.go#L28-L39
8,365
luci/luci-go
machine-db/client/cli/ips.go
Run
func (c *GetIPsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListFreeIPs(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printIPs(c.f.tsv, resp.Ips...) return 0 }
go
func (c *GetIPsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListFreeIPs(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printIPs(c.f.tsv, resp.Ips...) return 0 }
[ "func", "(", "c", "*", "GetIPsCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ","...
// Run runs the command to get free IP addresses.
[ "Run", "runs", "the", "command", "to", "get", "free", "IP", "addresses", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/ips.go#L48-L58
8,366
luci/luci-go
machine-db/client/cli/ips.go
getIPsCmd
func getIPsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-ips -vlan <id> [-n <limit>]", ShortDesc: "retrieves free IPs", LongDesc: "Retrieves free IP addresses on the given VLAN.\n\nExample to get 20 free IPs in VLAN 001:\ncrimson get-ips -vlan 001 -n 20", CommandRun: func() subcommands.CommandRun { cmd := &GetIPsCmd{} cmd.Initialize(params) cmd.Flags.Int64Var(&cmd.req.Vlan, "vlan", 0, "VLAN to get free IP addresses on.") cmd.Flags.Var(flag.Int32(&cmd.req.PageSize), "n", "The number of free IP addresses to get.") return cmd }, } }
go
func getIPsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-ips -vlan <id> [-n <limit>]", ShortDesc: "retrieves free IPs", LongDesc: "Retrieves free IP addresses on the given VLAN.\n\nExample to get 20 free IPs in VLAN 001:\ncrimson get-ips -vlan 001 -n 20", CommandRun: func() subcommands.CommandRun { cmd := &GetIPsCmd{} cmd.Initialize(params) cmd.Flags.Int64Var(&cmd.req.Vlan, "vlan", 0, "VLAN to get free IP addresses on.") cmd.Flags.Var(flag.Int32(&cmd.req.PageSize), "n", "The number of free IP addresses to get.") return cmd }, } }
[ "func", "getIPsCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", ...
// getIPsCmd returns a command to get free IP addresses.
[ "getIPsCmd", "returns", "a", "command", "to", "get", "free", "IP", "addresses", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/ips.go#L61-L74
8,367
luci/luci-go
logdog/client/annotee/processor.go
New
func New(c context.Context, o Options) *Processor { p := Processor{ ctx: c, o: &o, stepHandlers: make(map[*annotation.Step]*stepHandler), } p.astate = &annotation.State{ LogNameBase: o.Base, Callbacks: &annotationCallbacks{&p}, Execution: o.Execution, Clock: clock.Get(c), Offline: o.Offline, } return &p }
go
func New(c context.Context, o Options) *Processor { p := Processor{ ctx: c, o: &o, stepHandlers: make(map[*annotation.Step]*stepHandler), } p.astate = &annotation.State{ LogNameBase: o.Base, Callbacks: &annotationCallbacks{&p}, Execution: o.Execution, Clock: clock.Get(c), Offline: o.Offline, } return &p }
[ "func", "New", "(", "c", "context", ".", "Context", ",", "o", "Options", ")", "*", "Processor", "{", "p", ":=", "Processor", "{", "ctx", ":", "c", ",", "o", ":", "&", "o", ",", "stepHandlers", ":", "make", "(", "map", "[", "*", "annotation", ".",...
// New instantiates a new Processor.
[ "New", "instantiates", "a", "new", "Processor", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/processor.go#L169-L184
8,368
luci/luci-go
logdog/client/annotee/processor.go
initialize
func (p *Processor) initialize() (err error) { // If we're already initialized, do nothing. if p.annotationStream != nil { return nil } annotationPath := p.o.AnnotationSubpath if annotationPath == "" { annotationPath = DefaultAnnotationSubpath } annotationPath = p.astate.RootStep().BaseStream(annotationPath) // Create our annotation stream. if p.annotationStream, err = p.createStream(annotationPath, &metadataStreamArchetype); err != nil { log.WithError(err).Errorf(p.ctx, "Failed to create annotation stream.") return } // Complete initialization and start our annotation meter. p.annotationC = make(chan annotationSignal) p.annotationFinishedC = make(chan struct{}) p.allEmittedStreams = map[*Stream]struct{}{} // Run our annotation meter in a separate goroutine. go p.runAnnotationMeter(p.annotationStream, p.o.MetadataUpdateInterval) return nil }
go
func (p *Processor) initialize() (err error) { // If we're already initialized, do nothing. if p.annotationStream != nil { return nil } annotationPath := p.o.AnnotationSubpath if annotationPath == "" { annotationPath = DefaultAnnotationSubpath } annotationPath = p.astate.RootStep().BaseStream(annotationPath) // Create our annotation stream. if p.annotationStream, err = p.createStream(annotationPath, &metadataStreamArchetype); err != nil { log.WithError(err).Errorf(p.ctx, "Failed to create annotation stream.") return } // Complete initialization and start our annotation meter. p.annotationC = make(chan annotationSignal) p.annotationFinishedC = make(chan struct{}) p.allEmittedStreams = map[*Stream]struct{}{} // Run our annotation meter in a separate goroutine. go p.runAnnotationMeter(p.annotationStream, p.o.MetadataUpdateInterval) return nil }
[ "func", "(", "p", "*", "Processor", ")", "initialize", "(", ")", "(", "err", "error", ")", "{", "// If we're already initialized, do nothing.", "if", "p", ".", "annotationStream", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "annotationPath", ":=", ...
// initialize initializes p's annotation stream handling system. If it is called // more than once, it is a no-op.
[ "initialize", "initializes", "p", "s", "annotation", "stream", "handling", "system", ".", "If", "it", "is", "called", "more", "than", "once", "it", "is", "a", "no", "-", "op", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/processor.go#L188-L214
8,369
luci/luci-go
logdog/client/annotee/processor.go
RunStreams
func (p *Processor) RunStreams(streams []*Stream) error { ingestMu := sync.Mutex{} ingest := func(s *Stream, l string) error { ingestMu.Lock() defer ingestMu.Unlock() return p.IngestLine(s, l) } // Read from all configured streams until they are finished. return parallel.FanOutIn(func(taskC chan<- func() error) { for _, s := range streams { s := s bufferSize := s.BufferSize if bufferSize <= 0 { bufferSize = DefaultBufferSize } taskC <- func() error { lr := newLineReader(s.Reader, bufferSize) for { line, err := lr.readLine() if err != nil { if err == io.EOF { return nil } return err } if err := ingest(s, line); err != nil { log.Fields{ log.ErrorKey: err, "stream": s.Name, "line": line, }.Errorf(p.ctx, "Failed to ingest line.") } } } } }) }
go
func (p *Processor) RunStreams(streams []*Stream) error { ingestMu := sync.Mutex{} ingest := func(s *Stream, l string) error { ingestMu.Lock() defer ingestMu.Unlock() return p.IngestLine(s, l) } // Read from all configured streams until they are finished. return parallel.FanOutIn(func(taskC chan<- func() error) { for _, s := range streams { s := s bufferSize := s.BufferSize if bufferSize <= 0 { bufferSize = DefaultBufferSize } taskC <- func() error { lr := newLineReader(s.Reader, bufferSize) for { line, err := lr.readLine() if err != nil { if err == io.EOF { return nil } return err } if err := ingest(s, line); err != nil { log.Fields{ log.ErrorKey: err, "stream": s.Name, "line": line, }.Errorf(p.ctx, "Failed to ingest line.") } } } } }) }
[ "func", "(", "p", "*", "Processor", ")", "RunStreams", "(", "streams", "[", "]", "*", "Stream", ")", "error", "{", "ingestMu", ":=", "sync", ".", "Mutex", "{", "}", "\n", "ingest", ":=", "func", "(", "s", "*", "Stream", ",", "l", "string", ")", "...
// RunStreams executes the Processor, consuming data from its configured streams // and forwarding it to LogDog. Run will block until all streams have // terminated. // // If a stream terminates with an error, or if there is an error processing the // stream data, Run will return an error. If multiple Streams fail with errors, // an errors.MultiError will be returned. io.EOF does not count as an error.
[ "RunStreams", "executes", "the", "Processor", "consuming", "data", "from", "its", "configured", "streams", "and", "forwarding", "it", "to", "LogDog", ".", "Run", "will", "block", "until", "all", "streams", "have", "terminated", ".", "If", "a", "stream", "termi...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/processor.go#L223-L261
8,370
luci/luci-go
logdog/client/annotee/processor.go
Finish
func (p *Processor) Finish() *annotation.State { // Finish our step handlers. var closeTime *timestamp.Timestamp if !p.astate.Offline { // Note: p.astate.Clock is never nil here, see astate setup in New(). closeTime = google.NewTimestamp(p.astate.Clock.Now()) } for _, h := range p.stepHandlers { p.finishStepHandler(h, p.o.CloseSteps, closeTime) } // If we're initialized, shut down our annotation handling. if p.annotationStream != nil { // Close and reap our annotation meter goroutine. close(p.annotationC) <-p.annotationFinishedC // Close and destruct our annotation stream. if err := p.annotationStream.Close(); err != nil { log.WithError(err).Errorf(p.ctx, "Failed to close annotation stream.") } p.annotationStream = nil } return p.astate }
go
func (p *Processor) Finish() *annotation.State { // Finish our step handlers. var closeTime *timestamp.Timestamp if !p.astate.Offline { // Note: p.astate.Clock is never nil here, see astate setup in New(). closeTime = google.NewTimestamp(p.astate.Clock.Now()) } for _, h := range p.stepHandlers { p.finishStepHandler(h, p.o.CloseSteps, closeTime) } // If we're initialized, shut down our annotation handling. if p.annotationStream != nil { // Close and reap our annotation meter goroutine. close(p.annotationC) <-p.annotationFinishedC // Close and destruct our annotation stream. if err := p.annotationStream.Close(); err != nil { log.WithError(err).Errorf(p.ctx, "Failed to close annotation stream.") } p.annotationStream = nil } return p.astate }
[ "func", "(", "p", "*", "Processor", ")", "Finish", "(", ")", "*", "annotation", ".", "State", "{", "// Finish our step handlers.", "var", "closeTime", "*", "timestamp", ".", "Timestamp", "\n", "if", "!", "p", ".", "astate", ".", "Offline", "{", "// Note: p...
// Finish instructs the Processor to close any outstanding state. This should be // called when all automatic state updates have completed in case any steps // didn't properly close their state. // // Finish will return the closed annotation state that was accumulated during // processing.
[ "Finish", "instructs", "the", "Processor", "to", "close", "any", "outstanding", "state", ".", "This", "should", "be", "called", "when", "all", "automatic", "state", "updates", "have", "completed", "in", "case", "any", "steps", "didn", "t", "properly", "close",...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/processor.go#L425-L450
8,371
luci/luci-go
tokenserver/appengine/impl/delegation/token.go
SignToken
func SignToken(c context.Context, signer signing.Signer, subtok *messages.Subtoken) (string, error) { s := tokensigning.Signer{ Signer: signer, SigningContext: tokenSigningContext, Wrap: func(w *tokensigning.Unwrapped) proto.Message { return &messages.DelegationToken{ SerializedSubtoken: w.Body, Pkcs1Sha256Sig: w.RsaSHA256Sig, SignerId: "user:" + w.SignerID, SigningKeyId: w.KeyID, } }, } return s.SignToken(c, subtok) }
go
func SignToken(c context.Context, signer signing.Signer, subtok *messages.Subtoken) (string, error) { s := tokensigning.Signer{ Signer: signer, SigningContext: tokenSigningContext, Wrap: func(w *tokensigning.Unwrapped) proto.Message { return &messages.DelegationToken{ SerializedSubtoken: w.Body, Pkcs1Sha256Sig: w.RsaSHA256Sig, SignerId: "user:" + w.SignerID, SigningKeyId: w.KeyID, } }, } return s.SignToken(c, subtok) }
[ "func", "SignToken", "(", "c", "context", ".", "Context", ",", "signer", "signing", ".", "Signer", ",", "subtok", "*", "messages", ".", "Subtoken", ")", "(", "string", ",", "error", ")", "{", "s", ":=", "tokensigning", ".", "Signer", "{", "Signer", ":"...
// SignToken signs and serializes the delegation subtoken. // // It doesn't do any validation. Assumes the prepared subtoken is valid. // // Produces base64 URL-safe token or a transient error.
[ "SignToken", "signs", "and", "serializes", "the", "delegation", "subtoken", ".", "It", "doesn", "t", "do", "any", "validation", ".", "Assumes", "the", "prepared", "subtoken", "is", "valid", ".", "Produces", "base64", "URL", "-", "safe", "token", "or", "a", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/token.go#L43-L57
8,372
luci/luci-go
dm/appengine/distributor/pubsub.go
PubsubReceiver
func PubsubReceiver(ctx *router.Context) { c, rw, r := ctx.Context, ctx.Writer, ctx.Request defer r.Body.Close() type PubsubMessage struct { Attributes map[string]string `json:"attributes"` Data []byte `json:"data"` MessageID string `json:"message_id"` } type PubsubPushMessage struct { Message PubsubMessage `json:"message"` Subscription string `json:"subscription"` } psm := &PubsubPushMessage{} if err := json.NewDecoder(r.Body).Decode(psm); err != nil { logging.WithError(err).Errorf(c, "Failed to parse pubsub message") http.Error(rw, "Failed to parse pubsub message", http.StatusInternalServerError) return } eid, cfgName, err := decodeAuthToken(c, psm.Message.Attributes["auth_token"]) if err != nil { logging.WithError(err).Errorf(c, "bad auth_token") // Acknowledge this message, since it'll never be valid. rw.WriteHeader(http.StatusNoContent) return } // remove "auth_token" from Attributes to avoid having it pass to the // distributor. delete(psm.Message.Attributes, "auth_token") err = tumble.RunMutation(c, &NotifyExecution{ cfgName, &Notification{eid, psm.Message.Data, psm.Message.Attributes}, }) if err != nil { // TODO(riannucci): distinguish between transient/non-transient failures. logging.WithError(err).Errorf(c, "failed to NotifyExecution") rw.WriteHeader(http.StatusInternalServerError) return } rw.WriteHeader(http.StatusNoContent) }
go
func PubsubReceiver(ctx *router.Context) { c, rw, r := ctx.Context, ctx.Writer, ctx.Request defer r.Body.Close() type PubsubMessage struct { Attributes map[string]string `json:"attributes"` Data []byte `json:"data"` MessageID string `json:"message_id"` } type PubsubPushMessage struct { Message PubsubMessage `json:"message"` Subscription string `json:"subscription"` } psm := &PubsubPushMessage{} if err := json.NewDecoder(r.Body).Decode(psm); err != nil { logging.WithError(err).Errorf(c, "Failed to parse pubsub message") http.Error(rw, "Failed to parse pubsub message", http.StatusInternalServerError) return } eid, cfgName, err := decodeAuthToken(c, psm.Message.Attributes["auth_token"]) if err != nil { logging.WithError(err).Errorf(c, "bad auth_token") // Acknowledge this message, since it'll never be valid. rw.WriteHeader(http.StatusNoContent) return } // remove "auth_token" from Attributes to avoid having it pass to the // distributor. delete(psm.Message.Attributes, "auth_token") err = tumble.RunMutation(c, &NotifyExecution{ cfgName, &Notification{eid, psm.Message.Data, psm.Message.Attributes}, }) if err != nil { // TODO(riannucci): distinguish between transient/non-transient failures. logging.WithError(err).Errorf(c, "failed to NotifyExecution") rw.WriteHeader(http.StatusInternalServerError) return } rw.WriteHeader(http.StatusNoContent) }
[ "func", "PubsubReceiver", "(", "ctx", "*", "router", ".", "Context", ")", "{", "c", ",", "rw", ",", "r", ":=", "ctx", ".", "Context", ",", "ctx", ".", "Writer", ",", "ctx", ".", "Request", "\n", "defer", "r", ".", "Body", ".", "Close", "(", ")", ...
// PubsubReceiver is the HTTP handler that processes incoming pubsub events // delivered to topics prepared with TaskDescription.PrepareTopic, and routes // them to the appropriate distributor implementation's HandleNotification // method. // // It requires that a Registry be installed in c via WithRegistry.
[ "PubsubReceiver", "is", "the", "HTTP", "handler", "that", "processes", "incoming", "pubsub", "events", "delivered", "to", "topics", "prepared", "with", "TaskDescription", ".", "PrepareTopic", "and", "routes", "them", "to", "the", "appropriate", "distributor", "imple...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/pubsub.go#L40-L84
8,373
luci/luci-go
config/validation/handler.go
InstallHandlers
func InstallHandlers(r *router.Router, base router.MiddlewareChain, rules *RuleSet) { r.GET(metadataPath, base, metadataRequestHandler(rules)) r.POST(validationPath, base, validationRequestHandler(rules)) }
go
func InstallHandlers(r *router.Router, base router.MiddlewareChain, rules *RuleSet) { r.GET(metadataPath, base, metadataRequestHandler(rules)) r.POST(validationPath, base, validationRequestHandler(rules)) }
[ "func", "InstallHandlers", "(", "r", "*", "router", ".", "Router", ",", "base", "router", ".", "MiddlewareChain", ",", "rules", "*", "RuleSet", ")", "{", "r", ".", "GET", "(", "metadataPath", ",", "base", ",", "metadataRequestHandler", "(", "rules", ")", ...
// InstallHandlers installs the metadata and validation handlers that use // the given validation rules. // // It does not implement any authentication checks, thus the passed in // router.MiddlewareChain should implement any necessary authentication checks.
[ "InstallHandlers", "installs", "the", "metadata", "and", "validation", "handlers", "that", "use", "the", "given", "validation", "rules", ".", "It", "does", "not", "implement", "any", "authentication", "checks", "thus", "the", "passed", "in", "router", ".", "Midd...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/handler.go#L44-L47
8,374
luci/luci-go
config/validation/handler.go
validationRequestHandler
func validationRequestHandler(rules *RuleSet) router.Handler { return func(ctx *router.Context) { c, w, r := ctx.Context, ctx.Writer, ctx.Request var reqBody config.ValidationRequestMessage switch err := json.NewDecoder(r.Body).Decode(&reqBody); { case err != nil: badRequestStatus(c, w, "Validation: error decoding request body", err) return case reqBody.GetConfigSet() == "": badRequestStatus(c, w, "Must specify the config_set of the file to validate", nil) return case reqBody.GetPath() == "": badRequestStatus(c, w, "Must specify the path of the file to validate", nil) return } vc := &Context{Context: c} vc.SetFile(reqBody.GetPath()) err := rules.ValidateConfig(vc, reqBody.GetConfigSet(), reqBody.GetPath(), reqBody.GetContent()) if err != nil { internalErrStatus(c, w, "Validation: transient failure", err) return } w.Header().Set("Content-Type", "application/json") var msgList []*config.ValidationResponseMessage_Message if len(vc.errors) == 0 { logging.Infof(c, "No validation errors") } else { var errorBuffer bytes.Buffer for _, error := range vc.errors { // validation.Context currently only supports ERROR severity err := error.Error() msgList = append(msgList, &config.ValidationResponseMessage_Message{ Severity: config.ValidationResponseMessage_ERROR, Text: err, }) errorBuffer.WriteString("\n " + err) } logging.Warningf(c, "Validation errors%s", errorBuffer.String()) } if err := json.NewEncoder(w).Encode(config.ValidationResponseMessage{Messages: msgList}); err != nil { internalErrStatus(c, w, "Validation: failed to JSON encode output", err) } } }
go
func validationRequestHandler(rules *RuleSet) router.Handler { return func(ctx *router.Context) { c, w, r := ctx.Context, ctx.Writer, ctx.Request var reqBody config.ValidationRequestMessage switch err := json.NewDecoder(r.Body).Decode(&reqBody); { case err != nil: badRequestStatus(c, w, "Validation: error decoding request body", err) return case reqBody.GetConfigSet() == "": badRequestStatus(c, w, "Must specify the config_set of the file to validate", nil) return case reqBody.GetPath() == "": badRequestStatus(c, w, "Must specify the path of the file to validate", nil) return } vc := &Context{Context: c} vc.SetFile(reqBody.GetPath()) err := rules.ValidateConfig(vc, reqBody.GetConfigSet(), reqBody.GetPath(), reqBody.GetContent()) if err != nil { internalErrStatus(c, w, "Validation: transient failure", err) return } w.Header().Set("Content-Type", "application/json") var msgList []*config.ValidationResponseMessage_Message if len(vc.errors) == 0 { logging.Infof(c, "No validation errors") } else { var errorBuffer bytes.Buffer for _, error := range vc.errors { // validation.Context currently only supports ERROR severity err := error.Error() msgList = append(msgList, &config.ValidationResponseMessage_Message{ Severity: config.ValidationResponseMessage_ERROR, Text: err, }) errorBuffer.WriteString("\n " + err) } logging.Warningf(c, "Validation errors%s", errorBuffer.String()) } if err := json.NewEncoder(w).Encode(config.ValidationResponseMessage{Messages: msgList}); err != nil { internalErrStatus(c, w, "Validation: failed to JSON encode output", err) } } }
[ "func", "validationRequestHandler", "(", "rules", "*", "RuleSet", ")", "router", ".", "Handler", "{", "return", "func", "(", "ctx", "*", "router", ".", "Context", ")", "{", "c", ",", "w", ",", "r", ":=", "ctx", ".", "Context", ",", "ctx", ".", "Write...
// validationRequestHandler handles the validation request from luci-config and // responds with the corresponding results.
[ "validationRequestHandler", "handles", "the", "validation", "request", "from", "luci", "-", "config", "and", "responds", "with", "the", "corresponding", "results", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/handler.go#L67-L113
8,375
luci/luci-go
config/validation/handler.go
metadataRequestHandler
func metadataRequestHandler(rules *RuleSet) router.Handler { return func(ctx *router.Context) { c, w := ctx.Context, ctx.Writer patterns, err := rules.ConfigPatterns(c) if err != nil { internalErrStatus(c, w, "Metadata: failed to collect the list of validation patterns", err) return } meta := config.ServiceDynamicMetadata{ Version: metaDataFormatVersion, Validation: &config.Validator{ Url: fmt.Sprintf("https://%s%s", ctx.Request.URL.Host, validationPath), }, } for _, p := range patterns { meta.Validation.Patterns = append(meta.Validation.Patterns, &config.ConfigPattern{ ConfigSet: p.ConfigSet.String(), Path: p.Path.String(), }) } w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(&meta); err != nil { internalErrStatus(c, w, "Metadata: failed to JSON encode output", err) } } }
go
func metadataRequestHandler(rules *RuleSet) router.Handler { return func(ctx *router.Context) { c, w := ctx.Context, ctx.Writer patterns, err := rules.ConfigPatterns(c) if err != nil { internalErrStatus(c, w, "Metadata: failed to collect the list of validation patterns", err) return } meta := config.ServiceDynamicMetadata{ Version: metaDataFormatVersion, Validation: &config.Validator{ Url: fmt.Sprintf("https://%s%s", ctx.Request.URL.Host, validationPath), }, } for _, p := range patterns { meta.Validation.Patterns = append(meta.Validation.Patterns, &config.ConfigPattern{ ConfigSet: p.ConfigSet.String(), Path: p.Path.String(), }) } w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(&meta); err != nil { internalErrStatus(c, w, "Metadata: failed to JSON encode output", err) } } }
[ "func", "metadataRequestHandler", "(", "rules", "*", "RuleSet", ")", "router", ".", "Handler", "{", "return", "func", "(", "ctx", "*", "router", ".", "Context", ")", "{", "c", ",", "w", ":=", "ctx", ".", "Context", ",", "ctx", ".", "Writer", "\n\n", ...
// metadataRequestHandler handles the metadata request from luci-config and // responds with the necessary metadata defined by the given Validator.
[ "metadataRequestHandler", "handles", "the", "metadata", "request", "from", "luci", "-", "config", "and", "responds", "with", "the", "necessary", "metadata", "defined", "by", "the", "given", "Validator", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/handler.go#L117-L145
8,376
luci/luci-go
cipd/appengine/ui/metadata.go
fetchMetadata
func fetchMetadata(c context.Context, pfx string) (*metadataBlock, error) { meta, err := impl.PublicRepo.GetInheritedPrefixMetadata(c, &api.PrefixRequest{ Prefix: pfx, }) switch grpc.Code(err) { case codes.OK: break // handled below case codes.PermissionDenied: return fetchCallerRoles(c, pfx) default: return nil, err } // Grab URL of an auth server with the groups, if available. groupsURL := "" if url, err := auth.GetState(c).DB().GetAuthServiceURL(c); err == nil { groupsURL = url + "/auth/groups/" } out := &metadataBlock{CanView: true} for _, m := range meta.PerPrefixMetadata { for _, a := range m.Acls { role := strings.Title(strings.ToLower(a.Role.String())) prefix := m.Prefix if prefix == "" { prefix = "[root]" } for _, p := range a.Principals { whoHref := "" switch { case strings.HasPrefix(p, "group:"): p = strings.TrimPrefix(p, "group:") if groupsURL != "" { whoHref = groupsURL + p } case p == string(identity.AnonymousIdentity): p = "anonymous" default: p = strings.TrimPrefix(p, "user:") } out.ACLs = append(out.ACLs, metadataACL{ RolePb: a.Role, Role: role, Who: p, WhoHref: whoHref, Prefix: prefix, PrefixHref: prefixPageURL(m.Prefix), }) } } } sort.Slice(out.ACLs, func(i, j int) bool { l, r := out.ACLs[i], out.ACLs[j] if l.RolePb != r.RolePb { return l.RolePb > r.RolePb // "stronger" role (e.g. OWNERS) first } if l.Prefix != r.Prefix { return l.Prefix > r.Prefix // longer prefix first } return l.Who < r.Who // alphabetically }) return out, nil }
go
func fetchMetadata(c context.Context, pfx string) (*metadataBlock, error) { meta, err := impl.PublicRepo.GetInheritedPrefixMetadata(c, &api.PrefixRequest{ Prefix: pfx, }) switch grpc.Code(err) { case codes.OK: break // handled below case codes.PermissionDenied: return fetchCallerRoles(c, pfx) default: return nil, err } // Grab URL of an auth server with the groups, if available. groupsURL := "" if url, err := auth.GetState(c).DB().GetAuthServiceURL(c); err == nil { groupsURL = url + "/auth/groups/" } out := &metadataBlock{CanView: true} for _, m := range meta.PerPrefixMetadata { for _, a := range m.Acls { role := strings.Title(strings.ToLower(a.Role.String())) prefix := m.Prefix if prefix == "" { prefix = "[root]" } for _, p := range a.Principals { whoHref := "" switch { case strings.HasPrefix(p, "group:"): p = strings.TrimPrefix(p, "group:") if groupsURL != "" { whoHref = groupsURL + p } case p == string(identity.AnonymousIdentity): p = "anonymous" default: p = strings.TrimPrefix(p, "user:") } out.ACLs = append(out.ACLs, metadataACL{ RolePb: a.Role, Role: role, Who: p, WhoHref: whoHref, Prefix: prefix, PrefixHref: prefixPageURL(m.Prefix), }) } } } sort.Slice(out.ACLs, func(i, j int) bool { l, r := out.ACLs[i], out.ACLs[j] if l.RolePb != r.RolePb { return l.RolePb > r.RolePb // "stronger" role (e.g. OWNERS) first } if l.Prefix != r.Prefix { return l.Prefix > r.Prefix // longer prefix first } return l.Who < r.Who // alphabetically }) return out, nil }
[ "func", "fetchMetadata", "(", "c", "context", ".", "Context", ",", "pfx", "string", ")", "(", "*", "metadataBlock", ",", "error", ")", "{", "meta", ",", "err", ":=", "impl", ".", "PublicRepo", ".", "GetInheritedPrefixMetadata", "(", "c", ",", "&", "api",...
// fetchMetadata fetches and formats for UI metadata of the given prefix. // // It recognizes PermissionDenied errors and falls back to only displaying what // roles the caller has instead of the full metadata.
[ "fetchMetadata", "fetches", "and", "formats", "for", "UI", "metadata", "of", "the", "given", "prefix", ".", "It", "recognizes", "PermissionDenied", "errors", "and", "falls", "back", "to", "only", "displaying", "what", "roles", "the", "caller", "has", "instead", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/ui/metadata.go#L61-L128
8,377
luci/luci-go
scheduler/appengine/task/utils/apiclient.go
IsTransientAPIError
func IsTransientAPIError(err error) bool { if err == nil { return false } apiErr, _ := err.(*googleapi.Error) if apiErr == nil { return true // failed to get HTTP code => connectivity error => transient } return apiErr.Code >= 500 || apiErr.Code == 429 || apiErr.Code == 0 }
go
func IsTransientAPIError(err error) bool { if err == nil { return false } apiErr, _ := err.(*googleapi.Error) if apiErr == nil { return true // failed to get HTTP code => connectivity error => transient } return apiErr.Code >= 500 || apiErr.Code == 429 || apiErr.Code == 0 }
[ "func", "IsTransientAPIError", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n", "apiErr", ",", "_", ":=", "err", ".", "(", "*", "googleapi", ".", "Error", ")", "\n", "if", "apiErr", "==", "ni...
// IsTransientAPIError returns true if error from Google API client indicates // an error that can go away on its own in the future.
[ "IsTransientAPIError", "returns", "true", "if", "error", "from", "Google", "API", "client", "indicates", "an", "error", "that", "can", "go", "away", "on", "its", "own", "in", "the", "future", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/utils/apiclient.go#L24-L33
8,378
luci/luci-go
scheduler/appengine/task/utils/apiclient.go
WrapAPIError
func WrapAPIError(err error) error { if IsTransientAPIError(err) { return transient.Tag.Apply(err) } return err }
go
func WrapAPIError(err error) error { if IsTransientAPIError(err) { return transient.Tag.Apply(err) } return err }
[ "func", "WrapAPIError", "(", "err", "error", ")", "error", "{", "if", "IsTransientAPIError", "(", "err", ")", "{", "return", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// WrapAPIError wraps error from Google API client in transient wrapper if // necessary.
[ "WrapAPIError", "wraps", "error", "from", "Google", "API", "client", "in", "transient", "wrapper", "if", "necessary", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/utils/apiclient.go#L37-L42
8,379
luci/luci-go
logdog/client/annotee/annotation/annotation.go
initialize
func (s *State) initialize() { if s.stepMap != nil { return } s.stepMap = map[string]*Step{} s.stepLookup = map[*milo.Step]*Step{} name := "steps" if s.Execution != nil { name = s.Execution.Name } s.rootStep.initializeStep(s, nil, name, false) s.rootStep.LogNameBase = s.LogNameBase s.SetCurrentStep(nil) // Add our Command parameters, if applicable. if exec := s.Execution; exec != nil { s.rootStep.Command = &milo.Step_Command{ CommandLine: exec.Command, Cwd: exec.Dir, Environ: exec.Env, } } var annotatedNow *timestamp.Timestamp if !s.Offline { annotatedNow = s.now() } s.rootStep.Start(annotatedNow) }
go
func (s *State) initialize() { if s.stepMap != nil { return } s.stepMap = map[string]*Step{} s.stepLookup = map[*milo.Step]*Step{} name := "steps" if s.Execution != nil { name = s.Execution.Name } s.rootStep.initializeStep(s, nil, name, false) s.rootStep.LogNameBase = s.LogNameBase s.SetCurrentStep(nil) // Add our Command parameters, if applicable. if exec := s.Execution; exec != nil { s.rootStep.Command = &milo.Step_Command{ CommandLine: exec.Command, Cwd: exec.Dir, Environ: exec.Env, } } var annotatedNow *timestamp.Timestamp if !s.Offline { annotatedNow = s.now() } s.rootStep.Start(annotatedNow) }
[ "func", "(", "s", "*", "State", ")", "initialize", "(", ")", "{", "if", "s", ".", "stepMap", "!=", "nil", "{", "return", "\n", "}", "\n\n", "s", ".", "stepMap", "=", "map", "[", "string", "]", "*", "Step", "{", "}", "\n", "s", ".", "stepLookup"...
// initialize sets of the State's initial state. It will execute exactly once, // and must be called by any State methods that access internal variables.
[ "initialize", "sets", "of", "the", "State", "s", "initial", "state", ".", "It", "will", "execute", "exactly", "once", "and", "must", "be", "called", "by", "any", "State", "methods", "that", "access", "internal", "variables", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L105-L135
8,380
luci/luci-go
logdog/client/annotee/annotation/annotation.go
LookupStepErr
func (s *State) LookupStepErr(name string) (*Step, error) { if as := s.LookupStep(name); as != nil { return as, nil } return nil, fmt.Errorf("no step named %q", name) }
go
func (s *State) LookupStepErr(name string) (*Step, error) { if as := s.LookupStep(name); as != nil { return as, nil } return nil, fmt.Errorf("no step named %q", name) }
[ "func", "(", "s", "*", "State", ")", "LookupStepErr", "(", "name", "string", ")", "(", "*", "Step", ",", "error", ")", "{", "if", "as", ":=", "s", ".", "LookupStep", "(", "name", ")", ";", "as", "!=", "nil", "{", "return", "as", ",", "nil", "\n...
// LookupStepErr returns the step with the supplied name, or an error if no // such step exists. // // If multiple steps share a name, this will return the latest registered step // with that name.
[ "LookupStepErr", "returns", "the", "step", "with", "the", "supplied", "name", "or", "an", "error", "if", "no", "such", "step", "exists", ".", "If", "multiple", "steps", "share", "a", "name", "this", "will", "return", "the", "latest", "registered", "step", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L484-L489
8,381
luci/luci-go
logdog/client/annotee/annotation/annotation.go
SetCurrentStep
func (s *State) SetCurrentStep(v *Step) { if v == nil { v = &s.rootStep } if v.s != s { panic("step is not bound to state") } s.stepCursor = v }
go
func (s *State) SetCurrentStep(v *Step) { if v == nil { v = &s.rootStep } if v.s != s { panic("step is not bound to state") } s.stepCursor = v }
[ "func", "(", "s", "*", "State", ")", "SetCurrentStep", "(", "v", "*", "Step", ")", "{", "if", "v", "==", "nil", "{", "v", "=", "&", "s", ".", "rootStep", "\n", "}", "\n", "if", "v", ".", "s", "!=", "s", "{", "panic", "(", "\"", "\"", ")", ...
// SetCurrentStep sets the current step. If the supplied step is nil, the root // step will be used. // // The supplied step must already be registered with the State.
[ "SetCurrentStep", "sets", "the", "current", "step", ".", "If", "the", "supplied", "step", "is", "nil", "the", "root", "step", "will", "be", "used", ".", "The", "supplied", "step", "must", "already", "be", "registered", "with", "the", "State", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L516-L524
8,382
luci/luci-go
logdog/client/annotee/annotation/annotation.go
now
func (s *State) now() *timestamp.Timestamp { c := s.Clock if c == nil { c = clock.GetSystemClock() } return google.NewTimestamp(c.Now()) }
go
func (s *State) now() *timestamp.Timestamp { c := s.Clock if c == nil { c = clock.GetSystemClock() } return google.NewTimestamp(c.Now()) }
[ "func", "(", "s", "*", "State", ")", "now", "(", ")", "*", "timestamp", ".", "Timestamp", "{", "c", ":=", "s", ".", "Clock", "\n", "if", "c", "==", "nil", "{", "c", "=", "clock", ".", "GetSystemClock", "(", ")", "\n", "}", "\n", "return", "goog...
// now returns current time of s.Clock. Defaults to system clock.
[ "now", "returns", "current", "time", "of", "s", ".", "Clock", ".", "Defaults", "to", "system", "clock", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L549-L555
8,383
luci/luci-go
logdog/client/annotee/annotation/annotation.go
AddStep
func (as *Step) AddStep(name string, legacy bool) *Step { return (&Step{}).initializeStep(as.s, as, name, legacy) }
go
func (as *Step) AddStep(name string, legacy bool) *Step { return (&Step{}).initializeStep(as.s, as, name, legacy) }
[ "func", "(", "as", "*", "Step", ")", "AddStep", "(", "name", "string", ",", "legacy", "bool", ")", "*", "Step", "{", "return", "(", "&", "Step", "{", "}", ")", ".", "initializeStep", "(", "as", ".", "s", ",", "as", ",", "name", ",", "legacy", "...
// AddStep generates a new substep.
[ "AddStep", "generates", "a", "new", "substep", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L693-L695
8,384
luci/luci-go
logdog/client/annotee/annotation/annotation.go
Start
func (as *Step) Start(startTime *timestamp.Timestamp) bool { if as.Started != nil { return false } as.Started = startTime return true }
go
func (as *Step) Start(startTime *timestamp.Timestamp) bool { if as.Started != nil { return false } as.Started = startTime return true }
[ "func", "(", "as", "*", "Step", ")", "Start", "(", "startTime", "*", "timestamp", ".", "Timestamp", ")", "bool", "{", "if", "as", ".", "Started", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "as", ".", "Started", "=", "startTime", "\n", "r...
// Start marks the Step as started.
[ "Start", "marks", "the", "Step", "as", "started", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L732-L738
8,385
luci/luci-go
logdog/client/annotee/annotation/annotation.go
Close
func (as *Step) Close(closeTime *timestamp.Timestamp) bool { return as.closeWithStatus(closeTime, nil) }
go
func (as *Step) Close(closeTime *timestamp.Timestamp) bool { return as.closeWithStatus(closeTime, nil) }
[ "func", "(", "as", "*", "Step", ")", "Close", "(", "closeTime", "*", "timestamp", ".", "Timestamp", ")", "bool", "{", "return", "as", ".", "closeWithStatus", "(", "closeTime", ",", "nil", ")", "\n", "}" ]
// Close closes this step and any outstanding resources that it owns. // If it is already closed, does not have side effects and returns false.
[ "Close", "closes", "this", "step", "and", "any", "outstanding", "resources", "that", "it", "owns", ".", "If", "it", "is", "already", "closed", "does", "not", "have", "side", "effects", "and", "returns", "false", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L742-L744
8,386
luci/luci-go
logdog/client/annotee/annotation/annotation.go
LogLine
func (as *Step) LogLine(label, line string) bool { updated := false name, ok := as.logLines[label] if !ok { // No entry for this log line. Create a new one and register it. // // This will appear as: // [BASE]/logs/[label]/[ord] subName, err := types.MakeStreamName("s_", "logs", label, strconv.Itoa(as.logLineCount[label])) if err != nil { panic(fmt.Errorf("failed to generate log stream name for [%s]: %s", label, err)) } name = as.BaseStream(subName) as.AddLogdogStreamLink("", label, "", name) as.logLines[label] = name as.logLineCount[label]++ updated = true } as.s.Callbacks.StepLogLine(as, name, label, line) return updated }
go
func (as *Step) LogLine(label, line string) bool { updated := false name, ok := as.logLines[label] if !ok { // No entry for this log line. Create a new one and register it. // // This will appear as: // [BASE]/logs/[label]/[ord] subName, err := types.MakeStreamName("s_", "logs", label, strconv.Itoa(as.logLineCount[label])) if err != nil { panic(fmt.Errorf("failed to generate log stream name for [%s]: %s", label, err)) } name = as.BaseStream(subName) as.AddLogdogStreamLink("", label, "", name) as.logLines[label] = name as.logLineCount[label]++ updated = true } as.s.Callbacks.StepLogLine(as, name, label, line) return updated }
[ "func", "(", "as", "*", "Step", ")", "LogLine", "(", "label", ",", "line", "string", ")", "bool", "{", "updated", ":=", "false", "\n\n", "name", ",", "ok", ":=", "as", ".", "logLines", "[", "label", "]", "\n", "if", "!", "ok", "{", "// No entry for...
// LogLine emits a log line for a specified log label.
[ "LogLine", "emits", "a", "log", "line", "for", "a", "specified", "log", "label", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L800-L823
8,387
luci/luci-go
logdog/client/annotee/annotation/annotation.go
LogEnd
func (as *Step) LogEnd(label string) { name, ok := as.logLines[label] if !ok { return } delete(as.logLines, label) as.s.Callbacks.StepLogEnd(as, name) }
go
func (as *Step) LogEnd(label string) { name, ok := as.logLines[label] if !ok { return } delete(as.logLines, label) as.s.Callbacks.StepLogEnd(as, name) }
[ "func", "(", "as", "*", "Step", ")", "LogEnd", "(", "label", "string", ")", "{", "name", ",", "ok", ":=", "as", ".", "logLines", "[", "label", "]", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "delete", "(", "as", ".", "logLines", "...
// LogEnd ends the log for the specified label.
[ "LogEnd", "ends", "the", "log", "for", "the", "specified", "label", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L826-L834
8,388
luci/luci-go
logdog/client/annotee/annotation/annotation.go
AddText
func (as *Step) AddText(text string) bool { as.Text = append(as.Text, text) return true }
go
func (as *Step) AddText(text string) bool { as.Text = append(as.Text, text) return true }
[ "func", "(", "as", "*", "Step", ")", "AddText", "(", "text", "string", ")", "bool", "{", "as", ".", "Text", "=", "append", "(", "as", ".", "Text", ",", "text", ")", "\n", "return", "true", "\n", "}" ]
// AddText adds a line of step component text.
[ "AddText", "adds", "a", "line", "of", "step", "component", "text", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L837-L840
8,389
luci/luci-go
logdog/client/annotee/annotation/annotation.go
ClearText
func (as *Step) ClearText() bool { if len(as.Text) == 0 { return false } as.Text = nil return true }
go
func (as *Step) ClearText() bool { if len(as.Text) == 0 { return false } as.Text = nil return true }
[ "func", "(", "as", "*", "Step", ")", "ClearText", "(", ")", "bool", "{", "if", "len", "(", "as", ".", "Text", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "as", ".", "Text", "=", "nil", "\n", "return", "true", "\n", "}" ]
// ClearText clears step component text.
[ "ClearText", "clears", "step", "component", "text", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L843-L849
8,390
luci/luci-go
logdog/client/annotee/annotation/annotation.go
SetSummary
func (as *Step) SetSummary(value string) bool { if as.hasSummary { if as.Text[0] == value { return false } as.Text[0] = value } else { as.Text = append(as.Text, "") copy(as.Text[1:], as.Text) as.Text[0] = value as.hasSummary = true } return true }
go
func (as *Step) SetSummary(value string) bool { if as.hasSummary { if as.Text[0] == value { return false } as.Text[0] = value } else { as.Text = append(as.Text, "") copy(as.Text[1:], as.Text) as.Text[0] = value as.hasSummary = true } return true }
[ "func", "(", "as", "*", "Step", ")", "SetSummary", "(", "value", "string", ")", "bool", "{", "if", "as", ".", "hasSummary", "{", "if", "as", ".", "Text", "[", "0", "]", "==", "value", "{", "return", "false", "\n", "}", "\n\n", "as", ".", "Text", ...
// SetSummary sets the Step's summary text. // // The summary is implemented as the first line of step component text. If no // summary is currently defined, one will be inserted; otherwise, the current // summary will be replaced.
[ "SetSummary", "sets", "the", "Step", "s", "summary", "text", ".", "The", "summary", "is", "implemented", "as", "the", "first", "line", "of", "step", "component", "text", ".", "If", "no", "summary", "is", "currently", "defined", "one", "will", "be", "insert...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L856-L870
8,391
luci/luci-go
logdog/client/annotee/annotation/annotation.go
ClearSummary
func (as *Step) ClearSummary() { if as.hasSummary { as.Text = as.Text[:copy(as.Text, as.Text[1:])] as.hasSummary = false } }
go
func (as *Step) ClearSummary() { if as.hasSummary { as.Text = as.Text[:copy(as.Text, as.Text[1:])] as.hasSummary = false } }
[ "func", "(", "as", "*", "Step", ")", "ClearSummary", "(", ")", "{", "if", "as", ".", "hasSummary", "{", "as", ".", "Text", "=", "as", ".", "Text", "[", ":", "copy", "(", "as", ".", "Text", ",", "as", ".", "Text", "[", "1", ":", "]", ")", "]...
// ClearSummary clears the step's summary text.
[ "ClearSummary", "clears", "the", "step", "s", "summary", "text", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L873-L878
8,392
luci/luci-go
logdog/client/annotee/annotation/annotation.go
SetNestLevel
func (as *Step) SetNestLevel(l int) bool { if as.level == l { return false } as.level = l // Attach this step to the correct parent step based on nest level. Ascend // up the previously-declared steps. var nestParent *Step for prev := as.prevStep; prev != nil; prev = prev.prevStep { if prev.level < l { nestParent = prev break } } if nestParent == nil || nestParent == as.parent { return true } nestParent.appendSubstep(as) return true }
go
func (as *Step) SetNestLevel(l int) bool { if as.level == l { return false } as.level = l // Attach this step to the correct parent step based on nest level. Ascend // up the previously-declared steps. var nestParent *Step for prev := as.prevStep; prev != nil; prev = prev.prevStep { if prev.level < l { nestParent = prev break } } if nestParent == nil || nestParent == as.parent { return true } nestParent.appendSubstep(as) return true }
[ "func", "(", "as", "*", "Step", ")", "SetNestLevel", "(", "l", "int", ")", "bool", "{", "if", "as", ".", "level", "==", "l", "{", "return", "false", "\n", "}", "\n", "as", ".", "level", "=", "l", "\n\n", "// Attach this step to the correct parent step ba...
// SetNestLevel sets the nest level of this Step, and identifies its nesting // parent. // // If no parent could be found at level "l-1", the root step will become the // parent.
[ "SetNestLevel", "sets", "the", "nest", "level", "of", "this", "Step", "and", "identifies", "its", "nesting", "parent", ".", "If", "no", "parent", "could", "be", "found", "at", "level", "l", "-", "1", "the", "root", "step", "will", "become", "the", "paren...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L885-L905
8,393
luci/luci-go
logdog/client/annotee/annotation/annotation.go
AddLogdogStreamLink
func (as *Step) AddLogdogStreamLink(server, label string, prefix, name types.StreamName) { link := as.getOrCreateLinkForLabel(label) link.Value = &milo.Link_LogdogStream{&milo.LogdogStream{ Name: string(name), Server: server, Prefix: string(prefix), }} }
go
func (as *Step) AddLogdogStreamLink(server, label string, prefix, name types.StreamName) { link := as.getOrCreateLinkForLabel(label) link.Value = &milo.Link_LogdogStream{&milo.LogdogStream{ Name: string(name), Server: server, Prefix: string(prefix), }} }
[ "func", "(", "as", "*", "Step", ")", "AddLogdogStreamLink", "(", "server", ",", "label", "string", ",", "prefix", ",", "name", "types", ".", "StreamName", ")", "{", "link", ":=", "as", ".", "getOrCreateLinkForLabel", "(", "label", ")", "\n", "link", ".",...
// AddLogdogStreamLink adds a LogDog stream link to this Step's links list.
[ "AddLogdogStreamLink", "adds", "a", "LogDog", "stream", "link", "to", "this", "Step", "s", "links", "list", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L908-L915
8,394
luci/luci-go
logdog/client/annotee/annotation/annotation.go
AddURLLink
func (as *Step) AddURLLink(label, alias, url string) { link := as.getOrCreateLinkForLabel(label) link.AliasLabel = alias link.Value = &milo.Link_Url{url} }
go
func (as *Step) AddURLLink(label, alias, url string) { link := as.getOrCreateLinkForLabel(label) link.AliasLabel = alias link.Value = &milo.Link_Url{url} }
[ "func", "(", "as", "*", "Step", ")", "AddURLLink", "(", "label", ",", "alias", ",", "url", "string", ")", "{", "link", ":=", "as", ".", "getOrCreateLinkForLabel", "(", "label", ")", "\n", "link", ".", "AliasLabel", "=", "alias", "\n", "link", ".", "V...
// AddURLLink adds a URL link to this Step's links list.
[ "AddURLLink", "adds", "a", "URL", "link", "to", "this", "Step", "s", "links", "list", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L918-L922
8,395
luci/luci-go
logdog/client/annotee/annotation/annotation.go
SetStatus
func (as *Step) SetStatus(s milo.Status, fd *milo.FailureDetails) bool { if as.closed || as.Status == s { return false } as.Status = s as.FailureDetails = fd return true }
go
func (as *Step) SetStatus(s milo.Status, fd *milo.FailureDetails) bool { if as.closed || as.Status == s { return false } as.Status = s as.FailureDetails = fd return true }
[ "func", "(", "as", "*", "Step", ")", "SetStatus", "(", "s", "milo", ".", "Status", ",", "fd", "*", "milo", ".", "FailureDetails", ")", "bool", "{", "if", "as", ".", "closed", "||", "as", ".", "Status", "==", "s", "{", "return", "false", "\n", "}"...
// SetStatus sets this step's component status. // // If the status doesn't change, the supplied failure details will be ignored.
[ "SetStatus", "sets", "this", "step", "s", "component", "status", ".", "If", "the", "status", "doesn", "t", "change", "the", "supplied", "failure", "details", "will", "be", "ignored", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L944-L951
8,396
luci/luci-go
logdog/client/annotee/annotation/annotation.go
SetSTDOUTStream
func (as *Step) SetSTDOUTStream(st *milo.LogdogStream) (updated bool) { as.StdoutStream, updated = as.maybeSetLogDogStream(as.StdoutStream, st) return }
go
func (as *Step) SetSTDOUTStream(st *milo.LogdogStream) (updated bool) { as.StdoutStream, updated = as.maybeSetLogDogStream(as.StdoutStream, st) return }
[ "func", "(", "as", "*", "Step", ")", "SetSTDOUTStream", "(", "st", "*", "milo", ".", "LogdogStream", ")", "(", "updated", "bool", ")", "{", "as", ".", "StdoutStream", ",", "updated", "=", "as", ".", "maybeSetLogDogStream", "(", "as", ".", "StdoutStream",...
// SetSTDOUTStream sets the LogDog STDOUT stream value, returning true if the // Step was updated.
[ "SetSTDOUTStream", "sets", "the", "LogDog", "STDOUT", "stream", "value", "returning", "true", "if", "the", "Step", "was", "updated", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L974-L977
8,397
luci/luci-go
logdog/client/annotee/annotation/annotation.go
SetSTDERRStream
func (as *Step) SetSTDERRStream(st *milo.LogdogStream) (updated bool) { as.StderrStream, updated = as.maybeSetLogDogStream(as.StderrStream, st) return }
go
func (as *Step) SetSTDERRStream(st *milo.LogdogStream) (updated bool) { as.StderrStream, updated = as.maybeSetLogDogStream(as.StderrStream, st) return }
[ "func", "(", "as", "*", "Step", ")", "SetSTDERRStream", "(", "st", "*", "milo", ".", "LogdogStream", ")", "(", "updated", "bool", ")", "{", "as", ".", "StderrStream", ",", "updated", "=", "as", ".", "maybeSetLogDogStream", "(", "as", ".", "StderrStream",...
// SetSTDERRStream sets the LogDog STDERR stream value, returning true if the // Step was updated.
[ "SetSTDERRStream", "sets", "the", "LogDog", "STDERR", "stream", "value", "returning", "true", "if", "the", "Step", "was", "updated", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/annotation/annotation.go#L981-L984
8,398
luci/luci-go
logdog/client/butlerproto/proto.go
readMetadata
func (r *Reader) readMetadata(fr recordio.Reader) error { data, err := fr.ReadFrameAll() if err != nil { return err } md := logpb.ButlerMetadata{} if err := proto.Unmarshal(data, &md); err != nil { return fmt.Errorf("butlerproto: failed to unmarshal Metadata frame: %s", err) } r.Metadata = &md return nil }
go
func (r *Reader) readMetadata(fr recordio.Reader) error { data, err := fr.ReadFrameAll() if err != nil { return err } md := logpb.ButlerMetadata{} if err := proto.Unmarshal(data, &md); err != nil { return fmt.Errorf("butlerproto: failed to unmarshal Metadata frame: %s", err) } r.Metadata = &md return nil }
[ "func", "(", "r", "*", "Reader", ")", "readMetadata", "(", "fr", "recordio", ".", "Reader", ")", "error", "{", "data", ",", "err", ":=", "fr", ".", "ReadFrameAll", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", ...
// ReadMetadata reads the metadata header frame.
[ "ReadMetadata", "reads", "the", "metadata", "header", "frame", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerproto/proto.go#L73-L85
8,399
luci/luci-go
logdog/client/butlerproto/proto.go
Write
func (w *Writer) Write(iw io.Writer, b *logpb.ButlerLogBundle) error { return w.WriteWith(recordio.NewWriter(iw), b) }
go
func (w *Writer) Write(iw io.Writer, b *logpb.ButlerLogBundle) error { return w.WriteWith(recordio.NewWriter(iw), b) }
[ "func", "(", "w", "*", "Writer", ")", "Write", "(", "iw", "io", ".", "Writer", ",", "b", "*", "logpb", ".", "ButlerLogBundle", ")", "error", "{", "return", "w", ".", "WriteWith", "(", "recordio", ".", "NewWriter", "(", "iw", ")", ",", "b", ")", "...
// WriteWith writes a ButlerLogBundle to the supplied Writer.
[ "WriteWith", "writes", "a", "ButlerLogBundle", "to", "the", "supplied", "Writer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerproto/proto.go#L256-L258