-
Notifications
You must be signed in to change notification settings - Fork 6
/
check.go
378 lines (300 loc) · 11.1 KB
/
check.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package events
import (
"context"
"fmt"
"reflect"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"github.com/zapier/kubechecks/pkg"
"github.com/zapier/kubechecks/pkg/affected_apps"
"github.com/zapier/kubechecks/pkg/checks"
"github.com/zapier/kubechecks/pkg/container"
"github.com/zapier/kubechecks/pkg/git"
"github.com/zapier/kubechecks/pkg/msg"
"github.com/zapier/kubechecks/pkg/repo_config"
"github.com/zapier/kubechecks/pkg/vcs"
"github.com/zapier/kubechecks/telemetry"
)
var tracer = otel.Tracer("pkg/events")
type CheckEvent struct {
fileList []string // What files have changed in this PR/MR
pullRequest vcs.PullRequest
logger zerolog.Logger
vcsNote *msg.Message
affectedItems affected_apps.AffectedItems
ctr container.Container
repoManager repoManager
processors []checks.ProcessorEntry
repoLock sync.Mutex
clonedRepos map[string]*git.Repo
addedAppsSet map[string]v1alpha1.Application
addedAppsSetLock sync.Mutex
appsSent int32
appChannel chan *v1alpha1.Application
wg sync.WaitGroup
}
type repoManager interface {
Clone(ctx context.Context, cloneURL, branchName string) (*git.Repo, error)
}
func NewCheckEvent(pullRequest vcs.PullRequest, ctr container.Container, repoManager repoManager, processors []checks.ProcessorEntry) *CheckEvent {
ce := &CheckEvent{
addedAppsSet: make(map[string]v1alpha1.Application),
appChannel: make(chan *v1alpha1.Application, ctr.Config.MaxQueueSize),
ctr: ctr,
clonedRepos: make(map[string]*git.Repo),
processors: processors,
pullRequest: pullRequest,
repoManager: repoManager,
logger: log.Logger.With().
Str("repo", pullRequest.Name).
Int("event_id", pullRequest.CheckID).
Logger(),
}
return ce
}
func (ce *CheckEvent) UpdateListOfChangedFiles(ctx context.Context, repo *git.Repo) error {
ctx, span := tracer.Start(ctx, "CheckEventGetListOfChangedFiles")
defer span.End()
files, err := repo.GetListOfChangedFiles(ctx)
if err != nil {
return err
}
ce.logger.Debug().Msgf("Changed files: %s", strings.Join(files, ","))
ce.fileList = files
return nil
}
// GenerateListOfAffectedApps walks the repo to find any apps or appsets impacted by the changes in the MR/PR.
func (ce *CheckEvent) GenerateListOfAffectedApps(ctx context.Context, repo *git.Repo, targetBranch string) error {
_, span := tracer.Start(ctx, "GenerateListOfAffectedApps")
defer span.End()
var err error
var matcher affected_apps.Matcher
log.Debug().Msg("using an argocd matcher")
matcher, err = affected_apps.NewArgocdMatcher(ce.ctr.VcsToArgoMap, repo)
if err != nil {
return errors.Wrap(err, "failed to create argocd matcher")
}
cfg, err := repo_config.LoadRepoConfig(repo.Directory)
if err != nil {
return errors.Wrap(err, "failed to load repo config")
} else if cfg != nil {
log.Debug().Msg("using the config matcher")
configMatcher := affected_apps.NewConfigMatcher(cfg, ce.ctr)
matcher = affected_apps.NewMultiMatcher(matcher, configMatcher)
}
ce.affectedItems, err = matcher.AffectedApps(ctx, ce.fileList, targetBranch)
if err != nil {
telemetry.SetError(span, err, "Get Affected Apps")
ce.logger.Error().Err(err).Msg("could not get list of affected apps and appsets")
}
span.SetAttributes(
attribute.Int("numAffectedApps", len(ce.affectedItems.Applications)),
attribute.Int("numAffectedAppSets", len(ce.affectedItems.ApplicationSets)),
attribute.String("affectedApps", fmt.Sprintf("%+v", ce.affectedItems.Applications)),
attribute.String("affectedAppSets", fmt.Sprintf("%+v", ce.affectedItems.ApplicationSets)),
)
ce.logger.Debug().Msgf("Affected apps: %+v", ce.affectedItems.Applications)
ce.logger.Debug().Msgf("Affected appSets: %+v", ce.affectedItems.ApplicationSets)
return err
}
func canonicalize(cloneURL string) (pkg.RepoURL, error) {
parsed, _, err := pkg.NormalizeRepoUrl(cloneURL)
if err != nil {
return pkg.RepoURL{}, errors.Wrap(err, "failed to parse clone url")
}
return parsed, nil
}
func generateRepoKey(cloneURL pkg.RepoURL, branchName string) string {
return fmt.Sprintf("%s|||%s", cloneURL.CloneURL(""), branchName)
}
type hasUsername interface {
Username() string
}
func (ce *CheckEvent) getRepo(ctx context.Context, vcsClient hasUsername, cloneURL, branchName string) (*git.Repo, error) {
var (
err error
repo *git.Repo
)
ce.repoLock.Lock()
defer ce.repoLock.Unlock()
parsed, err := canonicalize(cloneURL)
if err != nil {
return nil, errors.Wrap(err, "failed to parse clone url")
}
cloneURL = parsed.CloneURL(vcsClient.Username())
branchName = strings.TrimSpace(branchName)
if branchName == "" {
branchName = "HEAD"
}
reposKey := generateRepoKey(parsed, branchName)
if repo, ok := ce.clonedRepos[reposKey]; ok {
return repo, nil
}
repo, err = ce.repoManager.Clone(ctx, cloneURL, branchName)
if err != nil {
return nil, errors.Wrap(err, "failed to clone repo")
}
ce.clonedRepos[reposKey] = repo
// if we cloned 'HEAD', figure out its original branch and store a copy of the repo there
if branchName == "" || branchName == "HEAD" {
remoteHeadBranchName, err := repo.GetRemoteHead()
if err != nil {
return repo, errors.Wrap(err, "failed to determine remote head")
}
repo.BranchName = remoteHeadBranchName
ce.clonedRepos[generateRepoKey(parsed, remoteHeadBranchName)] = repo
}
// if we don't have a 'HEAD' saved for the cloned repo, figure out which branch HEAD points to,
// and if it's the one we just cloned, store a copy of it as 'HEAD' for usage later
headKey := generateRepoKey(parsed, "HEAD")
if _, ok := ce.clonedRepos[headKey]; !ok {
remoteHeadBranchName, err := repo.GetRemoteHead()
if err != nil {
return repo, errors.Wrap(err, "failed to determine remote head")
}
if remoteHeadBranchName == repo.BranchName {
ce.clonedRepos[headKey] = repo
}
}
return repo, nil
}
func (ce *CheckEvent) Process(ctx context.Context) error {
start := time.Now()
_, span := tracer.Start(ctx, "GenerateListOfAffectedApps")
defer span.End()
// Clone the repo's BaseRef (main etc) locally into the temp dir we just made
repo, err := ce.getRepo(ctx, ce.ctr.VcsClient, ce.pullRequest.CloneURL, ce.pullRequest.BaseRef)
if err != nil {
return errors.Wrap(err, "failed to clone repo")
}
// Merge the most recent changes into the branch we just cloned
if err = repo.MergeIntoTarget(ctx, ce.pullRequest.SHA); err != nil {
return errors.Wrap(err, "failed to merge into target")
}
// Get the diff between the two branches, storing them within the CheckEvent (also returns but discarded here)
if err = ce.UpdateListOfChangedFiles(ctx, repo); err != nil {
return errors.Wrap(err, "failed to get list of changed files")
}
// Generate a list of affected apps, storing them within the CheckEvent (also returns but discarded here)
if err = ce.GenerateListOfAffectedApps(ctx, repo, ce.pullRequest.BaseRef); err != nil {
return errors.Wrap(err, "failed to generate a list of affected apps")
}
if err = ce.ctr.VcsClient.TidyOutdatedComments(ctx, ce.pullRequest); err != nil {
ce.logger.Error().Err(err).Msg("Failed to tidy outdated comments")
}
if len(ce.affectedItems.Applications) <= 0 && len(ce.affectedItems.ApplicationSets) <= 0 {
ce.logger.Info().Msg("No affected apps or appsets, skipping")
ce.ctr.VcsClient.PostMessage(ctx, ce.pullRequest, "No changes")
return nil
}
// We make one comment per run, containing output for all the apps
ce.vcsNote = ce.createNote(ctx)
for num := 0; num <= ce.ctr.Config.MaxConcurrenctChecks; num++ {
w := worker{
appChannel: ce.appChannel,
ctr: ce.ctr,
logger: ce.logger.With().Int("workerID", num).Logger(),
processors: ce.processors,
vcsNote: ce.vcsNote,
done: ce.wg.Done,
getRepo: ce.getRepo,
queueApp: ce.queueApp,
removeApp: ce.removeApp,
}
go w.run(ctx)
}
// Produce apps onto channel
for _, app := range ce.affectedItems.Applications {
ce.queueApp(app)
}
ce.wg.Wait()
close(ce.appChannel)
ce.logger.Debug().Msg("finished an app")
ce.logger.Debug().
Int("all apps", len(ce.addedAppsSet)).
Int32("sent apps", ce.appsSent).
Msg("completed apps")
ce.logger.Debug().Msg("Closing channels")
ce.logger.Info().Msg("Finished")
comment := ce.vcsNote.BuildComment(ctx, start, ce.pullRequest.SHA, ce.ctr.Config.LabelFilter, ce.ctr.Config.ShowDebugInfo)
if err = ce.ctr.VcsClient.UpdateMessage(ctx, ce.vcsNote, comment); err != nil {
return errors.Wrap(err, "failed to push comment")
}
worstStatus := ce.vcsNote.WorstState()
ce.CommitStatus(ctx, worstStatus)
return nil
}
func (ce *CheckEvent) removeApp(app v1alpha1.Application) {
ce.logger.Info().Str("app", app.Name).Msg("removing app")
ce.vcsNote.RemoveApp(app.Name)
}
func (ce *CheckEvent) queueApp(app v1alpha1.Application) {
ce.addedAppsSetLock.Lock()
defer ce.addedAppsSetLock.Unlock()
name := app.Name
dir := app.Spec.GetSource().Path
if old, ok := ce.addedAppsSet[name]; ok {
if reflect.DeepEqual(old, app) {
return
}
}
ce.addedAppsSet[name] = app
logger := ce.logger.With().
Str("app", name).
Str("dir", dir).
Str("cluster-name", app.Spec.Destination.Name).
Str("cluster-server", app.Spec.Destination.Server).
Logger()
logger.Info().Msg("adding app for processing")
ce.wg.Add(1)
atomic.AddInt32(&ce.appsSent, 1)
logger.Debug().Msg("producing app on channel")
ce.appChannel <- &app
logger.Debug().Msg("finished producing app")
}
// CommitStatus sets the commit status on the MR
// To set the PR/MR status
func (ce *CheckEvent) CommitStatus(ctx context.Context, status pkg.CommitState) {
_, span := tracer.Start(ctx, "CommitStatus")
defer span.End()
if err := ce.ctr.VcsClient.CommitStatus(ctx, ce.pullRequest, status); err != nil {
log.Warn().Err(err).Msg("failed to update commit status")
}
}
const (
errorCommentFormat = `
:warning: **Error while %s** :warning:
` + "```" + `
%v
` + "```" + `
Check kubechecks application logs for more information.
`
)
// Creates a generic Note struct that we can write into across all worker threads
func (ce *CheckEvent) createNote(ctx context.Context) *msg.Message {
ctx, span := otel.Tracer("check").Start(ctx, "createNote")
defer span.End()
ce.logger.Info().Msgf("Creating note")
return ce.ctr.VcsClient.PostMessage(ctx, ce.pullRequest, ":hourglass: kubechecks running ... ")
}
// cleanupGetManifestsError takes an error as input and returns a simplified and more user-friendly error message.
// It reformats Helm error messages by removing excess information, and makes file paths relative to the git repo root.
func cleanupGetManifestsError(err error, repoDirectory string) string {
// cleanup the chonky helm error message for a better DX
errStr := err.Error()
if strings.Contains(errStr, "helm template") && strings.Contains(errStr, "failed exit status") {
errMsgIdx := strings.Index(errStr, "Error:")
errStr = fmt.Sprintf("Helm %s", errStr[errMsgIdx:])
}
// strip the temp directory from any files mentioned to make file paths relative to git repo root
errStr = strings.ReplaceAll(errStr, repoDirectory+"/", "")
return errStr
}