Beispiel #1
0
    def ApplyConnectivityChanges(self, context, request):
        """
        Configures VLANs on multiple ports or port-channels
        :param ResourceCommandContext context: The context object for the command with resource and reservation info
        :param str request: A JSON string with the list of requested connectivity changes
        :return: a json object with the list of connectivity changes which were carried out by the driver
        :rtype: str
        """
        with LoggingSessionContext(context) as logger, ErrorHandlingContext(
                logger):
            self._log(logger, 'ApplyConnectivityChanges_request', request)
            self._log(logger, 'ApplyConnectivityChanges_context', context)

            # parse the json strings into action objects
            cloud_provider_resource = L2HeavenlyCloudShell.create_from_context(
                context)
            actions = self.request_parser.convert_driver_request_to_actions(
                request)

            # extract Set/Remove vlan actions
            remove_vlan_actions = filter(lambda x: isinstance(x, RemoveVlan),
                                         actions)
            remove_vlan_results = HeavenlyCloudServiceWrapper.disconnect_all(
                logger, cloud_provider_resource, remove_vlan_actions)

            set_vlan_actions = filter(lambda x: isinstance(x, SetVlan),
                                      actions)
            set_vlan_results = HeavenlyCloudServiceWrapper.connect_all(
                logger, cloud_provider_resource, set_vlan_actions)

            return DriverResponse(remove_vlan_results +
                                  set_vlan_results).to_driver_response_json()
Beispiel #2
0
 def CreateTrafficMirroring(self,
                            context,
                            request,
                            cancellation_context=None):
     action_results = self.aws_shell.create_traffic_mirroring(
         context, cancellation_context, request)
     return DriverResponse(action_results).to_driver_response_json()
Beispiel #3
0
    def deploy(self, request):
        """

        :param request:
        :return:
        """
        actions = self._request_parser.convert_driver_request_to_actions(
            request)
        deploy_action = single(actions, lambda x: isinstance(x, DeployApp))
        attrs = deploy_action.actionParams.deployment.attributes

        machine = self._get_free_machine(
            cpus=int(attrs["Maas.MAAS Machine.CPU Cores"]),
            memory=float(attrs["Maas.MAAS Machine.RAM GiB"]),
            disks=int(attrs["Maas.MAAS Machine.Disks"]),
            storage=float(attrs["Maas.MAAS Machine.Storage GB"]))

        operating_system = attrs["Maas.MAAS Machine.Operation System"]
        machine.deploy(distro_series=operating_system, wait=True)

        self._reconnect_machine_to_sandbox_subnet(machine=machine)

        deploy_result = DeployAppResult(deploy_action.actionId,
                                        vmUuid=machine.system_id,
                                        vmName=operating_system,
                                        vmDetailsData=None,
                                        deployedAppAdditionalData={})

        return DriverResponse([deploy_result]).to_driver_response_json()
Beispiel #4
0
 def DeleteSavedApps(self, context, request, cancellation_context=None):
     actions = self.request_parser.convert_driver_request_to_actions(
         request)
     delete_actions = [x for x in actions if isinstance(x, DeleteSavedApp)]
     save_app_results = self.command_orchestrator.delete_saved_sandbox(
         context, delete_actions, cancellation_context)
     return DriverResponse(save_app_results).to_driver_response_json()
Beispiel #5
0
    def CleanupSandboxInfra(self, context, request):
        """

        :param ResourceCommandContext context:
        :param str request:
        :return:
        :rtype: str
        """
        with LoggingSessionContext(context) as logger, ErrorHandlingContext(
                logger):
            with CloudShellSessionContext(context) as cloudshell_session:
                self._log(logger, 'CleanupSandboxInfra_request', request)
                self._log(logger, 'CleanupSandboxInfra_context', context)

                cloud_provider_resource = L3HeavenlyCloudShell.create_from_context(
                    context)

                # parse the json strings into action objects
                actions = self.request_parser.convert_driver_request_to_actions(
                    request)

                # extract CleanupNetwork action
                cleanup_action = single(
                    actions, lambda x: isinstance(x, CleanupNetwork))

                action_result = HeavenlyCloudServiceWrapper.cleanup_sandbox_infra(
                    cloud_provider_resource, cleanup_action)

                self._log(logger, 'CleanupSandboxInfra_action_result',
                          action_result)

                return DriverResponse([action_result
                                       ]).to_driver_response_json()
