mirror/merlin/sync/interface.go

69 lines
1.7 KiB
Go
Raw Normal View History

2021-12-11 18:28:09 -05:00
package sync
import (
"fmt"
"time"
"git.csclub.uwaterloo.ca/public/merlin/config"
)
2022-06-18 02:13:23 -04:00
// Start sync job for the repo if more than repo.Frequency seconds have elapsed since its last job
// and is not currently running. Returns true iff a job is started.
2022-06-27 23:36:51 -04:00
func SyncIfPossible(repo *config.Repo, force bool) bool {
2021-12-11 18:28:09 -05:00
if repo.State.IsRunning {
return false
}
curTime := time.Now().Unix()
2022-06-27 23:36:51 -04:00
if force || curTime-repo.State.LastAttemptStartTime > int64(repo.Frequency) {
2021-12-11 18:28:09 -05:00
repo.State.IsRunning = true
repo.State.LastAttemptStartTime = curTime
repo.SaveState()
repo.Logger.Info(fmt.Sprintf("Repo %s has started syncing", repo.Name))
2022-07-27 22:09:36 -04:00
go startRepoSync(repo, force)
2021-12-11 18:28:09 -05:00
return true
}
return false
}
2022-06-18 02:13:23 -04:00
// Called after a repo completes a sync. Update the repo's status using the current time and the exit code.
2021-12-11 18:28:09 -05:00
func SyncCompleted(repo *config.Repo, exit int) {
repoState := repo.State
2022-06-18 02:13:23 -04:00
2021-12-11 18:28:09 -05:00
syncTook := time.Now().Unix() - repoState.LastAttemptStartTime
2022-06-18 02:13:23 -04:00
nextSync := repo.Frequency - int(syncTook)
2021-12-11 18:28:09 -05:00
if nextSync < 0 {
nextSync = 0
}
repoState.IsRunning = false
repoState.LastAttemptExit = exit
repoState.LastAttemptRunTime = syncTook
2022-06-18 02:13:23 -04:00
repo.SaveState()
2021-12-11 18:28:09 -05:00
2022-07-27 22:09:36 -04:00
exitStr := config.StatusToString(exit)
2022-06-18 02:13:23 -04:00
repo.Logger.Info(fmt.Sprintf("Sync %s after running for %d seconds, will run again in %d seconds", exitStr, syncTook, nextSync))
2021-12-15 01:18:52 -05:00
2022-07-27 22:09:36 -04:00
go postRepoSync(repo, exit)
}
// begin and manage the steps of the sync and return the exit status
func startRepoSync(repo *config.Repo, force bool) {
2022-07-27 22:09:36 -04:00
status := config.FAILURE
done := false
defer func() {
repo.DoneChan <- config.SyncResult{
Name: repo.Name,
Exit: status,
}
}()
status, done = preRepoSync(repo)
if done && !force {
2022-07-27 22:09:36 -04:00
return
}
2022-07-27 22:09:36 -04:00
status = runRepoSync(repo)
2021-12-11 18:28:09 -05:00
}