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,700
luci/luci-go
milo/buildsource/buildbot/buildstore/master.go
getLUCIBuilders
func getLUCIBuilders(c context.Context, master string) ([]string, error) { buildersResponse, err := buildbucket.GetBuilders(c) if err != nil { return nil, err } var result []string for _, bucket := range buildersResponse.Buckets { for _, builder := range bucket.Builders { if builder.PropertiesJson == "" { continue } var prop struct { Mastername string `json:"mastername"` } if err := json.Unmarshal([]byte(builder.PropertiesJson), &prop); err != nil { logging.WithError(err).Errorf(c, "processing %s/%s", bucket.Name, builder.Name) continue } if prop.Mastername == master { result = append(result, builder.Name) } } } return result, nil }
go
func getLUCIBuilders(c context.Context, master string) ([]string, error) { buildersResponse, err := buildbucket.GetBuilders(c) if err != nil { return nil, err } var result []string for _, bucket := range buildersResponse.Buckets { for _, builder := range bucket.Builders { if builder.PropertiesJson == "" { continue } var prop struct { Mastername string `json:"mastername"` } if err := json.Unmarshal([]byte(builder.PropertiesJson), &prop); err != nil { logging.WithError(err).Errorf(c, "processing %s/%s", bucket.Name, builder.Name) continue } if prop.Mastername == master { result = append(result, builder.Name) } } } return result, nil }
[ "func", "getLUCIBuilders", "(", "c", "context", ".", "Context", ",", "master", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "buildersResponse", ",", "err", ":=", "buildbucket", ".", "GetBuilders", "(", "c", ")", "\n", "if", "err", "!...
// getLUCIBuilders returns all LUCI builders for a given master from Swarmbucket. // LUCI builders do not have their own concept of "master". Instead, this is // inferred from the "mastername" property in the property JSON.
[ "getLUCIBuilders", "returns", "all", "LUCI", "builders", "for", "a", "given", "master", "from", "Swarmbucket", ".", "LUCI", "builders", "do", "not", "have", "their", "own", "concept", "of", "master", ".", "Instead", "this", "is", "inferred", "from", "the", "...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/master.go#L49-L74
8,701
luci/luci-go
milo/buildsource/buildbot/buildstore/master.go
AllMasters
func AllMasters(c context.Context, checkAccess bool) ([]*Master, error) { const batchSize = int32(500) masters := make([]*Master, 0, batchSize) q := datastore.NewQuery(masterKind) // note: avoid calling isAllowedInternal is checkAccess is false. // checkAccess is usually false in cron jobs where there is no auth state, // so isAllowedInternal call would unconditionally log an error. allowInternal := !checkAccess || isAllowedInternal(c) err := datastore.RunBatch(c, batchSize, q, func(e *masterEntity) error { if allowInternal || !e.Internal { m, err := e.decode(c) if err != nil { return err } masters = append(masters, m) } return nil }) return masters, err }
go
func AllMasters(c context.Context, checkAccess bool) ([]*Master, error) { const batchSize = int32(500) masters := make([]*Master, 0, batchSize) q := datastore.NewQuery(masterKind) // note: avoid calling isAllowedInternal is checkAccess is false. // checkAccess is usually false in cron jobs where there is no auth state, // so isAllowedInternal call would unconditionally log an error. allowInternal := !checkAccess || isAllowedInternal(c) err := datastore.RunBatch(c, batchSize, q, func(e *masterEntity) error { if allowInternal || !e.Internal { m, err := e.decode(c) if err != nil { return err } masters = append(masters, m) } return nil }) return masters, err }
[ "func", "AllMasters", "(", "c", "context", ".", "Context", ",", "checkAccess", "bool", ")", "(", "[", "]", "*", "Master", ",", "error", ")", "{", "const", "batchSize", "=", "int32", "(", "500", ")", "\n", "masters", ":=", "make", "(", "[", "]", "*"...
// AllMasters returns all buildbot masters.
[ "AllMasters", "returns", "all", "buildbot", "masters", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/master.go#L206-L226
8,702
luci/luci-go
milo/buildsource/buildbot/buildstore/master.go
GetPendingCounts
func GetPendingCounts(c context.Context, builders []string) ([]int, error) { entities := make([]builderEntity, len(builders)) for i, b := range builders { parts := strings.SplitN(b, "/", 2) if len(parts) < 2 { return nil, errors.Reason("builder does not have a slash: %q", b).Err() } entities[i].MasterKey = datastore.MakeKey(c, masterKind, parts[0]) entities[i].Name = parts[1] } if err := datastore.Get(c, entities); err != nil { for _, e := range err.(errors.MultiError) { if e != nil && e != datastore.ErrNoSuchEntity { return nil, err } } } counts := make([]int, len(entities)) for i, e := range entities { counts[i] = e.PendingCount } return counts, nil }
go
func GetPendingCounts(c context.Context, builders []string) ([]int, error) { entities := make([]builderEntity, len(builders)) for i, b := range builders { parts := strings.SplitN(b, "/", 2) if len(parts) < 2 { return nil, errors.Reason("builder does not have a slash: %q", b).Err() } entities[i].MasterKey = datastore.MakeKey(c, masterKind, parts[0]) entities[i].Name = parts[1] } if err := datastore.Get(c, entities); err != nil { for _, e := range err.(errors.MultiError) { if e != nil && e != datastore.ErrNoSuchEntity { return nil, err } } } counts := make([]int, len(entities)) for i, e := range entities { counts[i] = e.PendingCount } return counts, nil }
[ "func", "GetPendingCounts", "(", "c", "context", ".", "Context", ",", "builders", "[", "]", "string", ")", "(", "[", "]", "int", ",", "error", ")", "{", "entities", ":=", "make", "(", "[", "]", "builderEntity", ",", "len", "(", "builders", ")", ")", ...
// GetPendingCounts returns numbers of pending builds in builders. // builders must be a list of slash-separated master, builder names.
[ "GetPendingCounts", "returns", "numbers", "of", "pending", "builds", "in", "builders", ".", "builders", "must", "be", "a", "list", "of", "slash", "-", "separated", "master", "builder", "names", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/master.go#L230-L253
8,703
luci/luci-go
milo/buildsource/buildbot/buildstore/master.go
PutPendingCount
func PutPendingCount(c context.Context, master, builder string, count int) error { return datastore.Put(c, &builderEntity{ MasterKey: datastore.MakeKey(c, masterKind, master), Name: builder, PendingCount: count, }) }
go
func PutPendingCount(c context.Context, master, builder string, count int) error { return datastore.Put(c, &builderEntity{ MasterKey: datastore.MakeKey(c, masterKind, master), Name: builder, PendingCount: count, }) }
[ "func", "PutPendingCount", "(", "c", "context", ".", "Context", ",", "master", ",", "builder", "string", ",", "count", "int", ")", "error", "{", "return", "datastore", ".", "Put", "(", "c", ",", "&", "builderEntity", "{", "MasterKey", ":", "datastore", "...
// PutPendingCount persists number of pending builds to a builder. // Useful for testing.
[ "PutPendingCount", "persists", "number", "of", "pending", "builds", "to", "a", "builder", ".", "Useful", "for", "testing", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/master.go#L257-L263
8,704
luci/luci-go
milo/buildsource/buildbot/buildstore/master.go
SaveMaster
func SaveMaster(c context.Context, master *buildbot.Master, internal bool, expireCallback ExpireCallback) error { entity := &masterEntity{ Name: master.Name, Internal: internal, Modified: clock.Now(c).UTC(), } toPut := []interface{}{entity} for builderName, builder := range master.Builders { // Trim out extra info in the "Changes" portion of the pending build state, // we don't actually need comments, files, and properties for _, pbs := range builder.PendingBuildStates { for i := range pbs.Source.Changes { c := &pbs.Source.Changes[i] c.Comments = "" c.Files = nil c.Properties = nil } } toPut = append(toPut, &builderEntity{ MasterKey: datastore.KeyForObj(c, entity), Name: builderName, PendingCount: builder.PendingBuilds, }) } publicTag := &masterPublic{Name: master.Name} if internal { // do the deletion immediately so that the 'public' bit is removed from // datastore before any internal details are actually written to datastore. if err := datastore.Delete(c, publicTag); err != nil && err != datastore.ErrNoSuchEntity { return err } } else { toPut = append(toPut, publicTag) } var err error entity.Data, err = encode(master) if err != nil { return err } logging.Debugf(c, "Length of gzipped master data: %d", len(entity.Data)) if len(entity.Data) > maxDataSize { return errors.Reason("master data is %d bytes, which is more than %d limit", len(entity.Data), maxDataSize). Tag(TooBigTag). Err() } if err := datastore.Put(c, toPut); err != nil { return err } return cleanUpExpiredBuilds(c, master, expireCallback) }
go
func SaveMaster(c context.Context, master *buildbot.Master, internal bool, expireCallback ExpireCallback) error { entity := &masterEntity{ Name: master.Name, Internal: internal, Modified: clock.Now(c).UTC(), } toPut := []interface{}{entity} for builderName, builder := range master.Builders { // Trim out extra info in the "Changes" portion of the pending build state, // we don't actually need comments, files, and properties for _, pbs := range builder.PendingBuildStates { for i := range pbs.Source.Changes { c := &pbs.Source.Changes[i] c.Comments = "" c.Files = nil c.Properties = nil } } toPut = append(toPut, &builderEntity{ MasterKey: datastore.KeyForObj(c, entity), Name: builderName, PendingCount: builder.PendingBuilds, }) } publicTag := &masterPublic{Name: master.Name} if internal { // do the deletion immediately so that the 'public' bit is removed from // datastore before any internal details are actually written to datastore. if err := datastore.Delete(c, publicTag); err != nil && err != datastore.ErrNoSuchEntity { return err } } else { toPut = append(toPut, publicTag) } var err error entity.Data, err = encode(master) if err != nil { return err } logging.Debugf(c, "Length of gzipped master data: %d", len(entity.Data)) if len(entity.Data) > maxDataSize { return errors.Reason("master data is %d bytes, which is more than %d limit", len(entity.Data), maxDataSize). Tag(TooBigTag). Err() } if err := datastore.Put(c, toPut); err != nil { return err } return cleanUpExpiredBuilds(c, master, expireCallback) }
[ "func", "SaveMaster", "(", "c", "context", ".", "Context", ",", "master", "*", "buildbot", ".", "Master", ",", "internal", "bool", ",", "expireCallback", "ExpireCallback", ")", "error", "{", "entity", ":=", "&", "masterEntity", "{", "Name", ":", "master", ...
// SaveMaster persists the master in the storage. // // Expires all incomplete builds in the datastore associated with this master // and // - associated with builders not declared in master.Builders // - OR or not "current" from this master's perspective and >=20min stale.
[ "SaveMaster", "persists", "the", "master", "in", "the", "storage", ".", "Expires", "all", "incomplete", "builds", "in", "the", "datastore", "associated", "with", "this", "master", "and", "-", "associated", "with", "builders", "not", "declared", "in", "master", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/master.go#L274-L327
8,705
luci/luci-go
milo/buildsource/buildbot/buildstore/master.go
expireBuild
func expireBuild(c context.Context, b *buildbot.Build) error { if !b.TimeStamp.IsZero() { b.Times.Finish = b.TimeStamp } else { b.Times.Finish.Time = clock.Now(c) } b.Finished = true b.Results = buildbot.Exception b.Currentstep = nil b.Text = append(b.Text, "Build expired on Milo") _, err := SaveBuild(c, b) return err }
go
func expireBuild(c context.Context, b *buildbot.Build) error { if !b.TimeStamp.IsZero() { b.Times.Finish = b.TimeStamp } else { b.Times.Finish.Time = clock.Now(c) } b.Finished = true b.Results = buildbot.Exception b.Currentstep = nil b.Text = append(b.Text, "Build expired on Milo") _, err := SaveBuild(c, b) return err }
[ "func", "expireBuild", "(", "c", "context", ".", "Context", ",", "b", "*", "buildbot", ".", "Build", ")", "error", "{", "if", "!", "b", ".", "TimeStamp", ".", "IsZero", "(", ")", "{", "b", ".", "Times", ".", "Finish", "=", "b", ".", "TimeStamp", ...
// expireBuild marks a build as finished and expired.
[ "expireBuild", "marks", "a", "build", "as", "finished", "and", "expired", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/master.go#L373-L385
8,706
luci/luci-go
milo/buildsource/buildbot/buildstore/master.go
isAllowedInternal
func isAllowedInternal(c context.Context) bool { settings := common.GetSettings(c) if settings.Buildbot.InternalReader == "" { return false } allowed, err := auth.IsMember(c, settings.Buildbot.InternalReader) if err != nil { logging.WithError(err).Errorf(c, "IsMember(%q) failed", settings.Buildbot.InternalReader) allowed = false } return allowed }
go
func isAllowedInternal(c context.Context) bool { settings := common.GetSettings(c) if settings.Buildbot.InternalReader == "" { return false } allowed, err := auth.IsMember(c, settings.Buildbot.InternalReader) if err != nil { logging.WithError(err).Errorf(c, "IsMember(%q) failed", settings.Buildbot.InternalReader) allowed = false } return allowed }
[ "func", "isAllowedInternal", "(", "c", "context", ".", "Context", ")", "bool", "{", "settings", ":=", "common", ".", "GetSettings", "(", "c", ")", "\n", "if", "settings", ".", "Buildbot", ".", "InternalReader", "==", "\"", "\"", "{", "return", "false", "...
// isAllowedInternal returns true if the current user has access to internal // data. In case of an error, logs it and returns false to prevent from // sniffing based on internal errors.
[ "isAllowedInternal", "returns", "true", "if", "the", "current", "user", "has", "access", "to", "internal", "data", ".", "In", "case", "of", "an", "error", "logs", "it", "and", "returns", "false", "to", "prevent", "from", "sniffing", "based", "on", "internal"...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/master.go#L397-L408
8,707
luci/luci-go
milo/buildsource/buildbot/buildstore/master.go
CanAccessMaster
func CanAccessMaster(c context.Context, name string) error { if ex, err := datastore.Exists(c, &masterPublic{Name: name}); err == nil && ex.Get(0) { // It exists => it is public return nil } if isAllowedInternal(c) { return nil } code := grpcutil.NotFoundTag if auth.CurrentUser(c).Identity == identity.AnonymousIdentity { code = grpcutil.UnauthenticatedTag } // Act like master does not exist. return errors.Reason("master %q not found", name).Tag(code).Err() }
go
func CanAccessMaster(c context.Context, name string) error { if ex, err := datastore.Exists(c, &masterPublic{Name: name}); err == nil && ex.Get(0) { // It exists => it is public return nil } if isAllowedInternal(c) { return nil } code := grpcutil.NotFoundTag if auth.CurrentUser(c).Identity == identity.AnonymousIdentity { code = grpcutil.UnauthenticatedTag } // Act like master does not exist. return errors.Reason("master %q not found", name).Tag(code).Err() }
[ "func", "CanAccessMaster", "(", "c", "context", ".", "Context", ",", "name", "string", ")", "error", "{", "if", "ex", ",", "err", ":=", "datastore", ".", "Exists", "(", "c", ",", "&", "masterPublic", "{", "Name", ":", "name", "}", ")", ";", "err", ...
// CanAccessMaster returns nil if the currently logged in user can see the // masters, or if the given master is a known public master, // otherwise an error.
[ "CanAccessMaster", "returns", "nil", "if", "the", "currently", "logged", "in", "user", "can", "see", "the", "masters", "or", "if", "the", "given", "master", "is", "a", "known", "public", "master", "otherwise", "an", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/master.go#L413-L429
8,708
luci/luci-go
cipd/client/cipd/internal/checksum.go
MarshalWithSHA256
func MarshalWithSHA256(pm proto.Message) ([]byte, error) { blob, err := proto.Marshal(pm) if err != nil { return nil, err } sum := sha256.Sum256(blob) envelope := messages.BlobWithSHA256{Blob: blob, Sha256: sum[:]} return proto.Marshal(&envelope) }
go
func MarshalWithSHA256(pm proto.Message) ([]byte, error) { blob, err := proto.Marshal(pm) if err != nil { return nil, err } sum := sha256.Sum256(blob) envelope := messages.BlobWithSHA256{Blob: blob, Sha256: sum[:]} return proto.Marshal(&envelope) }
[ "func", "MarshalWithSHA256", "(", "pm", "proto", ".", "Message", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "blob", ",", "err", ":=", "proto", ".", "Marshal", "(", "pm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "er...
// MarshalWithSHA256 serializes proto message to bytes, calculates SHA256 // checksum of it, and returns serialized envelope that contains both. // // UnmarshalWithSHA256 can then be used to verify SHA256 and deserialized the // original object.
[ "MarshalWithSHA256", "serializes", "proto", "message", "to", "bytes", "calculates", "SHA256", "checksum", "of", "it", "and", "returns", "serialized", "envelope", "that", "contains", "both", ".", "UnmarshalWithSHA256", "can", "then", "be", "used", "to", "verify", "...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/checksum.go#L37-L45
8,709
luci/luci-go
cipd/client/cipd/internal/checksum.go
UnmarshalWithSHA256
func UnmarshalWithSHA256(buf []byte, pm proto.Message) error { envelope := messages.BlobWithSHA256{} if err := proto.Unmarshal(buf, &envelope); err != nil { return err } if len(envelope.Sha256) == 0 { return ErrUnknownSHA256 } sum := sha256.Sum256(envelope.Blob) if !bytes.Equal(sum[:], envelope.Sha256) { return errors.New("sha256 of the file is invalid, it is probably corrupted") } return proto.Unmarshal(envelope.Blob, pm) }
go
func UnmarshalWithSHA256(buf []byte, pm proto.Message) error { envelope := messages.BlobWithSHA256{} if err := proto.Unmarshal(buf, &envelope); err != nil { return err } if len(envelope.Sha256) == 0 { return ErrUnknownSHA256 } sum := sha256.Sum256(envelope.Blob) if !bytes.Equal(sum[:], envelope.Sha256) { return errors.New("sha256 of the file is invalid, it is probably corrupted") } return proto.Unmarshal(envelope.Blob, pm) }
[ "func", "UnmarshalWithSHA256", "(", "buf", "[", "]", "byte", ",", "pm", "proto", ".", "Message", ")", "error", "{", "envelope", ":=", "messages", ".", "BlobWithSHA256", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "buf", ",", "&",...
// UnmarshalWithSHA256 is reverse of MarshalWithSHA256. // // It checks SHA256 checksum and deserializes the object if it matches the blob. // // If the expected SHA256 is not available in 'buf', returns ErrUnknownSHA256. // This can happen when reading blobs in old format that used SHA1.
[ "UnmarshalWithSHA256", "is", "reverse", "of", "MarshalWithSHA256", ".", "It", "checks", "SHA256", "checksum", "and", "deserializes", "the", "object", "if", "it", "matches", "the", "blob", ".", "If", "the", "expected", "SHA256", "is", "not", "available", "in", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/checksum.go#L53-L66
8,710
luci/luci-go
logdog/client/cmd/logdog_butler/output.go
AddFactory
func (ocf *outputConfigFlag) AddFactory(f outputFactory) { ocf.Options = append(ocf.Options, f.option()) }
go
func (ocf *outputConfigFlag) AddFactory(f outputFactory) { ocf.Options = append(ocf.Options, f.option()) }
[ "func", "(", "ocf", "*", "outputConfigFlag", ")", "AddFactory", "(", "f", "outputFactory", ")", "{", "ocf", ".", "Options", "=", "append", "(", "ocf", ".", "Options", ",", "f", ".", "option", "(", ")", ")", "\n", "}" ]
// Adds an output factory to this outputConfigFlag instance.
[ "Adds", "an", "output", "factory", "to", "this", "outputConfigFlag", "instance", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/output.go#L36-L38
8,711
luci/luci-go
logdog/client/cmd/logdog_butler/output.go
getFactory
func (ocf *outputConfigFlag) getFactory() outputFactory { if ocf.Selected == nil { return nil } if o, ok := ocf.Selected.(*outputOption); ok { return o.factory } return nil }
go
func (ocf *outputConfigFlag) getFactory() outputFactory { if ocf.Selected == nil { return nil } if o, ok := ocf.Selected.(*outputOption); ok { return o.factory } return nil }
[ "func", "(", "ocf", "*", "outputConfigFlag", ")", "getFactory", "(", ")", "outputFactory", "{", "if", "ocf", ".", "Selected", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "o", ",", "ok", ":=", "ocf", ".", "Selected", ".", "(", "*", "...
// Returns the Factory associated with the configured flag.
[ "Returns", "the", "Factory", "associated", "with", "the", "configured", "flag", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/output.go#L41-L50
8,712
luci/luci-go
logdog/client/cmd/logdog_butler/output.go
newOutputOption
func newOutputOption(name, description string, f outputFactory) *outputOption { return &outputOption{ FlagOption: multiflag.FlagOption{ Name: name, Description: description, }, factory: f, } }
go
func newOutputOption(name, description string, f outputFactory) *outputOption { return &outputOption{ FlagOption: multiflag.FlagOption{ Name: name, Description: description, }, factory: f, } }
[ "func", "newOutputOption", "(", "name", ",", "description", "string", ",", "f", "outputFactory", ")", "*", "outputOption", "{", "return", "&", "outputOption", "{", "FlagOption", ":", "multiflag", ".", "FlagOption", "{", "Name", ":", "name", ",", "Description",...
// newOutputOption instantiates a new outputOption.
[ "newOutputOption", "instantiates", "a", "new", "outputOption", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/output.go#L60-L68
8,713
luci/luci-go
tokenserver/appengine/impl/certconfig/rpc_list_cas.go
ListCAs
func (r *ListCAsRPC) ListCAs(c context.Context, _ *empty.Empty) (*admin.ListCAsResponse, error) { names, err := ListCAs(c) if err != nil { return nil, status.Errorf(codes.Internal, "transient datastore error - %s", err) } return &admin.ListCAsResponse{Cn: names}, nil }
go
func (r *ListCAsRPC) ListCAs(c context.Context, _ *empty.Empty) (*admin.ListCAsResponse, error) { names, err := ListCAs(c) if err != nil { return nil, status.Errorf(codes.Internal, "transient datastore error - %s", err) } return &admin.ListCAsResponse{Cn: names}, nil }
[ "func", "(", "r", "*", "ListCAsRPC", ")", "ListCAs", "(", "c", "context", ".", "Context", ",", "_", "*", "empty", ".", "Empty", ")", "(", "*", "admin", ".", "ListCAsResponse", ",", "error", ")", "{", "names", ",", "err", ":=", "ListCAs", "(", "c", ...
// ListCAs returns a list of Common Names of registered CAs.
[ "ListCAs", "returns", "a", "list", "of", "Common", "Names", "of", "registered", "CAs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/rpc_list_cas.go#L33-L39
8,714
luci/luci-go
gce/appengine/backend/queues.go
countVMs
func countVMs(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.CountVMs) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() } // Count VMs per project, server and zone. // VMs created from the same config eventually have the same project, server, // and zone but may currently exist for a previous version of the config. vms := &metrics.InstanceCount{} // Get the configured count. cfg := &model.Config{ ID: task.Id, } switch err := datastore.Get(c, cfg); { case err == datastore.ErrNoSuchEntity: case err != nil: return errors.Annotate(err, "failed to fetch config").Err() default: amt, err := cfg.Config.Amount.GetAmount(clock.Now(c)) if err != nil { return errors.Annotate(err, "failed to parse amount").Err() } vms.AddConfigured(int(amt), cfg.Config.Attributes.Project) } // Get the actual (connected, created) counts. var keys []*datastore.Key q := datastore.NewQuery(model.VMKind).Eq("config", task.Id) if err := datastore.GetAll(c, q, &keys); err != nil { return errors.Annotate(err, "failed to fetch VMs").Err() } vm := &model.VM{} for _, k := range keys { id := k.StringID() vm.ID = id switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() default: if vm.Created > 0 { vms.AddCreated(1, vm.Attributes.Project, vm.Attributes.Zone) } if vm.Connected > 0 { vms.AddConnected(1, vm.Attributes.Project, vm.Swarming, vm.Attributes.Zone) } } } if err := vms.Update(c, task.Id); err != nil { return errors.Annotate(err, "failed to update count").Err() } return nil }
go
func countVMs(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.CountVMs) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() } // Count VMs per project, server and zone. // VMs created from the same config eventually have the same project, server, // and zone but may currently exist for a previous version of the config. vms := &metrics.InstanceCount{} // Get the configured count. cfg := &model.Config{ ID: task.Id, } switch err := datastore.Get(c, cfg); { case err == datastore.ErrNoSuchEntity: case err != nil: return errors.Annotate(err, "failed to fetch config").Err() default: amt, err := cfg.Config.Amount.GetAmount(clock.Now(c)) if err != nil { return errors.Annotate(err, "failed to parse amount").Err() } vms.AddConfigured(int(amt), cfg.Config.Attributes.Project) } // Get the actual (connected, created) counts. var keys []*datastore.Key q := datastore.NewQuery(model.VMKind).Eq("config", task.Id) if err := datastore.GetAll(c, q, &keys); err != nil { return errors.Annotate(err, "failed to fetch VMs").Err() } vm := &model.VM{} for _, k := range keys { id := k.StringID() vm.ID = id switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() default: if vm.Created > 0 { vms.AddCreated(1, vm.Attributes.Project, vm.Attributes.Zone) } if vm.Connected > 0 { vms.AddConnected(1, vm.Attributes.Project, vm.Swarming, vm.Attributes.Zone) } } } if err := vms.Update(c, task.Id); err != nil { return errors.Annotate(err, "failed to update count").Err() } return nil }
[ "func", "countVMs", "(", "c", "context", ".", "Context", ",", "payload", "proto", ".", "Message", ")", "error", "{", "task", ",", "ok", ":=", "payload", ".", "(", "*", "tasks", ".", "CountVMs", ")", "\n", "switch", "{", "case", "!", "ok", ":", "ret...
// countVMs counts the VMs for a given config.
[ "countVMs", "counts", "the", "VMs", "for", "a", "given", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/queues.go#L44-L100
8,715
luci/luci-go
gce/appengine/backend/queues.go
drainVM
func drainVM(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.DrainVM) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() } vm := &model.VM{ ID: task.Id, } switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: return nil case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() case vm.Drained: return nil } cfg := &model.Config{ ID: vm.Config, } switch err := datastore.Get(c, cfg); { case err == datastore.ErrNoSuchEntity: // Config doesn't exist, drain the VM. case err != nil: return errors.Annotate(err, "failed to fetch config").Err() } switch amt, err := cfg.Config.Amount.GetAmount(clock.Now(c)); { case err != nil: return errors.Annotate(err, "failed to parse amount").Err() case amt > vm.Index: // VM is configured to exist, don't drain the VM. return nil } logging.Debugf(c, "draining VM") return datastore.RunInTransaction(c, func(c context.Context) error { // Double-check inside transaction. // VM may already be drained or deleted. switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: return nil case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() case vm.Drained: return nil } vm.Drained = true if err := datastore.Put(c, vm); err != nil { return errors.Annotate(err, "failed to store VM").Err() } return nil }, nil) }
go
func drainVM(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.DrainVM) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() } vm := &model.VM{ ID: task.Id, } switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: return nil case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() case vm.Drained: return nil } cfg := &model.Config{ ID: vm.Config, } switch err := datastore.Get(c, cfg); { case err == datastore.ErrNoSuchEntity: // Config doesn't exist, drain the VM. case err != nil: return errors.Annotate(err, "failed to fetch config").Err() } switch amt, err := cfg.Config.Amount.GetAmount(clock.Now(c)); { case err != nil: return errors.Annotate(err, "failed to parse amount").Err() case amt > vm.Index: // VM is configured to exist, don't drain the VM. return nil } logging.Debugf(c, "draining VM") return datastore.RunInTransaction(c, func(c context.Context) error { // Double-check inside transaction. // VM may already be drained or deleted. switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: return nil case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() case vm.Drained: return nil } vm.Drained = true if err := datastore.Put(c, vm); err != nil { return errors.Annotate(err, "failed to store VM").Err() } return nil }, nil) }
[ "func", "drainVM", "(", "c", "context", ".", "Context", ",", "payload", "proto", ".", "Message", ")", "error", "{", "task", ",", "ok", ":=", "payload", ".", "(", "*", "tasks", ".", "DrainVM", ")", "\n", "switch", "{", "case", "!", "ok", ":", "retur...
// drainVM drains a given VM.
[ "drainVM", "drains", "a", "given", "VM", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/queues.go#L106-L159
8,716
luci/luci-go
gce/appengine/backend/queues.go
getSuffix
func getSuffix(c context.Context) string { const allowed = "abcdefghijklmnopqrstuvwxyz0123456789" suf := make([]byte, 4) for i := range suf { suf[i] = allowed[mathrand.Intn(c, len(allowed))] } return string(suf) }
go
func getSuffix(c context.Context) string { const allowed = "abcdefghijklmnopqrstuvwxyz0123456789" suf := make([]byte, 4) for i := range suf { suf[i] = allowed[mathrand.Intn(c, len(allowed))] } return string(suf) }
[ "func", "getSuffix", "(", "c", "context", ".", "Context", ")", "string", "{", "const", "allowed", "=", "\"", "\"", "\n", "suf", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "for", "i", ":=", "range", "suf", "{", "suf", "[", "i", "]...
// getSuffix returns a random suffix to use when naming a GCE instance.
[ "getSuffix", "returns", "a", "random", "suffix", "to", "use", "when", "naming", "a", "GCE", "instance", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/queues.go#L162-L169
8,717
luci/luci-go
gce/appengine/backend/queues.go
createVM
func createVM(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.CreateVM) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() case task.GetConfig() == "": return errors.Reason("config is required").Err() } vm := &model.VM{ ID: task.Id, Config: task.Config, Hostname: fmt.Sprintf("%s-%d-%s", task.Prefix, task.Index, getSuffix(c)), Index: task.Index, Lifetime: task.Lifetime, Prefix: task.Prefix, Revision: task.Revision, Swarming: task.Swarming, Timeout: task.Timeout, } if task.Attributes != nil { vm.Attributes = *task.Attributes // TODO(crbug/942301): Auto-select zone if zone is unspecified. vm.Attributes.SetZone(vm.Attributes.GetZone()) } // createVM is called repeatedly, so do a fast check outside the transaction. // In most cases, this will skip the more expensive transactional check. switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() default: return nil } return datastore.RunInTransaction(c, func(c context.Context) error { switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() default: return nil } if err := datastore.Put(c, vm); err != nil { return errors.Annotate(err, "failed to store VM").Err() } return nil }, nil) }
go
func createVM(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.CreateVM) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() case task.GetConfig() == "": return errors.Reason("config is required").Err() } vm := &model.VM{ ID: task.Id, Config: task.Config, Hostname: fmt.Sprintf("%s-%d-%s", task.Prefix, task.Index, getSuffix(c)), Index: task.Index, Lifetime: task.Lifetime, Prefix: task.Prefix, Revision: task.Revision, Swarming: task.Swarming, Timeout: task.Timeout, } if task.Attributes != nil { vm.Attributes = *task.Attributes // TODO(crbug/942301): Auto-select zone if zone is unspecified. vm.Attributes.SetZone(vm.Attributes.GetZone()) } // createVM is called repeatedly, so do a fast check outside the transaction. // In most cases, this will skip the more expensive transactional check. switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() default: return nil } return datastore.RunInTransaction(c, func(c context.Context) error { switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() default: return nil } if err := datastore.Put(c, vm); err != nil { return errors.Annotate(err, "failed to store VM").Err() } return nil }, nil) }
[ "func", "createVM", "(", "c", "context", ".", "Context", ",", "payload", "proto", ".", "Message", ")", "error", "{", "task", ",", "ok", ":=", "payload", ".", "(", "*", "tasks", ".", "CreateVM", ")", "\n", "switch", "{", "case", "!", "ok", ":", "ret...
// createVM creates a VM if it doesn't already exist.
[ "createVM", "creates", "a", "VM", "if", "it", "doesn", "t", "already", "exist", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/queues.go#L175-L223
8,718
luci/luci-go
gce/appengine/backend/queues.go
expandConfig
func expandConfig(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.ExpandConfig) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() } cfg, err := getConfig(c).Get(c, &config.GetRequest{Id: task.Id}) if err != nil { return errors.Annotate(err, "failed to fetch config").Err() } now := clock.Now(c) amt, err := cfg.Amount.GetAmount(now) if err != nil { return errors.Annotate(err, "failed to parse amount").Err() } t := make([]*tq.Task, amt) for i := int32(0); i < amt; i++ { t[i] = &tq.Task{ Payload: &tasks.CreateVM{ Id: fmt.Sprintf("%s-%d", cfg.Prefix, i), Attributes: cfg.Attributes, Config: task.Id, Created: &timestamp.Timestamp{ Seconds: now.Unix(), }, Index: i, Lifetime: cfg.Lifetime.GetSeconds(), Prefix: cfg.Prefix, Revision: cfg.Revision, Swarming: cfg.Swarming, Timeout: cfg.Timeout.GetSeconds(), }, } } logging.Debugf(c, "creating %d VMs", len(t)) if err := getDispatcher(c).AddTask(c, t...); err != nil { return errors.Annotate(err, "failed to schedule tasks").Err() } return nil }
go
func expandConfig(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.ExpandConfig) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() } cfg, err := getConfig(c).Get(c, &config.GetRequest{Id: task.Id}) if err != nil { return errors.Annotate(err, "failed to fetch config").Err() } now := clock.Now(c) amt, err := cfg.Amount.GetAmount(now) if err != nil { return errors.Annotate(err, "failed to parse amount").Err() } t := make([]*tq.Task, amt) for i := int32(0); i < amt; i++ { t[i] = &tq.Task{ Payload: &tasks.CreateVM{ Id: fmt.Sprintf("%s-%d", cfg.Prefix, i), Attributes: cfg.Attributes, Config: task.Id, Created: &timestamp.Timestamp{ Seconds: now.Unix(), }, Index: i, Lifetime: cfg.Lifetime.GetSeconds(), Prefix: cfg.Prefix, Revision: cfg.Revision, Swarming: cfg.Swarming, Timeout: cfg.Timeout.GetSeconds(), }, } } logging.Debugf(c, "creating %d VMs", len(t)) if err := getDispatcher(c).AddTask(c, t...); err != nil { return errors.Annotate(err, "failed to schedule tasks").Err() } return nil }
[ "func", "expandConfig", "(", "c", "context", ".", "Context", ",", "payload", "proto", ".", "Message", ")", "error", "{", "task", ",", "ok", ":=", "payload", ".", "(", "*", "tasks", ".", "ExpandConfig", ")", "\n", "switch", "{", "case", "!", "ok", ":"...
// expandConfig creates task queue tasks to create each VM in the given config.
[ "expandConfig", "creates", "task", "queue", "tasks", "to", "create", "each", "VM", "in", "the", "given", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/queues.go#L229-L270
8,719
luci/luci-go
gce/appengine/backend/queues.go
reportQuota
func reportQuota(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.ReportQuota) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() } p := &model.Project{ ID: task.Id, } if err := datastore.Get(c, p); err != nil { return errors.Annotate(err, "failed to fetch project").Err() } mets := stringset.NewFromSlice(p.Config.Metric...) regs := stringset.NewFromSlice(p.Config.Region...) rsp, err := getCompute(c).Regions.List(p.Config.Project).Context(c).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok { logErrors(c, gerr) return errors.Reason("failed to fetch quota").Err() } return errors.Annotate(err, "failed to fetch quota").Err() } for _, r := range rsp.Items { if regs.Has(r.Name) { for _, q := range r.Quotas { if mets.Has(q.Metric) { metrics.UpdateQuota(c, q.Limit, q.Usage, q.Metric, p.Config.Project, r.Name) } } } } return nil }
go
func reportQuota(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.ReportQuota) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() } p := &model.Project{ ID: task.Id, } if err := datastore.Get(c, p); err != nil { return errors.Annotate(err, "failed to fetch project").Err() } mets := stringset.NewFromSlice(p.Config.Metric...) regs := stringset.NewFromSlice(p.Config.Region...) rsp, err := getCompute(c).Regions.List(p.Config.Project).Context(c).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok { logErrors(c, gerr) return errors.Reason("failed to fetch quota").Err() } return errors.Annotate(err, "failed to fetch quota").Err() } for _, r := range rsp.Items { if regs.Has(r.Name) { for _, q := range r.Quotas { if mets.Has(q.Metric) { metrics.UpdateQuota(c, q.Limit, q.Usage, q.Metric, p.Config.Project, r.Name) } } } } return nil }
[ "func", "reportQuota", "(", "c", "context", ".", "Context", ",", "payload", "proto", ".", "Message", ")", "error", "{", "task", ",", "ok", ":=", "payload", ".", "(", "*", "tasks", ".", "ReportQuota", ")", "\n", "switch", "{", "case", "!", "ok", ":", ...
// reportQuota reports GCE quota utilization.
[ "reportQuota", "reports", "GCE", "quota", "utilization", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/queues.go#L276-L310
8,720
luci/luci-go
common/isolatedclient/isolatedclient.go
NewBytesSource
func NewBytesSource(d []byte) Source { return func() (io.ReadCloser, error) { return ioutil.NopCloser(bytes.NewReader(d)), nil } }
go
func NewBytesSource(d []byte) Source { return func() (io.ReadCloser, error) { return ioutil.NopCloser(bytes.NewReader(d)), nil } }
[ "func", "NewBytesSource", "(", "d", "[", "]", "byte", ")", "Source", "{", "return", "func", "(", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "ioutil", ".", "NopCloser", "(", "bytes", ".", "NewReader", "(", "d", ")", ")", ",...
// NewBytesSource returns a Source implementation that reads from the supplied // byte slice.
[ "NewBytesSource", "returns", "a", "Source", "implementation", "that", "reads", "from", "the", "supplied", "byte", "slice", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolatedclient/isolatedclient.go#L46-L50
8,721
luci/luci-go
common/isolatedclient/isolatedclient.go
ServerCapabilities
func (i *Client) ServerCapabilities(c context.Context) (*isolateservice.HandlersEndpointsV1ServerDetails, error) { out := &isolateservice.HandlersEndpointsV1ServerDetails{} if err := i.postJSON(c, "/_ah/api/isolateservice/v1/server_details", nil, map[string]string{}, out); err != nil { return nil, err } return out, nil }
go
func (i *Client) ServerCapabilities(c context.Context) (*isolateservice.HandlersEndpointsV1ServerDetails, error) { out := &isolateservice.HandlersEndpointsV1ServerDetails{} if err := i.postJSON(c, "/_ah/api/isolateservice/v1/server_details", nil, map[string]string{}, out); err != nil { return nil, err } return out, nil }
[ "func", "(", "i", "*", "Client", ")", "ServerCapabilities", "(", "c", "context", ".", "Context", ")", "(", "*", "isolateservice", ".", "HandlersEndpointsV1ServerDetails", ",", "error", ")", "{", "out", ":=", "&", "isolateservice", ".", "HandlersEndpointsV1Server...
// ServerCapabilities returns the server details.
[ "ServerCapabilities", "returns", "the", "server", "details", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolatedclient/isolatedclient.go#L130-L136
8,722
luci/luci-go
common/isolatedclient/isolatedclient.go
Contains
func (i *Client) Contains(c context.Context, items []*isolateservice.HandlersEndpointsV1Digest) (out []*PushState, err error) { end := tracer.Span(i, "contains", tracer.Args{"number": len(items)}) defer func() { end(tracer.Args{"err": err}) }() in := isolateservice.HandlersEndpointsV1DigestCollection{Items: items, Namespace: &isolateservice.HandlersEndpointsV1Namespace{}} in.Namespace.Namespace = i.namespace data := &isolateservice.HandlersEndpointsV1UrlCollection{} if err = i.postJSON(c, "/_ah/api/isolateservice/v1/preupload", nil, in, data); err != nil { return nil, err } out = make([]*PushState, len(items)) for _, e := range data.Items { index := int(e.Index) out[index] = &PushState{ status: *e, digest: isolated.HexDigest(items[index].Digest), size: items[index].Size, } } return out, nil }
go
func (i *Client) Contains(c context.Context, items []*isolateservice.HandlersEndpointsV1Digest) (out []*PushState, err error) { end := tracer.Span(i, "contains", tracer.Args{"number": len(items)}) defer func() { end(tracer.Args{"err": err}) }() in := isolateservice.HandlersEndpointsV1DigestCollection{Items: items, Namespace: &isolateservice.HandlersEndpointsV1Namespace{}} in.Namespace.Namespace = i.namespace data := &isolateservice.HandlersEndpointsV1UrlCollection{} if err = i.postJSON(c, "/_ah/api/isolateservice/v1/preupload", nil, in, data); err != nil { return nil, err } out = make([]*PushState, len(items)) for _, e := range data.Items { index := int(e.Index) out[index] = &PushState{ status: *e, digest: isolated.HexDigest(items[index].Digest), size: items[index].Size, } } return out, nil }
[ "func", "(", "i", "*", "Client", ")", "Contains", "(", "c", "context", ".", "Context", ",", "items", "[", "]", "*", "isolateservice", ".", "HandlersEndpointsV1Digest", ")", "(", "out", "[", "]", "*", "PushState", ",", "err", "error", ")", "{", "end", ...
// Contains looks up cache presence on the server of multiple items. // // The returned list is in the same order as 'items', with entries nil for // items that were present.
[ "Contains", "looks", "up", "cache", "presence", "on", "the", "server", "of", "multiple", "items", ".", "The", "returned", "list", "is", "in", "the", "same", "order", "as", "items", "with", "entries", "nil", "for", "items", "that", "were", "present", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolatedclient/isolatedclient.go#L142-L161
8,723
luci/luci-go
common/isolatedclient/isolatedclient.go
Fetch
func (i *Client) Fetch(c context.Context, digest isolated.HexDigest, dest io.Writer) error { // Perform initial request. name := "" switch i.h { case crypto.SHA1: name = "sha-1" case crypto.SHA256: name = "sha-256" case crypto.SHA512: name = "sha-512" } url := i.url + "/_ah/api/isolateservice/v1/retrieve" in := &isolateservice.HandlersEndpointsV1RetrieveRequest{ Digest: string(digest), Namespace: &isolateservice.HandlersEndpointsV1Namespace{ DigestHash: name, Namespace: i.namespace, }, Offset: 0, } var out isolateservice.HandlersEndpointsV1RetrievedContent if _, err := lhttp.PostJSON(c, i.retryFactory, i.authClient, url, nil, in, &out); err != nil { return err } // Handle DB items. if out.Content != "" { decoded, err := base64.StdEncoding.DecodeString(out.Content) if err != nil { return err } decompressor, err := isolated.GetDecompressor(i.namespace, bytes.NewReader(decoded)) if err != nil { return err } defer decompressor.Close() _, err = io.Copy(dest, decompressor) return err } // Handle GCS items. return i.gcsHandler.Fetch(c, i, out, dest) }
go
func (i *Client) Fetch(c context.Context, digest isolated.HexDigest, dest io.Writer) error { // Perform initial request. name := "" switch i.h { case crypto.SHA1: name = "sha-1" case crypto.SHA256: name = "sha-256" case crypto.SHA512: name = "sha-512" } url := i.url + "/_ah/api/isolateservice/v1/retrieve" in := &isolateservice.HandlersEndpointsV1RetrieveRequest{ Digest: string(digest), Namespace: &isolateservice.HandlersEndpointsV1Namespace{ DigestHash: name, Namespace: i.namespace, }, Offset: 0, } var out isolateservice.HandlersEndpointsV1RetrievedContent if _, err := lhttp.PostJSON(c, i.retryFactory, i.authClient, url, nil, in, &out); err != nil { return err } // Handle DB items. if out.Content != "" { decoded, err := base64.StdEncoding.DecodeString(out.Content) if err != nil { return err } decompressor, err := isolated.GetDecompressor(i.namespace, bytes.NewReader(decoded)) if err != nil { return err } defer decompressor.Close() _, err = io.Copy(dest, decompressor) return err } // Handle GCS items. return i.gcsHandler.Fetch(c, i, out, dest) }
[ "func", "(", "i", "*", "Client", ")", "Fetch", "(", "c", "context", ".", "Context", ",", "digest", "isolated", ".", "HexDigest", ",", "dest", "io", ".", "Writer", ")", "error", "{", "// Perform initial request.", "name", ":=", "\"", "\"", "\n", "switch",...
// Fetch downloads an item from the server.
[ "Fetch", "downloads", "an", "item", "from", "the", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolatedclient/isolatedclient.go#L196-L238
8,724
luci/luci-go
common/isolatedclient/isolatedclient.go
postJSON
func (i *Client) postJSON(c context.Context, resource string, headers map[string]string, in, out interface{}) error { if len(resource) == 0 || resource[0] != '/' { return errors.New("resource must start with '/'") } _, err := lhttp.PostJSON(c, i.retryFactory, i.authClient, i.url+resource, headers, in, out) return err }
go
func (i *Client) postJSON(c context.Context, resource string, headers map[string]string, in, out interface{}) error { if len(resource) == 0 || resource[0] != '/' { return errors.New("resource must start with '/'") } _, err := lhttp.PostJSON(c, i.retryFactory, i.authClient, i.url+resource, headers, in, out) return err }
[ "func", "(", "i", "*", "Client", ")", "postJSON", "(", "c", "context", ".", "Context", ",", "resource", "string", ",", "headers", "map", "[", "string", "]", "string", ",", "in", ",", "out", "interface", "{", "}", ")", "error", "{", "if", "len", "("...
// postJSON does authenticated POST request.
[ "postJSON", "does", "authenticated", "POST", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolatedclient/isolatedclient.go#L241-L247
8,725
luci/luci-go
common/isolatedclient/isolatedclient.go
Fetch
func (gcs defaultGCSHandler) Fetch(c context.Context, i *Client, content isolateservice.HandlersEndpointsV1RetrievedContent, dest io.Writer) error { rgen := func() (*http.Request, error) { return http.NewRequest("GET", content.Url, nil) } handler := func(resp *http.Response) error { defer resp.Body.Close() decompressor, err := isolated.GetDecompressor(i.namespace, resp.Body) if err != nil { return err } defer decompressor.Close() _, err = io.Copy(dest, decompressor) return err } _, err := lhttp.NewRequest(c, i.authClient, i.retryFactory, rgen, handler, nil)() return err }
go
func (gcs defaultGCSHandler) Fetch(c context.Context, i *Client, content isolateservice.HandlersEndpointsV1RetrievedContent, dest io.Writer) error { rgen := func() (*http.Request, error) { return http.NewRequest("GET", content.Url, nil) } handler := func(resp *http.Response) error { defer resp.Body.Close() decompressor, err := isolated.GetDecompressor(i.namespace, resp.Body) if err != nil { return err } defer decompressor.Close() _, err = io.Copy(dest, decompressor) return err } _, err := lhttp.NewRequest(c, i.authClient, i.retryFactory, rgen, handler, nil)() return err }
[ "func", "(", "gcs", "defaultGCSHandler", ")", "Fetch", "(", "c", "context", ".", "Context", ",", "i", "*", "Client", ",", "content", "isolateservice", ".", "HandlersEndpointsV1RetrievedContent", ",", "dest", "io", ".", "Writer", ")", "error", "{", "rgen", ":...
// Fetch uses the provided HandlersEndpointsV1RetrievedContent response to // download content from GCS to the provided dest.
[ "Fetch", "uses", "the", "provided", "HandlersEndpointsV1RetrievedContent", "response", "to", "download", "content", "from", "GCS", "to", "the", "provided", "dest", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolatedclient/isolatedclient.go#L296-L312
8,726
luci/luci-go
common/isolatedclient/isolatedclient.go
Push
func (gcs defaultGCSHandler) Push(c context.Context, i *Client, status isolateservice.HandlersEndpointsV1PreuploadStatus, source Source) error { // GsUploadUrl is signed Google Storage URL that doesn't require additional // authentication. In fact, using authClient causes HTTP 403 because // authClient's tokens don't have Cloud Storage OAuth scope. Use anonymous // client instead. req := lhttp.NewRequest(c, i.anonClient, i.retryFactory, func() (*http.Request, error) { src, err := source() if err != nil { return nil, err } request, err := http.NewRequest("PUT", status.GsUploadUrl, nil) if err != nil { src.Close() return nil, err } request.Body = newCompressed(i.namespace, src) request.Header.Set("Content-Type", "application/octet-stream") return request, nil }, func(resp *http.Response) error { _, err4 := io.Copy(ioutil.Discard, resp.Body) err5 := resp.Body.Close() if err4 != nil { return err4 } return err5 }, nil) _, err := req() return err }
go
func (gcs defaultGCSHandler) Push(c context.Context, i *Client, status isolateservice.HandlersEndpointsV1PreuploadStatus, source Source) error { // GsUploadUrl is signed Google Storage URL that doesn't require additional // authentication. In fact, using authClient causes HTTP 403 because // authClient's tokens don't have Cloud Storage OAuth scope. Use anonymous // client instead. req := lhttp.NewRequest(c, i.anonClient, i.retryFactory, func() (*http.Request, error) { src, err := source() if err != nil { return nil, err } request, err := http.NewRequest("PUT", status.GsUploadUrl, nil) if err != nil { src.Close() return nil, err } request.Body = newCompressed(i.namespace, src) request.Header.Set("Content-Type", "application/octet-stream") return request, nil }, func(resp *http.Response) error { _, err4 := io.Copy(ioutil.Discard, resp.Body) err5 := resp.Body.Close() if err4 != nil { return err4 } return err5 }, nil) _, err := req() return err }
[ "func", "(", "gcs", "defaultGCSHandler", ")", "Push", "(", "c", "context", ".", "Context", ",", "i", "*", "Client", ",", "status", "isolateservice", ".", "HandlersEndpointsV1PreuploadStatus", ",", "source", "Source", ")", "error", "{", "// GsUploadUrl is signed Go...
// Push uploads content from the provided source to the GCS path specified in // the HandlersEndpointsV1PreuploadStatus response.
[ "Push", "uploads", "content", "from", "the", "provided", "source", "to", "the", "GCS", "path", "specified", "in", "the", "HandlersEndpointsV1PreuploadStatus", "response", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolatedclient/isolatedclient.go#L316-L345
8,727
luci/luci-go
luci_notify/config/validate.go
init
func init() { validation.Rules.Add( "regex:projects/.*", "${appid}.cfg", func(ctx *validation.Context, configSet, path string, content []byte) error { cfg := &notifypb.ProjectConfig{} if err := proto.UnmarshalText(string(content), cfg); err != nil { ctx.Errorf("invalid ProjectConfig proto message: %s", err) } else { validateProjectConfig(ctx, cfg) } return nil }) validation.Rules.Add( "regex:projects/.*", `regex:${appid}/email-templates/[^/]+\.template`, validateEmailTemplateFile) }
go
func init() { validation.Rules.Add( "regex:projects/.*", "${appid}.cfg", func(ctx *validation.Context, configSet, path string, content []byte) error { cfg := &notifypb.ProjectConfig{} if err := proto.UnmarshalText(string(content), cfg); err != nil { ctx.Errorf("invalid ProjectConfig proto message: %s", err) } else { validateProjectConfig(ctx, cfg) } return nil }) validation.Rules.Add( "regex:projects/.*", `regex:${appid}/email-templates/[^/]+\.template`, validateEmailTemplateFile) }
[ "func", "init", "(", ")", "{", "validation", ".", "Rules", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ",", "func", "(", "ctx", "*", "validation", ".", "Context", ",", "configSet", ",", "path", "string", ",", "content", "[", "]", "byte", ")", "...
// init registers validators for the project config and email template files.
[ "init", "registers", "validators", "for", "the", "project", "config", "and", "email", "template", "files", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/validate.go#L41-L59
8,728
luci/luci-go
luci_notify/config/validate.go
validateNotification
func validateNotification(c *validation.Context, cfgNotification *notifypb.Notification) { if cfgNotification.Email != nil { for _, addr := range cfgNotification.Email.Recipients { if _, err := mail.ParseAddress(addr); err != nil { c.Errorf(badEmailError, addr) } } } }
go
func validateNotification(c *validation.Context, cfgNotification *notifypb.Notification) { if cfgNotification.Email != nil { for _, addr := range cfgNotification.Email.Recipients { if _, err := mail.ParseAddress(addr); err != nil { c.Errorf(badEmailError, addr) } } } }
[ "func", "validateNotification", "(", "c", "*", "validation", ".", "Context", ",", "cfgNotification", "*", "notifypb", ".", "Notification", ")", "{", "if", "cfgNotification", ".", "Email", "!=", "nil", "{", "for", "_", ",", "addr", ":=", "range", "cfgNotifica...
// validateNotification is a helper function for validateConfig which validates // an individual notification configuration.
[ "validateNotification", "is", "a", "helper", "function", "for", "validateConfig", "which", "validates", "an", "individual", "notification", "configuration", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/validate.go#L72-L80
8,729
luci/luci-go
luci_notify/config/validate.go
validateBuilder
func validateBuilder(c *validation.Context, cfgBuilder *notifypb.Builder, builderNames stringset.Set) { if cfgBuilder.Bucket == "" { c.Errorf(requiredFieldError, "bucket") } if strings.HasPrefix(cfgBuilder.Bucket, "luci.") { // TODO(tandrii): change to warning once our validation library supports it. c.Errorf(`field "bucket" should not include legacy "luci.<project_name>." prefix, given %q`, cfgBuilder.Bucket) } if cfgBuilder.Name == "" { c.Errorf(requiredFieldError, "name") } if cfgBuilder.Repository != "" { if err := gitiles.ValidateRepoURL(cfgBuilder.Repository); err != nil { c.Errorf(badRepoURLError, cfgBuilder.Repository) } } fullName := fmt.Sprintf("%s/%s", cfgBuilder.Bucket, cfgBuilder.Name) if !builderNames.Add(fullName) { c.Errorf(duplicateBuilderError, fullName) } }
go
func validateBuilder(c *validation.Context, cfgBuilder *notifypb.Builder, builderNames stringset.Set) { if cfgBuilder.Bucket == "" { c.Errorf(requiredFieldError, "bucket") } if strings.HasPrefix(cfgBuilder.Bucket, "luci.") { // TODO(tandrii): change to warning once our validation library supports it. c.Errorf(`field "bucket" should not include legacy "luci.<project_name>." prefix, given %q`, cfgBuilder.Bucket) } if cfgBuilder.Name == "" { c.Errorf(requiredFieldError, "name") } if cfgBuilder.Repository != "" { if err := gitiles.ValidateRepoURL(cfgBuilder.Repository); err != nil { c.Errorf(badRepoURLError, cfgBuilder.Repository) } } fullName := fmt.Sprintf("%s/%s", cfgBuilder.Bucket, cfgBuilder.Name) if !builderNames.Add(fullName) { c.Errorf(duplicateBuilderError, fullName) } }
[ "func", "validateBuilder", "(", "c", "*", "validation", ".", "Context", ",", "cfgBuilder", "*", "notifypb", ".", "Builder", ",", "builderNames", "stringset", ".", "Set", ")", "{", "if", "cfgBuilder", ".", "Bucket", "==", "\"", "\"", "{", "c", ".", "Error...
// validateBuilder is a helper function for validateConfig which validates // an individual Builder.
[ "validateBuilder", "is", "a", "helper", "function", "for", "validateConfig", "which", "validates", "an", "individual", "Builder", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/validate.go#L84-L104
8,730
luci/luci-go
luci_notify/config/validate.go
validateNotifier
func validateNotifier(c *validation.Context, cfgNotifier *notifypb.Notifier, builderNames stringset.Set) { for i, cfgNotification := range cfgNotifier.Notifications { c.Enter("notification #%d", i+1) validateNotification(c, cfgNotification) c.Exit() } for i, cfgBuilder := range cfgNotifier.Builders { c.Enter("builder #%d", i+1) validateBuilder(c, cfgBuilder, builderNames) c.Exit() } }
go
func validateNotifier(c *validation.Context, cfgNotifier *notifypb.Notifier, builderNames stringset.Set) { for i, cfgNotification := range cfgNotifier.Notifications { c.Enter("notification #%d", i+1) validateNotification(c, cfgNotification) c.Exit() } for i, cfgBuilder := range cfgNotifier.Builders { c.Enter("builder #%d", i+1) validateBuilder(c, cfgBuilder, builderNames) c.Exit() } }
[ "func", "validateNotifier", "(", "c", "*", "validation", ".", "Context", ",", "cfgNotifier", "*", "notifypb", ".", "Notifier", ",", "builderNames", "stringset", ".", "Set", ")", "{", "for", "i", ",", "cfgNotification", ":=", "range", "cfgNotifier", ".", "Not...
// validateNotifier validates a Notifier.
[ "validateNotifier", "validates", "a", "Notifier", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/validate.go#L107-L118
8,731
luci/luci-go
luci_notify/config/validate.go
validateProjectConfig
func validateProjectConfig(ctx *validation.Context, projectCfg *notifypb.ProjectConfig) { builderNames := stringset.New(len(projectCfg.Notifiers)) // At least one builder per notifier for i, cfgNotifier := range projectCfg.Notifiers { ctx.Enter("notifier #%d", i+1) validateNotifier(ctx, cfgNotifier, builderNames) ctx.Exit() } }
go
func validateProjectConfig(ctx *validation.Context, projectCfg *notifypb.ProjectConfig) { builderNames := stringset.New(len(projectCfg.Notifiers)) // At least one builder per notifier for i, cfgNotifier := range projectCfg.Notifiers { ctx.Enter("notifier #%d", i+1) validateNotifier(ctx, cfgNotifier, builderNames) ctx.Exit() } }
[ "func", "validateProjectConfig", "(", "ctx", "*", "validation", ".", "Context", ",", "projectCfg", "*", "notifypb", ".", "ProjectConfig", ")", "{", "builderNames", ":=", "stringset", ".", "New", "(", "len", "(", "projectCfg", ".", "Notifiers", ")", ")", "// ...
// validateProjectConfig returns an error if the configuration violates any of the // requirements in the proto definition.
[ "validateProjectConfig", "returns", "an", "error", "if", "the", "configuration", "violates", "any", "of", "the", "requirements", "in", "the", "proto", "definition", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/validate.go#L122-L129
8,732
luci/luci-go
luci_notify/config/validate.go
validateSettings
func validateSettings(ctx *validation.Context, settings *notifypb.Settings) { switch { case settings.MiloHost == "": ctx.Errorf(requiredFieldError, "milo_host") case validation.ValidateHostname(settings.MiloHost) != nil: ctx.Errorf(invalidFieldError, "milo_host") } }
go
func validateSettings(ctx *validation.Context, settings *notifypb.Settings) { switch { case settings.MiloHost == "": ctx.Errorf(requiredFieldError, "milo_host") case validation.ValidateHostname(settings.MiloHost) != nil: ctx.Errorf(invalidFieldError, "milo_host") } }
[ "func", "validateSettings", "(", "ctx", "*", "validation", ".", "Context", ",", "settings", "*", "notifypb", ".", "Settings", ")", "{", "switch", "{", "case", "settings", ".", "MiloHost", "==", "\"", "\"", ":", "ctx", ".", "Errorf", "(", "requiredFieldErro...
// validateSettings returns an error if the service configuration violates any // of the requirements in the proto definition.
[ "validateSettings", "returns", "an", "error", "if", "the", "service", "configuration", "violates", "any", "of", "the", "requirements", "in", "the", "proto", "definition", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/validate.go#L133-L140
8,733
luci/luci-go
luci_notify/config/validate.go
validateEmailTemplateFile
func validateEmailTemplateFile(ctx *validation.Context, configSet, path string, content []byte) error { // Validate file name. rgx := emailTemplateFilenameRegexp(ctx.Context) if !rgx.MatchString(path) { ctx.Errorf("filename does not match %q", rgx.String()) } // Validate file contents. subject, body, err := splitEmailTemplateFile(string(content)) if err != nil { ctx.Error(err) } else { // Note: Parse does not return an error if the template attempts to // call an undefined template, e.g. {{template "does-not-exist"}} if _, err = text.New("subject").Funcs(EmailTemplateFuncs).Parse(subject); err != nil { ctx.Error(err) // error includes template name } // Due to luci-config limitation, we cannot detect an invalid reference to // a sub-template defined in a different file. if _, err = html.New("body").Funcs(EmailTemplateFuncs).Parse(body); err != nil { ctx.Error(err) // error includes template name } } return nil }
go
func validateEmailTemplateFile(ctx *validation.Context, configSet, path string, content []byte) error { // Validate file name. rgx := emailTemplateFilenameRegexp(ctx.Context) if !rgx.MatchString(path) { ctx.Errorf("filename does not match %q", rgx.String()) } // Validate file contents. subject, body, err := splitEmailTemplateFile(string(content)) if err != nil { ctx.Error(err) } else { // Note: Parse does not return an error if the template attempts to // call an undefined template, e.g. {{template "does-not-exist"}} if _, err = text.New("subject").Funcs(EmailTemplateFuncs).Parse(subject); err != nil { ctx.Error(err) // error includes template name } // Due to luci-config limitation, we cannot detect an invalid reference to // a sub-template defined in a different file. if _, err = html.New("body").Funcs(EmailTemplateFuncs).Parse(body); err != nil { ctx.Error(err) // error includes template name } } return nil }
[ "func", "validateEmailTemplateFile", "(", "ctx", "*", "validation", ".", "Context", ",", "configSet", ",", "path", "string", ",", "content", "[", "]", "byte", ")", "error", "{", "// Validate file name.", "rgx", ":=", "emailTemplateFilenameRegexp", "(", "ctx", "....
// validateEmailTemplateFile validates an email template file, including // its filename and contents.
[ "validateEmailTemplateFile", "validates", "an", "email", "template", "file", "including", "its", "filename", "and", "contents", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/validate.go#L144-L168
8,734
luci/luci-go
logdog/server/bundleServicesClient/client.go
RegisterStream
func (c *Client) RegisterStream(ctx context.Context, in *s.RegisterStreamRequest, opts ...grpc.CallOption) ( *s.RegisterStreamResponse, error) { resp, err := c.bundleRPC(ctx, opts, &s.BatchRequest_Entry{ Value: &s.BatchRequest_Entry_RegisterStream{RegisterStream: in}, }) if err != nil { return nil, err } return resp.GetRegisterStream(), nil }
go
func (c *Client) RegisterStream(ctx context.Context, in *s.RegisterStreamRequest, opts ...grpc.CallOption) ( *s.RegisterStreamResponse, error) { resp, err := c.bundleRPC(ctx, opts, &s.BatchRequest_Entry{ Value: &s.BatchRequest_Entry_RegisterStream{RegisterStream: in}, }) if err != nil { return nil, err } return resp.GetRegisterStream(), nil }
[ "func", "(", "c", "*", "Client", ")", "RegisterStream", "(", "ctx", "context", ".", "Context", ",", "in", "*", "s", ".", "RegisterStreamRequest", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "*", "s", ".", "RegisterStreamResponse", ",", "erro...
// RegisterStream implements ServicesClient.
[ "RegisterStream", "implements", "ServicesClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/bundleServicesClient/client.go#L72-L83
8,735
luci/luci-go
logdog/server/bundleServicesClient/client.go
LoadStream
func (c *Client) LoadStream(ctx context.Context, in *s.LoadStreamRequest, opts ...grpc.CallOption) ( *s.LoadStreamResponse, error) { resp, err := c.bundleRPC(ctx, opts, &s.BatchRequest_Entry{ Value: &s.BatchRequest_Entry_LoadStream{LoadStream: in}, }) if err != nil { return nil, err } return resp.GetLoadStream(), nil }
go
func (c *Client) LoadStream(ctx context.Context, in *s.LoadStreamRequest, opts ...grpc.CallOption) ( *s.LoadStreamResponse, error) { resp, err := c.bundleRPC(ctx, opts, &s.BatchRequest_Entry{ Value: &s.BatchRequest_Entry_LoadStream{LoadStream: in}, }) if err != nil { return nil, err } return resp.GetLoadStream(), nil }
[ "func", "(", "c", "*", "Client", ")", "LoadStream", "(", "ctx", "context", ".", "Context", ",", "in", "*", "s", ".", "LoadStreamRequest", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "*", "s", ".", "LoadStreamResponse", ",", "error", ")", ...
// LoadStream implements ServicesClient.
[ "LoadStream", "implements", "ServicesClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/bundleServicesClient/client.go#L86-L97
8,736
luci/luci-go
logdog/server/bundleServicesClient/client.go
TerminateStream
func (c *Client) TerminateStream(ctx context.Context, in *s.TerminateStreamRequest, opts ...grpc.CallOption) ( *empty.Empty, error) { _, err := c.bundleRPC(ctx, opts, &s.BatchRequest_Entry{ Value: &s.BatchRequest_Entry_TerminateStream{TerminateStream: in}, }) if err != nil { return nil, err } return &empty.Empty{}, nil }
go
func (c *Client) TerminateStream(ctx context.Context, in *s.TerminateStreamRequest, opts ...grpc.CallOption) ( *empty.Empty, error) { _, err := c.bundleRPC(ctx, opts, &s.BatchRequest_Entry{ Value: &s.BatchRequest_Entry_TerminateStream{TerminateStream: in}, }) if err != nil { return nil, err } return &empty.Empty{}, nil }
[ "func", "(", "c", "*", "Client", ")", "TerminateStream", "(", "ctx", "context", ".", "Context", ",", "in", "*", "s", ".", "TerminateStreamRequest", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", ...
// TerminateStream implements ServicesClient.
[ "TerminateStream", "implements", "ServicesClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/bundleServicesClient/client.go#L100-L111
8,737
luci/luci-go
logdog/server/bundleServicesClient/client.go
ArchiveStream
func (c *Client) ArchiveStream(ctx context.Context, in *s.ArchiveStreamRequest, opts ...grpc.CallOption) ( *empty.Empty, error) { _, err := c.bundleRPC(ctx, opts, &s.BatchRequest_Entry{ Value: &s.BatchRequest_Entry_ArchiveStream{ArchiveStream: in}, }) if err != nil { return nil, err } return &empty.Empty{}, nil }
go
func (c *Client) ArchiveStream(ctx context.Context, in *s.ArchiveStreamRequest, opts ...grpc.CallOption) ( *empty.Empty, error) { _, err := c.bundleRPC(ctx, opts, &s.BatchRequest_Entry{ Value: &s.BatchRequest_Entry_ArchiveStream{ArchiveStream: in}, }) if err != nil { return nil, err } return &empty.Empty{}, nil }
[ "func", "(", "c", "*", "Client", ")", "ArchiveStream", "(", "ctx", "context", ".", "Context", ",", "in", "*", "s", ".", "ArchiveStreamRequest", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{...
// ArchiveStream implements ServicesClient.
[ "ArchiveStream", "implements", "ServicesClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/bundleServicesClient/client.go#L114-L125
8,738
luci/luci-go
logdog/server/bundleServicesClient/client.go
Flush
func (c *Client) Flush() { c.initBundler() c.bundler.Flush() c.outstanding.Wait() }
go
func (c *Client) Flush() { c.initBundler() c.bundler.Flush() c.outstanding.Wait() }
[ "func", "(", "c", "*", "Client", ")", "Flush", "(", ")", "{", "c", ".", "initBundler", "(", ")", "\n", "c", ".", "bundler", ".", "Flush", "(", ")", "\n", "c", ".", "outstanding", ".", "Wait", "(", ")", "\n", "}" ]
// Flush flushes the Bundler. It should be called when terminating to ensure // that buffered client requests have been completed.
[ "Flush", "flushes", "the", "Bundler", ".", "It", "should", "be", "called", "when", "terminating", "to", "ensure", "that", "buffered", "client", "requests", "have", "been", "completed", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/bundleServicesClient/client.go#L129-L133
8,739
luci/luci-go
logdog/server/bundleServicesClient/client.go
bundleRPC
func (c *Client) bundleRPC(ctx context.Context, opts []grpc.CallOption, req *s.BatchRequest_Entry) (*s.BatchResponse_Entry, error) { c.initBundler() be := &batchEntry{ req: req, ctx: ctx, opts: opts, complete: make(chan *s.BatchResponse_Entry, 1), } if err := c.addEntry(be); err != nil { return nil, err } resp := <-be.complete if e := resp.GetErr(); e != nil { return nil, e.ToError() } return resp, nil }
go
func (c *Client) bundleRPC(ctx context.Context, opts []grpc.CallOption, req *s.BatchRequest_Entry) (*s.BatchResponse_Entry, error) { c.initBundler() be := &batchEntry{ req: req, ctx: ctx, opts: opts, complete: make(chan *s.BatchResponse_Entry, 1), } if err := c.addEntry(be); err != nil { return nil, err } resp := <-be.complete if e := resp.GetErr(); e != nil { return nil, e.ToError() } return resp, nil }
[ "func", "(", "c", "*", "Client", ")", "bundleRPC", "(", "ctx", "context", ".", "Context", ",", "opts", "[", "]", "grpc", ".", "CallOption", ",", "req", "*", "s", ".", "BatchRequest_Entry", ")", "(", "*", "s", ".", "BatchResponse_Entry", ",", "error", ...
// bundleRPC adds req to the underlying Bundler, blocks until it completes, and // returns its response.
[ "bundleRPC", "adds", "req", "to", "the", "underlying", "Bundler", "blocks", "until", "it", "completes", "and", "returns", "its", "response", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/bundleServicesClient/client.go#L147-L165
8,740
luci/luci-go
common/iotools/bufferingreaderat.go
init
func (l *blocksLRU) init(capacity int) { l.capacity = capacity l.blocks = make(map[int64]*list.Element, capacity) l.ll.Init() }
go
func (l *blocksLRU) init(capacity int) { l.capacity = capacity l.blocks = make(map[int64]*list.Element, capacity) l.ll.Init() }
[ "func", "(", "l", "*", "blocksLRU", ")", "init", "(", "capacity", "int", ")", "{", "l", ".", "capacity", "=", "capacity", "\n", "l", ".", "blocks", "=", "make", "(", "map", "[", "int64", "]", "*", "list", ".", "Element", ",", "capacity", ")", "\n...
// init initializes LRU guts.
[ "init", "initializes", "LRU", "guts", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/iotools/bufferingreaderat.go#L41-L45
8,741
luci/luci-go
common/iotools/bufferingreaderat.go
prepareForAdd
func (l *blocksLRU) prepareForAdd() { switch { case l.ll.Len() > l.capacity: panic("impossible") case l.ll.Len() == l.capacity: oldest := l.ll.Remove(l.ll.Back()).(block) delete(l.blocks, oldest.offset) l.evicted(oldest) } }
go
func (l *blocksLRU) prepareForAdd() { switch { case l.ll.Len() > l.capacity: panic("impossible") case l.ll.Len() == l.capacity: oldest := l.ll.Remove(l.ll.Back()).(block) delete(l.blocks, oldest.offset) l.evicted(oldest) } }
[ "func", "(", "l", "*", "blocksLRU", ")", "prepareForAdd", "(", ")", "{", "switch", "{", "case", "l", ".", "ll", ".", "Len", "(", ")", ">", "l", ".", "capacity", ":", "panic", "(", "\"", "\"", ")", "\n", "case", "l", ".", "ll", ".", "Len", "("...
// prepareForAdd removes oldest item from the list if it is at the capacity. // // Does nothing if it's not yet full.
[ "prepareForAdd", "removes", "oldest", "item", "from", "the", "list", "if", "it", "is", "at", "the", "capacity", ".", "Does", "nothing", "if", "it", "s", "not", "yet", "full", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/iotools/bufferingreaderat.go#L60-L69
8,742
luci/luci-go
common/iotools/bufferingreaderat.go
grabBuf
func (r *bufferingReaderAt) grabBuf() []byte { if len(r.pool) != 0 { b := r.pool[len(r.pool)-1] r.pool = r.pool[:len(r.pool)-1] return b } return make([]byte, r.blockSize) }
go
func (r *bufferingReaderAt) grabBuf() []byte { if len(r.pool) != 0 { b := r.pool[len(r.pool)-1] r.pool = r.pool[:len(r.pool)-1] return b } return make([]byte, r.blockSize) }
[ "func", "(", "r", "*", "bufferingReaderAt", ")", "grabBuf", "(", ")", "[", "]", "byte", "{", "if", "len", "(", "r", ".", "pool", ")", "!=", "0", "{", "b", ":=", "r", ".", "pool", "[", "len", "(", "r", ".", "pool", ")", "-", "1", "]", "\n", ...
// grabBuf returns a byte slice of blockSize size.
[ "grabBuf", "returns", "a", "byte", "slice", "of", "blockSize", "size", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/iotools/bufferingreaderat.go#L129-L136
8,743
luci/luci-go
common/iotools/bufferingreaderat.go
recycleBuf
func (r *bufferingReaderAt) recycleBuf(b []byte) { if cap(b) != r.blockSize { panic("trying to return a buffer not initially requested via grabBuf") } if len(r.pool)+1 > cap(r.pool) { panic("unexpected growth of byte buffer pool beyond capacity") } r.pool = append(r.pool, b[:cap(b)]) }
go
func (r *bufferingReaderAt) recycleBuf(b []byte) { if cap(b) != r.blockSize { panic("trying to return a buffer not initially requested via grabBuf") } if len(r.pool)+1 > cap(r.pool) { panic("unexpected growth of byte buffer pool beyond capacity") } r.pool = append(r.pool, b[:cap(b)]) }
[ "func", "(", "r", "*", "bufferingReaderAt", ")", "recycleBuf", "(", "b", "[", "]", "byte", ")", "{", "if", "cap", "(", "b", ")", "!=", "r", ".", "blockSize", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "r", ".", "po...
// recycleBuf is called when the buffer is no longer needed to put it for reuse.
[ "recycleBuf", "is", "called", "when", "the", "buffer", "is", "no", "longer", "needed", "to", "put", "it", "for", "reuse", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/iotools/bufferingreaderat.go#L139-L147
8,744
luci/luci-go
common/iotools/bufferingreaderat.go
ReadAt
func (r *bufferingReaderAt) ReadAt(p []byte, offset int64) (read int, err error) { if len(p) == 0 { return r.r.ReadAt(p, offset) } r.l.Lock() defer r.l.Unlock() bs := int64(r.blockSize) blockOff := int64((offset / bs) * bs) // block-aligned offset // Sequentially read blocks that intersect with the requested segment. for { // err here may be EOF or some other error. We consume all data first and // deal with errors later. data, err := r.readBlock(blockOff) // The first block may be read from the middle, since 'min' may be less than // 'offset'. if offset > blockOff { pos := offset - blockOff // position inside the block to read from if pos < int64(len(data)) { data = data[pos:] // grab the tail of the block } else { data = nil // we probably hit EOF before the requested offset } } // 'copy' copies min of len(data) and whatever space is left in 'p', so this // is always safe. The last block may be copied partially (if there's no // space left in 'p'). read += copy(p[read:], data) switch { case read == len(p): // We managed to read everything we wanted, ignore the last error, if any. return read, nil case err != nil: return read, err } // The last read was successful. Per ReaderAt contract (that we double // checked in readBlock) it means it read ALL requested data (and we request // 'bs' bytes). So move on to the next block. blockOff += bs } }
go
func (r *bufferingReaderAt) ReadAt(p []byte, offset int64) (read int, err error) { if len(p) == 0 { return r.r.ReadAt(p, offset) } r.l.Lock() defer r.l.Unlock() bs := int64(r.blockSize) blockOff := int64((offset / bs) * bs) // block-aligned offset // Sequentially read blocks that intersect with the requested segment. for { // err here may be EOF or some other error. We consume all data first and // deal with errors later. data, err := r.readBlock(blockOff) // The first block may be read from the middle, since 'min' may be less than // 'offset'. if offset > blockOff { pos := offset - blockOff // position inside the block to read from if pos < int64(len(data)) { data = data[pos:] // grab the tail of the block } else { data = nil // we probably hit EOF before the requested offset } } // 'copy' copies min of len(data) and whatever space is left in 'p', so this // is always safe. The last block may be copied partially (if there's no // space left in 'p'). read += copy(p[read:], data) switch { case read == len(p): // We managed to read everything we wanted, ignore the last error, if any. return read, nil case err != nil: return read, err } // The last read was successful. Per ReaderAt contract (that we double // checked in readBlock) it means it read ALL requested data (and we request // 'bs' bytes). So move on to the next block. blockOff += bs } }
[ "func", "(", "r", "*", "bufferingReaderAt", ")", "ReadAt", "(", "p", "[", "]", "byte", ",", "offset", "int64", ")", "(", "read", "int", ",", "err", "error", ")", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "r", ".", "r", ".", "...
// ReadAt implements io.ReaderAt interface.
[ "ReadAt", "implements", "io", ".", "ReaderAt", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/iotools/bufferingreaderat.go#L200-L246
8,745
luci/luci-go
milo/frontend/ui/builder.go
SwarmingURL
func (mp *MachinePool) SwarmingURL() string { if mp.SwarmingHost == "" { return "" } u := &url.URL{ Scheme: "https", Host: mp.SwarmingHost, Path: "botlist", RawQuery: url.Values{ "f": mp.Dimensions, }.Encode(), } return u.String() }
go
func (mp *MachinePool) SwarmingURL() string { if mp.SwarmingHost == "" { return "" } u := &url.URL{ Scheme: "https", Host: mp.SwarmingHost, Path: "botlist", RawQuery: url.Values{ "f": mp.Dimensions, }.Encode(), } return u.String() }
[ "func", "(", "mp", "*", "MachinePool", ")", "SwarmingURL", "(", ")", "string", "{", "if", "mp", ".", "SwarmingHost", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n", "u", ":=", "&", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ...
// SwarmingURL returns the swarming bot URL for the machine pool, if available.
[ "SwarmingURL", "returns", "the", "swarming", "bot", "URL", "for", "the", "machine", "pool", "if", "available", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/builder.go#L110-L123
8,746
luci/luci-go
milo/frontend/ui/builder.go
NewMachinePool
func NewMachinePool(c context.Context, botPool *model.BotPool) *MachinePool { fiveMinAgo := clock.Now(c).Add(-time.Minute * 5) result := &MachinePool{ Total: len(botPool.Bots), Bots: make([]Bot, len(botPool.Bots)), Dimensions: botPool.Descriptor.Dimensions().Format(), SwarmingHost: botPool.Descriptor.Host(), } for i, bot := range botPool.Bots { uiBot := Bot{bot, bot.Status} // Wrap the model.Bot if bot.Status == model.Offline && bot.LastSeen.After(fiveMinAgo) { // If the bot has been offline for less than 5 minutes, mark it as busy. uiBot.Status = model.Busy } switch bot.Status { case model.Idle: result.Idle++ case model.Busy: result.Busy++ case model.Offline: result.Offline++ } result.Bots[i] = uiBot } return result }
go
func NewMachinePool(c context.Context, botPool *model.BotPool) *MachinePool { fiveMinAgo := clock.Now(c).Add(-time.Minute * 5) result := &MachinePool{ Total: len(botPool.Bots), Bots: make([]Bot, len(botPool.Bots)), Dimensions: botPool.Descriptor.Dimensions().Format(), SwarmingHost: botPool.Descriptor.Host(), } for i, bot := range botPool.Bots { uiBot := Bot{bot, bot.Status} // Wrap the model.Bot if bot.Status == model.Offline && bot.LastSeen.After(fiveMinAgo) { // If the bot has been offline for less than 5 minutes, mark it as busy. uiBot.Status = model.Busy } switch bot.Status { case model.Idle: result.Idle++ case model.Busy: result.Busy++ case model.Offline: result.Offline++ } result.Bots[i] = uiBot } return result }
[ "func", "NewMachinePool", "(", "c", "context", ".", "Context", ",", "botPool", "*", "model", ".", "BotPool", ")", "*", "MachinePool", "{", "fiveMinAgo", ":=", "clock", ".", "Now", "(", "c", ")", ".", "Add", "(", "-", "time", ".", "Minute", "*", "5", ...
// NewMachinePool calculates stats from a model.Bot and generates a MachinePool. // This requires a context because setting the UI Status field requires the current time.
[ "NewMachinePool", "calculates", "stats", "from", "a", "model", ".", "Bot", "and", "generates", "a", "MachinePool", ".", "This", "requires", "a", "context", "because", "setting", "the", "UI", "Status", "field", "requires", "the", "current", "time", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/builder.go#L127-L152
8,747
luci/luci-go
dm/api/service/v1/walk_graph_normalize.go
Normalize
func (e *WalkGraphReq_Exclude) Normalize() error { if len(e.Quests) > 0 { e.Quests = e.Quests[:set.Uniq(sort.StringSlice(e.Quests))] } return e.Attempts.Normalize() }
go
func (e *WalkGraphReq_Exclude) Normalize() error { if len(e.Quests) > 0 { e.Quests = e.Quests[:set.Uniq(sort.StringSlice(e.Quests))] } return e.Attempts.Normalize() }
[ "func", "(", "e", "*", "WalkGraphReq_Exclude", ")", "Normalize", "(", ")", "error", "{", "if", "len", "(", "e", ".", "Quests", ")", ">", "0", "{", "e", ".", "Quests", "=", "e", ".", "Quests", "[", ":", "set", ".", "Uniq", "(", "sort", ".", "Str...
// Normalize returns an error iff the WalkGraphReq_Exclude is invalid.
[ "Normalize", "returns", "an", "error", "iff", "the", "WalkGraphReq_Exclude", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/walk_graph_normalize.go#L68-L73
8,748
luci/luci-go
dm/api/service/v1/walk_graph_normalize.go
Normalize
func (w *WalkGraphReq) Normalize() error { if w.Auth != nil { if err := w.Auth.Normalize(); err != nil { return err } } if w.Query == nil { return errors.New("must specify a Query") } if err := w.Query.Normalize(); err != nil { return err } if w.Mode == nil { w.Mode = &WalkGraphReq_Mode{} } if w.Limit != nil { if w.Limit.MaxDepth < -1 { return errors.New("limit.max_depth must be >= -1") } if google.DurationFromProto(w.Limit.GetMaxTime()) < 0 { return errors.New("limit.max_time must be positive") } } else { w.Limit = &WalkGraphReq_Limit{} } if w.Limit.MaxDataSize == 0 { w.Limit.MaxDataSize = DefaultLimitMaxDataSize } if w.Limit.MaxDataSize > MaxLimitMaxDataSize { w.Limit.MaxDataSize = MaxLimitMaxDataSize } if w.Include == nil { w.Include = &WalkGraphReq_Include{ Quest: &WalkGraphReq_Include_Options{}, Attempt: &WalkGraphReq_Include_Options{}, Execution: &WalkGraphReq_Include_Options{}, } } else { if w.Include.Quest == nil { w.Include.Quest = &WalkGraphReq_Include_Options{} } else if w.Include.Quest.Result || w.Include.Quest.Abnormal || w.Include.Quest.Expired { return errors.New("include.quest does not support result, abnormal or expired") } if w.Include.Attempt == nil { w.Include.Attempt = &WalkGraphReq_Include_Options{} } else { if w.Include.Attempt.Result { w.Include.Attempt.Data = true } } if w.Include.Execution == nil { w.Include.Execution = &WalkGraphReq_Include_Options{} } } if w.Exclude == nil { w.Exclude = &WalkGraphReq_Exclude{} } return w.Exclude.Normalize() }
go
func (w *WalkGraphReq) Normalize() error { if w.Auth != nil { if err := w.Auth.Normalize(); err != nil { return err } } if w.Query == nil { return errors.New("must specify a Query") } if err := w.Query.Normalize(); err != nil { return err } if w.Mode == nil { w.Mode = &WalkGraphReq_Mode{} } if w.Limit != nil { if w.Limit.MaxDepth < -1 { return errors.New("limit.max_depth must be >= -1") } if google.DurationFromProto(w.Limit.GetMaxTime()) < 0 { return errors.New("limit.max_time must be positive") } } else { w.Limit = &WalkGraphReq_Limit{} } if w.Limit.MaxDataSize == 0 { w.Limit.MaxDataSize = DefaultLimitMaxDataSize } if w.Limit.MaxDataSize > MaxLimitMaxDataSize { w.Limit.MaxDataSize = MaxLimitMaxDataSize } if w.Include == nil { w.Include = &WalkGraphReq_Include{ Quest: &WalkGraphReq_Include_Options{}, Attempt: &WalkGraphReq_Include_Options{}, Execution: &WalkGraphReq_Include_Options{}, } } else { if w.Include.Quest == nil { w.Include.Quest = &WalkGraphReq_Include_Options{} } else if w.Include.Quest.Result || w.Include.Quest.Abnormal || w.Include.Quest.Expired { return errors.New("include.quest does not support result, abnormal or expired") } if w.Include.Attempt == nil { w.Include.Attempt = &WalkGraphReq_Include_Options{} } else { if w.Include.Attempt.Result { w.Include.Attempt.Data = true } } if w.Include.Execution == nil { w.Include.Execution = &WalkGraphReq_Include_Options{} } } if w.Exclude == nil { w.Exclude = &WalkGraphReq_Exclude{} } return w.Exclude.Normalize() }
[ "func", "(", "w", "*", "WalkGraphReq", ")", "Normalize", "(", ")", "error", "{", "if", "w", ".", "Auth", "!=", "nil", "{", "if", "err", ":=", "w", ".", "Auth", ".", "Normalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}"...
// Normalize returns an error iff the WalkGraphReq is invalid.
[ "Normalize", "returns", "an", "error", "iff", "the", "WalkGraphReq", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/walk_graph_normalize.go#L76-L141
8,749
luci/luci-go
cipd/client/cipd/builder/builder.go
zipInputFiles
func zipInputFiles(ctx context.Context, files []fs.File, w io.Writer, level int) error { logging.Infof(ctx, "About to zip %d files with compression level %d", len(files), level) writer := zip.NewWriter(w) defer writer.Close() writer.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { return flate.NewWriter(out, level) }) // Reports zipping progress to the log each second. lastReport := time.Time{} progress := func(count int) { if time.Since(lastReport) > time.Second { lastReport = time.Now() logging.Infof(ctx, "Zipping files: %d files left", len(files)-count) } } for i, in := range files { progress(i) // Bail out early if context is canceled. if err := ctx.Err(); err != nil { return err } // Intentionally do not add file mode to make zip archive // deterministic. Timestamps sometimes need to be preserved, but normally // are zero valued. See also zip.FileInfoHeader() implementation. fh := zip.FileHeader{ Name: in.Name(), Method: zip.Deflate, } if level == 0 || in.Symlink() || isLikelyAlreadyCompressed(in) { fh.Method = zip.Store } mode := os.FileMode(0400) if in.Executable() { mode |= 0100 } if in.Writable() { mode |= 0200 } if in.Symlink() { mode |= os.ModeSymlink } fh.SetMode(mode) if !in.ModTime().IsZero() { fh.SetModTime(in.ModTime()) } fh.ExternalAttrs |= uint32(in.WinAttrs()) dst, err := writer.CreateHeader(&fh) if err != nil { return err } if in.Symlink() { err = zipSymlinkFile(dst, in) } else { err = zipRegularFile(dst, in) } if err != nil { return err } } return nil }
go
func zipInputFiles(ctx context.Context, files []fs.File, w io.Writer, level int) error { logging.Infof(ctx, "About to zip %d files with compression level %d", len(files), level) writer := zip.NewWriter(w) defer writer.Close() writer.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { return flate.NewWriter(out, level) }) // Reports zipping progress to the log each second. lastReport := time.Time{} progress := func(count int) { if time.Since(lastReport) > time.Second { lastReport = time.Now() logging.Infof(ctx, "Zipping files: %d files left", len(files)-count) } } for i, in := range files { progress(i) // Bail out early if context is canceled. if err := ctx.Err(); err != nil { return err } // Intentionally do not add file mode to make zip archive // deterministic. Timestamps sometimes need to be preserved, but normally // are zero valued. See also zip.FileInfoHeader() implementation. fh := zip.FileHeader{ Name: in.Name(), Method: zip.Deflate, } if level == 0 || in.Symlink() || isLikelyAlreadyCompressed(in) { fh.Method = zip.Store } mode := os.FileMode(0400) if in.Executable() { mode |= 0100 } if in.Writable() { mode |= 0200 } if in.Symlink() { mode |= os.ModeSymlink } fh.SetMode(mode) if !in.ModTime().IsZero() { fh.SetModTime(in.ModTime()) } fh.ExternalAttrs |= uint32(in.WinAttrs()) dst, err := writer.CreateHeader(&fh) if err != nil { return err } if in.Symlink() { err = zipSymlinkFile(dst, in) } else { err = zipRegularFile(dst, in) } if err != nil { return err } } return nil }
[ "func", "zipInputFiles", "(", "ctx", "context", ".", "Context", ",", "files", "[", "]", "fs", ".", "File", ",", "w", "io", ".", "Writer", ",", "level", "int", ")", "error", "{", "logging", ".", "Infof", "(", "ctx", ",", "\"", "\"", ",", "len", "(...
// zipInputFiles deterministically builds a zip archive out of input files and // writes it to the writer. Files are written in the order given.
[ "zipInputFiles", "deterministically", "builds", "a", "zip", "archive", "out", "of", "input", "files", "and", "writes", "it", "to", "the", "writer", ".", "Files", "are", "written", "in", "the", "order", "given", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/builder/builder.go#L139-L210
8,750
luci/luci-go
cipd/client/cipd/builder/builder.go
makeManifestFile
func makeManifestFile(opts Options) (fs.File, error) { if opts.VersionFile != "" && !fs.IsCleanSlashPath(opts.VersionFile) { return nil, fmt.Errorf("version file path should be a clean path relative to a package root: %s", opts.VersionFile) } if err := pkg.ValidateInstallMode(opts.InstallMode); err != nil { return nil, err } formatVer := pkg.ManifestFormatVersion if opts.OverrideFormatVersion != "" { formatVer = opts.OverrideFormatVersion } buf := &bytes.Buffer{} err := pkg.WriteManifest(&pkg.Manifest{ FormatVersion: formatVer, PackageName: opts.PackageName, VersionFile: opts.VersionFile, InstallMode: opts.InstallMode, }, buf) if err != nil { return nil, err } out := manifestFile(buf.Bytes()) return &out, nil }
go
func makeManifestFile(opts Options) (fs.File, error) { if opts.VersionFile != "" && !fs.IsCleanSlashPath(opts.VersionFile) { return nil, fmt.Errorf("version file path should be a clean path relative to a package root: %s", opts.VersionFile) } if err := pkg.ValidateInstallMode(opts.InstallMode); err != nil { return nil, err } formatVer := pkg.ManifestFormatVersion if opts.OverrideFormatVersion != "" { formatVer = opts.OverrideFormatVersion } buf := &bytes.Buffer{} err := pkg.WriteManifest(&pkg.Manifest{ FormatVersion: formatVer, PackageName: opts.PackageName, VersionFile: opts.VersionFile, InstallMode: opts.InstallMode, }, buf) if err != nil { return nil, err } out := manifestFile(buf.Bytes()) return &out, nil }
[ "func", "makeManifestFile", "(", "opts", "Options", ")", "(", "fs", ".", "File", ",", "error", ")", "{", "if", "opts", ".", "VersionFile", "!=", "\"", "\"", "&&", "!", "fs", ".", "IsCleanSlashPath", "(", "opts", ".", "VersionFile", ")", "{", "return", ...
// makeManifestFile generates a package manifest file and returns it as // File interface.
[ "makeManifestFile", "generates", "a", "package", "manifest", "file", "and", "returns", "it", "as", "File", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/builder/builder.go#L343-L366
8,751
luci/luci-go
common/tsmon/state.go
NewState
func NewState() *State { return &State{ store: store.NewNilStore(), monitor: monitor.NewNilMonitor(), invokeGlobalCallbacksOnFlush: true, } }
go
func NewState() *State { return &State{ store: store.NewNilStore(), monitor: monitor.NewNilMonitor(), invokeGlobalCallbacksOnFlush: true, } }
[ "func", "NewState", "(", ")", "*", "State", "{", "return", "&", "State", "{", "store", ":", "store", ".", "NewNilStore", "(", ")", ",", "monitor", ":", "monitor", ".", "NewNilMonitor", "(", ")", ",", "invokeGlobalCallbacksOnFlush", ":", "true", ",", "}",...
// NewState returns a new State instance, configured with a nil store and nil // monitor. By default, global callbacks that are registered will be invoked // when flushing registered metrics.
[ "NewState", "returns", "a", "new", "State", "instance", "configured", "with", "a", "nil", "store", "and", "nil", "monitor", ".", "By", "default", "global", "callbacks", "that", "are", "registered", "will", "be", "invoked", "when", "flushing", "registered", "me...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L44-L50
8,752
luci/luci-go
common/tsmon/state.go
Callbacks
func (s *State) Callbacks() []Callback { s.mu.RLock() defer s.mu.RUnlock() return append([]Callback{}, s.callbacks...) }
go
func (s *State) Callbacks() []Callback { s.mu.RLock() defer s.mu.RUnlock() return append([]Callback{}, s.callbacks...) }
[ "func", "(", "s", "*", "State", ")", "Callbacks", "(", ")", "[", "]", "Callback", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "return", "append", "(", "[", "]", "Callback", "{", ...
// Callbacks returns all registered Callbacks.
[ "Callbacks", "returns", "all", "registered", "Callbacks", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L61-L66
8,753
luci/luci-go
common/tsmon/state.go
GlobalCallbacks
func (s *State) GlobalCallbacks() []GlobalCallback { s.mu.RLock() defer s.mu.RUnlock() return append([]GlobalCallback{}, s.globalCallbacks...) }
go
func (s *State) GlobalCallbacks() []GlobalCallback { s.mu.RLock() defer s.mu.RUnlock() return append([]GlobalCallback{}, s.globalCallbacks...) }
[ "func", "(", "s", "*", "State", ")", "GlobalCallbacks", "(", ")", "[", "]", "GlobalCallback", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "return", "append", "(", "[", "]", "Global...
// GlobalCallbacks returns all registered GlobalCallbacks.
[ "GlobalCallbacks", "returns", "all", "registered", "GlobalCallbacks", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L69-L74
8,754
luci/luci-go
common/tsmon/state.go
InhibitGlobalCallbacksOnFlush
func (s *State) InhibitGlobalCallbacksOnFlush() { s.mu.Lock() defer s.mu.Unlock() s.invokeGlobalCallbacksOnFlush = false }
go
func (s *State) InhibitGlobalCallbacksOnFlush() { s.mu.Lock() defer s.mu.Unlock() s.invokeGlobalCallbacksOnFlush = false }
[ "func", "(", "s", "*", "State", ")", "InhibitGlobalCallbacksOnFlush", "(", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "s", ".", "invokeGlobalCallbacksOnFlush", "=", "false", "\n", ...
// InhibitGlobalCallbacksOnFlush signals that the registered global callbacks // are not to be executed upon flushing registered metrics.
[ "InhibitGlobalCallbacksOnFlush", "signals", "that", "the", "registered", "global", "callbacks", "are", "not", "to", "be", "executed", "upon", "flushing", "registered", "metrics", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L78-L83
8,755
luci/luci-go
common/tsmon/state.go
InvokeGlobalCallbacksOnFlush
func (s *State) InvokeGlobalCallbacksOnFlush() { s.mu.Lock() defer s.mu.Unlock() s.invokeGlobalCallbacksOnFlush = true }
go
func (s *State) InvokeGlobalCallbacksOnFlush() { s.mu.Lock() defer s.mu.Unlock() s.invokeGlobalCallbacksOnFlush = true }
[ "func", "(", "s", "*", "State", ")", "InvokeGlobalCallbacksOnFlush", "(", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "s", ".", "invokeGlobalCallbacksOnFlush", "=", "true", "\n", "}...
// InvokeGlobalCallbacksOnFlush signals that the registered global callbacks // are to be be executed upon flushing registered metrics.
[ "InvokeGlobalCallbacksOnFlush", "signals", "that", "the", "registered", "global", "callbacks", "are", "to", "be", "be", "executed", "upon", "flushing", "registered", "metrics", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L87-L92
8,756
luci/luci-go
common/tsmon/state.go
Monitor
func (s *State) Monitor() monitor.Monitor { s.mu.RLock() defer s.mu.RUnlock() return s.monitor }
go
func (s *State) Monitor() monitor.Monitor { s.mu.RLock() defer s.mu.RUnlock() return s.monitor }
[ "func", "(", "s", "*", "State", ")", "Monitor", "(", ")", "monitor", ".", "Monitor", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "return", "s", ".", "monitor", "\n", "}" ]
// Monitor returns the State's monitor.
[ "Monitor", "returns", "the", "State", "s", "monitor", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L95-L100
8,757
luci/luci-go
common/tsmon/state.go
Store
func (s *State) Store() store.Store { s.mu.RLock() defer s.mu.RUnlock() return s.store }
go
func (s *State) Store() store.Store { s.mu.RLock() defer s.mu.RUnlock() return s.store }
[ "func", "(", "s", "*", "State", ")", "Store", "(", ")", "store", ".", "Store", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "return", "s", ".", "store", "\n", "}" ]
// Store returns the State's store.
[ "Store", "returns", "the", "State", "s", "store", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L119-L124
8,758
luci/luci-go
common/tsmon/state.go
SetMonitor
func (s *State) SetMonitor(m monitor.Monitor) { s.mu.Lock() defer s.mu.Unlock() s.monitor = m }
go
func (s *State) SetMonitor(m monitor.Monitor) { s.mu.Lock() defer s.mu.Unlock() s.monitor = m }
[ "func", "(", "s", "*", "State", ")", "SetMonitor", "(", "m", "monitor", ".", "Monitor", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "s", ".", "monitor", "=", "m", "\n", "}" ...
// SetMonitor sets the Store's monitor.
[ "SetMonitor", "sets", "the", "Store", "s", "monitor", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L127-L132
8,759
luci/luci-go
common/tsmon/state.go
SetStore
func (s *State) SetStore(st store.Store) { s.mu.Lock() defer s.mu.Unlock() s.store = st }
go
func (s *State) SetStore(st store.Store) { s.mu.Lock() defer s.mu.Unlock() s.store = st }
[ "func", "(", "s", "*", "State", ")", "SetStore", "(", "st", "store", ".", "Store", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "s", ".", "store", "=", "st", "\n", "}" ]
// SetStore changes the metric store. All metrics that were registered with // the old store will be re-registered on the new store.
[ "SetStore", "changes", "the", "metric", "store", ".", "All", "metrics", "that", "were", "registered", "with", "the", "old", "store", "will", "be", "re", "-", "registered", "on", "the", "new", "store", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L136-L141
8,760
luci/luci-go
common/tsmon/state.go
ResetCumulativeMetrics
func (s *State) ResetCumulativeMetrics(ctx context.Context) { store := s.Store() registry.Iter(func(m types.Metric) { if m.Info().ValueType.IsCumulative() { store.Reset(ctx, m) } }) }
go
func (s *State) ResetCumulativeMetrics(ctx context.Context) { store := s.Store() registry.Iter(func(m types.Metric) { if m.Info().ValueType.IsCumulative() { store.Reset(ctx, m) } }) }
[ "func", "(", "s", "*", "State", ")", "ResetCumulativeMetrics", "(", "ctx", "context", ".", "Context", ")", "{", "store", ":=", "s", ".", "Store", "(", ")", "\n\n", "registry", ".", "Iter", "(", "func", "(", "m", "types", ".", "Metric", ")", "{", "i...
// ResetCumulativeMetrics resets only cumulative metrics.
[ "ResetCumulativeMetrics", "resets", "only", "cumulative", "metrics", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L144-L152
8,761
luci/luci-go
common/tsmon/state.go
RunGlobalCallbacks
func (s *State) RunGlobalCallbacks(ctx context.Context) { for _, cb := range s.GlobalCallbacks() { cb.Callback(ctx) } }
go
func (s *State) RunGlobalCallbacks(ctx context.Context) { for _, cb := range s.GlobalCallbacks() { cb.Callback(ctx) } }
[ "func", "(", "s", "*", "State", ")", "RunGlobalCallbacks", "(", "ctx", "context", ".", "Context", ")", "{", "for", "_", ",", "cb", ":=", "range", "s", ".", "GlobalCallbacks", "(", ")", "{", "cb", ".", "Callback", "(", "ctx", ")", "\n", "}", "\n", ...
// RunGlobalCallbacks runs all registered global callbacks that produce global // metrics. // // See RegisterGlobalCallback for more info.
[ "RunGlobalCallbacks", "runs", "all", "registered", "global", "callbacks", "that", "produce", "global", "metrics", ".", "See", "RegisterGlobalCallback", "for", "more", "info", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L158-L162
8,762
luci/luci-go
common/tsmon/state.go
Flush
func (s *State) Flush(ctx context.Context, mon monitor.Monitor) error { if mon == nil { mon = s.Monitor() } if mon == nil { return errors.New("no tsmon Monitor is configured") } // Run any callbacks that have been registered to populate values in callback // metrics. s.runCallbacks(ctx) if s.invokeGlobalCallbacksOnFlush { s.RunGlobalCallbacks(ctx) } cells := s.store.GetAll(ctx) if len(cells) == 0 { return nil } logging.Debugf(ctx, "Starting tsmon flush: %d cells", len(cells)) defer logging.Debugf(ctx, "Finished tsmon flush") // Split up the payload into chunks if there are too many cells. chunkSize := mon.ChunkSize() if chunkSize == 0 { chunkSize = len(cells) } var failedSends int var lastErr error for len(cells) > 0 { count := minInt(chunkSize, len(cells)) if err := mon.Send(ctx, cells[:count]); err != nil { logging.Errorf(ctx, "Failed to send %d cells: %v", count, err) failedSends += count lastErr = err // Continue anyway. } cells = cells[count:] } logging.Debugf(ctx, "Sent %d/%d cells", len(cells)-failedSends, len(cells)) s.resetGlobalCallbackMetrics(ctx) return lastErr }
go
func (s *State) Flush(ctx context.Context, mon monitor.Monitor) error { if mon == nil { mon = s.Monitor() } if mon == nil { return errors.New("no tsmon Monitor is configured") } // Run any callbacks that have been registered to populate values in callback // metrics. s.runCallbacks(ctx) if s.invokeGlobalCallbacksOnFlush { s.RunGlobalCallbacks(ctx) } cells := s.store.GetAll(ctx) if len(cells) == 0 { return nil } logging.Debugf(ctx, "Starting tsmon flush: %d cells", len(cells)) defer logging.Debugf(ctx, "Finished tsmon flush") // Split up the payload into chunks if there are too many cells. chunkSize := mon.ChunkSize() if chunkSize == 0 { chunkSize = len(cells) } var failedSends int var lastErr error for len(cells) > 0 { count := minInt(chunkSize, len(cells)) if err := mon.Send(ctx, cells[:count]); err != nil { logging.Errorf(ctx, "Failed to send %d cells: %v", count, err) failedSends += count lastErr = err // Continue anyway. } cells = cells[count:] } logging.Debugf(ctx, "Sent %d/%d cells", len(cells)-failedSends, len(cells)) s.resetGlobalCallbackMetrics(ctx) return lastErr }
[ "func", "(", "s", "*", "State", ")", "Flush", "(", "ctx", "context", ".", "Context", ",", "mon", "monitor", ".", "Monitor", ")", "error", "{", "if", "mon", "==", "nil", "{", "mon", "=", "s", ".", "Monitor", "(", ")", "\n", "}", "\n\n", "if", "m...
// Flush sends all the metrics that are registered in the application. // // Uses given monitor if not nil, otherwise the State's current monitor.
[ "Flush", "sends", "all", "the", "metrics", "that", "are", "registered", "in", "the", "application", ".", "Uses", "given", "monitor", "if", "not", "nil", "otherwise", "the", "State", "s", "current", "monitor", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L167-L216
8,763
luci/luci-go
common/tsmon/state.go
resetGlobalCallbackMetrics
func (s *State) resetGlobalCallbackMetrics(ctx context.Context) { store := s.Store() for _, cb := range s.GlobalCallbacks() { for _, m := range cb.metrics { store.Reset(ctx, m) } } }
go
func (s *State) resetGlobalCallbackMetrics(ctx context.Context) { store := s.Store() for _, cb := range s.GlobalCallbacks() { for _, m := range cb.metrics { store.Reset(ctx, m) } } }
[ "func", "(", "s", "*", "State", ")", "resetGlobalCallbackMetrics", "(", "ctx", "context", ".", "Context", ")", "{", "store", ":=", "s", ".", "Store", "(", ")", "\n\n", "for", "_", ",", "cb", ":=", "range", "s", ".", "GlobalCallbacks", "(", ")", "{", ...
// resetGlobalCallbackMetrics resets metrics produced by global callbacks. // // See RegisterGlobalCallback for more info.
[ "resetGlobalCallbackMetrics", "resets", "metrics", "produced", "by", "global", "callbacks", ".", "See", "RegisterGlobalCallback", "for", "more", "info", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L221-L229
8,764
luci/luci-go
common/tsmon/state.go
runCallbacks
func (s *State) runCallbacks(ctx context.Context) { for _, cb := range s.Callbacks() { cb(ctx) } }
go
func (s *State) runCallbacks(ctx context.Context) { for _, cb := range s.Callbacks() { cb(ctx) } }
[ "func", "(", "s", "*", "State", ")", "runCallbacks", "(", "ctx", "context", ".", "Context", ")", "{", "for", "_", ",", "cb", ":=", "range", "s", ".", "Callbacks", "(", ")", "{", "cb", "(", "ctx", ")", "\n", "}", "\n", "}" ]
// runCallbacks runs any callbacks that have been registered to populate values // in callback metrics.
[ "runCallbacks", "runs", "any", "callbacks", "that", "have", "been", "registered", "to", "populate", "values", "in", "callback", "metrics", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/state.go#L233-L237
8,765
luci/luci-go
logdog/client/butler/buffered_callback/datagram.go
assertGetDatagram
func assertGetDatagram(le *logpb.LogEntry) *logpb.Datagram { if dg := le.GetDatagram(); dg == nil { panic( errors.Annotate( InvalidStreamType, fmt.Sprintf("got %T, expected *logpb.LogEntry_Datagram", le.Content), ).Err(), ) } else { return dg } }
go
func assertGetDatagram(le *logpb.LogEntry) *logpb.Datagram { if dg := le.GetDatagram(); dg == nil { panic( errors.Annotate( InvalidStreamType, fmt.Sprintf("got %T, expected *logpb.LogEntry_Datagram", le.Content), ).Err(), ) } else { return dg } }
[ "func", "assertGetDatagram", "(", "le", "*", "logpb", ".", "LogEntry", ")", "*", "logpb", ".", "Datagram", "{", "if", "dg", ":=", "le", ".", "GetDatagram", "(", ")", ";", "dg", "==", "nil", "{", "panic", "(", "errors", ".", "Annotate", "(", "InvalidS...
// assertGetDatagram panics if the passed LogEntry does not contain Datagram data, or returns it.
[ "assertGetDatagram", "panics", "if", "the", "passed", "LogEntry", "does", "not", "contain", "Datagram", "data", "or", "returns", "it", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/buffered_callback/datagram.go#L26-L37
8,766
luci/luci-go
appengine/datastorecache/manager.go
installCronRoute
func (m *manager) installCronRoute(path string, r *router.Router, base router.MiddlewareChain) { r.GET(path, base, errHTTPHandler(m.handleManageCronGET)) }
go
func (m *manager) installCronRoute(path string, r *router.Router, base router.MiddlewareChain) { r.GET(path, base, errHTTPHandler(m.handleManageCronGET)) }
[ "func", "(", "m", "*", "manager", ")", "installCronRoute", "(", "path", "string", ",", "r", "*", "router", ".", "Router", ",", "base", "router", ".", "MiddlewareChain", ")", "{", "r", ".", "GET", "(", "path", ",", "base", ",", "errHTTPHandler", "(", ...
// installCronRoute installs a handler for this manager's cron task into the // supplied Router at the specified path. // // It is recommended to assert in the middleware that this endpoint is only // accessible from a cron task.
[ "installCronRoute", "installs", "a", "handler", "for", "this", "manager", "s", "cron", "task", "into", "the", "supplied", "Router", "at", "the", "specified", "path", ".", "It", "is", "recommended", "to", "assert", "in", "the", "middleware", "that", "this", "...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/datastorecache/manager.go#L84-L86
8,767
luci/luci-go
logdog/client/butlerlib/streamproto/streamType.go
DefaultContentType
func (t StreamType) DefaultContentType() types.ContentType { switch logpb.StreamType(t) { case logpb.StreamType_TEXT: return types.ContentTypeText case logpb.StreamType_DATAGRAM: return types.ContentTypeLogdogDatagram case logpb.StreamType_BINARY: fallthrough default: return types.ContentTypeBinary } }
go
func (t StreamType) DefaultContentType() types.ContentType { switch logpb.StreamType(t) { case logpb.StreamType_TEXT: return types.ContentTypeText case logpb.StreamType_DATAGRAM: return types.ContentTypeLogdogDatagram case logpb.StreamType_BINARY: fallthrough default: return types.ContentTypeBinary } }
[ "func", "(", "t", "StreamType", ")", "DefaultContentType", "(", ")", "types", ".", "ContentType", "{", "switch", "logpb", ".", "StreamType", "(", "t", ")", "{", "case", "logpb", ".", "StreamType_TEXT", ":", "return", "types", ".", "ContentTypeText", "\n\n", ...
// DefaultContentType returns the default ContentType for a given stream type.
[ "DefaultContentType", "returns", "the", "default", "ContentType", "for", "a", "given", "stream", "type", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamproto/streamType.go#L31-L44
8,768
luci/luci-go
common/api/gerrit/gerrit.go
NormalizeGerritURL
func NormalizeGerritURL(gerritURL string) (string, error) { u, err := url.Parse(gerritURL) if err != nil { return "", err } if u.Scheme != "https" { return "", fmt.Errorf("%s should start with https://", gerritURL) } if !strings.HasSuffix(u.Host, "-review.googlesource.com") { return "", errors.New("only *-review.googlesource.com Gerrits supported") } if u.Fragment != "" { return "", errors.New("no fragments allowed in gerritURL") } if u.Path != "" && u.Path != "/" { return "", errors.New("Unexpected path in URL") } if u.Path != "/" { u.Path = "/" } return u.String(), nil }
go
func NormalizeGerritURL(gerritURL string) (string, error) { u, err := url.Parse(gerritURL) if err != nil { return "", err } if u.Scheme != "https" { return "", fmt.Errorf("%s should start with https://", gerritURL) } if !strings.HasSuffix(u.Host, "-review.googlesource.com") { return "", errors.New("only *-review.googlesource.com Gerrits supported") } if u.Fragment != "" { return "", errors.New("no fragments allowed in gerritURL") } if u.Path != "" && u.Path != "/" { return "", errors.New("Unexpected path in URL") } if u.Path != "/" { u.Path = "/" } return u.String(), nil }
[ "func", "NormalizeGerritURL", "(", "gerritURL", "string", ")", "(", "string", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "gerritURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}...
// NormalizeGerritURL returns canonical for Gerrit URL. // // error is returned if validation fails.
[ "NormalizeGerritURL", "returns", "canonical", "for", "Gerrit", "URL", ".", "error", "is", "returned", "if", "validation", "fails", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gerrit/gerrit.go#L246-L267
8,769
luci/luci-go
common/api/gerrit/gerrit.go
NewClient
func NewClient(c *http.Client, gerritURL string) (*Client, error) { u, err := NormalizeGerritURL(gerritURL) if err != nil { return nil, err } pu, err := url.Parse(u) if err != nil { return nil, err } return &Client{c, *pu}, nil }
go
func NewClient(c *http.Client, gerritURL string) (*Client, error) { u, err := NormalizeGerritURL(gerritURL) if err != nil { return nil, err } pu, err := url.Parse(u) if err != nil { return nil, err } return &Client{c, *pu}, nil }
[ "func", "NewClient", "(", "c", "*", "http", ".", "Client", ",", "gerritURL", "string", ")", "(", "*", "Client", ",", "error", ")", "{", "u", ",", "err", ":=", "NormalizeGerritURL", "(", "gerritURL", ")", "\n", "if", "err", "!=", "nil", "{", "return",...
// NewClient creates a new instance of Client and validates and stores // the URL to reach Gerrit. The result is wrapped inside a Client so that // the apis can be called directly on the value returned by this function.
[ "NewClient", "creates", "a", "new", "instance", "of", "Client", "and", "validates", "and", "stores", "the", "URL", "to", "reach", "Gerrit", ".", "The", "result", "is", "wrapped", "inside", "a", "Client", "so", "that", "the", "apis", "can", "be", "called", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gerrit/gerrit.go#L282-L292
8,770
luci/luci-go
common/api/gerrit/gerrit.go
queryString
func (qr *ChangeQueryParams) queryString() url.Values { qs := make(url.Values, len(qr.Options)+3) qs.Add("q", qr.Query) if qr.N > 0 { qs.Add("n", strconv.Itoa(qr.N)) } if qr.S > 0 { qs.Add("S", strconv.Itoa(qr.S)) } for _, o := range qr.Options { qs.Add("o", o) } return qs }
go
func (qr *ChangeQueryParams) queryString() url.Values { qs := make(url.Values, len(qr.Options)+3) qs.Add("q", qr.Query) if qr.N > 0 { qs.Add("n", strconv.Itoa(qr.N)) } if qr.S > 0 { qs.Add("S", strconv.Itoa(qr.S)) } for _, o := range qr.Options { qs.Add("o", o) } return qs }
[ "func", "(", "qr", "*", "ChangeQueryParams", ")", "queryString", "(", ")", "url", ".", "Values", "{", "qs", ":=", "make", "(", "url", ".", "Values", ",", "len", "(", "qr", ".", "Options", ")", "+", "3", ")", "\n", "qs", ".", "Add", "(", "\"", "...
// queryString renders the ChangeQueryParams as a url.Values.
[ "queryString", "renders", "the", "ChangeQueryParams", "as", "a", "url", ".", "Values", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gerrit/gerrit.go#L314-L327
8,771
luci/luci-go
common/api/gerrit/gerrit.go
ChangeQuery
func (c *Client) ChangeQuery(ctx context.Context, qr ChangeQueryParams) ([]*Change, bool, error) { var resp struct { Collection []*Change } if _, err := c.get(ctx, "a/changes/", qr.queryString(), &resp.Collection); err != nil { return nil, false, err } result := resp.Collection if len(result) == 0 { return nil, false, nil } moreChanges := result[len(result)-1].MoreChanges result[len(result)-1].MoreChanges = false return result, moreChanges, nil }
go
func (c *Client) ChangeQuery(ctx context.Context, qr ChangeQueryParams) ([]*Change, bool, error) { var resp struct { Collection []*Change } if _, err := c.get(ctx, "a/changes/", qr.queryString(), &resp.Collection); err != nil { return nil, false, err } result := resp.Collection if len(result) == 0 { return nil, false, nil } moreChanges := result[len(result)-1].MoreChanges result[len(result)-1].MoreChanges = false return result, moreChanges, nil }
[ "func", "(", "c", "*", "Client", ")", "ChangeQuery", "(", "ctx", "context", ".", "Context", ",", "qr", "ChangeQueryParams", ")", "(", "[", "]", "*", "Change", ",", "bool", ",", "error", ")", "{", "var", "resp", "struct", "{", "Collection", "[", "]", ...
// ChangeQuery returns a list of Gerrit changes for a given ChangeQueryParams. // // One example use case for this is getting the CL for a given commit hash. // Only the .Query property of the qr parameter is required. // // Returns a slice of Change, whether there are more changes to fetch // and an error.
[ "ChangeQuery", "returns", "a", "list", "of", "Gerrit", "changes", "for", "a", "given", "ChangeQueryParams", ".", "One", "example", "use", "case", "for", "this", "is", "getting", "the", "CL", "for", "a", "given", "commit", "hash", ".", "Only", "the", ".", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gerrit/gerrit.go#L336-L350
8,772
luci/luci-go
common/api/gerrit/gerrit.go
queryString
func (qr *ChangeDetailsParams) queryString() url.Values { qs := make(url.Values, len(qr.Options)) for _, o := range qr.Options { qs.Add("o", o) } return qs }
go
func (qr *ChangeDetailsParams) queryString() url.Values { qs := make(url.Values, len(qr.Options)) for _, o := range qr.Options { qs.Add("o", o) } return qs }
[ "func", "(", "qr", "*", "ChangeDetailsParams", ")", "queryString", "(", ")", "url", ".", "Values", "{", "qs", ":=", "make", "(", "url", ".", "Values", ",", "len", "(", "qr", ".", "Options", ")", ")", "\n", "for", "_", ",", "o", ":=", "range", "qr...
// queryString renders the ChangeDetailsParams as a url.Values.
[ "queryString", "renders", "the", "ChangeDetailsParams", "as", "a", "url", ".", "Values", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gerrit/gerrit.go#L364-L370
8,773
luci/luci-go
common/api/gerrit/gerrit.go
CreateChange
func (c *Client) CreateChange(ctx context.Context, ci *ChangeInput) (*Change, error) { var resp Change if _, err := c.post(ctx, "a/changes/", ci, &resp); err != nil { return nil, err } return &resp, nil }
go
func (c *Client) CreateChange(ctx context.Context, ci *ChangeInput) (*Change, error) { var resp Change if _, err := c.post(ctx, "a/changes/", ci, &resp); err != nil { return nil, err } return &resp, nil }
[ "func", "(", "c", "*", "Client", ")", "CreateChange", "(", "ctx", "context", ".", "Context", ",", "ci", "*", "ChangeInput", ")", "(", "*", "Change", ",", "error", ")", "{", "var", "resp", "Change", "\n", "if", "_", ",", "err", ":=", "c", ".", "po...
// CreateChange creates a new change in Gerrit. // // Returns a Change describing the newly created change or an error.
[ "CreateChange", "creates", "a", "new", "change", "in", "Gerrit", ".", "Returns", "a", "Change", "describing", "the", "newly", "created", "change", "or", "an", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gerrit/gerrit.go#L446-L452
8,774
luci/luci-go
milo/buildsource/buildbot/buildstore/query.go
GetBuilds
func GetBuilds(c context.Context, q Query) (*QueryResult, error) { switch { case q.Master == "": return nil, errors.New("master is required") case q.Builder == "": return nil, errors.New("builder is required") } if !EmulationEnabled(c) { return getDatastoreBuilds(c, q, true) } var emulatedBuilds, buildbotBuilds []*buildbot.Build err := parallel.FanOutIn(func(work chan<- func() error) { work <- func() (err error) { res, err := getDatastoreBuilds(c, q, false) if res != nil { buildbotBuilds = res.Builds } return } work <- func() (err error) { emulatedBuilds, err = getEmulatedBuilds(c, q) return } }) if err != nil { return nil, errors.Annotate(err, "could not load builds").Err() } mergedBuilds := mergeBuilds(emulatedBuilds, buildbotBuilds) if q.Limit > 0 && len(mergedBuilds) > q.Limit { mergedBuilds = mergedBuilds[:q.Limit] } return &QueryResult{Builds: mergedBuilds}, nil }
go
func GetBuilds(c context.Context, q Query) (*QueryResult, error) { switch { case q.Master == "": return nil, errors.New("master is required") case q.Builder == "": return nil, errors.New("builder is required") } if !EmulationEnabled(c) { return getDatastoreBuilds(c, q, true) } var emulatedBuilds, buildbotBuilds []*buildbot.Build err := parallel.FanOutIn(func(work chan<- func() error) { work <- func() (err error) { res, err := getDatastoreBuilds(c, q, false) if res != nil { buildbotBuilds = res.Builds } return } work <- func() (err error) { emulatedBuilds, err = getEmulatedBuilds(c, q) return } }) if err != nil { return nil, errors.Annotate(err, "could not load builds").Err() } mergedBuilds := mergeBuilds(emulatedBuilds, buildbotBuilds) if q.Limit > 0 && len(mergedBuilds) > q.Limit { mergedBuilds = mergedBuilds[:q.Limit] } return &QueryResult{Builds: mergedBuilds}, nil }
[ "func", "GetBuilds", "(", "c", "context", ".", "Context", ",", "q", "Query", ")", "(", "*", "QueryResult", ",", "error", ")", "{", "switch", "{", "case", "q", ".", "Master", "==", "\"", "\"", ":", "return", "nil", ",", "errors", ".", "New", "(", ...
// GetBuilds executes a build query and returns results. // Does not check access.
[ "GetBuilds", "executes", "a", "build", "query", "and", "returns", "results", ".", "Does", "not", "check", "access", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/query.go#L112-L147
8,775
luci/luci-go
milo/buildsource/buildbot/buildstore/query.go
mergeBuilds
func mergeBuilds(a, b []*buildbot.Build) []*buildbot.Build { ret := make([]*buildbot.Build, len(a), len(a)+len(b)) copy(ret, a) // add builds from b that have unique build numbers. aNumbers := make(map[int]struct{}, len(a)) for _, build := range a { aNumbers[build.Number] = struct{}{} } for _, build := range b { if _, ok := aNumbers[build.Number]; !ok { ret = append(ret, build) } } sort.Slice(ret, func(i, j int) bool { return ret[i].Number > ret[j].Number }) return ret }
go
func mergeBuilds(a, b []*buildbot.Build) []*buildbot.Build { ret := make([]*buildbot.Build, len(a), len(a)+len(b)) copy(ret, a) // add builds from b that have unique build numbers. aNumbers := make(map[int]struct{}, len(a)) for _, build := range a { aNumbers[build.Number] = struct{}{} } for _, build := range b { if _, ok := aNumbers[build.Number]; !ok { ret = append(ret, build) } } sort.Slice(ret, func(i, j int) bool { return ret[i].Number > ret[j].Number }) return ret }
[ "func", "mergeBuilds", "(", "a", ",", "b", "[", "]", "*", "buildbot", ".", "Build", ")", "[", "]", "*", "buildbot", ".", "Build", "{", "ret", ":=", "make", "(", "[", "]", "*", "buildbot", ".", "Build", ",", "len", "(", "a", ")", ",", "len", "...
// mergeBuilds merges builds from a and b to one slice. // The returned builds are ordered by build numbers, descending. // // If a build number is present in both a and b, b's build is ignored.
[ "mergeBuilds", "merges", "builds", "from", "a", "and", "b", "to", "one", "slice", ".", "The", "returned", "builds", "are", "ordered", "by", "build", "numbers", "descending", ".", "If", "a", "build", "number", "is", "present", "in", "both", "a", "and", "b...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/query.go#L153-L171
8,776
luci/luci-go
scheduler/appengine/task/utils/kvlist.go
ValidateKVList
func ValidateKVList(kind string, list []string, sep rune) error { for _, item := range list { if !strings.ContainsRune(item, sep) { return fmt.Errorf("bad %s, not a 'key%svalue' pair: %q", kind, string(sep), item) } } return nil }
go
func ValidateKVList(kind string, list []string, sep rune) error { for _, item := range list { if !strings.ContainsRune(item, sep) { return fmt.Errorf("bad %s, not a 'key%svalue' pair: %q", kind, string(sep), item) } } return nil }
[ "func", "ValidateKVList", "(", "kind", "string", ",", "list", "[", "]", "string", ",", "sep", "rune", ")", "error", "{", "for", "_", ",", "item", ":=", "range", "list", "{", "if", "!", "strings", ".", "ContainsRune", "(", "item", ",", "sep", ")", "...
// ValidateKVList makes sure each string in the list is valid key-value pair.
[ "ValidateKVList", "makes", "sure", "each", "string", "in", "the", "list", "is", "valid", "key", "-", "value", "pair", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/utils/kvlist.go#L33-L40
8,777
luci/luci-go
scheduler/appengine/task/utils/kvlist.go
KVListFromMap
func KVListFromMap(m map[string]string) KVList { keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) } sort.Strings(keys) kvList := make([]KV, len(keys)) for i, k := range keys { kvList[i] = KV{ Key: k, Value: m[k], } } return kvList }
go
func KVListFromMap(m map[string]string) KVList { keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) } sort.Strings(keys) kvList := make([]KV, len(keys)) for i, k := range keys { kvList[i] = KV{ Key: k, Value: m[k], } } return kvList }
[ "func", "KVListFromMap", "(", "m", "map", "[", "string", "]", "string", ")", "KVList", "{", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "m", ")", ")", "\n", "for", "k", ":=", "range", "m", "{", "keys", "=", "append...
// KVListFromMap converts a map to KVList.
[ "KVListFromMap", "converts", "a", "map", "to", "KVList", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/utils/kvlist.go#L43-L57
8,778
luci/luci-go
scheduler/appengine/task/utils/kvlist.go
UnpackKVList
func UnpackKVList(list []string, sep rune) (out KVList) { for _, item := range list { idx := strings.IndexRune(item, sep) if idx == -1 { continue } out = append(out, KV{ Key: item[:idx], Value: item[idx+1:], }) } return out }
go
func UnpackKVList(list []string, sep rune) (out KVList) { for _, item := range list { idx := strings.IndexRune(item, sep) if idx == -1 { continue } out = append(out, KV{ Key: item[:idx], Value: item[idx+1:], }) } return out }
[ "func", "UnpackKVList", "(", "list", "[", "]", "string", ",", "sep", "rune", ")", "(", "out", "KVList", ")", "{", "for", "_", ",", "item", ":=", "range", "list", "{", "idx", ":=", "strings", ".", "IndexRune", "(", "item", ",", "sep", ")", "\n", "...
// UnpackKVList takes validated list of k-v pair strings and returns list of // structs. // // Silently skips malformed strings. Use ValidateKVList to detect them before // calling this function.
[ "UnpackKVList", "takes", "validated", "list", "of", "k", "-", "v", "pair", "strings", "and", "returns", "list", "of", "structs", ".", "Silently", "skips", "malformed", "strings", ".", "Use", "ValidateKVList", "to", "detect", "them", "before", "calling", "this"...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/utils/kvlist.go#L64-L76
8,779
luci/luci-go
scheduler/appengine/task/utils/kvlist.go
Pack
func (l KVList) Pack(sep rune) []string { out := make([]string, len(l)) for i, kv := range l { out[i] = kv.Key + string(sep) + kv.Value } return out }
go
func (l KVList) Pack(sep rune) []string { out := make([]string, len(l)) for i, kv := range l { out[i] = kv.Key + string(sep) + kv.Value } return out }
[ "func", "(", "l", "KVList", ")", "Pack", "(", "sep", "rune", ")", "[", "]", "string", "{", "out", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "l", ")", ")", "\n", "for", "i", ",", "kv", ":=", "range", "l", "{", "out", "[", "i", ...
// Pack converts KV list to a list of strings.
[ "Pack", "converts", "KV", "list", "to", "a", "list", "of", "strings", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/utils/kvlist.go#L79-L85
8,780
luci/luci-go
scheduler/appengine/engine/dsset/dsset.go
makeTombstonesEntity
func (p *PopOp) makeTombstonesEntity() *tombstonesEntity { p.entity.Tombstones = p.entity.Tombstones[:0] for id, ts := range p.tombs { p.entity.Tombstones = append(p.entity.Tombstones, struct { ID string Tombstoned time.Time }{id, ts}) } return p.entity }
go
func (p *PopOp) makeTombstonesEntity() *tombstonesEntity { p.entity.Tombstones = p.entity.Tombstones[:0] for id, ts := range p.tombs { p.entity.Tombstones = append(p.entity.Tombstones, struct { ID string Tombstoned time.Time }{id, ts}) } return p.entity }
[ "func", "(", "p", "*", "PopOp", ")", "makeTombstonesEntity", "(", ")", "*", "tombstonesEntity", "{", "p", ".", "entity", ".", "Tombstones", "=", "p", ".", "entity", ".", "Tombstones", "[", ":", "0", "]", "\n", "for", "id", ",", "ts", ":=", "range", ...
// makeTombstonesEntity is used internally by FinishPop.
[ "makeTombstonesEntity", "is", "used", "internally", "by", "FinishPop", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/dsset/dsset.go#L405-L414
8,781
luci/luci-go
scheduler/appengine/engine/dsset/dsset.go
shardRoot
func (s *Set) shardRoot(c context.Context, n int) *datastore.Key { return datastore.NewKey(c, "dsset.Shard", fmt.Sprintf("%s:%d", s.ID, n), 0, nil) }
go
func (s *Set) shardRoot(c context.Context, n int) *datastore.Key { return datastore.NewKey(c, "dsset.Shard", fmt.Sprintf("%s:%d", s.ID, n), 0, nil) }
[ "func", "(", "s", "*", "Set", ")", "shardRoot", "(", "c", "context", ".", "Context", ",", "n", "int", ")", "*", "datastore", ".", "Key", "{", "return", "datastore", ".", "NewKey", "(", "c", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", ...
// shardRoot returns entity group key to use for a given shard.
[ "shardRoot", "returns", "entity", "group", "key", "to", "use", "for", "a", "given", "shard", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/dsset/dsset.go#L529-L531
8,782
luci/luci-go
scheduler/appengine/engine/dsset/dsset.go
batchOp
func batchOp(total int, op func(start, end int) error) error { switch { case total == 0: return nil case total <= batchSize: return op(0, total) } errs := make(chan error) ops := 0 offset := 0 for total > 0 { count := batchSize if count > total { count = total } go func(start, end int) { errs <- op(start, end) }(offset, offset+count) offset += count total -= count ops++ } var all errors.MultiError for i := 0; i < ops; i++ { err := <-errs if merr, yep := err.(errors.MultiError); yep { for _, e := range merr { if e != nil { all = append(all, e) } } } else if err != nil { all = append(all, err) } } if len(all) == 0 { return nil } return all }
go
func batchOp(total int, op func(start, end int) error) error { switch { case total == 0: return nil case total <= batchSize: return op(0, total) } errs := make(chan error) ops := 0 offset := 0 for total > 0 { count := batchSize if count > total { count = total } go func(start, end int) { errs <- op(start, end) }(offset, offset+count) offset += count total -= count ops++ } var all errors.MultiError for i := 0; i < ops; i++ { err := <-errs if merr, yep := err.(errors.MultiError); yep { for _, e := range merr { if e != nil { all = append(all, e) } } } else if err != nil { all = append(all, err) } } if len(all) == 0 { return nil } return all }
[ "func", "batchOp", "(", "total", "int", ",", "op", "func", "(", "start", ",", "end", "int", ")", "error", ")", "error", "{", "switch", "{", "case", "total", "==", "0", ":", "return", "nil", "\n", "case", "total", "<=", "batchSize", ":", "return", "...
// batchOp splits 'total' into batches and calls 'op' in parallel. // // Doesn't preserve order of returned errors! Don't try to deconstruct the // returned multi error, the position of individual errors there does not // correlate with the original array.
[ "batchOp", "splits", "total", "into", "batches", "and", "calls", "op", "in", "parallel", ".", "Doesn", "t", "preserve", "order", "of", "returned", "errors!", "Don", "t", "try", "to", "deconstruct", "the", "returned", "multi", "error", "the", "position", "of"...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/dsset/dsset.go#L538-L580
8,783
luci/luci-go
buildbucket/cli/cl.go
retrieveCLs
func (f *clsFlag) retrieveCLs(ctx context.Context, httpClient *http.Client, requirePatchset bool) ([]*pb.GerritChange, error) { ret := make([]*pb.GerritChange, len(f.cls)) return ret, parallel.FanOutIn(func(work chan<- func() error) { for i, cl := range f.cls { i := i work <- func() error { change, err := f.retrieveCL(ctx, cl, httpClient, requirePatchset) if err != nil { return fmt.Errorf("CL %q: %s", cl, err) } ret[i] = change return nil } } }) }
go
func (f *clsFlag) retrieveCLs(ctx context.Context, httpClient *http.Client, requirePatchset bool) ([]*pb.GerritChange, error) { ret := make([]*pb.GerritChange, len(f.cls)) return ret, parallel.FanOutIn(func(work chan<- func() error) { for i, cl := range f.cls { i := i work <- func() error { change, err := f.retrieveCL(ctx, cl, httpClient, requirePatchset) if err != nil { return fmt.Errorf("CL %q: %s", cl, err) } ret[i] = change return nil } } }) }
[ "func", "(", "f", "*", "clsFlag", ")", "retrieveCLs", "(", "ctx", "context", ".", "Context", ",", "httpClient", "*", "http", ".", "Client", ",", "requirePatchset", "bool", ")", "(", "[", "]", "*", "pb", ".", "GerritChange", ",", "error", ")", "{", "r...
// retrieveCLs retrieves GerritChange objects from f.cls. // Makes Gerrit RPCs if necessary, in parallel.
[ "retrieveCLs", "retrieves", "GerritChange", "objects", "from", "f", ".", "cls", ".", "Makes", "Gerrit", "RPCs", "if", "necessary", "in", "parallel", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/cl.go#L45-L60
8,784
luci/luci-go
buildbucket/cli/cl.go
retrieveCL
func (f *clsFlag) retrieveCL(ctx context.Context, cl string, httpClient *http.Client, requirePatchset bool) (*pb.GerritChange, error) { ret, err := parseCL(cl) switch { case err != nil: return nil, err case requirePatchset && ret.Patchset == 0: return nil, fmt.Errorf("missing patchset number") case ret.Project != "" && ret.Patchset != 0: return ret, nil } // Fetch CL info from Gerrit. client, err := gerrit.NewRESTClient(httpClient, ret.Host, true) if err != nil { return nil, err } change, err := client.GetChange(ctx, &gerritpb.GetChangeRequest{ Number: ret.Change, Options: []gerritpb.QueryOption{gerritpb.QueryOption_CURRENT_REVISION}, }) if err != nil { return nil, fmt.Errorf("failed to fetch CL %d from %q: %s", ret.Change, ret.Host, err) } ret.Project = change.Project if ret.Patchset == 0 { ret.Patchset = int64(change.Revisions[change.CurrentRevision].Number) } return ret, nil }
go
func (f *clsFlag) retrieveCL(ctx context.Context, cl string, httpClient *http.Client, requirePatchset bool) (*pb.GerritChange, error) { ret, err := parseCL(cl) switch { case err != nil: return nil, err case requirePatchset && ret.Patchset == 0: return nil, fmt.Errorf("missing patchset number") case ret.Project != "" && ret.Patchset != 0: return ret, nil } // Fetch CL info from Gerrit. client, err := gerrit.NewRESTClient(httpClient, ret.Host, true) if err != nil { return nil, err } change, err := client.GetChange(ctx, &gerritpb.GetChangeRequest{ Number: ret.Change, Options: []gerritpb.QueryOption{gerritpb.QueryOption_CURRENT_REVISION}, }) if err != nil { return nil, fmt.Errorf("failed to fetch CL %d from %q: %s", ret.Change, ret.Host, err) } ret.Project = change.Project if ret.Patchset == 0 { ret.Patchset = int64(change.Revisions[change.CurrentRevision].Number) } return ret, nil }
[ "func", "(", "f", "*", "clsFlag", ")", "retrieveCL", "(", "ctx", "context", ".", "Context", ",", "cl", "string", ",", "httpClient", "*", "http", ".", "Client", ",", "requirePatchset", "bool", ")", "(", "*", "pb", ".", "GerritChange", ",", "error", ")",...
// retrieveCL retrieves a GerritChange from a string. // Makes a Gerrit RPC if necessary.
[ "retrieveCL", "retrieves", "a", "GerritChange", "from", "a", "string", ".", "Makes", "a", "Gerrit", "RPC", "if", "necessary", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/cl.go#L64-L93
8,785
luci/luci-go
machine-db/appengine/model/ips.go
fetch
func (t *IPsTable) fetch(c context.Context) error { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT id, ipv4, vlan_id FROM ips `) if err != nil { return errors.Annotate(err, "failed to select IP addresses").Err() } defer rows.Close() for rows.Next() { ip := &IP{} if err := rows.Scan(&ip.Id, &ip.IPv4, &ip.VLANId); err != nil { return errors.Annotate(err, "failed to scan IP address").Err() } t.current = append(t.current, ip) } return nil }
go
func (t *IPsTable) fetch(c context.Context) error { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT id, ipv4, vlan_id FROM ips `) if err != nil { return errors.Annotate(err, "failed to select IP addresses").Err() } defer rows.Close() for rows.Next() { ip := &IP{} if err := rows.Scan(&ip.Id, &ip.IPv4, &ip.VLANId); err != nil { return errors.Annotate(err, "failed to scan IP address").Err() } t.current = append(t.current, ip) } return nil }
[ "func", "(", "t", "*", "IPsTable", ")", "fetch", "(", "c", "context", ".", "Context", ")", "error", "{", "db", ":=", "database", ".", "Get", "(", "c", ")", "\n", "rows", ",", "err", ":=", "db", ".", "QueryContext", "(", "c", ",", "`\n\t\tSELECT id,...
// fetch fetches the IP addresses from the database.
[ "fetch", "fetches", "the", "IP", "addresses", "from", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/ips.go#L49-L67
8,786
luci/luci-go
machine-db/appengine/model/ips.go
computeChanges
func (t *IPsTable) computeChanges(c context.Context, vlans []*config.VLAN) error { cfgs := make(map[common.IPv4]*IP, len(vlans)) for _, vlan := range vlans { ipv4, length, err := common.IPv4Range(vlan.CidrBlock) if err != nil { return errors.Annotate(err, "failed to determine start address and range for CIDR block %q", vlan.CidrBlock).Err() } // TODO(smut): Mark the first address as the network address and the last address as the broadcast address. for i := int64(0); i < length; i++ { cfgs[ipv4] = &IP{ IPv4: ipv4, VLANId: vlan.Id, } ipv4 += 1 } } for _, ip := range t.current { if cfg, ok := cfgs[ip.IPv4]; ok { // IP address found in the config. if t.needsUpdate(ip, cfg) { // IP address doesn't match the config. cfg.Id = ip.Id t.updates = append(t.updates, cfg) } // Record that the IP address config has been seen. delete(cfgs, cfg.IPv4) } else { // IP address not found in the config. t.removals = append(t.removals, ip) } } // IP addresses remaining in the map are present in the config but not the database. // Iterate deterministically over the slices to determine which IP addresses need to be added. for _, vlan := range vlans { ipv4, length, err := common.IPv4Range(vlan.CidrBlock) if err != nil { return errors.Annotate(err, "failed to determine start address and range for CIDR block %q", vlan.CidrBlock).Err() } for i := int64(0); i < length; i++ { if ip, ok := cfgs[ipv4]; ok { t.additions = append(t.additions, ip) } ipv4 += 1 } } return nil }
go
func (t *IPsTable) computeChanges(c context.Context, vlans []*config.VLAN) error { cfgs := make(map[common.IPv4]*IP, len(vlans)) for _, vlan := range vlans { ipv4, length, err := common.IPv4Range(vlan.CidrBlock) if err != nil { return errors.Annotate(err, "failed to determine start address and range for CIDR block %q", vlan.CidrBlock).Err() } // TODO(smut): Mark the first address as the network address and the last address as the broadcast address. for i := int64(0); i < length; i++ { cfgs[ipv4] = &IP{ IPv4: ipv4, VLANId: vlan.Id, } ipv4 += 1 } } for _, ip := range t.current { if cfg, ok := cfgs[ip.IPv4]; ok { // IP address found in the config. if t.needsUpdate(ip, cfg) { // IP address doesn't match the config. cfg.Id = ip.Id t.updates = append(t.updates, cfg) } // Record that the IP address config has been seen. delete(cfgs, cfg.IPv4) } else { // IP address not found in the config. t.removals = append(t.removals, ip) } } // IP addresses remaining in the map are present in the config but not the database. // Iterate deterministically over the slices to determine which IP addresses need to be added. for _, vlan := range vlans { ipv4, length, err := common.IPv4Range(vlan.CidrBlock) if err != nil { return errors.Annotate(err, "failed to determine start address and range for CIDR block %q", vlan.CidrBlock).Err() } for i := int64(0); i < length; i++ { if ip, ok := cfgs[ipv4]; ok { t.additions = append(t.additions, ip) } ipv4 += 1 } } return nil }
[ "func", "(", "t", "*", "IPsTable", ")", "computeChanges", "(", "c", "context", ".", "Context", ",", "vlans", "[", "]", "*", "config", ".", "VLAN", ")", "error", "{", "cfgs", ":=", "make", "(", "map", "[", "common", ".", "IPv4", "]", "*", "IP", ",...
// computeChanges computes the changes that need to be made to the IP addresses in the database.
[ "computeChanges", "computes", "the", "changes", "that", "need", "to", "be", "made", "to", "the", "IP", "addresses", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/ips.go#L75-L123
8,787
luci/luci-go
machine-db/appengine/model/ips.go
add
func (t *IPsTable) 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 ips (ipv4, vlan_id) VALUES (?, ?) `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Add each IP address to the database, and update the slice of IP address with each addition. // TODO(smut): Batch SQL operations if it becomes necessary. logging.Infof(c, "Attempting to add %d IP addresses", len(t.additions)) for len(t.additions) > 0 { ip := t.additions[0] result, err := stmt.ExecContext(c, ip.IPv4, ip.VLANId) if err != nil { return errors.Annotate(err, "failed to add IP address %q", ip.IPv4).Err() } t.current = append(t.current, ip) t.additions = t.additions[1:] logging.Infof(c, "Added IP address %q", ip.IPv4) ip.Id, err = result.LastInsertId() if err != nil { return errors.Annotate(err, "failed to get IP address ID %q", ip.IPv4).Err() } } return nil }
go
func (t *IPsTable) 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 ips (ipv4, vlan_id) VALUES (?, ?) `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Add each IP address to the database, and update the slice of IP address with each addition. // TODO(smut): Batch SQL operations if it becomes necessary. logging.Infof(c, "Attempting to add %d IP addresses", len(t.additions)) for len(t.additions) > 0 { ip := t.additions[0] result, err := stmt.ExecContext(c, ip.IPv4, ip.VLANId) if err != nil { return errors.Annotate(err, "failed to add IP address %q", ip.IPv4).Err() } t.current = append(t.current, ip) t.additions = t.additions[1:] logging.Infof(c, "Added IP address %q", ip.IPv4) ip.Id, err = result.LastInsertId() if err != nil { return errors.Annotate(err, "failed to get IP address ID %q", ip.IPv4).Err() } } return nil }
[ "func", "(", "t", "*", "IPsTable", ")", "add", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "additions", ")", "==", "0", "{", "return", "nil", "...
// add adds all IP addresses pending addition to the database, clearing pending additions. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "add", "adds", "all", "IP", "addresses", "pending", "addition", "to", "the", "database", "clearing", "pending", "additions", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called",...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/ips.go#L127-L161
8,788
luci/luci-go
machine-db/appengine/model/ips.go
remove
func (t *IPsTable) 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 ips WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Remove each IP address from the table. It's more efficient to update the slice of // IP addresses once at the end rather than for each removal, so use a defer. removed := make(map[int64]struct{}, len(t.removals)) defer func() { var ips []*IP for _, ip := range t.current { if _, ok := removed[ip.Id]; !ok { ips = append(ips, ip) } } t.current = ips }() for len(t.removals) > 0 { ip := t.removals[0] if _, err := stmt.ExecContext(c, ip.Id); err != nil { // Defer ensures the slice of IP addresses is updated even if we exit early. return errors.Annotate(err, "failed to remove IP address %q", ip.IPv4).Err() } removed[ip.Id] = struct{}{} t.removals = t.removals[1:] logging.Infof(c, "Removed IP address %q", ip.IPv4) } return nil }
go
func (t *IPsTable) 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 ips WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Remove each IP address from the table. It's more efficient to update the slice of // IP addresses once at the end rather than for each removal, so use a defer. removed := make(map[int64]struct{}, len(t.removals)) defer func() { var ips []*IP for _, ip := range t.current { if _, ok := removed[ip.Id]; !ok { ips = append(ips, ip) } } t.current = ips }() for len(t.removals) > 0 { ip := t.removals[0] if _, err := stmt.ExecContext(c, ip.Id); err != nil { // Defer ensures the slice of IP addresses is updated even if we exit early. return errors.Annotate(err, "failed to remove IP address %q", ip.IPv4).Err() } removed[ip.Id] = struct{}{} t.removals = t.removals[1:] logging.Infof(c, "Removed IP address %q", ip.IPv4) } return nil }
[ "func", "(", "t", "*", "IPsTable", ")", "remove", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "removals", ")", "==", "0", "{", "return", "nil", ...
// remove removes all IP addresses pending removal from the database, clearing pending removals. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "remove", "removes", "all", "IP", "addresses", "pending", "removal", "from", "the", "database", "clearing", "pending", "removals", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "ca...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/ips.go#L165-L204
8,789
luci/luci-go
machine-db/appengine/model/ips.go
update
func (t *IPsTable) 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 ips SET vlan_id = ? WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Update each IP address in the table. It's more efficient to update the slice of // IP addresses once at the end rather than for each update, so use a defer. updated := make(map[int64]*IP, len(t.updates)) defer func() { for _, ip := range t.current { if u, ok := updated[ip.Id]; ok { ip.VLANId = u.VLANId } } }() for len(t.updates) > 0 { ip := t.updates[0] if _, err := stmt.ExecContext(c, ip.VLANId, ip.Id); err != nil { return errors.Annotate(err, "failed to update IP address %q", ip.IPv4).Err() } updated[ip.Id] = ip t.updates = t.updates[1:] logging.Infof(c, "Updated IP address %q", ip.IPv4) } return nil }
go
func (t *IPsTable) 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 ips SET vlan_id = ? WHERE id = ? `) if err != nil { return errors.Annotate(err, "failed to prepare statement").Err() } defer stmt.Close() // Update each IP address in the table. It's more efficient to update the slice of // IP addresses once at the end rather than for each update, so use a defer. updated := make(map[int64]*IP, len(t.updates)) defer func() { for _, ip := range t.current { if u, ok := updated[ip.Id]; ok { ip.VLANId = u.VLANId } } }() for len(t.updates) > 0 { ip := t.updates[0] if _, err := stmt.ExecContext(c, ip.VLANId, ip.Id); err != nil { return errors.Annotate(err, "failed to update IP address %q", ip.IPv4).Err() } updated[ip.Id] = ip t.updates = t.updates[1:] logging.Infof(c, "Updated IP address %q", ip.IPv4) } return nil }
[ "func", "(", "t", "*", "IPsTable", ")", "update", "(", "c", "context", ".", "Context", ")", "error", "{", "// Avoid using the database connection to prepare unnecessary statements.", "if", "len", "(", "t", ".", "updates", ")", "==", "0", "{", "return", "nil", ...
// update updates all IP addresses pending update in the database, clearing pending updates. // No-op unless computeChanges was called first. Idempotent until computeChanges is called again.
[ "update", "updates", "all", "IP", "addresses", "pending", "update", "in", "the", "database", "clearing", "pending", "updates", ".", "No", "-", "op", "unless", "computeChanges", "was", "called", "first", ".", "Idempotent", "until", "computeChanges", "is", "called...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/ips.go#L208-L245
8,790
luci/luci-go
machine-db/appengine/model/ips.go
ids
func (t *IPsTable) ids(c context.Context) map[common.IPv4]int64 { ips := make(map[common.IPv4]int64, len(t.current)) for _, ip := range t.current { ips[ip.IPv4] = ip.Id } return ips }
go
func (t *IPsTable) ids(c context.Context) map[common.IPv4]int64 { ips := make(map[common.IPv4]int64, len(t.current)) for _, ip := range t.current { ips[ip.IPv4] = ip.Id } return ips }
[ "func", "(", "t", "*", "IPsTable", ")", "ids", "(", "c", "context", ".", "Context", ")", "map", "[", "common", ".", "IPv4", "]", "int64", "{", "ips", ":=", "make", "(", "map", "[", "common", ".", "IPv4", "]", "int64", ",", "len", "(", "t", ".",...
// ids returns a map of IP addresses to IDs.
[ "ids", "returns", "a", "map", "of", "IP", "addresses", "to", "IDs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/ips.go#L248-L254
8,791
luci/luci-go
starlark/starlarkproto/conversions.go
checkAssignable
func checkAssignable(typ reflect.Type, val starlark.Value) error { _, err := getAssigner(typ, val) return err }
go
func checkAssignable(typ reflect.Type, val starlark.Value) error { _, err := getAssigner(typ, val) return err }
[ "func", "checkAssignable", "(", "typ", "reflect", ".", "Type", ",", "val", "starlark", ".", "Value", ")", "error", "{", "_", ",", "err", ":=", "getAssigner", "(", "typ", ",", "val", ")", "\n", "return", "err", "\n", "}" ]
// checkAssignable returns no errors if the given starlark value can be assigned // to a go value of the given type.
[ "checkAssignable", "returns", "no", "errors", "if", "the", "given", "starlark", "value", "can", "be", "assigned", "to", "a", "go", "value", "of", "the", "given", "type", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/conversions.go#L190-L193
8,792
luci/luci-go
starlark/starlarkproto/conversions.go
assign
func assign(gv reflect.Value, sv starlark.Value) error { assigner, err := getAssigner(gv.Type(), sv) if err != nil { return err } return assigner(gv) }
go
func assign(gv reflect.Value, sv starlark.Value) error { assigner, err := getAssigner(gv.Type(), sv) if err != nil { return err } return assigner(gv) }
[ "func", "assign", "(", "gv", "reflect", ".", "Value", ",", "sv", "starlark", ".", "Value", ")", "error", "{", "assigner", ",", "err", ":=", "getAssigner", "(", "gv", ".", "Type", "(", ")", ",", "sv", ")", "\n", "if", "err", "!=", "nil", "{", "ret...
// assign assigns the given starlark value to the given go value, if types // allow.
[ "assign", "assigns", "the", "given", "starlark", "value", "to", "the", "given", "go", "value", "if", "types", "allow", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/conversions.go#L197-L203
8,793
luci/luci-go
starlark/starlarkproto/conversions.go
refuseProto2
func refuseProto2(typ reflect.Type) error { if typ.Kind() == reflect.Ptr && typ.Elem().Kind() != reflect.Struct { return errNoProto2 } return nil }
go
func refuseProto2(typ reflect.Type) error { if typ.Kind() == reflect.Ptr && typ.Elem().Kind() != reflect.Struct { return errNoProto2 } return nil }
[ "func", "refuseProto2", "(", "typ", "reflect", ".", "Type", ")", "error", "{", "if", "typ", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "&&", "typ", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "retur...
// refuseProto2 returns errNoProto2 if the given typ came from proto2 message. // // Proto3 use pointers only to represent message-valued fields. Proto2 also // uses them to represent scalar-valued fields. We don't support proto2. So // check that if typ is a pointer, it points to a struct.
[ "refuseProto2", "returns", "errNoProto2", "if", "the", "given", "typ", "came", "from", "proto2", "message", ".", "Proto3", "use", "pointers", "only", "to", "represent", "message", "-", "valued", "fields", ".", "Proto2", "also", "uses", "them", "to", "represent...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/conversions.go#L316-L321
8,794
luci/luci-go
starlark/starlarkproto/conversions.go
typDesc
func typDesc(typ reflect.Type) string { if typ.Kind() == reflect.Ptr { if msgT, err := GetMessageType(typ); err == nil { return fmt.Sprintf("a %s message", msgT.Name()) } } return fmt.Sprintf("a value of kind %q", typ.Kind()) }
go
func typDesc(typ reflect.Type) string { if typ.Kind() == reflect.Ptr { if msgT, err := GetMessageType(typ); err == nil { return fmt.Sprintf("a %s message", msgT.Name()) } } return fmt.Sprintf("a value of kind %q", typ.Kind()) }
[ "func", "typDesc", "(", "typ", "reflect", ".", "Type", ")", "string", "{", "if", "typ", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "if", "msgT", ",", "err", ":=", "GetMessageType", "(", "typ", ")", ";", "err", "==", "nil", "{", "ret...
// typDesc returns a human readable description of the type, for error messages. // // Recognize proto types and report their proto names. Otherwise just reports // typ's kind.
[ "typDesc", "returns", "a", "human", "readable", "description", "of", "the", "type", "for", "error", "messages", ".", "Recognize", "proto", "types", "and", "report", "their", "proto", "names", ".", "Otherwise", "just", "reports", "typ", "s", "kind", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/conversions.go#L327-L334
8,795
luci/luci-go
common/clock/external.go
SetFactory
func SetFactory(ctx context.Context, f Factory) context.Context { return context.WithValue(ctx, &clockKey, f) }
go
func SetFactory(ctx context.Context, f Factory) context.Context { return context.WithValue(ctx, &clockKey, f) }
[ "func", "SetFactory", "(", "ctx", "context", ".", "Context", ",", "f", "Factory", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "&", "clockKey", ",", "f", ")", "\n", "}" ]
// SetFactory creates a new Context using the supplied Clock factory.
[ "SetFactory", "creates", "a", "new", "Context", "using", "the", "supplied", "Clock", "factory", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/clock/external.go#L29-L31
8,796
luci/luci-go
common/clock/external.go
Set
func Set(ctx context.Context, c Clock) context.Context { return SetFactory(ctx, func(context.Context) Clock { return c }) }
go
func Set(ctx context.Context, c Clock) context.Context { return SetFactory(ctx, func(context.Context) Clock { return c }) }
[ "func", "Set", "(", "ctx", "context", ".", "Context", ",", "c", "Clock", ")", "context", ".", "Context", "{", "return", "SetFactory", "(", "ctx", ",", "func", "(", "context", ".", "Context", ")", "Clock", "{", "return", "c", "}", ")", "\n", "}" ]
// Set creates a new Context using the supplied Clock.
[ "Set", "creates", "a", "new", "Context", "using", "the", "supplied", "Clock", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/clock/external.go#L34-L36
8,797
luci/luci-go
common/clock/external.go
Sleep
func Sleep(ctx context.Context, d time.Duration) TimerResult { return Get(ctx).Sleep(ctx, d) }
go
func Sleep(ctx context.Context, d time.Duration) TimerResult { return Get(ctx).Sleep(ctx, d) }
[ "func", "Sleep", "(", "ctx", "context", ".", "Context", ",", "d", "time", ".", "Duration", ")", "TimerResult", "{", "return", "Get", "(", "ctx", ")", ".", "Sleep", "(", "ctx", ",", "d", ")", "\n", "}" ]
// Sleep calls Clock.Sleep on the Clock instance stored in the supplied Context.
[ "Sleep", "calls", "Clock", ".", "Sleep", "on", "the", "Clock", "instance", "stored", "in", "the", "supplied", "Context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/clock/external.go#L58-L60
8,798
luci/luci-go
common/clock/external.go
Since
func Since(ctx context.Context, t time.Time) time.Duration { return Now(ctx).Sub(t) }
go
func Since(ctx context.Context, t time.Time) time.Duration { return Now(ctx).Sub(t) }
[ "func", "Since", "(", "ctx", "context", ".", "Context", ",", "t", "time", ".", "Time", ")", "time", ".", "Duration", "{", "return", "Now", "(", "ctx", ")", ".", "Sub", "(", "t", ")", "\n", "}" ]
// Since is an equivalent of time.Since.
[ "Since", "is", "an", "equivalent", "of", "time", ".", "Since", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/clock/external.go#L74-L76
8,799
luci/luci-go
tools/cmd/assets/main.go
run
func run(dir string, extraExts []string) error { exts := defaultExts.Union(stringset.NewFromSlice(extraExts...)).ToSlice() sort.Strings(exts) pkg, err := build.ImportDir(dir, build.ImportComment) if err != nil { return fmt.Errorf("can't import dir %q - %s", dir, err) } assets, err := findAssets(pkg.Dir, exts) if err != nil { return fmt.Errorf("can't find assets in %s - %s", pkg.Dir, err) } err = generate(assetsGenGoTmpl, pkg, assets, exts, filepath.Join(pkg.Dir, "assets.gen.go")) if err != nil { return fmt.Errorf("can't generate assets.gen.go - %s", err) } err = generate(assetsTestTmpl, pkg, assets, exts, filepath.Join(pkg.Dir, "assets_test.go")) if err != nil { return fmt.Errorf("can't generate assets_test.go - %s", err) } return nil }
go
func run(dir string, extraExts []string) error { exts := defaultExts.Union(stringset.NewFromSlice(extraExts...)).ToSlice() sort.Strings(exts) pkg, err := build.ImportDir(dir, build.ImportComment) if err != nil { return fmt.Errorf("can't import dir %q - %s", dir, err) } assets, err := findAssets(pkg.Dir, exts) if err != nil { return fmt.Errorf("can't find assets in %s - %s", pkg.Dir, err) } err = generate(assetsGenGoTmpl, pkg, assets, exts, filepath.Join(pkg.Dir, "assets.gen.go")) if err != nil { return fmt.Errorf("can't generate assets.gen.go - %s", err) } err = generate(assetsTestTmpl, pkg, assets, exts, filepath.Join(pkg.Dir, "assets_test.go")) if err != nil { return fmt.Errorf("can't generate assets_test.go - %s", err) } return nil }
[ "func", "run", "(", "dir", "string", ",", "extraExts", "[", "]", "string", ")", "error", "{", "exts", ":=", "defaultExts", ".", "Union", "(", "stringset", ".", "NewFromSlice", "(", "extraExts", "...", ")", ")", ".", "ToSlice", "(", ")", "\n", "sort", ...
// run generates assets.gen.go file with all assets discovered in the directory.
[ "run", "generates", "assets", ".", "gen", ".", "go", "file", "with", "all", "assets", "discovered", "in", "the", "directory", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/assets/main.go#L228-L253