Skip to content

Commit 9a2e47b

Browse files
zeripathlafrikslunnytechknowlogick
authored
Refactor Cron and merge dashboard tasks (#10745)
* Refactor Cron and merge dashboard tasks * Merge Cron and Dashboard tasks * Make every cron task report a system notice on completion * Refactor the creation of these tasks * Ensure that execution counts of tasks is correct * Allow cron tasks to be started from the cron page * golangci-lint fixes * Enforce that only one task with the same name can be registered Signed-off-by: Andrew Thornton <[email protected]> * fix name check Signed-off-by: Andrew Thornton <[email protected]> * as per @guillep2k * as per @lafriks Signed-off-by: Andrew Thornton <[email protected]> * Add git.CommandContext variants Signed-off-by: Andrew Thornton <[email protected]> Co-authored-by: Lauris BH <[email protected]> Co-authored-by: Lunny Xiao <[email protected]> Co-authored-by: techknowlogick <[email protected]>
1 parent c181440 commit 9a2e47b

File tree

25 files changed

+850
-452
lines changed

25 files changed

+850
-452
lines changed

integrations/auth_ldap_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ func TestLDAPUserSync(t *testing.T) {
151151
}
152152
defer prepareTestEnv(t)()
153153
addAuthSourceLDAP(t, "")
154-
models.SyncExternalUsers(context.Background())
154+
models.SyncExternalUsers(context.Background(), true)
155155

156156
session := loginUser(t, "user1")
157157
// Check if users exists
@@ -216,7 +216,7 @@ func TestLDAPUserSSHKeySync(t *testing.T) {
216216
defer prepareTestEnv(t)()
217217
addAuthSourceLDAP(t, "sshPublicKey")
218218

219-
models.SyncExternalUsers(context.Background())
219+
models.SyncExternalUsers(context.Background(), true)
220220

221221
// Check if users has SSH keys synced
222222
for _, u := range gitLDAPUsers {

models/admin.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ type NoticeType int
2020
const (
2121
//NoticeRepository type
2222
NoticeRepository NoticeType = iota + 1
23+
// NoticeTask type
24+
NoticeTask
2325
)
2426

2527
// Notice represents a system notice for admin.
@@ -36,11 +38,14 @@ func (n *Notice) TrStr() string {
3638
}
3739

3840
// CreateNotice creates new system notice.
39-
func CreateNotice(tp NoticeType, desc string) error {
40-
return createNotice(x, tp, desc)
41+
func CreateNotice(tp NoticeType, desc string, args ...interface{}) error {
42+
return createNotice(x, tp, desc, args...)
4143
}
4244

43-
func createNotice(e Engine, tp NoticeType, desc string) error {
45+
func createNotice(e Engine, tp NoticeType, desc string, args ...interface{}) error {
46+
if len(args) > 0 {
47+
desc = fmt.Sprintf(desc, args...)
48+
}
4449
n := &Notice{
4550
Type: tp,
4651
Description: desc,
@@ -50,8 +55,8 @@ func createNotice(e Engine, tp NoticeType, desc string) error {
5055
}
5156

5257
// CreateRepositoryNotice creates new system notice with type NoticeRepository.
53-
func CreateRepositoryNotice(desc string) error {
54-
return createNotice(x, NoticeRepository, desc)
58+
func CreateRepositoryNotice(desc string, args ...interface{}) error {
59+
return createNotice(x, NoticeRepository, desc, args...)
5560
}
5661

5762
// RemoveAllWithNotice removes all directories in given path and

models/branches.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import (
1212

1313
"code.gitea.io/gitea/modules/base"
1414
"code.gitea.io/gitea/modules/log"
15-
"code.gitea.io/gitea/modules/setting"
1615
"code.gitea.io/gitea/modules/timeutil"
1716
"code.gitea.io/gitea/modules/util"
1817

@@ -561,11 +560,11 @@ func RemoveDeletedBranch(repoID int64, branch string) error {
561560
}
562561

563562
// RemoveOldDeletedBranches removes old deleted branches
564-
func RemoveOldDeletedBranches(ctx context.Context) {
563+
func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
565564
// Nothing to do for shutdown or terminate
566565
log.Trace("Doing: DeletedBranchesCleanup")
567566

568-
deleteBefore := time.Now().Add(-setting.Cron.DeletedBranchesCleanup.OlderThan)
567+
deleteBefore := time.Now().Add(-olderThan)
569568
_, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
570569
if err != nil {
571570
log.Error("DeletedBranchesCleanup: %v", err)

models/error.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,28 @@ func (err ErrSSHDisabled) Error() string {
8585
return "SSH is disabled"
8686
}
8787

88+
// ErrCancelled represents an error due to context cancellation
89+
type ErrCancelled struct {
90+
Message string
91+
}
92+
93+
// IsErrCancelled checks if an error is a ErrCancelled.
94+
func IsErrCancelled(err error) bool {
95+
_, ok := err.(ErrCancelled)
96+
return ok
97+
}
98+
99+
func (err ErrCancelled) Error() string {
100+
return "Cancelled: " + err.Message
101+
}
102+
103+
// ErrCancelledf returns an ErrCancelled for the provided format and args
104+
func ErrCancelledf(format string, args ...interface{}) error {
105+
return ErrCancelled{
106+
fmt.Sprintf(format, args...),
107+
}
108+
}
109+
88110
// ____ ___
89111
// | | \______ ___________
90112
// | | / ___// __ \_ __ \

models/repo.go

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1853,35 +1853,44 @@ func GetPrivateRepositoryCount(u *User) (int64, error) {
18531853
}
18541854

18551855
// DeleteRepositoryArchives deletes all repositories' archives.
1856-
func DeleteRepositoryArchives() error {
1856+
func DeleteRepositoryArchives(ctx context.Context) error {
18571857
return x.
18581858
Where("id > 0").
18591859
Iterate(new(Repository),
18601860
func(idx int, bean interface{}) error {
18611861
repo := bean.(*Repository)
1862+
select {
1863+
case <-ctx.Done():
1864+
return ErrCancelledf("before deleting repository archives for %s", repo.FullName())
1865+
default:
1866+
}
18621867
return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
18631868
})
18641869
}
18651870

18661871
// DeleteOldRepositoryArchives deletes old repository archives.
1867-
func DeleteOldRepositoryArchives(ctx context.Context) {
1872+
func DeleteOldRepositoryArchives(ctx context.Context, olderThan time.Duration) error {
18681873
log.Trace("Doing: ArchiveCleanup")
18691874

18701875
if err := x.Where("id > 0").Iterate(new(Repository), func(idx int, bean interface{}) error {
1871-
return deleteOldRepositoryArchives(ctx, idx, bean)
1876+
return deleteOldRepositoryArchives(ctx, olderThan, idx, bean)
18721877
}); err != nil {
1873-
log.Error("ArchiveClean: %v", err)
1878+
log.Trace("Error: ArchiveClean: %v", err)
1879+
return err
18741880
}
1881+
1882+
log.Trace("Finished: ArchiveCleanup")
1883+
return nil
18751884
}
18761885

1877-
func deleteOldRepositoryArchives(ctx context.Context, idx int, bean interface{}) error {
1886+
func deleteOldRepositoryArchives(ctx context.Context, olderThan time.Duration, idx int, bean interface{}) error {
18781887
repo := bean.(*Repository)
18791888
basePath := filepath.Join(repo.RepoPath(), "archives")
18801889

18811890
for _, ty := range []string{"zip", "targz"} {
18821891
select {
18831892
case <-ctx.Done():
1884-
return fmt.Errorf("Aborted due to shutdown:\nin delete of old repository archives %v\nat delete file %s", repo, ty)
1893+
return ErrCancelledf("before deleting old repository archives with filetype %s for %s", ty, repo.FullName())
18851894
default:
18861895
}
18871896

@@ -1904,12 +1913,12 @@ func deleteOldRepositoryArchives(ctx context.Context, idx int, bean interface{})
19041913
return err
19051914
}
19061915

1907-
minimumOldestTime := time.Now().Add(-setting.Cron.ArchiveCleanup.OlderThan)
1916+
minimumOldestTime := time.Now().Add(-olderThan)
19081917
for _, info := range files {
19091918
if info.ModTime().Before(minimumOldestTime) && !info.IsDir() {
19101919
select {
19111920
case <-ctx.Done():
1912-
return fmt.Errorf("Aborted due to shutdown:\nin delete of old repository archives %v\nat delete file %s - %s", repo, ty, info.Name())
1921+
return ErrCancelledf("before deleting old repository archive file %s with filetype %s for %s", info.Name(), ty, repo.FullName())
19131922
default:
19141923
}
19151924
toDelete := filepath.Join(path, info.Name())
@@ -1936,13 +1945,13 @@ func repoStatsCheck(ctx context.Context, checker *repoChecker) {
19361945
return
19371946
}
19381947
for _, result := range results {
1948+
id := com.StrTo(result["id"]).MustInt64()
19391949
select {
19401950
case <-ctx.Done():
1941-
log.Warn("CheckRepoStats: Aborting due to shutdown")
1951+
log.Warn("CheckRepoStats: Cancelled before checking %s for Repo[%d]", checker.desc, id)
19421952
return
19431953
default:
19441954
}
1945-
id := com.StrTo(result["id"]).MustInt64()
19461955
log.Trace("Updating %s: %d", checker.desc, id)
19471956
_, err = x.Exec(checker.correctSQL, id, id)
19481957
if err != nil {
@@ -1952,7 +1961,7 @@ func repoStatsCheck(ctx context.Context, checker *repoChecker) {
19521961
}
19531962

19541963
// CheckRepoStats checks the repository stats
1955-
func CheckRepoStats(ctx context.Context) {
1964+
func CheckRepoStats(ctx context.Context) error {
19561965
log.Trace("Doing: CheckRepoStats")
19571966

19581967
checkers := []*repoChecker{
@@ -1987,13 +1996,13 @@ func CheckRepoStats(ctx context.Context) {
19871996
"issue count 'num_comments'",
19881997
},
19891998
}
1990-
for i := range checkers {
1999+
for _, checker := range checkers {
19912000
select {
19922001
case <-ctx.Done():
1993-
log.Warn("CheckRepoStats: Aborting due to shutdown")
1994-
return
2002+
log.Warn("CheckRepoStats: Cancelled before %s", checker.desc)
2003+
return ErrCancelledf("before checking %s", checker.desc)
19952004
default:
1996-
repoStatsCheck(ctx, checkers[i])
2005+
repoStatsCheck(ctx, checker)
19972006
}
19982007
}
19992008

@@ -2004,13 +2013,13 @@ func CheckRepoStats(ctx context.Context) {
20042013
log.Error("Select %s: %v", desc, err)
20052014
} else {
20062015
for _, result := range results {
2016+
id := com.StrTo(result["id"]).MustInt64()
20072017
select {
20082018
case <-ctx.Done():
2009-
log.Warn("CheckRepoStats: Aborting due to shutdown")
2010-
return
2019+
log.Warn("CheckRepoStats: Cancelled during %s for repo ID %d", desc, id)
2020+
return ErrCancelledf("during %s for repo ID %d", desc, id)
20112021
default:
20122022
}
2013-
id := com.StrTo(result["id"]).MustInt64()
20142023
log.Trace("Updating %s: %d", desc, id)
20152024
_, err = x.Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id)
20162025
if err != nil {
@@ -2027,13 +2036,13 @@ func CheckRepoStats(ctx context.Context) {
20272036
log.Error("Select %s: %v", desc, err)
20282037
} else {
20292038
for _, result := range results {
2039+
id := com.StrTo(result["id"]).MustInt64()
20302040
select {
20312041
case <-ctx.Done():
2032-
log.Warn("CheckRepoStats: Aborting due to shutdown")
2033-
return
2042+
log.Warn("CheckRepoStats: Cancelled")
2043+
return ErrCancelledf("during %s for repo ID %d", desc, id)
20342044
default:
20352045
}
2036-
id := com.StrTo(result["id"]).MustInt64()
20372046
log.Trace("Updating %s: %d", desc, id)
20382047
_, err = x.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, true, id)
20392048
if err != nil {
@@ -2050,13 +2059,13 @@ func CheckRepoStats(ctx context.Context) {
20502059
log.Error("Select repository count 'num_forks': %v", err)
20512060
} else {
20522061
for _, result := range results {
2062+
id := com.StrTo(result["id"]).MustInt64()
20532063
select {
20542064
case <-ctx.Done():
2055-
log.Warn("CheckRepoStats: Aborting due to shutdown")
2056-
return
2065+
log.Warn("CheckRepoStats: Cancelled")
2066+
return ErrCancelledf("during %s for repo ID %d", desc, id)
20572067
default:
20582068
}
2059-
id := com.StrTo(result["id"]).MustInt64()
20602069
log.Trace("Updating repository count 'num_forks': %d", id)
20612070

20622071
repo, err := GetRepositoryByID(id)
@@ -2079,6 +2088,7 @@ func CheckRepoStats(ctx context.Context) {
20792088
}
20802089
}
20812090
// ***** END: Repository.NumForks *****
2091+
return nil
20822092
}
20832093

20842094
// SetArchiveRepoState sets if a repo is archived
@@ -2189,12 +2199,17 @@ func (repo *Repository) generateRandomAvatar(e Engine) error {
21892199
}
21902200

21912201
// RemoveRandomAvatars removes the randomly generated avatars that were created for repositories
2192-
func RemoveRandomAvatars() error {
2202+
func RemoveRandomAvatars(ctx context.Context) error {
21932203
return x.
21942204
Where("id > 0").BufferSize(setting.Database.IterateBufferSize).
21952205
Iterate(new(Repository),
21962206
func(idx int, bean interface{}) error {
21972207
repository := bean.(*Repository)
2208+
select {
2209+
case <-ctx.Done():
2210+
return ErrCancelledf("before random avatars removed for %s", repository.FullName())
2211+
default:
2212+
}
21982213
stringifiedID := strconv.FormatInt(repository.ID, 10)
21992214
if repository.Avatar == stringifiedID {
22002215
return repository.DeleteAvatar()

0 commit comments

Comments
 (0)