Exemple #1
0
    def attributes(self):
        result = {}

        for attribute in self.base_attributes:
            attr = getattr(self, camelcase_to_underscores(attribute))
            result[attribute] = attr

        if self.fifo_queue:
            for attribute in self.fifo_attributes:
                attr = getattr(self, camelcase_to_underscores(attribute))
                result[attribute] = attr

        if self.kms_master_key_id:
            for attribute in self.kms_attributes:
                attr = getattr(self, camelcase_to_underscores(attribute))
                result[attribute] = attr

        if self.policy:
            result['Policy'] = self.policy

        if self.redrive_policy:
            result['RedrivePolicy'] = json.dumps(self.redrive_policy)

        for key in result:
            if isinstance(result[key], bool):
                result[key] = str(result[key]).lower()

        return result
Exemple #2
0
def test_camelcase_to_underscores():
    cases = {
        "theNewAttribute": "the_new_attribute",
        "attri bute With Space": "attribute_with_space",
        "FirstLetterCapital": "first_letter_capital",
    }
    for arg, expected in cases.items():
        camelcase_to_underscores(arg).should.equal(expected)
Exemple #3
0
 def set_queue_attributes(self):
     queue_name = self._get_queue_name()
     if "Attribute.Name" in self.querystring:
         key = camelcase_to_underscores(self.querystring.get("Attribute.Name")[0])
         value = self.querystring.get("Attribute.Value")[0]
         self.sqs_backend.set_queue_attribute(queue_name, key, value)
     for a in self._get_list_prefix("Attribute"):
         key = camelcase_to_underscores(a["name"])
         value = a["value"]
         self.sqs_backend.set_queue_attribute(queue_name, key, value)
     return SET_QUEUE_ATTRIBUTE_RESPONSE
Exemple #4
0
 def set_queue_attributes(self):
     queue_name = self._get_queue_name()
     if "Attribute.Name" in self.querystring:
         key = camelcase_to_underscores(
             self.querystring.get("Attribute.Name")[0])
         value = self.querystring.get("Attribute.Value")[0]
         self.sqs_backend.set_queue_attribute(queue_name, key, value)
     for a in self._get_list_prefix("Attribute"):
         key = camelcase_to_underscores(a["name"])
         value = a["value"]
         self.sqs_backend.set_queue_attribute(queue_name, key, value)
     return SET_QUEUE_ATTRIBUTE_RESPONSE
Exemple #5
0
    def call_action(self):
        headers = self.response_headers

        try:
            self._authenticate_and_authorize_normal_action()
        except HTTPException as http_error:
            response = http_error.description, dict(status=http_error.code)
            return self._send_response(headers, response)

        action = camelcase_to_underscores(self._get_action())
        method_names = method_names_from_class(self.__class__)
        if action in method_names:
            method = getattr(self, action)
            try:
                response = method()
            except HTTPException as http_error:
                response = http_error.description, dict(status=http_error.code)

            if isinstance(response, six.string_types):
                return 200, headers, response
            else:
                return self._send_response(headers, response)

        if not action:
            return 404, headers, ''

        raise NotImplementedError(
            "The {0} action has not been implemented".format(action))
Exemple #6
0
 def to_full_dict(self):
     hsh = {
         "executionInfo": self.to_medium_dict(),
         "executionConfiguration": {
             "taskList": {
                 "name": self.task_list
             }
         },
     }
     # configuration
     for key in self._configuration_keys:
         attr = camelcase_to_underscores(key)
         if not hasattr(self, attr):
             continue
         if not getattr(self, attr):
             continue
         hsh["executionConfiguration"][key] = getattr(self, attr)
     # counters
     hsh["openCounts"] = self.open_counts
     # latest things
     if self.latest_execution_context:
         hsh["latestExecutionContext"] = self.latest_execution_context
     if self.latest_activity_task_timestamp:
         hsh["latestActivityTaskTimestamp"] = self.latest_activity_task_timestamp
     return hsh
Exemple #7
0
    def create_topic(self, name, attributes=None, tags=None):

        if attributes is None:
            attributes = {}
        if (
            attributes.get("FifoTopic")
            and attributes.get("FifoTopic").lower() == "true"
        ):
            fails_constraints = not re.match(r"^[a-zA-Z0-9_-]{1,256}\.fifo$", name)
            msg = "Fifo Topic names must end with .fifo and must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, and hyphens, and must be between 1 and 256 characters long."

        else:
            fails_constraints = not re.match(r"^[a-zA-Z0-9_-]{1,256}$", name)
            msg = "Topic names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, and hyphens, and must be between 1 and 256 characters long."

        if fails_constraints:
            raise InvalidParameterValue(msg)

        candidate_topic = Topic(name, self)
        if attributes:
            for attribute in attributes:
                setattr(
                    candidate_topic,
                    camelcase_to_underscores(attribute),
                    attributes[attribute],
                )
        if tags:
            candidate_topic._tags = tags
        if candidate_topic.arn in self.topics:
            return self.topics[candidate_topic.arn]
        else:
            self.topics[candidate_topic.arn] = candidate_topic
            return candidate_topic
