Example #1
0
class Snapshot(Model):
    arn = StringType(default="")
    data_encryption_key_id = StringType(deserialize_from="DataEncryptionKeyId")
    description = StringType(deserialize_from="Description")
    encrypted = BooleanType(deserialize_from="Encrypted")
    kms_key_id = StringType(default="")
    kms_key_arn = StringType(deserialize_from="KmsKeyId")
    owner_id = StringType(deserialize_from="OwnerId")
    account_id = StringType(default="")
    progress = StringType(deserialize_from="Progress")
    snapshot_id = StringType(deserialize_from="SnapshotId")
    start_time = DateTimeType(deserialize_from="StartTime")
    state = StringType(deserialize_from="State",
                       choices=("pending", "completed", "error"))
    state_message = StringType(deserialize_from="StateMessage")
    volume_id = StringType(deserialize_from="VolumeId")
    volume_size = IntType(deserialize_from="VolumeSize")
    owner_alias = StringType(deserialize_from="OwnerAlias")
    tags = ListType(ModelType(Tags), deserialize_from="Tags")
    region_name = StringType(default="")

    @serializable
    def reference(self):
        return {
            "resource_id":
            self.arn,
            "external_link":
            f"https://console.aws.amazon.com/ec2/v2/home?region={self.region_name}#Snapshots:visibility=owned-by-me;snapshotId={self.snapshot_id};sort=snapshotId"
        }

    @serializable
    def cloudwatch(self):
        return {
            "namespace": "AWS/EBS",
            "dimensions": [{
                "Name": "SnapshotId",
                "Value": self.snapshot_id
            }],
            "region_name": self.region_name
        }
Example #2
0
class ElectionConfigSchema(Model):
    """Validating schema for election config."""
    identifier = ElectionIdType(required=True)
    questions = ListType(ElectionIdType, min_size=1, required=True)

    class ElectionVerificationSchema(Model):
        """Validating schema for election verification config."""
        count = IntType(required=True, min_value=0)
        minutes = IntType(required=True, min_value=0)

    verification = ModelType(ElectionVerificationSchema, required=True)

    class ElectionPeriodSchema(Model):
        """Validating schema for election period config."""
        servicestart = DateTimeType(required=True)
        electionstart = DateTimeType(required=True)
        electionstop = DateTimeType(required=True)
        servicestop = DateTimeType(required=True)

    period = ModelType(ElectionPeriodSchema, required=True)
    ignorevoterlist = StringType()

    def validate_questions(self, data, value):
        """Validate question field."""
        if value and len(value) > len(set(value)):
            raise ValidationError('Election questions must be unique')
        return value

    def validate_period(self, data, value):
        """Validate election period."""
        try:
            for point1, point2 in [['servicestart', 'electionstart'],
                                   ['electionstart', 'electionstop'],
                                   ['electionstop', 'servicestop']]:
                if data['period'][point1] >= data['period'][point2]:
                    raise ValidationError('Value "%s" is bigger than "%s"' %
                                          (point1, point2))
        except KeyError:
            pass  # error in data structure is catched later
        return value
Example #3
0
class Message(Model):
    """Represent a message object in a request sent to Facebook.

    # Arguments
        text: Message text. Previews will not be shown for the URLs in this field. Use attachment instead. Must be UTF-8 and has a 2000 character limit. text or attachment must be set.
        attachment: attachment object. Previews the URL. Used to send messages with media or Structured Messages. text or attachment must be set.
        quick_replies: Optional. Array of quick_reply to be sent with messages
        metadata: Optional. Custom string that is delivered as a message echo. 1000 character limit.

    """

    text = StringType(required=False, max_length=2000, serialize_when_none=False)
    attachment = ModelType(Attachment, required=False, serialize_when_none=False)
    quick_replies = ListType(ModelType(QuickReply), required=False)
    metadata = StringType(required=False, max_length=1000)

    def validate_text(self, data, value):
        if data["text"] and data["attachment"]:
            raise ValidationError(
                "Fields text and attachment can't be set at the same time."
            )
        return value
