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
use super::*;

mod impls;

/// NetworkSpec encapsulates all things related to AWS network.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct NetworkSpec {
    /// VPC configuration.
    // +optional
    pub vpc: Option<VPCSpec>, // `json:"vpc,omitempty"`

    /// Subnets configuration.
    // +optional
    pub subnets: Option<Subnets>, // `json:"subnets,omitempty"`

    /// CNI configuration
    // +optional
    pub cni: Option<CNISpec>, // `json:"cni,omitempty"`

    /// SecurityGroupOverrides is an optional set of security groups to use for cluster instances
    //./ This is optional - if not provided new security groups will be created for the cluster
    // +optional
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub security_group_overrides: BTreeMap<SecurityGroupRole, String>, // `json:"securityGroupOverrides,omitempty"`
}

/// VPCSpec configures an AWS VPC.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct VPCSpec {
    /// ID is the vpc-id of the VPC this provider should use to create resources.
    pub id: Option<String>, // `json:"id,omitempty"`

    /// CidrBlock is the CIDR block to be used when the provider creates a managed VPC.
    /// Defaults to 10.0.0.0/16.
    pub cidr_block: Option<String>, // `json:"cidrBlock,omitempty"`

    /// InternetGatewayID is the id of the internet gateway associated with the VPC.
    // +optional
    pub internet_gateway_id: Option<String>, // `json:"internetGatewayId,omitempty"`

    /// Tags is a collection of tags describing the resource.
    #[serde(default, skip_serializing_if = "Tags::is_empty")]
    pub tags: Tags, // `json:"tags,omitempty"`

    // AvailabilityZoneUsageLimit specifies the maximum number of availability zones (AZ) that
    // should be used in a region when automatically creating subnets. If a region has more
    // than this number of AZs then this number of AZs will be picked randomly when creating
    // default subnets. Defaults to 3
    // +kubebuilder:default=3
    // +kubebuilder:validation:Minimum=1
    pub availability_zone_usage_limit: Option<i64>, // `json:"availabilityZoneUsageLimit,omitempty"`

    // AvailabilityZoneSelection specifies how AZs should be selected if there are more AZs
    // in a region than specified by AvailabilityZoneUsageLimit. There are 2 selection schemes:
    // Ordered - selects based on alphabetical order
    // Random - selects AZs randomly in a region
    // Defaults to Ordered
    // +kubebuilder:default=Ordered
    // +kubebuilder:validation:Enum=Ordered;Random
    pub availability_zone_selection: Option<AZSelectionScheme>, // `json:"availabilityZoneSelection,omitempty"`
}

/// NetworkStatus encapsulates AWS networking resources.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct NetworkStatus {
    /// SecurityGroups is a map from the role/kind of the security group to its unique name, if any.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub security_groups: BTreeMap<SecurityGroupRole, SecurityGroup>, // `json:"securityGroups,omitempty"`

    /// APIServerELB is the Kubernetes api server classic load balancer.
    pub api_server_elb: ClassicELB, // `json:"apiServerElb,omitempty"`
}

/// ClassicELBScheme defines the scheme of a classic load balancer.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum ClassicELBScheme {
    /// ClassicELBSchemeInternetFacing defines an internet-facing, publicly
    /// accessible AWS Classic ELB scheme.
    #[serde(rename = "internet-facing")]
    InternetFacing,

    /// ClassicELBSchemeInternal defines an internal-only facing
    /// load balancer internal to an ELB.
    #[serde(rename = "internal")]
    Internal,

    /// ClassicELBSchemeIncorrectInternetFacing was inaccurately used to define an internet-facing LB in v0.6 releases > v0.6.6 and v0.7.0 release.
    #[serde(rename = "Internet-facing")]
    IncorrectInternetFacing,
}

/// Subnets is a slice of Subnet.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Subnets(pub Vec<SubnetSpec>);

