Beispiel #1
0
    def test_valid_input_value_is_id(self):
        input_data = "foo"
        field = EmbeddedResourceLinkField("TestResourceSpec", value_is_id=True)
        expected_output_data = [{
            "pred": "test_type_name",
            "obj": "foo",
            "type": "resource_link"
        }]

        links = field.parse(data=input_data, context={})
        output_data = [link.to_dict() for link in links]
        self.assertCountEqual(output_data, expected_output_data)
Beispiel #2
0
class TargetGroupResourceSpec(ElasticLoadBalancingResourceSpec):
    """Resource for target group"""

    type_name = "targetgroup"
    schema = Schema(
        ScalarField("TargetGroupName"),
        ScalarField("Protocol", optional=True),
        ScalarField("Port", optional=True),
        TransientResourceLinkField("VpcId", VPCResourceSpec, optional=True),
        ScalarField("HealthCheckProtocol", optional=True),
        ScalarField("HealthCheckPort", optional=True),
        ScalarField("HealthCheckEnabled"),
        ListField(
            "LoadBalancerArns",
            EmbeddedResourceLinkField(LoadBalancerResourceSpec,
                                      value_is_id=True),
        ),
        ScalarField("TargetType"),
        ListField(
            "TargetHealthDescriptions",
            EmbeddedDictField(
                AnonymousDictField(
                    "Target",
                    ScalarField("Id", alti_key="target_id"),
                    ScalarField("Port", alti_key="target_port", optional=True),
                    ScalarField("AvailabilityZone",
                                alti_key="target_az",
                                optional=True),
                ),
                ScalarField("HealthCheckPort", optional=True),
                AnonymousDictField(
                    "TargetHealth",
                    ScalarField("State"),
                    ScalarField("Reason", optional=True),
                    ScalarField("Description", optional=True),
                    optional=True,
                ),
            ),
        ),
    )

    @classmethod
    def list_from_aws(cls: Type["TargetGroupResourceSpec"], client: BaseClient,
                      account_id: str, region: str) -> ListFromAWSResult:
        """Return a dict of dicts of the format:

            {'target_group_1_arn': {target_group_1_dict},
             'target_group_2_arn': {target_group_2_dict},
             ...}

        Where the dicts represent results from describe_target_groups."""
        paginator = client.get_paginator("describe_target_groups")
        resources = {}
        for resp in paginator.paginate():
            for resource in resp.get("TargetGroups", []):
                resource_arn = resource["TargetGroupArn"]
                resource["TargetHealthDescriptions"] = get_target_group_health(
                    client, resource_arn)
                resources[resource_arn] = resource
        return ListFromAWSResult(resources=resources)
Beispiel #3
0
class LoadBalancerResourceSpec(ElasticLoadBalancingResourceSpec):
    """Resource for load balancer"""

    type_name = "loadbalancer"
    schema = Schema(
        ScalarField("DNSName"),
        ScalarField("CreatedTime"),
        ScalarField("LoadBalancerName"),
        ScalarField("Scheme"),
        ResourceLinkField("VpcId", VPCResourceSpec, optional=True),
        AnonymousDictField("State",
                           ScalarField("Code",
                                       alti_key="load_balancer_state")),
        ScalarField("Type"),
        ListField(
            "AvailabilityZones",
            EmbeddedDictField(
                ScalarField("ZoneName"),
                ResourceLinkField("SubnetId",
                                  SubnetResourceSpec,
                                  optional=True),
                ListField(
                    "LoadBalancerAddresses",
                    EmbeddedDictField(
                        ScalarField("IpAddress", optional=True),
                        ScalarField("AllocationId", optional=True),
                    ),
                    optional=True,
                ),
            ),
        ),
        ListField("SecurityGroups",
                  EmbeddedResourceLinkField(SecurityGroupResourceSpec),
                  optional=True),
        ScalarField("IpAddressType"),
    )

    @classmethod
    def list_from_aws(cls: Type["LoadBalancerResourceSpec"],
                      client: BaseClient, account_id: str,
                      region: str) -> ListFromAWSResult:
        """Return a dict of dicts of the format:

            {'lb_1_arn': {lb_1_dict},
             'lb_2_arn': {lb_2_dict},
             ...}

        Where the dicts represent results from describe_load_balancers."""
        paginator = client.get_paginator("describe_load_balancers")
        load_balancers = {}
        for resp in paginator.paginate():
            for lb in resp.get("LoadBalancers", []):
                resource_arn = lb["LoadBalancerArn"]
                load_balancers[resource_arn] = lb
        return ListFromAWSResult(resources=load_balancers)
