Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
3a7e682
Move process to create contexts
zeripath Sep 18, 2021
47bda44
display children processes
zeripath Sep 18, 2021
cd16cbb
Make requests a process
zeripath Sep 18, 2021
12039b9
Add context to repo and add ctx to OpenRepository
zeripath Sep 18, 2021
d2b01e4
minor comments
zeripath Sep 22, 2021
659fcf6
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Sep 23, 2021
9598eca
fix lint and children lock
zeripath Sep 23, 2021
3344e26
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Oct 10, 2021
7cf7749
separate remove and cancel functions
zeripath Oct 10, 2021
a8e228e
associate repo functions with the repo context
zeripath Oct 10, 2021
08b77d1
fix lint
zeripath Oct 13, 2021
47b0614
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Oct 13, 2021
518b79e
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Oct 15, 2021
9bb820b
Simplify PID to strings using the time of start plus/minus a counter
zeripath Oct 15, 2021
9895680
extract process out of manager.go
zeripath Oct 15, 2021
afc5b41
fix test
zeripath Oct 15, 2021
7446c87
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Oct 15, 2021
86ab980
Merge branch 'main' into request-as-process
zeripath Oct 17, 2021
4ce4614
Make the Mirror Queue a queue (#17326)
zeripath Oct 17, 2021
633b041
make mirroring a process
zeripath Oct 17, 2021
377a384
Ensure that mirrors are al within the same context
zeripath Oct 17, 2021
32c58ee
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Oct 17, 2021
71dec99
add clarity to the difference between cancel and remove
zeripath Oct 19, 2021
9e95fdb
add explanatory notes for remove and close
zeripath Oct 19, 2021
3010f59
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Oct 19, 2021
9cc97d0
explicitly name the arguments in the blame reader
zeripath Oct 19, 2021
e4aebfb
Change remove to finished
zeripath Oct 20, 2021
217fbf7
update blame documentation
zeripath Oct 20, 2021
6b6ac80
as per review
zeripath Oct 20, 2021
0fcbc38
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Oct 27, 2021
e06216b
Close the cat-file batch and checks after the context cancellation
zeripath Oct 27, 2021
2062e43
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Oct 28, 2021
46c2b7a
Merge branch 'main' into request-as-process
zeripath Nov 1, 2021
37bfa14
Merge branch 'main' into request-as-process
zeripath Nov 5, 2021
ad2e278
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Nov 16, 2021
6062b04
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Nov 20, 2021
59dc919
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Nov 26, 2021
347e6a8
Merge branch 'main' into request-as-process
lafriks Nov 28, 2021
fd86412
Merge branch 'main' into request-as-process
lunny Nov 28, 2021
0d1ae72
Merge remote-tracking branch 'origin/main' into request-as-process
zeripath Nov 28, 2021
1d565bb
Merge branch 'main' into request-as-process
zeripath Nov 29, 2021
bbe69c8
Merge branch 'main' into request-as-process
zeripath Nov 30, 2021
1203fa9
Ensure that http requests use the same context as the request
zeripath Nov 30, 2021
772d31d
use the repo context in the diff
zeripath Nov 30, 2021
37f0716
improve code documentation
zeripath Nov 30, 2021
ec6b663
use the gitrepo context
zeripath Nov 30, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
separate remove and cancel functions
Signed-off-by: Andrew Thornton <[email protected]>
  • Loading branch information
zeripath committed Oct 10, 2021
commit 7cf774919169f70b0b2e9521b847752cc46ca2a7
4 changes: 2 additions & 2 deletions modules/cron/tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ func (t *Task) RunWithUser(doer *models.User, config Config) {
}()
graceful.GetManager().RunWithShutdownContext(func(baseCtx context.Context) {
pm := process.GetManager()
ctx, cancel := pm.AddContext(baseCtx, config.FormatMessage(t.Name, "process", doer))
defer cancel()
ctx, _, remove := pm.AddContext(baseCtx, config.FormatMessage(t.Name, "process", doer))
defer remove()

if err := t.fun(ctx, doer, config); err != nil {
if models.IsErrCancelled(err) {
Expand Down
12 changes: 8 additions & 4 deletions modules/git/blame.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type BlameReader struct {
reader *bufio.Reader
lastSha *string
cancel context.CancelFunc
remove context.CancelFunc
}

var shaLineRegex = regexp.MustCompile("^([a-z0-9]{40})")
Expand Down Expand Up @@ -99,7 +100,8 @@ func (r *BlameReader) NextPart() (*BlamePart, error) {

// Close BlameReader - don't run NextPart after invoking that
func (r *BlameReader) Close() error {
defer r.cancel()
defer r.remove()
r.cancel()

_ = r.output.Close()

Expand All @@ -123,20 +125,21 @@ func CreateBlameReader(ctx context.Context, repoPath, commitID, file string) (*B

func createBlameReader(ctx context.Context, dir string, command ...string) (*BlameReader, error) {
// Here we use the provided context - this should be tied to the request performing the blame so that it does not hang around.
ctx, cancel := process.GetManager().AddContext(ctx, fmt.Sprintf("GetBlame [repo_path: %s]", dir))
ctx, cancel, remove := process.GetManager().AddContext(ctx, fmt.Sprintf("GetBlame [repo_path: %s]", dir))

cmd := exec.CommandContext(ctx, command[0], command[1:]...)
cmd.Dir = dir
cmd.Stderr = os.Stderr

stdout, err := cmd.StdoutPipe()
if err != nil {
defer cancel()
defer remove()
return nil, fmt.Errorf("StdoutPipe: %v", err)
}

if err = cmd.Start(); err != nil {
defer cancel()
defer remove()
_ = stdout.Close()
return nil, fmt.Errorf("Start: %v", err)
}

Expand All @@ -148,5 +151,6 @@ func createBlameReader(ctx context.Context, dir string, command ...string) (*Bla
reader,
nil,
cancel,
remove,
}, nil
}
4 changes: 2 additions & 2 deletions modules/git/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,8 @@ func (c *Command) RunWithContext(rc *RunContext) error {
desc = fmt.Sprintf("%s %s [repo_path: %s]", c.name, strings.Join(c.args, " "), rc.Dir)
}

ctx, cancel := process.GetManager().AddContextTimeout(c.parentContext, rc.Timeout, desc)
defer cancel()
ctx, cancel, remove := process.GetManager().AddContextTimeout(c.parentContext, rc.Timeout, desc)
defer remove()

cmd := exec.CommandContext(ctx, c.name, c.args...)
if rc.Env == nil {
Expand Down
4 changes: 2 additions & 2 deletions modules/git/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ func GetRepoRawDiffForFile(repo *Repository, startCommit, endCommit string, diff
fileArgs = append(fileArgs, "--", file)
}
// FIXME: graceful: These commands should have a timeout
ctx, cancel := process.GetManager().AddContext(DefaultContext, fmt.Sprintf("GetRawDiffForFile: [repo_path: %s]", repo.Path))
defer cancel()
ctx, _, remove := process.GetManager().AddContext(DefaultContext, fmt.Sprintf("GetRawDiffForFile: [repo_path: %s]", repo.Path))
defer remove()

var cmd *exec.Cmd
switch diffType {
Expand Down
8 changes: 7 additions & 1 deletion modules/git/repo_language_stats_nogogit.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
IndexFile: indexFilename,
WorkTree: tmpWorkTree,
}
ctx, cancel := context.WithCancel(DefaultContext)
ctx, cancel := context.WithCancel(repo.Ctx)
if err := checker.Init(ctx); err != nil {
log.Error("Unable to open checker for %s. Error: %v", commitID, err)
} else {
Expand All @@ -104,6 +104,12 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
var content []byte
sizes := make(map[string]int64)
for _, f := range entries {
select {
case <-repo.Ctx.Done():
return sizes, repo.Ctx.Err()
default:
}

contentBuf.Reset()
content = contentBuf.Bytes()

Expand Down
9 changes: 8 additions & 1 deletion modules/indexer/stats/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@
package stats

import (
"fmt"

"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/process"
)

// DBIndexer implements Indexer interface to use database's like search
Expand All @@ -16,6 +20,9 @@ type DBIndexer struct {

// Index repository status function
func (db *DBIndexer) Index(id int64) error {
ctx, _, remove := process.GetManager().AddContext(graceful.GetManager().ShutdownContext(), fmt.Sprintf("Stats.DB Index Repo[%d]", id))
defer remove()

repo, err := models.GetRepositoryByID(id)
if err != nil {
return err
Expand All @@ -29,7 +36,7 @@ func (db *DBIndexer) Index(id int64) error {
return err
}

gitRepo, err := git.OpenRepository(repo.RepoPath())
gitRepo, err := git.OpenRepositoryCtx(ctx, repo.RepoPath())
if err != nil {
return err
}
Expand Down
4 changes: 2 additions & 2 deletions modules/markup/external/external.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ func (p *Renderer) Render(ctx *markup.RenderContext, input io.Reader, output io.
ctx.Ctx = graceful.GetManager().ShutdownContext()
}

processCtx, cancel := process.GetManager().AddContext(ctx.Ctx, fmt.Sprintf("Render [%s] for %s", commands[0], ctx.URLPrefix))
defer cancel()
processCtx, _, remove := process.GetManager().AddContext(ctx.Ctx, fmt.Sprintf("Render [%s] for %s", commands[0], ctx.URLPrefix))
defer remove()

cmd := exec.CommandContext(processCtx, commands[0], args...)
cmd.Env = append(
Expand Down
25 changes: 13 additions & 12 deletions modules/process/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,31 +78,31 @@ func GetManager() *Manager {
}

// AddContext create a new context and add it as a process. The CancelFunc must always be called even if the context is Done()
func (pm *Manager) AddContext(parent context.Context, description string) (context.Context, context.CancelFunc) {
func (pm *Manager) AddContext(parent context.Context, description string) (ctx context.Context, cancel, remove context.CancelFunc) {
parentPID := GetParentPID(parent)

ctx, cancel := context.WithCancel(parent)
ctx, cancel = context.WithCancel(parent)

pid, cancel := pm.Add(parentPID, description, cancel)
pid, remove := pm.Add(parentPID, description, cancel)

return &Context{
Context: ctx,
pid: pid,
}, cancel
}, cancel, remove
}

// AddContextTimeout create a new context and add it as a process
func (pm *Manager) AddContextTimeout(parent context.Context, timeout time.Duration, description string) (context.Context, context.CancelFunc) {
func (pm *Manager) AddContextTimeout(parent context.Context, timeout time.Duration, description string) (ctx context.Context, cancel, remove context.CancelFunc) {
parentPID := GetParentPID(parent)

ctx, cancel := context.WithTimeout(parent, timeout)
ctx, cancel = context.WithTimeout(parent, timeout)

pid, cancel := pm.Add(parentPID, description, cancel)
pid, remove := pm.Add(parentPID, description, cancel)

return &Context{
Context: ctx,
pid: pid,
}, cancel
}, cancel, remove
}

// Add create a new process
Expand All @@ -120,9 +120,10 @@ func (pm *Manager) Add(parentPID int64, description string, cancel context.Cance
ParentPID: parentPID,
Description: description,
Start: time.Now(),
Cancel: cancel,
}

process.Cancel = func() {
remove := func() {
cancel()
pm.remove(process)
}
Expand All @@ -133,7 +134,7 @@ func (pm *Manager) Add(parentPID int64, description string, cancel context.Cance
pm.processes[pid] = process
pm.mutex.Unlock()

return pid, process.Cancel
return pid, remove
}

// nextPID will return the next available PID. pm.mutex should already be locked.
Expand Down Expand Up @@ -264,8 +265,8 @@ func (pm *Manager) ExecDirEnvStdIn(timeout time.Duration, dir, desc string, env
stdOut := new(bytes.Buffer)
stdErr := new(bytes.Buffer)

ctx, cancel := pm.AddContextTimeout(DefaultContext, timeout, desc)
defer cancel()
ctx, _, remove := pm.AddContextTimeout(DefaultContext, timeout, desc)
defer remove()

cmd := exec.CommandContext(ctx, cmdName, args...)
cmd.Dir = dir
Expand Down
33 changes: 23 additions & 10 deletions modules/process/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ func TestManager_AddContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

p1Ctx, cancel := pm.AddContext(ctx, "foo")
defer cancel()
p1Ctx, _, remove := pm.AddContext(ctx, "foo")
defer remove()
assert.Equal(t, int64(1), GetContext(p1Ctx).GetPID(), "expected to get pid 1 got %d", GetContext(p1Ctx).GetPID())

p2Ctx, cancel := pm.AddContext(p1Ctx, "bar")
defer cancel()
p2Ctx, _, remove := pm.AddContext(p1Ctx, "bar")
defer remove()

assert.Equal(t, int64(2), GetContext(p2Ctx).GetPID(), "expected to get pid 2 got %d", GetContext(p2Ctx).GetPID())
assert.Equal(t, int64(1), GetContext(p2Ctx).GetParent().GetPID(), "expected to get pid 1 got %d", GetContext(p2Ctx).GetParent().GetPID())
Expand All @@ -41,8 +41,8 @@ func TestManager_AddContext(t *testing.T) {
func TestManager_Cancel(t *testing.T) {
pm := Manager{processes: make(map[int64]*Process), next: 1, low: 1}

ctx, cancel := pm.AddContext(context.Background(), "foo")
defer cancel()
ctx, _, remove := pm.AddContext(context.Background(), "foo")
defer remove()

pm.Cancel(GetPID(ctx))

Expand All @@ -51,6 +51,19 @@ func TestManager_Cancel(t *testing.T) {
default:
assert.Fail(t, "Cancel should cancel the provided context")
}
remove()

ctx, cancel, remove := pm.AddContext(context.Background(), "foo")
defer remove()

cancel()

select {
case <-ctx.Done():
default:
assert.Fail(t, "Cancel should cancel the provided context")
}
remove()
}

func TestManager_Remove(t *testing.T) {
Expand All @@ -59,12 +72,12 @@ func TestManager_Remove(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

p1Ctx, cancel := pm.AddContext(ctx, "foo")
defer cancel()
p1Ctx, _, remove := pm.AddContext(ctx, "foo")
defer remove()
assert.Equal(t, int64(1), GetContext(p1Ctx).GetPID(), "expected to get pid 1 got %d", GetContext(p1Ctx).GetPID())

p2Ctx, cancel := pm.AddContext(p1Ctx, "bar")
defer cancel()
p2Ctx, _, remove := pm.AddContext(p1Ctx, "bar")
defer remove()

assert.Equal(t, int64(2), GetContext(p2Ctx).GetPID(), "expected to get pid 2 got %d", GetContext(p2Ctx).GetPID())

Expand Down
4 changes: 2 additions & 2 deletions modules/task/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ func runMigrateTask(t *models.Task) (err error) {
opts.MigrateToRepoID = t.RepoID

pm := process.GetManager()
ctx, cancel := pm.AddContext(graceful.GetManager().ShutdownContext(), fmt.Sprintf("MigrateTask: %s/%s", t.Owner.Name, opts.RepoName))
defer cancel()
ctx, _, remove := pm.AddContext(graceful.GetManager().ShutdownContext(), fmt.Sprintf("MigrateTask: %s/%s", t.Owner.Name, opts.RepoName))
defer remove()

t.StartTime = timeutil.TimeStampNow()
t.Status = structs.TaskStatusRunning
Expand Down
4 changes: 2 additions & 2 deletions routers/common/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ func Middlewares() []func(http.Handler) http.Handler {
var handlers = []func(http.Handler) http.Handler{
func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
ctx, cancel := process.GetManager().AddContext(req.Context(), fmt.Sprintf("%s: %s", req.Method, req.RequestURI))
defer cancel()
ctx, _, remove := process.GetManager().AddContext(req.Context(), fmt.Sprintf("%s: %s", req.Method, req.RequestURI))
defer remove()
next.ServeHTTP(context.NewResponse(resp), req.WithContext(ctx))
})
},
Expand Down
4 changes: 2 additions & 2 deletions routers/web/repo/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -482,8 +482,8 @@ func serviceRPC(h serviceHandler, service string) {
}

// ctx, cancel := gocontext.WithCancel(git.DefaultContext)
ctx, cancel := process.GetManager().AddContext(git.DefaultContext, fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", h.dir))
defer cancel()
ctx, _, remove := process.GetManager().AddContext(git.DefaultContext, fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", h.dir))
defer remove()

var stderr bytes.Buffer
cmd := exec.CommandContext(ctx, git.GitExecutable, service, "--stateless-rpc", h.dir)
Expand Down
4 changes: 2 additions & 2 deletions services/gitdiff/gitdiff.go
Original file line number Diff line number Diff line change
Expand Up @@ -1226,8 +1226,8 @@ func GetDiffRangeWithWhitespaceBehavior(gitRepo *git.Repository, beforeCommitID,
}

timeout := time.Duration(setting.Git.Timeout.Default) * time.Second
ctx, cancel := process.GetManager().AddContextTimeout(git.DefaultContext, timeout, fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath))
defer cancel()
ctx, _, remove := process.GetManager().AddContextTimeout(git.DefaultContext, timeout, fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath))
defer remove()

var cmd *exec.Cmd
if (len(beforeCommitID) == 0 || beforeCommitID == git.EmptySHA) && commit.ParentCount() == 0 {
Expand Down
6 changes: 4 additions & 2 deletions services/mailer/mailer.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,8 @@ func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error {

desc := fmt.Sprintf("SendMail: %s %v", setting.MailService.SendmailPath, args)

ctx, cancel := process.GetManager().AddContextTimeout(graceful.GetManager().HammerContext(), setting.MailService.SendmailTimeout, desc)
defer cancel()
ctx, cancel, remove := process.GetManager().AddContextTimeout(graceful.GetManager().HammerContext(), setting.MailService.SendmailTimeout, desc)
defer remove()

cmd := exec.CommandContext(ctx, setting.MailService.SendmailPath, args...)
pipe, err := cmd.StdinPipe()
Expand All @@ -259,6 +259,8 @@ func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error {
}

if err = cmd.Start(); err != nil {
_ = pipe.Close()
cancel()
return err
}

Expand Down