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,200 | luci/luci-go | scheduler/appengine/engine/engine.go | PullPubSubOnDevServer | func (e *engineImpl) PullPubSubOnDevServer(c context.Context, taskManagerName, publisher string) error {
_, sub := e.genTopicAndSubNames(c, taskManagerName, publisher)
msg, ack, err := pullSubcription(c, sub, "")
if err != nil {
return err
}
if msg == nil {
logging.Infof(c, "No new PubSub messages")
return nil
}
switch err = e.handlePubSubMessage(c, msg); {
case err == nil:
ack() // success
case transient.Tag.In(err) || tq.Retry.In(err):
// don't ack, ask for redelivery
default:
ack() // fatal error
}
return err
} | go | func (e *engineImpl) PullPubSubOnDevServer(c context.Context, taskManagerName, publisher string) error {
_, sub := e.genTopicAndSubNames(c, taskManagerName, publisher)
msg, ack, err := pullSubcription(c, sub, "")
if err != nil {
return err
}
if msg == nil {
logging.Infof(c, "No new PubSub messages")
return nil
}
switch err = e.handlePubSubMessage(c, msg); {
case err == nil:
ack() // success
case transient.Tag.In(err) || tq.Retry.In(err):
// don't ack, ask for redelivery
default:
ack() // fatal error
}
return err
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"PullPubSubOnDevServer",
"(",
"c",
"context",
".",
"Context",
",",
"taskManagerName",
",",
"publisher",
"string",
")",
"error",
"{",
"_",
",",
"sub",
":=",
"e",
".",
"genTopicAndSubNames",
"(",
"c",
",",
"taskManag... | // PullPubSubOnDevServer is called on dev server to pull messages from PubSub
// subscription associated with given publisher.
//
// Part of the internal interface, doesn't check ACLs. | [
"PullPubSubOnDevServer",
"is",
"called",
"on",
"dev",
"server",
"to",
"pull",
"messages",
"from",
"PubSub",
"subscription",
"associated",
"with",
"given",
"publisher",
".",
"Part",
"of",
"the",
"internal",
"interface",
"doesn",
"t",
"check",
"ACLs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L687-L706 |
8,201 | luci/luci-go | scheduler/appengine/engine/engine.go | GetDebugJobState | func (e *engineImpl) GetDebugJobState(c context.Context, jobID string) (*DebugJobState, error) {
job, err := e.getJob(c, jobID)
switch {
case err != nil:
return nil, errors.Annotate(err, "failed to fetch Job entity").Err()
case job == nil:
return nil, ErrNoSuchJob
}
state := &DebugJobState{Job: job}
// Fill in FinishedInvocations.
state.FinishedInvocations, err = unmarshalFinishedInvs(job.FinishedInvocationsRaw)
if err != nil {
return nil, errors.Annotate(err, "failed to unmarshal FinishedInvocationsRaw").Err()
}
// Fill in RecentlyFinishedSet.
finishedSet := recentlyFinishedSet(c, jobID)
listing, err := finishedSet.List(c)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch recentlyFinishedSet").Err()
}
state.RecentlyFinishedSet = make([]int64, len(listing.Items))
for i, itm := range listing.Items {
state.RecentlyFinishedSet[i] = finishedSet.ItemToInvID(&itm)
}
// Fill in PendingTriggersSet.
triggersSet := pendingTriggersSet(c, jobID)
_, state.PendingTriggersSet, err = triggersSet.Triggers(c)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch pendingTriggersSet").Err()
}
// Ask the corresponding task.Manager to fill in DebugManagerState. Pass it
// a phony controller configured just enough to be useful for fetching the
// state, but not anything else.
ctl, err := controllerForInvocation(c, e, &Invocation{
ID: -1,
JobID: jobID,
Task: job.Task,
})
if err == nil {
state.ManagerState, err = ctl.manager.GetDebugState(c, ctl)
}
if state.ManagerState == nil {
state.ManagerState = &internal.DebugManagerState{}
}
if err != nil {
state.ManagerState.Error = err.Error()
}
if ctl != nil {
state.ManagerState.DebugLog = ctl.debugLog
}
return state, nil
} | go | func (e *engineImpl) GetDebugJobState(c context.Context, jobID string) (*DebugJobState, error) {
job, err := e.getJob(c, jobID)
switch {
case err != nil:
return nil, errors.Annotate(err, "failed to fetch Job entity").Err()
case job == nil:
return nil, ErrNoSuchJob
}
state := &DebugJobState{Job: job}
// Fill in FinishedInvocations.
state.FinishedInvocations, err = unmarshalFinishedInvs(job.FinishedInvocationsRaw)
if err != nil {
return nil, errors.Annotate(err, "failed to unmarshal FinishedInvocationsRaw").Err()
}
// Fill in RecentlyFinishedSet.
finishedSet := recentlyFinishedSet(c, jobID)
listing, err := finishedSet.List(c)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch recentlyFinishedSet").Err()
}
state.RecentlyFinishedSet = make([]int64, len(listing.Items))
for i, itm := range listing.Items {
state.RecentlyFinishedSet[i] = finishedSet.ItemToInvID(&itm)
}
// Fill in PendingTriggersSet.
triggersSet := pendingTriggersSet(c, jobID)
_, state.PendingTriggersSet, err = triggersSet.Triggers(c)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch pendingTriggersSet").Err()
}
// Ask the corresponding task.Manager to fill in DebugManagerState. Pass it
// a phony controller configured just enough to be useful for fetching the
// state, but not anything else.
ctl, err := controllerForInvocation(c, e, &Invocation{
ID: -1,
JobID: jobID,
Task: job.Task,
})
if err == nil {
state.ManagerState, err = ctl.manager.GetDebugState(c, ctl)
}
if state.ManagerState == nil {
state.ManagerState = &internal.DebugManagerState{}
}
if err != nil {
state.ManagerState.Error = err.Error()
}
if ctl != nil {
state.ManagerState.DebugLog = ctl.debugLog
}
return state, nil
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"GetDebugJobState",
"(",
"c",
"context",
".",
"Context",
",",
"jobID",
"string",
")",
"(",
"*",
"DebugJobState",
",",
"error",
")",
"{",
"job",
",",
"err",
":=",
"e",
".",
"getJob",
"(",
"c",
",",
"jobID",
... | // GetDebugJobState is used by Admin RPC interface for debugging jobs.
//
// Part of the internal interface, doesn't check ACLs. | [
"GetDebugJobState",
"is",
"used",
"by",
"Admin",
"RPC",
"interface",
"for",
"debugging",
"jobs",
".",
"Part",
"of",
"the",
"internal",
"interface",
"doesn",
"t",
"check",
"ACLs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L711-L768 |
8,202 | luci/luci-go | scheduler/appengine/engine/engine.go | getJob | func (e *engineImpl) getJob(c context.Context, jobID string) (*Job, error) {
job := &Job{JobID: jobID}
switch err := ds.Get(c, job); {
case err == nil:
return job, nil
case err == ds.ErrNoSuchEntity:
return nil, nil
default:
return nil, transient.Tag.Apply(err)
}
} | go | func (e *engineImpl) getJob(c context.Context, jobID string) (*Job, error) {
job := &Job{JobID: jobID}
switch err := ds.Get(c, job); {
case err == nil:
return job, nil
case err == ds.ErrNoSuchEntity:
return nil, nil
default:
return nil, transient.Tag.Apply(err)
}
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"getJob",
"(",
"c",
"context",
".",
"Context",
",",
"jobID",
"string",
")",
"(",
"*",
"Job",
",",
"error",
")",
"{",
"job",
":=",
"&",
"Job",
"{",
"JobID",
":",
"jobID",
"}",
"\n",
"switch",
"err",
":=",
... | // getJob returns a job if it exists or nil if not.
//
// Doesn't check ACLs. | [
"getJob",
"returns",
"a",
"job",
"if",
"it",
"exists",
"or",
"nil",
"if",
"not",
".",
"Doesn",
"t",
"check",
"ACLs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L808-L818 |
8,203 | luci/luci-go | scheduler/appengine/engine/engine.go | getProjectJobs | func (e *engineImpl) getProjectJobs(c context.Context, projectID string) (map[string]*Job, error) {
q := ds.NewQuery("Job").
Eq("Enabled", true).
Eq("ProjectID", projectID)
entities := []*Job{}
if err := ds.GetAll(c, q, &entities); err != nil {
return nil, transient.Tag.Apply(err)
}
out := make(map[string]*Job, len(entities))
for _, job := range entities {
if job.Enabled && job.ProjectID == projectID {
out[job.JobID] = job
}
}
return out, nil
} | go | func (e *engineImpl) getProjectJobs(c context.Context, projectID string) (map[string]*Job, error) {
q := ds.NewQuery("Job").
Eq("Enabled", true).
Eq("ProjectID", projectID)
entities := []*Job{}
if err := ds.GetAll(c, q, &entities); err != nil {
return nil, transient.Tag.Apply(err)
}
out := make(map[string]*Job, len(entities))
for _, job := range entities {
if job.Enabled && job.ProjectID == projectID {
out[job.JobID] = job
}
}
return out, nil
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"getProjectJobs",
"(",
"c",
"context",
".",
"Context",
",",
"projectID",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"*",
"Job",
",",
"error",
")",
"{",
"q",
":=",
"ds",
".",
"NewQuery",
"(",
"\"",
"\"",... | // getProjectJobs fetches from ds all enabled jobs belonging to a given
// project. | [
"getProjectJobs",
"fetches",
"from",
"ds",
"all",
"enabled",
"jobs",
"belonging",
"to",
"a",
"given",
"project",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L822-L837 |
8,204 | luci/luci-go | scheduler/appengine/engine/engine.go | queryEnabledVisibleJobs | func (e *engineImpl) queryEnabledVisibleJobs(c context.Context, q *ds.Query) ([]*Job, error) {
entities := []*Job{}
if err := ds.GetAll(c, q, &entities); err != nil {
return nil, transient.Tag.Apply(err)
}
// Non-ancestor query used, need to recheck filters.
enabled := make([]*Job, 0, len(entities))
for _, job := range entities {
if job.Enabled {
enabled = append(enabled, job)
}
}
// Keep only ones visible to the caller.
return e.filterForRole(c, enabled, acl.Reader)
} | go | func (e *engineImpl) queryEnabledVisibleJobs(c context.Context, q *ds.Query) ([]*Job, error) {
entities := []*Job{}
if err := ds.GetAll(c, q, &entities); err != nil {
return nil, transient.Tag.Apply(err)
}
// Non-ancestor query used, need to recheck filters.
enabled := make([]*Job, 0, len(entities))
for _, job := range entities {
if job.Enabled {
enabled = append(enabled, job)
}
}
// Keep only ones visible to the caller.
return e.filterForRole(c, enabled, acl.Reader)
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"queryEnabledVisibleJobs",
"(",
"c",
"context",
".",
"Context",
",",
"q",
"*",
"ds",
".",
"Query",
")",
"(",
"[",
"]",
"*",
"Job",
",",
"error",
")",
"{",
"entities",
":=",
"[",
"]",
"*",
"Job",
"{",
"}",... | // queryEnabledVisibleJobs fetches all jobs from the query and keeps only ones
// that are enabled and visible by the current caller. | [
"queryEnabledVisibleJobs",
"fetches",
"all",
"jobs",
"from",
"the",
"query",
"and",
"keeps",
"only",
"ones",
"that",
"are",
"enabled",
"and",
"visible",
"by",
"the",
"current",
"caller",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L841-L855 |
8,205 | luci/luci-go | scheduler/appengine/engine/engine.go | filterForRole | func (e *engineImpl) filterForRole(c context.Context, jobs []*Job, role acl.Role) ([]*Job, error) {
// TODO(tandrii): improve batch ACLs check here to take advantage of likely
// shared ACLs between most jobs of the same project.
filtered := make([]*Job, 0, len(jobs))
for _, job := range jobs {
switch err := job.CheckRole(c, role); {
case err == nil:
filtered = append(filtered, job)
case err != ErrNoPermission:
return nil, err // a transient error when checking
}
}
return filtered, nil
} | go | func (e *engineImpl) filterForRole(c context.Context, jobs []*Job, role acl.Role) ([]*Job, error) {
// TODO(tandrii): improve batch ACLs check here to take advantage of likely
// shared ACLs between most jobs of the same project.
filtered := make([]*Job, 0, len(jobs))
for _, job := range jobs {
switch err := job.CheckRole(c, role); {
case err == nil:
filtered = append(filtered, job)
case err != ErrNoPermission:
return nil, err // a transient error when checking
}
}
return filtered, nil
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"filterForRole",
"(",
"c",
"context",
".",
"Context",
",",
"jobs",
"[",
"]",
"*",
"Job",
",",
"role",
"acl",
".",
"Role",
")",
"(",
"[",
"]",
"*",
"Job",
",",
"error",
")",
"{",
"// TODO(tandrii): improve bat... | // filterForRole returns jobs for which caller has the given role.
//
// May return transient errors. | [
"filterForRole",
"returns",
"jobs",
"for",
"which",
"caller",
"has",
"the",
"given",
"role",
".",
"May",
"return",
"transient",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L860-L873 |
8,206 | luci/luci-go | scheduler/appengine/engine/engine.go | updateJob | func (e *engineImpl) updateJob(c context.Context, def catalog.Definition) error {
return e.jobTxn(c, def.JobID, func(c context.Context, job *Job, isNew bool) error {
if !isNew && job.Enabled && job.MatchesDefinition(def) {
return errSkipPut
}
if isNew {
// JobID is <projectID>/<name>, it's ensured by Catalog.
chunks := strings.Split(def.JobID, "/")
if len(chunks) != 2 {
return fmt.Errorf("unexpected jobID format: %s", def.JobID)
}
*job = Job{
JobID: def.JobID,
ProjectID: chunks[0],
Flavor: def.Flavor,
Enabled: false, // to trigger 'if wasDisabled' below
Schedule: def.Schedule,
Task: def.Task,
TriggeringPolicyRaw: def.TriggeringPolicy,
TriggeredJobIDs: def.TriggeredJobIDs,
}
}
wasDisabled := !job.Enabled
oldEffectiveSchedule := job.EffectiveSchedule()
oldTriggeringPolicy := job.TriggeringPolicyRaw
// Update the job in full before running any state changes.
job.Flavor = def.Flavor
job.Revision = def.Revision
job.RevisionURL = def.RevisionURL
job.Acls = def.Acls
job.Enabled = true
job.Schedule = def.Schedule
job.Task = def.Task
job.TriggeringPolicyRaw = def.TriggeringPolicy
job.TriggeredJobIDs = def.TriggeredJobIDs
// If job triggering policy has changed, schedule a triage to potentially
// act based on the new policy.
if !bytes.Equal(oldTriggeringPolicy, job.TriggeringPolicyRaw) {
logging.Infof(c, "Job's triggering policy has changed, scheduling a triage")
if err := e.kickTriageLater(c, job.JobID, 0); err != nil {
return err
}
}
// If the job was just enabled or its schedule changed, poke the cron
// machine to potentially schedule a new tick.
return pokeCron(c, job, e.cfg.Dispatcher, func(m *cron.Machine) error {
if wasDisabled {
m.Enable()
}
if job.EffectiveSchedule() != oldEffectiveSchedule {
logging.Infof(c, "Job's schedule changed: %q -> %q", job.EffectiveSchedule(), oldEffectiveSchedule)
m.OnScheduleChange()
}
return nil
})
})
} | go | func (e *engineImpl) updateJob(c context.Context, def catalog.Definition) error {
return e.jobTxn(c, def.JobID, func(c context.Context, job *Job, isNew bool) error {
if !isNew && job.Enabled && job.MatchesDefinition(def) {
return errSkipPut
}
if isNew {
// JobID is <projectID>/<name>, it's ensured by Catalog.
chunks := strings.Split(def.JobID, "/")
if len(chunks) != 2 {
return fmt.Errorf("unexpected jobID format: %s", def.JobID)
}
*job = Job{
JobID: def.JobID,
ProjectID: chunks[0],
Flavor: def.Flavor,
Enabled: false, // to trigger 'if wasDisabled' below
Schedule: def.Schedule,
Task: def.Task,
TriggeringPolicyRaw: def.TriggeringPolicy,
TriggeredJobIDs: def.TriggeredJobIDs,
}
}
wasDisabled := !job.Enabled
oldEffectiveSchedule := job.EffectiveSchedule()
oldTriggeringPolicy := job.TriggeringPolicyRaw
// Update the job in full before running any state changes.
job.Flavor = def.Flavor
job.Revision = def.Revision
job.RevisionURL = def.RevisionURL
job.Acls = def.Acls
job.Enabled = true
job.Schedule = def.Schedule
job.Task = def.Task
job.TriggeringPolicyRaw = def.TriggeringPolicy
job.TriggeredJobIDs = def.TriggeredJobIDs
// If job triggering policy has changed, schedule a triage to potentially
// act based on the new policy.
if !bytes.Equal(oldTriggeringPolicy, job.TriggeringPolicyRaw) {
logging.Infof(c, "Job's triggering policy has changed, scheduling a triage")
if err := e.kickTriageLater(c, job.JobID, 0); err != nil {
return err
}
}
// If the job was just enabled or its schedule changed, poke the cron
// machine to potentially schedule a new tick.
return pokeCron(c, job, e.cfg.Dispatcher, func(m *cron.Machine) error {
if wasDisabled {
m.Enable()
}
if job.EffectiveSchedule() != oldEffectiveSchedule {
logging.Infof(c, "Job's schedule changed: %q -> %q", job.EffectiveSchedule(), oldEffectiveSchedule)
m.OnScheduleChange()
}
return nil
})
})
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"updateJob",
"(",
"c",
"context",
".",
"Context",
",",
"def",
"catalog",
".",
"Definition",
")",
"error",
"{",
"return",
"e",
".",
"jobTxn",
"(",
"c",
",",
"def",
".",
"JobID",
",",
"func",
"(",
"c",
"conte... | // updateJob updates an existing job if its definition has changed, adds
// a completely new job or enables a previously disabled job. | [
"updateJob",
"updates",
"an",
"existing",
"job",
"if",
"its",
"definition",
"has",
"changed",
"adds",
"a",
"completely",
"new",
"job",
"or",
"enables",
"a",
"previously",
"disabled",
"job",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L914-L974 |
8,207 | luci/luci-go | scheduler/appengine/engine/engine.go | disableJob | func (e *engineImpl) disableJob(c context.Context, jobID string) error {
return e.jobTxn(c, jobID, func(c context.Context, job *Job, isNew bool) error {
if isNew || !job.Enabled {
return errSkipPut
}
job.Enabled = false
// Stop the cron machine ticks.
err := pokeCron(c, job, e.cfg.Dispatcher, func(m *cron.Machine) error {
m.Disable()
return nil
})
if err != nil {
return err
}
// Kick the triage to clear the pending triggers. We can pop them only
// from within the triage procedure.
return e.kickTriageLater(c, job.JobID, 0)
})
} | go | func (e *engineImpl) disableJob(c context.Context, jobID string) error {
return e.jobTxn(c, jobID, func(c context.Context, job *Job, isNew bool) error {
if isNew || !job.Enabled {
return errSkipPut
}
job.Enabled = false
// Stop the cron machine ticks.
err := pokeCron(c, job, e.cfg.Dispatcher, func(m *cron.Machine) error {
m.Disable()
return nil
})
if err != nil {
return err
}
// Kick the triage to clear the pending triggers. We can pop them only
// from within the triage procedure.
return e.kickTriageLater(c, job.JobID, 0)
})
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"disableJob",
"(",
"c",
"context",
".",
"Context",
",",
"jobID",
"string",
")",
"error",
"{",
"return",
"e",
".",
"jobTxn",
"(",
"c",
",",
"jobID",
",",
"func",
"(",
"c",
"context",
".",
"Context",
",",
"jo... | // disableJob moves a job to the disabled state. | [
"disableJob",
"moves",
"a",
"job",
"to",
"the",
"disabled",
"state",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L977-L997 |
8,208 | luci/luci-go | scheduler/appengine/engine/engine.go | allocateInvocation | func (e *engineImpl) allocateInvocation(c context.Context, job *Job, req task.Request) (*Invocation, error) {
var inv *Invocation
err := runIsolatedTxn(c, func(c context.Context) (err error) {
inv, err = e.initInvocation(c, job.JobID, &Invocation{
Started: clock.Now(c).UTC(),
Revision: job.Revision,
RevisionURL: job.RevisionURL,
Task: job.Task,
TriggeredJobIDs: job.TriggeredJobIDs,
Status: task.StatusStarting,
}, &req)
if err != nil {
return
}
inv.debugLog(c, "New invocation is queued and will start shortly")
if req.TriggeredBy != "" {
inv.debugLog(c, "Triggered by %s", req.TriggeredBy)
}
return transient.Tag.Apply(ds.Put(c, inv))
})
if err != nil {
return nil, err
}
return inv, nil
} | go | func (e *engineImpl) allocateInvocation(c context.Context, job *Job, req task.Request) (*Invocation, error) {
var inv *Invocation
err := runIsolatedTxn(c, func(c context.Context) (err error) {
inv, err = e.initInvocation(c, job.JobID, &Invocation{
Started: clock.Now(c).UTC(),
Revision: job.Revision,
RevisionURL: job.RevisionURL,
Task: job.Task,
TriggeredJobIDs: job.TriggeredJobIDs,
Status: task.StatusStarting,
}, &req)
if err != nil {
return
}
inv.debugLog(c, "New invocation is queued and will start shortly")
if req.TriggeredBy != "" {
inv.debugLog(c, "Triggered by %s", req.TriggeredBy)
}
return transient.Tag.Apply(ds.Put(c, inv))
})
if err != nil {
return nil, err
}
return inv, nil
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"allocateInvocation",
"(",
"c",
"context",
".",
"Context",
",",
"job",
"*",
"Job",
",",
"req",
"task",
".",
"Request",
")",
"(",
"*",
"Invocation",
",",
"error",
")",
"{",
"var",
"inv",
"*",
"Invocation",
"\n... | // allocateInvocation creates new Invocation entity in a separate transaction. | [
"allocateInvocation",
"creates",
"new",
"Invocation",
"entity",
"in",
"a",
"separate",
"transaction",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1083-L1107 |
8,209 | luci/luci-go | scheduler/appengine/engine/engine.go | allocateInvocations | func (e *engineImpl) allocateInvocations(c context.Context, job *Job, req []task.Request) ([]*Invocation, error) {
wg := sync.WaitGroup{}
wg.Add(len(req))
invs := make([]*Invocation, len(req))
merr := errors.NewLazyMultiError(len(req))
for i := range req {
go func(i int) {
defer wg.Done()
inv, err := e.allocateInvocation(c, job, req[i])
invs[i] = inv
merr.Assign(i, err)
if err != nil {
logging.WithError(err).Errorf(c, "Failed to create invocation with %d triggers", len(req[i].IncomingTriggers))
}
}(i)
}
wg.Wait()
// Bail if any of them failed. Try best effort cleanup.
if err := merr.Get(); err != nil {
cleanupUnreferencedInvocations(c, invs)
return nil, transient.Tag.Apply(err)
}
return invs, nil
} | go | func (e *engineImpl) allocateInvocations(c context.Context, job *Job, req []task.Request) ([]*Invocation, error) {
wg := sync.WaitGroup{}
wg.Add(len(req))
invs := make([]*Invocation, len(req))
merr := errors.NewLazyMultiError(len(req))
for i := range req {
go func(i int) {
defer wg.Done()
inv, err := e.allocateInvocation(c, job, req[i])
invs[i] = inv
merr.Assign(i, err)
if err != nil {
logging.WithError(err).Errorf(c, "Failed to create invocation with %d triggers", len(req[i].IncomingTriggers))
}
}(i)
}
wg.Wait()
// Bail if any of them failed. Try best effort cleanup.
if err := merr.Get(); err != nil {
cleanupUnreferencedInvocations(c, invs)
return nil, transient.Tag.Apply(err)
}
return invs, nil
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"allocateInvocations",
"(",
"c",
"context",
".",
"Context",
",",
"job",
"*",
"Job",
",",
"req",
"[",
"]",
"task",
".",
"Request",
")",
"(",
"[",
"]",
"*",
"Invocation",
",",
"error",
")",
"{",
"wg",
":=",
... | // allocateInvocations is a batch version of allocateInvocation.
//
// It launches N independent transactions in parallel to create N invocations. | [
"allocateInvocations",
"is",
"a",
"batch",
"version",
"of",
"allocateInvocation",
".",
"It",
"launches",
"N",
"independent",
"transactions",
"in",
"parallel",
"to",
"create",
"N",
"invocations",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1112-L1139 |
8,210 | luci/luci-go | scheduler/appengine/engine/engine.go | abortInvocation | func (e *engineImpl) abortInvocation(c context.Context, jobID string, invID int64) error {
return e.withController(c, jobID, invID, "manual abort", func(c context.Context, ctl *taskController) error {
ctl.DebugLog("Invocation is manually aborted by %s", auth.CurrentIdentity(c))
switch err := ctl.manager.AbortTask(c, ctl); {
case transient.Tag.In(err):
return err // ask for retry on transient errors, don't touch Invocation
case err != nil:
ctl.DebugLog("Fatal error when aborting the invocation - %s", err)
}
// On success or on a fatal error mark the task as aborted (unless the
// manager already switched the state). We can't do anything about the
// failed abort attempt anyway.
if !ctl.State().Status.Final() {
ctl.State().Status = task.StatusAborted
}
return nil
})
} | go | func (e *engineImpl) abortInvocation(c context.Context, jobID string, invID int64) error {
return e.withController(c, jobID, invID, "manual abort", func(c context.Context, ctl *taskController) error {
ctl.DebugLog("Invocation is manually aborted by %s", auth.CurrentIdentity(c))
switch err := ctl.manager.AbortTask(c, ctl); {
case transient.Tag.In(err):
return err // ask for retry on transient errors, don't touch Invocation
case err != nil:
ctl.DebugLog("Fatal error when aborting the invocation - %s", err)
}
// On success or on a fatal error mark the task as aborted (unless the
// manager already switched the state). We can't do anything about the
// failed abort attempt anyway.
if !ctl.State().Status.Final() {
ctl.State().Status = task.StatusAborted
}
return nil
})
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"abortInvocation",
"(",
"c",
"context",
".",
"Context",
",",
"jobID",
"string",
",",
"invID",
"int64",
")",
"error",
"{",
"return",
"e",
".",
"withController",
"(",
"c",
",",
"jobID",
",",
"invID",
",",
"\"",
... | // abortInvocation marks some invocation as aborted. | [
"abortInvocation",
"marks",
"some",
"invocation",
"as",
"aborted",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1179-L1198 |
8,211 | luci/luci-go | scheduler/appengine/engine/engine.go | withController | func (e *engineImpl) withController(c context.Context, jobID string, invID int64, action string, cb func(context.Context, *taskController) error) error {
c = logging.SetField(c, "JobID", jobID)
c = logging.SetField(c, "InvID", invID)
logging.Infof(c, "Handling %s", action)
inv, err := e.getInvocation(c, jobID, invID)
switch {
case err != nil:
logging.WithError(err).Errorf(c, "Failed to fetch the invocation")
return err
case inv.Status.Final():
logging.Infof(c, "Skipping %s, the invocation is in final state %q", action, inv.Status)
return nil
}
ctl, err := controllerForInvocation(c, e, inv)
if err != nil {
logging.WithError(err).Errorf(c, "Cannot get the controller")
return err
}
if err := cb(c, ctl); err != nil {
logging.WithError(err).Errorf(c, "Failed to perform %s, skipping saving the invocation", action)
return err
}
if err := ctl.Save(c); err != nil {
logging.WithError(err).Errorf(c, "Error when saving the invocation")
return err
}
return nil
} | go | func (e *engineImpl) withController(c context.Context, jobID string, invID int64, action string, cb func(context.Context, *taskController) error) error {
c = logging.SetField(c, "JobID", jobID)
c = logging.SetField(c, "InvID", invID)
logging.Infof(c, "Handling %s", action)
inv, err := e.getInvocation(c, jobID, invID)
switch {
case err != nil:
logging.WithError(err).Errorf(c, "Failed to fetch the invocation")
return err
case inv.Status.Final():
logging.Infof(c, "Skipping %s, the invocation is in final state %q", action, inv.Status)
return nil
}
ctl, err := controllerForInvocation(c, e, inv)
if err != nil {
logging.WithError(err).Errorf(c, "Cannot get the controller")
return err
}
if err := cb(c, ctl); err != nil {
logging.WithError(err).Errorf(c, "Failed to perform %s, skipping saving the invocation", action)
return err
}
if err := ctl.Save(c); err != nil {
logging.WithError(err).Errorf(c, "Error when saving the invocation")
return err
}
return nil
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"withController",
"(",
"c",
"context",
".",
"Context",
",",
"jobID",
"string",
",",
"invID",
"int64",
",",
"action",
"string",
",",
"cb",
"func",
"(",
"context",
".",
"Context",
",",
"*",
"taskController",
")",
... | // withController fetches the invocation, instantiates the task controller,
// calls the callback, and saves back the modified invocation state, initiating
// all necessary engine transitions along the way.
//
// Does nothing and returns nil if the invocation is already in a final state.
// The callback is not called in this case at all.
//
// Skips saving the invocation if the callback returns non-nil.
//
// 'action' is used exclusively for logging. It's a human readable cause of why
// the controller is instantiated. | [
"withController",
"fetches",
"the",
"invocation",
"instantiates",
"the",
"task",
"controller",
"calls",
"the",
"callback",
"and",
"saves",
"back",
"the",
"modified",
"invocation",
"state",
"initiating",
"all",
"necessary",
"engine",
"transitions",
"along",
"the",
"w... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1226-L1259 |
8,212 | luci/luci-go | scheduler/appengine/engine/engine.go | launchTask | func (e *engineImpl) launchTask(c context.Context, inv *Invocation) error {
assertNotInTransaction(c)
// Grab the corresponding TaskManager to launch the task through it.
ctl, err := controllerForInvocation(c, e, inv)
if err != nil {
// Note: controllerForInvocation returns both ctl and err on errors, with
// ctl not fully initialized (but good enough for what's done below).
ctl.DebugLog("Failed to initialize task controller - %s", err)
ctl.State().Status = task.StatusFailed
return ctl.Save(c)
}
// Ask the manager to start the task. If it returns no errors, it should also
// move the invocation out of an initial state (a failure to do so is a fatal
// error). If it returns an error, the invocation is forcefully moved to
// StatusRetrying or StatusFailed state (depending on whether the error is
// transient or not and how many retries are left). In either case, invocation
// never ends up in StatusStarting state.
err = ctl.manager.LaunchTask(c, ctl)
if err != nil {
logging.WithError(err).Errorf(c, "Failed to LaunchTask")
}
if status := ctl.State().Status; status.Initial() && err == nil {
err = fmt.Errorf("LaunchTask didn't move invocation out of initial %s state", status)
}
if transient.Tag.In(err) && inv.RetryCount+1 >= invocationRetryLimit {
err = fmt.Errorf("Too many retries, giving up (original error - %s)", err)
}
// The task must always end up in a non-initial state. Do it on behalf of the
// controller if necessary.
if ctl.State().Status.Initial() {
if transient.Tag.In(err) {
// This invocation object will be reused for a retry later.
ctl.State().Status = task.StatusRetrying
} else {
// The invocation has crashed with the fatal error.
ctl.State().Status = task.StatusFailed
}
}
// Add a notice into the invocation log that we'll attempt to retry.
isRetrying := ctl.State().Status == task.StatusRetrying
if isRetrying {
ctl.DebugLog("The invocation will be retried")
}
// We MUST commit the state of the invocation. A failure to save the state
// may cause the job state machine to get stuck. If we can't save it, we need
// to retry the whole launch attempt from scratch (redoing all the work,
// a properly implemented LaunchTask should be idempotent).
if err := ctl.Save(c); err != nil {
logging.WithError(err).Errorf(c, "Failed to save invocation state")
return err
}
// Task retries happen via the task queue, need to explicitly trigger a retry
// by returning a transient error.
if isRetrying {
return errRetryingLaunch
}
return nil
} | go | func (e *engineImpl) launchTask(c context.Context, inv *Invocation) error {
assertNotInTransaction(c)
// Grab the corresponding TaskManager to launch the task through it.
ctl, err := controllerForInvocation(c, e, inv)
if err != nil {
// Note: controllerForInvocation returns both ctl and err on errors, with
// ctl not fully initialized (but good enough for what's done below).
ctl.DebugLog("Failed to initialize task controller - %s", err)
ctl.State().Status = task.StatusFailed
return ctl.Save(c)
}
// Ask the manager to start the task. If it returns no errors, it should also
// move the invocation out of an initial state (a failure to do so is a fatal
// error). If it returns an error, the invocation is forcefully moved to
// StatusRetrying or StatusFailed state (depending on whether the error is
// transient or not and how many retries are left). In either case, invocation
// never ends up in StatusStarting state.
err = ctl.manager.LaunchTask(c, ctl)
if err != nil {
logging.WithError(err).Errorf(c, "Failed to LaunchTask")
}
if status := ctl.State().Status; status.Initial() && err == nil {
err = fmt.Errorf("LaunchTask didn't move invocation out of initial %s state", status)
}
if transient.Tag.In(err) && inv.RetryCount+1 >= invocationRetryLimit {
err = fmt.Errorf("Too many retries, giving up (original error - %s)", err)
}
// The task must always end up in a non-initial state. Do it on behalf of the
// controller if necessary.
if ctl.State().Status.Initial() {
if transient.Tag.In(err) {
// This invocation object will be reused for a retry later.
ctl.State().Status = task.StatusRetrying
} else {
// The invocation has crashed with the fatal error.
ctl.State().Status = task.StatusFailed
}
}
// Add a notice into the invocation log that we'll attempt to retry.
isRetrying := ctl.State().Status == task.StatusRetrying
if isRetrying {
ctl.DebugLog("The invocation will be retried")
}
// We MUST commit the state of the invocation. A failure to save the state
// may cause the job state machine to get stuck. If we can't save it, we need
// to retry the whole launch attempt from scratch (redoing all the work,
// a properly implemented LaunchTask should be idempotent).
if err := ctl.Save(c); err != nil {
logging.WithError(err).Errorf(c, "Failed to save invocation state")
return err
}
// Task retries happen via the task queue, need to explicitly trigger a retry
// by returning a transient error.
if isRetrying {
return errRetryingLaunch
}
return nil
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"launchTask",
"(",
"c",
"context",
".",
"Context",
",",
"inv",
"*",
"Invocation",
")",
"error",
"{",
"assertNotInTransaction",
"(",
"c",
")",
"\n\n",
"// Grab the corresponding TaskManager to launch the task through it.",
"c... | // launchTask instantiates an invocation controller and calls its LaunchTask
// method, saving the invocation state when its done.
//
// It returns a transient error if the launch attempt should be retried. | [
"launchTask",
"instantiates",
"an",
"invocation",
"controller",
"and",
"calls",
"its",
"LaunchTask",
"method",
"saving",
"the",
"invocation",
"state",
"when",
"its",
"done",
".",
"It",
"returns",
"a",
"transient",
"error",
"if",
"the",
"launch",
"attempt",
"shou... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1265-L1329 |
8,213 | luci/luci-go | scheduler/appengine/engine/engine.go | execLaunchInvocationTask | func (e *engineImpl) execLaunchInvocationTask(c context.Context, tqTask proto.Message) error {
msg := tqTask.(*internal.LaunchInvocationTask)
c = logging.SetField(c, "JobID", msg.JobId)
c = logging.SetField(c, "InvID", msg.InvId)
hdrs, err := tq.RequestHeaders(c)
if err != nil {
return err
}
retryCount := hdrs.TaskExecutionCount // 0 for the first attempt
if retryCount != 0 {
logging.Warningf(c, "This is a retry (attempt %d)!", retryCount+1)
}
// Fetch up-to-date state of the invocation, verify we still need to start it.
// Log that we are about to do it. We MUST write something to the datastore
// before attempting the launch to make sure that if the datastore is in read
// only mode (that happens), we don't spam LaunchTask retries when failing to
// Save() the state in the end (better to fail now, before LaunchTask call).
var skipLaunch bool
var lastInvState Invocation
logging.Infof(c, "Opening the invocation transaction")
err = runTxn(c, func(c context.Context) error {
skipLaunch = false // reset in case the transaction is retried
// Grab up-to-date invocation state.
inv := Invocation{ID: msg.InvId}
switch err := ds.Get(c, &inv); {
case err == ds.ErrNoSuchEntity:
// This generally should not happen.
logging.Warningf(c, "The invocation is unexpectedly gone")
skipLaunch = true
return nil
case err != nil:
return transient.Tag.Apply(err)
case !inv.Status.Initial():
logging.Warningf(c, "The invocation is already running or finished: %s", inv.Status)
skipLaunch = true
return nil
}
// The invocation is still starting or being retried now. Update its state
// to indicate we are about to work with it. 'lastInvState' is later passed
// to the task controller.
lastInvState = inv
lastInvState.RetryCount = retryCount
lastInvState.MutationsCount++
if retryCount >= invocationRetryLimit {
logging.Errorf(c, "Too many attempts, giving up")
lastInvState.debugLog(c, "Too many attempts, giving up")
lastInvState.Status = task.StatusFailed
lastInvState.Finished = clock.Now(c).UTC()
skipLaunch = true
} else {
lastInvState.debugLog(c, "Starting the invocation (attempt %d)", retryCount+1)
}
// Make sure to trigger all necessary side effects, particularly important
// if the invocation was moved to Failed state above.
if err := e.invChanging(c, &inv, &lastInvState, nil, nil); err != nil {
return err
}
// Store the updated invocation.
lastInvState.trimDebugLog()
return transient.Tag.Apply(ds.Put(c, &lastInvState))
})
switch {
case err != nil:
logging.WithError(err).Errorf(c, "Failed to update the invocation")
return err
case skipLaunch:
logging.Warningf(c, "No need to start the invocation anymore")
return nil
}
logging.Infof(c, "Actually launching the task")
return e.launchTask(c, &lastInvState)
} | go | func (e *engineImpl) execLaunchInvocationTask(c context.Context, tqTask proto.Message) error {
msg := tqTask.(*internal.LaunchInvocationTask)
c = logging.SetField(c, "JobID", msg.JobId)
c = logging.SetField(c, "InvID", msg.InvId)
hdrs, err := tq.RequestHeaders(c)
if err != nil {
return err
}
retryCount := hdrs.TaskExecutionCount // 0 for the first attempt
if retryCount != 0 {
logging.Warningf(c, "This is a retry (attempt %d)!", retryCount+1)
}
// Fetch up-to-date state of the invocation, verify we still need to start it.
// Log that we are about to do it. We MUST write something to the datastore
// before attempting the launch to make sure that if the datastore is in read
// only mode (that happens), we don't spam LaunchTask retries when failing to
// Save() the state in the end (better to fail now, before LaunchTask call).
var skipLaunch bool
var lastInvState Invocation
logging.Infof(c, "Opening the invocation transaction")
err = runTxn(c, func(c context.Context) error {
skipLaunch = false // reset in case the transaction is retried
// Grab up-to-date invocation state.
inv := Invocation{ID: msg.InvId}
switch err := ds.Get(c, &inv); {
case err == ds.ErrNoSuchEntity:
// This generally should not happen.
logging.Warningf(c, "The invocation is unexpectedly gone")
skipLaunch = true
return nil
case err != nil:
return transient.Tag.Apply(err)
case !inv.Status.Initial():
logging.Warningf(c, "The invocation is already running or finished: %s", inv.Status)
skipLaunch = true
return nil
}
// The invocation is still starting or being retried now. Update its state
// to indicate we are about to work with it. 'lastInvState' is later passed
// to the task controller.
lastInvState = inv
lastInvState.RetryCount = retryCount
lastInvState.MutationsCount++
if retryCount >= invocationRetryLimit {
logging.Errorf(c, "Too many attempts, giving up")
lastInvState.debugLog(c, "Too many attempts, giving up")
lastInvState.Status = task.StatusFailed
lastInvState.Finished = clock.Now(c).UTC()
skipLaunch = true
} else {
lastInvState.debugLog(c, "Starting the invocation (attempt %d)", retryCount+1)
}
// Make sure to trigger all necessary side effects, particularly important
// if the invocation was moved to Failed state above.
if err := e.invChanging(c, &inv, &lastInvState, nil, nil); err != nil {
return err
}
// Store the updated invocation.
lastInvState.trimDebugLog()
return transient.Tag.Apply(ds.Put(c, &lastInvState))
})
switch {
case err != nil:
logging.WithError(err).Errorf(c, "Failed to update the invocation")
return err
case skipLaunch:
logging.Warningf(c, "No need to start the invocation anymore")
return nil
}
logging.Infof(c, "Actually launching the task")
return e.launchTask(c, &lastInvState)
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"execLaunchInvocationTask",
"(",
"c",
"context",
".",
"Context",
",",
"tqTask",
"proto",
".",
"Message",
")",
"error",
"{",
"msg",
":=",
"tqTask",
".",
"(",
"*",
"internal",
".",
"LaunchInvocationTask",
")",
"\n\n"... | // execLaunchInvocationTask handles LaunchInvocationTask.
//
// It can be redelivered a bunch of times in case the invocation fails to start. | [
"execLaunchInvocationTask",
"handles",
"LaunchInvocationTask",
".",
"It",
"can",
"be",
"redelivered",
"a",
"bunch",
"of",
"times",
"in",
"case",
"the",
"invocation",
"fails",
"to",
"start",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1472-L1552 |
8,214 | luci/luci-go | scheduler/appengine/engine/engine.go | execTimerTask | func (e *engineImpl) execTimerTask(c context.Context, tqTask proto.Message) error {
msg := tqTask.(*internal.TimerTask)
timer := msg.Timer
action := fmt.Sprintf("timer %q (%s)", timer.Title, timer.Id)
return e.withController(c, msg.JobId, msg.InvId, action, func(c context.Context, ctl *taskController) error {
// Pop the timer from the pending set, if it is still there. Return a fatal
// error if it isn't to stop this task from being redelivered.
switch consumed, err := ctl.consumeTimer(timer.Id); {
case err != nil:
return err
case !consumed:
return fmt.Errorf("no such timer: %s", timer.Id)
}
// Let the task manager handle the timer. It may add new timers.
ctl.DebugLog("Handling timer %q (%s)", timer.Title, timer.Id)
err := ctl.manager.HandleTimer(c, ctl, timer.Title, timer.Payload)
switch {
case err == nil:
return nil // success! save the invocation
case transient.Tag.In(err):
return err // ask for redelivery on transient errors, don't touch the invocation
}
// On fatal errors, move the invocation to failed state (if not already).
if ctl.State().Status != task.StatusFailed {
ctl.DebugLog("Fatal error when handling timer, aborting invocation - %s", err)
ctl.State().Status = task.StatusFailed
}
// Need to save the invocation, even on fatal errors (to indicate that the
// timer has been consumed). So return nil.
return nil
})
} | go | func (e *engineImpl) execTimerTask(c context.Context, tqTask proto.Message) error {
msg := tqTask.(*internal.TimerTask)
timer := msg.Timer
action := fmt.Sprintf("timer %q (%s)", timer.Title, timer.Id)
return e.withController(c, msg.JobId, msg.InvId, action, func(c context.Context, ctl *taskController) error {
// Pop the timer from the pending set, if it is still there. Return a fatal
// error if it isn't to stop this task from being redelivered.
switch consumed, err := ctl.consumeTimer(timer.Id); {
case err != nil:
return err
case !consumed:
return fmt.Errorf("no such timer: %s", timer.Id)
}
// Let the task manager handle the timer. It may add new timers.
ctl.DebugLog("Handling timer %q (%s)", timer.Title, timer.Id)
err := ctl.manager.HandleTimer(c, ctl, timer.Title, timer.Payload)
switch {
case err == nil:
return nil // success! save the invocation
case transient.Tag.In(err):
return err // ask for redelivery on transient errors, don't touch the invocation
}
// On fatal errors, move the invocation to failed state (if not already).
if ctl.State().Status != task.StatusFailed {
ctl.DebugLog("Fatal error when handling timer, aborting invocation - %s", err)
ctl.State().Status = task.StatusFailed
}
// Need to save the invocation, even on fatal errors (to indicate that the
// timer has been consumed). So return nil.
return nil
})
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"execTimerTask",
"(",
"c",
"context",
".",
"Context",
",",
"tqTask",
"proto",
".",
"Message",
")",
"error",
"{",
"msg",
":=",
"tqTask",
".",
"(",
"*",
"internal",
".",
"TimerTask",
")",
"\n",
"timer",
":=",
"... | // execTimerTask corresponds to a tick of a timer added via AddTimer. | [
"execTimerTask",
"corresponds",
"to",
"a",
"tick",
"of",
"a",
"timer",
"added",
"via",
"AddTimer",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1704-L1739 |
8,215 | luci/luci-go | scheduler/appengine/engine/engine.go | kickTriageLater | func (e *engineImpl) kickTriageLater(c context.Context, jobID string, delay time.Duration) error {
c = logging.SetField(c, "JobID", jobID)
return e.cfg.Dispatcher.AddTask(c, &tq.Task{
Payload: &internal.KickTriageTask{JobId: jobID},
Delay: delay,
})
} | go | func (e *engineImpl) kickTriageLater(c context.Context, jobID string, delay time.Duration) error {
c = logging.SetField(c, "JobID", jobID)
return e.cfg.Dispatcher.AddTask(c, &tq.Task{
Payload: &internal.KickTriageTask{JobId: jobID},
Delay: delay,
})
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"kickTriageLater",
"(",
"c",
"context",
".",
"Context",
",",
"jobID",
"string",
",",
"delay",
"time",
".",
"Duration",
")",
"error",
"{",
"c",
"=",
"logging",
".",
"SetField",
"(",
"c",
",",
"\"",
"\"",
",",
... | // kickTriageLater schedules a triage to be kicked later.
//
// Unlike kickTriageNow, this just posts a single TQ task, and thus can be
// used inside transactions. | [
"kickTriageLater",
"schedules",
"a",
"triage",
"to",
"be",
"kicked",
"later",
".",
"Unlike",
"kickTriageNow",
"this",
"just",
"posts",
"a",
"single",
"TQ",
"task",
"and",
"thus",
"can",
"be",
"used",
"inside",
"transactions",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1815-L1821 |
8,216 | luci/luci-go | scheduler/appengine/engine/engine.go | execKickTriageTask | func (e *engineImpl) execKickTriageTask(c context.Context, tqTask proto.Message) error {
return e.kickTriageNow(c, tqTask.(*internal.KickTriageTask).JobId)
} | go | func (e *engineImpl) execKickTriageTask(c context.Context, tqTask proto.Message) error {
return e.kickTriageNow(c, tqTask.(*internal.KickTriageTask).JobId)
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"execKickTriageTask",
"(",
"c",
"context",
".",
"Context",
",",
"tqTask",
"proto",
".",
"Message",
")",
"error",
"{",
"return",
"e",
".",
"kickTriageNow",
"(",
"c",
",",
"tqTask",
".",
"(",
"*",
"internal",
"."... | // execKickTriageTask handles delayed KickTriageTask by scheduling a triage. | [
"execKickTriageTask",
"handles",
"delayed",
"KickTriageTask",
"by",
"scheduling",
"a",
"triage",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1824-L1826 |
8,217 | luci/luci-go | scheduler/appengine/engine/engine.go | handlePubSubMessage | func (e *engineImpl) handlePubSubMessage(c context.Context, msg *pubsub.PubsubMessage) error {
logging.Infof(c, "Received PubSub message %q", msg.MessageId)
// Extract Job and Invocation ID from validated auth_token.
var jobID string
var invID int64
data, err := pubsubAuthToken.Validate(c, msg.Attributes["auth_token"], nil)
if err != nil {
logging.WithError(err).Errorf(c, "Bad auth_token attribute")
return err
}
jobID = data["job"]
if invID, err = strconv.ParseInt(data["inv"], 10, 64); err != nil {
logging.WithError(err).Errorf(c, "Could not parse 'inv' %q", data["inv"])
return err
}
// Hand the message to the controller.
action := fmt.Sprintf("pubsub message %q", msg.MessageId)
return e.withController(c, jobID, invID, action, func(c context.Context, ctl *taskController) error {
err := ctl.manager.HandleNotification(c, ctl, msg)
switch {
case err == nil:
return nil // success! save the invocation
case transient.Tag.In(err) || tq.Retry.In(err):
return err // ask for redelivery on transient errors, don't touch the invocation
}
// On fatal errors, move the invocation to failed state (if not already).
if ctl.State().Status != task.StatusFailed {
ctl.DebugLog("Fatal error when handling PubSub notification, aborting invocation - %s", err)
ctl.State().Status = task.StatusFailed
}
return nil // need to save the invocation, even on fatal errors
})
} | go | func (e *engineImpl) handlePubSubMessage(c context.Context, msg *pubsub.PubsubMessage) error {
logging.Infof(c, "Received PubSub message %q", msg.MessageId)
// Extract Job and Invocation ID from validated auth_token.
var jobID string
var invID int64
data, err := pubsubAuthToken.Validate(c, msg.Attributes["auth_token"], nil)
if err != nil {
logging.WithError(err).Errorf(c, "Bad auth_token attribute")
return err
}
jobID = data["job"]
if invID, err = strconv.ParseInt(data["inv"], 10, 64); err != nil {
logging.WithError(err).Errorf(c, "Could not parse 'inv' %q", data["inv"])
return err
}
// Hand the message to the controller.
action := fmt.Sprintf("pubsub message %q", msg.MessageId)
return e.withController(c, jobID, invID, action, func(c context.Context, ctl *taskController) error {
err := ctl.manager.HandleNotification(c, ctl, msg)
switch {
case err == nil:
return nil // success! save the invocation
case transient.Tag.In(err) || tq.Retry.In(err):
return err // ask for redelivery on transient errors, don't touch the invocation
}
// On fatal errors, move the invocation to failed state (if not already).
if ctl.State().Status != task.StatusFailed {
ctl.DebugLog("Fatal error when handling PubSub notification, aborting invocation - %s", err)
ctl.State().Status = task.StatusFailed
}
return nil // need to save the invocation, even on fatal errors
})
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"handlePubSubMessage",
"(",
"c",
"context",
".",
"Context",
",",
"msg",
"*",
"pubsub",
".",
"PubsubMessage",
")",
"error",
"{",
"logging",
".",
"Infof",
"(",
"c",
",",
"\"",
"\"",
",",
"msg",
".",
"MessageId",
... | // handlePubSubMessage routes the pubsub message to the invocation. | [
"handlePubSubMessage",
"routes",
"the",
"pubsub",
"message",
"to",
"the",
"invocation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1893-L1927 |
8,218 | luci/luci-go | scheduler/appengine/engine/engine.go | genTopicAndSubNames | func (e *engineImpl) genTopicAndSubNames(c context.Context, manager, publisher string) (topic string, sub string) {
// Avoid accidental override of the topic when running on dev server.
prefix := "scheduler"
if info.IsDevAppServer(c) {
prefix = "dev-scheduler"
}
// Each publisher gets its own topic (and subscription), so it's clearer from
// logs and PubSub console who's calling what. PubSub topics can't have "@" in
// them, so replace "@" with "~". URL encoding could have been used too, but
// Cloud Console confuses %40 with its own URL encoding and doesn't display
// all pages correctly.
id := fmt.Sprintf("%s.%s.%s",
prefix,
manager,
strings.Replace(publisher, "@", "~", -1))
appID := info.AppID(c)
topic = fmt.Sprintf("projects/%s/topics/%s", appID, id)
sub = fmt.Sprintf("projects/%s/subscriptions/%s", appID, id)
return
} | go | func (e *engineImpl) genTopicAndSubNames(c context.Context, manager, publisher string) (topic string, sub string) {
// Avoid accidental override of the topic when running on dev server.
prefix := "scheduler"
if info.IsDevAppServer(c) {
prefix = "dev-scheduler"
}
// Each publisher gets its own topic (and subscription), so it's clearer from
// logs and PubSub console who's calling what. PubSub topics can't have "@" in
// them, so replace "@" with "~". URL encoding could have been used too, but
// Cloud Console confuses %40 with its own URL encoding and doesn't display
// all pages correctly.
id := fmt.Sprintf("%s.%s.%s",
prefix,
manager,
strings.Replace(publisher, "@", "~", -1))
appID := info.AppID(c)
topic = fmt.Sprintf("projects/%s/topics/%s", appID, id)
sub = fmt.Sprintf("projects/%s/subscriptions/%s", appID, id)
return
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"genTopicAndSubNames",
"(",
"c",
"context",
".",
"Context",
",",
"manager",
",",
"publisher",
"string",
")",
"(",
"topic",
"string",
",",
"sub",
"string",
")",
"{",
"// Avoid accidental override of the topic when running o... | // genTopicAndSubNames derives PubSub topic and subscription names to use for
// notifications from given publisher. | [
"genTopicAndSubNames",
"derives",
"PubSub",
"topic",
"and",
"subscription",
"names",
"to",
"use",
"for",
"notifications",
"from",
"given",
"publisher",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1931-L1952 |
8,219 | luci/luci-go | scheduler/appengine/engine/engine.go | prepareTopic | func (e *engineImpl) prepareTopic(c context.Context, params *topicParams) (topic string, tok string, err error) {
// If given URL, ask the service for name of its default service account.
// FetchServiceInfo implements efficient cache internally, so it's fine to
// call it often.
if strings.HasPrefix(params.publisher, "https://") {
logging.Infof(c, "Fetching info about %q", params.publisher)
serviceInfo, err := signing.FetchServiceInfoFromLUCIService(c, params.publisher)
if err != nil {
logging.Errorf(c, "Failed to fetch info about %q - %s", params.publisher, err)
return "", "", err
}
logging.Infof(c, "%q is using %q", params.publisher, serviceInfo.ServiceAccountName)
params.publisher = serviceInfo.ServiceAccountName
}
topic, sub := e.genTopicAndSubNames(c, params.manager.Name(), params.publisher)
// Put same parameters in push URL to make them visible in logs. On dev server
// use pull based subscription, since localhost push URL is not valid.
pushURL := ""
if !info.IsDevAppServer(c) {
urlParams := url.Values{}
urlParams.Add("kind", params.manager.Name())
urlParams.Add("publisher", params.publisher)
pushURL = fmt.Sprintf(
"https://%s%s?%s", info.DefaultVersionHostname(c), e.cfg.PubSubPushPath, urlParams.Encode())
}
// Create and configure the topic. Do it only once.
err = e.opsCache.Do(c, fmt.Sprintf("prepareTopic:v1:%s", topic), func() error {
if e.configureTopic != nil {
return e.configureTopic(c, topic, sub, pushURL, params.publisher)
}
return configureTopic(c, topic, sub, pushURL, params.publisher, "")
})
if err != nil {
return "", "", err
}
// Encode full invocation identifier (job key + invocation ID) into HMAC
// protected token.
tok, err = pubsubAuthToken.Generate(c, nil, map[string]string{
"job": params.jobID,
"inv": fmt.Sprintf("%d", params.invID),
}, 0)
if err != nil {
return "", "", err
}
return topic, tok, nil
} | go | func (e *engineImpl) prepareTopic(c context.Context, params *topicParams) (topic string, tok string, err error) {
// If given URL, ask the service for name of its default service account.
// FetchServiceInfo implements efficient cache internally, so it's fine to
// call it often.
if strings.HasPrefix(params.publisher, "https://") {
logging.Infof(c, "Fetching info about %q", params.publisher)
serviceInfo, err := signing.FetchServiceInfoFromLUCIService(c, params.publisher)
if err != nil {
logging.Errorf(c, "Failed to fetch info about %q - %s", params.publisher, err)
return "", "", err
}
logging.Infof(c, "%q is using %q", params.publisher, serviceInfo.ServiceAccountName)
params.publisher = serviceInfo.ServiceAccountName
}
topic, sub := e.genTopicAndSubNames(c, params.manager.Name(), params.publisher)
// Put same parameters in push URL to make them visible in logs. On dev server
// use pull based subscription, since localhost push URL is not valid.
pushURL := ""
if !info.IsDevAppServer(c) {
urlParams := url.Values{}
urlParams.Add("kind", params.manager.Name())
urlParams.Add("publisher", params.publisher)
pushURL = fmt.Sprintf(
"https://%s%s?%s", info.DefaultVersionHostname(c), e.cfg.PubSubPushPath, urlParams.Encode())
}
// Create and configure the topic. Do it only once.
err = e.opsCache.Do(c, fmt.Sprintf("prepareTopic:v1:%s", topic), func() error {
if e.configureTopic != nil {
return e.configureTopic(c, topic, sub, pushURL, params.publisher)
}
return configureTopic(c, topic, sub, pushURL, params.publisher, "")
})
if err != nil {
return "", "", err
}
// Encode full invocation identifier (job key + invocation ID) into HMAC
// protected token.
tok, err = pubsubAuthToken.Generate(c, nil, map[string]string{
"job": params.jobID,
"inv": fmt.Sprintf("%d", params.invID),
}, 0)
if err != nil {
return "", "", err
}
return topic, tok, nil
} | [
"func",
"(",
"e",
"*",
"engineImpl",
")",
"prepareTopic",
"(",
"c",
"context",
".",
"Context",
",",
"params",
"*",
"topicParams",
")",
"(",
"topic",
"string",
",",
"tok",
"string",
",",
"err",
"error",
")",
"{",
"// If given URL, ask the service for name of it... | // prepareTopic creates a pubsub topic that can be used to pass task related
// messages back to the task.Manager that handles the task.
//
// It returns full topic name, as well as a token that securely identifies the
// task. It should be put into 'auth_token' attribute of PubSub messages by
// whoever publishes them. | [
"prepareTopic",
"creates",
"a",
"pubsub",
"topic",
"that",
"can",
"be",
"used",
"to",
"pass",
"task",
"related",
"messages",
"back",
"to",
"the",
"task",
".",
"Manager",
"that",
"handles",
"the",
"task",
".",
"It",
"returns",
"full",
"topic",
"name",
"as",... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/engine.go#L1960-L2010 |
8,220 | luci/luci-go | cipd/client/cipd/fs/fs.go | EnsureFile | func EnsureFile(ctx context.Context, fs FileSystem, path string, content io.Reader) error {
return fs.EnsureFile(ctx, path, func(f *os.File) error {
_, err := io.Copy(f, content)
return err
})
} | go | func EnsureFile(ctx context.Context, fs FileSystem, path string, content io.Reader) error {
return fs.EnsureFile(ctx, path, func(f *os.File) error {
_, err := io.Copy(f, content)
return err
})
} | [
"func",
"EnsureFile",
"(",
"ctx",
"context",
".",
"Context",
",",
"fs",
"FileSystem",
",",
"path",
"string",
",",
"content",
"io",
".",
"Reader",
")",
"error",
"{",
"return",
"fs",
".",
"EnsureFile",
"(",
"ctx",
",",
"path",
",",
"func",
"(",
"f",
"*... | // EnsureFile creates a file with the given content.
// It will create full directory path to the file if necessary. | [
"EnsureFile",
"creates",
"a",
"file",
"with",
"the",
"given",
"content",
".",
"It",
"will",
"create",
"full",
"directory",
"path",
"to",
"the",
"file",
"if",
"necessary",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/fs.go#L150-L155 |
8,221 | luci/luci-go | cipd/client/cipd/fs/fs.go | moveToTrash | func (f *fsImpl) moveToTrash(ctx context.Context, path string) string {
if err := os.MkdirAll(f.trash, 0777); err != nil {
logging.Warningf(ctx, "fs: can't create trash directory %q - %s", f.trash, err)
return ""
}
trashed := filepath.Join(f.trash, pseudoRand())
if err := atomicRename(path, trashed); err != nil {
if !os.IsNotExist(err) {
logging.Warningf(ctx, "fs: failed to rename(%q, %q) - %s", path, trashed, err)
}
return ""
}
return trashed
} | go | func (f *fsImpl) moveToTrash(ctx context.Context, path string) string {
if err := os.MkdirAll(f.trash, 0777); err != nil {
logging.Warningf(ctx, "fs: can't create trash directory %q - %s", f.trash, err)
return ""
}
trashed := filepath.Join(f.trash, pseudoRand())
if err := atomicRename(path, trashed); err != nil {
if !os.IsNotExist(err) {
logging.Warningf(ctx, "fs: failed to rename(%q, %q) - %s", path, trashed, err)
}
return ""
}
return trashed
} | [
"func",
"(",
"f",
"*",
"fsImpl",
")",
"moveToTrash",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"string",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"f",
".",
"trash",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{... | // moveToTrash is best-effort function to move file or dir to trash.
//
// It returns path to a moved file in trash, or empty string if it can't
// be done. | [
"moveToTrash",
"is",
"best",
"-",
"effort",
"function",
"to",
"move",
"file",
"or",
"dir",
"to",
"trash",
".",
"It",
"returns",
"path",
"to",
"a",
"moved",
"file",
"in",
"trash",
"or",
"empty",
"string",
"if",
"it",
"can",
"t",
"be",
"done",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/fs.go#L537-L550 |
8,222 | luci/luci-go | cipd/client/cipd/fs/fs.go | cleanupTrashedFile | func (f *fsImpl) cleanupTrashedFile(ctx context.Context, path string) error {
if filepath.Dir(path) != f.trash {
return fmt.Errorf("not in the trash - %q", path)
}
err := os.RemoveAll(path)
if err != nil {
logging.Debugf(ctx, "fs: failed to cleanup trashed file - %s", err)
}
return err
} | go | func (f *fsImpl) cleanupTrashedFile(ctx context.Context, path string) error {
if filepath.Dir(path) != f.trash {
return fmt.Errorf("not in the trash - %q", path)
}
err := os.RemoveAll(path)
if err != nil {
logging.Debugf(ctx, "fs: failed to cleanup trashed file - %s", err)
}
return err
} | [
"func",
"(",
"f",
"*",
"fsImpl",
")",
"cleanupTrashedFile",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"error",
"{",
"if",
"filepath",
".",
"Dir",
"(",
"path",
")",
"!=",
"f",
".",
"trash",
"{",
"return",
"fmt",
".",
"Errorf",... | // cleanupTrashedFile is best-effort function to remove a trashed file or dir.
//
// Logs errors. | [
"cleanupTrashedFile",
"is",
"best",
"-",
"effort",
"function",
"to",
"remove",
"a",
"trashed",
"file",
"or",
"dir",
".",
"Logs",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/fs.go#L555-L564 |
8,223 | luci/luci-go | cipd/client/cipd/fs/fs.go | pseudoRand | func pseudoRand() string {
ts := time.Now().UnixNano()
lastUsedTimeLock.Lock()
if ts <= lastUsedTime {
ts = lastUsedTime + 1
}
lastUsedTime = ts
lastUsedTimeLock.Unlock()
// Hash the state to get a smaller pseudorandom string.
h := sha256.New()
fmt.Fprintf(h, "%v_%v", os.Getpid(), ts)
sum := h.Sum(nil)
digest := base64.RawURLEncoding.EncodeToString(sum)
return digest[:12]
} | go | func pseudoRand() string {
ts := time.Now().UnixNano()
lastUsedTimeLock.Lock()
if ts <= lastUsedTime {
ts = lastUsedTime + 1
}
lastUsedTime = ts
lastUsedTimeLock.Unlock()
// Hash the state to get a smaller pseudorandom string.
h := sha256.New()
fmt.Fprintf(h, "%v_%v", os.Getpid(), ts)
sum := h.Sum(nil)
digest := base64.RawURLEncoding.EncodeToString(sum)
return digest[:12]
} | [
"func",
"pseudoRand",
"(",
")",
"string",
"{",
"ts",
":=",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
"\n",
"lastUsedTimeLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"ts",
"<=",
"lastUsedTime",
"{",
"ts",
"=",
"lastUsedTime",
"+",
"1",
"... | // pseudoRand returns "random enough" string that can be used in file system
// paths of temp files. | [
"pseudoRand",
"returns",
"random",
"enough",
"string",
"that",
"can",
"be",
"used",
"in",
"file",
"system",
"paths",
"of",
"temp",
"files",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/fs.go#L589-L604 |
8,224 | luci/luci-go | cipd/client/cipd/fs/fs.go | createFile | func createFile(path string, write func(*os.File) error) (err error) {
file, err := os.Create(path)
if err != nil {
return err
}
defer func() {
closeErr := file.Close()
if err == nil {
err = closeErr
}
}()
return write(file)
} | go | func createFile(path string, write func(*os.File) error) (err error) {
file, err := os.Create(path)
if err != nil {
return err
}
defer func() {
closeErr := file.Close()
if err == nil {
err = closeErr
}
}()
return write(file)
} | [
"func",
"createFile",
"(",
"path",
"string",
",",
"write",
"func",
"(",
"*",
"os",
".",
"File",
")",
"error",
")",
"(",
"err",
"error",
")",
"{",
"file",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"... | // createFile creates a file and calls the function to write file content.
//
// Does NOT cleanup the file if something fails midway. | [
"createFile",
"creates",
"a",
"file",
"and",
"calls",
"the",
"function",
"to",
"write",
"file",
"content",
".",
"Does",
"NOT",
"cleanup",
"the",
"file",
"if",
"something",
"fails",
"midway",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/fs.go#L634-L646 |
8,225 | luci/luci-go | auth/identity/glob.go | MakeGlob | func MakeGlob(glob string) (Glob, error) {
g := Glob(glob)
if err := g.Validate(); err != nil {
return "", err
}
return g, nil
} | go | func MakeGlob(glob string) (Glob, error) {
g := Glob(glob)
if err := g.Validate(); err != nil {
return "", err
}
return g, nil
} | [
"func",
"MakeGlob",
"(",
"glob",
"string",
")",
"(",
"Glob",
",",
"error",
")",
"{",
"g",
":=",
"Glob",
"(",
"glob",
")",
"\n",
"if",
"err",
":=",
"g",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
... | // MakeGlob ensures 'glob' string looks like a valid identity glob and
// returns it as Glob value. | [
"MakeGlob",
"ensures",
"glob",
"string",
"looks",
"like",
"a",
"valid",
"identity",
"glob",
"and",
"returns",
"it",
"as",
"Glob",
"value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/glob.go#L37-L43 |
8,226 | luci/luci-go | auth/identity/glob.go | Validate | func (g Glob) Validate() error {
chunks := strings.SplitN(string(g), ":", 2)
if len(chunks) != 2 {
return fmt.Errorf("auth: bad identity glob string %q", g)
}
if knownKinds[Kind(chunks[0])] == nil {
return fmt.Errorf("auth: bad identity glob kind %q", chunks[0])
}
if chunks[1] == "" {
return fmt.Errorf("auth: identity glob can't be empty")
}
if _, err := cache.translate(chunks[1]); err != nil {
return fmt.Errorf("auth: bad identity glob pattern %q - %s", chunks[1], err)
}
return nil
} | go | func (g Glob) Validate() error {
chunks := strings.SplitN(string(g), ":", 2)
if len(chunks) != 2 {
return fmt.Errorf("auth: bad identity glob string %q", g)
}
if knownKinds[Kind(chunks[0])] == nil {
return fmt.Errorf("auth: bad identity glob kind %q", chunks[0])
}
if chunks[1] == "" {
return fmt.Errorf("auth: identity glob can't be empty")
}
if _, err := cache.translate(chunks[1]); err != nil {
return fmt.Errorf("auth: bad identity glob pattern %q - %s", chunks[1], err)
}
return nil
} | [
"func",
"(",
"g",
"Glob",
")",
"Validate",
"(",
")",
"error",
"{",
"chunks",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"g",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"chunks",
")",
"!=",
"2",
"{",
"return",
"fmt",
... | // Validate checks that the identity glob string is well-formed. | [
"Validate",
"checks",
"that",
"the",
"identity",
"glob",
"string",
"is",
"well",
"-",
"formed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/glob.go#L46-L61 |
8,227 | luci/luci-go | auth/identity/glob.go | Kind | func (g Glob) Kind() Kind {
chunks := strings.SplitN(string(g), ":", 2)
if len(chunks) != 2 {
return Anonymous
}
return Kind(chunks[0])
} | go | func (g Glob) Kind() Kind {
chunks := strings.SplitN(string(g), ":", 2)
if len(chunks) != 2 {
return Anonymous
}
return Kind(chunks[0])
} | [
"func",
"(",
"g",
"Glob",
")",
"Kind",
"(",
")",
"Kind",
"{",
"chunks",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"g",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"chunks",
")",
"!=",
"2",
"{",
"return",
"Anonymous",
... | // Kind returns identity glob kind. If identity glob string is invalid returns
// Anonymous. | [
"Kind",
"returns",
"identity",
"glob",
"kind",
".",
"If",
"identity",
"glob",
"string",
"is",
"invalid",
"returns",
"Anonymous",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/glob.go#L65-L71 |
8,228 | luci/luci-go | auth/identity/glob.go | Pattern | func (g Glob) Pattern() string {
chunks := strings.SplitN(string(g), ":", 2)
if len(chunks) != 2 {
return ""
}
return chunks[1]
} | go | func (g Glob) Pattern() string {
chunks := strings.SplitN(string(g), ":", 2)
if len(chunks) != 2 {
return ""
}
return chunks[1]
} | [
"func",
"(",
"g",
"Glob",
")",
"Pattern",
"(",
")",
"string",
"{",
"chunks",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"g",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"chunks",
")",
"!=",
"2",
"{",
"return",
"\"",
... | // Pattern returns a pattern part of the identity glob. If the identity glob
// string is invalid returns empty string. | [
"Pattern",
"returns",
"a",
"pattern",
"part",
"of",
"the",
"identity",
"glob",
".",
"If",
"the",
"identity",
"glob",
"string",
"is",
"invalid",
"returns",
"empty",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/glob.go#L75-L81 |
8,229 | luci/luci-go | auth/identity/glob.go | Match | func (g Glob) Match(id Identity) bool {
globChunks := strings.SplitN(string(g), ":", 2)
if len(globChunks) != 2 || knownKinds[Kind(globChunks[0])] == nil {
return false
}
globKind := globChunks[0]
pattern := globChunks[1]
idChunks := strings.SplitN(string(id), ":", 2)
if len(idChunks) != 2 || knownKinds[Kind(idChunks[0])] == nil {
return false
}
idKind := idChunks[0]
name := idChunks[1]
if idKind != globKind {
return false
}
if strings.ContainsRune(name, '\n') {
return false
}
re, err := cache.translate(pattern)
if err != nil {
return false
}
return re.MatchString(name)
} | go | func (g Glob) Match(id Identity) bool {
globChunks := strings.SplitN(string(g), ":", 2)
if len(globChunks) != 2 || knownKinds[Kind(globChunks[0])] == nil {
return false
}
globKind := globChunks[0]
pattern := globChunks[1]
idChunks := strings.SplitN(string(id), ":", 2)
if len(idChunks) != 2 || knownKinds[Kind(idChunks[0])] == nil {
return false
}
idKind := idChunks[0]
name := idChunks[1]
if idKind != globKind {
return false
}
if strings.ContainsRune(name, '\n') {
return false
}
re, err := cache.translate(pattern)
if err != nil {
return false
}
return re.MatchString(name)
} | [
"func",
"(",
"g",
"Glob",
")",
"Match",
"(",
"id",
"Identity",
")",
"bool",
"{",
"globChunks",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"g",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"globChunks",
")",
"!=",
"2",
"... | // Match returns true if glob matches an identity. If identity string
// or identity glob string are invalid, returns false. | [
"Match",
"returns",
"true",
"if",
"glob",
"matches",
"an",
"identity",
".",
"If",
"identity",
"string",
"or",
"identity",
"glob",
"string",
"are",
"invalid",
"returns",
"false",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/glob.go#L85-L112 |
8,230 | luci/luci-go | auth/identity/glob.go | translate | func (c *patternCache) translate(pat string) (*regexp.Regexp, error) {
c.RLock()
val, ok := c.cache[pat]
c.RUnlock()
if ok {
return val.re, val.err
}
c.Lock()
defer c.Unlock()
if val, ok := c.cache[pat]; ok {
return val.re, val.err
}
if c.cache == nil || len(c.cache) > 500 {
c.cache = map[string]cacheEntry{}
}
var re *regexp.Regexp
reStr, err := translate(pat)
if err == nil {
re, err = regexp.Compile(reStr)
}
c.cache[pat] = cacheEntry{re, err}
return re, err
} | go | func (c *patternCache) translate(pat string) (*regexp.Regexp, error) {
c.RLock()
val, ok := c.cache[pat]
c.RUnlock()
if ok {
return val.re, val.err
}
c.Lock()
defer c.Unlock()
if val, ok := c.cache[pat]; ok {
return val.re, val.err
}
if c.cache == nil || len(c.cache) > 500 {
c.cache = map[string]cacheEntry{}
}
var re *regexp.Regexp
reStr, err := translate(pat)
if err == nil {
re, err = regexp.Compile(reStr)
}
c.cache[pat] = cacheEntry{re, err}
return re, err
} | [
"func",
"(",
"c",
"*",
"patternCache",
")",
"translate",
"(",
"pat",
"string",
")",
"(",
"*",
"regexp",
".",
"Regexp",
",",
"error",
")",
"{",
"c",
".",
"RLock",
"(",
")",
"\n",
"val",
",",
"ok",
":=",
"c",
".",
"cache",
"[",
"pat",
"]",
"\n",
... | // translate grabs converted regexp from cache or calls 'translate' to get it. | [
"translate",
"grabs",
"converted",
"regexp",
"from",
"cache",
"or",
"calls",
"translate",
"to",
"get",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/glob.go#L133-L159 |
8,231 | luci/luci-go | auth/identity/glob.go | translate | func translate(pat string) (string, error) {
res := "^"
for _, runeVal := range pat {
switch runeVal {
case '\n':
return "", fmt.Errorf("new lines are not supported in globs")
case '*':
res += ".*"
default:
res += regexp.QuoteMeta(string(runeVal))
}
}
return res + "$", nil
} | go | func translate(pat string) (string, error) {
res := "^"
for _, runeVal := range pat {
switch runeVal {
case '\n':
return "", fmt.Errorf("new lines are not supported in globs")
case '*':
res += ".*"
default:
res += regexp.QuoteMeta(string(runeVal))
}
}
return res + "$", nil
} | [
"func",
"translate",
"(",
"pat",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"res",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"runeVal",
":=",
"range",
"pat",
"{",
"switch",
"runeVal",
"{",
"case",
"'\\n'",
":",
"return",
"\"",
"\"",
",",
... | // translate converts glob pattern to a regular expression string. | [
"translate",
"converts",
"glob",
"pattern",
"to",
"a",
"regular",
"expression",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/glob.go#L162-L175 |
8,232 | luci/luci-go | machine-db/appengine/rpc/racks.go | ListRacks | func (*Service) ListRacks(c context.Context, req *crimson.ListRacksRequest) (*crimson.ListRacksResponse, error) {
racks, err := listRacks(c, req)
if err != nil {
return nil, err
}
return &crimson.ListRacksResponse{
Racks: racks,
}, nil
} | go | func (*Service) ListRacks(c context.Context, req *crimson.ListRacksRequest) (*crimson.ListRacksResponse, error) {
racks, err := listRacks(c, req)
if err != nil {
return nil, err
}
return &crimson.ListRacksResponse{
Racks: racks,
}, nil
} | [
"func",
"(",
"*",
"Service",
")",
"ListRacks",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"ListRacksRequest",
")",
"(",
"*",
"crimson",
".",
"ListRacksResponse",
",",
"error",
")",
"{",
"racks",
",",
"err",
":=",
"listRacks",
... | // ListRacks handles a request to retrieve racks. | [
"ListRacks",
"handles",
"a",
"request",
"to",
"retrieve",
"racks",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/racks.go#L30-L38 |
8,233 | luci/luci-go | machine-db/appengine/rpc/racks.go | listRacks | func listRacks(c context.Context, req *crimson.ListRacksRequest) ([]*crimson.Rack, error) {
stmt := squirrel.Select("r.name", "r.description", "r.state", "d.name", "h.name").
From("(racks r, datacenters d)").
LeftJoin("kvms k ON r.kvm_id = k.id").
LeftJoin("hostnames h ON k.hostname_id = h.id").
Where("r.datacenter_id = d.id")
stmt = selectInString(stmt, "r.name", req.Names)
stmt = selectInString(stmt, "d.name", req.Datacenters)
stmt = selectInString(stmt, "h.name", req.Kvms)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Annotate(err, "failed to generate statement").Err()
}
db := database.Get(c)
rows, err := db.QueryContext(c, query, args...)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch racks").Err()
}
defer rows.Close()
var racks []*crimson.Rack
for rows.Next() {
rack := &crimson.Rack{}
var kvm sql.NullString
if err = rows.Scan(&rack.Name, &rack.Description, &rack.State, &rack.Datacenter, &kvm); err != nil {
return nil, errors.Annotate(err, "failed to fetch rack").Err()
}
if kvm.Valid {
rack.Kvm = kvm.String
}
racks = append(racks, rack)
}
return racks, nil
} | go | func listRacks(c context.Context, req *crimson.ListRacksRequest) ([]*crimson.Rack, error) {
stmt := squirrel.Select("r.name", "r.description", "r.state", "d.name", "h.name").
From("(racks r, datacenters d)").
LeftJoin("kvms k ON r.kvm_id = k.id").
LeftJoin("hostnames h ON k.hostname_id = h.id").
Where("r.datacenter_id = d.id")
stmt = selectInString(stmt, "r.name", req.Names)
stmt = selectInString(stmt, "d.name", req.Datacenters)
stmt = selectInString(stmt, "h.name", req.Kvms)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Annotate(err, "failed to generate statement").Err()
}
db := database.Get(c)
rows, err := db.QueryContext(c, query, args...)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch racks").Err()
}
defer rows.Close()
var racks []*crimson.Rack
for rows.Next() {
rack := &crimson.Rack{}
var kvm sql.NullString
if err = rows.Scan(&rack.Name, &rack.Description, &rack.State, &rack.Datacenter, &kvm); err != nil {
return nil, errors.Annotate(err, "failed to fetch rack").Err()
}
if kvm.Valid {
rack.Kvm = kvm.String
}
racks = append(racks, rack)
}
return racks, nil
} | [
"func",
"listRacks",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"ListRacksRequest",
")",
"(",
"[",
"]",
"*",
"crimson",
".",
"Rack",
",",
"error",
")",
"{",
"stmt",
":=",
"squirrel",
".",
"Select",
"(",
"\"",
"\"",
",",
"... | // listRacks returns a slice of racks in the database. | [
"listRacks",
"returns",
"a",
"slice",
"of",
"racks",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/racks.go#L41-L75 |
8,234 | luci/luci-go | cipd/version/version.go | GetVersionFile | func GetVersionFile(exePath string) string {
// <root>/.versions/exename.cipd_version
return filepath.Join(filepath.Dir(exePath), ".versions", filepath.Base(exePath)+".cipd_version")
} | go | func GetVersionFile(exePath string) string {
// <root>/.versions/exename.cipd_version
return filepath.Join(filepath.Dir(exePath), ".versions", filepath.Base(exePath)+".cipd_version")
} | [
"func",
"GetVersionFile",
"(",
"exePath",
"string",
")",
"string",
"{",
"// <root>/.versions/exename.cipd_version",
"return",
"filepath",
".",
"Join",
"(",
"filepath",
".",
"Dir",
"(",
"exePath",
")",
",",
"\"",
"\"",
",",
"filepath",
".",
"Base",
"(",
"exePat... | // GetVersionFile returns the path to the version file corresponding to the
// provided exe. This isn't typically needed, but can be useful for debugging. | [
"GetVersionFile",
"returns",
"the",
"path",
"to",
"the",
"version",
"file",
"corresponding",
"to",
"the",
"provided",
"exe",
".",
"This",
"isn",
"t",
"typically",
"needed",
"but",
"can",
"be",
"useful",
"for",
"debugging",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/version/version.go#L117-L120 |
8,235 | luci/luci-go | cipd/version/version.go | readVersionFile | func readVersionFile(path string) (Info, error) {
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
err = nil
}
return Info{}, err
}
defer f.Close()
out := Info{}
if err = json.NewDecoder(f).Decode(&out); err != nil {
return Info{}, err
}
return out, nil
} | go | func readVersionFile(path string) (Info, error) {
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
err = nil
}
return Info{}, err
}
defer f.Close()
out := Info{}
if err = json.NewDecoder(f).Decode(&out); err != nil {
return Info{}, err
}
return out, nil
} | [
"func",
"readVersionFile",
"(",
"path",
"string",
")",
"(",
"Info",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"e... | // readVersionFile returns parsed version file. Returns empty struct and nil if
// it is missing, error if it can't be read. | [
"readVersionFile",
"returns",
"parsed",
"version",
"file",
".",
"Returns",
"empty",
"struct",
"and",
"nil",
"if",
"it",
"is",
"missing",
"error",
"if",
"it",
"can",
"t",
"be",
"read",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/version/version.go#L132-L146 |
8,236 | luci/luci-go | cipd/client/cipd/fs/path.go | IsSubpath | func IsSubpath(path, root string) bool {
path, err := filepath.Abs(filepath.Clean(path))
if err != nil {
return false
}
root, err = filepath.Abs(filepath.Clean(root))
if err != nil {
return false
}
if root == path {
return true
}
if root[len(root)-1] != filepath.Separator {
root += string(filepath.Separator)
}
return strings.HasPrefix(path, root)
} | go | func IsSubpath(path, root string) bool {
path, err := filepath.Abs(filepath.Clean(path))
if err != nil {
return false
}
root, err = filepath.Abs(filepath.Clean(root))
if err != nil {
return false
}
if root == path {
return true
}
if root[len(root)-1] != filepath.Separator {
root += string(filepath.Separator)
}
return strings.HasPrefix(path, root)
} | [
"func",
"IsSubpath",
"(",
"path",
",",
"root",
"string",
")",
"bool",
"{",
"path",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"filepath",
".",
"Clean",
"(",
"path",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
... | // IsSubpath returns true if 'path' is 'root' or is inside a subdirectory of
// 'root'. Both 'path' and 'root' should be given as a native paths. If any of
// paths can't be converted to an absolute path returns false. | [
"IsSubpath",
"returns",
"true",
"if",
"path",
"is",
"root",
"or",
"is",
"inside",
"a",
"subdirectory",
"of",
"root",
".",
"Both",
"path",
"and",
"root",
"should",
"be",
"given",
"as",
"a",
"native",
"paths",
".",
"If",
"any",
"of",
"paths",
"can",
"t",... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/path.go#L26-L42 |
8,237 | luci/luci-go | dm/api/service/v1/graph_data_query.go | ToQuery | func (g *GraphData) ToQuery() (ret *GraphQuery) {
partials := map[string][]uint32{}
for qid, qst := range g.Quests {
// TODO(iannucci): handle q.Partial explicitly?
for aid, atmpt := range qst.Attempts {
if atmpt.Partial.Any() {
partials[qid] = append(partials[qid], aid)
}
}
}
if len(partials) > 0 {
ret = &GraphQuery{AttemptList: NewAttemptList(partials)}
}
return
} | go | func (g *GraphData) ToQuery() (ret *GraphQuery) {
partials := map[string][]uint32{}
for qid, qst := range g.Quests {
// TODO(iannucci): handle q.Partial explicitly?
for aid, atmpt := range qst.Attempts {
if atmpt.Partial.Any() {
partials[qid] = append(partials[qid], aid)
}
}
}
if len(partials) > 0 {
ret = &GraphQuery{AttemptList: NewAttemptList(partials)}
}
return
} | [
"func",
"(",
"g",
"*",
"GraphData",
")",
"ToQuery",
"(",
")",
"(",
"ret",
"*",
"GraphQuery",
")",
"{",
"partials",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"uint32",
"{",
"}",
"\n",
"for",
"qid",
",",
"qst",
":=",
"range",
"g",
".",
"Quests",
... | // ToQuery generates a new GraphQuery.
//
// This generates a GraphQuery that queries for any Attempts which are marked as
// Partial in the current GraphData. | [
"ToQuery",
"generates",
"a",
"new",
"GraphQuery",
".",
"This",
"generates",
"a",
"GraphQuery",
"that",
"queries",
"for",
"any",
"Attempts",
"which",
"are",
"marked",
"as",
"Partial",
"in",
"the",
"current",
"GraphData",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_data_query.go#L21-L36 |
8,238 | luci/luci-go | client/isolate/isolate.go | Init | func (a *ArchiveOptions) Init() {
a.Blacklist = stringlistflag.Flag{}
a.PathVariables = map[string]string{}
if runtime.GOOS == "windows" {
a.PathVariables["EXECUTABLE_SUFFIX"] = ".exe"
} else {
a.PathVariables["EXECUTABLE_SUFFIX"] = ""
}
a.ExtraVariables = map[string]string{}
a.ConfigVariables = map[string]string{}
} | go | func (a *ArchiveOptions) Init() {
a.Blacklist = stringlistflag.Flag{}
a.PathVariables = map[string]string{}
if runtime.GOOS == "windows" {
a.PathVariables["EXECUTABLE_SUFFIX"] = ".exe"
} else {
a.PathVariables["EXECUTABLE_SUFFIX"] = ""
}
a.ExtraVariables = map[string]string{}
a.ConfigVariables = map[string]string{}
} | [
"func",
"(",
"a",
"*",
"ArchiveOptions",
")",
"Init",
"(",
")",
"{",
"a",
".",
"Blacklist",
"=",
"stringlistflag",
".",
"Flag",
"{",
"}",
"\n",
"a",
".",
"PathVariables",
"=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"if",
"runtime",
".... | // Init initializes with non-nil values. | [
"Init",
"initializes",
"with",
"non",
"-",
"nil",
"values",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/isolate.go#L71-L81 |
8,239 | luci/luci-go | client/isolate/isolate.go | PostProcess | func (a *ArchiveOptions) PostProcess(cwd string) {
// Set default blacklist only if none is set.
if len(a.Blacklist) == 0 {
// This cannot be generalized as ".*" as there is known use that require
// a ".pki" directory to be mapped.
a.Blacklist = stringlistflag.Flag{
// Temporary python files.
"*.pyc",
// Temporary vim files.
"*.swp",
".git",
".hg",
".svn",
}
}
if !filepath.IsAbs(a.Isolate) {
a.Isolate = filepath.Join(cwd, a.Isolate)
}
a.Isolate = filepath.Clean(a.Isolate)
if !filepath.IsAbs(a.Isolated) {
a.Isolated = filepath.Join(cwd, a.Isolated)
}
a.Isolated = filepath.Clean(a.Isolated)
for k, v := range a.PathVariables {
// This is due to a Windows + GYP specific issue, where double-quoted paths
// would get mangled in a way that cannot be resolved unless a space is
// injected.
a.PathVariables[k] = strings.TrimSpace(v)
}
} | go | func (a *ArchiveOptions) PostProcess(cwd string) {
// Set default blacklist only if none is set.
if len(a.Blacklist) == 0 {
// This cannot be generalized as ".*" as there is known use that require
// a ".pki" directory to be mapped.
a.Blacklist = stringlistflag.Flag{
// Temporary python files.
"*.pyc",
// Temporary vim files.
"*.swp",
".git",
".hg",
".svn",
}
}
if !filepath.IsAbs(a.Isolate) {
a.Isolate = filepath.Join(cwd, a.Isolate)
}
a.Isolate = filepath.Clean(a.Isolate)
if !filepath.IsAbs(a.Isolated) {
a.Isolated = filepath.Join(cwd, a.Isolated)
}
a.Isolated = filepath.Clean(a.Isolated)
for k, v := range a.PathVariables {
// This is due to a Windows + GYP specific issue, where double-quoted paths
// would get mangled in a way that cannot be resolved unless a space is
// injected.
a.PathVariables[k] = strings.TrimSpace(v)
}
} | [
"func",
"(",
"a",
"*",
"ArchiveOptions",
")",
"PostProcess",
"(",
"cwd",
"string",
")",
"{",
"// Set default blacklist only if none is set.",
"if",
"len",
"(",
"a",
".",
"Blacklist",
")",
"==",
"0",
"{",
"// This cannot be generalized as \".*\" as there is known use tha... | // PostProcess post-processes the flags to fix any compatibility issue. | [
"PostProcess",
"post",
"-",
"processes",
"the",
"flags",
"to",
"fix",
"any",
"compatibility",
"issue",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/isolate.go#L84-L115 |
8,240 | luci/luci-go | scheduler/appengine/apiservers/admin.go | AdminServerWithACL | func AdminServerWithACL(e engine.EngineInternal, c catalog.Catalog, adminGroup string) internal.AdminServer {
return &internal.DecoratedAdmin{
Service: &adminServer{
Engine: e,
Catalog: c,
},
Prelude: func(c context.Context, methodName string, req proto.Message) (context.Context, error) {
caller := auth.CurrentIdentity(c)
logging.Warningf(c, "Admin call %q by %q", methodName, caller)
switch yes, err := auth.IsMember(c, adminGroup); {
case err != nil:
return nil, status.Errorf(codes.Internal, "failed to check ACL")
case !yes:
return nil, status.Errorf(codes.PermissionDenied, "not an administrator")
default:
return c, nil
}
},
Postlude: func(c context.Context, methodName string, rsp proto.Message, err error) error {
return grpcutil.GRPCifyAndLogErr(c, err)
},
}
} | go | func AdminServerWithACL(e engine.EngineInternal, c catalog.Catalog, adminGroup string) internal.AdminServer {
return &internal.DecoratedAdmin{
Service: &adminServer{
Engine: e,
Catalog: c,
},
Prelude: func(c context.Context, methodName string, req proto.Message) (context.Context, error) {
caller := auth.CurrentIdentity(c)
logging.Warningf(c, "Admin call %q by %q", methodName, caller)
switch yes, err := auth.IsMember(c, adminGroup); {
case err != nil:
return nil, status.Errorf(codes.Internal, "failed to check ACL")
case !yes:
return nil, status.Errorf(codes.PermissionDenied, "not an administrator")
default:
return c, nil
}
},
Postlude: func(c context.Context, methodName string, rsp proto.Message, err error) error {
return grpcutil.GRPCifyAndLogErr(c, err)
},
}
} | [
"func",
"AdminServerWithACL",
"(",
"e",
"engine",
".",
"EngineInternal",
",",
"c",
"catalog",
".",
"Catalog",
",",
"adminGroup",
"string",
")",
"internal",
".",
"AdminServer",
"{",
"return",
"&",
"internal",
".",
"DecoratedAdmin",
"{",
"Service",
":",
"&",
"... | // AdminServerWithACL returns AdminServer implementation that checks all callers
// are in the given administrator group. | [
"AdminServerWithACL",
"returns",
"AdminServer",
"implementation",
"that",
"checks",
"all",
"callers",
"are",
"in",
"the",
"given",
"administrator",
"group",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/apiservers/admin.go#L37-L61 |
8,241 | luci/luci-go | scheduler/appengine/apiservers/admin.go | GetDebugJobState | func (s *adminServer) GetDebugJobState(c context.Context, r *schedulerpb.JobRef) (resp *internal.DebugJobState, err error) {
switch state, err := s.Engine.GetDebugJobState(c, r.Project+"/"+r.Job); {
case err == engine.ErrNoSuchJob:
return nil, status.Errorf(codes.NotFound, "no such job")
case err != nil:
return nil, err
default:
return &internal.DebugJobState{
Enabled: state.Job.Enabled,
Paused: state.Job.Paused,
LastTriage: google.NewTimestamp(state.Job.LastTriage),
CronState: &internal.DebugJobState_CronState{
Enabled: state.Job.Cron.Enabled,
Generation: state.Job.Cron.Generation,
LastRewind: google.NewTimestamp(state.Job.Cron.LastRewind),
LastTickWhen: google.NewTimestamp(state.Job.Cron.LastTick.When),
LastTickNonce: state.Job.Cron.LastTick.TickNonce,
},
ManagerState: state.ManagerState,
ActiveInvocations: state.Job.ActiveInvocations,
FinishedInvocations: state.FinishedInvocations,
RecentlyFinishedSet: state.RecentlyFinishedSet,
PendingTriggersSet: state.PendingTriggersSet,
}, nil
}
} | go | func (s *adminServer) GetDebugJobState(c context.Context, r *schedulerpb.JobRef) (resp *internal.DebugJobState, err error) {
switch state, err := s.Engine.GetDebugJobState(c, r.Project+"/"+r.Job); {
case err == engine.ErrNoSuchJob:
return nil, status.Errorf(codes.NotFound, "no such job")
case err != nil:
return nil, err
default:
return &internal.DebugJobState{
Enabled: state.Job.Enabled,
Paused: state.Job.Paused,
LastTriage: google.NewTimestamp(state.Job.LastTriage),
CronState: &internal.DebugJobState_CronState{
Enabled: state.Job.Cron.Enabled,
Generation: state.Job.Cron.Generation,
LastRewind: google.NewTimestamp(state.Job.Cron.LastRewind),
LastTickWhen: google.NewTimestamp(state.Job.Cron.LastTick.When),
LastTickNonce: state.Job.Cron.LastTick.TickNonce,
},
ManagerState: state.ManagerState,
ActiveInvocations: state.Job.ActiveInvocations,
FinishedInvocations: state.FinishedInvocations,
RecentlyFinishedSet: state.RecentlyFinishedSet,
PendingTriggersSet: state.PendingTriggersSet,
}, nil
}
} | [
"func",
"(",
"s",
"*",
"adminServer",
")",
"GetDebugJobState",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"schedulerpb",
".",
"JobRef",
")",
"(",
"resp",
"*",
"internal",
".",
"DebugJobState",
",",
"err",
"error",
")",
"{",
"switch",
"state",
... | // GetDebugJobState implements the corresponding RPC method. | [
"GetDebugJobState",
"implements",
"the",
"corresponding",
"RPC",
"method",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/apiservers/admin.go#L73-L98 |
8,242 | luci/luci-go | scheduler/appengine/engine/job.go | IsEqual | func (e *Job) IsEqual(other *Job) bool {
return e == other || (e.JobID == other.JobID &&
e.ProjectID == other.ProjectID &&
e.Flavor == other.Flavor &&
e.Enabled == other.Enabled &&
e.Paused == other.Paused &&
e.Revision == other.Revision &&
e.RevisionURL == other.RevisionURL &&
e.Schedule == other.Schedule &&
e.LastTriage.Equal(other.LastTriage) &&
e.Acls.Equal(&other.Acls) &&
bytes.Equal(e.Task, other.Task) &&
equalSortedLists(e.TriggeredJobIDs, other.TriggeredJobIDs) &&
e.Cron.Equal(&other.Cron) &&
bytes.Equal(e.TriggeringPolicyRaw, other.TriggeringPolicyRaw) &&
equalInt64Lists(e.ActiveInvocations, other.ActiveInvocations) &&
bytes.Equal(e.FinishedInvocationsRaw, other.FinishedInvocationsRaw))
} | go | func (e *Job) IsEqual(other *Job) bool {
return e == other || (e.JobID == other.JobID &&
e.ProjectID == other.ProjectID &&
e.Flavor == other.Flavor &&
e.Enabled == other.Enabled &&
e.Paused == other.Paused &&
e.Revision == other.Revision &&
e.RevisionURL == other.RevisionURL &&
e.Schedule == other.Schedule &&
e.LastTriage.Equal(other.LastTriage) &&
e.Acls.Equal(&other.Acls) &&
bytes.Equal(e.Task, other.Task) &&
equalSortedLists(e.TriggeredJobIDs, other.TriggeredJobIDs) &&
e.Cron.Equal(&other.Cron) &&
bytes.Equal(e.TriggeringPolicyRaw, other.TriggeringPolicyRaw) &&
equalInt64Lists(e.ActiveInvocations, other.ActiveInvocations) &&
bytes.Equal(e.FinishedInvocationsRaw, other.FinishedInvocationsRaw))
} | [
"func",
"(",
"e",
"*",
"Job",
")",
"IsEqual",
"(",
"other",
"*",
"Job",
")",
"bool",
"{",
"return",
"e",
"==",
"other",
"||",
"(",
"e",
".",
"JobID",
"==",
"other",
".",
"JobID",
"&&",
"e",
".",
"ProjectID",
"==",
"other",
".",
"ProjectID",
"&&",... | // IsEqual returns true iff 'e' is equal to 'other'. | [
"IsEqual",
"returns",
"true",
"iff",
"e",
"is",
"equal",
"to",
"other",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/job.go#L207-L224 |
8,243 | luci/luci-go | scheduler/appengine/engine/job.go | MatchesDefinition | func (e *Job) MatchesDefinition(def catalog.Definition) bool {
return e.JobID == def.JobID &&
e.Flavor == def.Flavor &&
e.Schedule == def.Schedule &&
e.Acls.Equal(&def.Acls) &&
bytes.Equal(e.Task, def.Task) &&
bytes.Equal(e.TriggeringPolicyRaw, def.TriggeringPolicy) &&
equalSortedLists(e.TriggeredJobIDs, def.TriggeredJobIDs)
} | go | func (e *Job) MatchesDefinition(def catalog.Definition) bool {
return e.JobID == def.JobID &&
e.Flavor == def.Flavor &&
e.Schedule == def.Schedule &&
e.Acls.Equal(&def.Acls) &&
bytes.Equal(e.Task, def.Task) &&
bytes.Equal(e.TriggeringPolicyRaw, def.TriggeringPolicy) &&
equalSortedLists(e.TriggeredJobIDs, def.TriggeredJobIDs)
} | [
"func",
"(",
"e",
"*",
"Job",
")",
"MatchesDefinition",
"(",
"def",
"catalog",
".",
"Definition",
")",
"bool",
"{",
"return",
"e",
".",
"JobID",
"==",
"def",
".",
"JobID",
"&&",
"e",
".",
"Flavor",
"==",
"def",
".",
"Flavor",
"&&",
"e",
".",
"Sched... | // MatchesDefinition returns true if job definition in the entity matches the
// one specified by catalog.Definition struct. | [
"MatchesDefinition",
"returns",
"true",
"if",
"job",
"definition",
"in",
"the",
"entity",
"matches",
"the",
"one",
"specified",
"by",
"catalog",
".",
"Definition",
"struct",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/job.go#L228-L236 |
8,244 | luci/luci-go | scheduler/appengine/engine/job.go | CheckRole | func (e *Job) CheckRole(c context.Context, role acl.Role) error {
switch yep, err := e.Acls.CallerHasRole(logging.SetField(c, "JobID", e.JobID), role); {
case err != nil:
return err
case !yep:
return ErrNoPermission
}
return nil
} | go | func (e *Job) CheckRole(c context.Context, role acl.Role) error {
switch yep, err := e.Acls.CallerHasRole(logging.SetField(c, "JobID", e.JobID), role); {
case err != nil:
return err
case !yep:
return ErrNoPermission
}
return nil
} | [
"func",
"(",
"e",
"*",
"Job",
")",
"CheckRole",
"(",
"c",
"context",
".",
"Context",
",",
"role",
"acl",
".",
"Role",
")",
"error",
"{",
"switch",
"yep",
",",
"err",
":=",
"e",
".",
"Acls",
".",
"CallerHasRole",
"(",
"logging",
".",
"SetField",
"("... | // CheckRole returns nil if the caller has the given role or ErrNoPermission
// otherwise.
//
// May also return transient errors. | [
"CheckRole",
"returns",
"nil",
"if",
"the",
"caller",
"has",
"the",
"given",
"role",
"or",
"ErrNoPermission",
"otherwise",
".",
"May",
"also",
"return",
"transient",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/job.go#L252-L260 |
8,245 | luci/luci-go | scheduler/appengine/engine/job.go | Add | func (s *invocationIDSet) Add(c context.Context, ids []int64) error {
items := make([]dsset.Item, len(ids))
for i, id := range ids {
items[i].ID = fmt.Sprintf("%d", id)
}
return s.Set.Add(c, items)
} | go | func (s *invocationIDSet) Add(c context.Context, ids []int64) error {
items := make([]dsset.Item, len(ids))
for i, id := range ids {
items[i].ID = fmt.Sprintf("%d", id)
}
return s.Set.Add(c, items)
} | [
"func",
"(",
"s",
"*",
"invocationIDSet",
")",
"Add",
"(",
"c",
"context",
".",
"Context",
",",
"ids",
"[",
"]",
"int64",
")",
"error",
"{",
"items",
":=",
"make",
"(",
"[",
"]",
"dsset",
".",
"Item",
",",
"len",
"(",
"ids",
")",
")",
"\n",
"fo... | // Add adds a bunch of invocation IDs to the set. | [
"Add",
"adds",
"a",
"bunch",
"of",
"invocation",
"IDs",
"to",
"the",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/job.go#L285-L291 |
8,246 | luci/luci-go | scheduler/appengine/engine/job.go | ItemToInvID | func (s *invocationIDSet) ItemToInvID(i *dsset.Item) int64 {
id, _ := strconv.ParseInt(i.ID, 10, 64)
return id
} | go | func (s *invocationIDSet) ItemToInvID(i *dsset.Item) int64 {
id, _ := strconv.ParseInt(i.ID, 10, 64)
return id
} | [
"func",
"(",
"s",
"*",
"invocationIDSet",
")",
"ItemToInvID",
"(",
"i",
"*",
"dsset",
".",
"Item",
")",
"int64",
"{",
"id",
",",
"_",
":=",
"strconv",
".",
"ParseInt",
"(",
"i",
".",
"ID",
",",
"10",
",",
"64",
")",
"\n",
"return",
"id",
"\n",
... | // ItemToInvID takes a dsset.Item and returns invocation ID stored there or 0 if
// it's malformed. | [
"ItemToInvID",
"takes",
"a",
"dsset",
".",
"Item",
"and",
"returns",
"invocation",
"ID",
"stored",
"there",
"or",
"0",
"if",
"it",
"s",
"malformed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/job.go#L295-L298 |
8,247 | luci/luci-go | scheduler/appengine/engine/job.go | Add | func (s *triggersSet) Add(c context.Context, triggers []*internal.Trigger) error {
items := make([]dsset.Item, 0, len(triggers))
for _, t := range triggers {
blob, err := proto.Marshal(t)
if err != nil {
return fmt.Errorf("failed to marshal proto - %s", err)
}
items = append(items, dsset.Item{
ID: t.Id,
Value: blob,
})
}
return s.Set.Add(c, items)
} | go | func (s *triggersSet) Add(c context.Context, triggers []*internal.Trigger) error {
items := make([]dsset.Item, 0, len(triggers))
for _, t := range triggers {
blob, err := proto.Marshal(t)
if err != nil {
return fmt.Errorf("failed to marshal proto - %s", err)
}
items = append(items, dsset.Item{
ID: t.Id,
Value: blob,
})
}
return s.Set.Add(c, items)
} | [
"func",
"(",
"s",
"*",
"triggersSet",
")",
"Add",
"(",
"c",
"context",
".",
"Context",
",",
"triggers",
"[",
"]",
"*",
"internal",
".",
"Trigger",
")",
"error",
"{",
"items",
":=",
"make",
"(",
"[",
"]",
"dsset",
".",
"Item",
",",
"0",
",",
"len"... | // Add adds triggers to the set. | [
"Add",
"adds",
"triggers",
"to",
"the",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/job.go#L321-L334 |
8,248 | luci/luci-go | machine-db/appengine/rpc/validation.go | validateUpdateMask | func validateUpdateMask(m *field_mask.FieldMask) error {
switch {
case m == nil:
return status.Error(codes.InvalidArgument, "update mask is required")
case len(m.Paths) == 0:
return status.Error(codes.InvalidArgument, "at least one update mask path is required")
}
// Path names must be unique.
// Keep records of ones we've already seen.
paths := stringset.New(len(m.Paths))
for _, path := range m.Paths {
if !paths.Add(path) {
return status.Errorf(codes.InvalidArgument, "duplicate update mask path %q", path)
}
}
return nil
} | go | func validateUpdateMask(m *field_mask.FieldMask) error {
switch {
case m == nil:
return status.Error(codes.InvalidArgument, "update mask is required")
case len(m.Paths) == 0:
return status.Error(codes.InvalidArgument, "at least one update mask path is required")
}
// Path names must be unique.
// Keep records of ones we've already seen.
paths := stringset.New(len(m.Paths))
for _, path := range m.Paths {
if !paths.Add(path) {
return status.Errorf(codes.InvalidArgument, "duplicate update mask path %q", path)
}
}
return nil
} | [
"func",
"validateUpdateMask",
"(",
"m",
"*",
"field_mask",
".",
"FieldMask",
")",
"error",
"{",
"switch",
"{",
"case",
"m",
"==",
"nil",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"l... | // valdiateUpdateMask validates the given update mask. | [
"valdiateUpdateMask",
"validates",
"the",
"given",
"update",
"mask",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/validation.go#L26-L42 |
8,249 | luci/luci-go | starlark/builtins/fail.go | GetFailureCollector | func GetFailureCollector(th *starlark.Thread) *FailureCollector {
fc, _ := th.Local(failSlotKey).(*FailureCollector)
return fc
} | go | func GetFailureCollector(th *starlark.Thread) *FailureCollector {
fc, _ := th.Local(failSlotKey).(*FailureCollector)
return fc
} | [
"func",
"GetFailureCollector",
"(",
"th",
"*",
"starlark",
".",
"Thread",
")",
"*",
"FailureCollector",
"{",
"fc",
",",
"_",
":=",
"th",
".",
"Local",
"(",
"failSlotKey",
")",
".",
"(",
"*",
"FailureCollector",
")",
"\n",
"return",
"fc",
"\n",
"}"
] | // GetFailureCollector returns a failure collector installed in the thread. | [
"GetFailureCollector",
"returns",
"a",
"failure",
"collector",
"installed",
"in",
"the",
"thread",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/builtins/fail.go#L114-L117 |
8,250 | luci/luci-go | starlark/builtins/fail.go | Install | func (fc *FailureCollector) Install(t *starlark.Thread) {
t.SetLocal(failSlotKey, fc)
} | go | func (fc *FailureCollector) Install(t *starlark.Thread) {
t.SetLocal(failSlotKey, fc)
} | [
"func",
"(",
"fc",
"*",
"FailureCollector",
")",
"Install",
"(",
"t",
"*",
"starlark",
".",
"Thread",
")",
"{",
"t",
".",
"SetLocal",
"(",
"failSlotKey",
",",
"fc",
")",
"\n",
"}"
] | // Install installs this failure collector into the thread. | [
"Install",
"installs",
"this",
"failure",
"collector",
"into",
"the",
"thread",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/builtins/fail.go#L120-L122 |
8,251 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | getMetadataImpl | func getMetadataImpl(c context.Context, prefix string) ([]*api.PrefixMetadata, []*packageACL, error) {
prefix, err := common.ValidatePackagePrefix(prefix)
if err != nil {
return nil, nil, errors.Annotate(err, "bad prefix given to GetMetadata").Err()
}
// Grab all subprefixes, i.e. ["a", "a/b", "a/b/c"]
var pfxs []string
for i, ch := range prefix {
if ch == '/' {
pfxs = append(pfxs, prefix[:i])
}
}
pfxs = append(pfxs, prefix)
// Start with the root metadata.
out := make([]*api.PrefixMetadata, 0, len(pfxs)+1)
out = append(out, rootMetadata())
// And finish with it if nothing else is requested.
if len(pfxs) == 0 {
return out, nil, nil
}
// Prepare the keys.
ents := make([]*packageACL, 0, len(pfxs)*len(legacyRoles))
for _, p := range pfxs {
ents = prefixACLs(c, p, ents)
}
// Fetch everything. ErrNoSuchEntity errors are fine, everything else is not.
if err = datastore.Get(c, ents); isInternalDSError(err) {
return nil, nil, errors.Annotate(err, "datastore error when fetching PackageACL").Tag(transient.Tag).Err()
}
// Combine the result into a bunch of PrefixMetadata structs.
legLen := len(legacyRoles)
for i, pfx := range pfxs {
if md := mergeIntoPrefixMetadata(c, pfx, ents[i*legLen:(i+1)*legLen]); md != nil {
out = append(out, md)
}
}
return out, ents, nil
} | go | func getMetadataImpl(c context.Context, prefix string) ([]*api.PrefixMetadata, []*packageACL, error) {
prefix, err := common.ValidatePackagePrefix(prefix)
if err != nil {
return nil, nil, errors.Annotate(err, "bad prefix given to GetMetadata").Err()
}
// Grab all subprefixes, i.e. ["a", "a/b", "a/b/c"]
var pfxs []string
for i, ch := range prefix {
if ch == '/' {
pfxs = append(pfxs, prefix[:i])
}
}
pfxs = append(pfxs, prefix)
// Start with the root metadata.
out := make([]*api.PrefixMetadata, 0, len(pfxs)+1)
out = append(out, rootMetadata())
// And finish with it if nothing else is requested.
if len(pfxs) == 0 {
return out, nil, nil
}
// Prepare the keys.
ents := make([]*packageACL, 0, len(pfxs)*len(legacyRoles))
for _, p := range pfxs {
ents = prefixACLs(c, p, ents)
}
// Fetch everything. ErrNoSuchEntity errors are fine, everything else is not.
if err = datastore.Get(c, ents); isInternalDSError(err) {
return nil, nil, errors.Annotate(err, "datastore error when fetching PackageACL").Tag(transient.Tag).Err()
}
// Combine the result into a bunch of PrefixMetadata structs.
legLen := len(legacyRoles)
for i, pfx := range pfxs {
if md := mergeIntoPrefixMetadata(c, pfx, ents[i*legLen:(i+1)*legLen]); md != nil {
out = append(out, md)
}
}
return out, ents, nil
} | [
"func",
"getMetadataImpl",
"(",
"c",
"context",
".",
"Context",
",",
"prefix",
"string",
")",
"(",
"[",
"]",
"*",
"api",
".",
"PrefixMetadata",
",",
"[",
"]",
"*",
"packageACL",
",",
"error",
")",
"{",
"prefix",
",",
"err",
":=",
"common",
".",
"Vali... | // getMetadataImpl implements GetMetadata.
//
// As a bonus it returns all packageACL entities it fetched. This is used by
// VisitMetadata to avoid unnecessary refetches. | [
"getMetadataImpl",
"implements",
"GetMetadata",
".",
"As",
"a",
"bonus",
"it",
"returns",
"all",
"packageACL",
"entities",
"it",
"fetched",
".",
"This",
"is",
"used",
"by",
"VisitMetadata",
"to",
"avoid",
"unnecessary",
"refetches",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L90-L133 |
8,252 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | VisitMetadata | func (legacyStorageImpl) VisitMetadata(c context.Context, prefix string, cb Visitor) error {
prefix, err := common.ValidatePackagePrefix(prefix)
if err != nil {
return errors.Annotate(err, "bad prefix given to VisitMetadata").Err()
}
// Visit 'prefix' directly first, per VisitMetadata contract. There's a chance
// we won't need to recurse deeper at all and can skip all expensive fetches.
md, ents, err := getMetadataImpl(c, prefix)
if err != nil {
return err
}
switch cont, err := cb(prefix, md); {
case err != nil:
return err
case !cont:
return nil
}
// We'll have to recurse into metadata subtree after all. Unfortunately,
// with legacy entity structure there's no way to efficiently fetch only
// immediate children of 'prefix', so we fetch EVERYTHING in advance, building
// a metadata graph for prefix/... in memory.
gr := metadataGraph{}
gr.init(rootMetadata())
// Seed this graph with already fetched entities. They'll be needed to derive
// metadata inherited from 'prefix' and its parents when visiting nodes. For
// example, the metadata graph when visiting prefix "a/b" may look like this:
//
// - "a/b/c"
// /
// ROOT - "a"- "a/b" -- "a/b/d"
// \
// - "a/b/e"
//
// The traversal will be started form "a/b", but we still need the nodes
// leading to the root to get all inherited metadata.
gr.insert(c, ents)
// Fetch each per-role subtree separately, they have different key prefixes.
err = parallel.FanOutIn(func(tasks chan<- func() error) {
mu := sync.Mutex{}
for _, role := range legacyRoles {
role := role
tasks <- func() error {
listing, err := listACLsByPrefix(c, role, prefix)
if err == nil {
mu.Lock()
gr.insert(c, listing)
mu.Unlock()
}
return err
}
}
})
if err != nil {
return errors.Annotate(err, "failed to fetch metadata").Tag(transient.Tag).Err()
}
// Make sure we have a path to 'prefix' before we freeze the graph. We need it
// to start the traversal below. It may be missing if there's no metadata
// attached to it and it has no children. This will naturally be handled by
// 'traverse'.
pfx := gr.node(prefix)
// Calculate all PrefixMetadata entries in the graph.
gr.freeze(c)
// Traverse the graph, but make sure to skip 'prefix' itself, we've already
// visited it at the very beginning.
return pfx.traverse(nil, func(n *metadataNode, md []*api.PrefixMetadata) (cont bool, err error) {
switch {
case n.prefix == prefix:
return true, nil
case n.md == nil:
return true, nil // an intermediary node with no metadata, look deeper
default:
return cb(n.prefix, md)
}
})
} | go | func (legacyStorageImpl) VisitMetadata(c context.Context, prefix string, cb Visitor) error {
prefix, err := common.ValidatePackagePrefix(prefix)
if err != nil {
return errors.Annotate(err, "bad prefix given to VisitMetadata").Err()
}
// Visit 'prefix' directly first, per VisitMetadata contract. There's a chance
// we won't need to recurse deeper at all and can skip all expensive fetches.
md, ents, err := getMetadataImpl(c, prefix)
if err != nil {
return err
}
switch cont, err := cb(prefix, md); {
case err != nil:
return err
case !cont:
return nil
}
// We'll have to recurse into metadata subtree after all. Unfortunately,
// with legacy entity structure there's no way to efficiently fetch only
// immediate children of 'prefix', so we fetch EVERYTHING in advance, building
// a metadata graph for prefix/... in memory.
gr := metadataGraph{}
gr.init(rootMetadata())
// Seed this graph with already fetched entities. They'll be needed to derive
// metadata inherited from 'prefix' and its parents when visiting nodes. For
// example, the metadata graph when visiting prefix "a/b" may look like this:
//
// - "a/b/c"
// /
// ROOT - "a"- "a/b" -- "a/b/d"
// \
// - "a/b/e"
//
// The traversal will be started form "a/b", but we still need the nodes
// leading to the root to get all inherited metadata.
gr.insert(c, ents)
// Fetch each per-role subtree separately, they have different key prefixes.
err = parallel.FanOutIn(func(tasks chan<- func() error) {
mu := sync.Mutex{}
for _, role := range legacyRoles {
role := role
tasks <- func() error {
listing, err := listACLsByPrefix(c, role, prefix)
if err == nil {
mu.Lock()
gr.insert(c, listing)
mu.Unlock()
}
return err
}
}
})
if err != nil {
return errors.Annotate(err, "failed to fetch metadata").Tag(transient.Tag).Err()
}
// Make sure we have a path to 'prefix' before we freeze the graph. We need it
// to start the traversal below. It may be missing if there's no metadata
// attached to it and it has no children. This will naturally be handled by
// 'traverse'.
pfx := gr.node(prefix)
// Calculate all PrefixMetadata entries in the graph.
gr.freeze(c)
// Traverse the graph, but make sure to skip 'prefix' itself, we've already
// visited it at the very beginning.
return pfx.traverse(nil, func(n *metadataNode, md []*api.PrefixMetadata) (cont bool, err error) {
switch {
case n.prefix == prefix:
return true, nil
case n.md == nil:
return true, nil // an intermediary node with no metadata, look deeper
default:
return cb(n.prefix, md)
}
})
} | [
"func",
"(",
"legacyStorageImpl",
")",
"VisitMetadata",
"(",
"c",
"context",
".",
"Context",
",",
"prefix",
"string",
",",
"cb",
"Visitor",
")",
"error",
"{",
"prefix",
",",
"err",
":=",
"common",
".",
"ValidatePackagePrefix",
"(",
"prefix",
")",
"\n",
"if... | // VisitMetadata is part of Storage interface. | [
"VisitMetadata",
"is",
"part",
"of",
"Storage",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L136-L217 |
8,253 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | UpdateMetadata | func (legacyStorageImpl) UpdateMetadata(c context.Context, prefix string, cb func(m *api.PrefixMetadata) error) (*api.PrefixMetadata, error) {
prefix, err := common.ValidatePackagePrefix(prefix)
if err != nil {
return nil, errors.Annotate(err, "bad prefix given to GetMetadata").Err()
}
if prefix == "" {
return nil, errors.Reason("the root metadata is not modifiable").Err()
}
var cbErr error // error from 'cb'
var updated *api.PrefixMetadata // updated metadata to return
err = datastore.RunInTransaction(c, func(c context.Context) error {
cbErr = nil // reset in case the transaction is being retried
updated = nil
// Fetch the existing metadata.
ents := prefixACLs(c, prefix, nil)
if err := datastore.Get(c, ents); isInternalDSError(err) {
return errors.Annotate(err, "datastore error when fetching PackageACL").Err()
}
// Convert it to PrefixMetadata object. This will be nil if there's no
// existing metadata, in which case we construct the default metadata
// with no fingerprint (to indicate it is new), see UpdateMetadata doc in
// Storage interface.
updated = mergeIntoPrefixMetadata(c, prefix, ents)
if updated == nil {
updated = &api.PrefixMetadata{Prefix: prefix}
}
// Let the callback update the metadata. Retain the old copy for diff later.
before := proto.Clone(updated).(*api.PrefixMetadata)
if cbErr = cb(updated); cbErr != nil {
return cbErr
}
// Don't let the callback mess with the prefix or the fingerprint.
updated.Prefix = before.Prefix
updated.Fingerprint = before.Fingerprint
if proto.Equal(before, updated) {
return nil // no changes whatsoever, don't touch anything
}
// Apply changes to the datastore. This updates 'ents' to match the metadata
// stored in 'updated'. We then rederive PrefixMetadata (including the new
// fingerprint) from them. We do it this way (instead of calculating the
// fingerprint using 'updated' directly), to be absolutely sure that the
// fingerprint returned by GetMetadata after this transaction lands matches
// the fingerprint we return from UpdateMetadata. In particular, the way
// we store ACLs in legacy entities doesn't preserve order of Acls entries
// in the proto, or order of principals inside Acls, so we need to
// "reformat" the updated metadata before calculating its fingerprint.
if err := applyACLDiff(c, ents, updated); err != nil {
return errors.Annotate(err, "failed to update PackageACL entities").Err()
}
updated = mergeIntoPrefixMetadata(c, prefix, ents)
return nil
}, &datastore.TransactionOptions{XG: true})
switch {
case cbErr != nil:
// The callback itself failed, need to return the error as is, as promised.
return nil, cbErr
case err != nil:
// All other errors are from the datastore, consider them transient.
return nil, errors.Annotate(err, "transaction failed").Tag(transient.Tag).Err()
case updated == nil || updated.Fingerprint == "":
// This happens if there's no existing metadata and the callback didn't
// create it. Return nil to indicate that the metadata is still missing.
return nil, nil
}
return updated, nil
} | go | func (legacyStorageImpl) UpdateMetadata(c context.Context, prefix string, cb func(m *api.PrefixMetadata) error) (*api.PrefixMetadata, error) {
prefix, err := common.ValidatePackagePrefix(prefix)
if err != nil {
return nil, errors.Annotate(err, "bad prefix given to GetMetadata").Err()
}
if prefix == "" {
return nil, errors.Reason("the root metadata is not modifiable").Err()
}
var cbErr error // error from 'cb'
var updated *api.PrefixMetadata // updated metadata to return
err = datastore.RunInTransaction(c, func(c context.Context) error {
cbErr = nil // reset in case the transaction is being retried
updated = nil
// Fetch the existing metadata.
ents := prefixACLs(c, prefix, nil)
if err := datastore.Get(c, ents); isInternalDSError(err) {
return errors.Annotate(err, "datastore error when fetching PackageACL").Err()
}
// Convert it to PrefixMetadata object. This will be nil if there's no
// existing metadata, in which case we construct the default metadata
// with no fingerprint (to indicate it is new), see UpdateMetadata doc in
// Storage interface.
updated = mergeIntoPrefixMetadata(c, prefix, ents)
if updated == nil {
updated = &api.PrefixMetadata{Prefix: prefix}
}
// Let the callback update the metadata. Retain the old copy for diff later.
before := proto.Clone(updated).(*api.PrefixMetadata)
if cbErr = cb(updated); cbErr != nil {
return cbErr
}
// Don't let the callback mess with the prefix or the fingerprint.
updated.Prefix = before.Prefix
updated.Fingerprint = before.Fingerprint
if proto.Equal(before, updated) {
return nil // no changes whatsoever, don't touch anything
}
// Apply changes to the datastore. This updates 'ents' to match the metadata
// stored in 'updated'. We then rederive PrefixMetadata (including the new
// fingerprint) from them. We do it this way (instead of calculating the
// fingerprint using 'updated' directly), to be absolutely sure that the
// fingerprint returned by GetMetadata after this transaction lands matches
// the fingerprint we return from UpdateMetadata. In particular, the way
// we store ACLs in legacy entities doesn't preserve order of Acls entries
// in the proto, or order of principals inside Acls, so we need to
// "reformat" the updated metadata before calculating its fingerprint.
if err := applyACLDiff(c, ents, updated); err != nil {
return errors.Annotate(err, "failed to update PackageACL entities").Err()
}
updated = mergeIntoPrefixMetadata(c, prefix, ents)
return nil
}, &datastore.TransactionOptions{XG: true})
switch {
case cbErr != nil:
// The callback itself failed, need to return the error as is, as promised.
return nil, cbErr
case err != nil:
// All other errors are from the datastore, consider them transient.
return nil, errors.Annotate(err, "transaction failed").Tag(transient.Tag).Err()
case updated == nil || updated.Fingerprint == "":
// This happens if there's no existing metadata and the callback didn't
// create it. Return nil to indicate that the metadata is still missing.
return nil, nil
}
return updated, nil
} | [
"func",
"(",
"legacyStorageImpl",
")",
"UpdateMetadata",
"(",
"c",
"context",
".",
"Context",
",",
"prefix",
"string",
",",
"cb",
"func",
"(",
"m",
"*",
"api",
".",
"PrefixMetadata",
")",
"error",
")",
"(",
"*",
"api",
".",
"PrefixMetadata",
",",
"error"... | // UpdateMetadata is part of Storage interface.
//
// It assembles prefix metadata from a bunch of packageACL entities, passes it
// to the callback for modification, then deconstructs it back into a bunch of
// packageACL entities, to be saved in the datastore. All done transactionally. | [
"UpdateMetadata",
"is",
"part",
"of",
"Storage",
"interface",
".",
"It",
"assembles",
"prefix",
"metadata",
"from",
"a",
"bunch",
"of",
"packageACL",
"entities",
"passes",
"it",
"to",
"the",
"callback",
"for",
"modification",
"then",
"deconstructs",
"it",
"back"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L224-L297 |
8,254 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | parseKey | func (e *packageACL) parseKey() (role, prefix string, err error) {
chunks := strings.Split(e.ID, ":")
if len(chunks) != 2 {
return "", "", fmt.Errorf("invalid key %q, not <role>:<prefix> pair", e.ID)
}
role = chunks[0]
if _, ok := legacyRoleMap[role]; !ok {
return "", "", fmt.Errorf("unrecognized role in the key %q", e.ID)
}
prefix, err = common.ValidatePackagePrefix(chunks[1])
if err != nil || prefix == "" { // note: there's no ACLs for root in the datastore
return "", "", fmt.Errorf("invalid package prefix in the key %q", e.ID)
}
return
} | go | func (e *packageACL) parseKey() (role, prefix string, err error) {
chunks := strings.Split(e.ID, ":")
if len(chunks) != 2 {
return "", "", fmt.Errorf("invalid key %q, not <role>:<prefix> pair", e.ID)
}
role = chunks[0]
if _, ok := legacyRoleMap[role]; !ok {
return "", "", fmt.Errorf("unrecognized role in the key %q", e.ID)
}
prefix, err = common.ValidatePackagePrefix(chunks[1])
if err != nil || prefix == "" { // note: there's no ACLs for root in the datastore
return "", "", fmt.Errorf("invalid package prefix in the key %q", e.ID)
}
return
} | [
"func",
"(",
"e",
"*",
"packageACL",
")",
"parseKey",
"(",
")",
"(",
"role",
",",
"prefix",
"string",
",",
"err",
"error",
")",
"{",
"chunks",
":=",
"strings",
".",
"Split",
"(",
"e",
".",
"ID",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"ch... | // parseKey parses the entity key into its components, validating them.
//
// On success, role is one of legacyRoles and prefix is non-empty valid prefix. | [
"parseKey",
"parses",
"the",
"entity",
"key",
"into",
"its",
"components",
"validating",
"them",
".",
"On",
"success",
"role",
"is",
"one",
"of",
"legacyRoles",
"and",
"prefix",
"is",
"non",
"-",
"empty",
"valid",
"prefix",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L340-L354 |
8,255 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | isInternalDSError | func isInternalDSError(err error) bool {
if err == nil {
return false
}
merr, _ := err.(errors.MultiError)
if merr == nil {
return true // an overall RPC error
}
for _, e := range merr {
if e != nil && e != datastore.ErrNoSuchEntity {
return true // some serious issues with this single entity
}
}
return false // all suberrors are either nil or ErrNoSuchEntity
} | go | func isInternalDSError(err error) bool {
if err == nil {
return false
}
merr, _ := err.(errors.MultiError)
if merr == nil {
return true // an overall RPC error
}
for _, e := range merr {
if e != nil && e != datastore.ErrNoSuchEntity {
return true // some serious issues with this single entity
}
}
return false // all suberrors are either nil or ErrNoSuchEntity
} | [
"func",
"isInternalDSError",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"merr",
",",
"_",
":=",
"err",
".",
"(",
"errors",
".",
"MultiError",
")",
"\n",
"if",
"merr",
"==",
"nil",
"{"... | // isInternalDSError is true for datastore errors that aren't entirely
// ErrNoSuchEntity. | [
"isInternalDSError",
"is",
"true",
"for",
"datastore",
"errors",
"that",
"aren",
"t",
"entirely",
"ErrNoSuchEntity",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L358-L375 |
8,256 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | rootKey | func rootKey(c context.Context) *datastore.Key {
return datastore.NewKey(c, "PackageACLRoot", "acls", 0, nil)
} | go | func rootKey(c context.Context) *datastore.Key {
return datastore.NewKey(c, "PackageACLRoot", "acls", 0, nil)
} | [
"func",
"rootKey",
"(",
"c",
"context",
".",
"Context",
")",
"*",
"datastore",
".",
"Key",
"{",
"return",
"datastore",
".",
"NewKey",
"(",
"c",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"0",
",",
"nil",
")",
"\n",
"}"
] | // rootKey returns a key of the root entity that stores ACL hierarchy. | [
"rootKey",
"returns",
"a",
"key",
"of",
"the",
"root",
"entity",
"that",
"stores",
"ACL",
"hierarchy",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L385-L387 |
8,257 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | child | func (n *metadataNode) child(name string) *metadataNode {
if c, ok := n.children[name]; ok {
return c
}
n.assertNonFrozen()
if n.children == nil {
n.children = make(map[string]*metadataNode, 1)
}
c := &metadataNode{
parent: n,
acls: make([]*packageACL, len(legacyRoles)),
}
if n.prefix == "" {
c.prefix = name
} else {
c.prefix = n.prefix + "/" + name
}
n.children[name] = c
return c
} | go | func (n *metadataNode) child(name string) *metadataNode {
if c, ok := n.children[name]; ok {
return c
}
n.assertNonFrozen()
if n.children == nil {
n.children = make(map[string]*metadataNode, 1)
}
c := &metadataNode{
parent: n,
acls: make([]*packageACL, len(legacyRoles)),
}
if n.prefix == "" {
c.prefix = name
} else {
c.prefix = n.prefix + "/" + name
}
n.children[name] = c
return c
} | [
"func",
"(",
"n",
"*",
"metadataNode",
")",
"child",
"(",
"name",
"string",
")",
"*",
"metadataNode",
"{",
"if",
"c",
",",
"ok",
":=",
"n",
".",
"children",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"c",
"\n",
"}",
"\n",
"n",
".",
"assertNonFro... | // child returns a direct child node, creating it if necessary. | [
"child",
"returns",
"a",
"direct",
"child",
"node",
"creating",
"it",
"if",
"necessary",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L619-L638 |
8,258 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | attachACL | func (n *metadataNode) attachACL(role string, e *packageACL) {
n.assertNonFrozen()
// 'acls' are ordered by legacyRoles. Insert 'e' into the corresponding slot.
// Such ordering is required by mergeIntoPrefixMetadata used by 'freeze'.
for i, r := range legacyRoles {
if r == role {
if n.acls[i] != nil {
panic(fmt.Sprintf("metadata for role %q at %q is already attached", role, n.prefix))
}
n.acls[i] = e
return
}
}
// 'attachACL' is called only with roles validated by packageACL.parseKey(),
// so this is impossible.
panic(fmt.Sprintf("unexpected impossible role %q", role))
} | go | func (n *metadataNode) attachACL(role string, e *packageACL) {
n.assertNonFrozen()
// 'acls' are ordered by legacyRoles. Insert 'e' into the corresponding slot.
// Such ordering is required by mergeIntoPrefixMetadata used by 'freeze'.
for i, r := range legacyRoles {
if r == role {
if n.acls[i] != nil {
panic(fmt.Sprintf("metadata for role %q at %q is already attached", role, n.prefix))
}
n.acls[i] = e
return
}
}
// 'attachACL' is called only with roles validated by packageACL.parseKey(),
// so this is impossible.
panic(fmt.Sprintf("unexpected impossible role %q", role))
} | [
"func",
"(",
"n",
"*",
"metadataNode",
")",
"attachACL",
"(",
"role",
"string",
",",
"e",
"*",
"packageACL",
")",
"{",
"n",
".",
"assertNonFrozen",
"(",
")",
"\n\n",
"// 'acls' are ordered by legacyRoles. Insert 'e' into the corresponding slot.",
"// Such ordering is re... | // attachACL attaches a packageACL to this node.
//
// All such attached ACLs are merged into single PrefixMetadata in 'freeze'. | [
"attachACL",
"attaches",
"a",
"packageACL",
"to",
"this",
"node",
".",
"All",
"such",
"attached",
"ACLs",
"are",
"merged",
"into",
"single",
"PrefixMetadata",
"in",
"freeze",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L643-L661 |
8,259 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | freeze | func (n *metadataNode) freeze(c context.Context) {
n.assertNonFrozen()
// md may be already non-nil for the root, this is fine.
if n.md == nil {
n.md = mergeIntoPrefixMetadata(c, n.prefix, n.acls)
}
n.acls = nil // mark as frozen, release unnecessary memory
for _, child := range n.children {
child.freeze(c)
}
} | go | func (n *metadataNode) freeze(c context.Context) {
n.assertNonFrozen()
// md may be already non-nil for the root, this is fine.
if n.md == nil {
n.md = mergeIntoPrefixMetadata(c, n.prefix, n.acls)
}
n.acls = nil // mark as frozen, release unnecessary memory
for _, child := range n.children {
child.freeze(c)
}
} | [
"func",
"(",
"n",
"*",
"metadataNode",
")",
"freeze",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"n",
".",
"assertNonFrozen",
"(",
")",
"\n\n",
"// md may be already non-nil for the root, this is fine.",
"if",
"n",
".",
"md",
"==",
"nil",
"{",
"n",
".",
... | // freeze marks the node and its subtree as fully constructed, calculating their
// PrefixMetadata from attached ACLs.
//
// The context is used only for logging. | [
"freeze",
"marks",
"the",
"node",
"and",
"its",
"subtree",
"as",
"fully",
"constructed",
"calculating",
"their",
"PrefixMetadata",
"from",
"attached",
"ACLs",
".",
"The",
"context",
"is",
"used",
"only",
"for",
"logging",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L667-L679 |
8,260 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | metadata | func (n *metadataNode) metadata() (md []*api.PrefixMetadata) {
n.assertFrozen()
if n.parent != nil {
md = n.parent.metadata()
} else {
md = make([]*api.PrefixMetadata, 0, 32) // 32 is picked arbitrarily
}
if n.md != nil {
md = append(md, n.md)
}
return
} | go | func (n *metadataNode) metadata() (md []*api.PrefixMetadata) {
n.assertFrozen()
if n.parent != nil {
md = n.parent.metadata()
} else {
md = make([]*api.PrefixMetadata, 0, 32) // 32 is picked arbitrarily
}
if n.md != nil {
md = append(md, n.md)
}
return
} | [
"func",
"(",
"n",
"*",
"metadataNode",
")",
"metadata",
"(",
")",
"(",
"md",
"[",
"]",
"*",
"api",
".",
"PrefixMetadata",
")",
"{",
"n",
".",
"assertFrozen",
"(",
")",
"\n",
"if",
"n",
".",
"parent",
"!=",
"nil",
"{",
"md",
"=",
"n",
".",
"pare... | // metadata returns this node's and all inherited metadata.
//
// Root metadata first. The return value is never nil. If there's no metadata,
// returns non-nil empty slice. | [
"metadata",
"returns",
"this",
"node",
"s",
"and",
"all",
"inherited",
"metadata",
".",
"Root",
"metadata",
"first",
".",
"The",
"return",
"value",
"is",
"never",
"nil",
".",
"If",
"there",
"s",
"no",
"metadata",
"returns",
"non",
"-",
"nil",
"empty",
"s... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L685-L696 |
8,261 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | init | func (g *metadataGraph) init(root *api.PrefixMetadata) {
if root != nil && root.Prefix != "" {
panic("the root node metadata should have empty prefix")
}
g.root = &metadataNode{
acls: make([]*packageACL, len(legacyRoles)),
md: root,
}
} | go | func (g *metadataGraph) init(root *api.PrefixMetadata) {
if root != nil && root.Prefix != "" {
panic("the root node metadata should have empty prefix")
}
g.root = &metadataNode{
acls: make([]*packageACL, len(legacyRoles)),
md: root,
}
} | [
"func",
"(",
"g",
"*",
"metadataGraph",
")",
"init",
"(",
"root",
"*",
"api",
".",
"PrefixMetadata",
")",
"{",
"if",
"root",
"!=",
"nil",
"&&",
"root",
".",
"Prefix",
"!=",
"\"",
"\"",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"g",
"... | // init initializes the root node. | [
"init",
"initializes",
"the",
"root",
"node",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L745-L753 |
8,262 | luci/luci-go | cipd/appengine/impl/metadata/legacy.go | freeze | func (g *metadataGraph) freeze(c context.Context) {
g.root.freeze(c)
} | go | func (g *metadataGraph) freeze(c context.Context) {
g.root.freeze(c)
} | [
"func",
"(",
"g",
"*",
"metadataGraph",
")",
"freeze",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"g",
".",
"root",
".",
"freeze",
"(",
"c",
")",
"\n",
"}"
] | // freeze finalizes graph construction by calculating all PrefixMetadata items.
//
// The graph is not modifiable after this point, but it becomes traversable.
// The context is used only for logging. | [
"freeze",
"finalizes",
"graph",
"construction",
"by",
"calculating",
"all",
"PrefixMetadata",
"items",
".",
"The",
"graph",
"is",
"not",
"modifiable",
"after",
"this",
"point",
"but",
"it",
"becomes",
"traversable",
".",
"The",
"context",
"is",
"used",
"only",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/metadata/legacy.go#L790-L792 |
8,263 | luci/luci-go | server/portal/yesno.go | Set | func (yn *YesOrNo) Set(v string) error {
switch v {
case "yes":
*yn = true
case "no":
*yn = false
default:
return errors.New("expecting 'yes' or 'no'")
}
return nil
} | go | func (yn *YesOrNo) Set(v string) error {
switch v {
case "yes":
*yn = true
case "no":
*yn = false
default:
return errors.New("expecting 'yes' or 'no'")
}
return nil
} | [
"func",
"(",
"yn",
"*",
"YesOrNo",
")",
"Set",
"(",
"v",
"string",
")",
"error",
"{",
"switch",
"v",
"{",
"case",
"\"",
"\"",
":",
"*",
"yn",
"=",
"true",
"\n",
"case",
"\"",
"\"",
":",
"*",
"yn",
"=",
"false",
"\n",
"default",
":",
"return",
... | // Set changes the value of YesOrNo. | [
"Set",
"changes",
"the",
"value",
"of",
"YesOrNo",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/portal/yesno.go#L35-L45 |
8,264 | luci/luci-go | server/portal/yesno.go | YesOrNoField | func YesOrNoField(f Field) Field {
f.Type = FieldChoice
f.ChoiceVariants = []string{"yes", "no"}
f.Validator = func(v string) error {
var x YesOrNo
return x.Set(v)
}
return f
} | go | func YesOrNoField(f Field) Field {
f.Type = FieldChoice
f.ChoiceVariants = []string{"yes", "no"}
f.Validator = func(v string) error {
var x YesOrNo
return x.Set(v)
}
return f
} | [
"func",
"YesOrNoField",
"(",
"f",
"Field",
")",
"Field",
"{",
"f",
".",
"Type",
"=",
"FieldChoice",
"\n",
"f",
".",
"ChoiceVariants",
"=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"f",
".",
"Validator",
"=",
"func",
"(",
"... | // YesOrNoField modifies the field so that it corresponds to YesOrNo value.
//
// It sets 'Type', 'ChoiceVariants' and 'Validator' properties. | [
"YesOrNoField",
"modifies",
"the",
"field",
"so",
"that",
"it",
"corresponds",
"to",
"YesOrNo",
"value",
".",
"It",
"sets",
"Type",
"ChoiceVariants",
"and",
"Validator",
"properties",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/portal/yesno.go#L50-L58 |
8,265 | luci/luci-go | logdog/client/butlerlib/streamproto/properties.go | Validate | func (p *Properties) Validate() error {
if err := p.LogStreamDescriptor.Validate(false); err != nil {
return err
}
return nil
} | go | func (p *Properties) Validate() error {
if err := p.LogStreamDescriptor.Validate(false); err != nil {
return err
}
return nil
} | [
"func",
"(",
"p",
"*",
"Properties",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"p",
".",
"LogStreamDescriptor",
".",
"Validate",
"(",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"... | // Validate validates that the configured Properties are valid and sufficient to
// create a Butler stream.
//
// It skips stream Prefix validation and instead asserts that it is empty, as
// it should not be populated when Properties are defined. | [
"Validate",
"validates",
"that",
"the",
"configured",
"Properties",
"are",
"valid",
"and",
"sufficient",
"to",
"create",
"a",
"Butler",
"stream",
".",
"It",
"skips",
"stream",
"Prefix",
"validation",
"and",
"instead",
"asserts",
"that",
"it",
"is",
"empty",
"a... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamproto/properties.go#L57-L62 |
8,266 | luci/luci-go | logdog/client/butlerlib/streamproto/properties.go | Clone | func (p *Properties) Clone() *Properties {
clone := *p
clone.LogStreamDescriptor = proto.Clone(p.LogStreamDescriptor).(*logpb.LogStreamDescriptor)
return &clone
} | go | func (p *Properties) Clone() *Properties {
clone := *p
clone.LogStreamDescriptor = proto.Clone(p.LogStreamDescriptor).(*logpb.LogStreamDescriptor)
return &clone
} | [
"func",
"(",
"p",
"*",
"Properties",
")",
"Clone",
"(",
")",
"*",
"Properties",
"{",
"clone",
":=",
"*",
"p",
"\n",
"clone",
".",
"LogStreamDescriptor",
"=",
"proto",
".",
"Clone",
"(",
"p",
".",
"LogStreamDescriptor",
")",
".",
"(",
"*",
"logpb",
".... | // Clone returns a fully-independent clone of this Properties object. | [
"Clone",
"returns",
"a",
"fully",
"-",
"independent",
"clone",
"of",
"this",
"Properties",
"object",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamproto/properties.go#L65-L69 |
8,267 | luci/luci-go | logdog/client/butlerlib/streamproto/properties.go | Properties | func (f *Flags) Properties() *Properties {
contentType := types.ContentType(f.ContentType)
if contentType == "" {
contentType = f.Type.DefaultContentType()
}
p := &Properties{
LogStreamDescriptor: &logpb.LogStreamDescriptor{
Name: string(f.Name),
ContentType: string(contentType),
StreamType: logpb.StreamType(f.Type),
Timestamp: google.NewTimestamp(time.Time(f.Timestamp)),
BinaryFileExt: f.BinaryFileExtension,
Tags: f.Tags,
},
Tee: f.Tee,
Timeout: time.Duration(f.Timeout),
Deadline: time.Duration(f.Deadline),
}
return p
} | go | func (f *Flags) Properties() *Properties {
contentType := types.ContentType(f.ContentType)
if contentType == "" {
contentType = f.Type.DefaultContentType()
}
p := &Properties{
LogStreamDescriptor: &logpb.LogStreamDescriptor{
Name: string(f.Name),
ContentType: string(contentType),
StreamType: logpb.StreamType(f.Type),
Timestamp: google.NewTimestamp(time.Time(f.Timestamp)),
BinaryFileExt: f.BinaryFileExtension,
Tags: f.Tags,
},
Tee: f.Tee,
Timeout: time.Duration(f.Timeout),
Deadline: time.Duration(f.Deadline),
}
return p
} | [
"func",
"(",
"f",
"*",
"Flags",
")",
"Properties",
"(",
")",
"*",
"Properties",
"{",
"contentType",
":=",
"types",
".",
"ContentType",
"(",
"f",
".",
"ContentType",
")",
"\n",
"if",
"contentType",
"==",
"\"",
"\"",
"{",
"contentType",
"=",
"f",
".",
... | // Properties converts the Flags to a standard Properties structure.
//
// If the values are not valid, this conversion will return an error. | [
"Properties",
"converts",
"the",
"Flags",
"to",
"a",
"standard",
"Properties",
"structure",
".",
"If",
"the",
"values",
"are",
"not",
"valid",
"this",
"conversion",
"will",
"return",
"an",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamproto/properties.go#L90-L110 |
8,268 | luci/luci-go | luci_notify/notify/emailgen.go | GenerateEmail | func (b *bundle) GenerateEmail(templateName string, input *EmailTemplateInput) (subject, body string) {
var err error
if subject, body, err = b.executeUserTemplate(templateName, input); err != nil {
// Execution of the user-defined template failed.
// Fallback to the error template.
subject, body = b.executeErrorTemplate(templateName, input, err)
}
return
} | go | func (b *bundle) GenerateEmail(templateName string, input *EmailTemplateInput) (subject, body string) {
var err error
if subject, body, err = b.executeUserTemplate(templateName, input); err != nil {
// Execution of the user-defined template failed.
// Fallback to the error template.
subject, body = b.executeErrorTemplate(templateName, input, err)
}
return
} | [
"func",
"(",
"b",
"*",
"bundle",
")",
"GenerateEmail",
"(",
"templateName",
"string",
",",
"input",
"*",
"EmailTemplateInput",
")",
"(",
"subject",
",",
"body",
"string",
")",
"{",
"var",
"err",
"error",
"\n",
"if",
"subject",
",",
"body",
",",
"err",
... | // GenerateEmail generates an email using the named template. If the template
// fails, an error template is used, which includes error details and a link to
// the definition of the failed template. | [
"GenerateEmail",
"generates",
"an",
"email",
"using",
"the",
"named",
"template",
".",
"If",
"the",
"template",
"fails",
"an",
"error",
"template",
"is",
"used",
"which",
"includes",
"error",
"details",
"and",
"a",
"link",
"to",
"the",
"definition",
"of",
"t... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/emailgen.go#L113-L121 |
8,269 | luci/luci-go | luci_notify/notify/emailgen.go | executeUserTemplate | func (b *bundle) executeUserTemplate(templateName string, input *EmailTemplateInput) (subject, body string, err error) {
if b.err != nil {
err = b.err
return
}
var buf bytes.Buffer
if err = b.subjects.ExecuteTemplate(&buf, templateName, input); err != nil {
return
}
subject = buf.String()
buf.Reset()
if err = b.bodies.ExecuteTemplate(&buf, templateName, input); err != nil {
return
}
body = buf.String()
return
} | go | func (b *bundle) executeUserTemplate(templateName string, input *EmailTemplateInput) (subject, body string, err error) {
if b.err != nil {
err = b.err
return
}
var buf bytes.Buffer
if err = b.subjects.ExecuteTemplate(&buf, templateName, input); err != nil {
return
}
subject = buf.String()
buf.Reset()
if err = b.bodies.ExecuteTemplate(&buf, templateName, input); err != nil {
return
}
body = buf.String()
return
} | [
"func",
"(",
"b",
"*",
"bundle",
")",
"executeUserTemplate",
"(",
"templateName",
"string",
",",
"input",
"*",
"EmailTemplateInput",
")",
"(",
"subject",
",",
"body",
"string",
",",
"err",
"error",
")",
"{",
"if",
"b",
".",
"err",
"!=",
"nil",
"{",
"er... | // executeUserTemplate executed a user-defined template.
// If b.err is not nil, returns it right away. | [
"executeUserTemplate",
"executed",
"a",
"user",
"-",
"defined",
"template",
".",
"If",
"b",
".",
"err",
"is",
"not",
"nil",
"returns",
"it",
"right",
"away",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/emailgen.go#L125-L143 |
8,270 | luci/luci-go | luci_notify/notify/emailgen.go | executeErrorTemplate | func (b *bundle) executeErrorTemplate(templateName string, input *EmailTemplateInput, err error) (subject, body string) {
subject = fmt.Sprintf(`[Build Status] Builder %q`, protoutil.FormatBuilderID(input.Build.Builder))
errorTemplateInput := map[string]interface{}{
"Build": input.Build,
"TemplateName": templateName,
"TemplateURL": b.defURLs[templateName],
"Error": err.Error(),
}
var buf bytes.Buffer
if err := errorBodyTemplate.Execute(&buf, errorTemplateInput); err != nil {
// Error template MAY NOT fail.
panic(errors.Annotate(err, "execution of the error template has failed").Err())
}
body = buf.String()
return
} | go | func (b *bundle) executeErrorTemplate(templateName string, input *EmailTemplateInput, err error) (subject, body string) {
subject = fmt.Sprintf(`[Build Status] Builder %q`, protoutil.FormatBuilderID(input.Build.Builder))
errorTemplateInput := map[string]interface{}{
"Build": input.Build,
"TemplateName": templateName,
"TemplateURL": b.defURLs[templateName],
"Error": err.Error(),
}
var buf bytes.Buffer
if err := errorBodyTemplate.Execute(&buf, errorTemplateInput); err != nil {
// Error template MAY NOT fail.
panic(errors.Annotate(err, "execution of the error template has failed").Err())
}
body = buf.String()
return
} | [
"func",
"(",
"b",
"*",
"bundle",
")",
"executeErrorTemplate",
"(",
"templateName",
"string",
",",
"input",
"*",
"EmailTemplateInput",
",",
"err",
"error",
")",
"(",
"subject",
",",
"body",
"string",
")",
"{",
"subject",
"=",
"fmt",
".",
"Sprintf",
"(",
"... | // executeErrorTemplate generates a spartan email that contains information
// about an error during execution of a user-defined template. | [
"executeErrorTemplate",
"generates",
"a",
"spartan",
"email",
"that",
"contains",
"information",
"about",
"an",
"error",
"during",
"execution",
"of",
"a",
"user",
"-",
"defined",
"template",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/emailgen.go#L147-L163 |
8,271 | luci/luci-go | luci_notify/notify/emailgen.go | getBundle | func getBundle(c context.Context, projectId string) (*bundle, error) {
// Untie c from the current transaction.
// What we do here has nothing to do with a possible current transaction in c.
c = datastore.WithoutTransaction(c)
// Fetch current revision of the project config.
project := &config.Project{Name: projectId}
if err := datastore.Get(c, project); err != nil {
return nil, errors.Annotate(err, "failed to fetch project").Err()
}
// Lookup an exising bundle in the process cache.
// If not available, make one and cache it.
var transientErr error
value, ok := bundleCache.LRU(c).Mutate(c, projectId, func(it *lru.Item) *lru.Item {
if it != nil && it.Value.(*bundle).revision == project.Revision {
return it // Cache hit.
}
// Cache miss. Either no cached value or revision mismatch.
// Fetch all templates from the Datastore transactionally with the project.
// On a transient error, return it and do not purge cache.
var templates []*config.EmailTemplate
transientErr = datastore.RunInTransaction(c, func(c context.Context) error {
templates = templates[:0] // txn may be retried
if err := datastore.Get(c, project); err != nil {
return err
}
q := datastore.NewQuery("EmailTemplate").Ancestor(datastore.KeyForObj(c, project))
return datastore.GetAll(c, q, &templates)
}, nil)
if transientErr != nil {
return it
}
logging.Infof(c, "bundleCache: fetched %d email templates of project %q", len(templates), projectId)
// Legacy: add a default template if we don't have one.
// TODO(nodir): delete this once all projects define their templates.
hasDefault := false
for _, t := range templates {
if t.Name == defaultTemplate.Name {
hasDefault = true
break
}
}
if !hasDefault {
templates = append(templates, &defaultTemplate)
}
// Bundle all fetched templates. If bundling/parsing fails, cache the error,
// so we don't recompile bad templates over and over.
b := &bundle{
revision: project.Revision,
defURLs: make(map[string]string, len(templates)),
subjects: text.New("").Funcs(config.EmailTemplateFuncs),
bodies: html.New("").Funcs(config.EmailTemplateFuncs),
}
for _, t := range templates {
b.defURLs[t.Name] = t.DefinitionURL
// Parse templates.
// Do not stop the loop on failure because we want all defURLs.
if b.err == nil {
if _, b.err = b.subjects.New(t.Name).Parse(t.SubjectTextTemplate); b.err == nil {
_, b.err = b.bodies.New(t.Name).Parse(t.BodyHTMLTemplate)
}
}
}
// Cache without expiration.
return &lru.Item{Value: b}
})
switch {
case transientErr != nil:
return nil, transientErr
case !ok:
panic("impossible: no cached value and no error")
default:
return value.(*bundle), nil
}
} | go | func getBundle(c context.Context, projectId string) (*bundle, error) {
// Untie c from the current transaction.
// What we do here has nothing to do with a possible current transaction in c.
c = datastore.WithoutTransaction(c)
// Fetch current revision of the project config.
project := &config.Project{Name: projectId}
if err := datastore.Get(c, project); err != nil {
return nil, errors.Annotate(err, "failed to fetch project").Err()
}
// Lookup an exising bundle in the process cache.
// If not available, make one and cache it.
var transientErr error
value, ok := bundleCache.LRU(c).Mutate(c, projectId, func(it *lru.Item) *lru.Item {
if it != nil && it.Value.(*bundle).revision == project.Revision {
return it // Cache hit.
}
// Cache miss. Either no cached value or revision mismatch.
// Fetch all templates from the Datastore transactionally with the project.
// On a transient error, return it and do not purge cache.
var templates []*config.EmailTemplate
transientErr = datastore.RunInTransaction(c, func(c context.Context) error {
templates = templates[:0] // txn may be retried
if err := datastore.Get(c, project); err != nil {
return err
}
q := datastore.NewQuery("EmailTemplate").Ancestor(datastore.KeyForObj(c, project))
return datastore.GetAll(c, q, &templates)
}, nil)
if transientErr != nil {
return it
}
logging.Infof(c, "bundleCache: fetched %d email templates of project %q", len(templates), projectId)
// Legacy: add a default template if we don't have one.
// TODO(nodir): delete this once all projects define their templates.
hasDefault := false
for _, t := range templates {
if t.Name == defaultTemplate.Name {
hasDefault = true
break
}
}
if !hasDefault {
templates = append(templates, &defaultTemplate)
}
// Bundle all fetched templates. If bundling/parsing fails, cache the error,
// so we don't recompile bad templates over and over.
b := &bundle{
revision: project.Revision,
defURLs: make(map[string]string, len(templates)),
subjects: text.New("").Funcs(config.EmailTemplateFuncs),
bodies: html.New("").Funcs(config.EmailTemplateFuncs),
}
for _, t := range templates {
b.defURLs[t.Name] = t.DefinitionURL
// Parse templates.
// Do not stop the loop on failure because we want all defURLs.
if b.err == nil {
if _, b.err = b.subjects.New(t.Name).Parse(t.SubjectTextTemplate); b.err == nil {
_, b.err = b.bodies.New(t.Name).Parse(t.BodyHTMLTemplate)
}
}
}
// Cache without expiration.
return &lru.Item{Value: b}
})
switch {
case transientErr != nil:
return nil, transientErr
case !ok:
panic("impossible: no cached value and no error")
default:
return value.(*bundle), nil
}
} | [
"func",
"getBundle",
"(",
"c",
"context",
".",
"Context",
",",
"projectId",
"string",
")",
"(",
"*",
"bundle",
",",
"error",
")",
"{",
"// Untie c from the current transaction.",
"// What we do here has nothing to do with a possible current transaction in c.",
"c",
"=",
"... | // getBundle returns a bundle of all email templates for the given project.
// The returned bundle is cached in the process memory, do not modify it.
//
// Returns an error only on transient failures.
//
// Ignores an existing Datastore transaction in c, if any. | [
"getBundle",
"returns",
"a",
"bundle",
"of",
"all",
"email",
"templates",
"for",
"the",
"given",
"project",
".",
"The",
"returned",
"bundle",
"is",
"cached",
"in",
"the",
"process",
"memory",
"do",
"not",
"modify",
"it",
".",
"Returns",
"an",
"error",
"onl... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/emailgen.go#L174-L257 |
8,272 | luci/luci-go | scheduler/appengine/engine/cron/machine.go | Enable | func (m *Machine) Enable() {
if !m.State.Enabled {
m.State = State{
Enabled: true,
Generation: m.nextGen(),
LastRewind: m.Now,
}
m.scheduleTick(m.Now)
}
} | go | func (m *Machine) Enable() {
if !m.State.Enabled {
m.State = State{
Enabled: true,
Generation: m.nextGen(),
LastRewind: m.Now,
}
m.scheduleTick(m.Now)
}
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"Enable",
"(",
")",
"{",
"if",
"!",
"m",
".",
"State",
".",
"Enabled",
"{",
"m",
".",
"State",
"=",
"State",
"{",
"Enabled",
":",
"true",
",",
"Generation",
":",
"m",
".",
"nextGen",
"(",
")",
",",
"LastRe... | // Enable makes the cron machine start counting time.
//
// Does nothing if already enabled. | [
"Enable",
"makes",
"the",
"cron",
"machine",
"start",
"counting",
"time",
".",
"Does",
"nothing",
"if",
"already",
"enabled",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/cron/machine.go#L157-L166 |
8,273 | luci/luci-go | scheduler/appengine/engine/cron/machine.go | Disable | func (m *Machine) Disable() {
m.State = State{Enabled: false, Generation: m.nextGen()}
} | go | func (m *Machine) Disable() {
m.State = State{Enabled: false, Generation: m.nextGen()}
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"Disable",
"(",
")",
"{",
"m",
".",
"State",
"=",
"State",
"{",
"Enabled",
":",
"false",
",",
"Generation",
":",
"m",
".",
"nextGen",
"(",
")",
"}",
"\n",
"}"
] | // Disable stops any pending timer ticks, resets state.
//
// The cron machine will ignore any events until Enable is called to turn it on. | [
"Disable",
"stops",
"any",
"pending",
"timer",
"ticks",
"resets",
"state",
".",
"The",
"cron",
"machine",
"will",
"ignore",
"any",
"events",
"until",
"Enable",
"is",
"called",
"to",
"turn",
"it",
"on",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/cron/machine.go#L171-L173 |
8,274 | luci/luci-go | scheduler/appengine/engine/cron/machine.go | OnScheduleChange | func (m *Machine) OnScheduleChange() {
// Do not touch timers on disabled cron machines.
if !m.State.Enabled {
return
}
// The following condition is true for cron machines on a relative schedule
// that have already "fired", and currently wait for manual RewindIfNecessary
// call to start ticking again. When such cron machines switch to an absolute
// schedule, we need to rewind them right away (since machines on absolute
// schedules always tick!). If the new schedule is also relative, do nothing:
// RewindIfNecessary() should be called manually by the host at some later
// time (as usual for relative schedules).
if m.State.LastTick.When.IsZero() {
if m.Schedule.IsAbsolute() {
m.RewindIfNecessary()
}
} else {
// In this branch, the cron machine has a timer tick scheduled. It means it
// is either in a relative or absolute schedule, and this schedule may have
// changed, so we may need to move the tick to reflect the change. Note that
// we are not resetting LastRewind here, since we want the new schedule to
// take into account real last RewindIfNecessary call. For example, if the
// last rewind happened at moment X, current time is Now, and the new
// schedule is "with 10s interval", we want the tick to happen at "X+10",
// not "Now+10".
m.scheduleTick(m.Now)
}
} | go | func (m *Machine) OnScheduleChange() {
// Do not touch timers on disabled cron machines.
if !m.State.Enabled {
return
}
// The following condition is true for cron machines on a relative schedule
// that have already "fired", and currently wait for manual RewindIfNecessary
// call to start ticking again. When such cron machines switch to an absolute
// schedule, we need to rewind them right away (since machines on absolute
// schedules always tick!). If the new schedule is also relative, do nothing:
// RewindIfNecessary() should be called manually by the host at some later
// time (as usual for relative schedules).
if m.State.LastTick.When.IsZero() {
if m.Schedule.IsAbsolute() {
m.RewindIfNecessary()
}
} else {
// In this branch, the cron machine has a timer tick scheduled. It means it
// is either in a relative or absolute schedule, and this schedule may have
// changed, so we may need to move the tick to reflect the change. Note that
// we are not resetting LastRewind here, since we want the new schedule to
// take into account real last RewindIfNecessary call. For example, if the
// last rewind happened at moment X, current time is Now, and the new
// schedule is "with 10s interval", we want the tick to happen at "X+10",
// not "Now+10".
m.scheduleTick(m.Now)
}
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"OnScheduleChange",
"(",
")",
"{",
"// Do not touch timers on disabled cron machines.",
"if",
"!",
"m",
".",
"State",
".",
"Enabled",
"{",
"return",
"\n",
"}",
"\n\n",
"// The following condition is true for cron machines on a rela... | // OnScheduleChange happens when cron's schedule changes.
//
// In particular, it handles switches between absolute and relative schedules. | [
"OnScheduleChange",
"happens",
"when",
"cron",
"s",
"schedule",
"changes",
".",
"In",
"particular",
"it",
"handles",
"switches",
"between",
"absolute",
"and",
"relative",
"schedules",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/cron/machine.go#L186-L214 |
8,275 | luci/luci-go | scheduler/appengine/engine/cron/machine.go | scheduleTick | func (m *Machine) scheduleTick(now time.Time) {
nextTickTime := m.Schedule.Next(now, m.State.LastRewind)
if nextTickTime != m.State.LastTick.When {
m.State.Generation = m.nextGen()
m.State.LastTick = TickLaterAction{
When: nextTickTime,
TickNonce: m.Nonce(),
}
if nextTickTime != schedule.DistantFuture {
m.Actions = append(m.Actions, m.State.LastTick)
}
}
} | go | func (m *Machine) scheduleTick(now time.Time) {
nextTickTime := m.Schedule.Next(now, m.State.LastRewind)
if nextTickTime != m.State.LastTick.When {
m.State.Generation = m.nextGen()
m.State.LastTick = TickLaterAction{
When: nextTickTime,
TickNonce: m.Nonce(),
}
if nextTickTime != schedule.DistantFuture {
m.Actions = append(m.Actions, m.State.LastTick)
}
}
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"scheduleTick",
"(",
"now",
"time",
".",
"Time",
")",
"{",
"nextTickTime",
":=",
"m",
".",
"Schedule",
".",
"Next",
"(",
"now",
",",
"m",
".",
"State",
".",
"LastRewind",
")",
"\n",
"if",
"nextTickTime",
"!=",
... | // scheduleTick emits TickLaterAction action according to the schedule, current
// time, and last time RewindIfNecessary was called.
//
// Does nothing if such tick has already been scheduled. | [
"scheduleTick",
"emits",
"TickLaterAction",
"action",
"according",
"to",
"the",
"schedule",
"current",
"time",
"and",
"last",
"time",
"RewindIfNecessary",
"was",
"called",
".",
"Does",
"nothing",
"if",
"such",
"tick",
"has",
"already",
"been",
"scheduled",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/cron/machine.go#L267-L279 |
8,276 | luci/luci-go | scheduler/appengine/engine/cron/machine.go | rewindIfNecessary | func (m *Machine) rewindIfNecessary(now time.Time) {
if m.State.Enabled && m.State.LastTick.When.IsZero() {
m.State.LastRewind = now
m.State.Generation = m.nextGen()
m.scheduleTick(now)
}
} | go | func (m *Machine) rewindIfNecessary(now time.Time) {
if m.State.Enabled && m.State.LastTick.When.IsZero() {
m.State.LastRewind = now
m.State.Generation = m.nextGen()
m.scheduleTick(now)
}
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"rewindIfNecessary",
"(",
"now",
"time",
".",
"Time",
")",
"{",
"if",
"m",
".",
"State",
".",
"Enabled",
"&&",
"m",
".",
"State",
".",
"LastTick",
".",
"When",
".",
"IsZero",
"(",
")",
"{",
"m",
".",
"State"... | // rewindIfNecessary implements RewindIfNecessary, accepting corrected 'now'.
//
// This is important for OnTimerTick. Note that m.Now is part of inputs and must
// not be mutated. | [
"rewindIfNecessary",
"implements",
"RewindIfNecessary",
"accepting",
"corrected",
"now",
".",
"This",
"is",
"important",
"for",
"OnTimerTick",
".",
"Note",
"that",
"m",
".",
"Now",
"is",
"part",
"of",
"inputs",
"and",
"must",
"not",
"be",
"mutated",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/cron/machine.go#L292-L298 |
8,277 | luci/luci-go | tokenserver/appengine/impl/delegation/rpc_mint_delegation_token.go | buildRulesQuery | func buildRulesQuery(c context.Context, req *minter.MintDelegationTokenRequest, requestor identity.Identity) (*RulesQuery, error) {
// Validate 'delegated_identity'.
var err error
var delegator identity.Identity
if req.DelegatedIdentity == "" {
return nil, fmt.Errorf("'delegated_identity' is required")
}
if req.DelegatedIdentity == Requestor {
delegator = requestor // the requestor is delegating its own identity
} else {
if delegator, err = identity.MakeIdentity(req.DelegatedIdentity); err != nil {
return nil, fmt.Errorf("bad 'delegated_identity' - %s", err)
}
}
// Validate 'audience', convert it into a set.
if len(req.Audience) == 0 {
return nil, fmt.Errorf("'audience' is required")
}
audienceSet, err := identityset.FromStrings(req.Audience, skipRequestor)
if err != nil {
return nil, fmt.Errorf("bad 'audience' - %s", err)
}
if sliceHasString(req.Audience, Requestor) {
audienceSet.AddIdentity(requestor)
}
// Split 'services' into two lists: URLs and everything else (which is
// "service:..." and "*" presumably, validated below).
if len(req.Services) == 0 {
return nil, fmt.Errorf("'services' is required")
}
urls := make([]string, 0, len(req.Services))
rest := make([]string, 0, len(req.Services))
for _, srv := range req.Services {
if strings.HasPrefix(srv, "https://") {
urls = append(urls, srv)
} else {
rest = append(rest, srv)
}
}
// Convert the list into a set, verify it contains only services (or "*").
servicesSet, err := identityset.FromStrings(rest, nil)
if err != nil {
return nil, fmt.Errorf("bad 'services' - %s", err)
}
if len(servicesSet.Groups) != 0 {
return nil, fmt.Errorf("bad 'services' - can't specify groups")
}
for ident := range servicesSet.IDs {
if ident.Kind() != identity.Service {
return nil, fmt.Errorf("bad 'services' - %q is not a service ID", ident)
}
}
// Resolve URLs into app IDs. This may involve URL fetch calls (if the cache
// is cold), so skip this expensive call if already specifying the universal
// set of all services.
if !servicesSet.All && len(urls) != 0 {
if err = resolveServiceIDs(c, urls, servicesSet); err != nil {
return nil, err
}
}
// Done!
return &RulesQuery{
Requestor: requestor,
Delegator: delegator,
Audience: audienceSet,
Services: servicesSet,
}, nil
} | go | func buildRulesQuery(c context.Context, req *minter.MintDelegationTokenRequest, requestor identity.Identity) (*RulesQuery, error) {
// Validate 'delegated_identity'.
var err error
var delegator identity.Identity
if req.DelegatedIdentity == "" {
return nil, fmt.Errorf("'delegated_identity' is required")
}
if req.DelegatedIdentity == Requestor {
delegator = requestor // the requestor is delegating its own identity
} else {
if delegator, err = identity.MakeIdentity(req.DelegatedIdentity); err != nil {
return nil, fmt.Errorf("bad 'delegated_identity' - %s", err)
}
}
// Validate 'audience', convert it into a set.
if len(req.Audience) == 0 {
return nil, fmt.Errorf("'audience' is required")
}
audienceSet, err := identityset.FromStrings(req.Audience, skipRequestor)
if err != nil {
return nil, fmt.Errorf("bad 'audience' - %s", err)
}
if sliceHasString(req.Audience, Requestor) {
audienceSet.AddIdentity(requestor)
}
// Split 'services' into two lists: URLs and everything else (which is
// "service:..." and "*" presumably, validated below).
if len(req.Services) == 0 {
return nil, fmt.Errorf("'services' is required")
}
urls := make([]string, 0, len(req.Services))
rest := make([]string, 0, len(req.Services))
for _, srv := range req.Services {
if strings.HasPrefix(srv, "https://") {
urls = append(urls, srv)
} else {
rest = append(rest, srv)
}
}
// Convert the list into a set, verify it contains only services (or "*").
servicesSet, err := identityset.FromStrings(rest, nil)
if err != nil {
return nil, fmt.Errorf("bad 'services' - %s", err)
}
if len(servicesSet.Groups) != 0 {
return nil, fmt.Errorf("bad 'services' - can't specify groups")
}
for ident := range servicesSet.IDs {
if ident.Kind() != identity.Service {
return nil, fmt.Errorf("bad 'services' - %q is not a service ID", ident)
}
}
// Resolve URLs into app IDs. This may involve URL fetch calls (if the cache
// is cold), so skip this expensive call if already specifying the universal
// set of all services.
if !servicesSet.All && len(urls) != 0 {
if err = resolveServiceIDs(c, urls, servicesSet); err != nil {
return nil, err
}
}
// Done!
return &RulesQuery{
Requestor: requestor,
Delegator: delegator,
Audience: audienceSet,
Services: servicesSet,
}, nil
} | [
"func",
"buildRulesQuery",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"minter",
".",
"MintDelegationTokenRequest",
",",
"requestor",
"identity",
".",
"Identity",
")",
"(",
"*",
"RulesQuery",
",",
"error",
")",
"{",
"// Validate 'delegated_identity'.",
... | // buildRulesQuery validates the request, extracts and normalizes relevant
// fields into RulesQuery object.
//
// May return transient errors. | [
"buildRulesQuery",
"validates",
"the",
"request",
"extracts",
"and",
"normalizes",
"relevant",
"fields",
"into",
"RulesQuery",
"object",
".",
"May",
"return",
"transient",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/rpc_mint_delegation_token.go#L259-L331 |
8,278 | luci/luci-go | mmutex/cmd/mmutex/shared.go | RunShared | func RunShared(ctx context.Context, env subcommands.Env, command []string) error {
ctx, cancel := clock.WithTimeout(ctx, lib.DefaultCommandTimeout)
defer cancel()
return lib.RunShared(ctx, env, func(ctx context.Context) error {
return runCommand(ctx, command)
})
} | go | func RunShared(ctx context.Context, env subcommands.Env, command []string) error {
ctx, cancel := clock.WithTimeout(ctx, lib.DefaultCommandTimeout)
defer cancel()
return lib.RunShared(ctx, env, func(ctx context.Context) error {
return runCommand(ctx, command)
})
} | [
"func",
"RunShared",
"(",
"ctx",
"context",
".",
"Context",
",",
"env",
"subcommands",
".",
"Env",
",",
"command",
"[",
"]",
"string",
")",
"error",
"{",
"ctx",
",",
"cancel",
":=",
"clock",
".",
"WithTimeout",
"(",
"ctx",
",",
"lib",
".",
"DefaultComm... | // RunShared runs the command with the specified environment while holding a
// shared mmutex lock. | [
"RunShared",
"runs",
"the",
"command",
"with",
"the",
"specified",
"environment",
"while",
"holding",
"a",
"shared",
"mmutex",
"lock",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mmutex/cmd/mmutex/shared.go#L59-L66 |
8,279 | luci/luci-go | vpython/cipd/cipd.go | Resolve | func (pl *PackageLoader) Resolve(c context.Context, e *vpython.Environment) error {
spec := e.Spec
if spec == nil {
return nil
}
expander, err := pl.expanderForTags(c, e.Pep425Tag)
if err != nil {
return err
}
// Generate CIPD client options. If no root is provided, use a temporary root.
if pl.Options.Root != "" {
return pl.resolveWithOpts(c, pl.Options, expander, spec)
}
td := filesystem.TempDir{
Prefix: "vpython_cipd",
CleanupErrFunc: func(tdir string, err error) {
logging.WithError(err).Warningf(c, "Failed to clean up CIPD temporary directory [%s]", tdir)
},
}
return td.With(func(tdir string) error {
opts := pl.Options
opts.Root = tdir
return pl.resolveWithOpts(c, opts, expander, spec)
})
} | go | func (pl *PackageLoader) Resolve(c context.Context, e *vpython.Environment) error {
spec := e.Spec
if spec == nil {
return nil
}
expander, err := pl.expanderForTags(c, e.Pep425Tag)
if err != nil {
return err
}
// Generate CIPD client options. If no root is provided, use a temporary root.
if pl.Options.Root != "" {
return pl.resolveWithOpts(c, pl.Options, expander, spec)
}
td := filesystem.TempDir{
Prefix: "vpython_cipd",
CleanupErrFunc: func(tdir string, err error) {
logging.WithError(err).Warningf(c, "Failed to clean up CIPD temporary directory [%s]", tdir)
},
}
return td.With(func(tdir string) error {
opts := pl.Options
opts.Root = tdir
return pl.resolveWithOpts(c, opts, expander, spec)
})
} | [
"func",
"(",
"pl",
"*",
"PackageLoader",
")",
"Resolve",
"(",
"c",
"context",
".",
"Context",
",",
"e",
"*",
"vpython",
".",
"Environment",
")",
"error",
"{",
"spec",
":=",
"e",
".",
"Spec",
"\n",
"if",
"spec",
"==",
"nil",
"{",
"return",
"nil",
"\... | // Resolve implements venv.PackageLoader.
//
// The resulting packages slice will be updated in-place with the resolved
// package name and instance ID. | [
"Resolve",
"implements",
"venv",
".",
"PackageLoader",
".",
"The",
"resulting",
"packages",
"slice",
"will",
"be",
"updated",
"in",
"-",
"place",
"with",
"the",
"resolved",
"package",
"name",
"and",
"instance",
"ID",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/cipd/cipd.go#L62-L90 |
8,280 | luci/luci-go | vpython/cipd/cipd.go | resolveWithOpts | func (pl *PackageLoader) resolveWithOpts(c context.Context, opts cipd.ClientOptions,
expander template.Expander, spec *vpython.Spec) error {
logging.Debugf(c, "Resolving CIPD packages in root [%s]:", opts.Root)
ef, packages := specToEnsureFile(spec)
// Log our unresolved packages. Note that "specToEnsureFile" only creates
// a subdir entry for the root (""), so we don't need to deterministically
// iterate over the full map.
if logging.IsLogging(c, logging.Debug) {
for _, pkg := range ef.PackagesBySubdir[""] {
logging.Debugf(c, "\tUnresolved package: %s", pkg)
}
}
client, err := cipd.NewClient(opts)
if err != nil {
return errors.Annotate(err, "failed to generate CIPD client").Err()
}
// Start a CIPD client batch.
client.BeginBatch(c)
defer client.EndBatch(c)
// Resolve our ensure file.
resolver := cipd.Resolver{Client: client}
resolved, err := resolver.Resolve(c, ef, expander)
if err != nil {
return err
}
// Write the results to "packages". All of them should have been installed
// into the root subdir.
for i, pkg := range resolved.PackagesBySubdir[""] {
packages[i].Name = pkg.PackageName
packages[i].Version = pkg.InstanceID
}
return nil
} | go | func (pl *PackageLoader) resolveWithOpts(c context.Context, opts cipd.ClientOptions,
expander template.Expander, spec *vpython.Spec) error {
logging.Debugf(c, "Resolving CIPD packages in root [%s]:", opts.Root)
ef, packages := specToEnsureFile(spec)
// Log our unresolved packages. Note that "specToEnsureFile" only creates
// a subdir entry for the root (""), so we don't need to deterministically
// iterate over the full map.
if logging.IsLogging(c, logging.Debug) {
for _, pkg := range ef.PackagesBySubdir[""] {
logging.Debugf(c, "\tUnresolved package: %s", pkg)
}
}
client, err := cipd.NewClient(opts)
if err != nil {
return errors.Annotate(err, "failed to generate CIPD client").Err()
}
// Start a CIPD client batch.
client.BeginBatch(c)
defer client.EndBatch(c)
// Resolve our ensure file.
resolver := cipd.Resolver{Client: client}
resolved, err := resolver.Resolve(c, ef, expander)
if err != nil {
return err
}
// Write the results to "packages". All of them should have been installed
// into the root subdir.
for i, pkg := range resolved.PackagesBySubdir[""] {
packages[i].Name = pkg.PackageName
packages[i].Version = pkg.InstanceID
}
return nil
} | [
"func",
"(",
"pl",
"*",
"PackageLoader",
")",
"resolveWithOpts",
"(",
"c",
"context",
".",
"Context",
",",
"opts",
"cipd",
".",
"ClientOptions",
",",
"expander",
"template",
".",
"Expander",
",",
"spec",
"*",
"vpython",
".",
"Spec",
")",
"error",
"{",
"l... | // resolveWithOpts resolves the specified packages.
//
// The supplied spec is updated with the resolved packages. | [
"resolveWithOpts",
"resolves",
"the",
"specified",
"packages",
".",
"The",
"supplied",
"spec",
"is",
"updated",
"with",
"the",
"resolved",
"packages",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/cipd/cipd.go#L95-L133 |
8,281 | luci/luci-go | vpython/cipd/cipd.go | Verify | func (pl *PackageLoader) Verify(c context.Context, sp *vpython.Spec, tags []*vpython.PEP425Tag) error {
client, err := cipd.NewClient(pl.Options)
if err != nil {
return errors.Annotate(err, "failed to generate CIPD client").Err()
}
client.BeginBatch(c)
defer client.EndBatch(c)
resolver := cipd.Resolver{
Client: client,
VerifyPresence: true,
}
// Build an Ensure file for our specification under each tag and register it
// with our Resolver.
ensureFileErrors := 0
for _, tag := range tags {
tagSlice := []*vpython.PEP425Tag{tag}
tagSpec := sp.Clone()
if err := spec.NormalizeSpec(tagSpec, tagSlice); err != nil {
return errors.Annotate(err, "failed to normalize spec for %q", tag).Err()
}
// Convert our spec into an ensure file.
ef, _ := specToEnsureFile(tagSpec)
expander, err := pl.expanderForTags(c, tagSlice)
if err != nil {
ensureFileErrors++
logging.Errorf(c, "Failed to generate template expander for: %s", tag.TagString())
continue
}
if _, err := resolver.Resolve(c, ef, expander); err != nil {
ensureFileErrors++
ts := tag.TagString()
if merr, ok := err.(errors.MultiError); ok {
for _, err := range merr {
logging.Errorf(c, "For %s - %s", ts, err)
}
} else {
logging.Errorf(c, "For %s - %s", ts, err)
}
}
}
if ensureFileErrors > 0 {
logging.Errorf(c, "Spec could not be resolved for %d tag(s).", ensureFileErrors)
return errors.New("verification failed")
}
logging.Infof(c, "Successfully verified all packages.")
return nil
} | go | func (pl *PackageLoader) Verify(c context.Context, sp *vpython.Spec, tags []*vpython.PEP425Tag) error {
client, err := cipd.NewClient(pl.Options)
if err != nil {
return errors.Annotate(err, "failed to generate CIPD client").Err()
}
client.BeginBatch(c)
defer client.EndBatch(c)
resolver := cipd.Resolver{
Client: client,
VerifyPresence: true,
}
// Build an Ensure file for our specification under each tag and register it
// with our Resolver.
ensureFileErrors := 0
for _, tag := range tags {
tagSlice := []*vpython.PEP425Tag{tag}
tagSpec := sp.Clone()
if err := spec.NormalizeSpec(tagSpec, tagSlice); err != nil {
return errors.Annotate(err, "failed to normalize spec for %q", tag).Err()
}
// Convert our spec into an ensure file.
ef, _ := specToEnsureFile(tagSpec)
expander, err := pl.expanderForTags(c, tagSlice)
if err != nil {
ensureFileErrors++
logging.Errorf(c, "Failed to generate template expander for: %s", tag.TagString())
continue
}
if _, err := resolver.Resolve(c, ef, expander); err != nil {
ensureFileErrors++
ts := tag.TagString()
if merr, ok := err.(errors.MultiError); ok {
for _, err := range merr {
logging.Errorf(c, "For %s - %s", ts, err)
}
} else {
logging.Errorf(c, "For %s - %s", ts, err)
}
}
}
if ensureFileErrors > 0 {
logging.Errorf(c, "Spec could not be resolved for %d tag(s).", ensureFileErrors)
return errors.New("verification failed")
}
logging.Infof(c, "Successfully verified all packages.")
return nil
} | [
"func",
"(",
"pl",
"*",
"PackageLoader",
")",
"Verify",
"(",
"c",
"context",
".",
"Context",
",",
"sp",
"*",
"vpython",
".",
"Spec",
",",
"tags",
"[",
"]",
"*",
"vpython",
".",
"PEP425Tag",
")",
"error",
"{",
"client",
",",
"err",
":=",
"cipd",
"."... | // Verify implements venv.PackageLoader. | [
"Verify",
"implements",
"venv",
".",
"PackageLoader",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/cipd/cipd.go#L183-L238 |
8,282 | luci/luci-go | common/tsmon/callback.go | RegisterCallbackIn | func RegisterCallbackIn(ctx context.Context, f Callback) {
GetState(ctx).RegisterCallbacks(f)
} | go | func RegisterCallbackIn(ctx context.Context, f Callback) {
GetState(ctx).RegisterCallbacks(f)
} | [
"func",
"RegisterCallbackIn",
"(",
"ctx",
"context",
".",
"Context",
",",
"f",
"Callback",
")",
"{",
"GetState",
"(",
"ctx",
")",
".",
"RegisterCallbacks",
"(",
"f",
")",
"\n",
"}"
] | // RegisterCallbackIn is like RegisterCallback but registers in a given context. | [
"RegisterCallbackIn",
"is",
"like",
"RegisterCallback",
"but",
"registers",
"in",
"a",
"given",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/callback.go#L43-L45 |
8,283 | luci/luci-go | common/tsmon/callback.go | RegisterGlobalCallbackIn | func RegisterGlobalCallbackIn(ctx context.Context, f Callback, metrics ...types.Metric) {
if len(metrics) == 0 {
panic("RegisterGlobalCallback called without any metrics")
}
GetState(ctx).RegisterGlobalCallbacks(GlobalCallback{f, metrics})
} | go | func RegisterGlobalCallbackIn(ctx context.Context, f Callback, metrics ...types.Metric) {
if len(metrics) == 0 {
panic("RegisterGlobalCallback called without any metrics")
}
GetState(ctx).RegisterGlobalCallbacks(GlobalCallback{f, metrics})
} | [
"func",
"RegisterGlobalCallbackIn",
"(",
"ctx",
"context",
".",
"Context",
",",
"f",
"Callback",
",",
"metrics",
"...",
"types",
".",
"Metric",
")",
"{",
"if",
"len",
"(",
"metrics",
")",
"==",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\... | // RegisterGlobalCallbackIn is like RegisterGlobalCallback but registers in a
// given context. | [
"RegisterGlobalCallbackIn",
"is",
"like",
"RegisterGlobalCallback",
"but",
"registers",
"in",
"a",
"given",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/callback.go#L63-L69 |
8,284 | luci/luci-go | common/data/base128/base128.go | DecodeString | func DecodeString(s string) ([]byte, error) {
src := []byte(s)
dst := make([]byte, DecodedLen(len(src)))
if _, err := Decode(dst, src); err != nil {
return nil, err
}
return dst, nil
} | go | func DecodeString(s string) ([]byte, error) {
src := []byte(s)
dst := make([]byte, DecodedLen(len(src)))
if _, err := Decode(dst, src); err != nil {
return nil, err
}
return dst, nil
} | [
"func",
"DecodeString",
"(",
"s",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"src",
":=",
"[",
"]",
"byte",
"(",
"s",
")",
"\n",
"dst",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"DecodedLen",
"(",
"len",
"(",
"src",
")",
")... | // DecodeString returns the bytes represented by the base128 string s. | [
"DecodeString",
"returns",
"the",
"bytes",
"represented",
"by",
"the",
"base128",
"string",
"s",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/base128/base128.go#L94-L101 |
8,285 | luci/luci-go | logdog/client/annotee/stream.go | TextStreamFlags | func TextStreamFlags(ctx context.Context, name types.StreamName) streamproto.Flags {
return streamFlagsFromArchetype(ctx, name, &textStreamArchetype)
} | go | func TextStreamFlags(ctx context.Context, name types.StreamName) streamproto.Flags {
return streamFlagsFromArchetype(ctx, name, &textStreamArchetype)
} | [
"func",
"TextStreamFlags",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"types",
".",
"StreamName",
")",
"streamproto",
".",
"Flags",
"{",
"return",
"streamFlagsFromArchetype",
"(",
"ctx",
",",
"name",
",",
"&",
"textStreamArchetype",
")",
"\n",
"}"
] | // TextStreamFlags returns the streamproto.Flags for a text stream using
// Annotee's text stream archetype. | [
"TextStreamFlags",
"returns",
"the",
"streamproto",
".",
"Flags",
"for",
"a",
"text",
"stream",
"using",
"Annotee",
"s",
"text",
"stream",
"archetype",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/stream.go#L42-L44 |
8,286 | luci/luci-go | config/validation/net_util.go | ValidateHostname | func ValidateHostname(hostname string) error {
if len(hostname) > 255 {
return fmt.Errorf("length exceeds 255 bytes")
}
if !hostnameRegexp.MatchString(hostname) {
return fmt.Errorf("hostname does not match regex %q", hostnameRegexp)
}
for _, s := range strings.Split(hostname, ".") {
if len(s) > 63 {
return fmt.Errorf("segment %q exceeds 63 bytes", s)
}
}
return nil
} | go | func ValidateHostname(hostname string) error {
if len(hostname) > 255 {
return fmt.Errorf("length exceeds 255 bytes")
}
if !hostnameRegexp.MatchString(hostname) {
return fmt.Errorf("hostname does not match regex %q", hostnameRegexp)
}
for _, s := range strings.Split(hostname, ".") {
if len(s) > 63 {
return fmt.Errorf("segment %q exceeds 63 bytes", s)
}
}
return nil
} | [
"func",
"ValidateHostname",
"(",
"hostname",
"string",
")",
"error",
"{",
"if",
"len",
"(",
"hostname",
")",
">",
"255",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"hostnameRegexp",
".",
"MatchString",
"(",
... | // ValidateHostname returns an error if the given string is not a valid
// RFC1123 hostname. | [
"ValidateHostname",
"returns",
"an",
"error",
"if",
"the",
"given",
"string",
"is",
"not",
"a",
"valid",
"RFC1123",
"hostname",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/net_util.go#L33-L46 |
8,287 | luci/luci-go | machine-db/client/cli/oses.go | printOSes | func printOSes(tsv bool, oses ...*crimson.OS) {
if len(oses) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Description")
}
for _, os := range oses {
p.Row(os.Name, os.Description)
}
}
} | go | func printOSes(tsv bool, oses ...*crimson.OS) {
if len(oses) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Description")
}
for _, os := range oses {
p.Row(os.Name, os.Description)
}
}
} | [
"func",
"printOSes",
"(",
"tsv",
"bool",
",",
"oses",
"...",
"*",
"crimson",
".",
"OS",
")",
"{",
"if",
"len",
"(",
"oses",
")",
">",
"0",
"{",
"p",
":=",
"newStdoutPrinter",
"(",
"tsv",
")",
"\n",
"defer",
"p",
".",
"Flush",
"(",
")",
"\n",
"i... | // printOSes prints operating system data to stdout in tab-separated columns. | [
"printOSes",
"prints",
"operating",
"system",
"data",
"to",
"stdout",
"in",
"tab",
"-",
"separated",
"columns",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/oses.go#L28-L39 |
8,288 | luci/luci-go | machine-db/client/cli/oses.go | Run | func (c *GetOSesCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListOSes(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printOSes(c.f.tsv, resp.Oses...)
return 0
} | go | func (c *GetOSesCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListOSes(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printOSes(c.f.tsv, resp.Oses...)
return 0
} | [
"func",
"(",
"c",
"*",
"GetOSesCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"c",
",... | // Run runs the command to get operating systems. | [
"Run",
"runs",
"the",
"command",
"to",
"get",
"operating",
"systems",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/oses.go#L48-L58 |
8,289 | luci/luci-go | machine-db/client/cli/oses.go | getOSesCmd | func getOSesCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-oses [-name <name>]...",
ShortDesc: "retrieves operating systems",
LongDesc: "Retrieves operating systems matching the given names, or all operating systems if names are omitted.\n\nExample to get all OSes:\ncrimson get-oses\nExample to get Mac 10.13.3:\ncrimson get-oses -name 'Mac 10.13.3 (Darwin 17.4.0)'",
CommandRun: func() subcommands.CommandRun {
cmd := &GetOSesCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of an operating system to filter by. Can be specified multiple times.")
return cmd
},
}
} | go | func getOSesCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-oses [-name <name>]...",
ShortDesc: "retrieves operating systems",
LongDesc: "Retrieves operating systems matching the given names, or all operating systems if names are omitted.\n\nExample to get all OSes:\ncrimson get-oses\nExample to get Mac 10.13.3:\ncrimson get-oses -name 'Mac 10.13.3 (Darwin 17.4.0)'",
CommandRun: func() subcommands.CommandRun {
cmd := &GetOSesCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of an operating system to filter by. Can be specified multiple times.")
return cmd
},
}
} | [
"func",
"getOSesCmd",
"(",
"params",
"*",
"Parameters",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\\n",
... | // getOSesCmd returns a command to get operating systems. | [
"getOSesCmd",
"returns",
"a",
"command",
"to",
"get",
"operating",
"systems",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/oses.go#L61-L73 |
8,290 | luci/luci-go | logdog/appengine/coordinator/tagMap.go | tagMapFromProperties | func tagMapFromProperties(props ds.PropertySlice) (TagMap, error) {
tm := TagMap{}
lme := errors.NewLazyMultiError(len(props))
for idx, prop := range props {
v, ok := prop.Value().(string)
if !ok {
lme.Assign(idx, fmt.Errorf("property is not a string (%T)", prop.Value()))
continue
}
e, err := decodeKey(v)
if err != nil {
lme.Assign(idx, fmt.Errorf("failed to decode property (%q): %s", v, err))
continue
}
parts := strings.SplitN(e, "=", 2)
if len(parts) != 2 {
// This is a presence entry. Ignore.
continue
}
k, v := parts[0], parts[1]
if err := types.ValidateTag(k, v); err != nil {
lme.Assign(idx, fmt.Errorf("invalid tag %q: %s", parts[0], err))
continue
}
tm[k] = v
}
if len(tm) == 0 {
tm = nil
}
return tm, lme.Get()
} | go | func tagMapFromProperties(props ds.PropertySlice) (TagMap, error) {
tm := TagMap{}
lme := errors.NewLazyMultiError(len(props))
for idx, prop := range props {
v, ok := prop.Value().(string)
if !ok {
lme.Assign(idx, fmt.Errorf("property is not a string (%T)", prop.Value()))
continue
}
e, err := decodeKey(v)
if err != nil {
lme.Assign(idx, fmt.Errorf("failed to decode property (%q): %s", v, err))
continue
}
parts := strings.SplitN(e, "=", 2)
if len(parts) != 2 {
// This is a presence entry. Ignore.
continue
}
k, v := parts[0], parts[1]
if err := types.ValidateTag(k, v); err != nil {
lme.Assign(idx, fmt.Errorf("invalid tag %q: %s", parts[0], err))
continue
}
tm[k] = v
}
if len(tm) == 0 {
tm = nil
}
return tm, lme.Get()
} | [
"func",
"tagMapFromProperties",
"(",
"props",
"ds",
".",
"PropertySlice",
")",
"(",
"TagMap",
",",
"error",
")",
"{",
"tm",
":=",
"TagMap",
"{",
"}",
"\n",
"lme",
":=",
"errors",
".",
"NewLazyMultiError",
"(",
"len",
"(",
"props",
")",
")",
"\n",
"for"... | // tagMapFromProperties converts a set of tag property objects into a TagMap.
//
// If an error occurs decoding a specific property, an errors.MultiError will be
// returned alongside the successfully-decoded tags. | [
"tagMapFromProperties",
"converts",
"a",
"set",
"of",
"tag",
"property",
"objects",
"into",
"a",
"TagMap",
".",
"If",
"an",
"error",
"occurs",
"decoding",
"a",
"specific",
"property",
"an",
"errors",
".",
"MultiError",
"will",
"be",
"returned",
"alongside",
"t... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/tagMap.go#L37-L70 |
8,291 | luci/luci-go | logdog/appengine/coordinator/tagMap.go | toProperties | func (m TagMap) toProperties() (ds.PropertySlice, error) {
if len(m) == 0 {
return nil, nil
}
// Deterministic conversion.
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make(ds.PropertySlice, 0, len(m)*2)
for _, k := range keys {
v := m[k]
if err := types.ValidateTag(k, v); err != nil {
return nil, err
}
// Presence entry.
parts = append(parts, ds.MkProperty(encodeKey(k)))
// Value entry.
parts = append(parts, ds.MkProperty(encodeKey(fmt.Sprintf("%s=%s", k, v))))
}
return parts, nil
} | go | func (m TagMap) toProperties() (ds.PropertySlice, error) {
if len(m) == 0 {
return nil, nil
}
// Deterministic conversion.
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make(ds.PropertySlice, 0, len(m)*2)
for _, k := range keys {
v := m[k]
if err := types.ValidateTag(k, v); err != nil {
return nil, err
}
// Presence entry.
parts = append(parts, ds.MkProperty(encodeKey(k)))
// Value entry.
parts = append(parts, ds.MkProperty(encodeKey(fmt.Sprintf("%s=%s", k, v))))
}
return parts, nil
} | [
"func",
"(",
"m",
"TagMap",
")",
"toProperties",
"(",
")",
"(",
"ds",
".",
"PropertySlice",
",",
"error",
")",
"{",
"if",
"len",
"(",
"m",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"// Deterministic conversion.",
"keys",
":... | // toProperties converts a TagMap to a set of Property objects for storage. | [
"toProperties",
"converts",
"a",
"TagMap",
"to",
"a",
"set",
"of",
"Property",
"objects",
"for",
"storage",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/tagMap.go#L73-L99 |
8,292 | luci/luci-go | logdog/appengine/coordinator/tagMap.go | AddLogStreamTagFilter | func AddLogStreamTagFilter(q *ds.Query, key string, value string) *ds.Query {
if value == "" {
return q.Eq("_Tags", encodeKey(key))
}
return q.Eq("_Tags", encodeKey(fmt.Sprintf("%s=%s", key, value)))
} | go | func AddLogStreamTagFilter(q *ds.Query, key string, value string) *ds.Query {
if value == "" {
return q.Eq("_Tags", encodeKey(key))
}
return q.Eq("_Tags", encodeKey(fmt.Sprintf("%s=%s", key, value)))
} | [
"func",
"AddLogStreamTagFilter",
"(",
"q",
"*",
"ds",
".",
"Query",
",",
"key",
"string",
",",
"value",
"string",
")",
"*",
"ds",
".",
"Query",
"{",
"if",
"value",
"==",
"\"",
"\"",
"{",
"return",
"q",
".",
"Eq",
"(",
"\"",
"\"",
",",
"encodeKey",
... | // AddLogStreamTagFilter adds a tag filter to a Query object.
//
// This method will only add equality filters to the query. If value is empty,
// a presence filter will be added; otherwise, an equality filter will be added.
//
// This incorporates the encoding expressed by TagMap. | [
"AddLogStreamTagFilter",
"adds",
"a",
"tag",
"filter",
"to",
"a",
"Query",
"object",
".",
"This",
"method",
"will",
"only",
"add",
"equality",
"filters",
"to",
"the",
"query",
".",
"If",
"value",
"is",
"empty",
"a",
"presence",
"filter",
"will",
"be",
"add... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/tagMap.go#L107-L112 |
8,293 | luci/luci-go | config/server/cfgclient/backend/format/formatters.go | Register | func Register(rk string, f Formatter) {
if rk == "" {
panic("cannot register empty key")
}
registry.Lock()
defer registry.Unlock()
if _, ok := registry.r[rk]; ok {
panic(fmt.Errorf("key %q is already registered", rk))
}
if registry.r == nil {
registry.r = map[string]Formatter{}
}
registry.r[rk] = f
} | go | func Register(rk string, f Formatter) {
if rk == "" {
panic("cannot register empty key")
}
registry.Lock()
defer registry.Unlock()
if _, ok := registry.r[rk]; ok {
panic(fmt.Errorf("key %q is already registered", rk))
}
if registry.r == nil {
registry.r = map[string]Formatter{}
}
registry.r[rk] = f
} | [
"func",
"Register",
"(",
"rk",
"string",
",",
"f",
"Formatter",
")",
"{",
"if",
"rk",
"==",
"\"",
"\"",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"registry",
".",
"Lock",
"(",
")",
"\n",
"defer",
"registry",
".",
"Unlock",
"(",
")",
... | // Register registers a Formatter implementation for given format.
//
// If the supplied key is already registered, Register will panic. | [
"Register",
"registers",
"a",
"Formatter",
"implementation",
"for",
"given",
"format",
".",
"If",
"the",
"supplied",
"key",
"is",
"already",
"registered",
"Register",
"will",
"panic",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/format/formatters.go#L44-L59 |
8,294 | luci/luci-go | config/server/cfgclient/backend/format/formatters.go | getFormatter | func getFormatter(f string) (Formatter, error) {
registry.RLock()
defer registry.RUnlock()
formatter := registry.r[f]
if formatter == nil {
return nil, errors.Reason("unknown formatter: %q", f).Err()
}
return formatter, nil
} | go | func getFormatter(f string) (Formatter, error) {
registry.RLock()
defer registry.RUnlock()
formatter := registry.r[f]
if formatter == nil {
return nil, errors.Reason("unknown formatter: %q", f).Err()
}
return formatter, nil
} | [
"func",
"getFormatter",
"(",
"f",
"string",
")",
"(",
"Formatter",
",",
"error",
")",
"{",
"registry",
".",
"RLock",
"(",
")",
"\n",
"defer",
"registry",
".",
"RUnlock",
"(",
")",
"\n\n",
"formatter",
":=",
"registry",
".",
"r",
"[",
"f",
"]",
"\n",
... | // getFormatter returns the Formatter associated with the provided Format. | [
"getFormatter",
"returns",
"the",
"Formatter",
"associated",
"with",
"the",
"provided",
"Format",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/format/formatters.go#L71-L80 |
8,295 | luci/luci-go | auth/internal/common.go | EqualTokens | func EqualTokens(a, b *Token) bool {
if a == b {
return true
}
if a == nil {
a = &Token{}
}
if b == nil {
b = &Token{}
}
return a.AccessToken == b.AccessToken && a.Expiry.Equal(b.Expiry) && a.Email == b.Email
} | go | func EqualTokens(a, b *Token) bool {
if a == b {
return true
}
if a == nil {
a = &Token{}
}
if b == nil {
b = &Token{}
}
return a.AccessToken == b.AccessToken && a.Expiry.Equal(b.Expiry) && a.Email == b.Email
} | [
"func",
"EqualTokens",
"(",
"a",
",",
"b",
"*",
"Token",
")",
"bool",
"{",
"if",
"a",
"==",
"b",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"a",
"==",
"nil",
"{",
"a",
"=",
"&",
"Token",
"{",
"}",
"\n",
"}",
"\n",
"if",
"b",
"==",
"nil",... | // EqualTokens returns true if tokens are equal.
//
// 'nil' token corresponds to an empty access token. | [
"EqualTokens",
"returns",
"true",
"if",
"tokens",
"are",
"equal",
".",
"nil",
"token",
"corresponds",
"to",
"an",
"empty",
"access",
"token",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/internal/common.go#L251-L262 |
8,296 | luci/luci-go | auth/internal/common.go | isBadKeyError | func isBadKeyError(err error) bool {
if err == nil {
return false
}
// See https://go.googlesource.com/oauth2.git/+/197281d4/internal/oauth2.go#32
// Unfortunately, if uses fmt.Errorf.
s := err.Error()
return strings.Contains(s, "private key should be a PEM") ||
s == "private key is invalid"
} | go | func isBadKeyError(err error) bool {
if err == nil {
return false
}
// See https://go.googlesource.com/oauth2.git/+/197281d4/internal/oauth2.go#32
// Unfortunately, if uses fmt.Errorf.
s := err.Error()
return strings.Contains(s, "private key should be a PEM") ||
s == "private key is invalid"
} | [
"func",
"isBadKeyError",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// See https://go.googlesource.com/oauth2.git/+/197281d4/internal/oauth2.go#32",
"// Unfortunately, if uses fmt.Errorf.",
"s",
":=",
"err",
... | // isBadKeyError sniffs out errors related to malformed private keys. | [
"isBadKeyError",
"sniffs",
"out",
"errors",
"related",
"to",
"malformed",
"private",
"keys",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/internal/common.go#L273-L282 |
8,297 | luci/luci-go | lucictx/swarming.go | GetSwarming | func GetSwarming(ctx context.Context) *Swarming {
ret := Swarming{}
ok, err := Lookup(ctx, "swarming", &ret)
if err != nil {
panic(err)
}
if !ok {
return nil
}
return &ret
} | go | func GetSwarming(ctx context.Context) *Swarming {
ret := Swarming{}
ok, err := Lookup(ctx, "swarming", &ret)
if err != nil {
panic(err)
}
if !ok {
return nil
}
return &ret
} | [
"func",
"GetSwarming",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"Swarming",
"{",
"ret",
":=",
"Swarming",
"{",
"}",
"\n",
"ok",
",",
"err",
":=",
"Lookup",
"(",
"ctx",
",",
"\"",
"\"",
",",
"&",
"ret",
")",
"\n",
"if",
"err",
"!=",
"nil",... | // GetSwarming calls Lookup and returns the current Swarming from LUCI_CONTEXT
// if it was present. If no Swarming is in the context, this returns nil. | [
"GetSwarming",
"calls",
"Lookup",
"and",
"returns",
"the",
"current",
"Swarming",
"from",
"LUCI_CONTEXT",
"if",
"it",
"was",
"present",
".",
"If",
"no",
"Swarming",
"is",
"in",
"the",
"context",
"this",
"returns",
"nil",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucictx/swarming.go#L30-L40 |
8,298 | luci/luci-go | lucictx/swarming.go | SetSwarming | func SetSwarming(ctx context.Context, swarm *Swarming) context.Context {
var raw interface{}
if swarm != nil {
raw = swarm
}
ctx, err := Set(ctx, "swarming", raw)
if err != nil {
panic(fmt.Errorf("impossible: %s", err))
}
return ctx
} | go | func SetSwarming(ctx context.Context, swarm *Swarming) context.Context {
var raw interface{}
if swarm != nil {
raw = swarm
}
ctx, err := Set(ctx, "swarming", raw)
if err != nil {
panic(fmt.Errorf("impossible: %s", err))
}
return ctx
} | [
"func",
"SetSwarming",
"(",
"ctx",
"context",
".",
"Context",
",",
"swarm",
"*",
"Swarming",
")",
"context",
".",
"Context",
"{",
"var",
"raw",
"interface",
"{",
"}",
"\n",
"if",
"swarm",
"!=",
"nil",
"{",
"raw",
"=",
"swarm",
"\n",
"}",
"\n",
"ctx",... | // SetSwarming Sets the Swarming in the LUCI_CONTEXT. | [
"SetSwarming",
"Sets",
"the",
"Swarming",
"in",
"the",
"LUCI_CONTEXT",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucictx/swarming.go#L43-L53 |
8,299 | luci/luci-go | cipd/appengine/ui/cursors.go | cursorKey | func (k cursorKind) cursorKey(pkg, cursor string) string {
blob := sha256.Sum224([]byte(pkg + ":" + cursor))
return string(k) + ":" + base64.RawStdEncoding.EncodeToString(blob[:])
} | go | func (k cursorKind) cursorKey(pkg, cursor string) string {
blob := sha256.Sum224([]byte(pkg + ":" + cursor))
return string(k) + ":" + base64.RawStdEncoding.EncodeToString(blob[:])
} | [
"func",
"(",
"k",
"cursorKind",
")",
"cursorKey",
"(",
"pkg",
",",
"cursor",
"string",
")",
"string",
"{",
"blob",
":=",
"sha256",
".",
"Sum224",
"(",
"[",
"]",
"byte",
"(",
"pkg",
"+",
"\"",
"\"",
"+",
"cursor",
")",
")",
"\n",
"return",
"string",... | // cursorKey is a memcache key for items that link cursor to a previous page. | [
"cursorKey",
"is",
"a",
"memcache",
"key",
"for",
"items",
"that",
"link",
"cursor",
"to",
"a",
"previous",
"page",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/ui/cursors.go#L32-L35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.