-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
plan_command_runner.go
322 lines (284 loc) · 11.3 KB
/
plan_command_runner.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
package events
import (
"github.com/runatlantis/atlantis/server/core/locking"
"github.com/runatlantis/atlantis/server/events/command"
"github.com/runatlantis/atlantis/server/events/models"
"github.com/runatlantis/atlantis/server/events/vcs"
)
func NewPlanCommandRunner(
silenceVCSStatusNoPlans bool,
silenceVCSStatusNoProjects bool,
vcsClient vcs.Client,
pendingPlanFinder PendingPlanFinder,
workingDir WorkingDir,
commitStatusUpdater CommitStatusUpdater,
projectCommandBuilder ProjectPlanCommandBuilder,
projectCommandRunner ProjectPlanCommandRunner,
dbUpdater *DBUpdater,
pullUpdater *PullUpdater,
policyCheckCommandRunner *PolicyCheckCommandRunner,
autoMerger *AutoMerger,
parallelPoolSize int,
SilenceNoProjects bool,
pullStatusFetcher PullStatusFetcher,
lockingLocker locking.Locker,
discardApprovalOnPlan bool,
) *PlanCommandRunner {
return &PlanCommandRunner{
silenceVCSStatusNoPlans: silenceVCSStatusNoPlans,
silenceVCSStatusNoProjects: silenceVCSStatusNoProjects,
vcsClient: vcsClient,
pendingPlanFinder: pendingPlanFinder,
workingDir: workingDir,
commitStatusUpdater: commitStatusUpdater,
prjCmdBuilder: projectCommandBuilder,
prjCmdRunner: projectCommandRunner,
dbUpdater: dbUpdater,
pullUpdater: pullUpdater,
policyCheckCommandRunner: policyCheckCommandRunner,
autoMerger: autoMerger,
parallelPoolSize: parallelPoolSize,
SilenceNoProjects: SilenceNoProjects,
pullStatusFetcher: pullStatusFetcher,
lockingLocker: lockingLocker,
DiscardApprovalOnPlan: discardApprovalOnPlan,
}
}
type PlanCommandRunner struct {
vcsClient vcs.Client
// SilenceNoProjects is whether Atlantis should respond to PRs if no projects
// are found
SilenceNoProjects bool
// SilenceVCSStatusNoPlans is whether autoplan should set commit status if no plans
// are found
silenceVCSStatusNoPlans bool
// SilenceVCSStatusNoPlans is whether any plan should set commit status if no projects
// are found
silenceVCSStatusNoProjects bool
commitStatusUpdater CommitStatusUpdater
pendingPlanFinder PendingPlanFinder
workingDir WorkingDir
prjCmdBuilder ProjectPlanCommandBuilder
prjCmdRunner ProjectPlanCommandRunner
dbUpdater *DBUpdater
pullUpdater *PullUpdater
policyCheckCommandRunner *PolicyCheckCommandRunner
autoMerger *AutoMerger
parallelPoolSize int
pullStatusFetcher PullStatusFetcher
lockingLocker locking.Locker
// DiscardApprovalOnPlan controls if all already existing approvals should be removed/dismissed before executing
// a plan.
DiscardApprovalOnPlan bool
}
func (p *PlanCommandRunner) runAutoplan(ctx *command.Context) {
baseRepo := ctx.Pull.BaseRepo
pull := ctx.Pull
projectCmds, err := p.prjCmdBuilder.BuildAutoplanCommands(ctx)
if err != nil {
if statusErr := p.commitStatusUpdater.UpdateCombined(baseRepo, pull, models.FailedCommitStatus, command.Plan); statusErr != nil {
ctx.Log.Warn("unable to update commit status: %s", statusErr)
}
p.pullUpdater.updatePull(ctx, AutoplanCommand{}, command.Result{Error: err})
return
}
projectCmds, policyCheckCmds := p.partitionProjectCmds(ctx, projectCmds)
if len(projectCmds) == 0 {
ctx.Log.Info("determined there was no project to run plan in")
if !(p.silenceVCSStatusNoPlans || p.silenceVCSStatusNoProjects) {
// If there were no projects modified, we set successful commit statuses
// with 0/0 projects planned/policy_checked/applied successfully because some users require
// the Atlantis status to be passing for all pull requests.
ctx.Log.Debug("setting VCS status to success with no projects found")
if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Plan, 0, 0); err != nil {
ctx.Log.Warn("unable to update commit status: %s", err)
}
if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil {
ctx.Log.Warn("unable to update commit status: %s", err)
}
if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Apply, 0, 0); err != nil {
ctx.Log.Warn("unable to update commit status: %s", err)
}
}
return
}
// At this point we are sure Atlantis has work to do, so set commit status to pending
if err := p.commitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.PendingCommitStatus, command.Plan); err != nil {
ctx.Log.Warn("unable to update plan commit status: %s", err)
}
// discard previous plans that might not be relevant anymore
ctx.Log.Debug("deleting previous plans and locks")
p.deletePlans(ctx)
_, err = p.lockingLocker.UnlockByPull(baseRepo.FullName, pull.Num)
if err != nil {
ctx.Log.Err("deleting locks: %s", err)
}
// Only run commands in parallel if enabled
var result command.Result
if p.isParallelEnabled(projectCmds) {
ctx.Log.Info("Running plans in parallel")
result = runProjectCmdsParallelGroups(projectCmds, p.prjCmdRunner.Plan, p.parallelPoolSize)
} else {
result = runProjectCmds(projectCmds, p.prjCmdRunner.Plan)
}
if p.autoMerger.automergeEnabled(projectCmds) && result.HasErrors() {
ctx.Log.Info("deleting plans because there were errors and automerge requires all plans succeed")
p.deletePlans(ctx)
result.PlansDeleted = true
}
p.pullUpdater.updatePull(ctx, AutoplanCommand{}, result)
pullStatus, err := p.dbUpdater.updateDB(ctx, ctx.Pull, result.ProjectResults)
if err != nil {
ctx.Log.Err("writing results: %s", err)
}
p.updateCommitStatus(ctx, pullStatus)
// Check if there are any planned projects and if there are any errors or if plans are being deleted
if len(policyCheckCmds) > 0 &&
!(result.HasErrors() || result.PlansDeleted) {
// Run policy_check command
ctx.Log.Info("Running policy_checks for all plans")
// refresh ctx's view of pull status since we just wrote to it.
// realistically each command should refresh this at the start,
// however, policy checking is weird since it's called within the plan command itself
// we need to better structure how this command works.
ctx.PullStatus = &pullStatus
p.policyCheckCommandRunner.Run(ctx, policyCheckCmds)
}
}
func (p *PlanCommandRunner) run(ctx *command.Context, cmd *CommentCommand) {
var err error
baseRepo := ctx.Pull.BaseRepo
pull := ctx.Pull
if p.DiscardApprovalOnPlan {
if err = p.pullUpdater.VCSClient.DiscardReviews(baseRepo, pull); err != nil {
ctx.Log.Err("failed to remove approvals: %s", err)
}
}
if err = p.commitStatusUpdater.UpdateCombined(baseRepo, pull, models.PendingCommitStatus, command.Plan); err != nil {
ctx.Log.Warn("unable to update commit status: %s", err)
}
projectCmds, err := p.prjCmdBuilder.BuildPlanCommands(ctx, cmd)
if err != nil {
if statusErr := p.commitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Plan); statusErr != nil {
ctx.Log.Warn("unable to update commit status: %s", statusErr)
}
p.pullUpdater.updatePull(ctx, cmd, command.Result{Error: err})
return
}
if len(projectCmds) == 0 && p.SilenceNoProjects {
ctx.Log.Info("determined there was no project to run plan in")
if !p.silenceVCSStatusNoProjects {
// If there were no projects modified, we set successful commit statuses
// with 0/0 projects planned successfully because some users require
// the Atlantis status to be passing for all pull requests.
ctx.Log.Debug("setting VCS status to success with no projects found")
if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Plan, 0, 0); err != nil {
ctx.Log.Warn("unable to update commit status: %s", err)
}
}
return
}
projectCmds, policyCheckCmds := p.partitionProjectCmds(ctx, projectCmds)
// if the plan is generic, new plans will be generated based on changes
// discard previous plans that might not be relevant anymore
if !cmd.IsForSpecificProject() {
ctx.Log.Debug("deleting previous plans and locks")
p.deletePlans(ctx)
_, err = p.lockingLocker.UnlockByPull(baseRepo.FullName, pull.Num)
if err != nil {
ctx.Log.Err("deleting locks: %s", err)
}
}
// Only run commands in parallel if enabled
var result command.Result
if p.isParallelEnabled(projectCmds) {
ctx.Log.Info("Running plans in parallel")
result = runProjectCmdsParallelGroups(projectCmds, p.prjCmdRunner.Plan, p.parallelPoolSize)
} else {
result = runProjectCmds(projectCmds, p.prjCmdRunner.Plan)
}
if p.autoMerger.automergeEnabled(projectCmds) && result.HasErrors() {
ctx.Log.Info("deleting plans because there were errors and automerge requires all plans succeed")
p.deletePlans(ctx)
result.PlansDeleted = true
}
p.pullUpdater.updatePull(
ctx,
cmd,
result)
pullStatus, err := p.dbUpdater.updateDB(ctx, pull, result.ProjectResults)
if err != nil {
ctx.Log.Err("writing results: %s", err)
return
}
p.updateCommitStatus(ctx, pullStatus)
// Runs policy checks step after all plans are successful.
// This step does not approve any policies that require approval.
if len(result.ProjectResults) > 0 &&
!(result.HasErrors() || result.PlansDeleted) {
ctx.Log.Info("Running policy check for %s", cmd.String())
p.policyCheckCommandRunner.Run(ctx, policyCheckCmds)
}
}
func (p *PlanCommandRunner) Run(ctx *command.Context, cmd *CommentCommand) {
if ctx.Trigger == command.AutoTrigger {
p.runAutoplan(ctx)
} else {
p.run(ctx, cmd)
}
}
func (p *PlanCommandRunner) updateCommitStatus(ctx *command.Context, pullStatus models.PullStatus) {
var numSuccess int
var numErrored int
status := models.SuccessCommitStatus
numErrored = pullStatus.StatusCount(models.ErroredPlanStatus)
// We consider anything that isn't a plan error as a plan success.
// For example, if there is an apply error, that means that at least a
// plan was generated successfully.
numSuccess = len(pullStatus.Projects) - numErrored
if numErrored > 0 {
status = models.FailedCommitStatus
}
if err := p.commitStatusUpdater.UpdateCombinedCount(
ctx.Pull.BaseRepo,
ctx.Pull,
status,
command.Plan,
numSuccess,
len(pullStatus.Projects),
); err != nil {
ctx.Log.Warn("unable to update commit status: %s", err)
}
}
// deletePlans deletes all plans generated in this ctx.
func (p *PlanCommandRunner) deletePlans(ctx *command.Context) {
pullDir, err := p.workingDir.GetPullDir(ctx.Pull.BaseRepo, ctx.Pull)
if err != nil {
ctx.Log.Err("getting pull dir: %s", err)
}
if err := p.pendingPlanFinder.DeletePlans(pullDir); err != nil {
ctx.Log.Err("deleting pending plans: %s", err)
}
}
func (p *PlanCommandRunner) partitionProjectCmds(
ctx *command.Context,
cmds []command.ProjectContext,
) (
projectCmds []command.ProjectContext,
policyCheckCmds []command.ProjectContext,
) {
for _, cmd := range cmds {
switch cmd.CommandName {
case command.Plan:
projectCmds = append(projectCmds, cmd)
case command.PolicyCheck:
policyCheckCmds = append(policyCheckCmds, cmd)
default:
ctx.Log.Err("%s is not supported", cmd.CommandName)
}
}
return
}
func (p *PlanCommandRunner) isParallelEnabled(projectCmds []command.ProjectContext) bool {
return len(projectCmds) > 0 && projectCmds[0].ParallelPlanEnabled
}