-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathclient.go
More file actions
1584 lines (1358 loc) · 52.3 KB
/
Copy pathclient.go
File metadata and controls
1584 lines (1358 loc) · 52.3 KB
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 powervs
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/IBM-Cloud/bluemix-go/crn"
"github.com/IBM-Cloud/power-go-client/clients/instance"
"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/networking-go-sdk/dnsrecordsv1"
"github.com/IBM/networking-go-sdk/dnssvcsv1"
"github.com/IBM/networking-go-sdk/dnszonesv1"
"github.com/IBM/networking-go-sdk/resourcerecordsv1"
"github.com/IBM/networking-go-sdk/transitgatewayapisv1"
"github.com/IBM/networking-go-sdk/zonesv1"
"github.com/IBM/platform-services-go-sdk/iamidentityv1"
"github.com/IBM/platform-services-go-sdk/resourcecontrollerv2"
"github.com/IBM/platform-services-go-sdk/resourcemanagerv2"
"github.com/IBM/vpc-go-sdk/vpcv1"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/utils/ptr"
"github.com/openshift/installer/pkg/types"
)
//go:generate mockgen -source=./client.go -destination=./mock/powervsclient_generated.go -package=mock
// API represents the calls made to the API.
type API interface {
// DNS
GetDNSRecordsByName(ctx context.Context, crnstr string, zoneID string, recordName string, publish types.PublishingStrategy) ([]DNSRecordResponse, error)
GetDNSZoneIDByName(ctx context.Context, name string, publish types.PublishingStrategy) (string, error)
GetDNSZones(ctx context.Context, publish types.PublishingStrategy) ([]DNSZoneResponse, error)
GetDNSInstancePermittedNetworks(ctx context.Context, dnsID string, dnsZone string) ([]string, error)
GetDNSCustomResolverIP(ctx context.Context, dnsID string, vpcID string) (string, error)
CreateDNSCustomResolver(ctx context.Context, name string, dnsID string, vpcID string) (*dnssvcsv1.CustomResolver, error)
EnableDNSCustomResolver(ctx context.Context, dnsID string, resolverID string) (*dnssvcsv1.CustomResolver, error)
CreateDNSRecord(ctx context.Context, publish types.PublishingStrategy, crnstr string, baseDomain string, hostname string, cname string) error
AddVPCToPermittedNetworks(ctx context.Context, vpcCRN string, dnsID string, dnsZone string) error
// VPC
GetVPCByName(ctx context.Context, vpcName string) (*vpcv1.VPC, error)
GetVPCByID(ctx context.Context, vpcID string, region string) (*vpcv1.VPC, error)
GetPublicGatewayByVPC(ctx context.Context, vpcName string) (*vpcv1.PublicGateway, error)
SetVPCServiceURLForRegion(ctx context.Context, region string) error
GetVPCs(ctx context.Context, region string) ([]vpcv1.VPC, error)
GetVPCSubnets(ctx context.Context, vpcID string) ([]vpcv1.Subnet, error)
// TG
TransitGatewayNameToID(ctx context.Context, name string) (string, error)
TransitGatewayIDValid(ctx context.Context, id string) error
GetTGConnectionVPC(ctx context.Context, gatewayID string, vpcSubnetID string) (string, error)
GetAttachedTransitGateway(ctx context.Context, svcInsID string) (string, error)
// Data Center
GetDatacenterCapabilities(ctx context.Context, region string) (map[string]bool, error)
GetDatacenterSupportedSystems(ctx context.Context, region string) ([]string, error)
// API
GetAuthenticatorAPIKeyDetails(ctx context.Context) (*iamidentityv1.APIKey, error)
GetAPIKey() string
// Subnet
GetSubnetByName(ctx context.Context, subnetName string, region string) (*vpcv1.Subnet, error)
// Resource Groups
ListResourceGroups(ctx context.Context) (*resourcemanagerv2.ResourceGroupList, error)
// Service Instance
ListServiceInstances(ctx context.Context) ([]string, error)
ServiceInstanceGUIDToName(ctx context.Context, id string) (string, error)
ServiceInstanceNameToGUID(ctx context.Context, name string) (string, error)
// Security Group
ListSecurityGroupRules(ctx context.Context, securityGroupID string) (*vpcv1.SecurityGroupRuleCollection, error)
AddSecurityGroupRule(ctx context.Context, securityGroupID string, rule *vpcv1.SecurityGroupRulePrototype) error
// SSH
CreateSSHKey(ctx context.Context, serviceInstance string, zone string, sshKeyName string, sshKey string) error
// Load Balancer
AddIPToLoadBalancerPool(ctx context.Context, lbID string, poolName string, port int64, ip string) error
// Virtual Private Endpoint Gateway
CreateVirtualPrivateEndpointGateway(ctx context.Context, name string, vpcID string, subnetID string, rgID string, targetCRN string) (*vpcv1.EndpointGateway, error)
}
// Client makes calls to the PowerVS API.
type Client struct {
APIKey string
BXCli *BxClient
managementAPI *resourcemanagerv2.ResourceManagerV2
controllerAPI *resourcecontrollerv2.ResourceControllerV2
vpcAPI *vpcv1.VpcV1
dnsServicesAPI *dnssvcsv1.DnsSvcsV1
transitGatewayAPI *transitgatewayapisv1.TransitGatewayApisV1
}
// cisServiceID is the Cloud Internet Services' catalog service ID.
const (
cisServiceID = "75874a60-cb12-11e7-948e-37ac098eb1b9"
dnsServiceID = "b4ed8a30-936f-11e9-b289-1d079699cbe5"
serviceInstanceType = "service_instance"
compositeInstanceType = "composite_instance"
)
// DNSZoneResponse represents a DNS zone response.
type DNSZoneResponse struct {
// Name is the domain name of the zone.
Name string
// ID is the zone's ID.
ID string
// CISInstanceCRN is the IBM Cloud Resource Name for the CIS instance where
// the DNS zone is managed.
InstanceCRN string
// CISInstanceName is the display name of the CIS instance where the DNS zone
// is managed.
InstanceName string
// ResourceGroupID is the resource group ID of the CIS instance.
ResourceGroupID string
}
// DNSRecordResponse represents a DNS record response.
type DNSRecordResponse struct {
Name string
Type string
}
// NewClient initializes a client with a session.
func NewClient() (*Client, error) {
bxCli, err := NewBxClient(false)
if err != nil {
return nil, err
}
client := &Client{
APIKey: bxCli.APIKey,
BXCli: bxCli,
}
if err := client.loadSDKServices(); err != nil {
return nil, fmt.Errorf("failed to load IBM SDK services: %w", err)
}
if bxCli.PowerVSResourceGroup == "Default" {
// Here we are initialized enough to handle a default resource group
ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Minute)
defer cancel()
resourceGroups, err := client.ListResourceGroups(ctx)
if err != nil {
return nil, fmt.Errorf("client.ListResourceGroups failed: %w", err)
}
if resourceGroups == nil {
return nil, errors.New("client.ListResourceGroups returns nil")
}
found := false
for _, resourceGroup := range resourceGroups.Resources {
if resourceGroup.Default != nil && *resourceGroup.Default {
bxCli.PowerVSResourceGroup = *resourceGroup.Name
found = true
break
}
}
if !found {
return nil, errors.New("no default resource group found")
}
}
return client, nil
}
func (c *Client) loadSDKServices() error {
servicesToLoad := []func() error{
c.loadResourceManagementAPI,
c.loadResourceControllerAPI,
c.loadVPCV1API,
c.loadDNSServicesAPI,
c.loadTransitGatewayAPI,
}
// Call all the load functions.
for _, fn := range servicesToLoad {
if err := fn(); err != nil {
return err
}
}
return nil
}
// GetDNSRecordsByName gets DNS records in specific Cloud Internet Services instance
// by its CRN, zone ID, and DNS record name.
func (c *Client) GetDNSRecordsByName(ctx context.Context, crnstr string, zoneID string, recordName string, publish types.PublishingStrategy) ([]DNSRecordResponse, error) {
authenticator := &core.IamAuthenticator{
ApiKey: c.APIKey,
}
dnsRecords := []DNSRecordResponse{}
switch publish {
case types.ExternalPublishingStrategy:
// Set CIS DNS record service
dnsService, err := dnsrecordsv1.NewDnsRecordsV1(&dnsrecordsv1.DnsRecordsV1Options{
Authenticator: authenticator,
Crn: core.StringPtr(crnstr),
ZoneIdentifier: core.StringPtr(zoneID),
})
if err != nil {
return nil, err
}
// Get CIS DNS records by name
records, _, err := dnsService.ListAllDnsRecordsWithContext(ctx, &dnsrecordsv1.ListAllDnsRecordsOptions{
Name: core.StringPtr(recordName),
})
if err != nil {
return nil, fmt.Errorf("could not retrieve DNS records: %w", err)
}
for _, record := range records.Result {
dnsRecords = append(dnsRecords, DNSRecordResponse{Name: *record.Name, Type: *record.Type})
}
case types.InternalPublishingStrategy:
// Set DNS record service
dnsService, err := resourcerecordsv1.NewResourceRecordsV1(&resourcerecordsv1.ResourceRecordsV1Options{
Authenticator: authenticator,
})
if err != nil {
return nil, err
}
dnsCRN, err := crn.Parse(crnstr)
if err != nil {
return nil, fmt.Errorf("failed to parse DNSInstanceCRN: %w", err)
}
// Get DNS records by name
records, _, err := dnsService.ListResourceRecords(&resourcerecordsv1.ListResourceRecordsOptions{
InstanceID: &dnsCRN.ServiceInstance,
DnszoneID: &zoneID,
})
for _, record := range records.ResourceRecords {
if *record.Name == recordName {
dnsRecords = append(dnsRecords, DNSRecordResponse{Name: *record.Name, Type: *record.Type})
}
}
if err != nil {
return nil, fmt.Errorf("could not retrieve DNS records: %w", err)
}
}
return dnsRecords, nil
}
// GetInstanceCRNByName finds the CRN of the instance with the specified name.
func (c *Client) GetInstanceCRNByName(ctx context.Context, name string, publish types.PublishingStrategy) (string, error) {
zones, err := c.GetDNSZones(ctx, publish)
if err != nil {
return "", err
}
for _, z := range zones {
if z.Name == name {
return z.InstanceCRN, nil
}
}
return "", fmt.Errorf("DNS zone %q not found", name)
}
// GetDNSCustomResolverIP gets the DNS Server IP of a custom resolver associated with the specified VPC subnet in the specified DNS zone.
func (c *Client) GetDNSCustomResolverIP(ctx context.Context, dnsID string, vpcID string) (string, error) {
listCustomResolversOptions := c.dnsServicesAPI.NewListCustomResolversOptions(dnsID)
customResolvers, _, err := c.dnsServicesAPI.ListCustomResolversWithContext(ctx, listCustomResolversOptions)
if err != nil {
return "", err
}
subnets, err := c.GetVPCSubnets(ctx, vpcID)
if err != nil {
return "", err
}
for _, customResolver := range customResolvers.CustomResolvers {
for _, location := range customResolver.Locations {
for _, subnet := range subnets {
if *subnet.CRN == *location.SubnetCrn {
return *location.DnsServerIp, nil
}
}
}
}
return "", fmt.Errorf("DNS server IP of custom resolver for %q not found", dnsID)
}
// CreateDNSCustomResolver creates a custom resolver associated with the specified VPC in the specified DNS zone.
func (c *Client) CreateDNSCustomResolver(ctx context.Context, name string, dnsID string, vpcID string) (*dnssvcsv1.CustomResolver, error) {
createCustomResolverOptions := c.dnsServicesAPI.NewCreateCustomResolverOptions(dnsID, name)
subnets, err := c.GetVPCSubnets(ctx, vpcID)
if err != nil {
return nil, err
}
locations := []dnssvcsv1.LocationInput{}
for _, subnet := range subnets {
location, err := c.dnsServicesAPI.NewLocationInput(*subnet.CRN)
if err != nil {
return nil, err
}
location.Enabled = core.BoolPtr(true)
locations = append(locations, *location)
}
createCustomResolverOptions.SetLocations(locations)
customResolver, _, err := c.dnsServicesAPI.CreateCustomResolverWithContext(ctx, createCustomResolverOptions)
if err != nil {
return nil, err
}
return customResolver, nil
}
// EnableDNSCustomResolver enables a specified custom resolver.
func (c *Client) EnableDNSCustomResolver(ctx context.Context, dnsID string, resolverID string) (*dnssvcsv1.CustomResolver, error) {
updateCustomResolverOptions := c.dnsServicesAPI.NewUpdateCustomResolverOptions(dnsID, resolverID)
updateCustomResolverOptions.SetEnabled(true)
customResolver, _, err := c.dnsServicesAPI.UpdateCustomResolverWithContext(ctx, updateCustomResolverOptions)
if err != nil {
return nil, err
}
return customResolver, nil
}
// GetDNSZoneIDByName gets the CIS zone ID from its domain name.
func (c *Client) GetDNSZoneIDByName(ctx context.Context, name string, publish types.PublishingStrategy) (string, error) {
zones, err := c.GetDNSZones(ctx, publish)
if err != nil {
return "", err
}
for _, z := range zones {
if z.Name == name {
return z.ID, nil
}
}
return "", fmt.Errorf("DNS zone %q not found", name)
}
// GetDNSZones returns all of the active DNS zones managed by CIS.
func (c *Client) GetDNSZones(ctx context.Context, publish types.PublishingStrategy) ([]DNSZoneResponse, error) {
_, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
options := c.controllerAPI.NewListResourceInstancesOptions()
switch publish {
case types.ExternalPublishingStrategy:
options.SetResourceID(cisServiceID)
case types.InternalPublishingStrategy:
options.SetResourceID(dnsServiceID)
default:
return nil, errors.New("unknown publishing strategy")
}
listResourceInstancesResponse, _, err := c.controllerAPI.ListResourceInstances(options)
if err != nil {
return nil, fmt.Errorf("failed to get cis instance: %w", err)
}
var allZones []DNSZoneResponse
for _, instance := range listResourceInstancesResponse.Resources {
authenticator := &core.IamAuthenticator{
ApiKey: c.APIKey,
}
switch publish {
case types.ExternalPublishingStrategy:
zonesService, err := zonesv1.NewZonesV1(&zonesv1.ZonesV1Options{
Authenticator: authenticator,
Crn: instance.CRN,
})
if err != nil {
return nil, fmt.Errorf("failed to list DNS zones: %w", err)
}
options := zonesService.NewListZonesOptions()
listZonesResponse, _, err := zonesService.ListZones(options)
if listZonesResponse == nil {
return nil, err
}
for _, zone := range listZonesResponse.Result {
if *zone.Status == "active" {
zoneStruct := DNSZoneResponse{
Name: *zone.Name,
ID: *zone.ID,
InstanceCRN: *instance.CRN,
InstanceName: *instance.Name,
ResourceGroupID: *instance.ResourceGroupID,
}
allZones = append(allZones, zoneStruct)
}
}
case types.InternalPublishingStrategy:
dnsZonesService, err := dnszonesv1.NewDnsZonesV1(&dnszonesv1.DnsZonesV1Options{
Authenticator: authenticator,
})
if err != nil {
return nil, fmt.Errorf("failed to list DNS zones: %w", err)
}
options := dnsZonesService.NewListDnszonesOptions(*instance.GUID)
listZonesResponse, _, err := dnsZonesService.ListDnszones(options)
if listZonesResponse == nil {
return nil, err
}
for _, zone := range listZonesResponse.Dnszones {
if *zone.State == "ACTIVE" || *zone.State == "PENDING_NETWORK_ADD" {
zoneStruct := DNSZoneResponse{
Name: *zone.Name,
ID: *zone.ID,
InstanceCRN: *instance.CRN,
InstanceName: *instance.Name,
ResourceGroupID: *instance.ResourceGroupID,
}
allZones = append(allZones, zoneStruct)
}
}
}
}
return allZones, nil
}
// GetDNSInstancePermittedNetworks gets the permitted VPC networks for a DNS Services instance.
func (c *Client) GetDNSInstancePermittedNetworks(ctx context.Context, dnsID string, dnsZone string) ([]string, error) {
_, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
listPermittedNetworksOptions := c.dnsServicesAPI.NewListPermittedNetworksOptions(dnsID, dnsZone)
permittedNetworks, _, err := c.dnsServicesAPI.ListPermittedNetworksWithContext(ctx, listPermittedNetworksOptions)
if err != nil {
return nil, err
}
networks := []string{}
for _, network := range permittedNetworks.PermittedNetworks {
networks = append(networks, *network.PermittedNetwork.VpcCrn)
}
return networks, nil
}
// AddVPCToPermittedNetworks adds the specified VPC to the specified DNS zone.
func (c *Client) AddVPCToPermittedNetworks(ctx context.Context, vpcCRN string, dnsID string, dnsZone string) error {
permittedNetwork, err := c.dnsServicesAPI.NewPermittedNetworkVpc(vpcCRN)
if err != nil {
return err
}
createPermittedNetworkOptions := c.dnsServicesAPI.NewCreatePermittedNetworkOptions(dnsID, dnsZone, dnssvcsv1.CreatePermittedNetworkOptions_Type_Vpc, permittedNetwork)
_, _, err = c.dnsServicesAPI.CreatePermittedNetworkWithContext(ctx, createPermittedNetworkOptions)
if err != nil {
return err
}
return nil
}
// CreateDNSRecord Creates a DNS CNAME record in the given base domain and CRN.
func (c *Client) CreateDNSRecord(ctx context.Context, publish types.PublishingStrategy, crnstr string, baseDomain string, hostname string, cname string) error {
switch publish {
case types.InternalPublishingStrategy:
return c.createPrivateDNSRecord(ctx, crnstr, baseDomain, hostname, cname)
case types.ExternalPublishingStrategy:
return c.createPublicDNSRecord(ctx, crnstr, baseDomain, hostname, cname)
default:
return fmt.Errorf("publish strategy %q not supported", publish)
}
}
func (c *Client) createPublicDNSRecord(ctx context.Context, crnstr string, baseDomain string, hostname string, cname string) error {
logrus.Debugf("createDNSRecord: crnstr = %s, hostname = %s, cname = %s", crnstr, hostname, cname)
var (
zoneID string
err error
authenticator *core.IamAuthenticator
globalOptions *dnsrecordsv1.DnsRecordsV1Options
dnsRecordService *dnsrecordsv1.DnsRecordsV1
)
// Get CIS zone ID by name
zoneID, err = c.GetDNSZoneIDByName(ctx, baseDomain, types.ExternalPublishingStrategy)
if err != nil {
logrus.Errorf("c.GetDNSZoneIDByName returns %v", err)
return err
}
logrus.Debugf("CreatePublicDNSRecord: zoneID = %s", zoneID)
authenticator = &core.IamAuthenticator{
ApiKey: c.APIKey,
}
globalOptions = &dnsrecordsv1.DnsRecordsV1Options{
Authenticator: authenticator,
Crn: ptr.To(crnstr),
ZoneIdentifier: ptr.To(zoneID),
}
dnsRecordService, err = dnsrecordsv1.NewDnsRecordsV1(globalOptions)
if err != nil {
logrus.Errorf("dnsrecordsv1.NewDnsRecordsV1 returns %v", err)
return err
}
logrus.Debugf("CreatePublicDNSRecord: dnsRecordService = %+v", dnsRecordService)
createOptions := dnsRecordService.NewCreateDnsRecordOptions()
createOptions.SetName(hostname)
createOptions.SetType(dnsrecordsv1.CreateDnsRecordOptions_Type_Cname)
createOptions.SetContent(cname)
result, response, err := dnsRecordService.CreateDnsRecord(createOptions)
if err != nil {
logrus.Errorf("dnsRecordService.CreateDnsRecord returns %v", err)
return err
}
logrus.Debugf("createPublicDNSRecord: Result.ID = %v, RawResult = %v", *result.Result.ID, response.RawResult)
return nil
}
func (c *Client) createPrivateDNSRecord(ctx context.Context, crnstr string, baseDomain string, hostname string, cname string) error {
logrus.Debugf("createPrivateDNSRecord: crnstr = %s, hostname = %s, cname = %s", crnstr, hostname, cname)
zoneID, err := c.GetDNSZoneIDByName(ctx, baseDomain, types.InternalPublishingStrategy)
if err != nil {
logrus.Errorf("c.GetDNSZoneIDByName returns %v", err)
return err
}
logrus.Debugf("createPrivateDNSRecord: zoneID = %s", zoneID)
dnsCRN, err := crn.Parse(crnstr)
if err != nil {
return fmt.Errorf("failed to parse DNSInstanceCRN: %w", err)
}
rdataCnameRecord, err := c.dnsServicesAPI.NewResourceRecordInputRdataRdataCnameRecord(cname)
if err != nil {
return fmt.Errorf("NewResourceRecordInputRdataRdataCnameRecord failed: %w", err)
}
createOptions := c.dnsServicesAPI.NewCreateResourceRecordOptions(dnsCRN.ServiceInstance, zoneID, dnssvcsv1.CreateResourceRecordOptions_Type_Cname)
createOptions.SetRdata(rdataCnameRecord)
createOptions.SetTTL(120)
createOptions.SetName(hostname)
result, resp, err := c.dnsServicesAPI.CreateResourceRecord(createOptions)
if err != nil {
logrus.Errorf("dnsRecordService.CreateResourceRecord returns %v", err)
return err
}
logrus.Debugf("createPrivateDNSRecord: result.ID = %v, resp.RawResult = %v", *result.ID, resp.RawResult)
return nil
}
// GetVPCByName gets a VPC by its name.
func (c *Client) GetVPCByName(ctx context.Context, vpcName string) (*vpcv1.VPC, error) {
_, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
listRegionsOptions := c.vpcAPI.NewListRegionsOptions()
listRegionsResponse, _, err := c.vpcAPI.ListRegionsWithContext(ctx, listRegionsOptions)
if err != nil {
return nil, fmt.Errorf("failed to list vpc regions: %w", err)
}
var vpcNamesList []string
for _, region := range listRegionsResponse.Regions {
err := c.vpcAPI.SetServiceURL(fmt.Sprintf("%s/v1", *region.Endpoint))
if err != nil {
return nil, fmt.Errorf("failed to set vpc api service url: %w", err)
}
vpcs, detailedResponse, err := c.vpcAPI.ListVpcsWithContext(ctx, c.vpcAPI.NewListVpcsOptions())
if err != nil {
if detailedResponse.GetStatusCode() != http.StatusNotFound {
return nil, err
}
} else {
for _, vpc := range vpcs.Vpcs {
vpcNamesList = append(vpcNamesList, *vpc.Name)
if *vpc.Name == vpcName {
return &vpc, nil
}
}
}
}
return nil, fmt.Errorf("failed to find VPC %q. Available VPCs: %v", vpcName, vpcNamesList)
}
// GetVPCByID checks if an id is a valid VPC id and, if so, returns the VPC.
func (c *Client) GetVPCByID(ctx context.Context, vpcID string, region string) (*vpcv1.VPC, error) {
vpcs, err := c.GetVPCs(ctx, region)
if err != nil {
return nil, err
}
for _, vpc := range vpcs {
if *vpc.ID == vpcID {
return &vpc, nil
}
}
return nil, fmt.Errorf("VPC with id (%s) does not exist in region (%s)", vpcID, region)
}
// GetPublicGatewayByVPC gets all PublicGateways in a region
func (c *Client) GetPublicGatewayByVPC(ctx context.Context, vpcName string) (*vpcv1.PublicGateway, error) {
_, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
vpc, err := c.GetVPCByName(ctx, vpcName)
if err != nil {
return nil, fmt.Errorf("failed to get VPC: %w", err)
}
vpcCRN, err := crn.Parse(*vpc.CRN)
if err != nil {
return nil, fmt.Errorf("failed to parse VPC CRN: %w", err)
}
err = c.SetVPCServiceURLForRegion(ctx, vpcCRN.Region)
if err != nil {
return nil, err
}
listPublicGatewaysOptions := c.vpcAPI.NewListPublicGatewaysOptions()
publicGatewayCollection, detailedResponse, err := c.vpcAPI.ListPublicGatewaysWithContext(ctx, listPublicGatewaysOptions)
if err != nil {
return nil, err
} else if detailedResponse.GetStatusCode() == http.StatusNotFound {
return nil, errors.New("failed to find publicGateways")
}
for _, gw := range publicGatewayCollection.PublicGateways {
if *vpc.ID == *gw.VPC.ID {
return &gw, nil
}
}
return nil, nil
}
// GetVPCSubnets retrieves all subnets in the given VPC.
func (c *Client) GetVPCSubnets(ctx context.Context, vpcID string) ([]vpcv1.Subnet, error) {
listSubnetsOptions := c.vpcAPI.NewListSubnetsOptions()
listSubnetsOptions.VPCID = &vpcID
subnets, _, err := c.vpcAPI.ListSubnetsWithContext(ctx, listSubnetsOptions)
if err != nil {
return nil, err
}
return subnets.Subnets, nil
}
// GetSubnetByName gets a VPC Subnet by its name and region.
func (c *Client) GetSubnetByName(ctx context.Context, subnetName string, region string) (*vpcv1.Subnet, error) {
_, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
err := c.SetVPCServiceURLForRegion(ctx, region)
if err != nil {
return nil, err
}
listSubnetsOptions := c.vpcAPI.NewListSubnetsOptions()
subnetCollection, detailedResponse, err := c.vpcAPI.ListSubnetsWithContext(ctx, listSubnetsOptions)
if err != nil {
return nil, err
} else if detailedResponse.GetStatusCode() == http.StatusNotFound {
return nil, errors.New("failed to find VPC Subnet")
}
for _, subnet := range subnetCollection.Subnets {
if subnetName == *subnet.Name {
return &subnet, nil
}
}
return nil, errors.New("failed to find VPC Subnet")
}
func (c *Client) loadResourceManagementAPI() error {
authenticator := &core.IamAuthenticator{
ApiKey: c.APIKey,
}
options := &resourcemanagerv2.ResourceManagerV2Options{
Authenticator: authenticator,
}
resourceManagerV2Service, err := resourcemanagerv2.NewResourceManagerV2(options)
if err != nil {
return err
}
c.managementAPI = resourceManagerV2Service
return nil
}
func (c *Client) loadResourceControllerAPI() error {
authenticator := &core.IamAuthenticator{
ApiKey: c.APIKey,
}
options := &resourcecontrollerv2.ResourceControllerV2Options{
Authenticator: authenticator,
}
resourceControllerV2Service, err := resourcecontrollerv2.NewResourceControllerV2(options)
if err != nil {
return err
}
c.controllerAPI = resourceControllerV2Service
return nil
}
func (c *Client) loadVPCV1API() error {
authenticator := &core.IamAuthenticator{
ApiKey: c.APIKey,
}
vpcService, err := vpcv1.NewVpcV1(&vpcv1.VpcV1Options{
Authenticator: authenticator,
})
if err != nil {
return err
}
c.vpcAPI = vpcService
return nil
}
func (c *Client) loadDNSServicesAPI() error {
authenticator := &core.IamAuthenticator{
ApiKey: c.APIKey,
}
dnsService, err := dnssvcsv1.NewDnsSvcsV1(&dnssvcsv1.DnsSvcsV1Options{
Authenticator: authenticator,
})
if err != nil {
return err
}
c.dnsServicesAPI = dnsService
return nil
}
func (c *Client) loadTransitGatewayAPI() error {
authenticator := &core.IamAuthenticator{
ApiKey: c.APIKey,
}
versionDate := "2023-07-04"
tgSvc, err := transitgatewayapisv1.NewTransitGatewayApisV1(&transitgatewayapisv1.TransitGatewayApisV1Options{
Authenticator: authenticator,
Version: &versionDate,
})
if err != nil {
return err
}
c.transitGatewayAPI = tgSvc
return nil
}
// SetVPCServiceURLForRegion will set the VPC Service URL to a specific IBM Cloud Region, in order to access Region scoped resources
func (c *Client) SetVPCServiceURLForRegion(ctx context.Context, region string) error {
regionOptions := c.vpcAPI.NewGetRegionOptions(region)
vpcRegion, _, err := c.vpcAPI.GetRegionWithContext(ctx, regionOptions)
if err != nil {
return err
}
err = c.vpcAPI.SetServiceURL(fmt.Sprintf("%s/v1", *vpcRegion.Endpoint))
if err != nil {
return err
}
return nil
}
// GetAuthenticatorAPIKeyDetails gets detailed information on the API key used
// for authentication to the IBM Cloud APIs.
func (c *Client) GetAuthenticatorAPIKeyDetails(ctx context.Context) (*iamidentityv1.APIKey, error) {
authenticator := &core.IamAuthenticator{
ApiKey: c.APIKey,
}
iamIdentityService, err := iamidentityv1.NewIamIdentityV1(&iamidentityv1.IamIdentityV1Options{
Authenticator: authenticator,
})
if err != nil {
return nil, err
}
options := iamIdentityService.NewGetAPIKeysDetailsOptions()
options.SetIamAPIKey(c.APIKey)
details, _, err := iamIdentityService.GetAPIKeysDetailsWithContext(ctx, options)
if err != nil {
return nil, err
}
// NOTE: details.Apikey
// https://cloud.ibm.com/apidocs/iam-identity-token-api?code=go#get-api-keys-details
// This property only contains the API key value for the following cases: create an API key,
// update a service ID API key that stores the API key value as retrievable, or get a service
// ID API key that stores the API key value as retrievable. All other operations don't return
// the API key value, for example all user API key related operations, except for create,
// don't contain the API key value.
return details, nil
}
// GetAPIKey returns the PowerVS API key
func (c *Client) GetAPIKey() string {
return c.APIKey
}
// GetVPCs gets all VPCs in a region.
func (c *Client) GetVPCs(ctx context.Context, region string) ([]vpcv1.VPC, error) {
ctx, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
err := c.SetVPCServiceURLForRegion(ctx, region)
if err != nil {
return nil, fmt.Errorf("failed to set vpc api service url: %w", err)
}
vpcs, _, err := c.vpcAPI.ListVpcs(c.vpcAPI.NewListVpcsOptions())
if err != nil {
return nil, err
}
return vpcs.Vpcs, nil
}
// ListResourceGroups returns a list of resource groups.
func (c *Client) ListResourceGroups(ctx context.Context) (*resourcemanagerv2.ResourceGroupList, error) {
listResourceGroupsOptions := c.managementAPI.NewListResourceGroupsOptions()
listResourceGroupsOptions.AccountID = &c.BXCli.User.Account
resourceGroups, _, err := c.managementAPI.ListResourceGroups(listResourceGroupsOptions)
if err != nil {
return nil, err
}
return resourceGroups, err
}
const (
// resource Id for Power Systems Virtual Server in the Global catalog.
powerIAASResourceID = "abd259f0-9990-11e8-acc8-b9f54a8f1661"
)
// ListServiceInstances lists all service instances in the cloud.
func (c *Client) ListServiceInstances(ctx context.Context) ([]string, error) {
var (
serviceInstances []string
options *resourcecontrollerv2.ListResourceInstancesOptions
resources *resourcecontrollerv2.ResourceInstancesList
err error
perPage int64 = 10
moreData = true
nextURL *string
groupID = c.BXCli.PowerVSResourceGroup
)
// If the user passes in a human readable group id, then we need to convert it to a UUID
listGroupOptions := c.managementAPI.NewListResourceGroupsOptions()
listGroupOptions.AccountID = &c.BXCli.User.Account
groups, _, err := c.managementAPI.ListResourceGroupsWithContext(ctx, listGroupOptions)
if err != nil {
return nil, fmt.Errorf("failed to list resource groups: %w", err)
}
for _, group := range groups.Resources {
if *group.Name == groupID {
groupID = *group.ID
}
}
options = c.controllerAPI.NewListResourceInstancesOptions()
options.SetResourceGroupID(groupID)
// resource ID for Power Systems Virtual Server in the Global catalog
options.SetResourceID(powerIAASResourceID)
options.SetLimit(perPage)
for moreData {
resources, _, err = c.controllerAPI.ListResourceInstancesWithContext(ctx, options)
if err != nil {
return nil, fmt.Errorf("failed to list resource instances: %w", err)
}
for _, resource := range resources.Resources {
var (
getResourceOptions *resourcecontrollerv2.GetResourceInstanceOptions
resourceInstance *resourcecontrollerv2.ResourceInstance
response *core.DetailedResponse
)
getResourceOptions = c.controllerAPI.NewGetResourceInstanceOptions(*resource.ID)
resourceInstance, response, err = c.controllerAPI.GetResourceInstance(getResourceOptions)
if err != nil {
return nil, fmt.Errorf("failed to get instance: %w", err)
}
if response != nil && response.StatusCode == http.StatusNotFound || response.StatusCode == http.StatusInternalServerError {
continue
}
if resourceInstance.Type != nil && (*resourceInstance.Type == serviceInstanceType || *resourceInstance.Type == compositeInstanceType) {
serviceInstances = append(serviceInstances, fmt.Sprintf("%s %s", *resource.Name, *resource.GUID))
}
}
// Based on: https://cloud.ibm.com/apidocs/resource-controller/resource-controller?code=go#list-resource-instances
nextURL, err = core.GetQueryParam(resources.NextURL, "start")
if err != nil {
return nil, fmt.Errorf("failed to GetQueryParam on start: %w", err)
}
if nextURL == nil {
options.SetStart("")
} else {
options.SetStart(*nextURL)
}
moreData = *resources.RowsCount == perPage
}
return serviceInstances, nil
}
// ServiceInstanceGUIDToName returns the name of the matching service instance GUID which was passed in.
func (c *Client) ServiceInstanceGUIDToName(ctx context.Context, id string) (string, error) {
var (
options *resourcecontrollerv2.ListResourceInstancesOptions
resources *resourcecontrollerv2.ResourceInstancesList
err error
perPage int64 = 10
moreData = true
nextURL *string
groupID = c.BXCli.PowerVSResourceGroup
)
// If the user passes in a human readable group id, then we need to convert it to a UUID
listGroupOptions := c.managementAPI.NewListResourceGroupsOptions()
listGroupOptions.AccountID = &c.BXCli.User.Account
groups, _, err := c.managementAPI.ListResourceGroupsWithContext(ctx, listGroupOptions)
if err != nil {
return "", fmt.Errorf("failed to list resource groups: %w", err)
}
for _, group := range groups.Resources {
if *group.Name == groupID {
groupID = *group.ID
}
}
options = c.controllerAPI.NewListResourceInstancesOptions()
options.SetResourceGroupID(groupID)
// resource ID for Power Systems Virtual Server in the Global catalog
options.SetResourceID(powerIAASResourceID)
options.SetLimit(perPage)
for moreData {
resources, _, err = c.controllerAPI.ListResourceInstancesWithContext(ctx, options)
if err != nil {
return "", fmt.Errorf("failed to list resource instances: %w", err)
}
for _, resource := range resources.Resources {
var (
getResourceOptions *resourcecontrollerv2.GetResourceInstanceOptions
resourceInstance *resourcecontrollerv2.ResourceInstance
response *core.DetailedResponse
)
getResourceOptions = c.controllerAPI.NewGetResourceInstanceOptions(*resource.ID)
resourceInstance, response, err = c.controllerAPI.GetResourceInstance(getResourceOptions)
if err != nil {
return "", fmt.Errorf("failed to get instance: %w", err)
}
if response != nil && response.StatusCode == http.StatusNotFound || response.StatusCode == http.StatusInternalServerError {
continue
}
if resourceInstance.Type != nil && (*resourceInstance.Type == serviceInstanceType || *resourceInstance.Type == compositeInstanceType) {
if resourceInstance.GUID != nil && *resourceInstance.GUID == id {
if resourceInstance.Name == nil {
return "", nil
}
return *resourceInstance.Name, nil
}
}
}