Beispiel #6
0
    def Deploy(self, context, request=None, cancellation_context=None):
        actions = self.request_parser.convert_driver_request_to_actions(request)
        deploy_action = single(actions, lambda x: isinstance(x, DeployApp))
        deployment_name = deploy_action.actionParams.deployment.deploymentPath

        if deployment_name in self.deployments.keys():
            deploy_method = self.deployments[deployment_name]
            result = deploy_method(context, deploy_action, cancellation_context)
            result.actionId = deploy_action.actionId
            return DriverResponse([result]).to_driver_response_json()
        else:
            raise Exception('Could not find the deployment')
Beispiel #7
0
    def Deploy(self, context, request, cancellation_context=None):
        """
       Deploy
       :param ResourceCommandContext context:
       :param str request: A JSON string with the list of requested deployment actions
       :param CancellationContext cancellation_context:
       :return:
       :rtype: str
       """
        with LoggingSessionContext(context) as logger, ErrorHandlingContext(
                logger):
            with CloudShellSessionContext(context) as cloudshell_session:
                self._log(logger, 'deploy_request', request)
                self._log(logger, 'deploy_context', context)

                # parse the json strings into action objects
                cloud_provider_resource = L3HeavenlyCloudShell.create_from_context(
                    context)
                actions = self.request_parser.convert_driver_request_to_actions(
                    request)

                # extract DeployApp action
                deploy_action = single(actions,
                                       lambda x: isinstance(x, DeployApp))

                # extract ConnectToSubnetActions
                connect_subnet_actions = list(
                    filter(lambda x: isinstance(x, ConnectSubnet), actions))

                # if we have multiple supported deployment options use the 'deploymentPath' property
                # to decide which deployment option to use.
                deployment_name = deploy_action.actionParams.deployment.deploymentPath

                if deployment_name == 'L3HeavenlyCloudShell.HeavenlyCloudAngelDeployment':
                    logger.info('calling deploy_angel')
                    deploy_results = HeavenlyCloudServiceWrapper.deploy_angel(
                        context, cloudshell_session, cloud_provider_resource,
                        deploy_action, connect_subnet_actions,
                        cancellation_context)
                elif deployment_name == 'L3HeavenlyCloudShell.HeavenlyCloudManDeployment':
                    deploy_results = HeavenlyCloudServiceWrapper.deploy_man(
                        context, cloudshell_session, cloud_provider_resource,
                        deploy_action, connect_subnet_actions,
                        cancellation_context)
                else:
                    raise ValueError(deployment_name +
                                     ' deployment option is not supported.')

                self._log(logger, 'deployment_name', deployment_name)
                self._log(logger, 'deploy_results', deploy_results)

                return DriverResponse(deploy_results).to_driver_response_json()
    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()
Beispiel #9
0
    def Deploy(self, context, request=None, cancellation_context=None):
        """  """

        actions = self.request_parser.convert_driver_request_to_actions(
            request)
        resource_config = ShellResource.create_from_context(context)
        # resource_config.api.WriteMessageToReservationOutput(context.reservation.reservation_id,
        #                                                     'Request JSON: ' + request)
        with LoggingSessionContext(context) as logger:

            deploy_action = None
            subnet_actions = list()
            for action in actions:
                if isinstance(action, DeployApp):
                    deploy_action = action
                if isinstance(action, ConnectSubnet):
                    subnet_actions.append(action)

            if deploy_action:

                deployment_name = deploy_action.actionParams.deployment.deploymentPath
                try:
                    deploy_method = next(
                        self.deployments[deployment]
                        for deployment in self.deployments.keys()
                        if deployment_name.endswith(deployment))
                except StopIteration:
                    raise VIRLShellError("Could not find the deployment " +
                                         deployment_name)
                results = deploy_method(resource_config, logger, deploy_action,
                                        subnet_actions, cancellation_context)
                logger.info("Deploy result {}".format(
                    DriverResponse(results).to_driver_response_json()))
                return DriverResponse(results).to_driver_response_json()
            else:
                raise VIRLShellError("Failed to deploy VM")
    def cleanup(self, request):
        """

        :param request:
        :return:
        """
        # self._delete_subnet(name=self.DEFAULT_SUBNET_NAME)
        # self._delete_fabric(name=self.DEFAULT_FABRIC_NAME)

        actions = self._request_parser.convert_driver_request_to_actions(request)
        cleanup_action = single(actions, lambda x: isinstance(x, CleanupNetwork))

        action_result = CleanupNetworkResult(cleanup_action.actionId)

        return DriverResponse([action_result]).to_driver_response_json()
