File: subnets.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (520 lines) | stat: -rw-r--r-- 18,710 bytes parent folder | download
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
from __future__ import annotations

import ipaddress
import itertools
from collections import defaultdict
from typing import TYPE_CHECKING, Any, Optional

from moto.core.common_models import CloudFormationModel

if TYPE_CHECKING:
    from moto.ec2.models.instances import Instance

from moto.ec2.models.availability_zones_and_regions import Zone

from ..exceptions import (
    DefaultSubnetAlreadyExistsInAvailabilityZoneError,
    DefaultVpcDoesNotExistError,
    InvalidAvailabilityZoneError,
    InvalidCIDRBlockParameterError,
    InvalidParameterValueError,
    InvalidSubnetCidrBlockAssociationID,
    InvalidSubnetConflictError,
    InvalidSubnetIdError,
    InvalidSubnetRangeError,
)
from ..utils import (
    generic_filter,
    random_subnet_id,
    random_subnet_ipv6_cidr_block_association_id,
)
from .availability_zones_and_regions import RegionsAndZonesBackend
from .core import TaggedEC2Resource


class Subnet(TaggedEC2Resource, CloudFormationModel):
    def __init__(
        self,
        ec2_backend: Any,
        subnet_id: str,
        vpc_id: str,
        cidr_block: str,
        ipv6_cidr_block: Optional[str],
        availability_zone: Zone,
        default_for_az: bool,
        map_public_ip_on_launch: bool,
        ipv6_native: bool = False,
    ):
        self.ec2_backend = ec2_backend
        self.id = subnet_id
        self.vpc_id = vpc_id
        self.cidr_block = cidr_block
        self.cidr = (
            ipaddress.IPv4Network(str(self.cidr_block), strict=False)
            if self.cidr_block
            else ipaddress.IPv6Network(ipv6_cidr_block)
        )
        self._available_ip_addresses = self.cidr.num_addresses - 5
        self._availability_zone = availability_zone
        self.default_for_az = default_for_az
        self.map_public_ip_on_launch = map_public_ip_on_launch
        self.assign_ipv6_address_on_creation = ipv6_native
        self.ipv6_cidr_block_associations: dict[str, dict[str, Any]] = {}
        if ipv6_cidr_block:
            self.attach_ipv6_cidr_block_associations(ipv6_cidr_block)

        # Theory is we assign ip's as we go (as 16,777,214 usable IPs in a /8)
        self._subnet_ip_generator = self.cidr.hosts()
        self.reserved_ips = [
            next(iter(self._subnet_ip_generator)) for _ in range(0, 3)
        ]  # Reserved by AWS
        self._unused_ips: set[str] = (
            set()
        )  # if instance is destroyed hold IP here for reuse
        self._subnet_ips: dict[str, Instance] = {}
        self.state = "available"

        # Placeholder for response templates until Ipv6 support implemented.
        self.ipv6_native = ipv6_native

    @property
    def arn(self) -> str:
        return f"arn:aws:ec2:{self.ec2_backend.region_name}:{self.owner_id}:subnet/{self.id}"

    @property
    def ipv6_cidr_block_association_set(self) -> list[dict[str, str]]:
        association_set = [
            {
                "ipv6CidrBlock": association["ipv6CidrBlock"],
                "associationId": association["associationId"],
                "ipv6CidrBlockState": {
                    "state": association["ipv6CidrBlockState"],
                },
            }
            for association in self.ipv6_cidr_block_associations.values()
            if association["ipv6CidrBlockState"]["State"] == "associated"
        ]
        return association_set

    @property
    def owner_id(self) -> str:
        return self.ec2_backend.account_id

    @staticmethod
    def cloudformation_name_type() -> str:
        return ""

    @staticmethod
    def cloudformation_type() -> str:
        # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html
        return "AWS::EC2::Subnet"

    @classmethod
    def create_from_cloudformation_json(  # type: ignore[misc]
        cls,
        resource_name: str,
        cloudformation_json: Any,
        account_id: str,
        region_name: str,
        **kwargs: Any,
    ) -> Subnet:
        from ..models import ec2_backends

        properties = cloudformation_json["Properties"]

        vpc_id = properties["VpcId"]
        cidr_block = properties["CidrBlock"]
        availability_zone = properties.get("AvailabilityZone")
        ec2_backend = ec2_backends[account_id][region_name]
        subnet = ec2_backend.create_subnet(
            vpc_id=vpc_id, cidr_block=cidr_block, availability_zone=availability_zone
        )
        for tag in properties.get("Tags", []):
            tag_key = tag["Key"]
            tag_value = tag["Value"]
            subnet.add_tag(tag_key, tag_value)

        return subnet

    @classmethod
    def delete_from_cloudformation_json(  # type: ignore[misc]
        cls,
        resource_name: str,
        cloudformation_json: dict[str, Any],
        account_id: str,
        region_name: str,
    ) -> None:
        from ..models import ec2_backends

        ec2_backends[account_id][region_name].delete_subnet(resource_name)

    @property
    def available_ip_address_count(self) -> int:
        enis = [
            eni
            for eni in self.ec2_backend.get_all_network_interfaces()
            if eni.subnet.id == self.id
        ]
        addresses_taken = []
        for eni in enis:
            if eni.private_ip_addresses:
                addresses_taken.extend(eni.private_ip_addresses)
        return self._available_ip_addresses - len(addresses_taken)

    @property
    def availability_zone(self) -> str:
        return self._availability_zone.name

    @property
    def availability_zone_id(self) -> str:
        return self._availability_zone.zone_id

    @property
    def physical_resource_id(self) -> str:
        return self.id

    def get_filter_value(
        self, filter_name: str, method_name: Optional[str] = None
    ) -> Any:
        """
        API Version 2014-10-01 defines the following filters for DescribeSubnets:

        * availabilityZone
        * available-ip-address-count
        * cidrBlock
        * defaultForAz
        * state
        * subnet-id
        * tag:key=value
        * tag-key
        * tag-value
        * vpc-id

        Taken from: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSubnets.html
        """
        if filter_name in ("cidr", "cidrBlock", "cidr-block"):
            return self.cidr_block
        elif filter_name in ("vpc-id", "vpcId"):
            return self.vpc_id
        elif filter_name == "subnet-id":
            return self.id
        elif filter_name in ("availabilityZone", "availability-zone"):
            return self.availability_zone
        elif filter_name in ("defaultForAz", "default-for-az"):
            return self.default_for_az
        elif filter_name == "state":
            return self.state
        else:
            return super().get_filter_value(filter_name, "DescribeSubnets")

    @classmethod
    def has_cfn_attr(cls, attr: str) -> bool:
        return attr in ["AvailabilityZone"]

    def get_cfn_attribute(self, attribute_name: str) -> None:
        from moto.cloudformation.exceptions import UnformattedGetAttTemplateException

        if attribute_name == "AvailabilityZone":
            raise NotImplementedError('"Fn::GetAtt" : [ "{0}" , "AvailabilityZone" ]"')
        raise UnformattedGetAttTemplateException()

    def get_available_subnet_ip(self, instance: Instance) -> str:
        try:
            new_ip = str(self._unused_ips.pop())
        except KeyError:
            new_ip_v4 = next(iter(self._subnet_ip_generator))

            # Skips any IP's if they've been manually specified
            while str(new_ip_v4) in self._subnet_ips:
                new_ip_v4 = next(iter(self._subnet_ip_generator))

            if new_ip_v4 == self.cidr.broadcast_address:
                raise StopIteration()  # Broadcast address cant be used obviously
            new_ip = str(new_ip_v4)
        # TODO StopIteration will be raised if no ip's available, not sure how aws handles this.

        self._subnet_ips[new_ip] = instance

        return new_ip

    # EFS calls this method as request_ip(str, MountTarget)
    # So technically it's not just Instances that are stored
    def request_ip(self, ip: str, instance: Instance) -> None:
        if ipaddress.ip_address(ip) not in self.cidr:
            raise Exception(f"IP does not fall in the subnet CIDR of {self.cidr}")

        if ip in self._subnet_ips:
            raise Exception("IP already in use")
        try:
            self._unused_ips.remove(ip)
        except KeyError:
            pass

        self._subnet_ips[ip] = instance

    def del_subnet_ip(self, ip: str) -> None:
        try:
            del self._subnet_ips[ip]
            self._unused_ips.add(ip)
        except KeyError:
            pass  # Unknown IP

    def attach_ipv6_cidr_block_associations(
        self, ipv6_cidr_block: str
    ) -> dict[str, Any]:
        association = {
            "associationId": random_subnet_ipv6_cidr_block_association_id(),
            "ipv6CidrBlock": ipv6_cidr_block,
            "ipv6CidrBlockState": {"State": "associated"},
        }
        self.ipv6_cidr_block_associations[str(association["associationId"])] = (
            association
        )
        return association

    def detach_subnet_cidr_block(self, association_id: str) -> dict[str, Any]:
        association = self.ipv6_cidr_block_associations.get(association_id)
        assert association is not None
        association["ipv6CidrBlockState"] = {"State": "disassociated"}
        return association


