Ejemplo n.º 1
0
    def cleanup_connectivity(self, command_context, request):
        with LoggingSessionContext(command_context) as logger:
            with ErrorHandlingContext(logger):
                logger.info('Teardown...')

                with CloudShellSessionContext(
                        command_context) as cloudshell_session:
                    cloud_provider_model = self.model_parser.convert_to_cloud_provider_resource_model(
                        resource=command_context.resource,
                        cloudshell_session=cloudshell_session)

                azure_clients = AzureClientsManager(cloud_provider_model)
                resource_group_name = command_context.reservation.reservation_id

                cleanup_connectivity_request = getattr(
                    DeployDataHolder(jsonpickle.decode(request)),
                    'driverRequest', None)

                result = self.delete_azure_vm_operation.cleanup_connectivity(
                    network_client=azure_clients.network_client,
                    resource_client=azure_clients.resource_client,
                    cloud_provider_model=cloud_provider_model,
                    resource_group_name=resource_group_name,
                    request=cleanup_connectivity_request,
                    logger=logger)

                logger.info('End Teardown')
                return self.command_result_parser.set_command_result(
                    {'driverResponse': {
                        'actionResults': [result]
                    }})
Ejemplo n.º 2
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
    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)
    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")
    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)
Ejemplo n.º 6
0
    def get_inventory(self, context):

        ## uncomment - if there is nothing to validate
        # return AutoLoadDetails([], [])

        # read from context
        cloud_provider_resource = L3HeavenlyCloudShell.create_from_context(
            context)

        with LoggingSessionContext(context) as logger, ErrorHandlingContext(
                logger):
            self._log(logger, 'get_inventory_context_json', context)

            # validating
            if cloud_provider_resource.name == 'evil':
                raise ValueError('evil cannot use heaven ')

            if cloud_provider_resource.region == 'sun':
                raise ValueError(
                    'invalid region, sorry cannot deploy instances on the sun')

            # using your cloud provider sdk
            if not HeavenlyCloudService.can_connect(
                    cloud_provider_resource.user,
                    cloud_provider_resource.password, context.resource.address
            ):  # TODO add address to resource (gal shellfoundry team)
                raise ValueError('could not connect using given credentials')

            # discovering - using your prefered custom cloud service you can discover and then update values
            if not cloud_provider_resource.heaven_cloud_color:
                cloud_provider_resource.heaven_cloud_color = HeavenlyCloudService.get_prefered_cloud_color(
                )

            return cloud_provider_resource.create_autoload_details()
    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))
Ejemplo n.º 8
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)
Ejemplo n.º 9
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):
            self._log(logger, 'GetVmDetails_context', context)
            self._log(logger, 'GetVmDetails_requests', requests)
            cloud_provider_resource = L2HeavenlyCloudShell.create_from_context(
                context)
            result = HeavenlyCloudServiceWrapper.get_vm_details(
                logger, cloud_provider_resource, cancellation_context,
                requests)
            result_json = json.dumps(result,
                                     default=lambda o: o.__dict__,
                                     sort_keys=True,
                                     separators=(',', ':'))

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

            return result_json
Ejemplo n.º 10
0
    def test_logger_initialized_for_resource_context_with_reservation(
            self, get_execution_info, log_execution_info, get_qs_logger):
        # Arrange
        resource_command_context = mock.create_autospec(ResourceCommandContext)
        resource_command_context.resource = mock.create_autospec(
            ResourceContextDetails)
        resource_command_context.resource.name = 'my_device'
        resource_command_context.reservation = mock.create_autospec(
            ReservationContextDetails)
        resource_command_context.reservation.reservation_id = 'reservation_id1'

        reservation_id = mock.Mock()
        resource_command_context.reservation.reservation_id = reservation_id

        execution_info = mock.Mock()
        get_execution_info.return_value = execution_info

        qs_logger = mock.Mock()
        get_qs_logger.return_value = qs_logger

        # Act
        with LoggingSessionContext(resource_command_context) as logger:
            # Assert
            get_execution_info.assert_called_once_with(
                resource_command_context)
            get_qs_logger.assert_called_once_with(
                log_group=reservation_id,
                log_category='QS',
                log_file_prefix=resource_command_context.resource.name)
            log_execution_info.assert_called_once_with(qs_logger,
                                                       execution_info)
            self.assertEqual(qs_logger, logger)