Beispiel #11
0
    def PrepareSandboxInfra(self, context, request, cancellation_context):
        """
        :param ResourceCommandContext context:
        :param str request:
        :param CancellationContext cancellation_context:
        :return:
        :rtype: DriverResponse
        """
        with LoggingSessionContext(context) as logger, ErrorHandlingContext(
                logger):
            with CloudShellSessionContext(context) as cloudshell_session:
                self._log(logger, 'PrepareSandboxInfra_request', request)
                self._log(logger, 'PrepareSandboxInfra_context', context)

                cloud_provider_resource = L3HeavenlyCloudShell.create_from_context(
                    context)

                # parse the json strings into action objects
                actions = self.request_parser.convert_driver_request_to_actions(
                    request)

                # extract PrepareCloudInfra action
                prepare_infa_action = single(
                    actions, lambda x: isinstance(x, PrepareCloudInfra))

                # extract CreateKeys action
                create_keys_action = single(
                    actions, lambda x: isinstance(x, CreateKeys))

                # extract PrepareSubnet actions
                prepare_subnet_actions = list(
                    filter(lambda x: isinstance(x, PrepareSubnet), actions))

                action_results = HeavenlyCloudServiceWrapper.prepare_sandbox_infra(
                    logger, cloud_provider_resource, prepare_infa_action,
                    create_keys_action, prepare_subnet_actions,
                    cancellation_context)

                self._log(logger, 'PrepareSandboxInfra_action_results',
                          action_results)

                return DriverResponse(action_results).to_driver_response_json()
Beispiel #12
0
    def Deploy(self, context, request=None, cancellation_context=None):
        """
       Deploy
       :param ResourceCommandContext context:
       :param str request: A JSON string with the list of requested deployment actions
       :param CancellationContext cancellation_context:
       :return:
       :rtype: str
       """
        with LoggingSessionContext(context) as logger:
            with ErrorHandlingContext(logger):
                self._log_value(logger, 'deploy_request', request)
                self._log_value(logger, 'deploy_context', context)

                # parse the json strings into action objects
                cloud_provider_resource = HeavenlyCloudsShell.create_from_context(
                    context)
                actions = self.request_parser.convert_driver_request_to_actions(
                    request)

                # extract DeployApp action
                deploy_action = single(actions,
                                       lambda x: isinstance(x, DeployApp))

                # if we have multiple supported deployment options use the 'deploymentPath' property
                # to decide which deployment option to use.
                deployment_name = deploy_action.actionParams.deployment.deploymentPath

                self._log_value(logger, 'deployment_name', deployment_name)
                _my_deploy_method = self.deployments[deployment_name]
                deploy_result = _my_deploy_method(cloud_provider_resource,
                                                  deploy_action,
                                                  cancellation_context, logger)

                self._log_value(logger, 'deploy_result', deploy_result)

                return DriverResponse([deploy_result
                                       ]).to_driver_response_json()
Beispiel #13
0
    def Deploy(self, context, request=None, cancellation_context=None):
        """
        Deploy
        :param ResourceCommandContext context:
        :param str request: A JSON string with the list of requested deployment actions
        :param CancellationContext cancellation_context:
        :return:
        :rtype: str
        """

        with LoggingSessionContext(context) as logger, ErrorHandlingContext(logger):
            with CloudShellSessionContext(context) as cloudshell_session:
                self._log(logger, 'deploy_request', request)
                self._log(logger, 'deploy_context', context)

                cloud_provider_resource = Nutanixshell.create_from_context(context)

                decrypted_pass = cloudshell_session.DecryptPassword(cloud_provider_resource.password).Value

                nutanix_service = NutanixService(context.resource.address, cloud_provider_resource.user, decrypted_pass)

                # parse the json strings into action objects
                actions = self.request_parser.convert_driver_request_to_actions(request)

                # extract DeployApp action
                deploy_action = single(actions, lambda x: isinstance(x, DeployApp))

                # if we have multiple supported deployment options use the 'deploymentPath' property
                # to decide which deployment option to use.
                # deployment_name = deploy_action.actionParams.deployment.deploymentPath

                deploy_result = nutanix_service.clone_vm(deploy_action, cloud_provider_resource.storage_container_name)

                self._log(logger, 'deploy_result', deploy_result)

                return DriverResponse([deploy_result]).to_driver_response_json()
Beispiel #14
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
Beispiel #15
0
 def PrepareSandboxInfra(self, context, request, cancellation_context):
     actions = self.request_parser.convert_driver_request_to_actions(request)
     results = self.azure_shell.prepare_connectivity(context, actions, cancellation_context)
     return DriverResponse(results).to_driver_response_json()