Exemple #8
0
 def _get_dict_param(self, param_prefix):
     params = {}
     for key, value in self.querystring.items():
         if key.startswith(param_prefix):
             params[camelcase_to_underscores(key.replace(param_prefix,
                                                         ""))] = value[0]
     return params
Exemple #9
0
 def _get_dict_param(self, param_prefix):
     return {
         camelcase_to_underscores(key.replace(param_prefix, "")): value[0]
         for key, value
         in self.querystring.items()
         if key.startswith(param_prefix)
     }
Exemple #10
0
    def create_from_cloudformation_json(
        cls, resource_name, cloudformation_json, region_name, **kwargs
    ):
        from ..models import ec2_backends

        properties = cloudformation_json["Properties"]["SpotFleetRequestConfigData"]
        ec2_backend = ec2_backends[region_name]

        spot_price = properties.get("SpotPrice")
        target_capacity = properties["TargetCapacity"]
        iam_fleet_role = properties["IamFleetRole"]
        allocation_strategy = properties["AllocationStrategy"]
        launch_specs = properties["LaunchSpecifications"]
        launch_specs = [
            dict(
                [
                    (camelcase_to_underscores(key), val)
                    for key, val in launch_spec.items()
                ]
            )
            for launch_spec in launch_specs
        ]

        spot_fleet_request = ec2_backend.request_spot_fleet(
            spot_price,
            target_capacity,
            iam_fleet_role,
            allocation_strategy,
            launch_specs,
        )

        return spot_fleet_request
Exemple #11
0
    def call_action(self):
        headers = self.response_headers
        action = self.querystring.get('Action', [""])[0]
        if not action:  # Some services use a header for the action
            # Headers are case-insensitive. Probably a better way to do this.
            match = self.headers.get(
                'x-amz-target') or self.headers.get('X-Amz-Target')
            if match:
                action = match.split(".")[-1]

        action = camelcase_to_underscores(action)
        method_names = method_names_from_class(self.__class__)
        if action in method_names:
            method = getattr(self, action)
            try:
                response = method()
            except HTTPException as http_error:
                response = http_error.description, dict(status=http_error.code)
            if isinstance(response, six.string_types):
                return 200, headers, response
            else:
                body, new_headers = response
                status = new_headers.get('status', 200)
                headers.update(new_headers)
                # Cast status to string
                if "status" in headers:
                    headers['status'] = str(headers['status'])
                return status, headers, body

        raise NotImplementedError(
            "The {0} action has not been implemented".format(action))
Exemple #12
0
    def call_action(self):
        headers = self.response_headers
        action = camelcase_to_underscores(self._get_action())
        method_names = method_names_from_class(self.__class__)
        if action in method_names:
            method = getattr(self, action)
            try:
                response = method()
            except HTTPException as http_error:
                response = http_error.description, dict(status=http_error.code)

            if isinstance(response, six.string_types):
                return 200, headers, response
            else:
                if len(response) == 2:
                    body, new_headers = response
                else:
                    status, new_headers, body = response
                status = new_headers.get('status', 200)
                headers.update(new_headers)
                # Cast status to string
                if "status" in headers:
                    headers['status'] = str(headers['status'])
                return status, headers, body

        if not action:
            return 404, headers, ''

        raise NotImplementedError(
            "The {0} action has not been implemented".format(action))
Exemple #13
0
 def set_queue_attributes(self):
     # TODO validate self.get_param('QueueUrl')
     queue_name = self._get_queue_name()
     for key, value in self.attribute.items():
         key = camelcase_to_underscores(key)
         self.sqs_backend.set_queue_attribute(queue_name, key, value)
     return SET_QUEUE_ATTRIBUTE_RESPONSE
Exemple #14
0
    def call_action(self):
        headers = self.response_headers
        action = camelcase_to_underscores(self._get_action())
        method_names = method_names_from_class(self.__class__)
        if action in method_names:
            method = getattr(self, action)
            try:
                response = method()
            except HTTPException as http_error:
                response = http_error.description, dict(status=http_error.code)

            if isinstance(response, six.string_types):
                return 200, headers, response
            else:
                if len(response) == 2:
                    body, new_headers = response
                else:
                    status, new_headers, body = response
                status = new_headers.get('status', 200)
                headers.update(new_headers)
                # Cast status to string
                if "status" in headers:
                    headers['status'] = str(headers['status'])
                return status, headers, body

        if not action:
            return 404, headers, ''

        raise NotImplementedError(
            "The {0} action has not been implemented".format(action))
Exemple #15
0
 def describe_vpc_attribute(self):
     vpc_id = self._get_param("VpcId")
     attribute = self._get_param("Attribute")
     attr_name = camelcase_to_underscores(attribute)
     value = self.ec2_backend.describe_vpc_attribute(vpc_id, attr_name)
     template = self.response_template(DESCRIBE_VPC_ATTRIBUTE_RESPONSE)
     return template.render(vpc_id=vpc_id, attribute=attribute, value=value)