/// SubnetSpec configures an AWS Subnet.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct SubnetSpec {
    /// ID defines a unique identifier to reference this resource.
    pub id: Option<String>, // `json:"id,omitempty"`

    /// CidrBlock is the CIDR block to be used when the provider creates a managed VPC.
    pub cidr_block: Option<String>, // `json:"cidrBlock,omitempty"`

    /// AvailabilityZone defines the availability zone to use for this subnet in the cluster's region.
    pub availability_zone: Option<String>, // `json:"availabilityZone,omitempty"`

    /// IsPublic defines the subnet as a public subnet. A subnet is public when it is associated with a route table that has a route to an internet gateway.
    // +optional
    pub is_public: Option<bool>, // `json:"isPublic"`

    /// RouteTableID is the routing table id associated with the subnet.
    // +optional
    pub route_table_id: Option<String>, // `json:"routeTableId,omitempty"`

    /// NatGatewayID is the NAT gateway id associated with the subnet.
    /// Ignored unless the subnet is managed by the provider, in which case this is set on the public subnet where the NAT gateway resides. It is then used to determine routes for private subnets in the same AZ as the public subnet.
    // +optional
    pub nat_gateway_id: Option<String>, // `json:"natGatewayId,omitempty"`

    /// Tags is a collection of tags describing the resource.
    #[serde(default, skip_serializing_if = "Tags::is_empty")]
    pub tags: Tags, // `json:"tags,omitempty"`
}

/// CNISpec defines configuration for CNI.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct CNISpec {
    /// CNIIngressRules specify rules to apply to control plane and worker node security groups.
    /// The source for the rule will be set to control plane and worker security group IDs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cni_ingress_rules: Vec<CNIIngressRule>, // `json:"cniIngressRules,omitempty"`
}

/// CNIIngressRule defines an AWS ingress rule for CNI requirements.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct CNIIngressRule {
    pub description: String,             //                `json:"description"`
    pub protocol: SecurityGroupProtocol, // `json:"protocol"`
    pub from_port: i64,                  //                 `json:"fromPort"`
    pub to_port: i64,                    //                 `json:"toPort"`
}

// SecurityGroupProtocol defines the protocol type for a security group rule.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum SecurityGroupProtocol {
    /// SecurityGroupProtocolAll is a wildcard for all IP protocols.
    #[serde(rename = "-1")]
    All,

    /// SecurityGroupProtocolIPinIP represents the IP in IP protocol in ingress rules.
    #[serde(rename = "4")]
    IPinIP,

    /// SecurityGroupProtocolTCP represents the TCP protocol in ingress rules.
    #[serde(rename = "tcp")]
    Tcp,

    /// SecurityGroupProtocolUDP represents the UDP protocol in ingress rules.
    #[serde(rename = "udp")]
    Udp,

    /// SecurityGroupProtocolICMP represents the ICMP protocol in ingress rules.
    #[serde(rename = "icmp")]
    Icmp,

    /// SecurityGroupProtocolICMPv6 represents the ICMPv6 protocol in ingress rules.
    #[serde(rename = "58")]
    Icmpv6,
}

/// SecurityGroupRole defines the unique role of a security group.
#[derive(Clone, Copy, Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Serialize, Deserialize)]
pub enum SecurityGroupRole {
    /// SecurityGroupBastion defines an SSH bastion role.
    #[serde(rename = "bastion")]
    Bastion,
    /// SecurityGroupNode defines a Kubernetes workload node role.
    #[serde(rename = "node")]
    Node,
    /// SecurityGroupEKSNodeAdditional defines an extra node group from eks nodes.
    #[serde(rename = "node-eks-additional")]
    EKSNodeAdditional,
    /// SecurityGroupControlPlane defines a Kubernetes control plane node role.
    #[serde(rename = "controlplane")]
    ControlPlane,
    /// SecurityGroupAPIServerLB defines a Kubernetes API Server Load Balancer role.
    #[serde(rename = "apiserver-lb")]
    APIServerLB,
    /// SecurityGroupLB defines a container for the cloud provider to inject its load balancer ingress rules.
    #[serde(rename = "lb")]
    LB,
}