Beispiel #16
0
    def Deploy(self, context, request=None, cancellation_context=None):
        """

        :param ResourceCommandContext context:
        :param str request: json string to be parsed
        :param cancellation_context:
        :return:
        """

        RESOURCE_POOL_ATTR = "App Pool Name"
        CP_RESTRICTED_ATTR = "Restricted App Model Pools"

        api = CloudShellSessionContext(context).get_api()
        res_id = context.reservation.reservation_id

        # VALIDATE THAT CLOUD PROVIDER RESOURCE HAS POOL LIST Attribute
        cp_attrs = context.resource.attributes
        try:
            cp_pool_list_val = cp_attrs[CP_RESTRICTED_ATTR]
        except KeyError:
            pass
        else:
            api.WriteMessageToReservationOutput(res_id,
                                                "=== full request json ===")
            api.WriteMessageToReservationOutput(res_id, request)
            request_obj = json.loads(request)
            request_action_params = request_obj["driverRequest"]["actions"][0][
                "actionParams"]
            app_name = request_action_params["appName"]
            deployment = request_action_params["deployment"]
            app_resource = request_action_params["appResource"]
            app_resource_attrs = app_resource["attributes"]

            pool_attr_search = [
                attr for attr in app_resource_attrs
                if attr["attributeName"] == RESOURCE_POOL_ATTR
            ]
            if pool_attr_search:
                app_pool_attr_val = pool_attr_search[0]["attributeValue"]
                restricted_attrs_dict = get_cp_restricted_attrs_dict(
                    cp_pool_list_val)
                try:
                    app_pool_limit = restricted_attrs_dict[app_pool_attr_val]
                except KeyError:
                    not_found_msg = "{} pool name key not in cp restricted list {}".format(
                        app_pool_attr_val, restricted_attrs_dict)
                    api.WriteMessageToReservationOutput(res_id, not_found_msg)
                else:
                    # count deployed apps
                    all_generic_app_resources = api.FindResources(
                        resourceFamily="Generic App Family").Resources

                    # collect matching apps
                    matching_apps = []
                    for resource in all_generic_app_resources:
                        attrs = api.GetResourceDetails(
                            resource.Name).ResourceAttributes
                        attr_search = [
                            attr for attr in attrs
                            if attr.Name == RESOURCE_POOL_ATTR
                        ]
                        if attr_search:
                            attr_val = attr_search[0].Value
                            if attr_val == app_pool_attr_val:
                                matching_apps.append(resource)

                    # PERFORM VALIDATION
                    if len(matching_apps) >= int(app_pool_limit):
                        matching_app_names = [r.Name for r in matching_apps]
                        exc_msg = "Can not deploy '{}'. The pool '{}' has reached it's limit of {}. Current Apps in Pool: {}".format(
                            app_name, app_pool_attr_val, app_pool_limit,
                            matching_app_names)
                        api.WriteMessageToReservationOutput(
                            res_id, '<span style="color:red">{}</span>'.format(
                                exc_msg))
                        raise AppLimitDeploymentError(exc_msg)

        actions = self.request_parser.convert_driver_request_to_actions(
            request)
        deploy_action = single(actions, lambda x: isinstance(x, DeployApp))
        deployment_name = deploy_action.actionParams.deployment.deploymentPath

        if deployment_name in self.deployments.keys():
            deploy_method = self.deployments[deployment_name]
            deploy_result = deploy_method(context, deploy_action,
                                          cancellation_context)
            return DriverResponse([deploy_result]).to_driver_response_json()
        else:
            raise Exception('Could not find the deployment')