class SubnetRouteTableAssociation(CloudFormationModel):
    def __init__(self, route_table_id: str, subnet_id: str):
        self.route_table_id = route_table_id
        self.subnet_id = subnet_id

    @property
    def physical_resource_id(self) -> str:
        return self.route_table_id

    @staticmethod
    def cloudformation_name_type() -> str:
        return ""

    @staticmethod
    def cloudformation_type() -> str:
        # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetroutetableassociation.html
        return "AWS::EC2::SubnetRouteTableAssociation"

    @classmethod
    def create_from_cloudformation_json(  # type: ignore[misc]
        cls,
        resource_name: str,
        cloudformation_json: Any,
        account_id: str,
        region_name: str,
        **kwargs: Any,
    ) -> SubnetRouteTableAssociation:
        from ..models import ec2_backends

        properties = cloudformation_json["Properties"]

        route_table_id = properties["RouteTableId"]
        subnet_id = properties["SubnetId"]

        ec2_backend = ec2_backends[account_id][region_name]
        subnet_association = ec2_backend.create_subnet_association(
            route_table_id=route_table_id, subnet_id=subnet_id
        )
        return subnet_association


class SubnetBackend:
    def __init__(self) -> None:
        # maps availability zone to dict of (subnet_id, subnet)
        self.subnets: dict[str, dict[str, Subnet]] = defaultdict(dict)
        self.subnet_associations: dict[str, SubnetRouteTableAssociation] = {}

    def get_subnet(self, subnet_id: str) -> Subnet:
        for subnets_per_zone in self.subnets.values():
            if subnet_id in subnets_per_zone:
                return subnets_per_zone[subnet_id]
        raise InvalidSubnetIdError(subnet_id)

    def get_default_subnets(self) -> dict[str, Subnet]:
        return {
            subnet.availability_zone: subnet
            for subnet in self.describe_subnets()
            if subnet.default_for_az
        }

    def create_default_subnet(self, availability_zone: str) -> Subnet:
        default_subnets = self.get_default_subnets()
        if availability_zone in default_subnets:
            raise DefaultSubnetAlreadyExistsInAvailabilityZoneError(
                default_subnets[availability_zone].id, availability_zone
            )

        default_vpc = self.get_default_vpc()  # type: ignore[attr-defined]
        if default_vpc is None:
            raise DefaultVpcDoesNotExistError()

        cidr_block = default_vpc.cidr_block
        blocks = list(ipaddress.ip_network(cidr_block).subnets(new_prefix=20))
        subnet = self.create_subnet(
            vpc_id=default_vpc.id,
            cidr_block=str(blocks[len(default_subnets)]),
            availability_zone=availability_zone,
        )
        return subnet

    def create_subnet(
        self,
        vpc_id: str,
        cidr_block: str,
        ipv6_cidr_block: Optional[str] = None,
        availability_zone: Optional[str] = None,
        availability_zone_id: Optional[str] = None,
        ipv6_native: bool = False,
        tags: Optional[dict[str, dict[str, str]]] = None,
    ) -> Subnet:
        subnet_id = random_subnet_id()
        # Validate VPC exists and the supplied CIDR block is a subnet of the VPC's
        vpc = self.get_vpc(vpc_id)  # type: ignore[attr-defined]
        if cidr_block:
            vpc_cidr_blocks = [
                ipaddress.IPv4Network(
                    str(cidr_block_association["cidr_block"]), strict=False
                )
                for cidr_block_association in vpc.get_cidr_block_association_set()
            ]
            try:
                subnet_cidr_block = ipaddress.IPv4Network(str(cidr_block), strict=False)
            except ValueError:
                raise InvalidCIDRBlockParameterError(cidr_block)

            subnet_in_vpc_cidr_range = False
            for vpc_cidr_block in vpc_cidr_blocks:
                if (
                    vpc_cidr_block.network_address <= subnet_cidr_block.network_address
                    and vpc_cidr_block.broadcast_address
                    >= subnet_cidr_block.broadcast_address
                ):
                    subnet_in_vpc_cidr_range = True
                    break

            if not subnet_in_vpc_cidr_range:
                raise InvalidSubnetRangeError(cidr_block)

            for subnet in self.describe_subnets(filters={"vpc-id": vpc_id}):
                if subnet.cidr.overlaps(subnet_cidr_block):
                    raise InvalidSubnetConflictError(cidr_block)

        # if this is the first subnet for an availability zone,
        # consider it the default
        default_for_az = len(self.subnets.get(availability_zone, [])) == 0  # type: ignore[arg-type]
        map_public_ip_on_launch = default_for_az

        if availability_zone is None and not availability_zone_id:
            availability_zone = "us-east-1a"
        try:
            if availability_zone:
                availability_zone_data = next(
                    zone
                    for zones in RegionsAndZonesBackend.zones.values()
                    for zone in zones
                    if zone.name == availability_zone
                )
            elif availability_zone_id:
                availability_zone_data = next(
                    zone
                    for zones in RegionsAndZonesBackend.zones.values()
                    for zone in zones
                    if zone.zone_id == availability_zone_id
                )

        except StopIteration:
            raise InvalidAvailabilityZoneError(
                availability_zone,
                ", ".join(
                    [
                        zone.name
                        for zones in RegionsAndZonesBackend.zones.values()
                        for zone in zones
                    ]
                ),
            )
        subnet = Subnet(
            self,
            subnet_id,
            vpc_id,
            cidr_block,
            ipv6_cidr_block,
            availability_zone_data,
            default_for_az,
            map_public_ip_on_launch,
            ipv6_native=ipv6_native,
        )

        for k, v in tags.get("subnet", {}).items() if tags else []:
            subnet.add_tag(k, v)

        # AWS associates a new subnet with the default Network ACL
        self.associate_default_network_acl_with_subnet(subnet_id, vpc_id)  # type: ignore[attr-defined]
        self.subnets[availability_zone][subnet_id] = subnet  # type: ignore[index]
        return subnet

    def describe_subnets(
        self, subnet_ids: Optional[list[str]] = None, filters: Optional[Any] = None
    ) -> list[Subnet]:
        # Extract a list of all subnets
        matches = list(
            itertools.chain(*[x.copy().values() for x in self.subnets.copy().values()])
        )
        if subnet_ids:
            matches = [sn for sn in matches if sn.id in subnet_ids]
            if len(subnet_ids) > len(matches):
                unknown_ids = set(subnet_ids) - set(matches)  # type: ignore[arg-type]
                raise InvalidSubnetIdError(list(unknown_ids)[0])
        if filters:
            matches = generic_filter(filters, matches)

        return matches

    def delete_subnet(self, subnet_id: str) -> Subnet:
        for subnets in self.subnets.values():
            if subnet_id in subnets:
                return subnets.pop(subnet_id)
        raise InvalidSubnetIdError(subnet_id)

    def modify_subnet_attribute(
        self, subnet_id: str, attr_name: str, attr_value: str
    ) -> None:
        subnet = self.get_subnet(subnet_id)
        if attr_name in ("map_public_ip_on_launch", "assign_ipv6_address_on_creation"):
            setattr(subnet, attr_name, attr_value)
        else:
            raise InvalidParameterValueError(attr_name)

    def get_subnet_from_ipv6_association(self, association_id: str) -> Optional[Subnet]:
        subnet = None
        for s in self.describe_subnets():
            if association_id in s.ipv6_cidr_block_associations:
                subnet = s
        return subnet

    def associate_subnet_cidr_block(
        self, subnet_id: str, ipv6_cidr_block: str
    ) -> dict[str, Any]:
        subnet = self.get_subnet(subnet_id)
        if not subnet:
            raise InvalidSubnetIdError(subnet_id)
        association = subnet.attach_ipv6_cidr_block_associations(ipv6_cidr_block)
        return association

    def disassociate_subnet_cidr_block(
        self, association_id: str
    ) -> tuple[str, dict[str, str]]:
        subnet = self.get_subnet_from_ipv6_association(association_id)
        if not subnet:
            raise InvalidSubnetCidrBlockAssociationID(association_id)
        association = subnet.detach_subnet_cidr_block(association_id)
        return subnet.id, association

    def create_subnet_association(
        self, route_table_id: str, subnet_id: str
    ) -> SubnetRouteTableAssociation:
        subnet_association = SubnetRouteTableAssociation(route_table_id, subnet_id)
        self.subnet_associations[f"{route_table_id}:{subnet_id}"] = subnet_association
        return subnet_association