-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
242 lines (206 loc) · 6.16 KB
/
config.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package main
import (
"context"
"errors"
"os"
"path"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/utilitywarehouse/git-mirror/pkg/giturl"
"github.com/utilitywarehouse/git-mirror/pkg/mirror"
"gopkg.in/yaml.v3"
)
const (
defaultGitGC = "always"
defaultInterval = 30 * time.Second
defaultMirrorTimeout = 2 * time.Minute
defaultSSHKeyPath = "/etc/git-secret/ssh"
defaultSSHKnownHostsPath = "/etc/git-secret/known_hosts"
)
var (
defaultRoot = path.Join(os.TempDir(), "git-mirror")
configSuccess = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "git_mirror_config_last_reload_successful",
Help: "Whether the last configuration reload attempt was successful.",
})
configSuccessTime = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "git_mirror_config_last_reload_success_timestamp_seconds",
Help: "Timestamp of the last successful configuration reload.",
})
)
// WatchConfig polls the config file every interval and reloads if modified
func WatchConfig(ctx context.Context, path string, watchConfig bool, interval time.Duration, onChange func(*mirror.RepoPoolConfig) bool) {
var lastModTime time.Time
var success bool
for {
lastModTime, success = loadConfig(path, lastModTime, onChange)
if success {
configSuccess.Set(1)
configSuccessTime.SetToCurrentTime()
} else {
configSuccess.Set(0)
}
if !watchConfig {
return
}
t := time.NewTimer(interval)
select {
case <-t.C:
case <-ctx.Done():
return
}
}
}
func loadConfig(path string, lastModTime time.Time, onChange func(*mirror.RepoPoolConfig) bool) (time.Time, bool) {
fileInfo, err := os.Stat(path)
if err != nil {
logger.Error("Error checking config file", "err", err)
return lastModTime, false
}
modTime := fileInfo.ModTime()
if modTime.Equal(lastModTime) {
return lastModTime, true
}
logger.Info("reloading config file...")
newConfig, err := parseConfigFile(path)
if err != nil {
logger.Error("failed to reload config", "err", err)
return lastModTime, false
}
return modTime, onChange(newConfig)
}
func ensureConfig(repoPool *mirror.RepoPool, newConfig *mirror.RepoPoolConfig) bool {
success := true
// add default values
applyGitDefaults(newConfig)
// validate and apply defaults to new config before compare
if err := newConfig.ValidateAndApplyDefaults(); err != nil {
logger.Error("failed to validate new config", "err", err)
return false
}
newRepos, removedRepos := diffRepositories(repoPool, newConfig)
for _, repo := range removedRepos {
if err := repoPool.RemoveRepository(repo); err != nil {
logger.Error("failed to remove repository", "remote", repo, "err", err)
success = false
}
}
for _, repo := range newRepos {
if err := repoPool.AddRepository(repo); err != nil {
logger.Error("failed to add new repository", "remote", repo.Remote, "err", err)
success = false
}
}
// find matched repos and check for worktree diffs
for _, newRepoConf := range newConfig.Repositories {
repo, err := repoPool.Repository(newRepoConf.Remote)
if err != nil {
logger.Error("unable to check worktree changes", "remote", newRepoConf.Remote, "err", err)
success = false
continue
}
newWTs, removedWTs := diffWorktrees(repo, &newRepoConf)
// 1st remove then add new in case new one has same link with diff reference
for _, wt := range removedWTs {
if err := repoPool.RemoveWorktreeLink(newRepoConf.Remote, wt); err != nil {
logger.Error("failed to remove worktree", "remote", newRepoConf.Remote, "link", wt, "err", err)
success = false
}
}
for _, wt := range newWTs {
if err := repoPool.AddWorktreeLink(newRepoConf.Remote, wt); err != nil {
logger.Error("failed to add worktree", "remote", newRepoConf.Remote, "link", wt.Link, "err", err)
success = false
}
}
}
// start mirror Loop on newly added repos
repoPool.StartLoop()
return success
}
func applyGitDefaults(mirrorConf *mirror.RepoPoolConfig) {
if mirrorConf.Defaults.Root == "" {
mirrorConf.Defaults.Root = defaultRoot
}
if mirrorConf.Defaults.GitGC == "" {
mirrorConf.Defaults.GitGC = defaultGitGC
}
if mirrorConf.Defaults.Interval == 0 {
mirrorConf.Defaults.Interval = defaultInterval
}
if mirrorConf.Defaults.MirrorTimeout == 0 {
mirrorConf.Defaults.MirrorTimeout = defaultMirrorTimeout
}
if mirrorConf.Defaults.Auth.SSHKeyPath == "" {
mirrorConf.Defaults.Auth.SSHKeyPath = defaultSSHKeyPath
}
if mirrorConf.Defaults.Auth.SSHKnownHostsPath == "" {
mirrorConf.Defaults.Auth.SSHKnownHostsPath = defaultSSHKnownHostsPath
}
}
func parseConfigFile(path string) (*mirror.RepoPoolConfig, error) {
yamlFile, err := os.ReadFile(path)
if err != nil {
return nil, err
}
conf := &mirror.RepoPoolConfig{}
err = yaml.Unmarshal(yamlFile, conf)
if err != nil {
return nil, err
}
return conf, nil
}
func diffRepositories(repoPool *mirror.RepoPool, newConfig *mirror.RepoPoolConfig) (
newRepos []mirror.RepositoryConfig,
removedRepos []string,
) {
for _, newRepo := range newConfig.Repositories {
if _, err := repoPool.Repository(newRepo.Remote); errors.Is(err, mirror.ErrNotExist) {
newRepos = append(newRepos, newRepo)
}
}
for _, currentRepoURL := range repoPool.RepositoriesRemote() {
var found bool
for _, newRepo := range newConfig.Repositories {
if currentRepoURL == giturl.NormaliseURL(newRepo.Remote) {
found = true
break
}
}
if !found {
removedRepos = append(removedRepos, currentRepoURL)
}
}
return
}
func diffWorktrees(repo *mirror.Repository, newRepoConf *mirror.RepositoryConfig) (
newWTCs []mirror.WorktreeConfig,
removedWTs []string,
) {
currentWTLinks := repo.WorktreeLinks()
for _, newWTC := range newRepoConf.Worktrees {
if _, ok := currentWTLinks[newWTC.Link]; !ok {
newWTCs = append(newWTCs, newWTC)
}
}
// for existing worktree
for cLink, wt := range currentWTLinks {
var found bool
for _, newWTC := range newRepoConf.Worktrees {
if newWTC.Link == cLink {
// wt link name is matching so make sure other
// config match as well if not replace it
if !wt.Equals(newWTC) {
newWTCs = append(newWTCs, newWTC)
break
}
found = true
break
}
}
if !found {
removedWTs = append(removedWTs, cLink)
}
}
return
}