Beispiel #17
0
    def Deploy(self, context, request, cancellation_context=None):
        """
        Called when reserving a sandbox during setup, a call for each app in the sandbox.

        Method creates the compute resource in the cloud provider - VM instance or container.

        If App deployment fails, return a "success false" action result.

        :param ResourceCommandContext context:
        :param str request: A JSON string with the list of requested deployment actions
        :param CancellationContext cancellation_context:
        :return:
        :rtype: str
        """
        '''
        # parse the json strings into action objects
        actions = self.request_parser.convert_driver_request_to_actions(request)
        
        # extract DeployApp action
        deploy_action = single(actions, lambda x: isinstance(x, DeployApp))
        
        # if we have multiple supported deployment options use the 'deploymentPath' property 
        # to decide which deployment option to use. 
        deployment_name = deploy_action.actionParams.deployment.deploymentPath
                
        deploy_result = _my_deploy_method(context, actions, cancellation_context)
        return DriverResponse(deploy_result).to_driver_response_json()
        '''
        with LoggingSessionContext(context) as logger:
            logger.info(request)
            api = CloudShellSessionContext(context).get_api()
            resource_config = JuniperCPResourceConfig.from_context(
                self.SHELL_NAME, context, api, self.SUPPORTED_OS)
            cli_configurator = JuniperCliConfigurator(CLI(self._session_pool),
                                                      resource_config, logger)

            ls_flow = CreateRemoveLSFlow(cli_configurator, logger)

            actions = DriverRequestParser().convert_driver_request_to_actions(
                request)
            reservation_details = api.GetReservationDetails(
                context.reservation.reservation_id,
                disableCache=True).ReservationDescription

            results = []
            for deploy_action in actions:
                app_name = deploy_action.actionParams.appName
                int_list = self._get_int_names(reservation_details, app_name)
                logger.info("{}:{}".format(app_name, str(int_list)))
                if not int_list:
                    raise Exception(
                        "Failed to deploy Logical System without interfaces. "
                        "Please create appropriate connections")
                vm_uuid = self._build_uuid(app_name,
                                           context.reservation.reservation_id)
                ls_name = "VR-{}".format(vm_uuid)
                vm_name = "{}-{}".format(app_name, ls_name)
                int_list = ls_flow.create_ls(ls_name, int_list)
                vm_instance_data = [
                    VmDetailsProperty(self.ATTRIBUTE.INST_UUID, vm_uuid),
                    VmDetailsProperty(self.ATTRIBUTE.LS_NAME, ls_name),
                ]
                vm_interfaces_data = [
                    VmDetailsProperty("vNIC {} Name".format(i), int_list[i])
                    for i in range(len(int_list))
                ]
                vm_instance_data.extend(vm_interfaces_data)

                deploy_result = DeployAppResult(
                    actionId=deploy_action.actionId,
                    infoMessage="Deployment Completed Successfully",
                    vmUuid=vm_uuid,
                    vmName=vm_name,
                    deployedAppAddress="",
                    deployedAppAttributes=[],
                    vmDetailsData=VmDetailsData(vm_instance_data))

                results.append(deploy_result)
            return DriverResponse(results).to_driver_response_json()
Beispiel #18
0
 def RemoveTrafficMirroring(self, context, request):
     action_results = self.aws_shell.remove_traffic_mirroring(
         context, request)
     return DriverResponse(action_results).to_driver_response_json()
    def Deploy(self, context, request=None, cancellation_context=None):
        self.logger.info('inside Deploy')
        """
        Deploy
        :param ResourceCommandContext context:
        :param str request: A JSON string with the list of requested deployment actions
        :param CancellationContext cancellation_context:
        :return:
        :rtype: str
        """
        '''
        # parse the json strings into action objects
        actions = self.request_parser.convert_driver_request_to_actions(request)
        
        # extract DeployApp action
        deploy_action = single(actions, lambda x: isinstance(x, DeployApp))
        
        # if we have multiple supported deployment options use the 'deploymentPath' property 
        # to decide which deployment option to use. 
        deployment_name = deploy_action.actionParams.deployment.deploymentPath
        
        deploy_result = _my_deploy_method(context, actions, cancellation_context)
        return DriverResponse(deploy_result).to_driver_response_json()
        '''

        self.logger.info('got into deploy')

        json_req = json.dumps(request,
                              default=lambda o: o.__dict__,
                              sort_keys=True,
                              indent=4)

        self.logger.info(json_req)
        actions = self.request_parser.convert_driver_request_to_actions(
            request)
        self.logger.info('connecting')

        cloud = self._connect_to_cloud(context)

        self.logger.info('deploying')
        self.logger.info('deployed')

        deploy_action = single(actions, lambda x: isinstance(x, DeployApp))
        self.logger.info('deploy action JSON')

        #delete me
        if (isinstance(deploy_action, DeployApp)):
            pass

        deployment_name = deploy_action.actionParams.deployment.deploymentPath

        raw_result = self.deploy_hwc_from_image(context, deploy_action,
                                                cancellation_context, cloud)
        #delete me
        if (isinstance(raw_result, Server)):
            pass
        deploy_result = DeployAppResult(
            vmName=raw_result.name,
            actionId=deploy_action.actionId,
            vmUuid='',
            success=True,
            deployedAppAddress=raw_result.addresses.get(
                raw_result.addresses.keys()[0])[0].get('addr'),
            deployedAppAttributes=[],
            vmDetailsData=None
            #vmDetailsData=VmDetailsCreator.extract_vm_details(raw_result)
        )

        # handle if Elastic IP is needed
        if deploy_action.actionParams.deployment.attributes.get(
                'Huaweicloud.HWC_deploy_from_image.EIP') == 'True':
            new_ip = cloud.createEIP(cloud.get_vm_port_id(raw_result))

        my_response = DriverResponse([deploy_result]).to_driver_response_json()
        self.logger.info('my response is : {0}'.format(my_response))
        return my_response