Esempio n. 1
0
 def __init__(
     self,
     virtual_network_id="",
     action_id="",
     success=True,
     info_message="",
     error_message="",
     subnet_id="",
 ):
     PrepareSubnetActionResult.__init__(self, action_id, success,
                                        info_message, error_message,
                                        subnet_id)
     self.virtual_network_id = virtual_network_id
Esempio n. 2
0
 def _prepare_results(self, network_action_result, actions):
     network_action_result.actionId = self._get_action_id_by_type(
         actions, PrepareCloudInfra)
     subnet_action_results = [
         PrepareSubnetActionResult(action_id)
         for action_id in self._get_action_ids_by_type(
             actions, PrepareSubnet)
     ]
     create_keys_action_result = CreateKeysActionResult(
         self._get_action_id_by_type(actions, CreateKeys))
     return [network_action_result, create_keys_action_result
             ] + subnet_action_results
Esempio n. 3
0
    def _create_prepare_subnet_result(self, action, subnet):
        action_result = PrepareSubnetActionResult()
        action_result.actionId = action.actionId
        action_result.subnetId = subnet.subnet_id
        action_result.success = True
        action_result.infoMessage = 'PrepareSubnet finished successfully'

        return action_result
    def prepare(self, request):
        """

        :param request:
        :return:
        """
        fabric = self._get_or_create_fabric(name=self.DEFAULT_FABRIC_NAME)

        self._get_or_create_subnet(
            name=self.DEFAULT_SUBNET_NAME,
            cidr=self._resource_config.default_subnet,
            gateway_ip=self._resource_config.default_gateway,
            vlan=fabric.vlans[0],
            managed=self._resource_config.managed_allocation,
        )

        actions = self._request_parser.convert_driver_request_to_actions(request)
        # ignore prepare infra actions
        prep_network_action = single(
            actions, lambda x: isinstance(x, PrepareCloudInfra)
        )
        prep_network_action_result = PrepareCloudInfraResult(
            prep_network_action.actionId
        )

        prep_subnet_action = single(actions, lambda x: isinstance(x, PrepareSubnet))
        prep_subnet_action_result = PrepareSubnetActionResult(
            prep_subnet_action.actionId
        )

        if self._ssh_keys_exists():
            public_key = self._get_ssh_public_key()
        else:
            public_key = self._generate_ssh_key_pair()
            # send to MAAS only public key
            self._maas_client.ssh_keys.create(key=public_key)

        access_keys_action = single(actions, lambda x: isinstance(x, CreateKeys))
        access_keys_action_results = CreateKeysActionResult(
            actionId=access_keys_action.actionId, accessKey=public_key
        )

        action_results = [
            prep_network_action_result,
            prep_subnet_action_result,
            access_keys_action_results,
        ]

        return DriverResponse(action_results).to_driver_response_json()
