-
Notifications
You must be signed in to change notification settings - Fork 84
/
powervs_cluster.go
2139 lines (1927 loc) · 72.5 KB
/
powervs_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
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package scope
import (
"context"
"errors"
"fmt"
"strings"
"github.com/go-logr/logr"
"github.com/IBM-Cloud/power-go-client/ibmpisession"
"github.com/IBM-Cloud/power-go-client/power/client/datacenters"
"github.com/IBM-Cloud/power-go-client/power/models"
"github.com/IBM/go-sdk-core/v5/core"
"github.com/IBM/ibm-cos-sdk-go/aws"
"github.com/IBM/ibm-cos-sdk-go/aws/awserr"
cosSession "github.com/IBM/ibm-cos-sdk-go/aws/session"
"github.com/IBM/ibm-cos-sdk-go/service/s3"
tgapiv1 "github.com/IBM/networking-go-sdk/transitgatewayapisv1"
"github.com/IBM/platform-services-go-sdk/resourcecontrollerv2"
"github.com/IBM/platform-services-go-sdk/resourcemanagerv2"
"github.com/IBM/vpc-go-sdk/vpcv1"
"k8s.io/klog/v2/textlogger"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/util/patch"
infrav1beta2 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/authenticator"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/cos"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/powervs"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/resourcecontroller"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/transitgateway"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/utils"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/vpc"
"sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/endpoints"
genUtil "sigs.k8s.io/cluster-api-provider-ibmcloud/util"
)
const (
// DEBUGLEVEL indicates the debug level of the logs.
DEBUGLEVEL = 5
)
// networkConnectionType represents network connection type in transit gateway.
type networkConnectionType string
var (
powervsNetworkConnectionType = networkConnectionType("power_virtual_server")
vpcNetworkConnectionType = networkConnectionType("vpc")
)
// powerEdgeRouter is identifier for PER.
const powerEdgeRouter = "power-edge-router"
// PowerVSClusterScopeParams defines the input parameters used to create a new PowerVSClusterScope.
type PowerVSClusterScopeParams struct {
Client client.Client
Logger logr.Logger
Cluster *capiv1beta1.Cluster
IBMPowerVSCluster *infrav1beta2.IBMPowerVSCluster
ServiceEndpoint []endpoints.ServiceEndpoint
}
// PowerVSClusterScope defines a scope defined around a Power VS Cluster.
type PowerVSClusterScope struct {
logr.Logger
Client client.Client
patchHelper *patch.Helper
session *ibmpisession.IBMPISession
IBMPowerVSClient powervs.PowerVS
IBMVPCClient vpc.Vpc
TransitGatewayClient transitgateway.TransitGateway
ResourceClient resourcecontroller.ResourceController
COSClient cos.Cos
Cluster *capiv1beta1.Cluster
IBMPowerVSCluster *infrav1beta2.IBMPowerVSCluster
ServiceEndpoint []endpoints.ServiceEndpoint
}
// NewPowerVSClusterScope creates a new PowerVSClusterScope from the supplied parameters.
func NewPowerVSClusterScope(params PowerVSClusterScopeParams) (*PowerVSClusterScope, error) { //nolint:gocyclo
if params.Client == nil {
err := errors.New("error failed to generate new scope from nil Client")
return nil, err
}
if params.Cluster == nil {
err := errors.New("error failed to generate new scope from nil Cluster")
return nil, err
}
if params.IBMPowerVSCluster == nil {
err := errors.New("error failed to generate new scope from nil IBMPowerVSCluster")
return nil, err
}
if params.Logger == (logr.Logger{}) {
params.Logger = textlogger.NewLogger(textlogger.NewConfig())
}
helper, err := patch.NewHelper(params.IBMPowerVSCluster, params.Client)
if err != nil {
err = fmt.Errorf("error failed to init patch helper: %w", err)
return nil, err
}
options := powervs.ServiceOptions{
IBMPIOptions: &ibmpisession.IBMPIOptions{
Debug: params.Logger.V(DEBUGLEVEL).Enabled(),
},
}
// if Spec.ServiceInstanceID is set fetch zone associated with it or else use Spec.Zone.
if params.IBMPowerVSCluster.Spec.ServiceInstanceID != "" {
// Create Resource Controller client.
var serviceOption resourcecontroller.ServiceOptions
// Fetch the resource controller endpoint.
rcEndpoint := endpoints.FetchEndpoints(string(endpoints.RC), params.ServiceEndpoint)
if rcEndpoint != "" {
serviceOption.URL = rcEndpoint
params.Logger.V(3).Info("Overriding the default resource controller endpoint", "ResourceControllerEndpoint", rcEndpoint)
}
rc, err := resourcecontroller.NewService(serviceOption)
if err != nil {
return nil, err
}
// Fetch the resource controller endpoint.
if rcEndpoint := endpoints.FetchRCEndpoint(params.ServiceEndpoint); rcEndpoint != "" {
if err := rc.SetServiceURL(rcEndpoint); err != nil {
params.Logger.V(3).Info("Overriding the default resource controller endpoint", "ResourceControllerEndpoint", rcEndpoint)
return nil, fmt.Errorf("failed to set resource controller endpoint: %w", err)
}
}
res, _, err := rc.GetResourceInstance(
&resourcecontrollerv2.GetResourceInstanceOptions{
ID: core.StringPtr(params.IBMPowerVSCluster.Spec.ServiceInstanceID),
})
if err != nil {
err = fmt.Errorf("failed to get resource instance: %w", err)
return nil, err
}
options.Zone = *res.RegionID
options.CloudInstanceID = params.IBMPowerVSCluster.Spec.ServiceInstanceID
} else {
options.Zone = *params.IBMPowerVSCluster.Spec.Zone
}
// Fetch the PowerVS service endpoint.
powerVSServiceEndpoint := endpoints.FetchEndpoints(string(endpoints.PowerVS), params.ServiceEndpoint)
if powerVSServiceEndpoint != "" {
params.Logger.V(3).Info("Overriding the default PowerVS endpoint", "powerVSEndpoint", powerVSServiceEndpoint)
options.IBMPIOptions.URL = powerVSServiceEndpoint
}
// TODO(karhtik-k-n): may be optimize NewService to use the session created here
powerVSClient, err := powervs.NewService(options)
if err != nil {
return nil, fmt.Errorf("error failed to create power vs client %w", err)
}
auth, err := authenticator.GetAuthenticator()
if err != nil {
return nil, fmt.Errorf("error failed to create authenticator %w", err)
}
account, err := utils.GetAccount(auth)
if err != nil {
return nil, fmt.Errorf("error failed to get account details %w", err)
}
sessionOptions := &ibmpisession.IBMPIOptions{
Authenticator: auth,
UserAccount: account,
Zone: options.Zone,
Debug: params.Logger.V(DEBUGLEVEL).Enabled(),
}
if powerVSServiceEndpoint != "" {
sessionOptions.URL = powerVSServiceEndpoint
}
session, err := ibmpisession.NewIBMPISession(sessionOptions)
if err != nil {
return nil, fmt.Errorf("error failed to get power vs session %w", err)
}
// if powervs.cluster.x-k8s.io/create-infra=true annotation is not set, create only powerVSClient.
if !genUtil.CheckCreateInfraAnnotation(*params.IBMPowerVSCluster) {
return &PowerVSClusterScope{
session: session,
Logger: params.Logger,
Client: params.Client,
patchHelper: helper,
Cluster: params.Cluster,
IBMPowerVSCluster: params.IBMPowerVSCluster,
ServiceEndpoint: params.ServiceEndpoint,
IBMPowerVSClient: powerVSClient,
}, nil
}
// if powervs.cluster.x-k8s.io/create-infra=true annotation is set, create necessary clients.
if params.IBMPowerVSCluster.Spec.VPC == nil || params.IBMPowerVSCluster.Spec.VPC.Region == nil {
return nil, fmt.Errorf("error failed to generate vpc client as VPC info is nil")
}
if params.Logger.V(DEBUGLEVEL).Enabled() {
core.SetLoggingLevel(core.LevelDebug)
}
svcEndpoint := endpoints.FetchVPCEndpoint(*params.IBMPowerVSCluster.Spec.VPC.Region, params.ServiceEndpoint)
vpcClient, err := vpc.NewService(svcEndpoint)
if err != nil {
return nil, fmt.Errorf("error failed to create IBM VPC client: %w", err)
}
// Create TransitGateway client
tgOptions := &tgapiv1.TransitGatewayApisV1Options{
Authenticator: auth,
}
// Fetch the TransitGateway service endpoint.
tgServiceEndpoint := endpoints.FetchEndpoints(string(endpoints.TransitGateway), params.ServiceEndpoint)
if tgServiceEndpoint != "" {
params.Logger.V(3).Info("Overriding the default TransitGateway endpoint", "transitGatewayEndpoint", tgServiceEndpoint)
tgOptions.URL = tgServiceEndpoint
}
tgClient, err := transitgateway.NewService(tgOptions)
if err != nil {
return nil, fmt.Errorf("error failed to create tranist gateway client: %w", err)
}
// Create Resource Controller client.
serviceOption := resourcecontroller.ServiceOptions{
ResourceControllerV2Options: &resourcecontrollerv2.ResourceControllerV2Options{
Authenticator: auth,
},
}
// Fetch the resource controller endpoint.
rcEndpoint := endpoints.FetchEndpoints(string(endpoints.RC), params.ServiceEndpoint)
if rcEndpoint != "" {
serviceOption.URL = rcEndpoint
params.Logger.V(3).Info("Overriding the default resource controller endpoint", "ResourceControllerEndpoint", rcEndpoint)
}
resourceClient, err := resourcecontroller.NewService(serviceOption)
if err != nil {
return nil, fmt.Errorf("error failed to create resource client: %w", err)
}
clusterScope := &PowerVSClusterScope{
session: session,
Logger: params.Logger,
Client: params.Client,
patchHelper: helper,
Cluster: params.Cluster,
IBMPowerVSCluster: params.IBMPowerVSCluster,
ServiceEndpoint: params.ServiceEndpoint,
IBMPowerVSClient: powerVSClient,
IBMVPCClient: vpcClient,
TransitGatewayClient: tgClient,
ResourceClient: resourceClient,
}
return clusterScope, nil
}
// PatchObject persists the cluster configuration and status.
func (s *PowerVSClusterScope) PatchObject() error {
return s.patchHelper.Patch(context.TODO(), s.IBMPowerVSCluster)
}
// Close closes the current scope persisting the cluster configuration and status.
func (s *PowerVSClusterScope) Close() error {
return s.PatchObject()
}
// Name returns the CAPI cluster name.
func (s *PowerVSClusterScope) Name() string {
return s.Cluster.Name
}
// Zone returns the cluster zone.
func (s *PowerVSClusterScope) Zone() *string {
return s.IBMPowerVSCluster.Spec.Zone
}
// ResourceGroup returns the cluster resource group.
func (s *PowerVSClusterScope) ResourceGroup() *infrav1beta2.IBMPowerVSResourceReference {
return s.IBMPowerVSCluster.Spec.ResourceGroup
}
// InfraCluster returns the IBMPowerVS infrastructure cluster object name.
func (s *PowerVSClusterScope) InfraCluster() string {
return s.IBMPowerVSCluster.Name
}
// APIServerPort returns the APIServerPort to use when creating the ControlPlaneEndpoint.
func (s *PowerVSClusterScope) APIServerPort() int32 {
if s.Cluster.Spec.ClusterNetwork != nil && s.Cluster.Spec.ClusterNetwork.APIServerPort != nil {
return *s.Cluster.Spec.ClusterNetwork.APIServerPort
}
return infrav1beta2.DefaultAPIServerPort
}
// ServiceInstance returns the cluster ServiceInstance.
func (s *PowerVSClusterScope) ServiceInstance() *infrav1beta2.IBMPowerVSResourceReference {
return s.IBMPowerVSCluster.Spec.ServiceInstance
}
// GetServiceInstanceID get the service instance id.
func (s *PowerVSClusterScope) GetServiceInstanceID() string {
if s.IBMPowerVSCluster.Spec.ServiceInstanceID != "" {
return s.IBMPowerVSCluster.Spec.ServiceInstanceID
}
if s.IBMPowerVSCluster.Spec.ServiceInstance != nil && s.IBMPowerVSCluster.Spec.ServiceInstance.ID != nil {
return *s.IBMPowerVSCluster.Spec.ServiceInstance.ID
}
if s.IBMPowerVSCluster.Status.ServiceInstance != nil && s.IBMPowerVSCluster.Status.ServiceInstance.ID != nil {
return *s.IBMPowerVSCluster.Status.ServiceInstance.ID
}
return ""
}
// TODO: Can we use generic here.
// SetStatus set the IBMPowerVSCluster status for provided ResourceType.
func (s *PowerVSClusterScope) SetStatus(resourceType infrav1beta2.ResourceType, resource infrav1beta2.ResourceReference) {
s.V(3).Info("Setting status", "resourceType", resourceType, "resource", resource)
switch resourceType {
case infrav1beta2.ResourceTypeServiceInstance:
if s.IBMPowerVSCluster.Status.ServiceInstance == nil {
s.IBMPowerVSCluster.Status.ServiceInstance = &resource
return
}
s.IBMPowerVSCluster.Status.ServiceInstance.Set(resource)
case infrav1beta2.ResourceTypeNetwork:
if s.IBMPowerVSCluster.Status.Network == nil {
s.IBMPowerVSCluster.Status.Network = &resource
return
}
s.IBMPowerVSCluster.Status.Network.Set(resource)
case infrav1beta2.ResourceTypeVPC:
if s.IBMPowerVSCluster.Status.VPC == nil {
s.IBMPowerVSCluster.Status.VPC = &resource
return
}
s.IBMPowerVSCluster.Status.VPC.Set(resource)
case infrav1beta2.ResourceTypeTransitGateway:
if s.IBMPowerVSCluster.Status.TransitGateway == nil {
s.IBMPowerVSCluster.Status.TransitGateway = &resource
return
}
s.IBMPowerVSCluster.Status.TransitGateway.Set(resource)
case infrav1beta2.ResourceTypeDHCPServer:
if s.IBMPowerVSCluster.Status.DHCPServer == nil {
s.IBMPowerVSCluster.Status.DHCPServer = &resource
return
}
s.IBMPowerVSCluster.Status.DHCPServer.Set(resource)
case infrav1beta2.ResourceTypeCOSInstance:
if s.IBMPowerVSCluster.Status.COSInstance == nil {
s.IBMPowerVSCluster.Status.COSInstance = &resource
return
}
s.IBMPowerVSCluster.Status.COSInstance.Set(resource)
case infrav1beta2.ResourceTypeResourceGroup:
if s.IBMPowerVSCluster.Status.ResourceGroup == nil {
s.IBMPowerVSCluster.Status.ResourceGroup = &resource
return
}
s.IBMPowerVSCluster.Status.ResourceGroup.Set(resource)
}
}
// Network returns the cluster Network.
func (s *PowerVSClusterScope) Network() *infrav1beta2.IBMPowerVSResourceReference {
return &s.IBMPowerVSCluster.Spec.Network
}
// GetDHCPServerID returns the DHCP id from spec or status of IBMPowerVSCluster object.
func (s *PowerVSClusterScope) GetDHCPServerID() *string {
if s.IBMPowerVSCluster.Spec.DHCPServer != nil && s.IBMPowerVSCluster.Spec.DHCPServer.ID != nil {
return s.IBMPowerVSCluster.Spec.DHCPServer.ID
}
if s.IBMPowerVSCluster.Status.DHCPServer != nil {
return s.IBMPowerVSCluster.Status.DHCPServer.ID
}
return nil
}
// DHCPServer returns the DHCP server details.
func (s *PowerVSClusterScope) DHCPServer() *infrav1beta2.DHCPServer {
return s.IBMPowerVSCluster.Spec.DHCPServer
}
// VPC returns the cluster VPC information.
func (s *PowerVSClusterScope) VPC() *infrav1beta2.VPCResourceReference {
return s.IBMPowerVSCluster.Spec.VPC
}
// GetVPCID returns the VPC id.
func (s *PowerVSClusterScope) GetVPCID() *string {
if s.IBMPowerVSCluster.Spec.VPC != nil && s.IBMPowerVSCluster.Spec.VPC.ID != nil {
return s.IBMPowerVSCluster.Spec.VPC.ID
}
if s.IBMPowerVSCluster.Status.VPC != nil {
return s.IBMPowerVSCluster.Status.VPC.ID
}
return nil
}
// GetVPCSubnetID returns the VPC subnet id.
func (s *PowerVSClusterScope) GetVPCSubnetID(subnetName string) *string {
if s.IBMPowerVSCluster.Status.VPCSubnet == nil {
return nil
}
if val, ok := s.IBMPowerVSCluster.Status.VPCSubnet[subnetName]; ok {
return val.ID
}
return nil
}
// GetVPCSubnetIDs returns all the VPC subnet ids.
func (s *PowerVSClusterScope) GetVPCSubnetIDs() []*string {
subnets := []*string{}
// use the vpc subnet id set by user.
for _, subnet := range s.IBMPowerVSCluster.Spec.VPCSubnets {
if subnet.ID != nil {
subnets = append(subnets, subnet.ID)
}
}
if len(subnets) != 0 {
return subnets
}
if s.IBMPowerVSCluster.Status.VPCSubnet == nil {
return nil
}
for _, subnet := range s.IBMPowerVSCluster.Status.VPCSubnet {
subnets = append(subnets, subnet.ID)
}
return subnets
}
// SetVPCSubnetID set the VPC subnet id.
func (s *PowerVSClusterScope) SetVPCSubnetID(name string, resource infrav1beta2.ResourceReference) {
s.V(3).Info("Setting status", "name", name, "resource", resource)
if s.IBMPowerVSCluster.Status.VPCSubnet == nil {
s.IBMPowerVSCluster.Status.VPCSubnet = make(map[string]infrav1beta2.ResourceReference)
}
if val, ok := s.IBMPowerVSCluster.Status.VPCSubnet[name]; ok {
if val.ControllerCreated != nil && *val.ControllerCreated {
resource.ControllerCreated = val.ControllerCreated
}
}
s.IBMPowerVSCluster.Status.VPCSubnet[name] = resource
}
// TransitGateway returns the cluster Transit Gateway information.
func (s *PowerVSClusterScope) TransitGateway() *infrav1beta2.TransitGateway {
return s.IBMPowerVSCluster.Spec.TransitGateway
}
// GetTransitGatewayID returns the transit gateway id.
func (s *PowerVSClusterScope) GetTransitGatewayID() *string {
if s.IBMPowerVSCluster.Spec.TransitGateway != nil && s.IBMPowerVSCluster.Spec.TransitGateway.ID != nil {
return s.IBMPowerVSCluster.Spec.TransitGateway.ID
}
if s.IBMPowerVSCluster.Status.TransitGateway != nil {
return s.IBMPowerVSCluster.Status.TransitGateway.ID
}
return nil
}
// PublicLoadBalancer returns the cluster public loadBalancer information.
func (s *PowerVSClusterScope) PublicLoadBalancer() *infrav1beta2.VPCLoadBalancerSpec {
// if the user did not specify any loadbalancer then return the public loadbalancer created by the controller.
if len(s.IBMPowerVSCluster.Spec.LoadBalancers) == 0 {
return &infrav1beta2.VPCLoadBalancerSpec{
Name: *s.GetServiceName(infrav1beta2.ResourceTypeLoadBalancer),
Public: ptr.To(true),
}
}
for _, lb := range s.IBMPowerVSCluster.Spec.LoadBalancers {
if lb.Public != nil && *lb.Public {
return &lb
}
}
return nil
}
// SetLoadBalancerStatus set the loadBalancer id.
func (s *PowerVSClusterScope) SetLoadBalancerStatus(name string, loadBalancer infrav1beta2.VPCLoadBalancerStatus) {
s.V(3).Info("Setting status", "name", name, "status", loadBalancer)
if s.IBMPowerVSCluster.Status.LoadBalancers == nil {
s.IBMPowerVSCluster.Status.LoadBalancers = make(map[string]infrav1beta2.VPCLoadBalancerStatus)
}
if val, ok := s.IBMPowerVSCluster.Status.LoadBalancers[name]; ok {
if val.ControllerCreated != nil && *val.ControllerCreated {
loadBalancer.ControllerCreated = val.ControllerCreated
}
}
s.IBMPowerVSCluster.Status.LoadBalancers[name] = loadBalancer
}
// GetLoadBalancerID returns the loadBalancer.
func (s *PowerVSClusterScope) GetLoadBalancerID(loadBalancerName string) *string {
if s.IBMPowerVSCluster.Status.LoadBalancers == nil {
return nil
}
if val, ok := s.IBMPowerVSCluster.Status.LoadBalancers[loadBalancerName]; ok {
return val.ID
}
return nil
}
// GetLoadBalancerState will return the state for the load balancer.
func (s *PowerVSClusterScope) GetLoadBalancerState(name string) *infrav1beta2.VPCLoadBalancerState {
if s.IBMPowerVSCluster.Status.LoadBalancers == nil {
return nil
}
if val, ok := s.IBMPowerVSCluster.Status.LoadBalancers[name]; ok {
return &val.State
}
return nil
}
// GetLoadBalancerHostName will return the hostname of load balancer.
func (s *PowerVSClusterScope) GetLoadBalancerHostName(name string) *string {
if s.IBMPowerVSCluster.Status.LoadBalancers == nil {
return nil
}
if val, ok := s.IBMPowerVSCluster.Status.LoadBalancers[name]; ok {
return val.Hostname
}
return nil
}
// GetResourceGroupID returns the resource group id if it present under spec or statue filed of IBMPowerVSCluster object
// or returns empty string.
func (s *PowerVSClusterScope) GetResourceGroupID() string {
if s.IBMPowerVSCluster.Spec.ResourceGroup != nil && s.IBMPowerVSCluster.Spec.ResourceGroup.ID != nil {
return *s.IBMPowerVSCluster.Spec.ResourceGroup.ID
}
if s.IBMPowerVSCluster.Status.ResourceGroup != nil && s.IBMPowerVSCluster.Status.ResourceGroup.ID != nil {
return *s.IBMPowerVSCluster.Status.ResourceGroup.ID
}
return ""
}
// IsPowerVSZoneSupportsPER checks whether PowerVS zone supports PER capabilities.
func (s *PowerVSClusterScope) IsPowerVSZoneSupportsPER() error {
zone := s.Zone()
if zone == nil {
return fmt.Errorf("powervs zone is not set")
}
// fetch the datacenter capabilities for zone.
// though the function name is WithDatacenterRegion it takes zone as parameter
params := datacenters.NewV1DatacentersGetParamsWithContext(context.TODO()).WithDatacenterRegion(*zone)
datacenter, err := s.session.Power.Datacenters.V1DatacentersGet(params)
if err != nil {
return fmt.Errorf("failed to get datacenter details for zone: %s err:%w", *zone, err)
}
if datacenter == nil || datacenter.Payload == nil || datacenter.Payload.Capabilities == nil {
return fmt.Errorf("failed to get datacenter capabilities for zone: %s", *zone)
}
// check for the PER support in datacenter capabilities.
perAvailable, ok := datacenter.Payload.Capabilities[powerEdgeRouter]
if !ok {
return fmt.Errorf("%s capability unknown for zone: %s", powerEdgeRouter, *zone)
}
if !perAvailable {
return fmt.Errorf("%s is not available for zone: %s", powerEdgeRouter, *zone)
}
return nil
}
// ReconcileResourceGroup reconciles resource group to fetch resource group id.
func (s *PowerVSClusterScope) ReconcileResourceGroup() error {
// Verify if resource group id is set in spec or status field of IBMPowerVSCluster object.
if resourceGroupID := s.GetResourceGroupID(); resourceGroupID != "" {
return nil
}
// Try to fetch resource group id from cloud associated with resource group name.
resourceGroupID, err := s.fetchResourceGroupID()
if err != nil {
return err
}
s.Info("Fetched resource group id from cloud", "resourceGroupID", resourceGroupID)
// Set the status of IBMPowerVSCluster object with resource group id.
s.SetStatus(infrav1beta2.ResourceTypeResourceGroup, infrav1beta2.ResourceReference{ID: &resourceGroupID, ControllerCreated: ptr.To(false)})
return nil
}
// ReconcilePowerVSServiceInstance reconciles Power VS service instance.
func (s *PowerVSClusterScope) ReconcilePowerVSServiceInstance() (bool, error) {
// Verify if service instance id is set in spec or status field of IBMPowerVSCluster object.
serviceInstanceID := s.GetServiceInstanceID()
if serviceInstanceID != "" {
// if serviceInstanceID is set, verify that it exist and in active state.
s.Info("Service instance id is set", "id", serviceInstanceID)
serviceInstance, _, err := s.ResourceClient.GetResourceInstance(&resourcecontrollerv2.GetResourceInstanceOptions{
ID: &serviceInstanceID,
})
if err != nil {
return false, err
}
if serviceInstance == nil {
return false, fmt.Errorf("error failed to get service instance with id %s", serviceInstanceID)
}
requeue, err := s.checkServiceInstanceState(serviceInstance.State)
if err != nil {
return false, err
}
return requeue, nil
}
// check PowerVS service instance exist in cloud, if it does not exist proceed with creating the instance.
serviceInstanceID, requeue, err := s.isServiceInstanceExists()
if err != nil {
return false, err
}
// Set the status of IBMPowerVSCluster object with serviceInstanceID and ControllerCreated to false as PowerVS service instance is already exist in cloud.
if serviceInstanceID != "" {
s.SetStatus(infrav1beta2.ResourceTypeServiceInstance, infrav1beta2.ResourceReference{ID: &serviceInstanceID, ControllerCreated: ptr.To(false)})
return requeue, nil
}
// create PowerVS Service Instance
serviceInstance, err := s.createServiceInstance()
if err != nil {
return false, err
}
if serviceInstance == nil {
return false, fmt.Errorf("created PowerVS service instance is nil")
}
s.Info("Created PowerVS service instance", "id", serviceInstance.GUID)
// Set the status of IBMPowerVSCluster object with serviceInstanceID and ControllerCreated to true as new PowerVS service instance is created.
s.SetStatus(infrav1beta2.ResourceTypeServiceInstance, infrav1beta2.ResourceReference{ID: serviceInstance.GUID, ControllerCreated: ptr.To(true)})
return true, nil
}
// checkServiceInstanceState checks the state of a PowerVS service instance.
// If state is provisioning, true is returned indicating a requeue for reconciliation.
// In all other cases, it returns false.
func (s *PowerVSClusterScope) checkServiceInstanceState(state *string) (bool, error) {
switch *state {
case string(infrav1beta2.ServiceInstanceStateActive):
s.Info("PowerVS service instance is in active state")
return false, nil
case string(infrav1beta2.ServiceInstanceStateProvisioning):
s.Info("PowerVS service instance is in provisioning state")
return true, nil
case string(infrav1beta2.ServiceInstanceStateFailed):
return false, fmt.Errorf("PowerVS service instance is in failed state")
}
return false, nil
}
// checkServiceInstance checks PowerVS service instance exist in cloud.
func (s *PowerVSClusterScope) isServiceInstanceExists() (string, bool, error) {
s.Info("Checking for service instance in cloud")
// Fetches service instance by name.
serviceInstance, err := s.getServiceInstance()
if err != nil {
s.Error(err, "failed to get service instance")
return "", false, err
}
if serviceInstance == nil {
s.Info("Power VS service isntance with given name does not exist in IBM Cloud", "name", *s.GetServiceName(infrav1beta2.ResourceTypeServiceInstance))
return "", false, nil
}
requeue, err := s.checkServiceInstanceState(serviceInstance.State)
if err != nil {
return "", false, err
}
return *serviceInstance.GUID, requeue, nil
}
// getServiceInstance return resource instance by name.
func (s *PowerVSClusterScope) getServiceInstance() (*resourcecontrollerv2.ResourceInstance, error) {
//TODO: Support regular expression
return s.ResourceClient.GetServiceInstance("", *s.GetServiceName(infrav1beta2.ResourceTypeServiceInstance))
}
// createServiceInstance creates the service instance.
func (s *PowerVSClusterScope) createServiceInstance() (*resourcecontrollerv2.ResourceInstance, error) {
// fetch resource group id.
resourceGroupID := s.GetResourceGroupID()
if resourceGroupID == "" {
s.Info("failed to create service instance, failed to fetch resource group id")
return nil, fmt.Errorf("error getting resource group id for resource group %v, id is empty", s.ResourceGroup())
}
// create service instance.
s.Info("Creating new PowerVS service instance", "name", s.GetServiceName(infrav1beta2.ResourceTypeServiceInstance))
zone := s.Zone()
if zone == nil {
return nil, fmt.Errorf("error creating new service instance, PowerVS zone is not set")
}
serviceInstance, _, err := s.ResourceClient.CreateResourceInstance(&resourcecontrollerv2.CreateResourceInstanceOptions{
Name: s.GetServiceName(infrav1beta2.ResourceTypeServiceInstance),
Target: zone,
ResourceGroup: &resourceGroupID,
ResourcePlanID: ptr.To(resourcecontroller.PowerVSResourcePlanID),
})
if err != nil {
return nil, err
}
return serviceInstance, nil
}
// ReconcileNetwork reconciles network.
func (s *PowerVSClusterScope) ReconcileNetwork() (bool, error) {
if s.GetDHCPServerID() != nil {
s.Info("DHCP server id is set")
requeue, err := s.isDHCPServerActive()
if err != nil {
return false, err
}
// if dhcp server exist and in active state, its assumed that dhcp network exist
// TODO(Phase 2): Verify that dhcp network is exist.
return requeue, nil
// TODO(karthik-k-n): If needed set dhcp status here
}
// check network exist in cloud
networkID, err := s.checkNetwork()
if err != nil {
return false, err
}
if networkID != nil {
s.Info("Found PowerVS network in IBM Cloud", "id", networkID)
s.SetStatus(infrav1beta2.ResourceTypeNetwork, infrav1beta2.ResourceReference{ID: networkID, ControllerCreated: ptr.To(false)})
return false, nil
}
s.Info("Creating DHCP server")
dhcpServer, err := s.createDHCPServer()
if err != nil {
s.Error(err, "Error creating DHCP server")
return false, err
}
s.Info("Created DHCP Server", "id", *dhcpServer)
s.SetStatus(infrav1beta2.ResourceTypeDHCPServer, infrav1beta2.ResourceReference{ID: dhcpServer, ControllerCreated: ptr.To(true)})
return true, nil
}
// checkNetwork checks the network exist in cloud.
func (s *PowerVSClusterScope) checkNetwork() (*string, error) {
// get network from cloud.
networkID, err := s.getNetwork()
if err != nil {
s.Error(err, "failed to get PowerVS network")
return nil, err
}
if networkID == nil {
s.Info("Not able to find PowerVS network in IBM Cloud", "network", s.IBMPowerVSCluster.Spec.Network)
return nil, nil
}
return networkID, nil
}
func (s *PowerVSClusterScope) getNetwork() (*string, error) {
// fetch the network associated with network id
if s.IBMPowerVSCluster.Spec.Network.ID != nil {
network, err := s.IBMPowerVSClient.GetNetworkByID(*s.IBMPowerVSCluster.Spec.Network.ID)
if err != nil {
return nil, err
}
return network.NetworkID, nil
}
// if the user has provided the already existing dhcp server name then there might exist network name
// with format DHCPSERVER<DHCPServer.Name>_Private , try fetching that
var networkName string
if s.DHCPServer() != nil && s.DHCPServer().Name != nil {
networkName = fmt.Sprintf("DHCPSERVER%s_Private", *s.DHCPServer().Name)
} else {
networkName = *s.GetServiceName(infrav1beta2.ResourceTypeNetwork)
}
// fetch the network associated with name
network, err := s.IBMPowerVSClient.GetNetworkByName(networkName)
if err != nil {
return nil, err
}
if network == nil {
return nil, nil
}
return network.NetworkID, nil
//TODO: Support regular expression
}
// isDHCPServerActive checks if the DHCP server status is active.
func (s *PowerVSClusterScope) isDHCPServerActive() (bool, error) {
dhcpID := *s.GetDHCPServerID()
dhcpServer, err := s.IBMPowerVSClient.GetDHCPServer(dhcpID)
if err != nil {
return false, err
}
requeue, err := s.checkDHCPServerStatus(dhcpServer.Status)
if err != nil {
return false, err
}
return requeue, nil
}
// checkDHCPServerStatus checks the state of a DHCP server.
// If state is BUILD, true is returned indicating a requeue for reconciliation.
// In all other cases, it returns false.
func (s *PowerVSClusterScope) checkDHCPServerStatus(status *string) (bool, error) {
switch *status {
case string(infrav1beta2.DHCPServerStateActive):
s.Info("DHCP server is in active state")
return false, nil
case string(infrav1beta2.DHCPServerStateBuild):
s.Info("DHCP server is in build state")
return true, nil
case string(infrav1beta2.DHCPServerStateError):
s.Info("DHCP server is in error state")
return false, fmt.Errorf("DHCP server creation failed and is in error state")
}
return false, nil
}
// createDHCPServer creates the DHCP server.
func (s *PowerVSClusterScope) createDHCPServer() (*string, error) {
var dhcpServerCreateParams models.DHCPServerCreate
dhcpServerDetails := s.DHCPServer()
if dhcpServerDetails == nil {
dhcpServerDetails = &infrav1beta2.DHCPServer{}
}
dhcpServerCreateParams.Name = s.GetServiceName(infrav1beta2.ResourceTypeDHCPServer)
if dhcpServerDetails.DNSServer != nil {
dhcpServerCreateParams.DNSServer = dhcpServerDetails.DNSServer
}
if dhcpServerDetails.Cidr != nil {
dhcpServerCreateParams.Cidr = dhcpServerDetails.Cidr
}
if dhcpServerDetails.Snat != nil {
dhcpServerCreateParams.SnatEnabled = dhcpServerDetails.Snat
}
dhcpServer, err := s.IBMPowerVSClient.CreateDHCPServer(&dhcpServerCreateParams)
if err != nil {
return nil, err
}
if dhcpServer == nil {
return nil, fmt.Errorf("created dhcp server is nil")
}
if dhcpServer.Network == nil {
return nil, fmt.Errorf("created dhcp server network is nil")
}
s.Info("DHCP Server network details", "details", *dhcpServer.Network)
s.SetStatus(infrav1beta2.ResourceTypeNetwork, infrav1beta2.ResourceReference{ID: dhcpServer.Network.ID, ControllerCreated: ptr.To(true)})
return dhcpServer.ID, nil
}
// ReconcileVPC reconciles VPC.
func (s *PowerVSClusterScope) ReconcileVPC() (bool, error) {
// if VPC server id is set means the VPC is already created
vpcID := s.GetVPCID()
if vpcID != nil {
s.Info("VPC id is set", "id", vpcID)
vpcDetails, _, err := s.IBMVPCClient.GetVPC(&vpcv1.GetVPCOptions{
ID: vpcID,
})
if err != nil {
return false, err
}
if vpcDetails == nil {
return false, fmt.Errorf("failed to get VPC with id %s", *vpcID)
}
if vpcDetails.Status != nil && *vpcDetails.Status == string(infrav1beta2.VPCStatePending) {
return true, nil
}
s.Info("Found VPC with provided id")
// TODO(karthik-k-n): Set status here as well
return false, nil
}
// check vpc exist in cloud
id, err := s.checkVPC()
if err != nil {
return false, err
}
if id != "" {
s.SetStatus(infrav1beta2.ResourceTypeVPC, infrav1beta2.ResourceReference{ID: &id, ControllerCreated: ptr.To(false)})
return false, nil
}
// TODO(karthik-k-n): create a generic cluster scope/service and implement common vpc logics, which can be consumed by both vpc and powervs
// create VPC
s.Info("Creating a VPC")
vpcDetails, err := s.createVPC()
if err != nil {
return false, err
}
s.Info("Successfully created VPC")
s.SetStatus(infrav1beta2.ResourceTypeVPC, infrav1beta2.ResourceReference{ID: vpcDetails, ControllerCreated: ptr.To(true)})
return true, nil
}
// checkVPC checks VPC exist in cloud.
func (s *PowerVSClusterScope) checkVPC() (string, error) {
vpcDetails, err := s.getVPCByName()
if err != nil {
s.Error(err, "failed to get vpc")
return "", err
}
if vpcDetails == nil {
s.Info("Unable to find VPC in IBM Cloud", "vpc", s.IBMPowerVSCluster.Spec.VPC)
return "", nil
}
s.Info("VPC found in IBM Cloud", "id", *vpcDetails.ID)
return *vpcDetails.ID, nil
}
func (s *PowerVSClusterScope) getVPCByName() (*vpcv1.VPC, error) {
vpcDetails, err := s.IBMVPCClient.GetVPCByName(*s.GetServiceName(infrav1beta2.ResourceTypeVPC))
if err != nil {
return nil, err
}
return vpcDetails, nil
//TODO: Support regular expression
}
// createVPC creates VPC.
func (s *PowerVSClusterScope) createVPC() (*string, error) {
resourceGroupID := s.GetResourceGroupID()
if resourceGroupID == "" {
s.Info("failed to create vpc, failed to fetch resource group id")
return nil, fmt.Errorf("error getting resource group id for resource group %v, id is empty", s.ResourceGroup())
}
addressPrefixManagement := "auto"
vpcOption := &vpcv1.CreateVPCOptions{
ResourceGroup: &vpcv1.ResourceGroupIdentity{ID: &resourceGroupID},
Name: s.GetServiceName(infrav1beta2.ResourceTypeVPC),
AddressPrefixManagement: &addressPrefixManagement,
}
vpcDetails, _, err := s.IBMVPCClient.CreateVPC(vpcOption)
if err != nil {
return nil, err
}
// set security group for vpc
options := &vpcv1.CreateSecurityGroupRuleOptions{}
options.SetSecurityGroupID(*vpcDetails.DefaultSecurityGroup.ID)
options.SetSecurityGroupRulePrototype(&vpcv1.SecurityGroupRulePrototype{
Direction: core.StringPtr("inbound"),
Protocol: core.StringPtr("tcp"),
IPVersion: core.StringPtr("ipv4"),
PortMin: core.Int64Ptr(int64(s.APIServerPort())),
PortMax: core.Int64Ptr(int64(s.APIServerPort())),
})
if _, _, err = s.IBMVPCClient.CreateSecurityGroupRule(options); err != nil {
return nil, err
}
return vpcDetails.ID, nil
}
// ReconcileVPCSubnet reconciles VPC subnet.
func (s *PowerVSClusterScope) ReconcileVPCSubnet() (bool, error) {
subnets := make([]infrav1beta2.Subnet, 0)
// check whether user has set the vpc subnets
if len(s.IBMPowerVSCluster.Spec.VPCSubnets) == 0 {
// if the user did not set any subnet, we try to create subnet in all the zones.
powerVSZone := s.Zone()
if powerVSZone == nil {
return false, fmt.Errorf("error reconicling vpc subnet, powervs zone is not set")
}
region := endpoints.ConstructRegionFromZone(*powerVSZone)
vpcZones, err := genUtil.VPCZonesForPowerVSRegion(region)
if err != nil {