Exemple #16
0
 def describe_vpc_attribute(self):
     vpc_id = self.querystring.get('VpcId')[0]
     attribute = self.querystring.get('Attribute')[0]
     attr_name = camelcase_to_underscores(attribute)
     value = self.ec2_backend.describe_vpc_attribute(vpc_id, attr_name)
     template = self.response_template(DESCRIBE_VPC_ATTRIBUTE_RESPONSE)
     return template.render(vpc_id=vpc_id, attribute=attribute, value=value)
Exemple #17
0
 def set_queue_attributes(self):
     # TODO validate self.get_param('QueueUrl')
     queue_name = self._get_queue_name()
     for key, value in self.attribute.items():
         key = camelcase_to_underscores(key)
         self.sqs_backend.set_queue_attribute(queue_name, key, value)
     return SET_QUEUE_ATTRIBUTE_RESPONSE
Exemple #18
0
    def apigateway_response_restapis_individual(self, request, full_url, headers):
        if request.method in ['GET', 'DELETE']:
            return apigateway_response_restapis_individual_orig(self, request, full_url, headers)

        self.setup_class(request, full_url, headers)
        function_id = self.path.replace('/restapis/', '', 1).split('/')[0]

        if self.method == 'PATCH':
            not_supported_attributes = ['/id', '/region_name', '/create_date']

            rest_api = self.backend.apis.get(function_id)
            if not rest_api:
                msg = 'Invalid API identifier specified %s:%s' % (TEST_AWS_ACCOUNT_ID, function_id)
                return (404, {}, msg)

            patch_operations = self._get_param('patchOperations')
            for operation in patch_operations:
                if operation['path'].strip('/') in REST_API_ATTRIBUTES:
                    operation['path'] = camelcase_to_underscores(operation['path'])
                if operation['path'] in not_supported_attributes:
                    msg = 'Invalid patch path %s' % (operation['path'])
                    return (400, {}, msg)

            rest_api.__dict__ = DelSafeDict(rest_api.__dict__)
            apply_json_patch_safe(rest_api.__dict__, patch_operations, in_place=True)

            return 200, {}, json.dumps(self.backend.get_rest_api(function_id).to_dict())

        # handle import rest_api via swagger file
        if self.method == 'PUT':
            body = json.loads(to_str(self.body))
            rest_api = self.backend.put_rest_api(function_id, body)
            return 200, {}, json.dumps(rest_api.to_dict())

        return 400, {}, ''
Exemple #19
0
    def _set_attributes(self, attributes, now=None):
        if not now:
            now = unix_time()

        integer_fields = (
            "DelaySeconds",
            "KmsDataKeyreusePeriodSeconds",
            "MaximumMessageSize",
            "MessageRetentionPeriod",
            "ReceiveMessageWaitTime",
            "VisibilityTimeout",
        )
        bool_fields = ("ContentBasedDeduplication", "FifoQueue")

        for key, value in six.iteritems(attributes):
            if key in integer_fields:
                value = int(value)
            if key in bool_fields:
                value = value == "true"

            if key in ["Policy", "RedrivePolicy"] and value is not None:
                continue

            setattr(self, camelcase_to_underscores(key), value)

        if attributes.get("RedrivePolicy", None):
            self._setup_dlq(attributes["RedrivePolicy"])

        if attributes.get("Policy"):
            self.policy = attributes["Policy"]

        self.last_modified_timestamp = now
Exemple #20
0
 def create_from_cloudformation_json(
     cls, resource_name, cloudformation_json, region_name, **kwargs
 ):
     # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html
     props = deepcopy(cloudformation_json["Properties"])
     props = {camelcase_to_underscores(k): v for k, v in props.items()}
     return efs_backends[region_name].create_mount_target(**props)
Exemple #21
0
 def dispatch(self):
     endpoint = self.get_endpoint_name(self.headers)
     if endpoint:
         endpoint = camelcase_to_underscores(endpoint)
         return getattr(self, endpoint)(self.uri, self.method, self.body, self.headers)
     else:
         return "", dict(status=404)
Exemple #22
0
 def describe_vpc_attribute(self):
     vpc_id = self.querystring.get('VpcId')[0]
     attribute = self.querystring.get('Attribute')[0]
     attr_name = camelcase_to_underscores(attribute)
     value = self.ec2_backend.describe_vpc_attribute(vpc_id, attr_name)
     template = self.response_template(DESCRIBE_VPC_ATTRIBUTE_RESPONSE)
     return template.render(vpc_id=vpc_id, attribute=attribute, value=value)
Exemple #23
0
 def set_queue_attributes(self):
     queue_name = self.path.split("/")[-1]
     key = camelcase_to_underscores(
         self.querystring.get('Attribute.Name')[0])
     value = self.querystring.get('Attribute.Value')[0]
     self.sqs_backend.set_queue_attribute(queue_name, key, value)
     return SET_QUEUE_ATTRIBUTE_RESPONSE
