-
Notifications
You must be signed in to change notification settings - Fork 153
/
scheduler.go
720 lines (633 loc) · 22.8 KB
/
scheduler.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
// Copyright 2020 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controller
import (
"context"
"encoding/json"
"fmt"
"io"
"path/filepath"
"time"
"go.uber.org/atomic"
"go.uber.org/zap"
"github.com/pipe-cd/pipecd/pkg/app/piped/deploysource"
"github.com/pipe-cd/pipecd/pkg/app/piped/executor"
"github.com/pipe-cd/pipecd/pkg/app/piped/executor/registry"
"github.com/pipe-cd/pipecd/pkg/app/piped/logpersister"
"github.com/pipe-cd/pipecd/pkg/app/piped/metadatastore"
pln "github.com/pipe-cd/pipecd/pkg/app/piped/planner"
"github.com/pipe-cd/pipecd/pkg/app/server/service/pipedservice"
"github.com/pipe-cd/pipecd/pkg/cache"
"github.com/pipe-cd/pipecd/pkg/config"
"github.com/pipe-cd/pipecd/pkg/model"
)
// scheduler is a dedicated object for a specific deployment of a single application.
type scheduler struct {
// Readonly deployment model.
deployment *model.Deployment
envName string
workingDir string
executorRegistry registry.Registry
apiClient apiClient
gitClient gitClient
commandLister commandLister
applicationLister applicationLister
liveResourceLister liveResourceLister
analysisResultStore analysisResultStore
logPersister logpersister.Persister
metadataStore metadatastore.MetadataStore
notifier notifier
secretDecrypter secretDecrypter
pipedConfig *config.PipedSpec
appManifestsCache cache.Cache
logger *zap.Logger
targetDSP deploysource.Provider
runningDSP deploysource.Provider
// Current status of each stages.
// We stores their current statuses into this field
// because the deployment model is readonly to avoid data race.
// We may need a mutex for this field in the future
// when the stages can be executed concurrently.
stageStatuses map[string]model.StageStatus
genericApplicationConfig config.GenericApplicationSpec
done atomic.Bool
doneTimestamp time.Time
doneDeploymentStatus model.DeploymentStatus
cancelled bool
cancelledCh chan *model.ReportableCommand
nowFunc func() time.Time
}
func newScheduler(
d *model.Deployment,
envName string,
workingDir string,
apiClient apiClient,
gitClient gitClient,
commandLister commandLister,
applicationLister applicationLister,
liveResourceLister liveResourceLister,
analysisResultStore analysisResultStore,
lp logpersister.Persister,
notifier notifier,
sd secretDecrypter,
pipedConfig *config.PipedSpec,
appManifestsCache cache.Cache,
logger *zap.Logger,
) *scheduler {
logger = logger.Named("scheduler").With(
zap.String("deployment-id", d.Id),
zap.String("app-id", d.ApplicationId),
zap.String("env-id", d.EnvId),
zap.String("project-id", d.ProjectId),
zap.String("app-kind", d.Kind.String()),
zap.String("working-dir", workingDir),
)
s := &scheduler{
deployment: d,
envName: envName,
workingDir: workingDir,
executorRegistry: registry.DefaultRegistry(),
apiClient: apiClient,
gitClient: gitClient,
commandLister: commandLister,
applicationLister: applicationLister,
liveResourceLister: liveResourceLister,
analysisResultStore: analysisResultStore,
logPersister: lp,
metadataStore: metadatastore.NewMetadataStore(apiClient, d),
notifier: notifier,
secretDecrypter: sd,
pipedConfig: pipedConfig,
appManifestsCache: appManifestsCache,
doneDeploymentStatus: d.Status,
cancelledCh: make(chan *model.ReportableCommand, 1),
logger: logger,
nowFunc: time.Now,
}
// Initialize the map of current status of all stages.
s.stageStatuses = make(map[string]model.StageStatus, len(d.Stages))
for _, stage := range d.Stages {
s.stageStatuses[stage.Id] = stage.Status
}
return s
}
// ID returns the id of scheduler.
// This is the same value with deployment ID.
func (s *scheduler) ID() string {
return s.deployment.Id
}
// CommitHash returns the hash value of deploying commit.
func (s *scheduler) CommitHash() string {
return s.deployment.CommitHash()
}
// IsDone tells whether this scheduler is done it tasks or not.
// Returning true means this scheduler can be removable.
func (s *scheduler) IsDone() bool {
return s.done.Load()
}
// DoneTimestamp returns the time when scheduler has done.
// This can be used only after IsDone() returns true.
func (s *scheduler) DoneTimestamp() time.Time {
if !s.IsDone() {
return time.Now().AddDate(1, 0, 0)
}
return s.doneTimestamp
}
// DoneDeploymentStatus returns the deployment status when scheduler has done.
// This can be used only after IsDone() returns true.
func (s *scheduler) DoneDeploymentStatus() model.DeploymentStatus {
if !s.IsDone() {
return s.deployment.Status
}
return s.doneDeploymentStatus
}
func (s *scheduler) Cancel(cmd model.ReportableCommand) {
if s.cancelled {
return
}
s.cancelled = true
s.cancelledCh <- &cmd
close(s.cancelledCh)
}
// Run starts running the scheduler.
// It determines what stage should be executed next by which executor.
// The returning error does not mean that the pipeline was failed,
// but it means that the scheduler could not finish its job normally.
func (s *scheduler) Run(ctx context.Context) error {
s.logger.Info("start running scheduler")
deploymentStatus := s.deployment.Status
defer func() {
s.doneTimestamp = s.nowFunc()
s.doneDeploymentStatus = deploymentStatus
s.done.Store(true)
}()
// If this deployment is already completed. Do nothing.
if model.IsCompletedDeployment(s.deployment.Status) {
s.logger.Info("this deployment is already completed")
return nil
}
// Update deployment status to RUNNING if needed.
if model.CanUpdateDeploymentStatus(s.deployment.Status, model.DeploymentStatus_DEPLOYMENT_RUNNING) {
err := s.reportDeploymentStatusChanged(ctx, model.DeploymentStatus_DEPLOYMENT_RUNNING, "The piped started handling this deployment")
if err != nil {
return err
}
}
var (
cancelCommand *model.ReportableCommand
cancelCommander string
lastStage *model.PipelineStage
statusReason = "The deployment was completed successfully"
)
deploymentStatus = model.DeploymentStatus_DEPLOYMENT_SUCCESS
repoCfg := config.PipedRepository{
RepoID: s.deployment.GitPath.Repo.Id,
Remote: s.deployment.GitPath.Repo.Remote,
Branch: s.deployment.GitPath.Repo.Branch,
}
s.targetDSP = deploysource.NewProvider(
filepath.Join(s.workingDir, "target-deploysource"),
deploysource.NewGitSourceCloner(s.gitClient, repoCfg, "target", s.deployment.Trigger.Commit.Hash),
*s.deployment.GitPath,
s.secretDecrypter,
)
if s.deployment.RunningCommitHash != "" {
s.runningDSP = deploysource.NewProvider(
filepath.Join(s.workingDir, "running-deploysource"),
deploysource.NewGitSourceCloner(s.gitClient, repoCfg, "running", s.deployment.RunningCommitHash),
*s.deployment.GitPath,
s.secretDecrypter,
)
}
// We use another deploy source provider to load the application configuration at the target commit.
// This provider is configured with a nil secretDecrypter
// because decrypting the sealed secrets is not required.
// We need only the application configuration spec.
configDSP := deploysource.NewProvider(
filepath.Join(s.workingDir, "target-config"),
deploysource.NewGitSourceCloner(s.gitClient, repoCfg, "target", s.deployment.Trigger.Commit.Hash),
*s.deployment.GitPath,
nil,
)
ds, err := configDSP.GetReadOnly(ctx, io.Discard)
if err != nil {
deploymentStatus = model.DeploymentStatus_DEPLOYMENT_FAILURE
statusReason = fmt.Sprintf("Unable to prepare application configuration source data at target commit (%v)", err)
s.reportDeploymentCompleted(ctx, deploymentStatus, statusReason, "")
return err
}
s.genericApplicationConfig = ds.GenericApplicationConfig
timer := time.NewTimer(s.genericApplicationConfig.Timeout.Duration())
defer timer.Stop()
// Iterate all the stages and execute the uncompleted ones.
for i, ps := range s.deployment.Stages {
lastStage = s.deployment.Stages[i]
if ps.Status == model.StageStatus_STAGE_SUCCESS {
continue
}
if !ps.Visible || ps.Name == model.StageRollback.String() {
continue
}
// This stage is already completed by a previous scheduler.
if ps.Status == model.StageStatus_STAGE_CANCELLED {
deploymentStatus = model.DeploymentStatus_DEPLOYMENT_CANCELLED
statusReason = fmt.Sprintf("Deployment was cancelled while executing stage %s", ps.Id)
break
}
if ps.Status == model.StageStatus_STAGE_FAILURE {
deploymentStatus = model.DeploymentStatus_DEPLOYMENT_FAILURE
statusReason = fmt.Sprintf("Failed while executing stage %s", ps.Id)
break
}
var (
result model.StageStatus
sig, handler = executor.NewStopSignal()
doneCh = make(chan struct{})
)
go func() {
result = s.executeStage(sig, *ps, func(in executor.Input) (executor.Executor, bool) {
return s.executorRegistry.Executor(model.Stage(ps.Name), in)
})
close(doneCh)
}()
select {
case <-ctx.Done():
handler.Terminate()
<-doneCh
case <-timer.C:
handler.Timeout()
<-doneCh
case cmd := <-s.cancelledCh:
if cmd != nil {
cancelCommand = cmd
cancelCommander = cmd.Commander
handler.Cancel()
<-doneCh
}
case <-doneCh:
break
}
// If all operations of the stage were completed successfully
// handle the next stage.
if result == model.StageStatus_STAGE_SUCCESS {
continue
}
// The deployment was cancelled by a web user.
if result == model.StageStatus_STAGE_CANCELLED {
deploymentStatus = model.DeploymentStatus_DEPLOYMENT_CANCELLED
statusReason = fmt.Sprintf("Cancelled by %s while executing stage %s", cancelCommander, ps.Id)
break
}
if result == model.StageStatus_STAGE_FAILURE {
deploymentStatus = model.DeploymentStatus_DEPLOYMENT_FAILURE
// The stage was failed because of timing out.
if sig.Signal() == executor.StopSignalTimeout {
statusReason = fmt.Sprintf("Timed out while executing stage %s", ps.Id)
} else {
statusReason = fmt.Sprintf("Failed while executing stage %s", ps.Id)
}
break
}
// The deployment was cancelled at the previous stage and this stage was terminated before run.
if result == model.StageStatus_STAGE_NOT_STARTED_YET && cancelCommand != nil {
deploymentStatus = model.DeploymentStatus_DEPLOYMENT_CANCELLED
statusReason = fmt.Sprintf("Cancelled by %s while executing the previous stage of %s", cancelCommander, ps.Id)
break
}
s.logger.Info("stop scheduler because of temination signal", zap.String("stage-id", ps.Id))
return nil
}
// When the deployment has completed but not successful,
// we start rollback stage if the auto-rollback option is true.
if deploymentStatus == model.DeploymentStatus_DEPLOYMENT_CANCELLED ||
deploymentStatus == model.DeploymentStatus_DEPLOYMENT_FAILURE {
if stage, ok := s.deployment.FindRollbackStage(); ok {
// Update to change deployment status to ROLLING_BACK.
if err := s.reportDeploymentStatusChanged(ctx, model.DeploymentStatus_DEPLOYMENT_ROLLING_BACK, statusReason); err != nil {
return err
}
// Start running rollback stage.
var (
sig, handler = executor.NewStopSignal()
doneCh = make(chan struct{})
)
go func() {
rbs := *stage
rbs.Requires = []string{lastStage.Id}
s.executeStage(sig, rbs, func(in executor.Input) (executor.Executor, bool) {
return s.executorRegistry.RollbackExecutor(s.deployment.Kind, in)
})
close(doneCh)
}()
select {
case <-ctx.Done():
handler.Terminate()
<-doneCh
return nil
case <-doneCh:
break
}
}
}
if model.IsCompletedDeployment(deploymentStatus) {
err := s.reportDeploymentCompleted(ctx, deploymentStatus, statusReason, cancelCommander)
if err == nil && deploymentStatus == model.DeploymentStatus_DEPLOYMENT_SUCCESS {
s.reportMostRecentlySuccessfulDeployment(ctx)
}
}
if cancelCommand != nil {
if err := cancelCommand.Report(ctx, model.CommandStatus_COMMAND_SUCCEEDED, nil, nil); err != nil {
s.logger.Error("failed to report command status", zap.Error(err))
}
}
return nil
}
// executeStage finds the executor for the given stage and execute.
func (s *scheduler) executeStage(sig executor.StopSignal, ps model.PipelineStage, executorFactory func(executor.Input) (executor.Executor, bool)) (finalStatus model.StageStatus) {
var (
ctx = sig.Context()
originalStatus = ps.Status
lp = s.logPersister.StageLogPersister(s.deployment.Id, ps.Id)
)
defer func() {
// When the piped has been terminated (PS kill) while the stage is still running
// we should not mark the log persister as completed.
if !model.IsCompletedStage(finalStatus) && sig.Terminated() {
return
}
lp.Complete(time.Minute)
}()
// Update stage status to RUNNING if needed.
if model.CanUpdateStageStatus(ps.Status, model.StageStatus_STAGE_RUNNING) {
if err := s.reportStageStatus(ctx, ps.Id, model.StageStatus_STAGE_RUNNING, ps.Requires); err != nil {
return model.StageStatus_STAGE_FAILURE
}
originalStatus = model.StageStatus_STAGE_RUNNING
}
// Check the existence of the specified cloud provider.
if !s.pipedConfig.HasCloudProvider(s.deployment.CloudProvider, s.deployment.CloudProviderType()) {
lp.Errorf("This piped is not having the specified cloud provider in this deployment: %v", s.deployment.CloudProvider)
if err := s.reportStageStatus(ctx, ps.Id, model.StageStatus_STAGE_FAILURE, ps.Requires); err != nil {
s.logger.Error("failed to report stage status", zap.Error(err))
}
return model.StageStatus_STAGE_FAILURE
}
// Load the stage configuration.
var stageConfig config.PipelineStage
var stageConfigFound bool
if ps.Predefined {
stageConfig, stageConfigFound = pln.GetPredefinedStage(ps.Id)
} else {
stageConfig, stageConfigFound = s.genericApplicationConfig.GetStage(ps.Index)
}
if !stageConfigFound {
lp.Error("Unable to find the stage configuration")
if err := s.reportStageStatus(ctx, ps.Id, model.StageStatus_STAGE_FAILURE, ps.Requires); err != nil {
s.logger.Error("failed to report stage status", zap.Error(err))
}
return model.StageStatus_STAGE_FAILURE
}
app, ok := s.applicationLister.Get(s.deployment.ApplicationId)
if !ok {
lp.Errorf("Application %s for this deployment was not found (Maybe it was disabled).", s.deployment.ApplicationId)
s.reportStageStatus(ctx, ps.Id, model.StageStatus_STAGE_FAILURE, ps.Requires)
return model.StageStatus_STAGE_FAILURE
}
cmdLister := stageCommandLister{
lister: s.commandLister,
deploymentID: s.deployment.Id,
stageID: ps.Id,
}
alrLister := appLiveResourceLister{
lister: s.liveResourceLister,
cloudProvider: app.CloudProvider,
appID: app.Id,
}
aStore := appAnalysisResultStore{
store: s.analysisResultStore,
applicationID: app.Id,
}
input := executor.Input{
Stage: &ps,
StageConfig: stageConfig,
Deployment: s.deployment,
Application: app,
PipedConfig: s.pipedConfig,
TargetDSP: s.targetDSP,
RunningDSP: s.runningDSP,
GitClient: s.gitClient,
CommandLister: cmdLister,
LogPersister: lp,
MetadataStore: s.metadataStore,
AppManifestsCache: s.appManifestsCache,
AppLiveResourceLister: alrLister,
AnalysisResultStore: aStore,
Logger: s.logger,
Notifier: s.notifier,
EnvName: s.envName,
}
// Find the executor for this stage.
ex, ok := executorFactory(input)
if !ok {
err := fmt.Errorf("no registered executor for stage %s", ps.Name)
lp.Error(err.Error())
s.reportStageStatus(ctx, ps.Id, model.StageStatus_STAGE_FAILURE, ps.Requires)
return model.StageStatus_STAGE_FAILURE
}
// Start running executor.
status := ex.Execute(sig)
// Commit deployment state status in the following cases:
// - Apply state successfully.
// - State was canceled while running (cancel via Controlpane).
// - Apply state failed but not because of terminating piped process.
if status == model.StageStatus_STAGE_SUCCESS ||
status == model.StageStatus_STAGE_CANCELLED ||
(status == model.StageStatus_STAGE_FAILURE && !sig.Terminated()) {
s.reportStageStatus(ctx, ps.Id, status, ps.Requires)
return status
}
// In case piped process got killed (Terminated signal occurred)
// the original state status will be returned.
return originalStatus
}
func (s *scheduler) reportStageStatus(ctx context.Context, stageID string, status model.StageStatus, requires []string) error {
var (
err error
now = s.nowFunc()
req = &pipedservice.ReportStageStatusChangedRequest{
DeploymentId: s.deployment.Id,
StageId: stageID,
Status: status,
Requires: requires,
Visible: true,
CompletedAt: now.Unix(),
}
retry = pipedservice.NewRetry(10)
)
// Update stage status at local.
s.stageStatuses[stageID] = status
// Update stage status on the remote.
for retry.WaitNext(ctx) {
_, err = s.apiClient.ReportStageStatusChanged(ctx, req)
if err == nil {
break
}
err = fmt.Errorf("failed to report stage status to control-plane: %v", err)
}
return err
}
func (s *scheduler) reportDeploymentStatusChanged(ctx context.Context, status model.DeploymentStatus, desc string) error {
var (
err error
retry = pipedservice.NewRetry(10)
req = &pipedservice.ReportDeploymentStatusChangedRequest{
DeploymentId: s.deployment.Id,
Status: status,
StatusReason: desc,
DeploymentChainId: s.deployment.DeploymentChainId,
DeploymentChainBlockIndex: s.deployment.DeploymentChainBlockIndex,
}
)
// Update deployment status on remote.
for retry.WaitNext(ctx) {
if _, err = s.apiClient.ReportDeploymentStatusChanged(ctx, req); err == nil {
return nil
}
err = fmt.Errorf("failed to report deployment status to control-plane: %v", err)
}
return err
}
func (s *scheduler) reportDeploymentCompleted(ctx context.Context, status model.DeploymentStatus, desc, cancelCommander string) error {
var (
err error
now = s.nowFunc()
req = &pipedservice.ReportDeploymentCompletedRequest{
DeploymentId: s.deployment.Id,
Status: status,
StatusReason: desc,
StageStatuses: s.stageStatuses,
DeploymentChainId: s.deployment.DeploymentChainId,
DeploymentChainBlockIndex: s.deployment.DeploymentChainBlockIndex,
CompletedAt: now.Unix(),
}
retry = pipedservice.NewRetry(10)
)
defer func() {
switch status {
case model.DeploymentStatus_DEPLOYMENT_SUCCESS:
accounts, err := s.getMentionedAccounts(model.NotificationEventType_EVENT_DEPLOYMENT_SUCCEEDED)
if err != nil {
s.logger.Error("failed to get the list of accounts", zap.Error(err))
}
s.notifier.Notify(model.NotificationEvent{
Type: model.NotificationEventType_EVENT_DEPLOYMENT_SUCCEEDED,
Metadata: &model.NotificationEventDeploymentSucceeded{
Deployment: s.deployment,
EnvName: s.envName,
MentionedAccounts: accounts,
},
})
case model.DeploymentStatus_DEPLOYMENT_FAILURE:
accounts, err := s.getMentionedAccounts(model.NotificationEventType_EVENT_DEPLOYMENT_FAILED)
if err != nil {
s.logger.Error("failed to get the list of accounts", zap.Error(err))
}
s.notifier.Notify(model.NotificationEvent{
Type: model.NotificationEventType_EVENT_DEPLOYMENT_FAILED,
Metadata: &model.NotificationEventDeploymentFailed{
Deployment: s.deployment,
EnvName: s.envName,
Reason: desc,
MentionedAccounts: accounts,
},
})
case model.DeploymentStatus_DEPLOYMENT_CANCELLED:
accounts, err := s.getMentionedAccounts(model.NotificationEventType_EVENT_DEPLOYMENT_CANCELLED)
if err != nil {
s.logger.Error("failed to get the list of accounts", zap.Error(err))
}
s.notifier.Notify(model.NotificationEvent{
Type: model.NotificationEventType_EVENT_DEPLOYMENT_CANCELLED,
Metadata: &model.NotificationEventDeploymentCancelled{
Deployment: s.deployment,
EnvName: s.envName,
Commander: cancelCommander,
MentionedAccounts: accounts,
},
})
}
}()
// Update deployment status on remote.
for retry.WaitNext(ctx) {
if _, err = s.apiClient.ReportDeploymentCompleted(ctx, req); err == nil {
return nil
}
err = fmt.Errorf("failed to report deployment status to control-plane: %w", err)
}
return err
}
func (s *scheduler) getMentionedAccounts(event model.NotificationEventType) ([]string, error) {
n, ok := s.metadataStore.Shared().Get(model.MetadataKeyDeploymentNotification)
if !ok {
return []string{}, nil
}
var notification config.DeploymentNotification
if err := json.Unmarshal([]byte(n), ¬ification); err != nil {
return nil, fmt.Errorf("could not extract mentions config: %w", err)
}
return notification.FindSlackAccounts(event), nil
}
func (s *scheduler) reportMostRecentlySuccessfulDeployment(ctx context.Context) error {
var (
err error
req = &pipedservice.ReportApplicationMostRecentDeploymentRequest{
ApplicationId: s.deployment.ApplicationId,
Status: model.DeploymentStatus_DEPLOYMENT_SUCCESS,
Deployment: &model.ApplicationDeploymentReference{
DeploymentId: s.deployment.Id,
Trigger: s.deployment.Trigger,
Summary: s.deployment.Summary,
Version: s.deployment.Version,
StartedAt: s.deployment.CreatedAt,
CompletedAt: s.deployment.CompletedAt,
},
}
retry = pipedservice.NewRetry(10)
)
for retry.WaitNext(ctx) {
if _, err = s.apiClient.ReportApplicationMostRecentDeployment(ctx, req); err == nil {
return nil
}
err = fmt.Errorf("failed to report most recent successful deployment: %w", err)
}
return err
}
type stageCommandLister struct {
lister commandLister
deploymentID string
stageID string
}
func (s stageCommandLister) ListCommands() []model.ReportableCommand {
return s.lister.ListStageCommands(s.deploymentID, s.stageID)
}
type appAnalysisResultStore struct {
store analysisResultStore
applicationID string
}
func (a appAnalysisResultStore) GetLatestAnalysisResult(ctx context.Context) (*model.AnalysisResult, error) {
return a.store.GetLatestAnalysisResult(ctx, a.applicationID)
}
func (a appAnalysisResultStore) PutLatestAnalysisResult(ctx context.Context, analysisResult *model.AnalysisResult) error {
return a.store.PutLatestAnalysisResult(ctx, a.applicationID, analysisResult)
}