/// SecurityGroup defines an AWS security group.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct SecurityGroup {
    /// ID is a unique identifier.
    pub id: String, // `json:"id"`

    /// Name is the security group name.
    pub name: String, // `json:"name"`

    /// IngressRules is the inbound rules associated with the security group.
    // +optional
    pub ingress_rule: Option<Vec<IngressRule>>, // `json:"ingressRule,omitempty"`

    /// Tags is a map of tags associated with the security group.
    #[serde(default, skip_serializing_if = "Tags::is_empty")]
    pub tags: Tags, // `json:"tags,omitempty"`
}

/// IngressRule defines an AWS ingress rule for security groups.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct IngressRule {
    pub description: String,             //                `json:"description"`
    pub protocol: SecurityGroupProtocol, // `json:"protocol"`
    pub from_port: i64,                  //                 `json:"fromPort"`
    pub to_port: i64,                    //                 `json:"toPort"`

    /// List of CIDR blocks to allow access from. Cannot be specified with SourceSecurityGroupID.
    // +optional
    pub cidr_blocks: Option<Vec<String>>, // `json:"cidrBlocks,omitempty"`

    /// The security group id to allow access from. Cannot be specified with CidrBlocks.
    // +optional
    pub source_security_group_ids: Option<Vec<String>>, // `json:"sourceSecurityGroupIds,omitempty"`
}

// ClassicELB defines an AWS classic load balancer.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct ClassicELB {
    /// The name of the load balancer. It must be unique within the set of load balancers
    /// defined in the region. It also serves as identifier.
    pub name: Option<String>, // `json:"name,omitempty"`

    /// DNSName is the dns name of the load balancer.
    pub dns_name: Option<String>, // `json:"dnsName,omitempty"`

    /// Scheme is the load balancer scheme, either internet-facing or private.
    pub scheme: Option<ClassicELBScheme>, // `json:"scheme,omitempty"`

    /// AvailabilityZones is an array of availability zones in the VPC attached to the load balancer.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub availability_zones: Vec<String>, // `json:"availabilityZones,omitempty"`

    /// SubnetIDs is an array of subnets in the VPC attached to the load balancer.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub subnet_ids: Vec<String>, // `json:"subnetIds,omitempty"`

    /// SecurityGroupIDs is an array of security groups assigned to the load balancer.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub security_group_ids: Vec<String>, // `json:"securityGroupIds,omitempty"`

    /// Listeners is an array of classic elb listeners associated with the load balancer. There must be at least one.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub listeners: Vec<ClassicELBListener>, // `json:"listeners,omitempty"`

    /// HealthCheck is the classic elb health check associated with the load balancer.
    pub health_check: Option<ClassicELBHealthCheck>, // `json:"healthChecks,omitempty"`

    /// Attributes defines extra attributes associated with the load balancer.
    pub attributes: Option<ClassicELBAttributes>, // `json:"attributes,omitempty"`

    /// Tags is a map of tags associated with the load balancer.
    #[serde(default, skip_serializing_if = "Tags::is_empty")]
    pub tags: Tags, // `json:"tags,omitempty"`
}

/// ClassicELBListener defines an AWS classic load balancer listener.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct ClassicELBListener {
    pub protocol: ClassicELBProtocol,          // `json:"protocol"`
    pub port: i64,                             //              `json:"port"`
    pub instance_protocol: ClassicELBProtocol, // `json:"instanceProtocol"`
    pub instance_port: i64,                    //             `json:"instancePort"`
}