class Snapshot(Model):
    id = StringType()
    location = StringType()
    managed_by = StringType(serialize_when_none=False)
    resource_group = StringType()
    name = StringType()
    creation_data = ModelType(CreationData)
    disk_access_id = StringType(serialize_when_none=False)
    disk_iops_read_write = StringType(serialize_when_none=False)
    disk_m_bps_read_write = StringType(serialize_when_none=False)
    disk_size_bytes = IntType()
    disk_size_gb = IntType()
    disk_state = StringType(choices=('ActiveSAS', 'ActiveUpload', 'Attached', 'ReadyToUpload',
                                     'Reserved', 'Unattached'))
    encryption = ModelType(Encryption)
    encryption_settings_collection = ModelType(EncryptionSettingsCollection, serialize_when_none=False)
    hyper_v_generation = StringType(serialize_when_none=False)
    incremental = BooleanType()
    incremental_display = StringType(default='Full', serialize_when_none=False)
    network_access_policy = StringType(choices=('AllowAll', 'AllowPrivate', 'DenyAll'), serialize_when_none=False)
    network_access_policy_display = StringType(serialize_when_none=False)
    os_type = StringType(serialize_when_none=False)
    provisioning_state = StringType(choices=('Failed', 'Succeeded'), serialize_when_none=False)
    time_created = DateTimeType()
    unique_id = StringType()
    size = IntType()
    sku = ModelType(Sku)
    source_disk_name = StringType()
    subscription_id = StringType()
    subscription_name = StringType()
    tags = ListType(ModelType(Tags), default=[])
    tier_display = StringType(default='')
    type = StringType(serialize_when_none=False)

    def reference(self):
        return {
            "resource_id": self.id,
            "external_link": f"https://portal.azure.com/#@.onmicrosoft.com/resource{self.id}/overview",
        }
Example #5
0
class OptionGroup(Model):
    option_group_name = StringType(deserialize_from="OptionGroupName")
    option_group_description = StringType(
        deserialize_from="OptionGroupDescription")
    engine_name = StringType(deserialize_from="EngineName")
    major_engine_version = StringType(deserialize_from="MajorEngineVersion")
    options = ListType(ModelType(Option), deserialize_from="Options")
    allows_vpc_and_non_vpc_instance_memberships = BooleanType(
        deserialize_from="AllowsVpcAndNonVpcInstanceMemberships")
    vpc_id = StringType(deserialize_from="VpcId")
    option_group_arn = StringType(deserialize_from="OptionGroupArn")
    account_id = StringType()
    region_name = StringType()

    @serializable
    def reference(self):
        return {
            "resource_id":
            self.option_group_arn,
            "external_link":
            f"https://console.aws.amazon.com/rds/home?region={self.region_name}#option-group-details:option-group-name={self.option_group_name}"
        }
Example #6
0
class ResponsePolicy(Model):
    resource_version = StringType(required=True)
    bindings = ListType(ModelType(PolicyBinding), required=True)
    created_at = ArrowType(required=True)
    updated_at = ArrowType(required=True)

    @classmethod
    def from_database(cls, policy: IAMPolicy):
        model = cls()
        model.resource_version = policy.resource_version

        model.bindings = []

        for binding in policy.bindings:
            binding_model = PolicyBinding()
            binding_model.role = binding['role']
            binding_model.members = binding['members']
            model.bindings.append(binding_model)

        model.created_at = policy.created_at
        model.updated_at = policy.updated_at
        return model
Example #7
0
class HTTPModule(BaseModule):
    http = ModelType(HTTPParams, default=lambda: HTTPParams())
    valid_status_codes = ListType(IntType, default=lambda: [200, 201, 204])
    timeout = IntType(default=10)
    no_follow_redirects = BooleanType(default=False)

    def check(self, service_name: str, target_url: str) -> bool:
        is_success = False
        try:
            resp = requests.request(
                method=self.http.method,
                url=target_url,
                data=self.http.body,
                headers=self.http.headers,
                timeout=self.timeout,
            )
            resp.raise_for_status()
            is_success = True
        except Exception:
            logger.exception(
                f"request failed. url: {target_url}, timeout: {self.timeout}")
        return is_success
class CustomerGateway(Model):
    name = StringType(default="")
    bgp_asn = StringType(deserialize_from="BgpAsn")
    customer_gateway_id = StringType(deserialize_from="CustomerGatewayId")
    ip_address = StringType(deserialize_from="IpAddress")
    certificate_arn = StringType(deserialize_from="CertificateArn")
    state = StringType(deserialize_from="State",
                       choices=("pending", "available", "deleting", "deleted"))
    type = StringType(deserialize_from="Type")
    device_name = StringType(deserialize_from="DeviceName")
    tags = ListType(ModelType(Tags), deserialize_from="Tags", default=[])
    vpn_connection = ModelType(VPNConnection)
    region_name = StringType(default="")
    account_id = StringType(default="")

    def reference(self, region_code):
        return {
            "resource_id":
            self.customer_gateway_id,
            "external_link":
            f"https://console.aws.amazon.com/vpc/home?region={region_code}#CustomerGateways:CustomerGatewayId={self.customer_gateway_id};sort=CustomerGatewayId"
        }
