forked from evergreen-ci/evergreen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
environment.go
1046 lines (889 loc) · 30 KB
/
environment.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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package evergreen
import (
"context"
"encoding/gob"
"fmt"
"math"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/evergreen-ci/certdepot"
"github.com/evergreen-ci/evergreen/util"
"github.com/evergreen-ci/gimlet"
"github.com/evergreen-ci/gimlet/rolemanager"
"github.com/mitchellh/mapstructure"
"github.com/mongodb/amboy"
"github.com/mongodb/amboy/logger"
"github.com/mongodb/amboy/pool"
"github.com/mongodb/amboy/queue"
"github.com/mongodb/anser/apm"
"github.com/mongodb/anser/db"
"github.com/mongodb/grip"
"github.com/mongodb/grip/level"
"github.com/mongodb/grip/message"
"github.com/mongodb/grip/send"
"github.com/mongodb/jasper"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
globalEnv Environment
globalEnvLock *sync.RWMutex
// don't ever access this directly except from testutil
PermissionSystemDisabled = false
)
const (
// duration of wait time during queue chut down.
queueShutdownWaitInterval = 10 * time.Millisecond
queueShutdownWaitTimeout = 10 * time.Second
RoleCollection = "roles"
ScopeCollection = "scopes"
)
func init() { globalEnvLock = &sync.RWMutex{} }
// GetEnvironment returns the global application level
// environment. This implementation is thread safe, but must be
// configured before use.
//
// In general you should call this operation once per process
// execution and pass the Environment interface through your
// application like a context, although there are cases in legacy code
// (e.g. models) and in the implementation of amboy jobs where it is
// necessary to access the global environment. There is a mock
// implementation for use in testing.
func GetEnvironment() Environment {
return globalEnv
}
func SetEnvironment(env Environment) {
globalEnvLock.Lock()
defer globalEnvLock.Unlock()
globalEnv = env
}
// Environment provides application-level services (e.g. databases,
// configuration, queues.
type Environment interface {
// Returns the settings object. The settings object is not
// necessarily safe for concurrent access.
Settings() *Settings
Context() (context.Context, context.CancelFunc)
Session() db.Session
Client() *mongo.Client
DB() *mongo.Database
// The Environment provides access to several amboy queues for
// processing background work in the context of the Evergreen
// application.
//
// The LocalQueue provides process-local execution, to support
// reporting and cleanup operations local to a single instance
// of the evergreen application. These queues are not
// durable, and job data are not available between application
// restarts.
//
// The RemoteQueue provides a single queue with many
// workers, distributed across all application servers. Each
// application dedicates a moderate pool of workers, and work
// enters this queue from periodic operations
// (e.g. "cron-like") as well as work that is submitted as a
// result of user requests. The service queue is
// mixed-workload.
//
// The RemoteQueueGroup provides logically distinct
// application queues in situations where we need to isolate
// workloads between queues. The queues are backed remotely, which
// means that their work persists between restarts.
LocalQueue() amboy.Queue
RemoteQueue() amboy.Queue
RemoteQueueGroup() amboy.QueueGroup
// Jasper is a process manager for running external
// commands. Every process has a manager service.
JasperManager() jasper.Manager
CertificateDepot() certdepot.Depot
// ClientConfig provides access to a list of the latest evergreen
// clients, that this server can serve to users
ClientConfig() *ClientConfig
// SaveConfig persists the configuration settings.
SaveConfig() error
// GetSender provides a grip Sender configured with the environment's
// settings. These Grip senders must be used with Composers that specify
// all message details.
GetSender(SenderKey) (send.Sender, error)
SetSender(SenderKey, send.Sender) error
// RegisterCloser adds a function object to an internal
// tracker to be called by the Close method before process
// termination. The ID is used in reporting, but must be
// unique or a new closer could overwrite an existing closer
// in some implementations.
RegisterCloser(string, bool, func(context.Context) error)
// Close calls all registered closers in the environment.
Close(context.Context) error
// RoleManager returns an interface that can be used to interact with roles and permissions
RoleManager() gimlet.RoleManager
// UserManager returns the global user manager for authentication.
UserManager() gimlet.UserManager
SetUserManager(gimlet.UserManager)
// UserManagerInfo returns the information about the user manager.
UserManagerInfo() UserManagerInfo
SetUserManagerInfo(UserManagerInfo)
// ShutdownSequenceStarted is true iff the shutdown sequence has been started
ShutdownSequenceStarted() bool
SetShutdown()
}
// NewEnvironment constructs an Environment instance, establishing a
// new connection to the database, and creating a new set of worker
// queues.
//
// When NewEnvironment returns without an error, you should assume
// that the queues have been started, there was no issue
// establishing a connection to the database, and that the
// local and remote queues have started.
//
// NewEnvironment requires that either the path or DB is sent so that
// if both are specified, the settings are read from the file.
func NewEnvironment(ctx context.Context, confPath string, db *DBSettings) (Environment, error) {
ctx, cancel := context.WithCancel(ctx)
e := &envState{
ctx: ctx,
senders: map[SenderKey]send.Sender{},
shutdownSequenceStarted: false,
}
defer func() {
e.RegisterCloser("root-context", false, func(_ context.Context) error {
cancel()
return nil
})
}()
if db != nil && confPath == "" {
if err := e.initDB(ctx, *db); err != nil {
return nil, errors.Wrap(err, "error configuring db")
}
e.dbName = db.DB
}
if err := e.initSettings(confPath); err != nil {
return nil, errors.WithStack(err)
}
if db != nil && confPath == "" {
e.settings.Database = *db
}
e.dbName = e.settings.Database.DB
catcher := grip.NewBasicCatcher()
if e.client == nil {
catcher.Add(e.initDB(ctx, e.settings.Database))
}
catcher.Add(e.initJasper())
catcher.Add(e.initDepot(ctx))
catcher.Add(e.initSenders(ctx))
catcher.Add(e.createLocalQueue(ctx))
catcher.Add(e.createApplicationQueue(ctx))
catcher.Add(e.createNotificationQueue(ctx))
catcher.Add(e.createRemoteQueueGroup(ctx))
catcher.Add(e.setupRoleManager())
catcher.Extend(e.initQueues(ctx))
if catcher.HasErrors() {
return nil, errors.WithStack(catcher.Resolve())
}
return e, nil
}
type envState struct {
remoteQueue amboy.Queue
localQueue amboy.Queue
remoteQueueGroup amboy.QueueGroup
notificationsQueue amboy.Queue
ctx context.Context
jasperManager jasper.Manager
depot certdepot.Depot
settings *Settings
dbName string
client *mongo.Client
mu sync.RWMutex
clientConfig *ClientConfig
s3ClientBinaries []ClientBinary
closers []closerOp
senders map[SenderKey]send.Sender
roleManager gimlet.RoleManager
userManager gimlet.UserManager
userManagerInfo UserManagerInfo
shutdownSequenceStarted bool
}
// UserManagerInfo lists properties of the UserManager regarding its support for
// certain features.
// TODO: this should probably be removed by refactoring the optional methods in
// the gimlet.UserManager.
type UserManagerInfo struct {
CanClearTokens bool
CanReauthorize bool
}
type closerOp struct {
name string
background bool
closerFn func(context.Context) error
}
func (e *envState) initSettings(path string) error {
// read configuration from either the file or DB and validate
// if the file path is blank, the DB session must be configured already
var err error
if e.settings == nil {
// this helps us test the validate method
if path != "" {
e.settings, err = NewSettings(path)
if err != nil {
return errors.Wrap(err, "problem getting settings from file")
}
} else {
e.settings, err = BootstrapConfig(e)
if err != nil {
return errors.Wrap(err, "problem getting settings from DB")
}
}
}
if e.settings == nil {
return errors.New("unable to get settings from file and DB")
}
if err = e.settings.Validate(); err != nil {
return errors.Wrap(err, "problem validating settings")
}
return nil
}
func (e *envState) initDB(ctx context.Context, settings DBSettings) error {
opts := options.Client().ApplyURI(settings.Url).SetWriteConcern(settings.WriteConcernSettings.Resolve()).
SetReadConcern(settings.ReadConcernSettings.Resolve()).
SetConnectTimeout(5 * time.Second).SetMonitor(apm.NewLoggingMonitor(ctx, time.Minute, apm.NewBasicMonitor(nil)).DriverAPM())
if settings.HasAuth() {
ymlUser, ymlPwd, err := settings.GetAuth()
if err != nil {
grip.Error(errors.Wrap(err, "problem getting auth from yaml authfile, attempting to connect without auth"))
}
if err == nil && ymlUser != "" {
credential := options.Credential{
Username: ymlUser,
Password: ymlPwd,
}
opts.SetAuth(credential)
}
}
var err error
e.client, err = mongo.NewClient(opts)
if err != nil {
return errors.Wrap(err, "problem constructing database")
}
if err = e.client.Connect(ctx); err != nil {
return errors.Wrap(err, "problem connecting to the database")
}
return nil
}
func (e *envState) Context() (context.Context, context.CancelFunc) {
e.mu.RLock()
defer e.mu.RUnlock()
return context.WithCancel(e.ctx)
}
func (e *envState) SetShutdown() {
e.mu.Lock()
defer e.mu.Unlock()
e.shutdownSequenceStarted = true
return
}
func (e *envState) ShutdownSequenceStarted() bool {
e.mu.RLock()
defer e.mu.RUnlock()
return e.shutdownSequenceStarted
}
func (e *envState) Client() *mongo.Client {
e.mu.RLock()
defer e.mu.RUnlock()
return e.client
}
func (e *envState) DB() *mongo.Database {
e.mu.RLock()
defer e.mu.RUnlock()
return e.client.Database(e.dbName)
}
func (e *envState) createLocalQueue(ctx context.Context) error {
// configure the local-only (memory-backed) queue.
e.localQueue = queue.NewLocalLimitedSize(e.settings.Amboy.PoolSizeLocal, e.settings.Amboy.LocalStorage)
if err := e.localQueue.SetRunner(pool.NewAbortablePool(e.settings.Amboy.PoolSizeLocal, e.localQueue)); err != nil {
return errors.Wrap(err, "problem configuring worker pool for local queue")
}
e.RegisterCloser("background-local-queue", true, func(ctx context.Context) error {
e.localQueue.Close(ctx)
return nil
})
return nil
}
func (e *envState) createApplicationQueue(ctx context.Context) error {
// configure the remote mongodb-backed amboy
// queue.
opts := queue.DefaultMongoDBOptions()
opts.URI = e.settings.Database.Url
opts.DB = e.settings.Amboy.DB
opts.Priority = e.settings.Amboy.RequireRemotePriority
opts.SkipQueueIndexBuilds = true
opts.SkipReportingIndexBuilds = true
opts.UseGroups = false
opts.LockTimeout = time.Duration(e.settings.Amboy.LockTimeoutMinutes) * time.Minute
opts.SampleSize = e.settings.Amboy.SampleSize
args := queue.MongoDBQueueCreationOptions{
Size: e.settings.Amboy.PoolSizeRemote,
Name: e.settings.Amboy.Name,
Ordered: false,
Client: e.client,
MDB: opts,
Retryable: e.settings.Amboy.Retry.RetryableQueueOptions(),
}
rq, err := queue.NewMongoDBQueue(ctx, args)
if err != nil {
return errors.Wrap(err, "problem setting main queue backend")
}
if err = rq.SetRunner(pool.NewAbortablePool(e.settings.Amboy.PoolSizeRemote, rq)); err != nil {
return errors.Wrap(err, "problem configuring worker pool for main remote queue")
}
e.remoteQueue = rq
e.RegisterCloser("application-queue", false, func(ctx context.Context) error {
e.remoteQueue.Close(ctx)
return nil
})
return nil
}
func (e *envState) createRemoteQueueGroup(ctx context.Context) error {
opts := queue.DefaultMongoDBOptions()
opts.URI = e.settings.Database.Url
opts.DB = e.settings.Amboy.DB
opts.Priority = e.settings.Amboy.RequireRemotePriority
opts.SkipQueueIndexBuilds = true
opts.SkipReportingIndexBuilds = true
opts.UseGroups = true
opts.GroupName = e.settings.Amboy.Name
opts.LockTimeout = time.Duration(e.settings.Amboy.LockTimeoutMinutes) * time.Minute
remoteQueueGroupOpts := queue.MongoDBQueueGroupOptions{
Prefix: e.settings.Amboy.Name,
DefaultWorkers: e.settings.Amboy.GroupDefaultWorkers,
Ordered: false,
BackgroundCreateFrequency: time.Duration(e.settings.Amboy.GroupBackgroundCreateFrequencyMinutes) * time.Minute,
PruneFrequency: time.Duration(e.settings.Amboy.GroupPruneFrequencyMinutes) * time.Minute,
TTL: time.Duration(e.settings.Amboy.GroupTTLMinutes) * time.Minute,
Retryable: e.settings.Amboy.Retry.RetryableQueueOptions(),
}
remoteQueueGroup, err := queue.NewMongoDBSingleQueueGroup(ctx, remoteQueueGroupOpts, e.client, opts)
if err != nil {
return errors.Wrap(err, "problem constructing remote queue group")
}
e.remoteQueueGroup = remoteQueueGroup
e.RegisterCloser("remote-queue-group", false, func(ctx context.Context) error {
return errors.Wrap(e.remoteQueueGroup.Close(ctx), "problem waiting for remote queue group to close")
})
return nil
}
func (e *envState) createNotificationQueue(ctx context.Context) error {
// Notifications queue w/ moving weight avg pool
e.notificationsQueue = queue.NewLocalLimitedSize(len(e.senders), e.settings.Amboy.LocalStorage)
runner, err := pool.NewMovingAverageRateLimitedWorkers(e.settings.Amboy.PoolSizeLocal,
e.settings.Notify.BufferTargetPerInterval,
time.Duration(e.settings.Notify.BufferIntervalSeconds)*time.Second,
e.notificationsQueue)
if err != nil {
return errors.Wrap(err, "Failed to make notifications queue runner")
}
if err = e.notificationsQueue.SetRunner(runner); err != nil {
return errors.Wrap(err, "failed to set notifications queue runner")
}
rootSenders := []send.Sender{}
for _, s := range e.senders {
rootSenders = append(rootSenders, s)
}
e.RegisterCloser("notification-queue", false, func(ctx context.Context) error {
var cancel context.CancelFunc
catcher := grip.NewBasicCatcher()
ctx, cancel = context.WithTimeout(ctx, queueShutdownWaitTimeout)
defer cancel()
if !amboy.WaitInterval(ctx, e.notificationsQueue, queueShutdownWaitInterval) {
grip.Critical(message.Fields{
"message": "pending jobs failed to finish",
"queue": "notifications",
"status": e.notificationsQueue.Stats(ctx),
})
catcher.Add(errors.New("failed to stop with running jobs"))
}
e.notificationsQueue.Close(ctx)
grip.Debug(message.Fields{
"message": "closed notification queue",
"num_senders": len(rootSenders),
"errors": catcher.HasErrors(),
})
for _, s := range rootSenders {
catcher.Add(s.Close())
}
grip.Debug(message.Fields{
"message": "closed all root senders",
"num_senders": len(rootSenders),
"errors": catcher.HasErrors(),
})
return catcher.Resolve()
})
for k := range e.senders {
e.senders[k] = logger.MakeQueueSender(ctx, e.notificationsQueue, e.senders[k])
}
return nil
}
func (e *envState) initQueues(ctx context.Context) []error {
catcher := grip.NewBasicCatcher()
catcher.NewWhen(e.localQueue == nil, "local queue is not defined")
catcher.NewWhen(e.notificationsQueue == nil, "notification queue is not defined")
if e.localQueue != nil {
catcher.Add(e.localQueue.Start(ctx))
}
if e.notificationsQueue != nil {
catcher.Add(e.notificationsQueue.Start(ctx))
}
return catcher.Errors()
}
func (e *envState) initClientConfig() {
if e.settings == nil {
grip.Critical("no settings object, cannot build client configuration")
return
}
var err error
e.clientConfig, err = getClientConfig(e.settings.Ui.Url, e.settings.HostInit.S3BaseURL)
if err != nil {
grip.Critical(message.WrapError(err, message.Fields{
"message": "problem finding local clients",
"cause": "infrastructure configuration issue",
}))
} else if len(e.clientConfig.ClientBinaries) == 0 {
grip.Critical("No clients are available for this server")
}
}
func (e *envState) initSenders(ctx context.Context) error {
if e.settings == nil {
return errors.New("no settings object, cannot build senders")
}
levelInfo := send.LevelInfo{
Default: level.Notice,
Threshold: level.Notice,
}
if e.settings.Notify.SMTP.From != "" {
smtp := e.settings.Notify.SMTP
opts := send.SMTPOptions{
Name: "evergreen",
Server: smtp.Server,
Port: smtp.Port,
UseSSL: smtp.UseSSL,
Username: smtp.Username,
Password: smtp.Password,
From: smtp.From,
PlainTextContents: false,
NameAsSubject: true,
}
if len(smtp.AdminEmail) == 0 {
if err := opts.AddRecipient("", "[email protected]"); err != nil {
return errors.Wrap(err, "failed to setup email logger")
}
} else {
for i := range smtp.AdminEmail {
if err := opts.AddRecipient("", smtp.AdminEmail[i]); err != nil {
return errors.Wrap(err, "failed to setup email logger")
}
}
}
sender, err := send.NewSMTPLogger(&opts, levelInfo)
if err != nil {
return errors.Wrap(err, "Failed to setup email logger")
}
e.senders[SenderEmail] = sender
}
var sender send.Sender
githubToken, err := e.settings.GetGithubOauthToken()
if err == nil && len(githubToken) > 0 {
// Github Status
sender, err = send.NewGithubStatusLogger("evergreen", &send.GithubOptions{
Token: githubToken,
}, "")
if err != nil {
return errors.Wrap(err, "Failed to setup github status logger")
}
e.senders[SenderGithubStatus] = sender
}
if jira := &e.settings.Jira; len(jira.GetHostURL()) != 0 {
sender, err = send.NewJiraLogger(ctx, jira.Export(), levelInfo)
if err != nil {
return errors.Wrap(err, "Failed to setup jira issue logger")
}
e.senders[SenderJIRAIssue] = sender
sender, err = send.NewJiraCommentLogger(ctx, "", jira.Export(), levelInfo)
if err != nil {
return errors.Wrap(err, "Failed to setup jira comment logger")
}
e.senders[SenderJIRAComment] = sender
}
if slack := &e.settings.Slack; len(slack.Token) != 0 {
// this sender is initialised with an invalid channel. Any
// messages sent with it that do not use message.SlackMessage
// will not be received
sender, err = send.NewSlackLogger(&send.SlackOptions{
Channel: "#",
Name: "evergreen",
Username: "Evergreen",
IconURL: fmt.Sprintf("%s/static/img/evergreen_green_150x150.png", e.settings.Ui.Url),
}, slack.Token, levelInfo)
if err != nil {
return errors.Wrap(err, "Failed to setup slack logger")
}
e.senders[SenderSlack] = sender
}
sender, err = util.NewEvergreenWebhookLogger()
if err != nil {
return errors.Wrap(err, "Failed to setup evergreen webhook logger")
}
e.senders[SenderEvergreenWebhook] = sender
sender, err = send.NewGenericLogger("evergreen", levelInfo)
if err != nil {
return errors.Wrap(err, "Failed to setup evergreen generic logger")
}
e.senders[SenderGeneric] = sender
catcher := grip.NewBasicCatcher()
for name, s := range e.senders {
catcher.Add(s.SetLevel(levelInfo))
catcher.Add(s.SetErrorHandler(func(err error, m message.Composer) {
if err == nil {
return
}
grip.Error(message.WrapError(err, message.Fields{
"notification": m.String(),
"message_type": fmt.Sprintf("%T", m),
"notification_target": name.String(),
"event": m,
}))
}))
}
return catcher.Resolve()
}
func (e *envState) initJasper() error {
jpm, err := jasper.NewSynchronizedManager(true)
if err != nil {
return errors.WithStack(err)
}
e.jasperManager = jpm
e.RegisterCloser("jasper-manager", true, func(ctx context.Context) error {
return errors.WithStack(jpm.Close(ctx))
})
return nil
}
func (e *envState) initDepot(ctx context.Context) error {
if e.settings.DomainName == "" {
return errors.Errorf("bootstrapping '%s' collection requires domain name to be set in admin settings", CredentialsCollection)
}
maxExpiration := time.Duration(math.MaxInt64)
bootstrapConfig := certdepot.BootstrapDepotConfig{
CAName: CAName,
MongoDepot: &certdepot.MongoDBOptions{
MongoDBURI: e.settings.Database.Url,
DatabaseName: e.settings.Database.DB,
CollectionName: CredentialsCollection,
DepotOptions: certdepot.DepotOptions{
CA: CAName,
DefaultExpiration: maxExpiration,
},
},
CAOpts: &certdepot.CertificateOptions{
CA: CAName,
CommonName: CAName,
Expires: maxExpiration,
},
ServiceName: e.settings.DomainName,
ServiceOpts: &certdepot.CertificateOptions{
CA: CAName,
CommonName: e.settings.DomainName,
Host: e.settings.DomainName,
Expires: maxExpiration,
},
}
var err error
if e.depot, err = certdepot.BootstrapDepotWithMongoClient(ctx, e.client, bootstrapConfig); err != nil {
return errors.Wrapf(err, "could not bootstrap %s collection", CredentialsCollection)
}
return nil
}
func (e *envState) setupRoleManager() error {
e.roleManager = rolemanager.NewMongoBackedRoleManager(rolemanager.MongoBackedRoleManagerOpts{
Client: e.client,
DBName: e.dbName,
RoleCollection: RoleCollection,
ScopeCollection: ScopeCollection,
})
catcher := grip.NewBasicCatcher()
catcher.Add(e.roleManager.RegisterPermissions(ProjectPermissions))
catcher.Add(e.roleManager.RegisterPermissions(DistroPermissions))
catcher.Add(e.roleManager.RegisterPermissions(SuperuserPermissions))
return catcher.Resolve()
}
func (e *envState) UserManager() gimlet.UserManager {
e.mu.RLock()
defer e.mu.RUnlock()
return e.userManager
}
func (e *envState) SetUserManager(um gimlet.UserManager) {
e.mu.Lock()
defer e.mu.Unlock()
e.userManager = um
}
func (e *envState) UserManagerInfo() UserManagerInfo {
e.mu.RLock()
defer e.mu.RUnlock()
return e.userManagerInfo
}
func (e *envState) SetUserManagerInfo(umi UserManagerInfo) {
e.mu.Lock()
defer e.mu.Unlock()
e.userManagerInfo = umi
}
func (e *envState) Settings() *Settings {
e.mu.RLock()
defer e.mu.RUnlock()
return e.settings
}
func (e *envState) LocalQueue() amboy.Queue {
e.mu.RLock()
defer e.mu.RUnlock()
return e.localQueue
}
func (e *envState) RemoteQueue() amboy.Queue {
e.mu.RLock()
defer e.mu.RUnlock()
return e.remoteQueue
}
func (e *envState) RemoteQueueGroup() amboy.QueueGroup {
e.mu.RLock()
defer e.mu.RUnlock()
return e.remoteQueueGroup
}
func (e *envState) Session() db.Session {
e.mu.RLock()
defer e.mu.RUnlock()
return db.WrapClient(e.ctx, e.client).Clone()
}
func (e *envState) ClientConfig() *ClientConfig {
e.mu.RLock()
defer e.mu.RUnlock()
if e.clientConfig == nil {
e.initClientConfig()
if e.clientConfig == nil {
return nil
}
}
config := *e.clientConfig
return &config
}
type BuildBaronProject struct {
// todo: reconfigure the BuildBaronConfigured check to use TicketSearchProjects instead
TicketCreateProject string `mapstructure:"ticket_create_project" bson:"ticket_create_project"`
TicketSearchProjects []string `mapstructure:"ticket_search_projects" bson:"ticket_search_projects"`
TaskAnnotationSettings AnnotationsSettings `mapstructure:"task_annotation_settings" bson:"task_annotation_settings"`
// The BF Suggestion server as a source of suggestions is only enabled for projects where BFSuggestionServer isn't the empty string.
BFSuggestionServer string `mapstructure:"bf_suggestion_server" bson:"bf_suggestion_server"`
BFSuggestionUsername string `mapstructure:"bf_suggestion_username" bson:"bf_suggestion_username"`
BFSuggestionPassword string `mapstructure:"bf_suggestion_password" bson:"bf_suggestion_password"`
BFSuggestionTimeoutSecs int `mapstructure:"bf_suggestion_timeout_secs" bson:"bf_suggestion_timeout_secs"`
BFSuggestionFeaturesURL string `mapstructure:"bf_suggestion_features_url" bson:"bf_suggestion_features_url"`
}
type AnnotationsSettings struct {
// a list of jira fields the user wants to display in addition to state assignee and priority
JiraCustomFields []JiraField `mapstructure:"jira_custom_fields" bson:"jira_custom_fields"`
// the endpoint that the user would like to send data to when the file ticket button is clicked
FileTicketWebHook WebHook `mapstructure:"web_hook" bson:"web_hook"`
}
type JiraField struct {
// the name that jira calls the field
Field string `mapstructure:"field" bson:"field"`
// the name the user would like to call it in the UI
DisplayText string `mapstructure:"display_text" bson:"display_text"`
}
type WebHook struct {
Endpoint string `mapstructure:"endpoint" bson:"endpoint"`
Secret string `mapstructure:"secret" bson:"secret"`
}
func (e *envState) SaveConfig() error {
if e.settings == nil {
return errors.New("no settings object, cannot persist to DB")
}
// this is a hacky workaround to any plugins that have fields that are maps, since
// deserializing these fields from yaml does not maintain the typing information
var copy Settings
registeredTypes := []interface{}{
map[interface{}]interface{}{},
map[string]interface{}{},
[]interface{}{},
[]util.KeyValuePair{},
}
err := util.DeepCopy(*e.settings, ©, registeredTypes)
if err != nil {
return errors.Wrap(err, "problem copying settings")
}
gob.Register(map[interface{}]interface{}{})
for pluginName, plugin := range copy.Plugins {
if pluginName == "buildbaron" {
for fieldName, field := range plugin {
if fieldName == "projects" {
var projects map[string]BuildBaronProject
err := mapstructure.Decode(field, &projects)
if err != nil {
return errors.Wrap(err, "problem decoding buildbaron projects")
}
plugin[fieldName] = projects
}
}
}
if pluginName == "dashboard" {
for fieldName, field := range plugin {
if fieldName == "branches" {
var branches map[string][]string
err := mapstructure.Decode(field, &branches)
if err != nil {
return errors.Wrap(err, "problem decoding dashboard branches")
}
plugin[fieldName] = branches
}
}
}
}
return errors.WithStack(UpdateConfig(©))
}
func (e *envState) GetSender(key SenderKey) (send.Sender, error) {
e.mu.RLock()
defer e.mu.RUnlock()
sender, ok := e.senders[key]
if !ok {
return nil, errors.Errorf("unknown sender key %v", key)
}
return sender, nil
}
func (e *envState) SetSender(key SenderKey, impl send.Sender) error {
if impl == nil {
return errors.New("cannot add a nil sender")
}
if err := key.Validate(); err != nil {
return errors.WithStack(err)
}
e.mu.Lock()
defer e.mu.Unlock()
e.senders[key] = impl
return nil
}
func (e *envState) RegisterCloser(name string, background bool, closer func(context.Context) error) {
e.mu.Lock()
defer e.mu.Unlock()
e.closers = append(e.closers, closerOp{name: name, background: background, closerFn: closer})
}
func (e *envState) Close(ctx context.Context) error {
e.mu.RLock()
defer e.mu.RUnlock()
// TODO we could, in the future call all closers in but that
// would require more complex waiting and timeout logic
deadline, _ := ctx.Deadline()
catcher := grip.NewBasicCatcher()
wg := &sync.WaitGroup{}
for n, closer := range e.closers {
if !closer.background {
continue
}
if closer.closerFn == nil {
continue
}
wg.Add(1)
go func(idx int, name string, clfn func(context.Context) error) {
defer wg.Done()
grip.Info(message.Fields{
"message": "calling closer",
"index": idx,
"closer": name,
"timeout_secs": time.Until(deadline),
"deadline": deadline,
"background": true,
})
catcher.Add(clfn(ctx))
}(n, closer.name, closer.closerFn)
}
for idx, closer := range e.closers {
if closer.background {
continue
}
if closer.closerFn == nil {
continue
}
grip.Info(message.Fields{
"message": "calling closer",
"index": idx,
"closer": closer.name,
"timeout_secs": time.Until(deadline),
"deadline": deadline,
"background": false,
})
catcher.Add(closer.closerFn(ctx))
}
wg.Wait()
return catcher.Resolve()
}
// getClientConfig should be called once at startup and looks at the
// current environment and loads all currently available client
// binaries for use by the API server in presenting the settings page.
//
// If there are no built clients, this returns an empty config
// version, but does *not* error.
func getClientConfig(baseURL, s3BaseURL string) (*ClientConfig, error) {
c := &ClientConfig{}
c.LatestRevision = ClientVersion
root := filepath.Join(FindEvergreenHome(), ClientDirectory)
if _, err := os.Stat(root); os.IsNotExist(err) {
grip.Warningf("client directory '%s' does not exist, creating empty "+
"directory and continuing with caution", root)
grip.Error(os.MkdirAll(root, 0755))
}
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || !strings.Contains(info.Name(), "evergreen") {
return nil
}
parts := strings.Split(path, string(filepath.Separator))
buildInfo := strings.Split(parts[len(parts)-2], "_")
displayName := ValidArchDisplayNames[fmt.Sprintf("%s_%s", buildInfo[0], buildInfo[1])]
archPath := strings.Join(parts[len(parts)-2:], "/")
c.ClientBinaries = append(c.ClientBinaries, ClientBinary{
URL: fmt.Sprintf("%s/%s/%s", baseURL, ClientDirectory, archPath),