Welcome to mirror list, hosted at ThFree Co, Russian Federation.

daily.go « maintenance « gitaly « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fdf3ced82a0424d0a501b4ccd0816bbf4dbb4e4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package maintenance

import (
	"context"
	"time"

	"gitlab.com/gitlab-org/gitaly/v16/internal/dontpanic"
	"gitlab.com/gitlab-org/gitaly/v16/internal/gitaly/config"
	"gitlab.com/gitlab-org/gitaly/v16/internal/log"
)

// StoragesJob runs a job on storages. The string slice param indicates which
// storages are currently enabled for the feature.
type StoragesJob func(context.Context, log.Logger, []string) error

// DailyWorker allows for a storage job to be executed on a daily schedule
type DailyWorker struct {
	// clock allows the time telling to be overridden deterministically in unit tests
	clock func() time.Time
	// timer allows the timing of tasks to be overridden deterministically in unit tests
	timer func(time.Duration) <-chan time.Time
}

// NewDailyWorker returns an initialized daily worker
func NewDailyWorker() DailyWorker {
	return DailyWorker{
		clock: time.Now,
		timer: time.After,
	}
}

func (dw DailyWorker) nextTime(hour, minute int) time.Time {
	n := dw.clock()
	next := time.Date(n.Year(), n.Month(), n.Day(), hour, minute, 0, 0, n.Location())
	if next.Equal(n) || next.Before(n) {
		next = next.AddDate(0, 0, 1)
	}
	return next
}

// StartDaily will run the provided job every day at the specified time for the
// specified duration. Only the specified storages wil be worked on.
func (dw DailyWorker) StartDaily(ctx context.Context, l log.Logger, schedule config.DailyJob, job StoragesJob) error {
	if schedule.Duration == 0 || len(schedule.Storages) == 0 || schedule.Disabled {
		return nil
	}

	for {
		nt := dw.nextTime(int(schedule.Hour), int(schedule.Minute))
		l.WithField("scheduled", nt).Info("maintenance: daily scheduled")

		var start time.Time

		select {
		case <-ctx.Done():
			return ctx.Err()
		case start = <-dw.timer(nt.Sub(dw.clock())):
			l.WithField("max_duration", schedule.Duration).
				Info("maintenance: daily starting")
		}

		var jobErr error
		dontpanic.Try(l, func() {
			ctx, cancel := context.WithTimeout(ctx, schedule.Duration.Duration())
			defer cancel()

			jobErr = job(ctx, l, schedule.Storages)
		})

		l.WithError(jobErr).
			WithField("max_duration", schedule.Duration).
			WithField("actual_duration", time.Since(start)).
			Info("maintenance: daily completed")
	}
}