Example #9
0
class Aliyun(Model):
    resource_group_id = StringType(serialize_when_none=False)
    instance_type_family = StringType()
    instance_network_type = StringType(choices=("classic", "vpc"))
    instance_charge_type = StringType(choices=("PostPaid", "PrePaid"))
    internet_charge_type = StringType(choices=("PayByBandwidth",
                                               "PayByTraffic"))
    internet_max_bandwidth_in = IntType(serialize_when_none=False)
    internet_max_bandwidth_out = IntType(serialize_when_none=False)
    io_optimized = BooleanType()
    gpu_spec = StringType()
    gpu_amount = IntType()
    recyclable = BooleanType()
    stopped_mode = StringType(choices=("KeepCharging", "StopCharging",
                                       "Not-applicable"))
    credit_specification = StringType(choices=("Standard", "Unlimited"))
    spot_duration = IntType(serialize_when_none=False)
    spot_price_limit = FloatType()
    spot_strategy = StringType(choices=("no_spot", "spot_with_price_limit",
                                        "spot_as_price_go"))
    auto_release_time = DateTimeType(serialize_when_none=False)
    tags = ListType(ModelType(Tags), serialize_when_none=False)
Example #10
0
class Firewall(Model):
    id = StringType()
    name = StringType()
    description = StringType()
    network = StringType()
    priority = IntType()
    direction = StringType()
    source_ranges = ListType(StringType(),
                             deserialize_from='sourceRanges',
                             serialize_when_none=False)
    destination_ranges = ListType(StringType(),
                                  deserialize_from='destinationRanges',
                                  serialize_when_none=False)
    source_tags = ListType(StringType(),
                           deserialize_from='sourceTags',
                           serialize_when_none=False)
    target_tags = ListType(StringType(),
                           deserialize_from='targetTags',
                           serialize_when_none=False)
    source_service_accounts = ListType(
        StringType(),
        deserialize_from='sourceServiceAccounts',
        serialize_when_none=False)
    target_service_accounts = ListType(
        StringType(),
        deserialize_from='targetServiceAccounts',
        serialize_when_none=False)
    allowed = ListType(ModelType(Allowed), serialize_when_none=False)
    denied = ListType(ModelType(Allowed), serialize_when_none=False)
    disabled = BooleanType(serialize_when_none=False)
    log_config = ModelType(LogConfig,
                           deserialize_from='logConfig',
                           serialize_when_none=False)
    self_link = StringType(deserialize_from='selfLink')
    creation_timestamp = DateTimeType(deserialize_from='creationTimestamp')
    display = ModelType(FirewallDisplay, serialize_when_none=False)
Example #11
0
class Raw002(SequenceSpecificationBase):
    '''
    Raw JPEG sequences with 1 or 3 channels and coordinates.

    Attributes:
        filename_fields (list[str]): project, specification, descriptor,
            version, frame, extension
        asset_name_fields (list[str]): project, specification, descriptor,
            version,
        height (int): Image height. Must be 1024.
        width (int): Image width. Must be 1024.
        extension (str): File extension. Must be "png".
    '''
    asset_name_fields = ['project', 'specification', 'descriptor',
                         'version']  # type: List[str]
    filename_fields = [
        'project', 'specification', 'descriptor', 'version', 'coordinate',
        'frame', 'extension'
    ]  # type: List[str]
    height = ListType(IntType(), required=True)  # type: ListType
    width = ListType(IntType(), required=True)  # type: ListType
    frame = ListType(IntType(), required=True,
                     validators=[vd.is_frame])  # type: ListType
    coordinate = ListType(
        ListType(IntType(), validators=[vd.is_coordinate]),
        required=True,
    )  # type: ListType
    channels = ListType(IntType(),
                        required=True,
                        validators=[lambda x: vd.is_in(x, [1, 3])
                                    ])  # type: ListType
    extension = ListType(
        StringType(),
        required=True,
        validators=[vd.is_extension,
                    lambda x: vd.is_eq(x, 'jpg')])  # type: ListType
    file_traits = dict(
        width=tr.get_image_width,
        height=tr.get_image_height,
        channels=tr.get_num_image_channels,
    )  # type: Dict[str, Any]
Example #12
0
class PredictionDTO(Model):
    """ Describes JSON of a set of predictions from a model """

    prediction_id = IntType(serialized_name='predictionsId')
    created = DateTimeType()
    model_id = IntType(serialized_name='modelId', required=True)
    version_id = IntType(serialized_name='versionId', required=True)
    version_string = StringType(serialized_name='versionString')
    docker_url = StringType(serialized_name='dockerUrl')
    bbox = ListType(FloatType, required=True)
    tile_zoom = IntType(serialized_name='tileZoom', required=True)

    """ Asset Status
        log_link - store a link to the AWS CloudWatch Console
        model_link - store a link to the S3 Location of the raw model
        docker_link - store a link to the container in ECR
        save_link - download the TFServing container
    """

    log_link = StringType(serialized_name='logLink')
    model_link = StringType(serialized_name='modelLink')
    docker_link = StringType(serialized_name='dockerLink')
    save_link = StringType(serialized_name='saveLink')
