forked from openshift/assisted-service
/
cluster.go
1724 lines (1562 loc) · 66 KB
/
cluster.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 cluster
import (
"context"
"encoding/json"
"fmt"
"net/http"
"path/filepath"
reflect "reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/filanov/stateswitch"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/google/uuid"
"github.com/hashicorp/go-multierror"
"github.com/kennygrant/sanitize"
"github.com/openshift/assisted-service/internal/common"
eventgen "github.com/openshift/assisted-service/internal/common/events"
"github.com/openshift/assisted-service/internal/constants"
"github.com/openshift/assisted-service/internal/dns"
eventsapi "github.com/openshift/assisted-service/internal/events/api"
"github.com/openshift/assisted-service/internal/host"
"github.com/openshift/assisted-service/internal/host/hostutil"
"github.com/openshift/assisted-service/internal/metrics"
"github.com/openshift/assisted-service/internal/network"
"github.com/openshift/assisted-service/internal/operators"
"github.com/openshift/assisted-service/internal/stream"
"github.com/openshift/assisted-service/internal/uploader"
"github.com/openshift/assisted-service/models"
"github.com/openshift/assisted-service/pkg/auth"
"github.com/openshift/assisted-service/pkg/commonutils"
"github.com/openshift/assisted-service/pkg/leader"
logutil "github.com/openshift/assisted-service/pkg/log"
"github.com/openshift/assisted-service/pkg/ocm"
"github.com/openshift/assisted-service/pkg/requestid"
"github.com/openshift/assisted-service/pkg/s3wrapper"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
"gorm.io/gorm"
"k8s.io/apimachinery/pkg/types"
)
const (
DhcpLeaseTimeoutMinutes = 2
ForceSchedulableMastersMaxHostCount = 5
)
var S3FileNames = []string{
constants.Kubeconfig,
"bootstrap.ign",
"master.ign",
"worker.ign",
"metadata.json",
"kubeadmin-password",
"kubeconfig-noingress",
"install-config.yaml",
"custom_manifests.json",
"custom_manifests.yaml",
}
var ClusterOwnerFileNames = []string{
constants.Kubeconfig,
"kubeadmin-password",
"kubeconfig-noingress",
}
//go:generate mockgen -source=cluster.go -package=cluster -destination=mock_cluster_api.go
type RegistrationAPI interface {
// Register a new cluster
RegisterCluster(ctx context.Context, c *common.Cluster) error
// Register a new add-host cluster
RegisterAddHostsCluster(ctx context.Context, c *common.Cluster) error
// Register a new add-host-ocp cluster
RegisterAddHostsOCPCluster(c *common.Cluster, db *gorm.DB) error
//deregister cluster
DeregisterCluster(ctx context.Context, c *common.Cluster) error
}
type InstallationAPI interface {
// Get the cluster master nodes ID's
GetMasterNodesIds(ctx context.Context, c *common.Cluster, db *gorm.DB) ([]*strfmt.UUID, error)
}
type ProgressAPI interface {
UpdateInstallProgress(ctx context.Context, clusterID strfmt.UUID) error
UpdateFinalizingProgress(ctx context.Context, db *gorm.DB, clusterID strfmt.UUID) error
}
type API interface {
RegistrationAPI
InstallationAPI
ProgressAPI
// Refresh state in case of hosts update
RefreshStatus(ctx context.Context, c *common.Cluster, db *gorm.DB) (*common.Cluster, error)
ClusterMonitoring()
IsOperatorMonitored(c *common.Cluster, operatorName string) bool
IsOperatorAvailable(c *common.Cluster, operatorName string) bool
UploadIngressCert(c *common.Cluster) (err error)
VerifyClusterUpdatability(c *common.Cluster) (err error)
AcceptRegistration(c *common.Cluster) (err error)
CancelInstallation(ctx context.Context, c *common.Cluster, reason string, db *gorm.DB) *common.ApiErrorResponse
ResetCluster(ctx context.Context, c *common.Cluster, reason string, db *gorm.DB) *common.ApiErrorResponse
PrepareForInstallation(ctx context.Context, c *common.Cluster, db *gorm.DB) error
HandlePreInstallError(ctx context.Context, c *common.Cluster, err error)
HandlePreInstallSuccess(ctx context.Context, c *common.Cluster)
SetVipsData(ctx context.Context, c *common.Cluster, apiVip, ingressVip, apiVipLease, ingressVipLease string, db *gorm.DB) error
IsReadyForInstallation(c *common.Cluster) (bool, string)
PrepareHostLogFile(ctx context.Context, c *common.Cluster, host *models.Host, objectHandler s3wrapper.API) (string, error)
PrepareClusterLogFile(ctx context.Context, c *common.Cluster, objectHandler s3wrapper.API) (string, error)
SetUploadControllerLogsAt(ctx context.Context, c *common.Cluster, db *gorm.DB) error
SetConnectivityMajorityGroupsForCluster(clusterID strfmt.UUID, db *gorm.DB) error
DetectAndStoreCollidingIPsForCluster(clusterID strfmt.UUID, db *gorm.DB) error
DeleteClusterLogs(ctx context.Context, c *common.Cluster, objectHandler s3wrapper.API) error
DeleteClusterFiles(ctx context.Context, c *common.Cluster, objectHandler s3wrapper.API) error
UpdateLogsProgress(ctx context.Context, c *common.Cluster, progress string) error
GetClusterByKubeKey(key types.NamespacedName) (*common.Cluster, error)
UpdateAmsSubscriptionID(ctx context.Context, clusterID, amsSubscriptionID strfmt.UUID) *common.ApiErrorResponse
GenerateAdditionalManifests(ctx context.Context, cluster *common.Cluster) error
CompleteInstallation(ctx context.Context, db *gorm.DB, cluster *common.Cluster, successfullyFinished bool, reason string) (*common.Cluster, error)
PermanentClustersDeletion(ctx context.Context, olderThan strfmt.DateTime, objectHandler s3wrapper.API) error
DeregisterInactiveCluster(ctx context.Context, maxDeregisterPerInterval int, inactiveSince strfmt.DateTime) error
TransformClusterToDay2(ctx context.Context, cluster *common.Cluster, db *gorm.DB) error
RefreshSchedulableMastersForcedTrue(ctx context.Context, clusterID strfmt.UUID) error
HandleVerifyVipsResponse(ctx context.Context, clusterID strfmt.UUID, stepReply string) error
}
type LogTimeoutConfig struct {
LogCollectionTimeout time.Duration `envconfig:"LOG_COLLECTION_TIMEOUT" default:"60m"`
LogPendingTimeout time.Duration `envconfig:"LOG_PENDING_TIMEOUT" default:"10m"`
}
type PrepareConfig struct {
LogTimeoutConfig
PrepareForInstallationTimeout time.Duration `envconfig:"PREPARE_FOR_INSTALLATION_TIMEOUT" default:"10m"`
}
type Config struct {
PrepareConfig PrepareConfig
InstallationTimeout time.Duration `envconfig:"INSTALLATION_TIMEOUT" default:"24h"`
FinalizingTimeout time.Duration `envconfig:"FINALIZING_TIMEOUT" default:"5h"`
MonitorBatchSize int `envconfig:"CLUSTER_MONITOR_BATCH_SIZE" default:"100"`
}
type Manager struct {
Config
log logrus.FieldLogger
db *gorm.DB
stream stream.Notifier
registrationAPI RegistrationAPI
installationAPI InstallationAPI
eventsHandler eventsapi.Handler
sm stateswitch.StateMachine
metricAPI metrics.API
manifestsGeneratorAPI network.ManifestsGeneratorAPI
hostAPI host.API
rp *refreshPreprocessor
leaderElector leader.Leader
prevMonitorInvokedAt time.Time
ocmClient *ocm.Client
objectHandler s3wrapper.API
dnsApi dns.DNSApi
monitorQueryGenerator *common.MonitorClusterQueryGenerator
authHandler auth.Authenticator
uploadClient uploader.Client
}
func NewManager(cfg Config, log logrus.FieldLogger, db *gorm.DB, stream stream.Notifier, eventsHandler eventsapi.Handler,
uploadClient uploader.Client, hostAPI host.API, metricApi metrics.API, manifestsGeneratorAPI network.ManifestsGeneratorAPI,
leaderElector leader.Leader, operatorsApi operators.API, ocmClient *ocm.Client, objectHandler s3wrapper.API,
dnsApi dns.DNSApi, authHandler auth.Authenticator) *Manager {
th := &transitionHandler{
log: log,
db: db,
stream: stream,
prepareConfig: cfg.PrepareConfig,
installationTimeout: cfg.InstallationTimeout,
finalizingTimeout: cfg.FinalizingTimeout,
eventsHandler: eventsHandler,
}
return &Manager{
Config: cfg,
log: log,
db: db,
stream: stream,
registrationAPI: NewRegistrar(log, db),
installationAPI: NewInstaller(log, db, eventsHandler),
eventsHandler: eventsHandler,
sm: NewClusterStateMachine(th),
metricAPI: metricApi,
manifestsGeneratorAPI: manifestsGeneratorAPI,
rp: newRefreshPreprocessor(log, hostAPI, operatorsApi),
hostAPI: hostAPI,
leaderElector: leaderElector,
prevMonitorInvokedAt: time.Now(),
ocmClient: ocmClient,
objectHandler: objectHandler,
dnsApi: dnsApi,
authHandler: authHandler,
uploadClient: uploadClient,
}
}
func (m *Manager) RegisterCluster(ctx context.Context, c *common.Cluster) error {
return m.registrationAPI.RegisterCluster(ctx, c)
}
func (m *Manager) RegisterAddHostsCluster(ctx context.Context, c *common.Cluster) error {
err := m.registrationAPI.RegisterAddHostsCluster(ctx, c)
if err != nil {
return err
}
eventgen.SendClusterRegistrationSucceededEvent(ctx, m.eventsHandler, *c.ID, models.ClusterKindAddHostsCluster)
return nil
}
func (m *Manager) RegisterAddHostsOCPCluster(c *common.Cluster, db *gorm.DB) error {
return m.registrationAPI.RegisterAddHostsOCPCluster(c, db)
}
func (m *Manager) DeregisterCluster(ctx context.Context, c *common.Cluster) error {
var metricsErr error
for _, h := range c.Hosts {
if err := m.hostAPI.ReportValidationFailedMetrics(ctx, h, c.OpenshiftVersion, c.EmailDomain); err != nil {
m.log.WithError(err).Errorf("Failed to report metrics for failed validations on host %s in cluster %s", h.ID, c.ID)
metricsErr = multierror.Append(metricsErr, err)
}
}
if err := m.reportValidationFailedMetrics(ctx, c, c.OpenshiftVersion, c.EmailDomain); err != nil {
m.log.WithError(err).Errorf("Failed to report metrics for failed validations on cluster %s", c.ID)
metricsErr = multierror.Append(metricsErr, err)
}
if metricsErr != nil {
return metricsErr
}
err := m.registrationAPI.DeregisterCluster(ctx, c)
if err != nil {
eventgen.SendClusterDeregisterFailedEvent(ctx, m.eventsHandler, *c.ID, err.Error())
} else {
eventgen.SendClusterDeregisteredEvent(ctx, m.eventsHandler, *c.ID)
}
return err
}
func (m *Manager) reportValidationFailedMetrics(ctx context.Context, c *common.Cluster, ocpVersion, emailDomain string) error {
log := logutil.FromContext(ctx, m.log)
if c.ValidationsInfo == "" {
log.Warnf("Cluster %s doesn't contain any validations info, cannot report metrics for that cluster", *c.ID)
return nil
}
var validationRes ValidationsStatus
if err := json.Unmarshal([]byte(c.ValidationsInfo), &validationRes); err != nil {
log.WithError(err).Errorf("Failed to unmarshal validations info from cluster %s", *c.ID)
return err
}
for _, vRes := range validationRes {
for _, v := range vRes {
if v.Status == ValidationFailure {
m.metricAPI.ClusterValidationFailed(models.ClusterValidationID(v.ID))
}
}
}
return nil
}
func (m *Manager) reportValidationStatusChanged(ctx context.Context, c *common.Cluster,
newValidationRes, currentValidationRes ValidationsStatus) {
for vCategory, vRes := range newValidationRes {
for _, v := range vRes {
if previousStatus, ok := m.getValidationStatus(currentValidationRes, vCategory, v.ID); ok {
if v.Status == ValidationFailure && previousStatus != ValidationFailure {
failureMessage := "failed"
if previousStatus == ValidationSuccess {
failureMessage = "that used to succeed is now failing"
m.metricAPI.ClusterValidationChanged(models.ClusterValidationID(v.ID))
}
eventgen.SendClusterValidationFailedEvent(ctx, m.eventsHandler, *c.ID, v.ID.String(), v.Message, failureMessage)
} else if v.Status == ValidationSuccess && previousStatus == ValidationFailure {
eventgen.SendClusterValidationFixedEvent(ctx, m.eventsHandler, *c.ID, v.ID.String(), v.Message)
} else if v.Status != previousStatus {
msg := fmt.Sprintf("Cluster %s: validation '%s' status changed from %s to %s",
*c.ID, v.ID.String(), previousStatus, v.Status)
m.eventsHandler.NotifyInternalEvent(ctx, c.ID, nil, nil, msg)
}
}
}
}
}
func (m *Manager) getValidationStatus(vs ValidationsStatus, category string, vID ValidationID) (ValidationStatus, bool) {
for _, v := range vs[category] {
if v.ID == vID {
return v.Status, true
}
}
return ValidationStatus(""), false
}
func GetValidations(c *common.Cluster) (ValidationsStatus, error) {
var currentValidationRes ValidationsStatus
if c.ValidationsInfo != "" {
if err := json.Unmarshal([]byte(c.ValidationsInfo), ¤tValidationRes); err != nil {
return ValidationsStatus{}, errors.Wrapf(err, "Failed to unmarshal validations info from cluster %s", *c.ID)
}
}
return currentValidationRes, nil
}
func (m *Manager) didValidationChanged(ctx context.Context, newValidationRes, currentValidationRes ValidationsStatus) bool {
if len(newValidationRes) == 0 {
// in order to be considered as a change, newValidationRes should not contain less data than currentValidations
return false
}
return !reflect.DeepEqual(newValidationRes, currentValidationRes)
}
func (m *Manager) updateValidationsInDB(ctx context.Context, db *gorm.DB, c *common.Cluster, newValidationRes ValidationsStatus) (*common.Cluster, error) {
b, err := json.Marshal(newValidationRes)
if err != nil {
return nil, err
}
return UpdateCluster(ctx, logutil.FromContext(ctx, m.log), db, m.stream, *c.ID, *c.Status, "validations_info", string(b))
}
func (m *Manager) RefreshStatus(ctx context.Context, c *common.Cluster, db *gorm.DB) (*common.Cluster, error) {
//new transition code
if db == nil {
db = m.db
}
cluster, err := common.GetClusterFromDBWithHosts(db, *c.ID)
if err != nil {
return nil, err
}
return m.refreshStatusInternal(ctx, cluster, db)
}
func (m *Manager) refreshStatusInternal(ctx context.Context, c *common.Cluster, db *gorm.DB) (*common.Cluster, error) {
//new transition code
if db == nil {
db = m.db
}
var (
vc *clusterPreprocessContext
err error
conditions map[string]bool
newValidationRes map[string][]ValidationResult
)
vc = newClusterValidationContext(c, db)
conditions, newValidationRes, err = m.rp.preprocess(ctx, vc)
if err != nil {
return c, err
}
currentValidationRes, err := GetValidations(c)
if err != nil {
return nil, err
}
if m.didValidationChanged(ctx, newValidationRes, currentValidationRes) {
// Validation status changes are detected when new validations are different from the
// current validations in the DB.
// For changes to be detected and reported correctly, the comparison needs to be
// performed before the new validations are updated to the DB.
m.reportValidationStatusChanged(ctx, c, newValidationRes, currentValidationRes)
if _, err = m.updateValidationsInDB(ctx, db, c, newValidationRes); err != nil {
return nil, err
}
}
args := &TransitionArgsRefreshCluster{
ctx: ctx,
db: db,
eventHandler: m.eventsHandler,
metricApi: m.metricAPI,
hostApi: m.hostAPI,
conditions: conditions,
validationResults: newValidationRes,
clusterAPI: m,
objectHandler: m.objectHandler,
ocmClient: m.ocmClient,
dnsApi: m.dnsApi,
}
err = m.sm.Run(TransitionTypeRefreshStatus, newStateCluster(vc.cluster), args)
if err != nil {
return nil, common.NewApiError(http.StatusConflict, err)
}
ret := args.updatedCluster
if ret == nil {
ret = c
}
return ret, err
}
func (m *Manager) SetUploadControllerLogsAt(ctx context.Context, c *common.Cluster, db *gorm.DB) error {
err := db.Model(&common.Cluster{}).Where("id = ?", c.ID.String()).Update("controller_logs_collected_at", strfmt.DateTime(time.Now())).Error
if err != nil {
return errors.Wrapf(err, "failed to set controller_logs_collected_at to cluster %s", c.ID.String())
}
return nil
}
func (m *Manager) GetMasterNodesIds(ctx context.Context, c *common.Cluster, db *gorm.DB) ([]*strfmt.UUID, error) {
return m.installationAPI.GetMasterNodesIds(ctx, c, db)
}
func (m *Manager) tryAssignMachineCidrDHCPMode(cluster *common.Cluster) error {
networks := network.GetInventoryNetworks(cluster.Hosts, m.log)
if len(networks) == 1 {
/*
* Auto assign machine network CIDR is relevant if there is only single host network. Otherwise the user
* has to select the machine network CIDR
*/
return UpdateMachineNetwork(m.db, cluster, []string{networks[0]})
}
return nil
}
func (m *Manager) tryAssignMachineCidrNonDHCPMode(cluster *common.Cluster) error {
primaryMachineNetwork, err := network.CalculateMachineNetworkCIDR(
network.GetApiVipById(cluster, 0), network.GetIngressVipById(cluster, 0), cluster.Hosts, false)
if err != nil {
return err
} else if primaryMachineNetwork == "" && network.CheckIfClusterIsDualStack(cluster) {
// This function is running inside the monitoring loop, therefore it only relates to
// cases when we autocalculate Machine Networks. In case we run it against a cluster with
// no hosts, it will remove currently configured entries (provided e.g. in the creation
// payload). In order to prevent this, for a cluster with no hosts we return without any
// modifications.
return nil
}
secondaryMachineNetwork, err := network.CalculateMachineNetworkCIDR(
network.GetApiVipById(cluster, 1), network.GetIngressVipById(cluster, 1), cluster.Hosts, false)
if err != nil {
return err
}
// The condition below is preventing a scenario where a cluster has 2 Machine Networks
// configured manually, but we can only autocalculate the first one. We need to prevent the
// case where we would transparently remove the second network. Therefore we will skip if the
// following happens
// * autocalculated 1st machine network is the same as currently configured, and
// * autocalculated 2nd machine network is empty or the same as currently configured
if primaryMachineNetwork == network.GetMachineCidrById(cluster, 0) &&
(secondaryMachineNetwork == "" || secondaryMachineNetwork == network.GetMachineCidrById(cluster, 1)) {
return nil
}
return UpdateMachineNetwork(m.db, cluster, []string{primaryMachineNetwork, secondaryMachineNetwork})
}
func (m *Manager) tryAssignMachineCidrSNO(cluster *common.Cluster) error {
if network.IsMachineCidrAvailable(cluster) {
return nil
}
clusterFamilies, err := network.CidrsToAddressFamilies(network.GetClusterNetworkCidrs(cluster))
if err != nil {
return err
}
clusterFamilies = network.CanonizeAddressFamilies(clusterFamilies)
serviceFamilies, err := network.CidrsToAddressFamilies(network.GetServiceNetworkCidrs(cluster))
if err != nil {
return err
}
if reflect.DeepEqual(clusterFamilies, serviceFamilies) {
var pendingCidrs []string
cidrsByFamily, err := network.GetInventoryNetworksByFamily(cluster.Hosts, m.log)
if err != nil {
return err
}
for _, family := range clusterFamilies {
familyCidrs := cidrsByFamily[family]
switch len(familyCidrs) {
case 0:
return nil
case 1:
pendingCidrs = append(pendingCidrs, familyCidrs[0])
default:
// multiple cidrs are available: select the one that matches
// the best defaul route
defaultCidrByFamily, err := network.GetDefaultRouteNetworkByFamily(cluster.Hosts[0], cidrsByFamily, m.log)
if err != nil {
return err
}
if defaultCidr, ok := defaultCidrByFamily[family]; ok {
pendingCidrs = append(pendingCidrs, defaultCidr)
} else {
return fmt.Errorf("missing default cidr for %s", family.String())
}
}
}
return UpdateMachineNetwork(m.db, cluster, pendingCidrs)
}
return nil
}
func (m *Manager) autoAssignMachineNetworkCidr(c *common.Cluster) error {
if !funk.ContainsString([]string{models.ClusterStatusPendingForInput, models.ClusterStatusInsufficient}, swag.StringValue(c.Status)) {
return nil
}
/*
* This handles two cases: Auto assign for DHCP mode when there is a single host network in cluster and in non DHCP mode
* when at least one of the VIPs is defined.
* In DHCP mode the aim is to get from DB only clusters that are candidates for machine network CIDR auto assign
* The cluster query is for clusters that have their DHCP mode set (vip_dhcp_allocation), the machine network CIDR empty, and in status insufficient, or pending for input.
* In the SNO case, machine networks are set in case that the machine CIDR is not set yet, and the address families of the service and cluster networks are the same,
* and the available networks to be set as machine network each have single CIDR.
*/
var err error
if swag.BoolValue(c.VipDhcpAllocation) {
err = m.tryAssignMachineCidrDHCPMode(c)
} else if swag.StringValue(c.HighAvailabilityMode) == models.ClusterHighAvailabilityModeNone {
err = m.tryAssignMachineCidrSNO(c)
} else if !swag.BoolValue(c.UserManagedNetworking) {
err = m.tryAssignMachineCidrNonDHCPMode(c)
}
if err != nil {
m.log.WithError(err).Warnf("Set machine cidr for cluster %s. dhcp mode %q user managed networking mode: %q",
c.ID.String(), strconv.FormatBool(swag.BoolValue(c.VipDhcpAllocation)), strconv.FormatBool(swag.BoolValue(c.UserManagedNetworking)))
}
return err
}
func (m *Manager) shouldTriggerLeaseTimeoutEvent(c *common.Cluster, curMonitorInvokedAt time.Time) bool {
notAllowedStates := []string{models.ClusterStatusInstalled, models.ClusterStatusError, models.ClusterStatusCancelled}
if funk.Contains(notAllowedStates, *c.Status) {
return false
}
timeToCompare := c.MachineNetworkCidrUpdatedAt.Add(DhcpLeaseTimeoutMinutes * time.Minute)
return swag.BoolValue(c.VipDhcpAllocation) && (network.GetApiVipById(c, 0) == "" || network.GetIngressVipById(c, 0) == "") && network.IsMachineCidrAvailable(c) &&
(m.prevMonitorInvokedAt.Before(timeToCompare) || m.prevMonitorInvokedAt.Equal(timeToCompare)) &&
curMonitorInvokedAt.After(timeToCompare)
}
func (m *Manager) triggerLeaseTimeoutEvent(ctx context.Context, c *common.Cluster) {
eventgen.SendApiIngressVipTimedOutEvent(ctx, m.eventsHandler, *c.ID, DhcpLeaseTimeoutMinutes)
}
func (m *Manager) SkipMonitoring(c *common.Cluster) bool {
// logs required monitoring on error state until IsLogCollectionTimedOut move the logs state to timeout,
// or remote controllers reports that their log colection has been completed. Then, monitoring should be
// stopped to avoid excessive computation
skipMonitoringStates := []string{string(models.LogsStateCompleted), string(models.LogsStateTimeout)}
result := ((swag.StringValue(c.Status) == models.ClusterStatusError || swag.StringValue(c.Status) == models.ClusterStatusCancelled) &&
funk.Contains(skipMonitoringStates, c.LogsInfo))
return result
}
func (m *Manager) initMonitorQueryGenerator() {
if m.monitorQueryGenerator == nil {
buildInitialQuery := func(db *gorm.DB) *gorm.DB {
noNeedToMonitorInStates := []string{
models.ClusterStatusInstalled,
}
dbWithCondition := common.LoadTableFromDB(db, common.HostsTable)
dbWithCondition = common.LoadClusterTablesFromDB(dbWithCondition, common.HostsTable)
dbWithCondition = dbWithCondition.Where("status NOT IN (?)", noNeedToMonitorInStates)
return dbWithCondition
}
m.monitorQueryGenerator = common.NewMonitorQueryGenerator(m.db, buildInitialQuery, m.MonitorBatchSize)
}
}
func (m *Manager) ClusterMonitoring() {
if !m.leaderElector.IsLeader() {
m.log.Debugf("Not a leader, exiting ClusterMonitoring")
return
}
m.log.Debugf("Running ClusterMonitoring")
defer commonutils.MeasureOperation("ClusterMonitoring", m.log, m.metricAPI)()
var (
offset int
limit = m.MonitorBatchSize
monitored int64
clusters []*common.Cluster
clusterAfterRefresh *common.Cluster
requestID = requestid.NewID()
ctx = requestid.ToContext(context.Background(), requestID)
log = requestid.RequestIDLogger(m.log, requestID)
err error
)
curMonitorInvokedAt := time.Now()
defer func() {
m.prevMonitorInvokedAt = curMonitorInvokedAt
}()
//no need to refresh cluster status if the cluster is in the following statuses
//when cluster is in error. it should be still monitored until all the logs are collected.
//Then, SkipMonitoring() stops the logic from running forever
m.initMonitorQueryGenerator()
query := m.monitorQueryGenerator.NewClusterQuery()
for {
clusters, err = query.Next()
if err != nil {
log.WithError(err).Errorf("failed to get clusters")
return
}
if len(clusters) == 0 {
break
}
m.log.Debugf("We are going to monitor %d, query is: %+v", len(clusters), query)
for _, cluster := range clusters {
if !m.leaderElector.IsLeader() {
m.log.Debugf("Not a leader, exiting ClusterMonitoring")
return
}
if !m.SkipMonitoring(cluster) {
monitored += 1
_ = m.autoAssignMachineNetworkCidr(cluster)
if err = m.setConnectivityMajorityGroupsForClusterInternal(cluster, m.db); err != nil {
log.WithError(err).Error("failed to set majority group for clusters")
}
err = m.detectAndStoreCollidingIPsForCluster(cluster, m.db)
if err != nil {
m.log.WithError(err).Errorf("Failed to detect and store colliding IPs for cluster %s", cluster.ID.String())
}
clusterAfterRefresh, err = m.refreshStatusInternal(ctx, cluster, m.db)
if err != nil {
log.WithError(err).Errorf("failed to refresh cluster %s state", cluster.ID)
continue
}
if swag.StringValue(clusterAfterRefresh.Status) != swag.StringValue(cluster.Status) {
log.Infof("cluster %s updated status from %s to %s via monitor", cluster.ID,
swag.StringValue(cluster.Status), swag.StringValue(clusterAfterRefresh.Status))
}
if m.shouldTriggerLeaseTimeoutEvent(cluster, curMonitorInvokedAt) {
m.triggerLeaseTimeoutEvent(ctx, cluster)
}
}
}
offset += limit
}
m.log.Debugf("Monitored %d clusters", monitored)
m.metricAPI.MonitoredClusterCount(monitored)
}
func CanDownloadFiles(c *common.Cluster) (err error) {
clusterStatus := swag.StringValue(c.Status)
allowedStatuses := []string{
models.ClusterStatusInstalling,
models.ClusterStatusFinalizing,
models.ClusterStatusInstalled,
models.ClusterStatusError,
models.ClusterStatusAddingHosts,
models.ClusterStatusCancelled,
models.ClusterStatusInstallingPendingUserAction,
}
if !funk.Contains(allowedStatuses, clusterStatus) {
err = errors.Errorf("cluster %s is in %s state, files can be downloaded only when status is one of: %s",
c.ID, clusterStatus, allowedStatuses)
}
return err
}
func CanDownloadKubeconfig(c *common.Cluster) (err error) {
clusterStatus := swag.StringValue(c.Status)
allowedStatuses := []string{
models.ClusterStatusFinalizing,
models.ClusterStatusInstalled,
models.ClusterStatusError,
models.ClusterStatusAddingHosts,
models.ClusterStatusCancelled,
models.ClusterStatusInstallingPendingUserAction,
}
if !funk.Contains(allowedStatuses, clusterStatus) {
err = errors.Errorf("cluster %s is in %s state, %s can be downloaded only when status is one of: %s",
c.ID, clusterStatus, constants.Kubeconfig, allowedStatuses)
}
return err
}
func (m *Manager) IsOperatorMonitored(c *common.Cluster, operatorName string) bool {
for _, o := range c.MonitoredOperators {
if o.Name == operatorName {
return true
}
}
return false
}
func (m *Manager) IsOperatorAvailable(c *common.Cluster, operatorName string) bool {
// TODO: MGMT-4458
// Backward-compatible solution for clusters that don't have monitored operators data
if len(c.MonitoredOperators) == 0 {
clusterStatus := swag.StringValue(c.Status)
allowedStatuses := []string{models.ClusterStatusInstalling, models.ClusterStatusFinalizing, models.ClusterStatusInstalled}
return funk.ContainsString(allowedStatuses, clusterStatus)
}
for _, o := range c.MonitoredOperators {
if o.Name == operatorName {
return o.Status == models.OperatorStatusAvailable
}
}
return false
}
func (m *Manager) UploadIngressCert(c *common.Cluster) (err error) {
clusterStatus := swag.StringValue(c.Status)
allowedStatuses := []string{models.ClusterStatusFinalizing, models.ClusterStatusInstalled}
if !funk.ContainsString(allowedStatuses, clusterStatus) {
err = errors.Errorf("Cluster %s is in %s state, upload ingress ca can be done only in %s or %s state", c.ID, clusterStatus, models.ClusterStatusFinalizing, models.ClusterStatusInstalled)
}
return err
}
func (m *Manager) AcceptRegistration(c *common.Cluster) (err error) {
clusterStatus := swag.StringValue(c.Status)
allowedStatuses := []string{models.ClusterStatusInsufficient, models.ClusterStatusReady, models.ClusterStatusPendingForInput, models.ClusterStatusAddingHosts}
if !funk.ContainsString(allowedStatuses, clusterStatus) {
if clusterStatus == models.ClusterStatusInstalled {
msg := "Cannot add hosts to an existing cluster using the original Discovery ISO."
isSaaS := m.authHandler.AuthType() == auth.TypeRHSSO
if isSaaS {
msg = msg + " Try to add new hosts by using the Discovery ISO that can be found in console.redhat.com under your cluster “Add hosts“ tab."
}
err = errors.Errorf(msg)
} else {
err = errors.Errorf("Host can register only in one of the following states: %s", allowedStatuses)
}
}
return err
}
func (m *Manager) VerifyClusterUpdatability(c *common.Cluster) (err error) {
clusterStatus := swag.StringValue(c.Status)
allowedStatuses := []string{models.ClusterStatusInsufficient, models.ClusterStatusReady, models.ClusterStatusPendingForInput, models.ClusterStatusAddingHosts}
if !funk.ContainsString(allowedStatuses, clusterStatus) {
err = errors.Errorf("Cluster %s is in %s state, cluster can be updated only in one of %s", c.ID, clusterStatus, allowedStatuses)
}
return err
}
func (m *Manager) CancelInstallation(ctx context.Context, c *common.Cluster, reason string, db *gorm.DB) *common.ApiErrorResponse {
lastState := newStateCluster(c)
isFailed := false
var err error
installationStates := []string{
models.ClusterStatusPreparingForInstallation, models.ClusterStatusInstalling, models.ClusterStatusFinalizing}
defer func() {
if !isFailed {
eventgen.SendClusterInstallationCanceledEvent(ctx, m.eventsHandler, *c.ID)
} else {
eventgen.SendCancelInstallationFailedEvent(ctx, m.eventsHandler, *c.ID, err.Error())
}
//metrics for cancel as final state are calculated only when the transition to cancel was made
//from one of the installing states
if funk.Contains(installationStates, lastState.srcState) {
m.metricAPI.ClusterInstallationFinished(ctx, models.ClusterStatusCancelled, lastState.srcState, c.OpenshiftVersion, *c.ID, c.EmailDomain, c.InstallStartedAt)
}
}()
err = m.sm.Run(TransitionTypeCancelInstallation, lastState, &TransitionArgsCancelInstallation{
ctx: ctx,
reason: reason,
db: db,
})
if err != nil {
isFailed = true
return common.NewApiError(http.StatusConflict, err)
}
return nil
}
func (m *Manager) UpdateLogsProgress(ctx context.Context, c *common.Cluster, progress string) error {
err := updateLogsProgress(logutil.FromContext(ctx, m.log), m.db, c, progress)
return err
}
func (m *Manager) UpdateInstallProgress(ctx context.Context, clusterID strfmt.UUID) error {
log := logutil.FromContext(ctx, m.log)
cluster, err := common.GetClusterFromDB(m.db, clusterID, common.SkipEagerLoading)
if err != nil {
log.WithError(err).Error("Failed to get cluster from DB")
return err
}
// day2 cluster isn't a real cluster and doesn't have a real progress
if *cluster.Kind == models.ClusterKindAddHostsCluster {
return nil
}
var hostsCount []struct {
Count int
Role models.HostRole
Bootstrap bool
CurrentStage models.HostStage
}
err = m.db.Table("hosts").Select("count(*) as count, role, bootstrap, progress_current_stage as current_stage").
Group("role").Group("bootstrap").Group("current_stage").Where("cluster_id = ?", clusterID.String()).
Scan(&hostsCount).Error
if err != nil {
log.WithError(err).Error("Failed to host count from DB")
return err
}
isSno := swag.StringValue(cluster.HighAvailabilityMode) == models.ClusterHighAvailabilityModeNone
var totalHostsDoneStages, totalHostsStages float64
for _, h := range hostsCount {
stages := host.FindMatchingStages(h.Role, h.Bootstrap, isSno)
currentIndex := m.hostAPI.IndexOfStage(h.CurrentStage, stages)
totalHostsDoneStages += float64((currentIndex + 1) * h.Count)
totalHostsStages += float64(len(stages) * h.Count)
}
installingStagePercentage := int64((totalHostsDoneStages / totalHostsStages) * 100)
var totalPercentage int64
if swag.StringValue(cluster.Status) == models.ClusterStatusInstalled {
//if the cluster is in INSTALLED stage, force the progress bar to reach 100%
//even if there are hosts that are not ready yet
totalPercentage = int64(100)
} else {
totalPercentage = int64(common.ProgressWeightInstallingStage * float64(installingStagePercentage))
if cluster.Progress != nil {
totalPercentage += int64(common.ProgressWeightPreparingForInstallationStage*float64(cluster.Progress.PreparingForInstallationStagePercentage) +
common.ProgressWeightFinalizingStage*float64(cluster.Progress.FinalizingStagePercentage))
}
}
updates := map[string]interface{}{
"progress_installing_stage_percentage": installingStagePercentage,
"progress_total_percentage": totalPercentage,
}
return m.db.Model(&common.Cluster{}).Where("id = ?", cluster.ID.String()).UpdateColumns(updates).Error
}
func (m *Manager) UpdateFinalizingProgress(ctx context.Context, db *gorm.DB, clusterID strfmt.UUID) error {
log := logutil.FromContext(ctx, m.log)
cluster, err := common.GetClusterFromDB(common.LoadTableFromDB(db, common.MonitoredOperatorsTable), clusterID, common.SkipEagerLoading)
if err != nil {
log.WithError(err).Error("Failed to get cluster from DB")
return err
}
var doneOperatorsCount float64
for _, o := range cluster.MonitoredOperators {
// built in operators must succeed
if o.OperatorType == models.OperatorTypeBuiltin && o.Status == models.OperatorStatusAvailable {
doneOperatorsCount++
log.Debugf("cluster %s: incremented doneOperatorsCount to %.2f. %s operator %s reached status %s",
clusterID.String(), doneOperatorsCount, o.OperatorType, o.Name, o.Status)
}
// failing OLM operators will lead to a degraded cluster but are still considered as a progress
if o.OperatorType == models.OperatorTypeOlm && (o.Status == models.OperatorStatusAvailable || o.Status == models.OperatorStatusFailed) {
doneOperatorsCount++
log.Debugf("cluster %s: incremented doneOperatorsCount to %.2f. %s operator %s reached status %s",
clusterID.String(), doneOperatorsCount, o.OperatorType, o.Name, o.Status)
}
}
finalizingStagePercentage := int64((doneOperatorsCount / float64(len(cluster.MonitoredOperators))) * 100)
totalPercentage := int64(common.ProgressWeightFinalizingStage * float64(finalizingStagePercentage))
if cluster.Progress != nil {
totalPercentage += int64(common.ProgressWeightPreparingForInstallationStage*float64(cluster.Progress.PreparingForInstallationStagePercentage) +
common.ProgressWeightInstallingStage*float64(cluster.Progress.InstallingStagePercentage))
}
if cluster.Progress != nil && totalPercentage < cluster.Progress.TotalPercentage {
log.Debugf(
"cluster %s: skipping progress_total_percentage update.The new progress_total_percentage is:"+
" %d, which is lower then the current cluster progress_total_percentage: %d",
clusterID.String(), totalPercentage, cluster.Progress.TotalPercentage)
return nil
}
updates := map[string]interface{}{
"progress_finalizing_stage_percentage": finalizingStagePercentage,
"progress_total_percentage": totalPercentage,
}
if finalizingStagePercentage == 100 {
updates["trigger_monitor_timestamp"] = time.Now()
}
return db.Model(&common.Cluster{}).Where("id = ?", cluster.ID.String()).UpdateColumns(updates).Error
}
func (m *Manager) UpdateAmsSubscriptionID(ctx context.Context, clusterID, amsSubscriptionID strfmt.UUID) *common.ApiErrorResponse {
log := logutil.FromContext(ctx, m.log)
if err := m.db.Model(&common.Cluster{}).Where("id = ?", clusterID.String()).Update("ams_subscription_id", amsSubscriptionID).Error; err != nil {
log.WithError(err).Errorf("Failed to patch DB with AMS subscription ID for cluster %v", clusterID)
return common.NewApiError(http.StatusInternalServerError, err)
}
return nil
}
func (m *Manager) ResetCluster(ctx context.Context, c *common.Cluster, reason string, db *gorm.DB) *common.ApiErrorResponse {
isFailed := false
var err error
defer func() {
if !isFailed {
eventgen.SendClusterInstallationResetEvent(ctx, m.eventsHandler, *c.ID)
} else {
eventgen.SendResetInstallationFailedEvent(ctx, m.eventsHandler, *c.ID, err.Error())
}
}()
err = m.sm.Run(TransitionTypeResetCluster, newStateCluster(c), &TransitionArgsResetCluster{
ctx: ctx,
reason: reason,
db: db,
})
if err != nil {
isFailed = true
return common.NewApiError(http.StatusConflict, err)
}
return nil
}
func (m *Manager) PrepareForInstallation(ctx context.Context, c *common.Cluster, db *gorm.DB) error {
err := m.sm.Run(TransitionTypePrepareForInstallation, newStateCluster(c),
&TransitionArgsPrepareForInstallation{
ctx: ctx,
db: db,
manifestsGenerator: m.manifestsGeneratorAPI,
metricApi: m.metricAPI,
},
)
return err
}
func (m *Manager) UploadEvents() {
if !m.leaderElector.IsLeader() {
m.log.Infof("Not a leader, exiting upload")
return
}
if !m.uploadClient.IsEnabled() {
m.log.Infof("Event uploading is not enabled")
return
}
m.log.Info("Event upload is enabled. Running event upload")
var (
requestID = requestid.NewID()
ctx = requestid.ToContext(context.Background(), requestID)
log = requestid.RequestIDLogger(m.log, requestID)
err error
)
clustersToUpload, err := common.GetClustersFromDBWhere(m.db, common.SkipEagerLoading, common.SkipDeletedRecords,
"uploaded = ? AND (status in (?) OR (status = ? AND install_completed_at > ?))",
false, []string{models.ClusterStatusInstalled, models.ClusterStatusCancelled, models.ClusterStatusError},
models.ClusterStatusAddingHosts, strfmt.NewDateTime())
if err != nil {
log.WithError(err).Warnf("failed getting clusters for uploading events")
return
}
clustersUploaded := 0
for _, cluster := range clustersToUpload {
if !m.leaderElector.IsLeader() {
log.Info("not a leader, exiting event uploader")
return
}
if uploadErr := m.uploadClient.UploadEvents(ctx, cluster, m.eventsHandler); uploadErr != nil {
log.WithError(uploadErr).Warnf("failed uploading events for cluster %s", cluster.ID)
continue
}
log.Infof("successfully uploaded events for cluster %s", *cluster.ID)
if err = m.db.Model(&common.Cluster{}).Where("id = ?", cluster.ID.String()).Update("uploaded", true).Error; err != nil {
log.WithError(err).Warnf("couldn't update uploaded field for cluster %s in db", cluster.ID.String())
}
clustersUploaded++
}
log.Debugf("Uploaded events for %d clusters", clustersUploaded)
}
func (m *Manager) HandlePreInstallError(ctx context.Context, c *common.Cluster, installErr error) {
log := logutil.FromContext(ctx, m.log)
log.WithError(installErr).Warnf("Failed to prepare installation of cluster %s", c.ID.String())
err := m.db.Model(&common.Cluster{}).Where("id = ?", c.ID.String()).Updates(&common.Cluster{
InstallationPreparationCompletionStatus: common.InstallationPreparationFailed,
}).Error
if err != nil {
log.WithError(err).Errorf("Failed to handle pre installation error for cluster %s", c.ID.String())
} else {
log.Infof("Successfully handled pre-installation error, cluster %s", c.ID.String())
eventgen.SendPrepareInstallationFailedEvent(ctx, m.eventsHandler, *c.ID, installErr.Error())
}
}
func (m *Manager) HandlePreInstallSuccess(ctx context.Context, c *common.Cluster) {
log := logutil.FromContext(ctx, m.log)
err := m.db.Model(&common.Cluster{}).Where("id = ?", c.ID.String()).Updates(&common.Cluster{
InstallationPreparationCompletionStatus: common.InstallationPreparationSucceeded,
}).Error