Ejemplo n.º 11
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
Ejemplo n.º 12
0
    def test_logger_initialized_for_autoload_context(self, get_execution_info,
                                                     log_execution_info,
                                                     get_qs_logger):
        # Arrange
        auto_load_context = mock.create_autospec(AutoLoadCommandContext)
        auto_load_context.resource = mock.create_autospec(
            ResourceContextDetails)
        auto_load_context.resource.name = 'my_device'

        execution_info = mock.Mock()
        get_execution_info.return_value = execution_info

        qs_logger = mock.Mock()
        get_qs_logger.return_value = qs_logger

        # Act
        with LoggingSessionContext(auto_load_context) as logger:
            get_execution_info.assert_called_once_with(auto_load_context)
            get_qs_logger.assert_called_once_with(
                log_group=INVENTORY,
                log_category='QS',
                log_file_prefix=auto_load_context.resource.name)
            log_execution_info.assert_called_once_with(qs_logger,
                                                       execution_info)
            self.assertEqual(qs_logger, logger)
Ejemplo n.º 13
0
    def power_off_vm(self, command_context):
        """Power off Azure VM

        :param ResourceCommandContext command_context:
        :return:
        """
        with LoggingSessionContext(command_context) as logger:
            with ErrorHandlingContext(logger):
                logger.info('Starting power off operation on Azure VM...')

                group_name = self.model_parser.convert_to_reservation_model(command_context.remote_reservation) \
                    .reservation_id

                resource = command_context.remote_endpoints[0]
                data_holder = self.model_parser.convert_app_resource_to_deployed_app(
                    resource)
                vm_name = data_holder.name

                with CloudShellSessionContext(
                        command_context) as cloudshell_session:
                    cloud_provider_model = self.model_parser.convert_to_cloud_provider_resource_model(
                        resource=command_context.resource,
                        cloudshell_session=cloudshell_session)

                azure_clients = AzureClientsManager(cloud_provider_model)

                self.power_vm_operation.power_off(
                    compute_client=azure_clients.compute_client,
                    resource_group_name=group_name,
                    vm_name=vm_name)

                logger.info(
                    'Azure VM {} was successfully powered off'.format(vm_name))
Ejemplo n.º 14
0
    def delete_azure_vm(self, command_context):
        with LoggingSessionContext(command_context) as logger:
            with ErrorHandlingContext(logger):
                logger.info('Deleting Azure VM...')

                resource_group_name = command_context.remote_reservation.reservation_id

                with CloudShellSessionContext(
                        command_context) as cloudshell_session:
                    cloud_provider_model = self.model_parser.convert_to_cloud_provider_resource_model(
                        resource=command_context.resource,
                        cloudshell_session=cloudshell_session)

                azure_clients = AzureClientsManager(cloud_provider_model)
                vm_name = command_context.remote_endpoints[0].fullname

                self.delete_azure_vm_operation.delete(
                    compute_client=azure_clients.compute_client,
                    network_client=azure_clients.network_client,
                    storage_client=azure_clients.storage_client,
                    group_name=resource_group_name,
                    vm_name=vm_name,
                    logger=logger)

                logger.info('End Deleting Azure VM')
Ejemplo n.º 15
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
Ejemplo n.º 16
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()
Ejemplo n.º 17
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()
Ejemplo n.º 18
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
    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
Ejemplo n.º 20
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
    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()
Ejemplo n.º 22
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 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
Ejemplo n.º 24
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 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()
Ejemplo n.º 26
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
    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])
Ejemplo n.º 28
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
    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 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 = KubernetesResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api)
            api_clients = ApiClientsProvider(logger).get_api_clients(
                resource_config)
            autoload_flow = AutolaodFlow(api_clients)
            autoload_flow.validate_config(resource_config)

        return AutoLoadDetails([], [])