class ElasticPool(Model):
    name = StringType(serialize_when_none=False)
    id = StringType()
    kind = StringType(serialize_when_none=False)
    location = StringType()
    creation_date = DateTimeType(serialize_when_none=False)
    license_type = StringType(choices=('BasePrice', 'LicenseIncluded'), default='BasePrice')
    maintenance_configuration_id = StringType(serialize_when_none=False)
    max_size_bytes = IntType(serialize_when_none=False)
    max_size_gb = FloatType(serialize_when_none=False, default=0)
    per_database_settings = ModelType(ElasticPoolPerDatabaseSettings, serialize_when_none=False)
    state = StringType(choices=('Creating', 'Disabled', 'Ready'), serialize_when_none=False)
    zone_redundant = BooleanType(serialize_when_none=False)
    sku = ModelType(Sku)
    per_db_settings_display = StringType(serialize_when_none=False)
    pricing_tier_display = StringType(serialize_when_none=False)
    databases = ListType(ModelType(Database))
    number_of_databases = IntType(serialize_when_none=False, default=0)
    unit_display = StringType(serialize_when_none=False),
    server_name_display = StringType(serialize_when_none=False)
    resource_group_display = StringType(serialize_when_none=False)
    tags = ModelType(Tags)
    type = StringType(serialize_when_none=False)
Example #14
0
class Route(Model):
    id = StringType()
    name = StringType()
    description = StringType()
    network = StringType()
    dest_range = StringType(deserialize_from='destRange')
    priority = IntType()
    tags = ListType(StringType(), default=[])
    nextHopInstance = StringType(deserialize_from='nextHopInstance',
                                 serialize_when_none=False)
    nextHopIp = StringType(deserialize_from='nextHopIp',
                           serialize_when_none=False)
    nextHopNetwork = StringType(deserialize_from='nextHopNetwork',
                                serialize_when_none=False)
    nextHopGateway = StringType(deserialize_from='nextHopGateway',
                                serialize_when_none=False)
    nextHopPeering = StringType(deserialize_from='nextHopPeering',
                                serialize_when_none=False)
    nextHopIlb = StringType(deserialize_from='nextHopIlb',
                            serialize_when_none=False)
    next_hop = StringType()
    self_link = StringType(deserialize_from='selfLink')
    creation_timestamp = DateTimeType(deserialize_from='creationTimestamp')
class DbNode(Model):
    id = StringType(deserialize_from='_id')
    db_system_id = StringType(deserialize_from='_db_system_id')
    vnic_id = StringType(deserialize_from='_vnid_id')
    backup_vnic_id = StringType(deserialize_from='_backup_vnic_id')
    lifecycle_state = StringType(
        deserialize_from='_lifecycle_state',
        choices=('PROVISIONING', 'AVAILABLE', 'UPDATING', 'STOPPING',
                 'STOPPED', 'STARTING', 'TERMINATING', 'TERMINATED', 'FAILED'))
    hostname = StringType(deserialize_from='_hostname')
    fault_domain = StringType(deserialize_from='_fault_domain')
    time_created = DateTimeType(deserialize_from='_time_created')
    software_storage_size_in_gb = StringType(
        deserialize_from='_software_storage_size_in_gb')
    maintenance_type = StringType(deserialize_from='_maintenance_type')
    time_maintenance_window_start = DateTimeType(
        deserialize_from='_time_maintenance_window_start')
    time_maintenance_window_end = DateTimeType(
        deserialize_from='_time_maintenance_window_end')
    additional_details = StringType(deserialize_from='_additional_details')
    console_connections = ListType(ModelType(ConsoleConnections),
                                   deserialize_from='console_connections',
                                   default=[])
Example #16
0
class UserManagementCommandSchema(Model):
    """Validating schema for user management command."""
    action = StringType(required=True, regex='user-permissions')
    cn = StringType(required=True, regex='.+,.+,[0-9]{11}')
    roles = ListType(StringType(), required=True)

    def validate(self, partial=False, convert=True, app_data=None, **kwargs):
        """Validate model."""
        super().validate(partial, convert, app_data, **kwargs)

        # role list checks
        if not isinstance(self.roles, list):
            raise DataError({'roles': 'Value is not a list'})
        # pylint: disable=not-an-iterable
        for role in self.roles:
            if role not in ROLES:
                raise DataError({'roles': 'Unknown role "%s"' % role})
        if len(self.roles) != len(set(self.roles)):
            raise DataError({'roles': 'Duplicate roles'})
        # pylint: disable=unsupported-membership-test
        if 'none' in self.roles and len(self.roles) > 1:
            raise DataError(
                {'roles': 'Role "none" can\'t be used with orher roles'})
