/
inventory.go
6541 lines (5688 loc) · 262 KB
/
inventory.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 bminventory
import (
"bytes"
"context"
"crypto/md5" // #nosec
"crypto/x509"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"runtime"
"runtime/debug"
"strings"
"time"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/google/uuid"
"github.com/hashicorp/go-version"
"github.com/kennygrant/sanitize"
clusterPkg "github.com/openshift/assisted-service/internal/cluster"
"github.com/openshift/assisted-service/internal/cluster/validations"
"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/featuresupport"
"github.com/openshift/assisted-service/internal/garbagecollector"
"github.com/openshift/assisted-service/internal/gencrypto"
"github.com/openshift/assisted-service/internal/hardware"
"github.com/openshift/assisted-service/internal/host"
"github.com/openshift/assisted-service/internal/host/hostcommands"
"github.com/openshift/assisted-service/internal/host/hostutil"
"github.com/openshift/assisted-service/internal/ignition"
"github.com/openshift/assisted-service/internal/infraenv"
installcfgdata "github.com/openshift/assisted-service/internal/installcfg"
installcfg "github.com/openshift/assisted-service/internal/installcfg/builder"
"github.com/openshift/assisted-service/internal/isoeditor"
"github.com/openshift/assisted-service/internal/manifests"
"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/operators/lvm"
"github.com/openshift/assisted-service/internal/provider"
"github.com/openshift/assisted-service/internal/provider/registry"
"github.com/openshift/assisted-service/internal/stream"
"github.com/openshift/assisted-service/internal/usage"
"github.com/openshift/assisted-service/internal/versions"
"github.com/openshift/assisted-service/models"
"github.com/openshift/assisted-service/pkg/auth"
ctxparams "github.com/openshift/assisted-service/pkg/context"
"github.com/openshift/assisted-service/pkg/filemiddleware"
"github.com/openshift/assisted-service/pkg/generator"
"github.com/openshift/assisted-service/pkg/k8sclient"
"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/s3wrapper"
"github.com/openshift/assisted-service/pkg/staticnetworkconfig"
"github.com/openshift/assisted-service/pkg/transaction"
pkgvalidations "github.com/openshift/assisted-service/pkg/validations"
"github.com/openshift/assisted-service/restapi/operations/installer"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
"gopkg.in/yaml.v2"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"k8s.io/apimachinery/pkg/apis/meta/v1/validation"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/client-go/tools/clientcmd"
)
const DefaultUser = "kubeadmin"
const WindowBetweenRequestsInSeconds = 10 * time.Second
const (
MediaDisconnected int64 = 256
// 125 is the generic exit code for cases the error is in podman / docker and not the container we tried to run
ContainerAlreadyRunningExitCode = 125
// The following constants are controlling the script type served for iPXE
// Always boot the discovery ISO when using iPXE
DiscoveryImageAlways = "discovery-image-always"
// Apply boot order control when using iPXE
BootOrderControl = "boot-order-control"
)
type Config struct {
ignition.IgnitionConfig
AgentDockerImg string `envconfig:"AGENT_DOCKER_IMAGE" default:"quay.io/edge-infrastructure/assisted-installer-agent:latest"`
ServiceBaseURL string `envconfig:"SERVICE_BASE_URL"`
ImageServiceBaseURL string `envconfig:"IMAGE_SERVICE_BASE_URL"`
ServiceCACertPath string `envconfig:"SERVICE_CA_CERT_PATH" default:""`
S3EndpointURL string `envconfig:"S3_ENDPOINT_URL" default:"http://10.35.59.36:30925"`
S3Bucket string `envconfig:"S3_BUCKET" default:"test"`
ImageExpirationTime time.Duration `envconfig:"IMAGE_EXPIRATION_TIME" default:"4h"`
AwsAccessKeyID string `envconfig:"AWS_ACCESS_KEY_ID" default:"accessKey1"`
AwsSecretAccessKey string `envconfig:"AWS_SECRET_ACCESS_KEY" default:"verySecretKey1"`
BaseDNSDomains map[string]string `envconfig:"BASE_DNS_DOMAINS" default:""`
SkipCertVerification bool `envconfig:"SKIP_CERT_VERIFICATION" default:"false"`
InstallRHCa bool `envconfig:"INSTALL_RH_CA" default:"false"`
RhQaRegCred string `envconfig:"REGISTRY_CREDS" default:""`
AgentTimeoutStart time.Duration `envconfig:"AGENT_TIMEOUT_START" default:"3m"`
ServiceIPs string `envconfig:"SERVICE_IPS" default:""`
DefaultNTPSource string `envconfig:"NTP_DEFAULT_SERVER"`
ISOCacheDir string `envconfig:"ISO_CACHE_DIR" default:"/tmp/isocache"`
DefaultClusterNetworkCidr string `envconfig:"CLUSTER_NETWORK_CIDR" default:"10.128.0.0/14"`
DefaultClusterNetworkHostPrefix int64 `envconfig:"CLUSTER_NETWORK_HOST_PREFIX" default:"23"`
DefaultClusterNetworkCidrIPv6 string `envconfig:"CLUSTER_NETWORK_CIDR_IPV6" default:"fd01::/48"`
DefaultClusterNetworkHostPrefixIPv6 int64 `envconfig:"CLUSTER_NETWORK_HOST_PREFIX_IPV6" default:"64"`
DefaultServiceNetworkCidr string `envconfig:"SERVICE_NETWORK_CIDR" default:"172.30.0.0/16"`
DefaultServiceNetworkCidrIPv6 string `envconfig:"SERVICE_NETWORK_CIDR_IPV6" default:"fd02::/112"`
ISOImageType string `envconfig:"ISO_IMAGE_TYPE" default:"full-iso"`
IPv6Support bool `envconfig:"IPV6_SUPPORT" default:"true"`
DiskEncryptionSupport bool `envconfig:"DISK_ENCRYPTION_SUPPORT" default:"true"`
// InfraEnv ID for the ephemeral installer. Should not be set explicitly.Ephemeral (agent) installer sets this env var
InfraEnvID strfmt.UUID `envconfig:"INFRA_ENV_ID" default:""`
}
const minimalOpenShiftVersionForSingleNode = "4.8.0-0.0"
const minimalOpenShiftVersionForDefaultNetworkTypeOVNKubernetes = "4.12.0-0.0"
const minimalOpenShiftVersionForConsoleCapability = "4.12.0-0.0"
const minimalOpenShiftVersionForNutanix = "4.11.0-0.0"
type Interactivity bool
const (
Interactive Interactivity = true
NonInteractive Interactivity = false
)
type OCPClusterAPI interface {
RegisterOCPCluster(ctx context.Context) error
}
//go:generate mockgen --build_flags=--mod=mod -package bminventory -destination mock_installer_internal.go . InstallerInternals
type InstallerInternals interface {
RegisterClusterInternal(ctx context.Context, kubeKey *types.NamespacedName, params installer.V2RegisterClusterParams) (*common.Cluster, error)
GetClusterInternal(ctx context.Context, params installer.V2GetClusterParams) (*common.Cluster, error)
UpdateClusterNonInteractive(ctx context.Context, params installer.V2UpdateClusterParams) (*common.Cluster, error)
GetClusterByKubeKey(key types.NamespacedName) (*common.Cluster, error)
GetHostByKubeKey(key types.NamespacedName) (*common.Host, error)
InstallClusterInternal(ctx context.Context, params installer.V2InstallClusterParams) (*common.Cluster, error)
DeregisterClusterInternal(ctx context.Context, cluster *common.Cluster) error
V2DeregisterHostInternal(ctx context.Context, params installer.V2DeregisterHostParams, interactivity Interactivity) error
GetCommonHostInternal(ctx context.Context, infraEnvId string, hostId string) (*common.Host, error)
UpdateHostApprovedInternal(ctx context.Context, infraEnvId string, hostId string, approved bool) error
V2UpdateHostInstallerArgsInternal(ctx context.Context, params installer.V2UpdateHostInstallerArgsParams) (*models.Host, error)
V2UpdateHostIgnitionInternal(ctx context.Context, params installer.V2UpdateHostIgnitionParams) (*models.Host, error)
GetCredentialsInternal(ctx context.Context, params installer.V2GetCredentialsParams) (*models.Credentials, error)
V2DownloadClusterFilesInternal(ctx context.Context, params installer.V2DownloadClusterFilesParams) (io.ReadCloser, int64, error)
V2DownloadClusterCredentialsInternal(ctx context.Context, params installer.V2DownloadClusterCredentialsParams) (io.ReadCloser, int64, error)
V2ImportClusterInternal(ctx context.Context, kubeKey *types.NamespacedName, id *strfmt.UUID, params installer.V2ImportClusterParams) (*common.Cluster, error)
InstallSingleDay2HostInternal(ctx context.Context, clusterId strfmt.UUID, infraEnvId strfmt.UUID, hostId strfmt.UUID) error
UpdateClusterInstallConfigInternal(ctx context.Context, params installer.V2UpdateClusterInstallConfigParams) (*common.Cluster, error)
CancelInstallationInternal(ctx context.Context, params installer.V2CancelInstallationParams) (*common.Cluster, error)
TransformClusterToDay2Internal(ctx context.Context, clusterID strfmt.UUID) (*common.Cluster, error)
GetClusterSupportedPlatformsInternal(ctx context.Context, params installer.GetClusterSupportedPlatformsParams) (*[]models.PlatformType, error)
V2UpdateHostInternal(ctx context.Context, params installer.V2UpdateHostParams, interactivity Interactivity) (*common.Host, error)
GetInfraEnvByKubeKey(key types.NamespacedName) (*common.InfraEnv, error)
UpdateInfraEnvInternal(ctx context.Context, params installer.UpdateInfraEnvParams, internalIgnitionConfig *string) (*common.InfraEnv, error)
RegisterInfraEnvInternal(ctx context.Context, kubeKey *types.NamespacedName, params installer.RegisterInfraEnvParams) (*common.InfraEnv, error)
DeregisterInfraEnvInternal(ctx context.Context, params installer.DeregisterInfraEnvParams) error
UnbindHostInternal(ctx context.Context, params installer.UnbindHostParams, reclaimHost bool, interactivity Interactivity) (*common.Host, error)
BindHostInternal(ctx context.Context, params installer.BindHostParams) (*common.Host, error)
GetInfraEnvHostsInternal(ctx context.Context, infraEnvId strfmt.UUID) ([]*common.Host, error)
GetKnownHostApprovedCounts(clusterID strfmt.UUID) (registered, approved int, err error)
HostWithCollectedLogsExists(clusterId strfmt.UUID) (bool, error)
GetKnownApprovedHosts(clusterId strfmt.UUID) ([]*common.Host, error)
ValidatePullSecret(secret string, username string) error
GetInfraEnvInternal(ctx context.Context, params installer.GetInfraEnvParams) (*common.InfraEnv, error)
V2UpdateHostInstallProgressInternal(ctx context.Context, params installer.V2UpdateHostInstallProgressParams) error
}
//go:generate mockgen --build_flags=--mod=mod -package bminventory -destination mock_crd_utils.go . CRDUtils
type CRDUtils interface {
CreateAgentCR(ctx context.Context, log logrus.FieldLogger, hostId string, infraenv *common.InfraEnv, cluster *common.Cluster) error
}
type bareMetalInventory struct {
Config
db *gorm.DB
stream stream.Notifier
log logrus.FieldLogger
hostApi host.API
clusterApi clusterPkg.API
infraEnvApi infraenv.API
dnsApi dns.DNSApi
eventsHandler eventsapi.Handler
objectHandler s3wrapper.API
metricApi metrics.API
usageApi usage.API
operatorManagerApi operators.API
generator generator.ISOInstallConfigGenerator
authHandler auth.Authenticator
authzHandler auth.Authorizer
k8sClient k8sclient.K8SClient
ocmClient *ocm.Client
leaderElector leader.Leader
secretValidator validations.PullSecretValidator
versionsHandler versions.Handler
osImages versions.OSImages
crdUtils CRDUtils
IgnitionBuilder ignition.IgnitionBuilder
hwValidator hardware.Validator
installConfigBuilder installcfg.InstallConfigBuilder
staticNetworkConfig staticnetworkconfig.StaticNetworkConfig
gcConfig garbagecollector.Config
providerRegistry registry.ProviderRegistry
insecureIPXEURLs bool
}
func NewBareMetalInventory(
db *gorm.DB,
stream stream.Notifier,
log logrus.FieldLogger,
hostApi host.API,
clusterApi clusterPkg.API,
infraEnvApi infraenv.API,
cfg Config,
generator generator.ISOInstallConfigGenerator,
eventsHandler eventsapi.Handler,
objectHandler s3wrapper.API,
metricApi metrics.API,
usageApi usage.API,
operatorManagerApi operators.API,
authHandler auth.Authenticator,
authzHandler auth.Authorizer,
k8sClient k8sclient.K8SClient,
ocmClient *ocm.Client,
leaderElector leader.Leader,
pullSecretValidator validations.PullSecretValidator,
versionsHandler versions.Handler,
osImages versions.OSImages,
crdUtils CRDUtils,
IgnitionBuilder ignition.IgnitionBuilder,
hwValidator hardware.Validator,
dnsApi dns.DNSApi,
installConfigBuilder installcfg.InstallConfigBuilder,
staticNetworkConfig staticnetworkconfig.StaticNetworkConfig,
gcConfig garbagecollector.Config,
providerRegistry registry.ProviderRegistry,
insecureIPXEURLs bool,
) *bareMetalInventory {
return &bareMetalInventory{
db: db,
stream: stream,
log: log,
Config: cfg,
hostApi: hostApi,
clusterApi: clusterApi,
infraEnvApi: infraEnvApi,
dnsApi: dnsApi,
generator: generator,
eventsHandler: eventsHandler,
objectHandler: objectHandler,
metricApi: metricApi,
usageApi: usageApi,
operatorManagerApi: operatorManagerApi,
authHandler: authHandler,
authzHandler: authzHandler,
k8sClient: k8sClient,
ocmClient: ocmClient,
leaderElector: leaderElector,
secretValidator: pullSecretValidator,
versionsHandler: versionsHandler,
osImages: osImages,
crdUtils: crdUtils,
IgnitionBuilder: IgnitionBuilder,
hwValidator: hwValidator,
installConfigBuilder: installConfigBuilder,
staticNetworkConfig: staticNetworkConfig,
gcConfig: gcConfig,
providerRegistry: providerRegistry,
insecureIPXEURLs: insecureIPXEURLs,
}
}
func (b *bareMetalInventory) ValidatePullSecret(secret string, username string) error {
return b.secretValidator.ValidatePullSecret(secret, username)
}
func (b *bareMetalInventory) updatePullSecret(pullSecret string, log logrus.FieldLogger) (string, error) {
if b.Config.RhQaRegCred != "" {
ps, err := validations.AddRHRegPullSecret(pullSecret, b.Config.RhQaRegCred)
if err != nil {
log.Errorf("Failed to add RH QA Credentials to Pull Secret: %s", err.Error())
return "", errors.Errorf("Failed to add RH QA Credentials to Pull Secret: %s", err.Error())
}
return ps, nil
}
return pullSecret, nil
}
func (b *bareMetalInventory) setDefaultRegisterClusterParams(ctx context.Context, params installer.V2RegisterClusterParams, id strfmt.UUID) (installer.V2RegisterClusterParams, error) {
log := logutil.FromContext(ctx, b.log)
if params.NewClusterParams.APIVip != "" && len(params.NewClusterParams.APIVips) == 0 {
params.NewClusterParams.APIVips = []*models.APIVip{{IP: models.IP(params.NewClusterParams.APIVip), ClusterID: id}}
}
if params.NewClusterParams.IngressVip != "" && len(params.NewClusterParams.IngressVip) == 0 {
params.NewClusterParams.IngressVips = []*models.IngressVip{{IP: models.IP(params.NewClusterParams.IngressVip), ClusterID: id}}
}
if params.NewClusterParams.ClusterNetworks == nil {
params.NewClusterParams.ClusterNetworks = []*models.ClusterNetwork{
{Cidr: models.Subnet(b.Config.DefaultClusterNetworkCidr), HostPrefix: b.Config.DefaultClusterNetworkHostPrefix},
}
}
if params.NewClusterParams.ServiceNetworks == nil {
params.NewClusterParams.ServiceNetworks = []*models.ServiceNetwork{
{Cidr: models.Subnet(b.Config.DefaultServiceNetworkCidr)},
}
}
if params.NewClusterParams.MachineNetworks == nil {
params.NewClusterParams.MachineNetworks = []*models.MachineNetwork{}
}
if params.NewClusterParams.VipDhcpAllocation == nil {
params.NewClusterParams.VipDhcpAllocation = swag.Bool(false)
}
if params.NewClusterParams.Hyperthreading == nil {
params.NewClusterParams.Hyperthreading = swag.String(models.ClusterHyperthreadingAll)
}
if params.NewClusterParams.SchedulableMasters == nil {
params.NewClusterParams.SchedulableMasters = swag.Bool(false)
}
if params.NewClusterParams.HighAvailabilityMode == nil {
params.NewClusterParams.HighAvailabilityMode = swag.String(models.ClusterHighAvailabilityModeFull)
}
log.Infof("Verifying cluster platform and user-managed-networking, got platform=%s and userManagedNetworking=%s", getPlatformType(params.NewClusterParams.Platform), common.BoolPtrForLog(params.NewClusterParams.UserManagedNetworking))
platform, userManagedNetworking, err := provider.GetActualCreateClusterPlatformParams(params.NewClusterParams.Platform, params.NewClusterParams.UserManagedNetworking, params.NewClusterParams.HighAvailabilityMode, params.NewClusterParams.CPUArchitecture)
if err != nil {
log.Error(err)
return params, err
}
params.NewClusterParams.Platform = platform
params.NewClusterParams.UserManagedNetworking = userManagedNetworking
log.Infof("Cluster high-availability-mode is set to %s, setting platform type to %s and user-managed-networking to %s", swag.StringValue(params.NewClusterParams.HighAvailabilityMode), getPlatformType(platform), common.BoolPtrForLog(userManagedNetworking))
if params.NewClusterParams.AdditionalNtpSource == nil {
params.NewClusterParams.AdditionalNtpSource = &b.Config.DefaultNTPSource
}
if params.NewClusterParams.DiskEncryption == nil {
params.NewClusterParams.DiskEncryption = &models.DiskEncryption{
EnableOn: swag.String(models.DiskEncryptionEnableOnNone),
Mode: swag.String(models.DiskEncryptionModeTpmv2),
}
}
params.NewClusterParams.NetworkType, err = getDefaultNetworkType(params)
if err != nil {
return params, err
}
return params, nil
}
// If the cluster is SNO or the OpenShift version >= 4.12.0-0.0,
// the network type will be set to "OVNKubernetes", otherwise it will be set to "OpenShiftSDN"
func getDefaultNetworkType(params installer.V2RegisterClusterParams) (*string, error) {
if params.NewClusterParams.NetworkType != nil {
return params.NewClusterParams.NetworkType, nil
}
isOpenShiftVersionRecentEnough, err := common.BaseVersionGreaterOrEqual(minimalOpenShiftVersionForDefaultNetworkTypeOVNKubernetes, swag.StringValue(params.NewClusterParams.OpenshiftVersion))
if err != nil {
return nil, err
}
isSingleNodeCluster := swag.StringValue(params.NewClusterParams.HighAvailabilityMode) == models.ClusterCreateParamsHighAvailabilityModeNone
if isOpenShiftVersionRecentEnough || isSingleNodeCluster {
return swag.String(models.ClusterCreateParamsNetworkTypeOVNKubernetes), nil
} else {
return swag.String(models.ClusterCreateParamsNetworkTypeOpenShiftSDN), nil
}
}
func (b *bareMetalInventory) validateRegisterClusterInternalParams(params *installer.V2RegisterClusterParams, log logrus.FieldLogger) error {
var err error
if err = validateProxySettings(params.NewClusterParams.HTTPProxy,
params.NewClusterParams.HTTPSProxy,
params.NewClusterParams.NoProxy, params.NewClusterParams.OpenshiftVersion); err != nil {
return common.NewApiError(http.StatusBadRequest, err)
}
if err = validations.ValidateDiskEncryptionParams(params.NewClusterParams.DiskEncryption, b.DiskEncryptionSupport); err != nil {
return common.NewApiError(http.StatusBadRequest, err)
}
if swag.StringValue(params.NewClusterParams.HighAvailabilityMode) == models.ClusterHighAvailabilityModeNone {
// verify minimal OCP version
err = verifyMinimalOpenShiftVersionForSingleNode(swag.StringValue(params.NewClusterParams.OpenshiftVersion))
if err != nil {
return common.NewApiError(http.StatusBadRequest, err)
}
err = validateAndUpdateSingleNodeParams(params.NewClusterParams, log)
if err != nil {
return common.NewApiError(http.StatusBadRequest, err)
}
}
if getPlatformType(params.NewClusterParams.Platform) == string(models.PlatformTypeNutanix) {
if err = verifyMinimalOpenShiftVersionForNutanix(swag.StringValue(params.NewClusterParams.OpenshiftVersion)); err != nil {
return common.NewApiError(http.StatusBadRequest, err)
}
}
if err = b.validateIgnitionEndpoint(params.NewClusterParams.IgnitionEndpoint, log); err != nil {
return err
}
if params.NewClusterParams.AdditionalNtpSource != nil {
ntpSource := swag.StringValue(params.NewClusterParams.AdditionalNtpSource)
if ntpSource != "" && !pkgvalidations.ValidateAdditionalNTPSource(ntpSource) {
err = errors.Errorf("Invalid NTP source: %s", ntpSource)
return common.NewApiError(http.StatusBadRequest, err)
}
}
if params.NewClusterParams.Tags != nil {
if err := pkgvalidations.ValidateTags(swag.StringValue(params.NewClusterParams.Tags)); err != nil {
return common.NewApiError(http.StatusBadRequest, err)
}
}
if params.NewClusterParams.Platform != nil {
if err := validations.ValidateHighAvailabilityModeWithPlatform(params.NewClusterParams.HighAvailabilityMode, params.NewClusterParams.Platform); err != nil {
return common.NewApiError(http.StatusBadRequest, err)
}
}
return nil
}
func (b *bareMetalInventory) getOLMMonitoredOperators(log *logrus.Entry, cluster *common.Cluster, params installer.V2RegisterClusterParams, releaseImageVersion string) ([]*models.MonitoredOperator, error) {
if params.NewClusterParams.OlmOperators != nil {
var newOLMOperators []*models.MonitoredOperator
newOLMOperators, err := b.getOLMOperators(cluster, params.NewClusterParams.OlmOperators, log)
if err != nil {
return nil, err
}
err = b.operatorManagerApi.EnsureOperatorPrerequisite(cluster, releaseImageVersion, params.NewClusterParams.CPUArchitecture, newOLMOperators)
if err != nil {
log.Error(err)
return nil, common.NewApiError(http.StatusBadRequest, err)
}
return newOLMOperators, nil
}
return nil, nil
}
func (b *bareMetalInventory) getNewClusterReleaseImage(ctx context.Context, params *models.ClusterCreateParams, arch string) (*models.ReleaseImage, error) {
releaseImage, err := b.versionsHandler.GetReleaseImage(ctx, swag.StringValue(params.OpenshiftVersion),
arch, swag.StringValue(params.PullSecret))
if err != nil {
return nil, errors.Wrapf(err, "Openshift version %s for CPU architecture %s is not supported",
swag.StringValue(params.OpenshiftVersion), arch)
}
if models.OpenshiftVersionSupportLevelMaintenance == releaseImage.SupportLevel {
return nil, errors.Errorf("Openshift version %s support level is: %s, and can't be used for creating a new cluster",
swag.StringValue(params.OpenshiftVersion), releaseImage.SupportLevel)
}
// Ensure a relevant OsImage exists. For multiarch we disabling the code below because we don't know yet
// what is going to be the architecture of InfraEnv and Agent.
if len(releaseImage.CPUArchitectures) == 1 {
releaseVersion := *releaseImage.OpenshiftVersion
releaseArch := releaseImage.CPUArchitectures[0]
var osImage *models.OsImage
osImage, err = b.osImages.GetOsImage(releaseVersion, releaseArch)
if err != nil || osImage.URL == nil {
return nil, errors.Errorf("No OS images are available for version %s and architecture %s", releaseVersion, releaseArch)
}
}
return releaseImage, nil
}
func (b *bareMetalInventory) RegisterClusterInternal(
ctx context.Context,
kubeKey *types.NamespacedName,
params installer.V2RegisterClusterParams) (*common.Cluster, error) {
id := strfmt.UUID(uuid.New().String())
url := installer.V2GetClusterURL{ClusterID: id}
log := logutil.FromContext(ctx, b.log).WithField(ctxparams.ClusterId, id)
log.Infof("Register cluster: %s with id %s and params %+v", swag.StringValue(params.NewClusterParams.Name), id, params.NewClusterParams)
success := false
cluster := &common.Cluster{}
var err error
defer func() {
if success {
if err == nil && cluster != nil {
err = b.stream.Notify(ctx, cluster)
if err != nil {
log.WithError(err).Warning("failed to notify cluster registration event")
}
}
msg := fmt.Sprintf("Successfully registered cluster %s with id %s",
swag.StringValue(params.NewClusterParams.Name), id)
log.Info(msg)
eventgen.SendClusterRegistrationSucceededEvent(ctx, b.eventsHandler, id, models.ClusterKindCluster)
} else {
errWrapperLog := log
errStr := fmt.Sprintf("Failed to registered cluster %s with id %s", swag.StringValue(params.NewClusterParams.Name), id)
if err != nil {
errWrapperLog = log.WithError(err)
}
errWrapperLog.Errorf(errStr)
}
}()
if err = validations.ValidateClusterCreateIPAddresses(b.IPv6Support, id, params.NewClusterParams); err != nil {
b.log.WithError(err).Error("Cannot register cluster. Failed VIP validations")
return nil, common.NewApiError(http.StatusBadRequest, err)
}
if err = validations.ValidateDualStackNetworks(params.NewClusterParams, false); err != nil {
return nil, common.NewApiError(http.StatusBadRequest, err)
}
if err = validations.ValidatePlatformCapability(params.NewClusterParams.Platform, ctx, b.authzHandler); err != nil {
return nil, common.NewApiError(http.StatusBadRequest, err)
}
params, err = b.setDefaultRegisterClusterParams(ctx, params, id)
if err != nil {
return nil, err
}
if err = b.validateRegisterClusterInternalParams(¶ms, log); err != nil {
return nil, err
}
cpuArchitecture, err := b.getNewClusterCPUArchitecture(params.NewClusterParams)
if err != nil {
return nil, common.NewApiError(http.StatusBadRequest, err)
}
releaseImage, err := b.getNewClusterReleaseImage(ctx, params.NewClusterParams, cpuArchitecture)
if err != nil {
return nil, common.NewApiError(http.StatusBadRequest, err)
}
log.Infof("selected cluster release image: arch=%s, openshiftVersion=%s, url=%s",
swag.StringValue(releaseImage.CPUArchitecture),
swag.StringValue(releaseImage.OpenshiftVersion),
swag.StringValue(releaseImage.URL))
if len(releaseImage.CPUArchitectures) > 1 {
log.Infof("Setting cluster as multi-arch because of the release image (requested was %s)", cpuArchitecture)
cpuArchitecture = common.MultiCPUArchitecture
// (MGMT-11859) Additional check here ensures that the customer cannot just guess a version
// with multiarch in order to get access to that release payload.
var multiarchAllowed bool
multiarchAllowed, err = b.authzHandler.HasOrgBasedCapability(ctx, ocm.MultiarchCapabilityName)
if err != nil || !multiarchAllowed {
err = common.NewApiError(http.StatusBadRequest, errors.New("multiarch clusters are not available"))
return nil, err
}
}
if kubeKey == nil {
kubeKey = &types.NamespacedName{}
}
monitoredOperators := b.operatorManagerApi.GetSupportedOperatorsByType(models.OperatorTypeBuiltin)
cluster = &common.Cluster{
Cluster: models.Cluster{
ID: &id,
Href: swag.String(url.String()),
Kind: swag.String(models.ClusterKindCluster),
APIVip: params.NewClusterParams.APIVip,
APIVips: params.NewClusterParams.APIVips,
BaseDNSDomain: params.NewClusterParams.BaseDNSDomain,
IngressVip: params.NewClusterParams.IngressVip,
IngressVips: params.NewClusterParams.IngressVips,
Name: swag.StringValue(params.NewClusterParams.Name),
OpenshiftVersion: *releaseImage.Version,
OcpReleaseImage: *releaseImage.URL,
SSHPublicKey: params.NewClusterParams.SSHPublicKey,
UserName: ocm.UserNameFromContext(ctx),
OrgID: ocm.OrgIDFromContext(ctx),
EmailDomain: ocm.EmailDomainFromContext(ctx),
HTTPProxy: swag.StringValue(params.NewClusterParams.HTTPProxy),
HTTPSProxy: swag.StringValue(params.NewClusterParams.HTTPSProxy),
NoProxy: swag.StringValue(params.NewClusterParams.NoProxy),
VipDhcpAllocation: params.NewClusterParams.VipDhcpAllocation,
NetworkType: params.NewClusterParams.NetworkType,
UserManagedNetworking: params.NewClusterParams.UserManagedNetworking,
AdditionalNtpSource: swag.StringValue(params.NewClusterParams.AdditionalNtpSource),
MonitoredOperators: monitoredOperators,
HighAvailabilityMode: params.NewClusterParams.HighAvailabilityMode,
Hyperthreading: swag.StringValue(params.NewClusterParams.Hyperthreading),
SchedulableMasters: params.NewClusterParams.SchedulableMasters,
SchedulableMastersForcedTrue: swag.Bool(true),
Platform: params.NewClusterParams.Platform,
ClusterNetworks: params.NewClusterParams.ClusterNetworks,
ServiceNetworks: params.NewClusterParams.ServiceNetworks,
MachineNetworks: params.NewClusterParams.MachineNetworks,
CPUArchitecture: cpuArchitecture,
IgnitionEndpoint: params.NewClusterParams.IgnitionEndpoint,
Tags: swag.StringValue(params.NewClusterParams.Tags),
},
KubeKeyName: kubeKey.Name,
KubeKeyNamespace: kubeKey.Namespace,
TriggerMonitorTimestamp: time.Now(),
MachineNetworkCidrUpdatedAt: time.Now(),
}
newOLMOperators, err := b.getOLMMonitoredOperators(log, cluster, params, *releaseImage.Version)
if err != nil {
return nil, err
}
cluster.MonitoredOperators = append(monitoredOperators, newOLMOperators...)
if err = featuresupport.ValidateIncompatibleFeatures(log, params.NewClusterParams.CPUArchitecture, cluster, nil, nil); err != nil {
b.log.Error(err)
return nil, common.NewApiError(http.StatusBadRequest, err)
}
pullSecret := swag.StringValue(params.NewClusterParams.PullSecret)
err = b.ValidatePullSecret(pullSecret, ocm.UserNameFromContext(ctx))
if err != nil {
err = errors.Wrap(secretValidationToUserError(err), "pull secret for new cluster is invalid")
return nil, common.NewApiError(http.StatusBadRequest, err)
}
ps, err := b.updatePullSecret(pullSecret, log)
if err != nil {
return nil, common.NewApiError(http.StatusBadRequest,
errors.New("Failed to update Pull-secret with additional credentials"))
}
setPullSecret(cluster, ps)
if err = validations.ValidateClusterNameFormat(swag.StringValue(params.NewClusterParams.Name),
getPlatformType(params.NewClusterParams.Platform)); err != nil {
return nil, common.NewApiError(http.StatusBadRequest, err)
}
if err = b.validateDNSName(*cluster); err != nil {
return nil, common.NewApiError(http.StatusBadRequest, err)
}
if err = updateSSHPublicKey(cluster); err != nil {
return nil, common.NewApiError(http.StatusBadRequest, err)
}
setDiskEncryptionWithDefaultValues(&cluster.Cluster, params.NewClusterParams.DiskEncryption)
if err = b.setDefaultUsage(&cluster.Cluster); err != nil {
return nil, common.NewApiError(http.StatusBadRequest, err)
}
err = b.clusterApi.RegisterCluster(ctx, cluster)
if err != nil {
return nil, common.NewApiError(http.StatusInternalServerError, err)
}
if b.ocmClient != nil {
if err = b.integrateWithAMSClusterRegistration(ctx, cluster); err != nil {
err = errors.Wrapf(err, "cluster %s failed to integrate with AMS on cluster registration", id)
return nil, common.NewApiError(http.StatusInternalServerError, err)
}
}
success = true
b.metricApi.ClusterRegistered()
cluster, err = b.GetClusterInternal(ctx, installer.V2GetClusterParams{ClusterID: *cluster.ID})
return cluster, err
}
func setDiskEncryptionWithDefaultValues(c *models.Cluster, config *models.DiskEncryption) {
// When enabling the encryption we set the mode to TPMv2 unless the request contains an
// explicit value.
if config == nil {
return
}
c.DiskEncryption = config
if c.DiskEncryption.EnableOn == nil {
c.DiskEncryption.EnableOn = swag.String(models.DiskEncryptionEnableOnNone)
}
if config.Mode == nil {
c.DiskEncryption.Mode = swag.String(models.DiskEncryptionModeTpmv2)
}
}
func updateSSHPublicKey(cluster *common.Cluster) error {
sshPublicKey := swag.StringValue(&cluster.SSHPublicKey)
if sshPublicKey == "" {
return nil
}
sshPublicKey = strings.TrimSpace(cluster.SSHPublicKey)
if err := validations.ValidateSSHPublicKey(sshPublicKey); err != nil {
return err
}
cluster.SSHPublicKey = sshPublicKey
return nil
}
func updateSSHAuthorizedKey(infraEnv *common.InfraEnv) error {
sshPublicKey := swag.StringValue(&infraEnv.SSHAuthorizedKey)
if sshPublicKey == "" {
return nil
}
sshPublicKey = strings.TrimSpace(infraEnv.SSHAuthorizedKey)
if err := validations.ValidateSSHPublicKey(sshPublicKey); err != nil {
return err
}
infraEnv.SSHAuthorizedKey = sshPublicKey
return nil
}
func (b *bareMetalInventory) validateDNSName(cluster common.Cluster) error {
if cluster.Name == "" || cluster.BaseDNSDomain == "" {
return nil
}
return b.dnsApi.ValidateDNSName(cluster.Name, cluster.BaseDNSDomain)
}
func (b *bareMetalInventory) integrateWithAMSClusterRegistration(ctx context.Context, cluster *common.Cluster) error {
log := logutil.FromContext(ctx, b.log)
log.Infof("Creating AMS subscription for cluster %s", *cluster.ID)
sub, err := b.ocmClient.AccountsMgmt.CreateSubscription(ctx, *cluster.ID, cluster.Name)
if err != nil {
log.WithError(err).Errorf("Failed to create AMS subscription for cluster %s, rolling back cluster registration", *cluster.ID)
if deregisterErr := b.clusterApi.DeregisterCluster(ctx, cluster); deregisterErr != nil {
log.WithError(deregisterErr).Errorf("Failed to rollback cluster %s registration", *cluster.ID)
}
return err
}
log.Infof("AMS subscription %s was created for cluster %s", sub.ID(), *cluster.ID)
if err := b.clusterApi.UpdateAmsSubscriptionID(ctx, *cluster.ID, strfmt.UUID(sub.ID())); err != nil {
log.WithError(err).Errorf("Failed to update ams_subscription_id in cluster %s, rolling back AMS subscription and cluster registration", *cluster.ID)
if deleteSubErr := b.ocmClient.AccountsMgmt.DeleteSubscription(ctx, strfmt.UUID(sub.ID())); deleteSubErr != nil {
log.WithError(deleteSubErr).Errorf("Failed to rollback AMS subscription %s in cluster %s", sub.ID(), *cluster.ID)
}
if deregisterErr := b.clusterApi.DeregisterCluster(ctx, cluster); deregisterErr != nil {
log.WithError(deregisterErr).Errorf("Failed to rollback cluster %s registration", *cluster.ID)
}
return err
}
return nil
}
func verifyMinimalOpenShiftVersionForSingleNode(requestedOpenshiftVersion string) error {
ocpVersion, err := version.NewVersion(requestedOpenshiftVersion)
if err != nil {
return errors.Errorf("Failed to parse OCP version %s", requestedOpenshiftVersion)
}
minimalVersionForSno, err := version.NewVersion(minimalOpenShiftVersionForSingleNode)
if err != nil {
return errors.Errorf("Failed to parse minimal OCP version %s", minimalOpenShiftVersionForSingleNode)
}
if ocpVersion.LessThan(minimalVersionForSno) {
return errors.Errorf("Invalid OCP version (%s) for Single node, Single node OpenShift is supported for version 4.8 and above", requestedOpenshiftVersion)
}
return nil
}
func verifyMinimalOpenShiftVersionForNutanix(requestedOpenshiftVersion string) error {
ocpVersion, err := version.NewVersion(requestedOpenshiftVersion)
if err != nil {
return errors.Errorf("Failed to parse OCP version %s", requestedOpenshiftVersion)
}
minimalVersionForSno, err := version.NewVersion(minimalOpenShiftVersionForNutanix)
if err != nil {
return errors.Errorf("Failed to parse minimal OCP version %s", minimalOpenShiftVersionForSingleNode)
}
if ocpVersion.LessThan(minimalVersionForSno) {
return errors.Errorf("Invalid OCP version (%s) for Nutanix, Nutanix integration is supported for version 4.11 and above", requestedOpenshiftVersion)
}
return nil
}
func validateAndUpdateSingleNodeParams(newClusterParams *models.ClusterCreateParams, log logrus.FieldLogger) error {
if newClusterParams.UserManagedNetworking == nil {
log.Infof("HA mode is None, setting UserManagedNetworking to true")
// in case of single node UserManagedNetworking should be true
newClusterParams.UserManagedNetworking = swag.Bool(true)
}
if newClusterParams.VipDhcpAllocation == nil {
log.Infof("HA mode is None, setting VipDhcpAllocation to false")
// in case of single node VipDhcpAllocation should be false
newClusterParams.VipDhcpAllocation = swag.Bool(false)
}
if !swag.BoolValue(newClusterParams.UserManagedNetworking) {
return errors.Errorf("User Managed Networking must be enabled on single node OpenShift")
}
if swag.BoolValue(newClusterParams.VipDhcpAllocation) {
return errors.Errorf("VIP DHCP Allocation cannot be enabled on single node OpenShift")
}
if swag.StringValue(newClusterParams.NetworkType) == models.ClusterNetworkTypeOpenShiftSDN {
return errors.Errorf("OpenShiftSDN network type is not allowed in single node mode")
}
return nil
}
func (b *bareMetalInventory) getNewClusterCPUArchitecture(newClusterParams *models.ClusterCreateParams) (string, error) {
if newClusterParams.CPUArchitecture == common.MultiCPUArchitecture {
return newClusterParams.CPUArchitecture, nil
}
if newClusterParams.CPUArchitecture == "" || newClusterParams.CPUArchitecture == common.DefaultCPUArchitecture {
// Empty value implies x86_64 (default architecture),
// which is supported for now regardless of the release images list.
// TODO: remove once release images list is exclusively used.
return common.DefaultCPUArchitecture, nil
}
cpuArchitectures := b.osImages.GetCPUArchitectures(*newClusterParams.OpenshiftVersion)
for _, cpuArchitecture := range cpuArchitectures {
if cpuArchitecture == newClusterParams.CPUArchitecture {
return cpuArchitecture, nil
}
}
// Didn't find requested architecture in the release images list
return "", errors.Errorf("Requested CPU architecture %s is not available", newClusterParams.CPUArchitecture)
}
// importedClusterBaseDomain attempts to convert the API hostname provided
// by users during cluster import into a cluster base domain. If the hostname
// is an IP address and not a domain, or if the provided domain is not an API
// domain, this function returns an empty string. This function also returns
// the cluster name that is implied by the domain.
//
// Examples:
//
// importedClusterBaseDomain("api.cluster.example.com") returns ("example.com", "cluster")
// importedClusterBaseDomain("api-int.cluster.example.com") returns ("", "")
// importedClusterBaseDomain("192.168.111.111") returns ("", "")
// importedClusterBaseDomain("2001:db8::ff") returns ("", "")
func importedClusterBaseDomain(hostname string) (string, string) {
if net.ParseIP(hostname) != nil {
return "", ""
}
domainComponents := strings.SplitN(hostname, ".", 3)
if len(domainComponents) != 3 {
return "", ""
}
api := domainComponents[0]
clusterName := domainComponents[1]
clusterBaseDomain := domainComponents[2]
if api != "api" {
return "", ""
}
return clusterBaseDomain, clusterName
}
func (b *bareMetalInventory) V2ImportClusterInternal(ctx context.Context, kubeKey *types.NamespacedName, id *strfmt.UUID,
params installer.V2ImportClusterParams) (*common.Cluster, error) {
url := installer.V2GetClusterURL{ClusterID: *id}
log := logutil.FromContext(ctx, b.log).WithField(ctxparams.ClusterId, id)
apiHostname := swag.StringValue(params.NewImportClusterParams.APIVipDnsname)
clusterName := swag.StringValue(params.NewImportClusterParams.Name)
log.Infof("Import add-hosts-cluster: %s, id %s, openshift cluster id %s", clusterName, id.String(), params.NewImportClusterParams.OpenshiftClusterID)
if clusterPkg.ClusterExists(b.db, *id) {
return nil, common.NewApiError(http.StatusBadRequest, fmt.Errorf("AddHostsCluster for AI cluster %s already exists", id))
}
if kubeKey == nil {
kubeKey = &types.NamespacedName{}
}
baseDomain := ""
if importedBaseDomain, importedClusterName := importedClusterBaseDomain(apiHostname); importedBaseDomain != "" {
baseDomain = importedBaseDomain
// Explicitly ignore the user-provided cluster name as we derive a more
// accurate name from the API domain the user provided. The cluster
// name from the API domain takes precedence because the cluster name
// is used in DNS validations and it is more likely to be correct. For
// example, some versions of the UI provide a cluster name with a junk
// prefix "scale-up-" that could later mess with DNS validations, as
// that's obviously incorrect.
clusterName = importedClusterName
}
newCluster := common.Cluster{Cluster: models.Cluster{
ID: id,
Href: swag.String(url.String()),
Kind: swag.String(models.ClusterKindAddHostsCluster),
Name: clusterName,
OpenshiftClusterID: common.StrFmtUUIDVal(params.NewImportClusterParams.OpenshiftClusterID),
UserName: ocm.UserNameFromContext(ctx),
OrgID: ocm.OrgIDFromContext(ctx),
EmailDomain: ocm.EmailDomainFromContext(ctx),
APIVipDNSName: swag.String(apiHostname),
BaseDNSDomain: baseDomain,
HostNetworks: []*models.HostNetwork{},
Hosts: []*models.Host{},
Platform: &models.Platform{Type: common.PlatformTypePtr(models.PlatformTypeBaremetal)},
Imported: swag.Bool(true),
},
KubeKeyName: kubeKey.Name,
KubeKeyNamespace: kubeKey.Namespace,
}
err := validations.ValidateClusterNameFormat(clusterName, getPlatformType(newCluster.Platform))
if err != nil {
return nil, common.NewApiError(http.StatusBadRequest, err)
}
// After registering the cluster, its status should be 'ClusterStatusAddingHosts'
err = b.clusterApi.RegisterAddHostsCluster(ctx, &newCluster)
if err != nil {
log.Errorf("failed to register cluster %s ", clusterName)
return nil, common.NewApiError(http.StatusInternalServerError, err)
}
b.metricApi.ClusterRegistered()
return &newCluster, nil
}
func (b *bareMetalInventory) createAndUploadDay2NodeIgnition(ctx context.Context, cluster *common.Cluster, host *models.Host, ignitionEndpointToken string) error {
log := logutil.FromContext(ctx, b.log)
log.Infof("Starting createAndUploadDay2NodeIgnition for cluster %s, host %s", cluster.ID, host.ID)
ignitionEndpointUrl, err := hostutil.GetIgnitionEndpoint(cluster, host)
if err != nil {
return errors.Wrapf(err, "Failed to build ignition endpoint for host %s in cluster %s", host.ID, cluster.ID)
}
var caCert *string = nil
if cluster.IgnitionEndpoint != nil {
caCert = cluster.IgnitionEndpoint.CaCertificate
}
fullIgnition, err := b.IgnitionBuilder.FormatSecondDayWorkerIgnitionFile(ignitionEndpointUrl, caCert, ignitionEndpointToken, host)
if err != nil {
return errors.Wrapf(err, "Failed to create ignition string for cluster %s, host %s", cluster.ID, host.ID)
}
fileName := fmt.Sprintf("%s/%s-%s.ign", cluster.ID, common.GetEffectiveRole(host), host.ID)
log.Infof("Uploading ignition file <%s>", fileName)
err = b.objectHandler.Upload(ctx, fullIgnition, fileName)
if err != nil {
return errors.Errorf("Failed to upload worker ignition for cluster %s", cluster.ID)
}
return nil
}
func (b *bareMetalInventory) integrateWithAMSClusterDeregistration(ctx context.Context, cluster *common.Cluster) error {
log := logutil.FromContext(ctx, b.log)
// AMS subscription is created only for day1 clusters
if *cluster.Kind == models.ClusterKindCluster {
log.Infof("Deleting AMS subscription %s for non-active cluster %s", cluster.AmsSubscriptionID, *cluster.ID)
sub, err := b.ocmClient.AccountsMgmt.GetSubscription(ctx, cluster.AmsSubscriptionID)
if err != nil {
log.WithError(err).Errorf("Failed to get AMS subscription %s for cluster %s", cluster.AmsSubscriptionID, *cluster.ID)
return common.NewApiError(http.StatusInternalServerError, err)
}
if sub.Status() == ocm.SubscriptionStatusReserved {
if err = b.ocmClient.AccountsMgmt.DeleteSubscription(ctx, cluster.AmsSubscriptionID); err != nil {
log.WithError(err).Errorf("Failed to delete AMS subscription %s for cluster %s", cluster.AmsSubscriptionID, *cluster.ID)
return common.NewApiError(http.StatusInternalServerError, err)
}
}
}
return nil
}
// DeregisterClusterInternal contains only what is required for the cluster deployment controller to deregister the cluster
func (b *bareMetalInventory) DeregisterClusterInternal(ctx context.Context, cluster *common.Cluster) error {
log := logutil.FromContext(ctx, b.log)
log.Infof("Deregister cluster id %s", cluster.ID)
if err := b.clusterApi.DeregisterCluster(ctx, cluster); err != nil {
log.WithError(err).Errorf("failed to deregister cluster %s", cluster.ID)