Exemple #24
0
    def call_action(self):
        headers = self.response_headers
        action = self.querystring.get('Action', [""])[0]
        if not action:  # Some services use a header for the action
            # Headers are case-insensitive. Probably a better way to do this.
            match = self.headers.get('x-amz-target') or self.headers.get(
                'X-Amz-Target')
            if match:
                action = match.split(".")[-1]

        action = camelcase_to_underscores(action)
        method_names = method_names_from_class(self.__class__)
        if action in method_names:
            method = getattr(self, action)
            try:
                response = method()
            except HTTPException as http_error:
                response = http_error.description, dict(status=http_error.code)
            if isinstance(response, six.string_types):
                return 200, headers, response
            else:
                body, new_headers = response
                status = new_headers.get('status', 200)
                headers.update(new_headers)
                return status, headers, body
        raise NotImplementedError(
            "The {0} action has not been implemented".format(action))
Exemple #25
0
    def create_from_cloudformation_json(cls, resource_name,
                                        cloudformation_json, region_name):
        properties = cloudformation_json["Properties"]

        elbv2_backend = elbv2_backends[region_name]
        load_balancer_arn = properties.get("LoadBalancerArn")
        protocol = properties.get("Protocol")
        port = properties.get("Port")
        ssl_policy = properties.get("SslPolicy")
        certificates = properties.get("Certificates")
        # transform default actions to confirm with the rest of the code and XML templates
        if "DefaultActions" in properties:
            default_actions = []
            for i, action in enumerate(properties["DefaultActions"]):
                action_type = action["Type"]
                if action_type == "forward":
                    default_actions.append({
                        "type":
                        action_type,
                        "target_group_arn":
                        action["TargetGroupArn"],
                    })
                elif action_type in [
                        "redirect",
                        "authenticate-cognito",
                        "fixed-response",
                ]:
                    redirect_action = {"type": action_type}
                    key = (underscores_to_camelcase(
                        action_type.capitalize().replace("-", "_")) + "Config")
                    for redirect_config_key, redirect_config_value in action[
                            key].items():
                        # need to match the output of _get_list_prefix
                        redirect_action[
                            camelcase_to_underscores(key) + "._" +
                            camelcase_to_underscores(
                                redirect_config_key)] = redirect_config_value
                    default_actions.append(redirect_action)
                else:
                    raise InvalidActionTypeError(action_type, i + 1)
        else:
            default_actions = None

        listener = elbv2_backend.create_listener(load_balancer_arn, protocol,
                                                 port, ssl_policy,
                                                 certificates, default_actions)
        return listener
Exemple #26
0
 def describe_instance_attribute(self):
     # TODO this and modify below should raise IncorrectInstanceState if instance not in stopped state
     attribute = self.querystring.get("Attribute")[0]
     key = camelcase_to_underscores(attribute)
     instance_id = self.instance_ids[0]
     instance, value = ec2_backend.describe_instance_attribute(instance_id, key)
     template = Template(EC2_DESCRIBE_INSTANCE_ATTRIBUTE)
     return template.render(instance=instance, attribute=attribute, value=value)
Exemple #27
0
    def _set_attributes(fn, self, attributes, now=None):
        fn(self, attributes, now)

        integer_fields = ["ReceiveMessageWaitTimeSeconds"]

        for key in integer_fields:
            attribute = camelcase_to_underscores(key)
            setattr(self, attribute, int(getattr(self, attribute, 0)))
Exemple #28
0
 def attributes(self):
     result = {}
     for attribute in self.camelcase_attributes:
         attr = getattr(self, camelcase_to_underscores(attribute))
         if isinstance(attr, bool):
             attr = str(attr).lower()
         result[attribute] = attr
     return result
Exemple #29
0
 def attributes(self):
     result = {}
     for attribute in self.camelcase_attributes:
         attr = getattr(self, camelcase_to_underscores(attribute))
         if isinstance(attr, bool):
             attr = str(attr).lower()
         result[attribute] = attr
     return result
Exemple #30
0
 def describe_instance_attribute(self):
     # TODO this and modify below should raise IncorrectInstanceState if instance not in stopped state
     attribute = self.querystring.get("Attribute")[0]
     key = camelcase_to_underscores(attribute)
     instance_ids = instance_ids_from_querystring(self.querystring)
     instance_id = instance_ids[0]
     instance, value = ec2_backend.describe_instance_attribute(instance_id, key)
     template = Template(EC2_DESCRIBE_INSTANCE_ATTRIBUTE)
     return template.render(instance=instance, attribute=attribute, value=value)
Exemple #31
0
    def modify_vpc_attribute(self):
        vpc_id = self.querystring.get('VpcId')[0]

        for attribute in ('EnableDnsSupport', 'EnableDnsHostnames'):
            if self.querystring.get('%s.Value' % attribute):
                attr_name = camelcase_to_underscores(attribute)
                attr_value = self.querystring.get('%s.Value' % attribute)[0]
                self.ec2_backend.modify_vpc_attribute(vpc_id, attr_name, attr_value)
                return MODIFY_VPC_ATTRIBUTE_RESPONSE