Example #17
0
class LAGConnections(Model):
    owner_account = StringType(deserialize_from="ownerAccount")
    connection_id = StringType(deserialize_from="connectionId")
    connection_name = StringType(deserialize_from="connectionName")
    connection_state = StringType(deserialize_from="connectionState",
                                  choices=("ordering", "requested", "pending",
                                           "available", "down", "deleting",
                                           "deleted", "rejected", "unknown"))
    region = StringType(deserialize_from="region")
    location = StringType(deserialize_from="location")
    bandwidth = StringType(deserialize_from="bandwidth")
    vlan = IntType(deserialize_from="vlan")
    partner_name = StringType(deserialize_from="partnerName")
    loa_issue_time = DateTimeType(deserialize_from="loaIssueTime")
    lag_id = StringType(deserialize_from="lagId")
    aws_device = StringType(deserialize_from="awsDevice")
    jumbo_frame_capable = BooleanType(deserialize_from="jumboFrameCapable")
    aws_device_v2 = StringType(deserialize_from="awsDeviceV2")
    has_logical_redundancy = StringType(
        deserialize_from="hasLogicalRedundancy",
        choices=("unknown", "yes", "no"))
    tags = ListType(ModelType(Tags))
    provider_name = StringType(deserialize_from="providerName")
Example #18
0
class Branch(BaseModel):
    collection_name = "branches"

    _id = MongoUIDType(serialize_when_none=False)
    name = StringType(required=True, min_length=3, max_length=300)
    description = StringType(max_length=1000)
    features = ListType(ModelType(BranchFeature))

    created_at = DateTimeType(default=datetime.datetime.now)
    parent_id = MongoUIDType()

    def get_parent(self):
        if self.parent_id:
            return self.get(self.parent_id)

    def set_parent(self, value):
        self.parent_id = value.id

    parent = property(get_parent, set_parent)

    def __init__(self, raw_data, *args, **kwargs):
        raw_data["features"] = raw_data.get("features") or []
        super(Branch, self).__init__(raw_data, *args, **kwargs)
Example #19
0
class ResponseInstance(Model):
    id = UUIDType(required=True)
    name = StringType(required=True, min_length=3)
    image_id = UUIDType(required=True)
    network_port_id = UUIDType(required=True)
    region_id = UUIDType(required=True)
    zone_id = UUIDType()
    service_account_id = UUIDType()
    keypair_ids = ListType(UUIDType, default=list)
    state = EnumType(InstanceState, required=True)
    tags = DictType(StringType, default=dict)

    created_at = ArrowType(required=True)
    updated_at = ArrowType(required=True)

    @classmethod
    def from_database(cls, instance: Instance):
        instance_model = cls()
        instance_model.id = instance.id
        instance_model.name = instance.name
        instance_model.image_id = instance.image_id
        instance_model.network_port_id = instance.network_port_id
        instance_model.state = instance.state
        instance_model.tags = instance.tags
        instance_model.service_account_id = instance.service_account_id

        instance_model.region_id = instance.region_id
        if instance.zone_id is not None:
            instance_model.zone_id = instance.zone_id

        for keypair in instance.keypairs:
            instance_model.keypair_ids.append(keypair.id)

        instance_model.created_at = instance.created_at
        instance_model.updated_at = instance.updated_at

        return instance_model
Example #20
0
class InstanceSetting(Model):
    authorize_gae_applications = ListType(
        StringType, deserialize_from="authorizedGaeApplications")
    tier = StringType()
    kind = StringType()
    availability_type = StringType(deserialize_from="availabilityType")
    pricing_plan = StringType(deserialize_from="pricingPlan")
    replication_type = StringType(deserialize_from="replicationType")
    activation_policy = StringType(deserialize_from="activationPolicy")
    ip_configuration = ModelType(IPConfiguration,
                                 deserialize_from="ipConfiguration")
    location_preference = ModelType(LocationPreference,
                                    deserialize_from="locationPreference")
    data_disk_type = StringType(deserialize_from="dataDiskType")
    maintenance_window = ModelType(MaintenanceWindow,
                                   deserialize_from="maintenanceWindow")
    backup_configuration = ModelType(BackupConfiguration,
                                     deserialize_from="backupConfiguration")
    collation = StringType()
    settings_version = StringType(deserialize_from="settingsVersion")
    storage_auto_resize_limit = StringType(
        deserialize_from="storageAutoResizeLimit")
    storage_auto_resize = BooleanType(deserialize_from="storageAutoResize")
    data_disk_size_gb = StringType(deserialize_from="dataDiskSizeGb")