class ClassicLoadBalancerResourceSpec(ELBV1ResourceSpec):
    """Resource for classic load balancer"""

    type_name = "loadbalancer"
    schema = Schema(
        ScalarField("DNSName"),
        ScalarField("CreatedTime"),
        ScalarField("LoadBalancerName"),
        ScalarField("Scheme"),
        ResourceLinkField("VPCId", VPCResourceSpec, optional=True),
        ListField("Subnets",
                  EmbeddedResourceLinkField(SubnetResourceSpec),
                  optional=True),
        ListField("SecurityGroups",
                  EmbeddedResourceLinkField(SecurityGroupResourceSpec),
                  optional=True),
        ScalarField("Type"),
        ScalarField("AccessLogsEnabled"),
        TransientResourceLinkField(
            "AccessLogsS3Bucket",
            S3BucketResourceSpec,
            alti_key="access_logs_s3_bucket",
            optional=True,
        ),
        ScalarField("AccessLogsS3Prefix", optional=True),
    )

    @classmethod
    def list_from_aws(
        cls: Type["ClassicLoadBalancerResourceSpec"],
        client: BaseClient,
        account_id: str,
        region: str,
    ) -> ListFromAWSResult:
        """Return a dict of dicts of the format:

            {'lb_1_arn': {lb_1_dict},
             'lb_2_arn': {lb_2_dict},
             ...}

        Where the dicts represent results from describe_load_balancers."""
        paginator = client.get_paginator("describe_load_balancers")
        load_balancers = {}
        for resp in paginator.paginate():
            for lb in resp["LoadBalancerDescriptions"]:
                lb_name = lb["LoadBalancerName"]
                resource_arn = cls.generate_arn(account_id=account_id,
                                                region=region,
                                                resource_id=lb_name)
                try:
                    lb_attrs = cls.get_lb_attrs(client, lb_name)
                    lb.update(lb_attrs)
                    lb["Type"] = "classic"
                    load_balancers[resource_arn] = lb
                except ClientError as c_e:
                    if (getattr(c_e, "response", {}).get("Error", {}).get(
                            "Code", {}) != "LoadBalancerNotFound"):
                        raise c_e
        return ListFromAWSResult(resources=load_balancers)

    @classmethod
    def get_lb_attrs(
        cls: Type["ClassicLoadBalancerResourceSpec"],
        client: BaseClient,
        lb_name: str,
    ) -> Dict[str, str]:
        """Get lb attributes that Altimeter graphs."""
        lb_attrs = {}
        resp = client.describe_load_balancer_attributes(
            LoadBalancerName=lb_name)
        access_log_attrs = resp["LoadBalancerAttributes"]["AccessLog"]
        lb_attrs["AccessLogsEnabled"] = access_log_attrs["Enabled"]
        if "S3BucketName" in access_log_attrs:
            lb_attrs["AccessLogsS3Bucket"] = access_log_attrs["S3BucketName"]
        if "S3BucketPrefix" in access_log_attrs:
            lb_attrs["AccessLogsS3Prefix"] = access_log_attrs["S3BucketPrefix"]
        return lb_attrs
Beispiel #5
0
class LoadBalancerResourceSpec(ELBV2ResourceSpec):
    """Resource for load balancer"""

    type_name = "loadbalancer"
    schema = Schema(
        ScalarField("DNSName"),
        ScalarField("CreatedTime"),
        ScalarField("LoadBalancerName"),
        ScalarField("Scheme"),
        ResourceLinkField("VpcId", VPCResourceSpec, optional=True),
        AnonymousDictField("State",
                           ScalarField("Code",
                                       alti_key="load_balancer_state")),
        ScalarField("Type"),
        ListField(
            "AvailabilityZones",
            EmbeddedDictField(
                ScalarField("ZoneName"),
                ResourceLinkField("SubnetId",
                                  SubnetResourceSpec,
                                  optional=True),
                ListField(
                    "LoadBalancerAddresses",
                    EmbeddedDictField(
                        ScalarField("IpAddress", optional=True),
                        ScalarField("AllocationId", optional=True),
                    ),
                    optional=True,
                ),
            ),
        ),
        ListField("SecurityGroups",
                  EmbeddedResourceLinkField(SecurityGroupResourceSpec),
                  optional=True),
        ScalarField("IpAddressType"),
        ScalarField("AccessLogsEnabled"),
        TransientResourceLinkField(
            "AccessLogsS3Bucket",
            S3BucketResourceSpec,
            alti_key="access_logs_s3_bucket",
            optional=True,
        ),
        ScalarField("AccessLogsS3Prefix", optional=True),
    )

    @classmethod
    def list_from_aws(cls: Type["LoadBalancerResourceSpec"],
                      client: BaseClient, account_id: str,
                      region: str) -> ListFromAWSResult:
        """Return a dict of dicts of the format:

            {'lb_1_arn': {lb_1_dict},
             'lb_2_arn': {lb_2_dict},
             ...}

        Where the dicts represent results from describe_load_balancers."""
        paginator = client.get_paginator("describe_load_balancers")
        load_balancers = {}
        for resp in paginator.paginate():
            for lb in resp.get("LoadBalancers", []):
                resource_arn = lb["LoadBalancerArn"]
                try:
                    lb_attrs = cls.get_lb_attrs(client, resource_arn)
                    lb.update(lb_attrs)
                    load_balancers[resource_arn] = lb
                except ClientError as c_e:
                    if (getattr(c_e, "response", {}).get("Error", {}).get(
                            "Code", {}) != "LoadBalancerNotFound"):
                        raise c_e
        return ListFromAWSResult(resources=load_balancers)

    @classmethod
    def get_lb_attrs(
        cls: Type["LoadBalancerResourceSpec"],
        client: BaseClient,
        lb_arn: str,
    ) -> Dict[str, str]:
        """Get lb attributes that Altimeter graphs."""
        lb_attrs = {}
        resp = client.describe_load_balancer_attributes(LoadBalancerArn=lb_arn)
        for attr in resp["Attributes"]:
            if attr["Key"] == "access_logs.s3.enabled":
                lb_attrs["AccessLogsEnabled"] = attr["Value"]
            elif attr["Key"] == "access_logs.s3.bucket":
                if attr["Value"]:
                    lb_attrs["AccessLogsS3Bucket"] = attr["Value"]
            elif attr["Key"] == "access_logs.s3.prefix":
                if attr["Value"]:
                    lb_attrs["AccessLogsS3Prefix"] = attr["Value"]
        return lb_attrs