/// ClassicELBProtocol defines listener protocols for a classic load balancer.
#[derive(Clone, Copy, Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Serialize, Deserialize)]
pub enum ClassicELBProtocol {
    /// ClassicELBProtocolTCP defines the ELB API string representing the TCP protocol.
    #[serde(rename = "TCP")]
    Tcp,
    /// ClassicELBProtocolSSL defines the ELB API string representing the TLS protocol.
    #[serde(rename = "SSL")]
    Ssl,
    /// ClassicELBProtocolHTTP defines the ELB API string representing the HTTP protocol at L7.
    #[serde(rename = "HTTP")]
    Http,
    /// ClassicELBProtocolHTTPS defines the ELB API string representing the HTTPS protocol at L7.
    #[serde(rename = "HTTPS")]
    Https,
}

/// ClassicELBHealthCheck defines an AWS classic load balancer health check.
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct ClassicELBHealthCheck {
    pub target: String, //       `json:"target"`
    #[serde_as(as = "serde_with::DurationSeconds<i64>")]
    pub interval: chrono::Duration, // `json:"interval"`
    #[serde_as(as = "serde_with::DurationSeconds<i64>")]
    pub timeout: chrono::Duration, // `json:"timeout"`
    pub healthy_threshold: i64, //         `json:"healthyThreshold"`
    pub unhealthy_threshold: i64, //         `json:"unhealthyThreshold"`
}

/// ClassicELBAttributes defines extra attributes associated with a classic load balancer.
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[skip_serializing_none]
pub struct ClassicELBAttributes {
    /// IdleTimeout is time that the connection is allowed to be idle (no data
    /// has been sent over the connection) before it is closed by the load balancer.
    #[serde_as(as = "serde_with::DurationSeconds<i64>")]
    pub idle_timeout: chrono::Duration, // `json:"idleTimeout,omitempty"`

    /// CrossZoneLoadBalancing enables the classic load balancer load balancing.
    // +optional
    pub cross_zone_load_balancing: Option<bool>, // `json:"crossZoneLoadBalancing,omitempty"`
}