class HostedZone(Model):
    arn = StringType()
    id = StringType(deserialize_from="Id")
    hosted_zone_id = StringType()
    name = StringType(deserialize_from="Name")
    caller_reference = StringType(deserialize_from="CallerReference")
    config = ModelType(Config, deserialize_from="Config")
    resource_record_set_count = IntType(
        deserialize_from="ResourceRecordSetCount")
    linked_service = ModelType(LinkedService, deserialize_from="LinkedService")
    type = StringType(default="")
    record_sets = ListType(ModelType(RecordSet))
    account_id = StringType(default="")
    cloudwatch = ModelType(CloudWatchModel, serialize_when_none=False)

    def reference(self):
        return {
            "resource_id":
            self.arn,
            "external_link":
            f"https://console.aws.amazon.com/route53/home#resource-record-sets:{self.hosted_zone_id}"
        }

    def set_cloudwatch(self, region_name='us-east-1'):
        return {
            "namespace":
            "AWS/Route53",
            "dimensions": [
                CloudWatchDimensionModel({
                    'Name': 'HostedZoneId',
                    'Value': self.hosted_zone_id
                })
            ],
            "region_name":
            region_name
        }
Example #22
0
class ElasticIPAddress(Model):
    name = StringType(default="")
    instance_id = StringType(deserialize_from="InstanceId")
    public_ip = StringType(deserialize_from="PublicIp")
    public_dns = StringType()
    nat_gateway_id = StringType()
    allocation_status = StringType(choices=('In-use', 'Unused'))
    allocation_id = StringType(deserialize_from="AllocationId")
    association_id = StringType(deserialize_from="AssociationId")
    domain = StringType(deserialize_from="Domain", choices=("vpc", "standard"))
    network_interface_id = StringType(deserialize_from="NetworkInterfaceId")
    network_interface_owner_id = StringType(deserialize_from="NetworkInterfaceOwnerId")
    private_ip_address = StringType(deserialize_from="PrivateIpAddress")
    tags = ListType(ModelType(ElasticIPAddressTags), deserialize_from="Tags", default=[])
    public_ipv4_pool = StringType(deserialize_from="PublicIpv4Pool")
    network_border_group = StringType(deserialize_from="NetworkBorderGroup")
    customer_owned_ip = StringType(deserialize_from="CustomerOwnedIp")
    customer_owned_ipv4_pool = StringType(deserialize_from="CustomerOwnedIpv4Pool")

    def reference(self, region_code):
        return {
            "resource_id": self.public_ip,
            "external_link": f"https://console.aws.amazon.com/ec2/v2/home?region={region_code}#ElasticIpDetails:PublicIp={self.public_ip}"
        }
Example #23
0
class RequestCreateNetwork(Model):
    name = KubeName(required=True, min_length=3)
    port_group = StringType(required=True)
    cidr = IPv4NetworkType(required=True)
    gateway = IPv4AddressType(required=True)
    dns_servers = ListType(IPv4AddressType, min_size=1, required=True)
    pool_start = IPv4AddressType(required=True)
    pool_end = IPv4AddressType(required=True)
    region_name = KubeName(required=True)

    def validate_gateway(self, data, value):
        cidr: ipaddress.IPv4Network = data['cidr']

        if value not in cidr:
            raise ValidationError('is not an address within ' + str(cidr))

        return value

    def validate_pool_start(self, data, value):
        cidr: ipaddress.IPv4Network = data['cidr']

        if value not in cidr:
            raise ValidationError('is not an address within ' + str(cidr))

        return value

    def validate_pool_end(self, data, value):
        cidr: ipaddress.IPv4Network = data['cidr']

        if value not in cidr:
            raise ValidationError('is not an address within ' + str(cidr))

        if value < self.pool_start:
            raise ValidationError('needs to be larger than pool_start')

        return value
