Beispiel #1
0
    def run_custom_config_command(self, context, ports, custom_command):
        """Send custom command in configuration mode

        :param ResourceCommandContext context: ResourceCommandContext object with all Resource Attributes inside
        :return: result
        :rtype: str
        """
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()

            resource_config = JuniperCPResourceConfig.from_context(
                self.SHELL_NAME, context, api, self.SUPPORTED_OS)

            response = ""
            for endpoint in context.remote_endpoints:
                res_details = api.GetResourceDetails(endpoint.name)
                ls_name = self._extract_attribute(
                    res_details.VmDetails.InstanceData, self.ATTRIBUTE.LS_NAME)
                ls_cli_configurator = LSConfigurator(ls_name,
                                                     self._session_pool,
                                                     resource_config, logger)

                send_command_operations = RunCommandFlow(
                    logger, ls_cli_configurator)
                response += send_command_operations.run_custom_config_command(
                    custom_command)
            return response
Beispiel #2
0
    def DeleteInstance(self, context, ports):
        """
        Called during sandbox's teardown or when removing a deployed App from the sandbox

        Method deletes the VM from the cloud provider.

        If the operation fails, method should raise an exception.

        :param ResourceRemoteCommandContext context:
        :param ports:
        """
        with LoggingSessionContext(context) as logger:
            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)

            for endpoint in context.remote_endpoints:
                res_details = api.GetResourceDetails(endpoint.name)
                ls_name = self._extract_attribute(
                    res_details.VmDetails.InstanceData, self.ATTRIBUTE.LS_NAME)
                ls_flow.remove_ls(ls_name)
    def load_config(self, context, ixc_config):
        """ Load IxChariot configuration and select end points.

        :type context: cloudshell.shell.core.driver_context.ResourceRemoteCommandContext
        :param ixc_config: IxChariot configuration name.
        """

        session_id = self.handler.load_config(context, ixc_config)
        my_api = CloudShellSessionContext(context).get_api()
        my_api.WriteMessageToReservationOutput(
            context.reservation.reservation_id,
            ixc_config + ' loaded, endpoints reserved')
        return session_id
    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 object with the list of requested connectivity changes
        :return: a json object with the list of connectivity changes which were carried out by the switch
        :rtype: str
        """
        # res_id = context.reservation.reservation_id
        # api = CloudShellSessionContext(context).get_api()
        # api.WriteMessageToReservationOutput(res_id, "=== connectivity request ===")
        # api.WriteMessageToReservationOutput(res_id, request)
        # # response = apply_connectivity_changes(request=request,
        # #                                       add_vlan_action=lambda action: ConnectivitySuccessResponse(action, 'Success'),
        # #                                       remove_vlan_action=lambda action: ConnectivitySuccessResponse(action, 'Success'))
        # response = apply_connectivity_changes(request=request,
        #                                       add_vlan_action=my_add_vlan_action),
        #                                       remove_vlan_action=lambda action: ConnectivitySuccessResponse(action,
        #                                                                                                     'Success'))
        # api.WriteMessageToReservationOutput(res_id, "=== connectivity response ===")
        # # response.driverResponse.actionResults
        # api.WriteMessageToReservationOutput(res_id, response)
        # return response

        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()
            res_id = context.reservation.reservation_id
            api.WriteMessageToReservationOutput(
                res_id, "=== connectivity request ===")
            api.WriteMessageToReservationOutput(res_id, request)
            resource_config = NetworkingResourceConfig.from_context(
                self.SHELL_NAME,
                context,
                api,
                self.SUPPORTED_OS,
            )
            resource_config = NetworkingSwitchDemo.create_from_context(context)
            cli_configurator = JuniperCliConfigurator(self._cli,
                                                      resource_config, logger)
            connectivity_flow = MyConnectivityFlow(cli_configurator, logger)
            logger.info(
                'Start applying connectivity changes, request is: {0}'.format(
                    str(request)))
            result = connectivity_flow.apply_connectivity_changes(
                request=request)
            logger.info(
                'Finished applying connectivity changes, response is: {0}'.
                format(str(result)))
            logger.info('Apply Connectivity changes completed')
            return result
    def hello_world(self, context):
        """
        :param ResourceCommandContext context:
        :return:
        """
        api = CloudShellSessionContext(context).get_api()
        res_id = context.reservation.reservation_id

        name = context.resource.name
        ip = context.resource.address

        api.WriteMessageToReservationOutput(
            res_id, "resource name: {}, ip: {}".format(name, ip))

        pass
Beispiel #6
0
    def set_port_attribute(self, context, port_name):
        """

        :param context:
        :param port_name: String example :'TestCenter Chassis 222/Module9/Port Group3/Port3':'TCP'
        :return:
        """
        splited_name = port_name.split(":")
        port_full_name = splited_name[0]
        port_logic_name = splited_name[1]

        my_api = CloudShellSessionContext(context).get_api()
        return my_api.SetAttributeValue(resourceFullPath=port_full_name,
                                        attributeName="Logical Name",
                                        attributeValue=port_logic_name)
    def PrepareSandboxInfra(self, context, request, cancellation_context):
        """
        Called in the beginning of the orchestration flow (preparation stage), even before Deploy is called.

        Prepares all of the required infrastructure needed for a sandbox operating with L3 connectivity.
        For example, creating networking infrastructure like VPC, subnets or routing tables in AWS, storage entities such as S3 buckets, or
        keyPair objects for authentication.
        In general, any other entities needed on the sandbox level should be created here.

        Note:
        PrepareSandboxInfra can be called multiple times in a sandbox.
        Setup can be called multiple times in the sandbox, and every time setup is called, the PrepareSandboxInfra method will be called again.
        Implementation should support this use case and take under consideration that the cloud resource might already exist.
        It's recommended to follow the "get or create" pattern when implementing this method.

        When an error is raised or method returns action result with success false
        Cloudshell will fail sandbox creation, so bear that in mind when doing so.

        :param ResourceCommandContext context:
        :param str request:
        :param CancellationContext cancellation_context:
        :return:
        :rtype: str
        """
        with LoggingSessionContext(context) as logger:
            logger.info("Starting Prepare Sandbox Infra command...")
            api = CloudShellSessionContext(context).get_api()
            resource_config = MaasResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api)

            prepare_sandbox_flow = MaasPrepareSandboxInfraFlow(
                resource_config=resource_config, logger=logger)
            return prepare_sandbox_flow.prepare(request=request)
Beispiel #8
0
 def PowerOff(self, context, ports):
     # doesn't do anything now
     # just change icon on resource
     with CloudShellSessionContext(context) as cloudshell_session:
         cloudshell_session.SetResourceLiveStatus(
             context.remote_endpoints[0].fullname, "Offline", "Powered Off")
     pass
Beispiel #9
0
    def test_cloudshell_session_context_proper_initialized_using_https(self):

        # Arrange
        context = mock.create_autospec(ResourceCommandContext)
        context.connectivity = mock.create_autospec(ConnectivityContext)
        context.connectivity.server_address = 'localhost'
        context.connectivity.admin_auth_token = '123456789'
        context.connectivity.cloudshell_api_scheme = 'https'
        context.resource = mock.create_autospec(ResourceContextDetails)
        context.resource.name = 'my_device'
        context.reservation = mock.create_autospec(ReservationContextDetails)
        context.reservation.domain = 'my_space'

        with mock.patch('cloudshell.shell.core.session.cloudshell_session.CloudShellAPISession') as cloudshell_api_session:
            expected_cloudshell_session = Mock()
            cloudshell_api_session.return_value = expected_cloudshell_session

            # Act
            with CloudShellSessionContext(context) as cloudshell_session:

                # Assert
                cloudshell_api_session.assert_called_with(domain='my_space',
                                                          host='localhost',
                                                          password=None,
                                                          token_id='123456789',
                                                          cloudshell_api_scheme='https',
                                                          username=None)
                self.assertEqual(cloudshell_session, expected_cloudshell_session)
    def get_inventory(self, context):
        """Called when the cloud provider resource is created in the inventory.

        Method validates the values of the cloud provider attributes, entered by the user as part of the cloud provider
        resource creation. In addition, this would be the place to assign values programmatically to optional attributes
        that were not given a value by the user. If one of the validations failed, the method should raise an exception
        :param AutoLoadCommandContext context: the context the command runs on
        :return Attribute and sub-resource information for the Shell resource you can return an AutoLoadDetails object
        :rtype: AutoLoadDetails
        """
        with LoggingSessionContext(context) as logger:
            logger.info("Starting Autoload command...")
            api = CloudShellSessionContext(context).get_api()
            resource_config = VCenterResourceConfig.from_context(
                context=context, api=api)

            vcenter_client = VCenterAPIClient(
                host=resource_config.address,
                user=resource_config.user,
                password=resource_config.password,
                logger=logger)

            autoload_flow = VCenterAutoloadFlow(
                resource_config=resource_config,
                vcenter_client=vcenter_client,
                logger=logger)

            return autoload_flow.discover()
    def get_inventory(self,
                      context: AutoLoadCommandContext) -> AutoLoadDetails:
        """Return device structure with all standard attributes.

        :param context: an object with all Resource Attributes inside
        :return: response
        """
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()

            resource_config = FirewallResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )
            cli_handler = self._cli.get_cli_handler(resource_config, logger)
            snmp_handler = SNMPHandler(resource_config, logger, cli_handler)

            autoload_operations = AutoloadFlow(logger=logger,
                                               snmp_handler=snmp_handler)
            logger.info("Autoload started")
            resource_model = FirewallResourceModel(
                resource_config.name,
                resource_config.shell_name,
                resource_config.family_name,
            )

            response = autoload_operations.discover(
                resource_config.supported_os, resource_model)
            logger.info("Autoload completed")
            return response
    def shutdown(self, context: ResourceCommandContext):
        """Shutdown device.

        :param context: an object with all Resource Attributes inside
        :return:
        """
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()

            resource_config = FirewallResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            cli_handler = self._cli.get_cli_handler(resource_config, logger)
            state_operations = StateFlow(
                logger=logger,
                api=api,
                resource_config=resource_config,
                cli_configurator=cli_handler,
            )

            return state_operations.shutdown()
Beispiel #13
0
    def orchestration_save(
        self, context: ResourceCommandContext, mode: str, custom_params: str
    ) -> str:
        with LoggingSessionContext(context) as logger:
            logger.info("Starting 'Orchestration Save' command ...")
            api = CloudShellSessionContext(context).get_api()

            resource_config = NetworkingResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            mode = mode or "shallow"

            cli_handler = self._cli.get_cli_handler(resource_config, logger)
            configuration_flow = CiscoNXOSConfigurationFlow(
                cli_handler=cli_handler, logger=logger, resource_config=resource_config
            )

            response = configuration_flow.orchestration_save(
                mode=mode, custom_params=custom_params
            )

            response_json = OrchestrationSaveRestore(
                logger, resource_config.name
            ).prepare_orchestration_save_result(response)

            logger.info("'Orchestration Save' command completed")
            return response_json
Beispiel #14
0
    def ApplyConnectivityChanges(
        self, context: ResourceCommandContext, request: str
    ) -> str:
        """Create VLAN and add/remove it to/from network interface."""
        with LoggingSessionContext(context) as logger:
            logger.info("Starting 'Apply Connectivity Changes' command ...")
            logger.info(f"Request: {request}")

            api = CloudShellSessionContext(context).get_api()

            resource_config = NetworkingResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            cli_handler = self._cli.get_cli_handler(resource_config, logger)
            connectivity_operations = CiscoNXOSConnectivityFlow(
                logger=logger, cli_handler=cli_handler
            )
            result = connectivity_operations.apply_connectivity_changes(request=request)

            logger.info(
                f"'Apply Connectivity Changes' command completed with result '{result}'"
            )
            return result
Beispiel #15
0
    def load_config(self, context, stc_config_file_name):
        """
        :param stc_config_file_name: full path to STC configuration file (tcc or xml)
        """

        self.stc.load_config(stc_config_file_name)
        config_ports = self.stc.project.get_ports()

        reservation_id = context.reservation.reservation_id
        my_api = CloudShellSessionContext(context).get_api()

        reservation_ports = {}
        for port in get_reservation_resources(
                my_api, reservation_id, 'Generic Traffic Generator Port',
                'PerfectStorm Chassis Shell 2G.GenericTrafficGeneratorPort',
                'STC Chassis Shell 2G.GenericTrafficGeneratorPort'):
            reservation_ports[get_family_attribute(
                my_api, port, 'Logical Name').Value.strip()] = port

        for name, port in config_ports.items():
            if name in reservation_ports:
                address = get_address(reservation_ports[name])
                self.logger.debug(
                    'Logical Port {} will be reserved on Physical location {}'.
                    format(name, address))
                port.reserve(address, force=True, wait_for_up=False)
            else:
                self.logger.error(
                    'Configuration port "{}" not found in reservation ports {}'
                    .format(port, reservation_ports.keys()))
                raise Exception(
                    'Configuration port "{}" not found in reservation ports {}'
                    .format(port, reservation_ports.keys()))

        self.logger.info("Port Reservation Completed")
    def run_custom_config_command(self, context: ResourceCommandContext,
                                  custom_command: str) -> str:
        """Send custom command in configuration mode.

        :param custom_command: Command user wants to send to the device
        :param context: an object with all Resource Attributes inside
        :return: result
        """
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()

            resource_config = FirewallResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            cli_handler = self._cli.get_cli_handler(resource_config, logger)
            send_command_operations = CommandFlow(logger=logger,
                                                  cli_configurator=cli_handler)

            result_str = send_command_operations.run_custom_config_command(
                custom_command=custom_command)

            return result_str
    def load_firmware(self, context: ResourceCommandContext, path: str,
                      vrf_management_name: str):
        """Upload and updates firmware on the resource.

        :param context: an object with all Resource Attributes inside
        :param path: full path to firmware file, i.e. tftp://10.10.10.1/firmware.tar
        :param vrf_management_name: VRF management Name
        """
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()

            resource_config = FirewallResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            if not vrf_management_name:
                vrf_management_name = resource_config.vrf_management_name

            cli_handler = self._cli.get_cli_handler(resource_config, logger)

            logger.info("Start Load Firmware")
            firmware_operations = FirmwareFlow(cli_handler=cli_handler,
                                               logger=logger)
            response = firmware_operations.load_firmware(
                path=path, vrf_management_name=vrf_management_name)
            logger.info("Finish Load Firmware: {}".format(response))
Beispiel #18
0
    def orchestration_restore(
        self,
        context: ResourceCommandContext,
        saved_artifact_info: str,
        custom_params: str,
    ):
        with LoggingSessionContext(context) as logger:
            logger.info("Starting 'Orchestration Restore' command ...")
            api = CloudShellSessionContext(context).get_api()

            resource_config = NetworkingResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            cli_handler = self._cli.get_cli_handler(resource_config, logger)
            configuration_flow = CiscoNXOSConfigurationFlow(
                cli_handler=cli_handler, logger=logger, resource_config=resource_config
            )

            restore_params = OrchestrationSaveRestore(
                logger, resource_config.name
            ).parse_orchestration_save_result(saved_artifact_info)

            configuration_flow.restore(**restore_params)
            logger.info("'Orchestration Restore' command completed")
    def orchestration_restore(
        self,
        context: ResourceCommandContext,
        saved_artifact_info: str,
        custom_params: str,
    ):
        """Restore selected file to the provided destination.

        :param context: an object with all Resource Attributes inside
        :param saved_artifact_info: OrchestrationSavedArtifactInfo json
        :param custom_params: json with custom restore parameters
        """
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()

            resource_config = FirewallResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            cli_handler = self._cli.get_cli_handler(resource_config, logger)
            configuration_flow = ConfigurationFlow(
                cli_handler=cli_handler,
                logger=logger,
                resource_config=resource_config)

            logger.info("Orchestration restore started")
            restore_params = OrchestrationSaveRestore(
                logger, resource_config.name).parse_orchestration_save_result(
                    saved_artifact_info)
            configuration_flow.restore(**restore_params)
            logger.info("Orchestration restore completed")
Beispiel #20
0
    def load_firmware(
        self, context: ResourceCommandContext, path: str, vrf_management_name: str
    ):
        """Upload and updates firmware on the resource."""
        with LoggingSessionContext(context) as logger:
            logger.info("Starting 'Load Firmware' command ...")
            api = CloudShellSessionContext(context).get_api()

            resource_config = NetworkingResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            vrf_management_name = (
                vrf_management_name or resource_config.vrf_management_name
            )
            cli_handler = self._cli.get_cli_handler(resource_config, logger)

            firmware_operations = CiscoLoadFirmwareFlow(
                cli_handler=cli_handler, logger=logger
            )
            firmware_operations.load_firmware(
                path=path, vrf_management_name=vrf_management_name
            )
            logger.info("'Load Firmware' command completed")
    def execute_playbook(self, command_context, ansi_conf_json,
                         cancellation_context):
        """
        :type command_context: ResourceCommandContext
        :type ansi_conf_json: str
        :type cancellation_context: CancellationContext
        :rtype str
        """
        with LoggingSessionContext(command_context) as logger:
            logger.debug(
                '\'execute_playbook\' is called with the configuration json: \n'
                + ansi_conf_json)

            with ErrorHandlingContext(logger):
                with CloudShellSessionContext(command_context) as api:
                    ansi_conf = AnsibleConfigurationParser(api).json_to_object(
                        ansi_conf_json)
                    output_writer = ReservationOutputWriter(
                        api, command_context)
                    cancellation_sampler = CancellationSampler(
                        cancellation_context)

                    with TempFolderScope(self.file_system, logger):
                        self._add_ansible_config_file(logger)
                        self._add_host_vars_files(ansi_conf, logger)
                        self._wait_for_all_hosts_to_be_deployed(
                            ansi_conf, logger, output_writer)
                        self._add_inventory_file(ansi_conf, logger)
                        playbook_name = self._download_playbook(
                            ansi_conf, cancellation_sampler, logger)
                        self._run_playbook(ansi_conf, playbook_name,
                                           output_writer, cancellation_sampler,
                                           logger)
Beispiel #22
0
    def health_check(self, context: ResourceCommandContext) -> str:
        """Performs device health check."""
        with LoggingSessionContext(context) as logger:
            logger.info("Starting 'Health Check' command ...")

            api = CloudShellSessionContext(context).get_api()

            resource_config = NetworkingResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            cli_handler = self._cli.get_cli_handler(resource_config, logger)

            state_operations = CiscoStateFlow(
                logger=logger,
                api=api,
                resource_config=resource_config,
                cli_configurator=cli_handler,
            )

            result = state_operations.health_check()
            logger.info(f"'Health Check' command completed with result '{result}'")

            return result
Beispiel #23
0
    def GetVmDetails(self, context, requests, cancellation_context):
        """

        :param ResourceCommandContext context:
        :param str requests:
        :param CancellationContext cancellation_context:
        :return:
        """

        with LoggingSessionContext(context) as logger, ErrorHandlingContext(logger):
            with CloudShellSessionContext(context) as cloudshell_session:
                self._log(logger, 'GetVmDetails_context', context)
                self._log(logger, 'GetVmDetails_requests', requests)
                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)

                results = []

                requests_loaded = json.loads(requests)

                for request in requests_loaded[u'items']:
                    vm_name = request[u'deployedAppJson'][u'name']
                    vm_uid = request[u'deployedAppJson'][u'vmdetails'][u'uid']

                    result = nutanix_service.get_vm_details(vm_name, vm_uid)
                    results.append(result)

                result_json = json.dumps(results, default=lambda o: o.__dict__, sort_keys=True, separators=(',', ':'))

                self._log(logger, 'GetVmDetails_result', result_json)

                return result_json
Beispiel #24
0
    def get_inventory(self, context: AutoLoadCommandContext) -> AutoLoadDetails:
        """Return device structure with all standard attributes."""
        with LoggingSessionContext(context) as logger:
            logger.info("Starting 'Autoload' command ...")
            api = CloudShellSessionContext(context).get_api()
            resource_config = NetworkingResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )
            cli_handler = self._cli.get_cli_handler(resource_config, logger)
            snmp_handler = CiscoSnmpHandler(resource_config, logger, cli_handler)
            autoload_operations = CiscoSnmpAutoloadFlow(
                logger=logger, snmp_handler=snmp_handler
            )

            resource_model = NetworkingResourceModel(
                resource_config.name,
                resource_config.shell_name,
                resource_config.family_name,
            )

            response = autoload_operations.discover(
                resource_config.supported_os, resource_model
            )
            logger.info("'Autoload' command completed")

            return response
Beispiel #25
0
    def test_cloudshell_session_global_domain_used_when_outside_of_reservation(self):

        # Arrange
        context = mock.create_autospec(ResourceCommandContext)
        context.connectivity = mock.create_autospec(ConnectivityContext)
        context.connectivity.server_address = 'localhost'
        context.connectivity.admin_auth_token = '123456789'
        context.resource = mock.create_autospec(ResourceContextDetails)
        context.resource.name = 'my_device'
        context.reservation = None

        with mock.patch('cloudshell.shell.core.session.cloudshell_session.CloudShellAPISession') as cloudshell_api_session:
            expected_cloudshell_session = MagicMock()
            cloudshell_api_session.return_value = expected_cloudshell_session

            # Act
            with CloudShellSessionContext(context) as cloudshell_session:

                # Assert
                cloudshell_api_session.assert_called_with(domain='Global',
                                                          host='localhost',
                                                          password=None,
                                                          token_id='123456789',
                                                          username=None)

                self.assertEqual(cloudshell_session, expected_cloudshell_session)
Beispiel #26
0
    def run_custom_command(
        self, context: ResourceCommandContext, custom_command: str
    ) -> str:
        """Send custom command."""
        with LoggingSessionContext(context) as logger:
            logger.info("Starting 'Run Custom Command' command ...")
            api = CloudShellSessionContext(context).get_api()

            resource_config = NetworkingResourceConfig.from_context(
                shell_name=self.SHELL_NAME,
                supported_os=self.SUPPORTED_OS,
                context=context,
                api=api,
            )

            cli_handler = self._cli.get_cli_handler(resource_config, logger)

            send_command_operations = CiscoRunCommandFlow(
                logger=logger, cli_configurator=cli_handler
            )

            response = send_command_operations.run_custom_command(
                custom_command=custom_command
            )

            logger.info("'Run Custom Command' command completed")
            return response
    def remote_refresh_ip(self, context, ports, cancellation_context):
        """

        Called when reserving a sandbox during setup, a call for each app in the sandbox can also be run manually by the sandbox end-user from the deployed App's commands pane

        Method retrieves the VM's updated IP address from the cloud provider and sets it on the deployed App resource
        Both private and public IPs are retrieved, as appropriate.

        If the operation fails, method should raise an exception.

        :param ResourceRemoteCommandContext context:
        :param ports:
        :param CancellationContext cancellation_context:
        :return:
        """
        with LoggingSessionContext(context) as logger:
            logger.info("Starting Remote Refresh IP command...")
            api = CloudShellSessionContext(context).get_api()
            resource_config = MaasResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api)

            refresh_ip_flow = MaasRemoteRefreshIPFlow(
                resource_config=resource_config, cs_api=api, logger=logger)

            return refresh_ip_flow.refresh_ip(
                resource=context.remote_endpoints[0])
Beispiel #28
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()
    def CleanupSandboxInfra(self, context, request):
        """
        Called at the end of reservation teardown

        Cleans all entities (beside VMs) created for sandbox, usually entities created in the
        PrepareSandboxInfra command.

        Basically all created entities for the sandbox will be deleted by calling the methods: DeleteInstance, CleanupSandboxInfra

        If a failure occurs, return a "success false" action result.

        :param ResourceCommandContext context:
        :param str request:
        :return:
        :rtype: str
        """
        with LoggingSessionContext(context) as logger:
            logger.info("Starting Cleanup Sandbox Infra command...")
            api = CloudShellSessionContext(context).get_api()
            resource_config = MaasResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api)

            cleanup_sandbox_flow = MaasCleanupSandboxInfraFlow(
                resource_config=resource_config, logger=logger)
            return cleanup_sandbox_flow.cleanup(request=request)
    def test_cloudshell_session_from_remote_command(self):
        # Arrange
        context = mock.create_autospec(ResourceRemoteCommandContext)
        context.connectivity = mock.create_autospec(ConnectivityContext)
        context.connectivity.server_address = "localhost"
        context.connectivity.admin_auth_token = "123456789"
        context.resource = Mock()
        context.resource.name = "my_device"
        context.remote_reservation = Mock()
        context.remote_reservation.domain = "my_space"

        with mock.patch(
                "cloudshell.shell.core.session.cloudshell_session.CloudShellAPISession"
        ) as cloudshell_api_session:
            expected_cloudshell_session = Mock()
            cloudshell_api_session.return_value = expected_cloudshell_session

            # Act
            with CloudShellSessionContext(context) as cloudshell_session:

                # Assert
                cloudshell_api_session.assert_called_with(
                    domain="my_space",
                    host="localhost",
                    password=None,
                    token_id="123456789",
                    username=None,
                )
                self.assertEqual(cloudshell_session,
                                 expected_cloudshell_session)