/*  ============================================================================
package v1beta1

import (
    "fmt"
    "sort"
    "time"
)


func (e ClassicELBScheme) String() string {
    return string(e)
}

// IsUnmanaged returns true if the Classic ELB is unmanaged.
func (b *ClassicELB) IsUnmanaged(clusterName string) bool {
    return b.Name != "" && !Tags(b.Tags).HasOwned(clusterName)
}

// IsManaged returns true if Classic ELB is managed.
func (b *ClassicELB) IsManaged(clusterName string) bool {
    return !b.IsUnmanaged(clusterName)
}



// String returns a string representation of the VPC.
func (v *VPCSpec) String() string {
    return fmt.Sprintf("id=%s", v.ID)
}

// IsUnmanaged returns true if the VPC is unmanaged.
func (v *VPCSpec) IsUnmanaged(clusterName string) bool {
    return v.ID != "" && !v.Tags.HasOwned(clusterName)
}

// IsManaged returns true if VPC is managed.
func (v *VPCSpec) IsManaged(clusterName string) bool {
    return !v.IsUnmanaged(clusterName)
}


// String returns a string representation of the subnet.
func (s *SubnetSpec) String() string {
    return fmt.Sprintf("id=%s/az=%s/public=%v", s.ID, s.AvailabilityZone, s.IsPublic)
}

// ToMap returns a map from id to subnet.
func (s Subnets) ToMap() map[string]*SubnetSpec {
    res := make(map[string]*SubnetSpec)
    for i := range s {
        x := s[i]
        res[x.ID] = &x
    }
    return res
}

// IDs returns a slice of the subnet ids.
func (s Subnets) IDs() []string {
    res := []string{}
    for _, subnet := range s {
        res = append(res, subnet.ID)
    }
    return res
}

// FindByID returns a single subnet matching the given id or nil.
func (s Subnets) FindByID(id string) *SubnetSpec {
    for _, x := range s {
        if x.ID == id {
            return &x
        }
    }

    return nil
}

// FindEqual returns a subnet spec that is equal to the one passed in.
// Two subnets are defined equal to each other if their id is equal
// or if they are in the same vpc and the cidr block is the same.
func (s Subnets) FindEqual(spec *SubnetSpec) *SubnetSpec {
    for _, x := range s {
        if (spec.ID != "" && x.ID == spec.ID) || (spec.CidrBlock == x.CidrBlock) {
            return &x
        }
    }
    return nil
}

// FilterPrivate returns a slice containing all subnets marked as private.
func (s Subnets) FilterPrivate() (res Subnets) {
    for _, x := range s {
        if !x.IsPublic {
            res = append(res, x)
        }
    }
    return
}

// FilterPublic returns a slice containing all subnets marked as public.
func (s Subnets) FilterPublic() (res Subnets) {
    for _, x := range s {
        if x.IsPublic {
            res = append(res, x)
        }
    }
    return
}

// FilterByZone returns a slice containing all subnets that live in the availability zone specified.
func (s Subnets) FilterByZone(zone string) (res Subnets) {
    for _, x := range s {
        if x.AvailabilityZone == zone {
            res = append(res, x)
        }
    }
    return
}

// GetUniqueZones returns a slice containing the unique zones of the subnets.
func (s Subnets) GetUniqueZones() []string {
    keys := make(map[string]bool)
    zones := []string{}
    for _, x := range s {
        if _, value := keys[x.AvailabilityZone]; !value {
            keys[x.AvailabilityZone] = true
            zones = append(zones, x.AvailabilityZone)
        }
    }
    return zones
}

// RouteTable defines an AWS routing table.
type RouteTable struct {
    ID string `json:"id"`
}


// String returns a string representation of the security group.
func (s *SecurityGroup) String() string {
    return fmt.Sprintf("id=%s/name=%s", s.ID, s.Name)
}



// String returns a string representation of the ingress rule.
func (i *IngressRule) String() string {
    return fmt.Sprintf("protocol=%s/range=[%d-%d]/description=%s", i.Protocol, i.FromPort, i.ToPort, i.Description)
}

// IngressRules is a slice of AWS ingress rules for security groups.
type IngressRules []IngressRule

// Difference returns the difference between this slice and the other slice.
func (i IngressRules) Difference(o IngressRules) (out IngressRules) {
    for index := range i {
        x := i[index]
        found := false
        for oIndex := range o {
            y := o[oIndex]
            if x.Equals(&y) {
                found = true
                break
            }
        }

        if !found {
            out = append(out, x)
        }
    }

    return
}

// Equals returns true if two IngressRule are equal.
func (i *IngressRule) Equals(o *IngressRule) bool {
    if len(i.CidrBlocks) != len(o.CidrBlocks) {
        return false
    }

    sort.Strings(i.CidrBlocks)
    sort.Strings(o.CidrBlocks)

    for i, v := range i.CidrBlocks {
        if v != o.CidrBlocks[i] {
            return false
        }
    }

    if len(i.SourceSecurityGroupIDs) != len(o.SourceSecurityGroupIDs) {
        return false
    }

    sort.Strings(i.SourceSecurityGroupIDs)
    sort.Strings(o.SourceSecurityGroupIDs)

    for i, v := range i.SourceSecurityGroupIDs {
        if v != o.SourceSecurityGroupIDs[i] {
            return false
        }
    }

    if i.Description != o.Description || i.Protocol != o.Protocol {
        return false
    }

    // AWS seems to ignore the From/To port when set on protocols where it doesn't apply, but
    // we avoid serializing it out for clarity's sake.
    // See: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_IpPermission.html
    switch i.Protocol {
    case SecurityGroupProtocolTCP,
        SecurityGroupProtocolUDP,
        SecurityGroupProtocolICMP,
        SecurityGroupProtocolICMPv6:
        return i.FromPort == o.FromPort && i.ToPort == o.ToPort
    case SecurityGroupProtocolAll, SecurityGroupProtocolIPinIP:
        // FromPort / ToPort are not applicable
    }

    return true
}
 ============================================================================ */