Example #24
0
class DeliveryStreamDescription(Model):
    delivery_stream_name = StringType(deserialize_from='DeliveryStreamName')
    delivery_stream_arn = StringType(deserialize_from='DeliveryStreamARN')
    delivery_stream_status = StringType(
        deserialize_from='DeliveryStreamStatus',
        choices=('CREATING', 'CREATING_FAILED', 'DELETING', 'DELETING_FAILED',
                 'ACTIVE', 'SUSPENDED'))
    failure_description = ModelType(FailureDescription,
                                    deserialize_from='FailureDescription')
    delivery_stream_encryption_configuration = ModelType(
        DeliveryStreamEncryptionConfiguration,
        deserialize_from='DeliveryStreamEncryptionConfiguration',
        serialize_when_none=False)
    delivery_stream_type = StringType(deserialize_from="DeliveryStreamType",
                                      choices=('DirectPut',
                                               'KinesisStreamAsSource'))
    version_id = StringType(deserialize_from='VersionId')
    create_timestamp = DateTimeType(deserialize_from='CreateTimestamp')
    last_update_timestamp = DateTimeType(
        deserialize_from='LastUpdateTimestamp')
    source = ModelType(Source,
                       serialize_when_none=False,
                       deserialize_from='Source')
    destinations = ListType(ModelType(Destinations),
                            deserialize_from="Destinations")
    # destinations_ref = ModelType(DestinationsRef)
    # additional_tabs = ModelType(AdditionalTabs)
    HasMoreDestinations = BooleanType(deserialize_from='has_more_destinations')

    def reference(self, region_code):
        return {
            'resource_id':
            self.delivery_stream_arn,
            'external_link':
            f'https://console.aws.amazon.com/firehose/home?region={region_code}#/details/{self.delivery_stream_name}'
        }
Example #25
0
class ForwardingRule(Model):
    id = StringType()
    name = StringType()
    description = StringType()
    type = StringType(choices=['Global', 'Regional'])
    ip_address = StringType(deserialize_from='IPAddress', serialize_when_none=False)
    ip_protocol = StringType(deserialize_from='IPProtocol', serialize_when_none=False)
    port_range = StringType(deserialize_from='portRange', serialize_when_none=False)
    ports = ListType(StringType(), default=[])
    region = StringType(default='global')
    ip_version = StringType(deserialize_from='ipVersion', serialize_when_none=False)
    fingerprint = StringType(serialize_when_none=False)
    kind = StringType(serialize_when_none=False)
    target = StringType(serialize_when_none=False)
    self_link = StringType(deserialize_from='selfLink', serialize_when_none=False)
    load_balancing_scheme = StringType(choices=['EXTERNAL', 'INTERNAL', 'INTERNAL_MANAGED', 'INTERNAL_SELF_MANAGED'],
                                       serialize_when_none=False)
    subnetwork = StringType(serialize_when_none=False)
    network = StringType(serialize_when_none=False)
    back_service = StringType(serialize_when_none=False)
    service_label = StringType(serialize_when_none=False)
    service_name = StringType(serialize_when_none=False)
    network_tier = StringType(deserialize_from='networkTier', choices=('Premium', 'Standard'))
    creation_timestamp = DateTimeType(deserialize_from='creationTimestamp', serialize_when_none=False)
Example #26
0
class ConfigurationServiceSecret(ServiceWithParameters):
    name = StringType(required=True)
    provider = StringType(required=True)
    parameters = ListType(ModelType(ProviderParameters), default=[])

    __value = StringType()

    def validate_provider(self, data, value):
        if value not in ProviderManager.plugins.keys():
            raise ProviderNotFoundException(value)

        if not isinstance(ProviderManager.plugins[value], BaseSecretPluginProvider):
            raise WrongConfiguration("Provider '%s' can not be used for secret discovery" % value)

    def __init__(self, *args, **kwargs):
        super(ConfigurationServiceSecret, self).__init__(*args, **kwargs)
        self.validate()

        sd = ProviderManager.plugins[self.provider].call(
            parameters=self.parameters
        )

        self.__value = sd.value
        self.validate()
Example #27
0
class VPNConnectionTunnelOption(Model):
    outside_ip_address = StringType(deserialize_from="OutsideIpAddress")
    tunnel_inside_cidr = StringType(deserialize_from="TunnelInsideCidr")
    pre_shared_key = StringType(deserialize_from="PreSharedKey")
    phase1_lifetime_seconds = IntType(deserialize_from="Phase1LifetimeSeconds")
    phase2_lifetime_seconds = IntType(deserialize_from="Phase2LifetimeSeconds")
    rekey_margin_time_seconds = IntType(deserialize_from="RekeyMarginTimeSeconds")
    rekey_fuzz_percentage = IntType(deserialize_from="RekeyFuzzPercentage")
    replay_window_size = IntType(deserialize_from="ReplayWindowSize")
    dpd_timeout_seconds = IntType(deserialize_from="DpdTimeoutSeconds")
    phase1_encryption_algorithms = ListType(ModelType(VPNConnectionTunnelOptionPhase1EncryptionAlgorithms),
                                            deserialize_from="Phase1EncryptionAlgorithms")
    phase2_encryption_algorithms = ListType(ModelType(VPNConnectionTunnelOptionPhase2EncryptionAlgorithms),
                                            deserialize_from="Phase2EncryptionAlgorithms")
    phase1_integrity_algorithms = ListType(ModelType(VPNConnectionTunnelOptionPhase1IntegrityAlgorithms),
                                           deserialize_from="Phase1IntegrityAlgorithms")
    phase2_integrity_algorithms = ListType(ModelType(VPNConnectionTunnelOptionPhase2IntegrityAlgorithms),
                                           deserialize_from="Phase2IntegrityAlgorithms")
    phase1_dh_group_numbers = ListType(ModelType(VPNConnectionTunnelOptionPhase1DHGroupNumbers),
                                       deserialize_from="Phase1DHGroupNumbers")
    phase2_dh_group_numbers = ListType(ModelType(VPNConnectionTunnelOptionPhase2DHGroupNumbers),
                                       deserialize_from="Phase2DHGroupNumbers")
    ike_versions = ListType(ModelType(VPNConnectionTunnelOptionIkeVersions), deserialize_from="IkeVersions")