Exemple #32
0
    def apigateway_response_restapis_individual(self, request, full_url,
                                                headers):
        if request.method in ["GET", "DELETE"]:
            return apigateway_response_restapis_individual_orig(
                self, request, full_url, headers)

        self.setup_class(request, full_url, headers)
        function_id = self.path.replace("/restapis/", "", 1).split("/")[0]

        if self.method == "PATCH":
            not_supported_attributes = ["/id", "/region_name", "/createdDate"]

            rest_api = self.backend.apis.get(function_id)
            if not rest_api:
                msg = "Invalid API identifier specified %s:%s" % (
                    TEST_AWS_ACCOUNT_ID,
                    function_id,
                )
                return 404, {}, msg

            patch_operations = self._get_param("patchOperations")
            model_attributes = list(rest_api.__dict__.keys())
            for operation in patch_operations:
                if operation["path"] in not_supported_attributes:
                    msg = "Invalid patch path %s" % (operation["path"])
                    return 400, {}, msg
                path_start = operation["path"].strip("/").split("/")[0]
                path_start_usc = camelcase_to_underscores(path_start)
                if path_start not in model_attributes and path_start_usc in model_attributes:
                    operation["path"] = operation["path"].replace(
                        path_start, path_start_usc)

            rest_api.__dict__ = DelSafeDict(rest_api.__dict__)
            apply_json_patch_safe(rest_api.__dict__,
                                  patch_operations,
                                  in_place=True)

            # fix data types after patches have been applied
            rest_api.minimum_compression_size = int(
                rest_api.minimum_compression_size or -1)
            endpoint_configs = rest_api.endpoint_configuration or {}
            if isinstance(endpoint_configs.get("vpcEndpointIds"), str):
                endpoint_configs["vpcEndpointIds"] = [
                    endpoint_configs["vpcEndpointIds"]
                ]

            return 200, {}, json.dumps(
                self.backend.get_rest_api(function_id).to_dict())

        # handle import rest_api via swagger file
        if self.method == "PUT":
            body = json.loads(to_str(self.body))
            rest_api = self.backend.put_rest_api(function_id, body,
                                                 self.querystring)
            return 200, {}, json.dumps(rest_api.to_dict())

        return 400, {}, ""
Exemple #33
0
    def modify_vpc_attribute(self):
        vpc_id = self._get_param("VpcId")

        for attribute in ("EnableDnsSupport", "EnableDnsHostnames"):
            if self.querystring.get("%s.Value" % attribute):
                attr_name = camelcase_to_underscores(attribute)
                attr_value = self.querystring.get("%s.Value" % attribute)[0]
                self.ec2_backend.modify_vpc_attribute(vpc_id, attr_name, attr_value)
                return MODIFY_VPC_ATTRIBUTE_RESPONSE
Exemple #34
0
    def modify_instance_attribute(self):
        for key, value in self.querystring.iteritems():
            if ".Value" in key:
                break

        value = self.querystring.get(key)[0]
        normalized_attribute = camelcase_to_underscores(key.split(".")[0])
        instance_id = self.instance_ids[0]
        ec2_backend.modify_instance_attribute(instance_id, normalized_attribute, value)
        return EC2_MODIFY_INSTANCE_ATTRIBUTE
Exemple #35
0
    def modify_subnet_attribute(self):
        subnet_id = self._get_param('SubnetId')

        for attribute in ('MapPublicIpOnLaunch', 'AssignIpv6AddressOnCreation'):
            if self.querystring.get('%s.Value' % attribute):
                attr_name = camelcase_to_underscores(attribute)
                attr_value = self.querystring.get('%s.Value' % attribute)[0]
                self.ec2_backend.modify_subnet_attribute(
                    subnet_id, attr_name, attr_value)
                return MODIFY_SUBNET_ATTRIBUTE_RESPONSE
Exemple #36
0
 def attributes(self):
     result = {}
     for attribute in self.camelcase_attributes:
         attr = getattr(self, camelcase_to_underscores(attribute))
         if isinstance(attr, bool):
             attr = str(attr).lower()
         elif attribute == 'RedrivePolicy':
             attr = json.dumps(attr)
         result[attribute] = attr
     return result
Exemple #37
0
 def to_full_dict(self):
     hsh = {"typeInfo": self.to_medium_dict(), "configuration": {}}
     if self.task_list:
         hsh["configuration"]["defaultTaskList"] = {"name": self.task_list}
     for key in self._configuration_keys:
         attr = camelcase_to_underscores(key)
         if not getattr(self, attr):
             continue
         hsh["configuration"][key] = getattr(self, attr)
     return hsh
Exemple #38
0
    def modify_vpc_attribute(self):
        vpc_id = self.querystring.get('VpcId')[0]

        for attribute in ('EnableDnsSupport', 'EnableDnsHostnames'):
            if self.querystring.get('%s.Value' % attribute):
                attr_name = camelcase_to_underscores(attribute)
                attr_value = self.querystring.get('%s.Value' % attribute)[0]
                self.ec2_backend.modify_vpc_attribute(vpc_id, attr_name,
                                                      attr_value)
                return MODIFY_VPC_ATTRIBUTE_RESPONSE
