-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathcluster.go
More file actions
431 lines (369 loc) · 13.4 KB
/
cluster.go
File metadata and controls
431 lines (369 loc) · 13.4 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
/*
Copyright 2018 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"
"fmt"
"strconv"
"time"
"github.com/pkg/errors"
"google.golang.org/api/compute/v1"
"k8s.io/utils/ptr"
infrav1 "sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1"
"sigs.k8s.io/cluster-api-provider-gcp/cloud"
clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1"
clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2"
"sigs.k8s.io/cluster-api/util/patch"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// ClusterScopeParams defines the input parameters used to create a new Scope.
type ClusterScopeParams struct {
GCPServices
Client client.Client
Cluster *clusterv1.Cluster
GCPCluster *infrav1.GCPCluster
}
// NewClusterScope creates a new Scope from the supplied parameters.
// This is meant to be called for each reconcile iteration.
func NewClusterScope(ctx context.Context, params ClusterScopeParams) (*ClusterScope, error) {
if params.Cluster == nil {
return nil, errors.New("failed to generate new scope from nil Cluster")
}
if params.GCPCluster == nil {
return nil, errors.New("failed to generate new scope from nil GCPCluster")
}
if params.Compute == nil {
computeSvc, err := newComputeService(ctx, params.GCPCluster.Spec.CredentialsRef, params.Client, params.GCPCluster.Spec.ServiceEndpoints)
if err != nil {
return nil, errors.Errorf("failed to create gcp compute client: %v", err)
}
params.Compute = computeSvc
}
helper, err := patch.NewHelper(params.GCPCluster, params.Client)
if err != nil {
return nil, errors.Wrap(err, "failed to init patch helper")
}
return &ClusterScope{
client: params.Client,
Cluster: params.Cluster,
GCPCluster: params.GCPCluster,
GCPServices: params.GCPServices,
patchHelper: helper,
}, nil
}
// ClusterScope defines the basic context for an actuator to operate upon.
type ClusterScope struct {
client client.Client
patchHelper *patch.Helper
Cluster *clusterv1.Cluster
GCPCluster *infrav1.GCPCluster
GCPServices
}
// ANCHOR: ClusterGetter
// Cloud returns initialized cloud.
func (s *ClusterScope) Cloud() cloud.Cloud {
return newCloud(s.Project(), s.GCPServices)
}
// NetworkCloud returns initialized cloud.
func (s *ClusterScope) NetworkCloud() cloud.Cloud {
return newCloud(s.NetworkProject(), s.GCPServices)
}
// Project returns the current project name.
func (s *ClusterScope) Project() string {
return s.GCPCluster.Spec.Project
}
// NetworkProject returns the project name where network resources should exist.
// The network project defaults to the Project when one is not supplied.
func (s *ClusterScope) NetworkProject() string {
return ptr.Deref(s.GCPCluster.Spec.Network.HostProject, s.Project())
}
// SkipFirewallRuleCreation returns whether the spec indicates that firewall rules
// should be created or not. If the RulesManagement for the default firewall rules is
// set to unmanaged or when the cluster will include a shared VPC, the default firewall
// rule creation will be skipped.
func (s *ClusterScope) SkipFirewallRuleCreation() bool {
return (s.GCPCluster.Spec.Network.Firewall.DefaultRulesManagement == infrav1.RulesManagementUnmanaged) || s.IsSharedVpc()
}
// IsSharedVpc returns true If sharedVPC used else , returns false.
func (s *ClusterScope) IsSharedVpc() bool {
return s.NetworkProject() != s.Project()
}
// Region returns the cluster region.
func (s *ClusterScope) Region() string {
return s.GCPCluster.Spec.Region
}
// Name returns the cluster name.
func (s *ClusterScope) Name() string {
return s.Cluster.Name
}
// Namespace returns the cluster namespace.
func (s *ClusterScope) Namespace() string {
return s.Cluster.Namespace
}
// NetworkName returns the cluster network unique identifier.
func (s *ClusterScope) NetworkName() string {
return ptr.Deref(s.GCPCluster.Spec.Network.Name, "default")
}
// NetworkMtu returns the Network MTU of 1440 which is the default, otherwise returns back what is being set.
// Mtu: Maximum Transmission Unit in bytes. The minimum value for this field is
// 1300 and the maximum value is 8896. The suggested value is 1500, which is
// the default MTU used on the Internet, or 8896 if you want to use Jumbo
// frames. If unspecified, the value defaults to 1460.
// More info
// - https://pkg.go.dev/google.golang.org/api/compute/v1#Network
// - https://cloud.google.com/vpc/docs/mtu
func (s *ClusterScope) NetworkMtu() int64 {
if s.GCPCluster.Spec.Network.Mtu == 0 {
return int64(1460)
}
return s.GCPCluster.Spec.Network.Mtu
}
// NetworkLink returns the partial URL for the network.
func (s *ClusterScope) NetworkLink() string {
return fmt.Sprintf("projects/%s/global/networks/%s", s.NetworkProject(), s.NetworkName())
}
// Network returns the cluster network object.
func (s *ClusterScope) Network() *infrav1.Network {
return &s.GCPCluster.Status.Network
}
// AdditionalLabels returns the cluster additional labels.
func (s *ClusterScope) AdditionalLabels() infrav1.Labels {
return s.GCPCluster.Spec.AdditionalLabels
}
// LoadBalancer returns the LoadBalancer configuration.
func (s *ClusterScope) LoadBalancer() infrav1.LoadBalancerSpec {
return s.GCPCluster.Spec.LoadBalancer
}
// ResourceManagerTags returns ResourceManagerTags from the scope's GCPCluster. The returned value will never be nil.
func (s *ClusterScope) ResourceManagerTags() infrav1.ResourceManagerTags {
if len(s.GCPCluster.Spec.ResourceManagerTags) == 0 {
s.GCPCluster.Spec.ResourceManagerTags = infrav1.ResourceManagerTags{}
}
return s.GCPCluster.Spec.ResourceManagerTags.DeepCopy()
}
// ControlPlaneEndpoint returns the cluster control-plane endpoint.
func (s *ClusterScope) ControlPlaneEndpoint() clusterv1.APIEndpoint {
endpoint := clusterv1.APIEndpoint{
Host: s.GCPCluster.Spec.ControlPlaneEndpoint.Host,
Port: 443,
}
if s.Cluster.Spec.ClusterNetwork.APIServerPort != 0 {
endpoint.Port = s.Cluster.Spec.ClusterNetwork.APIServerPort
}
return endpoint
}
// FailureDomains returns the cluster failure domains.
func (s *ClusterScope) FailureDomains() []string {
failureDomains := []string{}
for failureDomainName := range s.GCPCluster.Status.FailureDomains {
failureDomains = append(failureDomains, failureDomainName)
}
return failureDomains
}
// ANCHOR_END: ClusterGetter
// ANCHOR: ClusterSetter
// SetReady sets cluster ready status.
func (s *ClusterScope) SetReady() {
s.GCPCluster.Status.Ready = true
}
// SetFailureDomains sets cluster failure domains.
func (s *ClusterScope) SetFailureDomains(fd clusterv1beta1.FailureDomains) {
s.GCPCluster.Status.FailureDomains = fd
}
// SetControlPlaneEndpoint sets cluster control-plane endpoint.
func (s *ClusterScope) SetControlPlaneEndpoint(endpoint clusterv1.APIEndpoint) {
s.GCPCluster.Spec.ControlPlaneEndpoint = clusterv1beta1.APIEndpoint{
Host: endpoint.Host,
Port: endpoint.Port,
}
}
// ANCHOR_END: ClusterSetter
// ANCHOR: ClusterNetworkSpec
// NetworkSpec returns google compute network spec.
func (s *ClusterScope) NetworkSpec() *compute.Network {
createSubnet := ptr.Deref(s.GCPCluster.Spec.Network.AutoCreateSubnetworks, true)
network := &compute.Network{
Name: s.NetworkName(),
Description: infrav1.ClusterTagKey(s.Name()),
AutoCreateSubnetworks: createSubnet,
ForceSendFields: []string{"AutoCreateSubnetworks"},
Mtu: s.NetworkMtu(),
}
return network
}
// NatRouterSpec returns google compute nat router spec.
func (s *ClusterScope) NatRouterSpec() *compute.Router {
networkSpec := s.NetworkSpec()
return &compute.Router{
Name: fmt.Sprintf("%s-%s", networkSpec.Name, "router"),
Nats: []*compute.RouterNat{
{
Name: fmt.Sprintf("%s-%s", networkSpec.Name, "nat"),
NatIpAllocateOption: "AUTO_ONLY",
SourceSubnetworkIpRangesToNat: "ALL_SUBNETWORKS_ALL_IP_RANGES",
MinPortsPerVm: s.GCPCluster.Spec.Network.MinPortsPerVM,
},
},
}
}
// ANCHOR_END: ClusterNetworkSpec
// SubnetSpecs returns google compute subnets spec.
func (s *ClusterScope) SubnetSpecs() []*compute.Subnetwork {
subnets := []*compute.Subnetwork{}
for _, subnetwork := range s.GCPCluster.Spec.Network.Subnets {
secondaryIPRanges := []*compute.SubnetworkSecondaryRange{}
for rangeName, secondaryCidrBlock := range subnetwork.SecondaryCidrBlocks {
secondaryIPRanges = append(secondaryIPRanges, &compute.SubnetworkSecondaryRange{RangeName: rangeName, IpCidrRange: secondaryCidrBlock})
}
subnets = append(subnets, &compute.Subnetwork{
Name: subnetwork.Name,
Region: subnetwork.Region,
EnableFlowLogs: ptr.Deref(subnetwork.EnableFlowLogs, false),
PrivateIpGoogleAccess: ptr.Deref(subnetwork.PrivateGoogleAccess, false),
IpCidrRange: subnetwork.CidrBlock,
SecondaryIpRanges: secondaryIPRanges,
Description: ptr.Deref(subnetwork.Description, infrav1.ClusterTagKey(s.Name())),
Network: s.NetworkLink(),
Purpose: ptr.Deref(subnetwork.Purpose, "PRIVATE_RFC_1918"),
Role: "ACTIVE",
StackType: subnetwork.StackType,
})
}
return subnets
}
// ANCHOR: ClusterFirewallSpec
// FirewallRulesSpec returns google compute firewall spec.
func (s *ClusterScope) FirewallRulesSpec() []*compute.Firewall {
firewallRules := []*compute.Firewall{
{
Name: fmt.Sprintf("allow-%s-healthchecks", s.Name()),
Network: s.NetworkLink(),
Allowed: []*compute.FirewallAllowed{
{
IPProtocol: "TCP",
Ports: []string{
strconv.FormatInt(6443, 10),
},
},
},
Direction: "INGRESS",
SourceRanges: []string{
"35.191.0.0/16",
"130.211.0.0/22",
},
TargetTags: []string{
s.Name() + "-control-plane",
},
},
{
Name: fmt.Sprintf("allow-%s-cluster", s.Name()),
Network: s.NetworkLink(),
Allowed: []*compute.FirewallAllowed{
{
IPProtocol: "all",
},
},
Direction: "INGRESS",
SourceTags: []string{
s.Name() + "-control-plane",
s.Name() + "-node",
},
TargetTags: []string{
s.Name() + "-control-plane",
s.Name() + "-node",
},
},
}
return firewallRules
}
// ANCHOR_END: ClusterFirewallSpec
// ANCHOR: ClusterControlPlaneSpec
// AddressSpec returns google compute address spec.
func (s *ClusterScope) AddressSpec(lbname string) *compute.Address {
return &compute.Address{
Name: fmt.Sprintf("%s-%s", s.Name(), lbname),
AddressType: "EXTERNAL",
IpVersion: "IPV4",
}
}
// BackendServiceSpec returns google compute backend-service spec.
func (s *ClusterScope) BackendServiceSpec(lbname string) *compute.BackendService {
return &compute.BackendService{
Name: fmt.Sprintf("%s-%s", s.Name(), lbname),
LoadBalancingScheme: "EXTERNAL",
PortName: "apiserver",
Protocol: "TCP",
TimeoutSec: int64((10 * time.Minute).Seconds()),
}
}
// ForwardingRuleSpec returns google compute forwarding-rule spec.
func (s *ClusterScope) ForwardingRuleSpec(lbname string) *compute.ForwardingRule {
port := int32(443)
if s.Cluster.Spec.ClusterNetwork.APIServerPort != 0 {
port = s.Cluster.Spec.ClusterNetwork.APIServerPort
}
portRange := fmt.Sprintf("%d-%d", port, port)
return &compute.ForwardingRule{
Name: fmt.Sprintf("%s-%s", s.Name(), lbname),
IPProtocol: "TCP",
LoadBalancingScheme: "EXTERNAL",
PortRange: portRange,
Labels: s.AdditionalLabels(),
}
}
// HealthCheckSpec returns google compute health-check spec.
func (s *ClusterScope) HealthCheckSpec(lbname string) *compute.HealthCheck {
return &compute.HealthCheck{
Name: fmt.Sprintf("%s-%s", s.Name(), lbname),
Type: "HTTPS",
HttpsHealthCheck: &compute.HTTPSHealthCheck{
Port: 6443,
PortSpecification: "USE_FIXED_PORT",
RequestPath: "/readyz",
},
CheckIntervalSec: 10,
TimeoutSec: 5,
HealthyThreshold: 5,
UnhealthyThreshold: 3,
}
}
// InstanceGroupSpec returns google compute instance-group spec.
func (s *ClusterScope) InstanceGroupSpec(zone string) *compute.InstanceGroup {
port := ptr.Deref(s.GCPCluster.Spec.Network.LoadBalancerBackendPort, 6443)
tag := ptr.Deref(s.GCPCluster.Spec.LoadBalancer.APIServerInstanceGroupTagOverride, infrav1.APIServerRoleTagValue)
return &compute.InstanceGroup{
Name: fmt.Sprintf("%s-%s-%s", s.Name(), tag, zone),
NamedPorts: []*compute.NamedPort{
{
Name: "apiserver",
Port: int64(port),
},
},
}
}
// TargetTCPProxySpec returns google compute target-tcp-proxy spec.
func (s *ClusterScope) TargetTCPProxySpec() *compute.TargetTcpProxy {
return &compute.TargetTcpProxy{
Name: fmt.Sprintf("%s-%s", s.Name(), infrav1.APIServerRoleTagValue),
ProxyHeader: "NONE",
}
}
// ANCHOR_END: ClusterControlPlaneSpec
// PatchObject persists the cluster configuration and status.
func (s *ClusterScope) PatchObject(ctx context.Context) error {
return s.patchHelper.Patch(ctx, s.GCPCluster)
}
// Close closes the current scope persisting the cluster configuration and status.
func (s *ClusterScope) Close(ctx context.Context) error {
return s.PatchObject(ctx)
}