Esempio n. 5
0
    def PrepareSandboxInfra(self, context, request, cancellation_context):
        """ Called by CloudShell Orchestration during the Setup process
        in order to populate information about the networking environment used by the sandbox

        :param context: ResourceRemoteCommandContext
        :param request: Actions to be performed to prepare the networking environment sent by CloudShell Server
        :param cancellation_context:
        :return:
        """

        with LoggingSessionContext(context) as logger:

            resource_config = ShellResource.create_from_context(context)
            resource_config.api.WriteMessageToReservationOutput(
                resource_config.reservation_id,
                "Preparing Sandbox Connectivity...")

            logger.info(f"REQUEST: {request}")
            logger.info("Cloud Provider Name: {}".format(resource_config.name))

            r_id, reservation_details = get_reservation_details(
                api=resource_config.api,
                reservation_id=resource_config.reservation_id,
                cloud_provider_name=resource_config.name)

            logger.info(
                "Initial Reservation <{res_id}> Details: {details}".format(
                    res_id=r_id, details=reservation_details))
            json_request = json.loads(request)

            vcn_action_id = ""
            subnet_dict = {}
            subnet_results = []

            for action in json_request["driverRequest"]["actions"]:
                if action["type"] == "prepareCloudInfra":
                    vcn_action_id = action.get("actionId")
                elif action["type"] == "prepareSubnet":
                    subnet_action_id = action.get("actionId")
                    subnet_cidr = action.get("actionParams", {}).get("cidr")
                    subnet_alias = action.get("actionParams", {}).get("alias")
                    subnet_dict[subnet_cidr] = (subnet_action_id, subnet_alias)
                elif action["type"] == "createKeys":
                    keys_action_id = action.get("actionId")

            prepare_network_result = PrepareCloudInfraResult(vcn_action_id)

            virl_api = VIRL_API(host=resource_config.address,
                                std_port=resource_config.std_port,
                                uwm_port=resource_config.uwm_port,
                                username=resource_config.username,
                                password=resource_config.password)

            avail_image_types = virl_api.get_available_image_types()

            default_gateway_info = virl_api.get_default_gateway()

            # resources = {}
            for res_name, res_params in reservation_details["resources"].items(
            ):
                image_type = res_params.get("image type")
                if image_type not in avail_image_types:
                    raise VIRLShellError(
                        f"Unable to find requested Image Type {image_type}>. "
                        f"Avail images: {avail_image_types}")

                # NX-OS hack with IP address determination
                # if image_type in self.NEED_IP_ADDRESS:
                # res_params["ip address"] = virl_api.get_dhcp_ipaddr(network_name=resource_config.mgmt_network)
                # resources.update({res_name: res_params})

            # res_details.update({"resources": resources, "default_gateway_info": default_gateway_info})
            reservation_details.update(
                {"default_gateway_info": default_gateway_info})

            logger.info(f"Updated Reservation Details: {reservation_details}")

            topology = Topology(**reservation_details)
            topology_data = topology.create_topology(
                mgmt_net_name=resource_config.mgmt_network,
                template_path=resource_config.templates_path)

            logger.info(f"Topology Data: {topology_data}")

            virl_api.upload_topology(
                topology_data=topology_data,
                reservation_id=resource_config.reservation_id)
            ifaces_info = virl_api.get_ifaces_info(
                topology_name=resource_config.reservation_id)

            for subnet_action_cidr, (subnet_action_id,
                                     alias) in subnet_dict.items():
                logger.info(
                    f"ACTIONS: {subnet_action_id}, {alias}, {subnet_action_cidr}"
                )
                action_id = None

                if alias == "DefaultSubnet":
                    action_id = subnet_action_id
                    subnet_id = resource_config.mgmt_network
                else:
                    for connection in reservation_details.get(
                            "connections", []):
                        logger.info("ACTION CIDR: {}, CONN NETWORK: {}".format(
                            subnet_action_cidr, connection.get("network")))
                        if connection.get("network") == subnet_action_cidr:
                            action_id = subnet_action_id
                            break
                    if not action_id and subnet_action_cidr in reservation_details.get(
                            "subnets", {}).values():
                        action_id = subnet_action_id
                    # else:
                    if not action_id:
                        raise VIRLShellError(
                            f"Couldn't find appropriate network for action id {subnet_action_id}"
                        )

                    subnet_id = None
                    for _, node_params in ifaces_info.items():
                        for node in node_params:
                            address = node.get("ipv4")

                            if address and ipaddress.ip_address(
                                    address) in ipaddress.ip_network(
                                        subnet_action_cidr):
                                subnet_id = node.get("network")
                                break
                        if subnet_id:
                            break

                subnet_result = PrepareSubnetActionResult()
                subnet_result.actionId = action_id
                subnet_result.subnetId = subnet_id
                subnet_result.infoMessage = "Success"
                subnet_results.append(subnet_result)

            prepare_network_result.infoMessage = "PrepareConnectivity finished successfully"

            create_key_result = CreateKeysActionResult(actionId=keys_action_id,
                                                       infoMessage="",
                                                       accessKey="")

            results = [prepare_network_result, create_key_result]
            results.extend(subnet_results)

            result = DriverResponse(results).to_driver_response_json()
            logger.info(f"Prepare result {result}")
            return result