Exemple #39
0
    def create_from_cloudformation_json(cls, resource_name,
                                        cloudformation_json, region_name):
        properties = cloudformation_json['Properties']

        elbv2_backend = elbv2_backends[region_name]
        load_balancer_arn = properties.get("LoadBalancerArn")
        protocol = properties.get("Protocol")
        port = properties.get("Port")
        ssl_policy = properties.get("SslPolicy")
        certificates = properties.get("Certificates")
        # transform default actions to confirm with the rest of the code and XML templates
        if "DefaultActions" in properties:
            default_actions = []
            for i, action in enumerate(properties['DefaultActions']):
                action_type = action['Type']
                if action_type == 'forward':
                    default_actions.append({
                        'type':
                        action_type,
                        'target_group_arn':
                        action['TargetGroupArn']
                    })
                elif action_type in ['redirect', 'authenticate-cognito']:
                    redirect_action = {'type': action_type}
                    key = 'RedirectConfig' if action_type == 'redirect' else 'AuthenticateCognitoConfig'
                    for redirect_config_key, redirect_config_value in action[
                            key].items():
                        # need to match the output of _get_list_prefix
                        redirect_action[
                            camelcase_to_underscores(key) + '._' +
                            camelcase_to_underscores(
                                redirect_config_key)] = redirect_config_value
                    default_actions.append(redirect_action)
                else:
                    raise InvalidActionTypeError(action_type, i + 1)
        else:
            default_actions = None

        listener = elbv2_backend.create_listener(load_balancer_arn, protocol,
                                                 port, ssl_policy,
                                                 certificates, default_actions)
        return listener
Exemple #40
0
 def modify_subnet_attribute(
     self, context: RequestContext, request: ModifySubnetAttributeRequest
 ) -> None:
     try:
         return call_moto(context)
     except Exception as e:
         if not isinstance(e, ResponseParserError) and "InvalidParameterValue" not in str(e):
             raise
         # fix setting subnet attributes currently not supported upstream
         backend = ec2_backends[context.region]
         subnet_id = request["SubnetId"]
         host_type = request.get("PrivateDnsHostnameTypeOnLaunch")
         if host_type:
             attr_name = camelcase_to_underscores("PrivateDnsNameOptionsOnLaunch")
             value = {"HostnameType": host_type}
             backend.modify_subnet_attribute(subnet_id, attr_name, value)
         enable_dns64 = request.get("EnableDns64")
         if enable_dns64:
             attr_name = camelcase_to_underscores("EnableDns64")
             backend.modify_subnet_attribute(subnet_id, attr_name, enable_dns64)
Exemple #41
0
    def describe_instance_attribute(self, instance_id, attribute):
        if attribute not in Instance.VALID_ATTRIBUTES:
            raise InvalidParameterValueErrorUnknownAttribute(attribute)

        if attribute == "groupSet":
            key = "security_groups"
        else:
            key = camelcase_to_underscores(attribute)
        instance = self.get_instance(instance_id)
        value = getattr(instance, key)
        return instance, value
Exemple #42
0
    def modify_subnet_attribute(self):
        subnet_id = self._get_param("SubnetId")

        for attribute in ("MapPublicIpOnLaunch",
                          "AssignIpv6AddressOnCreation"):
            if self.querystring.get("%s.Value" % attribute):
                attr_name = camelcase_to_underscores(attribute)
                attr_value = self.querystring.get("%s.Value" % attribute)[0]
                self.ec2_backend.modify_subnet_attribute(
                    subnet_id, attr_name, attr_value)
                return MODIFY_SUBNET_ATTRIBUTE_RESPONSE
Exemple #43
0
    def _patch_api_gateway_entity(
            self, entity: Dict) -> Optional[Tuple[int, Dict, str]]:
        not_supported_attributes = ["/id", "/region_name", "/create_date"]

        patch_operations = self._get_param("patchOperations")

        model_attributes = list(entity.keys())
        for operation in patch_operations:
            if operation["path"].strip("/") in REST_API_ATTRIBUTES:
                operation["path"] = camelcase_to_underscores(operation["path"])
            path_start = operation["path"].strip("/").split("/")[0]
            path_start_usc = camelcase_to_underscores(path_start)
            if path_start not in model_attributes and path_start_usc in model_attributes:
                operation["path"] = operation["path"].replace(
                    path_start, path_start_usc)
            if operation["path"] in not_supported_attributes:
                msg = "Invalid patch path %s" % (operation["path"])
                return 400, {}, msg

        apply_json_patch_safe(entity, patch_operations, in_place=True)
