-
Notifications
You must be signed in to change notification settings - Fork 16
/
oke_manager_client.go
1910 lines (1621 loc) · 70.3 KB
/
oke_manager_client.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 2019 Oracle and/or its affiliates. All rights reserved.
//
// 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 oke
/*
ClusterManagerClient is a client for interacting with Oracle Cloud Engine API.
It does all of the real work in providing CRUD operations for the OKE cluster
and VCN.
*/
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/oracle/oci-go-sdk/v65/common"
"github.com/oracle/oci-go-sdk/v65/containerengine"
"github.com/oracle/oci-go-sdk/v65/core"
"github.com/oracle/oci-go-sdk/v65/example/helpers"
"github.com/oracle/oci-go-sdk/v65/identity"
"github.com/rancher/kontainer-engine/store"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
"gopkg.in/yaml.v2"
)
const (
// TODO VCN block only needs to be large enough for the subnets below
vcnCIDRBlock = "10.0.0.0/16"
controlPlaneCIDRBlock = "10.0.0.0/28"
nodeCIDRBlock = "10.0.10.0/24"
bastionCIDRBlock = "10.0.16.0/24"
serviceCIDRBlock = "10.0.20.0/24"
podCIDRBlock = "10.244.0.0/16"
servicesCIDRBlock = "10.96.0.0/16"
controlPlaneSubnetName = "k8sendpoint"
nodeSubnetName = "nodedns"
serviceSubnetName = "svclbsubnet"
bastionSubnetName = "bastionsubnet"
controlPlaneSubnetSecurityListName = "oke-k8sapiendpointseclist"
nodePoolSubnetSecurityListName = "oke-nodeseclist"
serviceSubnetSecurityListName = "oke-svclbseclist"
)
// Defines / contains the OCI/OKE/Identity clients and operations.
type ClusterManagerClient struct {
configuration common.ConfigurationProvider
containerEngineClient containerengine.ContainerEngineClient
computeClient core.ComputeClient
virtualNetworkClient core.VirtualNetworkClient
identityClient identity.IdentityClient
sleepDuration time.Duration
// TODO we could also include the retry settings here
}
// NewClusterManagerClient creates a new OCI cluster manager, which has a set of
// clients (CE, VCN, Identity).
func NewClusterManagerClient(configuration common.ConfigurationProvider) (*ClusterManagerClient, error) {
containerClient, err := containerengine.NewContainerEngineClientWithConfigurationProvider(configuration)
if err != nil {
logrus.Debugf("[oraclecontainerengine] create new ContainerEngine client failed with err %v", err)
return nil, err
}
coreComputeClient, err := core.NewComputeClientWithConfigurationProvider(configuration)
if err != nil {
logrus.Debugf("[oraclecontainerengine] create new Compute client failed with err %v", err)
return nil, err
}
vNetClient, err := core.NewVirtualNetworkClientWithConfigurationProvider(configuration)
if err != nil {
logrus.Debugf("[oraclecontainerengine] create new VirtualNetwork client failed with err %v", err)
return nil, err
}
identityClient, err := identity.NewIdentityClientWithConfigurationProvider(configuration)
if err != nil {
logrus.Debugf("[oraclecontainerengine] create new Identity client failed with err %v", err)
return nil, err
}
c := &ClusterManagerClient{
configuration: configuration,
containerEngineClient: containerClient,
computeClient: coreComputeClient,
virtualNetworkClient: vNetClient,
identityClient: identityClient,
sleepDuration: 5,
}
return c, nil
}
// CreateCluster creates a new cluster with no initial node pool and attaches
// it to the existing network resources, or an error.
// TODO stop passing in state
func (mgr *ClusterManagerClient) CreateCluster(ctx context.Context, state *State, vcnID string, controlPlaneSubnetID string, serviceSubnetIds, nodeSubnetIds []string) error {
if state == nil {
return fmt.Errorf("valid state is required")
}
logrus.Debugf("[oraclecontainerengine] creating cluster %s with VCN ID %s", state.Name, vcnID)
if state.KubernetesVersion == "" {
kubernetesVersion, err := getDefaultKubernetesVersion(mgr.containerEngineClient)
if err != nil {
return err
} else if kubernetesVersion == nil {
return fmt.Errorf("could not determine default Kubernetes version")
}
state.KubernetesVersion = *kubernetesVersion
}
var podCIDRRequest = common.String(state.Network.PodCidr)
if state.Network.PodCidr == podCIDRBlock {
podCIDRRequest = nil
}
var serviceCIDRRequest = common.String(state.Network.ServiceCidr)
if state.Network.ServiceCidr == servicesCIDRBlock {
serviceCIDRRequest = nil
}
cReq := containerengine.CreateClusterRequest{}
cReq.Name = common.String(state.Name)
cReq.CompartmentId = &state.CompartmentID
cReq.VcnId = common.String(vcnID)
if state.KmsKeyID != "" {
cReq.KmsKeyId = &state.KmsKeyID
}
cReq.KubernetesVersion = common.String(state.KubernetesVersion)
cReq.Options = &containerengine.ClusterCreateOptions{
ServiceLbSubnetIds: serviceSubnetIds,
AddOns: &containerengine.AddOnOptions{
IsKubernetesDashboardEnabled: common.Bool(state.EnableKubernetesDashboard),
IsTillerEnabled: common.Bool(state.EnableTiller),
},
KubernetesNetworkConfig: &containerengine.KubernetesNetworkConfig{
PodsCidr: podCIDRRequest,
ServicesCidr: serviceCIDRRequest,
},
}
if len(controlPlaneSubnetID) > 0 {
cReq.EndpointConfig = &containerengine.CreateClusterEndpointConfigDetails{
SubnetId: common.String(controlPlaneSubnetID),
IsPublicIpEnabled: negate(state.PrivateControlPlane),
}
}
clusterResp, err := mgr.containerEngineClient.CreateCluster(ctx, cReq)
if err != nil {
return err
}
// wait until cluster creation work request complete
logrus.Debugf("[oraclecontainerengine] waiting for cluster %s to reach Active status..", state.Name)
// initial delay since subsequent back-off function waits longer each time the retry fails
time.Sleep(time.Minute * 3)
workReqRespCluster, err := waitUntilWorkRequestComplete(mgr.containerEngineClient, clusterResp.OpcWorkRequestId)
if err != nil {
logrus.Debugf("[oraclecontainerengine] get work request failed with err %v", err)
return err
} else if containerengine.WorkRequestStatusFailed == workReqRespCluster.WorkRequest.Status {
logrus.Debugf("[oraclecontainerengine] work request operation type %v returned with status %v",
workReqRespCluster.WorkRequest.OperationType,
workReqRespCluster.WorkRequest.Status)
return fmt.Errorf("work request operation type %v returned with status %v",
workReqRespCluster.WorkRequest.OperationType,
workReqRespCluster.WorkRequest.Status)
}
clusterID := getResourceID(workReqRespCluster.Resources, containerengine.WorkRequestResourceActionTypeCreated, string(containerengine.ListWorkRequestsResourceTypeCluster))
if clusterID == nil {
return fmt.Errorf("could not retrieve clusterID")
}
logrus.Debugf("[oraclecontainerengine] clusterID: %s has been created", *clusterID)
state.ClusterID = *clusterID
return nil
}
// GetClusterByID returns the cluster with the specified Id, or an error
func (mgr *ClusterManagerClient) GetClusterByID(ctx context.Context, clusterID string) (containerengine.Cluster, error) {
logrus.Debugf("[oraclecontainerengine] getting cluster with Cluster ID %s", clusterID)
if len(clusterID) == 0 {
return containerengine.Cluster{}, fmt.Errorf("clusterID must be set to retrieve the cluster")
}
req := containerengine.GetClusterRequest{}
req.ClusterId = common.String(clusterID)
resp, err := mgr.containerEngineClient.GetCluster(ctx, req)
if err != nil {
logrus.Debugf("[oraclecontainerengine] get cluster request failed with err %v", err)
return containerengine.Cluster{}, err
}
return resp.Cluster, nil
}
// GetClusterByName returns the Cluster ID of the Cluster with the specified
// name in the specified compartment or an error if it is not found.
func (mgr *ClusterManagerClient) GetClusterByName(ctx context.Context, compartmentID, name string) (string, error) {
logrus.Debugf("[oraclecontainerengine] getting cluster with name %s", name)
if len(compartmentID) == 0 {
return "", fmt.Errorf("compartmentID must be set to retrieve the cluster")
} else if len(name) == 0 {
return "", fmt.Errorf("name must be set to retrieve the cluster")
}
listClustersReq := containerengine.ListClustersRequest{}
listClustersReq.CompartmentId = common.String(compartmentID)
listClustersReq.Name = common.String(name)
listClustersResp, err := mgr.containerEngineClient.ListClusters(ctx, listClustersReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list clusters failed with err %v", err)
return "", err
}
for _, cluster := range listClustersResp.Items {
if *cluster.Name == name {
return *cluster.Id, nil
}
}
return "", fmt.Errorf("%s not found", name)
}
// CreateNodePool creates a new node pool (i.e. a set of compute nodes) for the
// cluster, or an error.
// TODO stop passing in state
func (mgr *ClusterManagerClient) CreateNodePool(ctx context.Context, state *State, vcnID string, serviceSubnetIds, nodeSubnetIds []string) error {
if state == nil {
return fmt.Errorf("valid state is required")
}
logrus.Debugf("[oraclecontainerengine] creating node pool %s with VCN ID %s", state.Name, vcnID)
if state.KubernetesVersion == "" {
kubernetesVersion, err := getDefaultKubernetesVersion(mgr.containerEngineClient)
if err != nil {
return err
}
state.KubernetesVersion = *kubernetesVersion
}
// Create a node pool for the cluster
npReq := containerengine.CreateNodePoolRequest{}
// get Image Id from OKE
image, err := mgr.getImageID(ctx, mgr.computeClient, state.CompartmentID, state.NodePool.NodeShape, state.NodePool.NodeImageName)
if err != nil {
logrus.Printf("[oraclecontainerengine] Node image ID not found")
return err
}
logrus.Printf("[oraclecontainerengine] Node image ID found %v", image)
// Set a custom boot volume size if set
if state.NodePool.CustomBootVolumeSize != 0 {
npReq.NodeSourceDetails = containerengine.NodeSourceViaImageDetails{ImageId: common.String(image),
BootVolumeSizeInGBs: common.Int64(state.NodePool.CustomBootVolumeSize)}
} else {
npReq.NodeSourceDetails = containerengine.NodeSourceViaImageDetails{ImageId: common.String(image)}
}
req := identity.ListAvailabilityDomainsRequest{}
req.CompartmentId = &state.CompartmentID
allADs, err := mgr.identityClient.ListAvailabilityDomains(ctx, req)
if err != nil {
return err
}
// Our particular image may not be available in every available AD
usableADs := make([]identity.AvailabilityDomain, 0, len(allADs.Items))
// Only add the AD to usableADs if our image is available.
for i := 0; i < len(allADs.Items); i++ {
listShapesReq := core.ListShapesRequest{}
listShapesReq.ImageId = common.String(image)
listShapesReq.CompartmentId = common.String(state.CompartmentID)
listShapesReq.AvailabilityDomain = allADs.Items[i].Name
listShapes, err := mgr.computeClient.ListShapes(ctx, listShapesReq)
if err != nil {
return err
}
for _, shape := range listShapes.Items {
if *shape.Shape == state.NodePool.NodeShape {
usableADs = append(usableADs, allADs.Items[i])
}
}
}
npReq.Name = common.String(state.Name + "-1")
npReq.CompartmentId = common.String(state.CompartmentID)
npReq.ClusterId = &state.ClusterID
npReq.KubernetesVersion = &state.KubernetesVersion
npReq.NodeShape = common.String(state.NodePool.NodeShape)
if state.NodePool.FlexOCPUs != 0 {
logrus.Debugf("[oraclecontainerengine] creating node-pool with %d OCPUs", state.NodePool.FlexOCPUs)
var ocpus = float32(state.NodePool.FlexOCPUs)
npReq.NodeShapeConfig = &containerengine.CreateNodeShapeConfigDetails{Ocpus: &ocpus}
}
// Node-pool subnet(s) used for node instances in the node pool.
// These subnets should be different from the cluster Kubernetes Service LB subnets.
npReq.InitialNodeLabels = []containerengine.KeyValue{{Key: common.String("driver"), Value: common.String("oraclekubernetesengine")}}
if state.NodePool.NodePublicSSHKeyContents != "" {
npReq.SshPublicKey = common.String(state.NodePool.NodePublicSSHKeyContents)
}
if state.NodePool.NodeUserDataContents != "" {
nodeMetadata := make(map[string]string)
nodeMetadata["user_data"] = state.NodePool.NodeUserDataContents
npReq.NodeMetadata = nodeMetadata
}
npReq.NodeConfigDetails = &containerengine.CreateNodePoolNodeConfigDetails{
PlacementConfigs: make([]containerengine.NodePoolPlacementConfigDetails, 0, len(usableADs)),
Size: common.Int(limitN(int(state.NodePool.QuantityPerSubnet)*len(usableADs), int(state.NodePool.LimitNodeCount))),
}
// Match up subnet(s) to availability domains
for i := 0; i < len(usableADs); i++ {
nextSubnetId := ""
if len(nodeSubnetIds) == 1 {
// use a single regional subnet (default)
nextSubnetId = nodeSubnetIds[0]
} else {
// use AD specific subnets (possibly coming from an existing VCN)
nextSubnetId = nodeSubnetIds[i]
}
npReq.NodeConfigDetails.PlacementConfigs = append(npReq.NodeConfigDetails.PlacementConfigs,
containerengine.NodePoolPlacementConfigDetails{
AvailabilityDomain: usableADs[i].Name,
SubnetId: &nextSubnetId,
})
}
createNodePoolResp, err := mgr.containerEngineClient.CreateNodePool(ctx, npReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] create node pool request failed with err %v", err)
return err
}
// wait until cluster creation work request complete
logrus.Debugf("[oraclecontainerengine] waiting for node pool to be created...")
workReqRespNodePool, err := waitUntilWorkRequestComplete(mgr.containerEngineClient, createNodePoolResp.OpcWorkRequestId)
if err != nil {
logrus.Debugf("[oraclecontainerengine] get work request failed with err %v", err)
return err
}
// Wait for at least one individual nodes in the node pool to be created
if state.NodePool.QuantityPerSubnet > 0 {
nodePoolID := getResourceID(workReqRespNodePool.Resources, containerengine.WorkRequestResourceActionTypeCreated,
string(containerengine.ListWorkRequestsResourceTypeNodepool))
if nodePoolID == nil {
return fmt.Errorf("could not retrieve node pool ID")
}
doneWaiting := false
for retry := 15; retry > 0; retry-- {
np, err := mgr.GetNodePoolByID(ctx, *nodePoolID)
if err != nil {
doneWaiting = true
}
for _, node := range np.Nodes {
if node.LifecycleState != containerengine.NodeLifecycleStateCreating && node.LifecycleState !=
containerengine.NodeLifecycleStateUpdating && node.LifecycleState !=
containerengine.NodeLifecycleStateFailing {
doneWaiting = true
break
}
time.Sleep(1 * time.Minute)
}
if doneWaiting {
break
}
}
}
return nil
}
func (mgr *ClusterManagerClient) getImageID(ctx context.Context, c core.ComputeClient, compartment, shape, displayName string) (string, error) {
request := containerengine.GetNodePoolOptionsRequest{
NodePoolOptionId: common.String("all"),
}
r, err := mgr.containerEngineClient.GetNodePoolOptions(ctx, request)
if err != nil {
logrus.Debugf("[oraclecontainerengine] listing image id's failed with err %v", err)
return "", err
}
for _, i := range r.Sources {
if strings.Compare(displayName, *i.GetSourceName()) == 0 {
return *i.(containerengine.NodeSourceViaImageOption).ImageId, nil
}
}
logrus.Debugf("[oraclecontainerengine] unable to find an image for displayName: %s", displayName)
return "", err
}
// GetNodePoolByID returns the node pool with the specified Id, or an error.
func (mgr *ClusterManagerClient) GetNodePoolByID(ctx context.Context, nodePoolID string) (containerengine.NodePool, error) {
logrus.Debugf("[oraclecontainerengine] getting node pool with node pool ID %s", nodePoolID)
if len(nodePoolID) == 0 {
return containerengine.NodePool{}, fmt.Errorf("nodePoolID must be set to retrieve the node pool")
}
req := containerengine.GetNodePoolRequest{}
req.NodePoolId = common.String(nodePoolID)
resp, err := mgr.containerEngineClient.GetNodePool(ctx, req)
if err != nil {
logrus.Debugf("[oraclecontainerengine] get node pool request failed with err %v", err)
return containerengine.NodePool{}, err
}
return resp.NodePool, nil
}
// ScaleNodePool updates the number of nodes in the node pool, or an error.
func (mgr *ClusterManagerClient) ScaleNodePool(ctx context.Context, nodePoolID string, numNodes int, compartmentID string) error {
logrus.Debugf("[oraclecontainerengine] scaling node pool %s to %d nodes", nodePoolID, numNodes)
npReq := containerengine.UpdateNodePoolRequest{}
npReq.NodePoolId = common.String(nodePoolID)
npReq.NodeConfigDetails = &containerengine.UpdateNodePoolNodeConfigDetails{
Size: common.Int(numNodes),
}
_, err := mgr.containerEngineClient.UpdateNodePool(ctx, npReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] scale node pool request failed with err %v", err)
return err
}
// TODO consider optionally waiting until request is complete
return nil
}
// UpdateKubernetesMasterVersion updates the version of Kubernetes on the master(s),
// or an error.
func (mgr *ClusterManagerClient) UpdateMasterKubernetesVersion(ctx context.Context, clusterID, version string) error {
logrus.Debugf("[oraclecontainerengine] updating master Kubernetes version of cluster ID %s to %s", clusterID, version)
if len(clusterID) == 0 {
return fmt.Errorf("clusterID must be set to upgrade the master(s)")
}
clReq := containerengine.UpdateClusterRequest{}
clReq.ClusterId = common.String(clusterID)
clReq.KubernetesVersion = common.String(version)
cl, err := mgr.GetClusterByID(ctx, clusterID)
if err == nil {
logrus.Debugf("[oraclecontainerengine] current Kubernetes version of cluster is %s", *cl.KubernetesVersion)
} else {
logrus.Debugf("[oraclecontainerengine] cluster ID lookup failed with error %v", err)
return err
}
cpRes, err := mgr.containerEngineClient.UpdateCluster(ctx, clReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] update Kubernetes version on cluster failed with err %v", err)
return err
}
// wait until node pool deletion work request complete
logrus.Debugf("[oraclecontainerengine] waiting for cluster master version update...")
_, err = waitUntilWorkRequestComplete(mgr.containerEngineClient, cpRes.OpcWorkRequestId)
if err != nil {
logrus.Debugf("[oraclecontainerengine] get work request failed with err %v", err)
return err
}
return nil
}
// UpdateNodepoolKubernetesVersion updates the version of Kubernetes on (new)
// worker that will be added to the node pool. Be sure to call
// UpdateKubernetesMasterVersion before updating the version of node pools, or
// an error.
func (mgr *ClusterManagerClient) UpdateNodepoolKubernetesVersion(ctx context.Context, nodePoolID, version string) error {
logrus.Debugf("[oraclecontainerengine] updating node pool Kubernetes version of node pool ID %s to %s", nodePoolID, version)
if len(nodePoolID) == 0 {
return fmt.Errorf("nodePoolID must be set to upgrade the node pool")
}
npReq := containerengine.UpdateNodePoolRequest{}
npReq.NodePoolId = common.String(nodePoolID)
npReq.KubernetesVersion = common.String(version)
np, err := mgr.GetNodePoolByID(ctx, nodePoolID)
if err == nil {
logrus.Debugf("[oraclecontainerengine] current Kubernetes version of node pool is %s", *np.KubernetesVersion)
} else {
logrus.Debugf("[oraclecontainerengine] node pool lookup failed with error %v", err)
return err
}
// New nodes added to this node pool will run the updated version
_, err = mgr.containerEngineClient.UpdateNodePool(ctx, npReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] update Kubernetes version on node pool failed with err %v", err)
return err
}
// TODO consider optionally waiting until request is complete
return nil
}
// GetVcnIDByClusterID returns the VCN ID for the existing cluster with the
// specified Id, or an error.
func (mgr *ClusterManagerClient) GetVcnIDByClusterID(ctx context.Context, clusterID string) (string, error) {
logrus.Debugf("[oraclecontainerengine] getting cluster VCN with cluster ID %s", clusterID)
cluster, err := mgr.GetClusterByID(ctx, clusterID)
if err != nil {
return "", err
}
return *cluster.VcnId, nil
}
// GetVcnIDByName returns the VCN ID of the VCN with the specified name in the
// specified compartment or an error if it is not found.
func (mgr *ClusterManagerClient) GetVcnIDByName(ctx context.Context, compartmentID, displayName string) (string, error) {
vcn, err := mgr.GetVcnByName(ctx, compartmentID, displayName)
if vcn.Id == nil {
return "", err
}
return *vcn.Id, err
}
// GetVcnIDByName returns the VCN with the specified name in the specified compartment or an error if it is not found.
func (mgr *ClusterManagerClient) GetVcnByName(ctx context.Context, compartmentID, displayName string) (core.Vcn, error) {
logrus.Debugf("[oraclecontainerengine] getting VCN with name %s", displayName)
vcn := core.Vcn{}
if len(compartmentID) == 0 {
return vcn, fmt.Errorf("compartmentID must be set to retrieve its VCN")
} else if len(displayName) == 0 {
return vcn, fmt.Errorf("displayName must be set to retrieve its VCN")
}
listVcnsReq := core.ListVcnsRequest{}
listVcnsReq.CompartmentId = common.String(compartmentID)
listVcnsReq.DisplayName = common.String(displayName)
listVcnsResp, err := mgr.virtualNetworkClient.ListVcns(ctx, listVcnsReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list VCNs failed with err %v", err)
return vcn, err
}
for _, vcn := range listVcnsResp.Items {
if *vcn.DisplayName == displayName {
return vcn, nil
}
}
return vcn, fmt.Errorf("%s not found", displayName)
}
// GetSubnetIDByName returns the subnet ID of the subnet with the specified name
// in the specified VCN and compartment, or an error if it is not found.
func (mgr *ClusterManagerClient) GetSubnetIDByName(ctx context.Context, compartmentID, vcnID, displayName string) (string, error) {
subnet, err := mgr.GetSubnetByName(ctx, compartmentID, vcnID, displayName)
if subnet.Id == nil {
return "", err
}
return *subnet.Id, err
}
// GetSubnetByName returns the subnet with the specified name in the specified
// VCN and compartment, or an error if it is not found.
func (mgr *ClusterManagerClient) GetSubnetByName(ctx context.Context, compartmentID, vcnID, displayName string) (core.Subnet, error) {
logrus.Debugf("[oraclecontainerengine] getting subnet with name %s", displayName)
subnet := core.Subnet{}
if len(compartmentID) == 0 {
return subnet, fmt.Errorf("compartmentID must be set to get the subnet")
} else if len(displayName) == 0 {
return subnet, fmt.Errorf("displayName must be set to get the subnet")
}
listSubnetsReq := core.ListSubnetsRequest{}
listSubnetsReq.CompartmentId = common.String(compartmentID)
listSubnetsReq.VcnId = common.String(vcnID)
listSubnetsReq.DisplayName = common.String(displayName)
listSubnetsResp, err := mgr.virtualNetworkClient.ListSubnets(ctx, listSubnetsReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list subnets failed with err %v", err)
return subnet, err
}
for _, subnet := range listSubnetsResp.Items {
if *subnet.DisplayName == displayName {
return subnet, nil
}
}
return subnet, fmt.Errorf("%s not found", displayName)
}
// GetSubnetById returns the subnet with the specified id, or an error if it is not found.
func (mgr *ClusterManagerClient) GetSubnetById(ctx context.Context, subnetId string) (core.Subnet, error) {
logrus.Debugf("[oraclecontainerengine] getting subnet with ID %s", subnetId)
subnet := core.Subnet{}
if len(subnetId) == 0 {
return subnet, fmt.Errorf("subnetId must be set to get the subnet")
}
getSubnetsReq := core.GetSubnetRequest{}
getSubnetsReq.SubnetId = common.String(subnetId)
getSubnetResp, err := mgr.virtualNetworkClient.GetSubnet(ctx, getSubnetsReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list subnets failed with err %v", err)
return subnet, err
}
return getSubnetResp.Subnet, nil
}
// ListSubnetIdsInVcn returns the subnet IDs of any and all subnets in the
// specified VCN.
func (mgr *ClusterManagerClient) ListSubnetIdsInVcn(ctx context.Context, compartmentID, vcnID string) ([]string, error) {
logrus.Debugf("[oraclecontainerengine] list subnet Ids called")
var ids []string
if len(compartmentID) == 0 {
return ids, fmt.Errorf("compartmentID must be set to list the subnets in the VCN")
} else if len(vcnID) == 0 {
return ids, fmt.Errorf("vcnID must be set to list the subnets in the VCN")
}
listSubnetsReq := core.ListSubnetsRequest{}
listSubnetsReq.CompartmentId = common.String(compartmentID)
listSubnetsReq.VcnId = common.String(vcnID)
listSubnetsResp, err := mgr.virtualNetworkClient.ListSubnets(ctx, listSubnetsReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list subnets failed with err %v", err)
return ids, err
}
for _, subnet := range listSubnetsResp.Items {
ids = append(ids, *subnet.Id)
}
// subnet ids may be empty
return ids, nil
}
// ListRouteTableIdsInVcn returns the route table IDs of any and all route tables
// in the specified VCN.
func (mgr *ClusterManagerClient) ListRouteTableIdsInVcn(ctx context.Context, compartmentID, vcnID string) ([]string, error) {
logrus.Debugf("[oraclecontainerengine] list route table Ids called")
var ids []string
if len(compartmentID) == 0 {
return ids, fmt.Errorf("compartmentID must be set to list the route table in the VCN")
} else if len(vcnID) == 0 {
return ids, fmt.Errorf("vcnID must be set to list the route table in the VCN")
}
listRouteTablesReq := core.ListRouteTablesRequest{}
listRouteTablesReq.CompartmentId = common.String(compartmentID)
listRouteTablesReq.VcnId = common.String(vcnID)
listRouteTablesResp, err := mgr.virtualNetworkClient.ListRouteTables(ctx, listRouteTablesReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list route tables failed with err %v", err)
return ids, err
}
for _, rt := range listRouteTablesResp.Items {
ids = append(ids, *rt.Id)
}
// route table ids may be empty
return ids, nil
}
// ListInternetGatewayIdsInVcn returns the route table IDs of any and all
// Internet gateways in the specified VCN.
func (mgr *ClusterManagerClient) ListInternetGatewayIdsInVcn(ctx context.Context, compartmentID, vcnID string) ([]string, error) {
logrus.Debugf("[oraclecontainerengine] list Internet gateway Ids called")
var ids []string
if len(compartmentID) == 0 {
return ids, fmt.Errorf("compartmentID must be set to list the Internet gateway in the VCN")
} else if len(vcnID) == 0 {
return ids, fmt.Errorf("vcnID must be set to list the Internet gateway in the VCN")
}
listInternetGatewaysReq := core.ListInternetGatewaysRequest{}
listInternetGatewaysReq.CompartmentId = common.String(compartmentID)
listInternetGatewaysReq.VcnId = common.String(vcnID)
listRouteTablesResp, err := mgr.virtualNetworkClient.ListInternetGateways(ctx, listInternetGatewaysReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list Internet gateways failed with err %v", err)
return ids, err
}
for _, ig := range listRouteTablesResp.Items {
ids = append(ids, *ig.Id)
}
// route table ids may be empty
return ids, nil
}
// ListNatGatewayIdsInVcn returns the NAT gateway IDs of any and all NAT
// gateways in the specified VCN.
func (mgr *ClusterManagerClient) ListNatGatewayIdsInVcn(ctx context.Context, compartmentID, vcnID string) ([]string, error) {
logrus.Debugf("[oraclecontainerengine] list NAT gateway Ids called")
var ids []string
if len(compartmentID) == 0 {
return ids, fmt.Errorf("compartmentID must be set to list the NAT gateway in the VCN")
} else if len(vcnID) == 0 {
return ids, fmt.Errorf("vcnID must be set to list the NAT gateway in the VCN")
}
listInternetGatewaysReq := core.ListNatGatewaysRequest{}
listInternetGatewaysReq.CompartmentId = common.String(compartmentID)
listInternetGatewaysReq.VcnId = common.String(vcnID)
listNATGatewaysResp, err := mgr.virtualNetworkClient.ListNatGateways(ctx, listInternetGatewaysReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list NAT gateways failed with err %v", err)
return ids, err
}
for _, nGW := range listNATGatewaysResp.Items {
ids = append(ids, *nGW.Id)
}
// NAT gateway ids may be empty
return ids, nil
}
// ListSecurityListIdsInVcn returns the security list IDs of any and all security
// lists in the specified VCN.
func (mgr *ClusterManagerClient) ListSecurityListIdsInVcn(ctx context.Context, compartmentID, vcnID string) ([]string, error) {
logrus.Debugf("[oraclecontainerengine] list security list Ids called")
var ids []string
if len(compartmentID) == 0 {
return ids, fmt.Errorf("compartmentID must be set to list the security lists in the VCN")
} else if len(vcnID) == 0 {
return ids, fmt.Errorf("vcnID must be set to list the security lists in the VCN")
}
listSecurityListsReq := core.ListSecurityListsRequest{}
listSecurityListsReq.CompartmentId = common.String(compartmentID)
listSecurityListsReq.VcnId = common.String(vcnID)
listSecurityListsResp, err := mgr.virtualNetworkClient.ListSecurityLists(ctx, listSecurityListsReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list security lists failed with err %v", err)
return ids, err
}
for _, sl := range listSecurityListsResp.Items {
ids = append(ids, *sl.Id)
}
// route table ids may be empty
return ids, nil
}
// ListNodepoolIdsInCluster returns the node pool IDs of any and all node pools
// in the specified cluster.
func (mgr *ClusterManagerClient) ListNodepoolIdsInCluster(ctx context.Context, compartmentID, clusterID string) ([]string, error) {
logrus.Debugf("[oraclecontainerengine] list node pool ID(s) for cluster ID %s", clusterID)
var ids []string
if len(compartmentID) == 0 {
return ids, fmt.Errorf("compartmentID must be set to list the node pools in the cluster")
} else if len(clusterID) == 0 {
return ids, fmt.Errorf("clusterID must be set to list the node pools in the cluster")
}
req := containerengine.ListNodePoolsRequest{}
req.CompartmentId = common.String(compartmentID)
req.ClusterId = common.String(clusterID)
resp, err := mgr.containerEngineClient.ListNodePools(ctx, req)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list Node Pools request failed with err %v", err)
return ids, err
}
for _, np := range resp.Items {
ids = append(ids, *np.Id)
}
// subnet ids may be empty
return ids, nil
}
// DeleteNodePool deletes the node pool with the specified ID, or an error
func (mgr *ClusterManagerClient) DeleteNodePool(ctx context.Context, nodePoolID string) error {
logrus.Debugf("[oraclecontainerengine] delete node pool with ID %s", nodePoolID)
if len(nodePoolID) == 0 {
return fmt.Errorf("nodePoolID must be set to delete the node pool")
}
req := containerengine.DeleteNodePoolRequest{}
req.NodePoolId = common.String(nodePoolID)
deleteNodePoolResp, err := mgr.containerEngineClient.DeleteNodePool(ctx, req)
if err != nil {
logrus.Debugf("[oraclecontainerengine] delete node pool request failed with err %v", err)
return err
}
// wait until node pool deletion work request complete
logrus.Debugf("[oraclecontainerengine] waiting for node pool to be deleted...")
// TODO better to poll instead of sleep
time.Sleep(mgr.sleepDuration * time.Second)
_, err = waitUntilWorkRequestComplete(mgr.containerEngineClient, deleteNodePoolResp.OpcWorkRequestId)
if err != nil {
logrus.Debugf("[oraclecontainerengine] get work request failed with err %v", err)
return err
}
return nil
}
// DeleteCluster deletes the cluster with the specified ID, or an error.
func (mgr *ClusterManagerClient) DeleteCluster(ctx context.Context, clusterID string) error {
logrus.Debugf("[oraclecontainerengine] deleting cluster with cluster ID %s", clusterID)
if len(clusterID) == 0 {
return fmt.Errorf("clusterID must be set to delete the cluster")
}
req := containerengine.DeleteClusterRequest{}
req.ClusterId = common.String(clusterID)
deleteClusterResp, err := mgr.containerEngineClient.DeleteCluster(ctx, req)
if err != nil {
logrus.Debugf("[oraclecontainerengine] delete cluster request failed with err %v", err)
return err
}
// wait until cluster deletion work request complete
logrus.Debugf("[oraclecontainerengine] waiting for cluster to be deleted...")
// initial delay since subsequent back-off function waits longer each time the retry fails
time.Sleep(time.Minute * 3)
_, err = waitUntilWorkRequestComplete(mgr.containerEngineClient, deleteClusterResp.OpcWorkRequestId)
if err != nil {
logrus.Debugf("[oraclecontainerengine] get work request failed with err %v", err)
return err
}
return nil
}
// DeleteVCN deletes the VCN and its associated resources (subnets, attached
// gateways, etc.) with the specified ID, or an error.
func (mgr *ClusterManagerClient) DeleteVCN(ctx context.Context, vcnID string) error {
logrus.Debugf("[oraclecontainerengine] deleting VCN with VCN ID %s", vcnID)
if len(vcnID) == 0 {
return fmt.Errorf("vcnID must be set to delete the VCN")
}
getVCNReq := core.GetVcnRequest{}
getVCNReq.VcnId = common.String(vcnID)
getVCNResp, err := mgr.virtualNetworkClient.GetVcn(ctx, getVCNReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] get VCN failed with err %v", err)
return err
}
// The VCN must be completely empty (meaning no subnets, attached gateways,
// or security lists)
// Delete Route Rules
listRouteTblsReq := core.ListRouteTablesRequest{}
listRouteTblsReq.VcnId = common.String(vcnID)
listRouteTblsReq.CompartmentId = getVCNResp.Vcn.CompartmentId
rtResp, err := mgr.virtualNetworkClient.ListRouteTables(ctx, listRouteTblsReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list route tables failed with err %v", err)
return err
}
for _, rt := range rtResp.Items {
updateRTReq := core.UpdateRouteTableRequest{}
updateRTReq.RtId = rt.Id
updateRTReq.RouteRules = []core.RouteRule{}
logrus.Debugf("[oraclecontainerengine] removing default route rule from route table %s", *rt.Id)
_, err = mgr.virtualNetworkClient.UpdateRouteTable(ctx, updateRTReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] update route table failed with err %v", err)
return err
}
}
// Delete Internet Gateways from VCN
listIGsReq := core.ListInternetGatewaysRequest{}
listIGsReq.VcnId = common.String(vcnID)
listIGsReq.CompartmentId = getVCNResp.Vcn.CompartmentId
igsResp, err := mgr.virtualNetworkClient.ListInternetGateways(ctx, listIGsReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list internet gateway(s) failed with err %v", err)
return err
}
for _, ig := range igsResp.Items {
deleteIGReq := core.DeleteInternetGatewayRequest{}
deleteIGReq.IgId = ig.Id
logrus.Debugf("[oraclecontainerengine] deleting internet gateway %s", *ig.Id)
_, err = mgr.virtualNetworkClient.DeleteInternetGateway(ctx, deleteIGReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] warning: delete internet gateway failed with err %v", err)
// Continue tearing down.
}
}
// Delete all the subnets from VCN
listSubnetsReq := core.ListSubnetsRequest{}
listSubnetsReq.VcnId = common.String(vcnID)
listSubnetsReq.CompartmentId = getVCNResp.Vcn.CompartmentId
listSubnetResp, err := mgr.virtualNetworkClient.ListSubnets(ctx, listSubnetsReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list subnets failed with err %v", err)
return err
}
for _, subnet := range listSubnetResp.Items {
deleteSubnetReq := core.DeleteSubnetRequest{}
deleteSubnetReq.SubnetId = subnet.Id
logrus.Debugf("[oraclecontainerengine] deleting subnet %s", *subnet.Id)
_, err := mgr.virtualNetworkClient.DeleteSubnet(ctx, deleteSubnetReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] warning: delete subnet failed with err %v", err)
// Continue tearing down.
}
}
// TODO better to poll instead of sleep
time.Sleep(mgr.sleepDuration * time.Second)
// Delete all security lists from VCN
listSecurityListsReq := core.ListSecurityListsRequest{}
listSecurityListsReq.VcnId = common.String(vcnID)
listSecurityListsReq.CompartmentId = getVCNResp.Vcn.CompartmentId
listSecurityListsResp, err := mgr.virtualNetworkClient.ListSecurityLists(ctx, listSecurityListsReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] list security lists failed with err %v", err)
return err
}
for _, securityList := range listSecurityListsResp.Items {
deleteSecurityListReq := core.DeleteSecurityListRequest{}
deleteSecurityListReq.SecurityListId = securityList.Id
logrus.Debugf("[oraclecontainerengine] deleting security list (%s)", *securityList.Id)
_, err := mgr.virtualNetworkClient.DeleteSecurityList(ctx, deleteSecurityListReq)
if err != nil {
logrus.Debugf("[oraclecontainerengine] warning: delete security list failed with err %v", err)
// Continue tearing down.
}
}
// Delete the route tables now that the subnets are gone...
for _, rt := range rtResp.Items {