Example #28
0
class SecurityRule(Model):
    etag = StringType(serialize_when_none=False)
    id = StringType(serialize_when_none=False)
    name = StringType(serialize_when_none=False)
    access = StringType(choices=('Allow', 'Deny'), serialize_when_none=False)
    description = StringType(serialize_when_none=False)
    destination_address_prefix = StringType(serialize_when_none=False)
    destination_address_prefixes = ListType(StringType, serialize_when_none=False)
    destination_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
    destination_port_range = StringType(serialize_when_none=False)
    destination_port_ranges = ListType(StringType, serialize_when_none=False)
    direction = StringType(choices=('Inbound', 'Outbound'), serialize_when_none=False)
    priority = IntType(serialize_when_none=False)
    protocol = StringType(choices=('*', 'Ah', 'Esp', 'Icmp', 'Tcp', 'Udp'), serialize_when_none=False)
    provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
    source_address_prefix = StringType(serialize_when_none=False)
    source_address_prefixes = ListType(StringType, serialize_when_none=False)
    source_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
    source_port_range = StringType(serialize_when_none=False)
    source_port_ranges = ListType(StringType, serialize_when_none=False)
Example #29
0
class Config(Model):
    '''
        Used to validate the batch configuration file
    '''

    # Input C/C++ header files to parse
    headers = ListType(StringType, required=True)

    # Jinja2 templates processed once per config
    templates = ListType(ModelType(Template), default=[])

    # Jinja2 templates processed for each class
    class_templates = ListType(ModelType(Template), default=[])

    # Input custom hooks
    hooks = StringType()

    #: YAML file to load with variables
    data = StringType()

    #: Variables to pass to the template
    vars = DictType(StringType, default={})

    #: For macros or other nonsense, these will
    #: be added to CppHeaderParser's ignore list
    ignore_symbols = ListType(StringType)

    #: Enable preprocessing of the file
    preprocess = BooleanType(default=False)

    #: If True, don't modify preprocessed output and keep #line preprocessing
    #: tokens in the output. Otherwise, remove anything not associated with
    #: the file being parsed.
    pp_retain_all_content = BooleanType(default=False)

    #: Include directories (relative to root) to use for preprocessing
    pp_include_paths = ListType(StringType, default=[])

    #: Preprocessor defines. For example, if you're parsing C++ code,
    #: it might make sense to add '__cplusplus 201103L' here
    pp_defines = ListType(StringType, default=[])
Example #30
0
class AzureFirewall(Model):
    etag = StringType()
    id = StringType()
    location = StringType(serialize_when_none=False)
    name = StringType(serialize_when_none=False)
    subnet = StringType(serialize_when_none=False)
    application_rule_collections = ListType(ModelType(AzureFirewallApplicationRuleCollection), serialize_when_none=False)
    firewall_policy = ModelType(SubResource, serialize_when_none=False)
    hub_ip_addresses = ModelType(HubIPAddresses, serialize_when_none=False)
    ip_configurations = ListType(ModelType(AzureFirewallIPConfiguration), serialize_when_none=False)
    ip_groups = ListType(ModelType(AzureFirewallIpGroups), serialize_when_none=False)
    management_ip_configuration = ModelType(AzureFirewallIPConfiguration, serialize_when_none=False)
    nat_rule_collections = ListType(ModelType(AzureFirewallNatRuleCollection), serialize_when_none=False)
    network_rule_collections = ListType(ModelType(AzureFirewallNetworkRuleCollection), serialize_when_none=False)
    provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
    sku = ModelType(AzureFirewallSku, serialize_when_none=False)
    threat_intel_mode = StringType(choices=('Alert', 'Deny', 'Off'), serialize_when_none=False)
    virtual_hub = ModelType(SubResource, serialize_when_none=False)
    tags = ModelType(Tags, serialize_when_none=False)
    type = StringType(serialize_when_none=False)
    zones = ListType(StringType, serialize_when_none=False)