Exemple #44
0
    def create_from_cloudformation_json(cls, resource_name,
                                        cloudformation_json, region_name):
        properties = cloudformation_json["Properties"]

        elbv2_backend = elbv2_backends[region_name]
        listener_arn = properties.get("ListenerArn")
        priority = properties.get("Priority")
        conditions = properties.get("Conditions")

        default_actions = []
        for i, action in enumerate(properties["Actions"]):
            action_type = action["Type"]
            if action_type == "forward":
                default_actions.append({
                    "type":
                    action_type,
                    "target_group_arn":
                    action["TargetGroupArn"],
                })
            elif action_type in [
                    "redirect",
                    "authenticate-cognito",
                    "fixed-response",
            ]:
                redirect_action = {"type": action_type}
                key = (underscores_to_camelcase(
                    action_type.capitalize().replace("-", "_")) + "Config")
                for redirect_config_key, redirect_config_value in action[
                        key].items():
                    # need to match the output of _get_list_prefix
                    redirect_action[
                        camelcase_to_underscores(key) + "._" +
                        camelcase_to_underscores(
                            redirect_config_key)] = redirect_config_value
                default_actions.append(redirect_action)
            else:
                raise InvalidActionTypeError(action_type, i + 1)

        listener_rule = elbv2_backend.create_rule(listener_arn, conditions,
                                                  priority, default_actions)
        return listener_rule
Exemple #45
0
 def to_full_dict(self):
     hsh = {
         "typeInfo": self.to_medium_dict(),
         "configuration": {}
     }
     if self.task_list:
         hsh["configuration"]["defaultTaskList"] = {"name": self.task_list}
     for key in self._configuration_keys:
         attr = camelcase_to_underscores(key)
         if not getattr(self, attr):
             continue
         hsh["configuration"][key] = getattr(self, attr)
     return hsh
Exemple #46
0
    def set_topic_attributes(self):
        topic_arn = self._get_param('TopicArn')
        attribute_name = self._get_param('AttributeName')
        attribute_name = camelcase_to_underscores(attribute_name)
        attribute_value = self._get_param('AttributeValue')
        self.backend.set_topic_attribute(topic_arn, attribute_name, attribute_value)

        return json.dumps({
            "SetTopicAttributesResponse": {
                "ResponseMetadata": {
                    "RequestId": "a8763b99-33a7-11df-a9b7-05d48da6f042"
                }
            }
        })
Exemple #47
0
 def _get_list_prefix(self, param_prefix):
     results = []
     param_index = 1
     while True:
         index_prefix = "{0}.{1}.".format(param_prefix, param_index)
         new_items = {}
         for key, value in self.querystring.items():
             if key.startswith(index_prefix):
                 new_items[camelcase_to_underscores(key.replace(index_prefix, ""))] = value[0]
         if not new_items:
             break
         results.append(new_items)
         param_index += 1
     return results
Exemple #48
0
    def call_action(self):
        self.body = json.loads(self.body or '{}')
        endpoint = self.get_endpoint_name(self.headers)
        if endpoint:
            endpoint = camelcase_to_underscores(endpoint)
            response = getattr(self, endpoint)()
            if isinstance(response, six.string_types):
                return 200, self.response_headers, response

            else:
                status_code, new_headers, response_content = response
                self.response_headers.update(new_headers)
                return status_code, self.response_headers, response_content
        else:
            return 404, self.response_headers, ""
Exemple #49
0
    def modify_instance_attribute(self):
        attribute_key = None
        for key, value in self.querystring.iteritems():
            if '.Value' in key:
                attribute_key = key
                break

        if not attribute_key:
            return
        value = self.querystring.get(attribute_key)[0]
        normalized_attribute = camelcase_to_underscores(attribute_key.split(".")[0])
        instance_ids = instance_ids_from_querystring(self.querystring)
        instance_id = instance_ids[0]
        ec2_backend.modify_instance_attribute(instance_id, normalized_attribute, value)
        return EC2_MODIFY_INSTANCE_ATTRIBUTE
Exemple #50
0
 def __init__(self, name, version, **kwargs):
     self.name = name
     self.version = version
     self.status = "REGISTERED"
     if "description" in kwargs:
         self.description = kwargs.pop("description")
     for key, value in kwargs.items():
         self.__setattr__(key, value)
     # default values set to none
     for key in self._configuration_keys:
         attr = camelcase_to_underscores(key)
         if not hasattr(self, attr):
             self.__setattr__(attr, None)
     if not hasattr(self, "task_list"):
         self.task_list = None
Exemple #51
0
    def describe_instance_attribute(self):
        # TODO this and modify below should raise IncorrectInstanceState if
        # instance not in stopped state
        attribute = self.querystring.get("Attribute")[0]
        key = camelcase_to_underscores(attribute)
        instance_ids = instance_ids_from_querystring(self.querystring)
        instance_id = instance_ids[0]
        instance, value = self.ec2_backend.describe_instance_attribute(instance_id, key)

        if key == "group_set":
            template = self.response_template(EC2_DESCRIBE_INSTANCE_GROUPSET_ATTRIBUTE)
        else:
            template = self.response_template(EC2_DESCRIBE_INSTANCE_ATTRIBUTE)

        return template.render(instance=instance, attribute=attribute, value=value)
Exemple #52
0
 def call_action(self):
     headers = self.response_headers
     action = self.querystring.get('Action', [""])[0]
     action = camelcase_to_underscores(action)
     method_names = method_names_from_class(self.__class__)
     if action in method_names:
         method = getattr(self, action)
         response = method()
         if isinstance(response, basestring):
             return 200, headers, response
         else:
             body, new_headers = response
             status = new_headers.pop('status', 200)
             headers.update(new_headers)
             return status, headers, body
     raise NotImplementedError("The {} action has not been implemented".format(action))
Exemple #53
0
    def describe_instance_attribute(self):
        # TODO this and modify below should raise IncorrectInstanceState if
        # instance not in stopped state
        attribute = self._get_param('Attribute')
        key = camelcase_to_underscores(attribute)
        instance_id = self._get_param('InstanceId')
        instance, value = self.ec2_backend.describe_instance_attribute(
            instance_id, key)

        if key == "group_set":
            template = self.response_template(
                EC2_DESCRIBE_INSTANCE_GROUPSET_ATTRIBUTE)
        else:
            template = self.response_template(EC2_DESCRIBE_INSTANCE_ATTRIBUTE)

        return template.render(instance=instance, attribute=attribute, value=value)
Exemple #54
0
    def dispatch(self, uri, method, body, headers):
        if body:
            querystring = parse_qs(body)
        else:
            querystring = parse_qs(headers)

        action = querystring.get('Action', [None])[0]
        if action:
            action = camelcase_to_underscores(action)

        for sub_response in self.sub_responses:
            method_names = method_names_from_class(sub_response)
            if action in method_names:
                response = sub_response(querystring)
                method = getattr(response, action)
                return method()
        raise NotImplementedError("The {} action has not been implemented".format(action))
Exemple #55
0
    def dispatch(self, uri, method, body, headers):
        if body:
            querystring = parse_qs(body)
        else:
            querystring = headers_to_dict(headers)

        self.path = uri.path
        self.querystring = querystring

        action = querystring.get('Action', [""])[0]
        action = camelcase_to_underscores(action)

        method_names = method_names_from_class(self.__class__)
        if action in method_names:
            method = getattr(self, action)
            return method()
        raise NotImplementedError("The {} action has not been implemented".format(action))
Exemple #56
0
    def set_topic_attributes(self):
        topic_arn = self._get_param('TopicArn')
        attribute_name = self._get_param('AttributeName')
        attribute_name = camelcase_to_underscores(attribute_name)
        attribute_value = self._get_param('AttributeValue')
        self.backend.set_topic_attribute(topic_arn, attribute_name, attribute_value)

        if self.request_json:
            return json.dumps({
                "SetTopicAttributesResponse": {
                    "ResponseMetadata": {
                        "RequestId": "a8763b99-33a7-11df-a9b7-05d48da6f042"
                    }
                }
            })

        template = self.response_template(SET_TOPIC_ATTRIBUTES_TEMPLATE)
        return template.render()
Exemple #57
0
    def _dot_value_instance_attribute_handler(self):
        attribute_key = None
        for key, value in self.querystring.items():
            if '.Value' in key:
                attribute_key = key
                break

        if not attribute_key:
            return

        if self.is_not_dryrun('Modify' + attribute_key.split(".")[0]):
            value = self.querystring.get(attribute_key)[0]
            normalized_attribute = camelcase_to_underscores(
                attribute_key.split(".")[0])
            instance_id = self._get_param('InstanceId')
            self.ec2_backend.modify_instance_attribute(
                instance_id, normalized_attribute, value)
            return EC2_MODIFY_INSTANCE_ATTRIBUTE
Exemple #58
0
    def call_action(self):
        if 'GetSessionToken' in self.body:
            return 200, self.response_headers, sts_handler()

        self.body = json.loads(self.body or '{}')
        endpoint = self.get_endpoint_name(self.headers)
        if endpoint:
            endpoint = camelcase_to_underscores(endpoint)
            response = getattr(self, endpoint)()
            if isinstance(response, basestring):
                return 200, self.response_headers, response

            else:
                status_code, new_headers, response_content = response
                self.response_headers.update(new_headers)
                return status_code, self.response_headers, response_content
        else:
            return 404, self.response_headers, ""
Exemple #59
0
    def _get_dict_param(self, param_prefix):
        """
        Given a parameter dict of
        {
            'Instances.SlaveInstanceType': ['m1.small'],
            'Instances.InstanceCount': ['1']
        }

        returns
        {
            "SlaveInstanceType": "m1.small",
            "InstanceCount": "1",
        }
        """
        params = {}
        for key, value in self.querystring.items():
            if key.startswith(param_prefix):
                params[camelcase_to_underscores(key.replace(param_prefix, ""))] = value[0]
        return params
Exemple #60
0
 def call_action(self):
     headers = self.response_headers
     action = self.querystring.get('Action', [""])[0]
     action = camelcase_to_underscores(action)
     method_names = method_names_from_class(self.__class__)
     if action in method_names:
         method = getattr(self, action)
         try:
             response = method()
         except HTTPException as http_error:
             response = http_error.description, dict(status=http_error.code)
         if isinstance(response, six.string_types):
             return 200, headers, response
         else:
             body, new_headers = response
             status = new_headers.get('status', 200)
             headers.update(new_headers)
             return status, headers, body
     raise NotImplementedError("The {0} action has not been implemented".format(action))