Exemple #1
0
    def health_check(self, context):
        """Checks if the device is up and connectable.

        :param ResourceCommandContext context: ResourceCommandContext
            object with all Resource Attributes inside
        :return: Success or fail message
        :rtype: str
        """
        with LoggingSessionContext(context) as logger, LogCommand(
            logger, "health_check"
        ):
            api = CloudShellSessionContext(context).get_api()

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

            cli_configurator = CheckpointCliConfigurator(
                self._cli, resource_config, logger
            )

            state_flow = CheckpointStateFlow(
                logger, resource_config, cli_configurator, api
            )
            return state_flow.health_check()
Exemple #2
0
    def restore(self, context, path, configuration_type, restore_method):
        """Restores a configuration file.

        :param ResourceCommandContext context: The context object for the
        command with resource and reservation info
        :param str path: The path to the configuration file, including
        the configuration file name
        :param str restore_method: Determines whether the restore should
        append or override the current configuration
        :param str configuration_type: Specify whether the file should
        update the startup or running config
        """
        with LoggingSessionContext(context) as logger, LogCommand(logger, "restore"):
            api = CloudShellSessionContext(context).get_api()

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

            cli_configurator = CheckpointCliConfigurator(
                self._cli, resource_config, logger
            )

            configuration_flow = CheckpointConfigurationFlow(
                logger, resource_config, cli_configurator
            )
            configuration_type = configuration_type or "running"
            restore_method = restore_method or "override"
            return configuration_flow.restore(path, configuration_type, restore_method)
Exemple #3
0
    def get_inventory(self, context):
        """Discovers the resource structure and attributes.

        :param ResourceCommandContext context: ResourceCommandContext object
            with all Resource Attributes inside
        :return Attribute and sub-resource information for the Shell resource
        :rtype: AutoLoadDetails
        """
        with LoggingSessionContext(context) as logger, LogCommand(
            logger, "get_inventory"
        ):
            api = CloudShellSessionContext(context).get_api()

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

            cli_configurator = CheckpointCliConfigurator(
                self._cli, resource_config, logger
            )
            enable_disable_snmp_flow = CheckpointEnableDisableSnmpFlow(
                cli_configurator, logger
            )
            snmp_configurator = EnableDisableSnmpConfigurator(
                enable_disable_snmp_flow, resource_config, logger
            )

            resource_model = FirewallResourceModel.from_resource_config(resource_config)

            autoload_operations = CheckpointSnmpAutoloadFlow(logger, snmp_configurator)
            logger.info("Autoload started")
            response = autoload_operations.discover(self.SUPPORTED_OS, resource_model)
            logger.info("Autoload completed")
            return response
Exemple #4
0
    def orchestration_restore(self, context, saved_artifact_info, custom_params):
        """Restores a saved artifact.

        Restores a saved artifact previously saved by this Shell driver using the
            orchestration_save function.

        :param ResourceCommandContext context: The context object for the command
            with resource andreservation info
        :param str saved_artifact_info: A JSON string representing the state to
            restore including saved artifacts and info
        :param str custom_params: Set of custom parameters for the restore operation
        """
        with LoggingSessionContext(context) as logger, LogCommand(
            logger, "orchestration_restore"
        ):
            api = CloudShellSessionContext(context).get_api()

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

            cli_configurator = CheckpointCliConfigurator(
                self._cli, resource_config, logger
            )

            configuration_flow = CheckpointConfigurationFlow(
                logger, resource_config, cli_configurator
            )
            return configuration_flow.orchestration_restore(
                saved_artifact_info, custom_params
            )
Exemple #5
0
    def orchestration_save(self, context, mode, custom_params):
        """Saves the shell state.

        Saves the shell state and returns a description of the saved
            artifacts and information. This command is intended for API use
            only by sandbox orchestration scripts to implement a save and
            restore workflow.

        :param ResourceCommandContext context: the context object containing
        resource and reservation info
        :param str mode: Snapshot save mode, can be one of two values
        "shallow" (default) or "deep"
        :param str custom_params: Set of custom parameters for the save operation
        :return: SavedResults serialized as JSON
        :rtype: OrchestrationSaveResult
        """
        with LoggingSessionContext(context) as logger, LogCommand(
            logger, "orchestration_save"
        ):
            api = CloudShellSessionContext(context).get_api()

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

            cli_configurator = CheckpointCliConfigurator(
                self._cli, resource_config, logger
            )

            configuration_flow = CheckpointConfigurationFlow(
                logger, resource_config, cli_configurator
            )
            return configuration_flow.orchestration_save(mode, custom_params)
Exemple #6
0
    def save(self, context, folder_path, configuration_type, vrf_management_name):
        """Save a configuration file to the provided destination.

        :param ResourceCommandContext context: The context object for
        the command with resource and reservation info
        :param str folder_path: The path to the folder in which the
        configuration file will be saved
        :param str configuration_type: startup or running config
        :param vrf_management_name:
        :return The configuration file name
        :rtype: str
        """
        with LoggingSessionContext(context) as logger, LogCommand(logger, "save"):
            api = CloudShellSessionContext(context).get_api()

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

            cli_configurator = CheckpointCliConfigurator(
                self._cli, resource_config, logger
            )

            configuration_flow = CheckpointConfigurationFlow(
                logger, resource_config, cli_configurator
            )
            configuration_type = configuration_type or "running"
            return configuration_flow.save(
                folder_path, configuration_type, vrf_management_name
            )
    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:
        """
        dump_context("refresh-ip-context", context, r"C:\temp\context")
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()
            resource_config = KubernetesResourceConfig.from_context(
                self.SHELL_NAME, context, api)
            api_clients = ApiClientsProvider(logger).get_api_clients(
                resource_config)
            service_provider = ServiceProvider(api_clients, logger, None)
            DeployedVMActions.register_deployment_path(KubernetesDeployedApp)
            deployed_app = DeployedVMActions.from_remote_resource(
                context.remote_endpoints[0], api).deployed_app
            RefreshIpFlow(logger, resource_config,
                          service_provider).refresh_ip(deployed_app)
Exemple #8
0
    def test_logger_initialized_for_remote_context_with_reservation(
            self, get_execution_info, log_execution_info, get_qs_logger):
        # Arrange
        remote_command_context = mock.create_autospec(
            ResourceRemoteCommandContext)
        remote_command_context.resource = mock.create_autospec(
            ResourceContextDetails)
        remote_command_context.resource.name = 'my_device'
        remote_command_context.remote_reservation = mock.create_autospec(
            ReservationContextDetails)
        remote_command_context.remote_reservation.reservation_id = 'reservation_id1'
        remote_endpoint = mock.create_autospec(ResourceContextDetails)
        remote_endpoint.name = 'connected_device'
        remote_command_context.remote_endpoints = [remote_endpoint]

        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(remote_command_context) as logger:
            # Assert
            get_execution_info.assert_called_once_with(remote_command_context)
            get_qs_logger.assert_called_once_with(
                log_group=remote_command_context.remote_reservation.
                reservation_id,
                log_category='QS',
                log_file_prefix=remote_endpoint.name)
            log_execution_info.assert_called_once_with(qs_logger,
                                                       execution_info)
            self.assertEqual(qs_logger, logger)
Exemple #9
0
    def get_inventory(self, context):

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

        # read from context
        resource = HeavenlyCloudsShell.create_from_context(context)

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

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

                if resource.region == 'sun':
                    raise ValueError(
                        'invalid region, sorry ca\'nt deploy instances on the sun'
                    )

                # using your cloud provider sdk
                if not HeavenlyCloudsService.can_connect(
                        resource.user, 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 resource.heaven_cloud_color:
                    resource.heaven_cloud_color = HeavenlyCloudsService.get_prefered_cloud_color(
                    )

                return resource.create_autoload_details()
    def GetAvailablePrivateIP(self, context, subnet_cidr, owner):
        with LoggingSessionContext(context) as logger:
            logger.info("Starting Get Available Private IP command...")
            api = CloudShellSessionContext(context).get_api()
            resource_config = AzureResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api
            )

            reservation_info = AzureReservationInfo.from_remote_resource_context(
                context
            )
            cs_ip_pool_manager = CSIPPoolManager(cs_api=api, logger=logger)

            azure_client = AzureAPIClient(
                azure_subscription_id=resource_config.azure_subscription_id,
                azure_tenant_id=resource_config.azure_tenant_id,
                azure_application_id=resource_config.azure_application_id,
                azure_application_key=resource_config.azure_application_key,
                logger=logger,
            )

            get_available_ip_flow = AzureGetAvailablePrivateIPFlow(
                resource_config=resource_config,
                azure_client=azure_client,
                cs_ip_pool_manager=cs_ip_pool_manager,
                reservation_info=reservation_info,
                logger=logger,
            )

            return get_available_ip_flow.get_available_private_ip(
                subnet_cidr=subnet_cidr, owner=owner
            )
    def PowerOn(self, context, ports):
        """
        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 spins up the VM

        If the operation fails, method should raise an exception.

        :param ResourceRemoteCommandContext context:
        :param ports:
        """

        dump_context("poweron-context", context, r"C:\temp\context")
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()
            resource_config = KubernetesResourceConfig.from_context(
                self.SHELL_NAME, context, api)
            api_clients = ApiClientsProvider(logger).get_api_clients(
                resource_config)
            service_provider = ServiceProvider(api_clients, logger, None)
            DeployedVMActions.register_deployment_path(KubernetesDeployedApp)
            deployed_app = DeployedVMActions.from_remote_resource(
                context.remote_endpoints[0], api).deployed_app
            PowerFlow(logger, resource_config,
                      service_provider).power_on(deployed_app)
    def GetAccessKey(self, context, ports):
        with LoggingSessionContext(context) as logger:
            logger.info("Starting Get Access Key command...")
            api = CloudShellSessionContext(context).get_api()
            resource_config = AzureResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api
            )

            reservation_info = AzureReservationInfo.from_remote_resource_context(
                context
            )

            azure_client = AzureAPIClient(
                azure_subscription_id=resource_config.azure_subscription_id,
                azure_tenant_id=resource_config.azure_tenant_id,
                azure_application_id=resource_config.azure_application_id,
                azure_application_key=resource_config.azure_application_key,
                logger=logger,
            )

            access_key_flow = AzureGetAccessKeyFlow(
                resource_config=resource_config,
                azure_client=azure_client,
                reservation_info=reservation_info,
                logger=logger,
            )

            return access_key_flow.get_access_key()
    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 = AzureResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api
            )

            azure_client = AzureAPIClient(
                azure_subscription_id=resource_config.azure_subscription_id,
                azure_tenant_id=resource_config.azure_tenant_id,
                azure_application_id=resource_config.azure_application_id,
                azure_application_key=resource_config.azure_application_key,
                logger=logger,
            )

            autoload_flow = AzureAutoloadFlow(
                resource_config=resource_config,
                azure_client=azure_client,
                logger=logger,
            )

            return autoload_flow.discover()
    def CreateRouteTables(self, context, request):
        with LoggingSessionContext(context) as logger:
            logger.info("Starting Create Route Tables command...")
            api = CloudShellSessionContext(context).get_api()

            resource_config = AzureResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api
            )

            request_actions = CreateRouteTablesRequestActions.from_request(request)
            reservation_info = AzureReservationInfo.from_resource_context(context)

            azure_client = AzureAPIClient(
                azure_subscription_id=resource_config.azure_subscription_id,
                azure_tenant_id=resource_config.azure_tenant_id,
                azure_application_id=resource_config.azure_application_id,
                azure_application_key=resource_config.azure_application_key,
                logger=logger,
            )

            route_table_flow = CreateRouteTablesFlow(
                resource_config=resource_config,
                reservation_info=reservation_info,
                azure_client=azure_client,
                cs_api=api,
                logger=logger,
            )

            return route_table_flow.create_route_tables(request_actions=request_actions)
    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:
        """
        dump_context("delete-context", context, r"C:\temp\context")
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()
            resource_config = KubernetesResourceConfig.from_context(
                self.SHELL_NAME, context, api)
            api_clients = ApiClientsProvider(logger).get_api_clients(
                resource_config)
            service_provider = ServiceProvider(api_clients, logger, None)
            DeployedVMActions.register_deployment_path(KubernetesDeployedApp)
            deployed_app = DeployedVMActions.from_remote_resource(
                context.remote_endpoints[0], api).deployed_app
            DeleteInstanceFlow(logger, resource_config,
                               service_provider).delete_instance(
                                   deployed_app.kubernetes_name,
                                   deployed_app.name, deployed_app.namespace)
    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]
                    }})
    def test_logger_initialized_for_resource_context_without_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 = None

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

        qs_logger = mock.Mock()
        child_logger = mock.Mock()
        qs_logger.getChild.return_value = child_logger
        qs_logger.handlers = [mock.Mock()]
        qs_logger.filters = [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=INVENTORY,
                log_category="QS",
                log_file_prefix=resource_command_context.resource.name,
            )
            log_execution_info.assert_called_once_with(qs_logger,
                                                       execution_info)
            self.assertEqual(child_logger, logger)
Exemple #18
0
    def run_custom_command(self, context: ResourceCommandContext,
                           custom_command: str) -> str:
        """Send custom command.

        :param custom_command: Command user wants to send to the device.
        :param context: an object with all Resource Attributes inside
        :return: result
        """
        logger = LoggingSessionContext.get_logger_with_thread_id(context)
        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 = CommandFlow(logger=logger,
                                              cli_configurator=cli_handler)

        response = send_command_operations.run_custom_command(
            custom_command=custom_command)

        return response
Exemple #19
0
    def shutdown(self, context: ResourceCommandContext):
        """Shutdown device.

        :param context: an object with all Resource Attributes inside
        :return:
        """
        logger = LoggingSessionContext.get_logger_with_thread_id(context)
        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 = StateFlow(
            logger=logger,
            api=api,
            resource_config=resource_config,
            cli_configurator=cli_handler,
        )

        return state_operations.shutdown()
Exemple #20
0
    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
        """
        logger = LoggingSessionContext.get_logger_with_thread_id(context)
        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 = SNMPHandler(resource_config, logger, cli_handler)

        autoload_operations = AutoloadFlow(logger=logger,
                                           snmp_handler=snmp_handler)
        logger.info("Autoload started")
        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 completed")
        return response
Exemple #21
0
    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
        """
        logger = LoggingSessionContext.get_logger_with_thread_id(context)
        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 = 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")
Exemple #22
0
    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
        """
        logger = LoggingSessionContext.get_logger_with_thread_id(context)
        api = CloudShellSessionContext(context).get_api()

        resource_config = NetworkingResourceConfig.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))
Exemple #23
0
    def ApplyConnectivityChanges(self, context: ResourceCommandContext,
                                 request: str) -> str:
        """
        Create vlan and add or remove it to/from network interface.

        :param context: an object with all Resource Attributes inside
        :param str request: request json
        :return:
        """
        logger = LoggingSessionContext.get_logger_with_thread_id(context)
        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 = ConnectivityFlow(
            logger=logger,
            cli_handler=cli_handler,
            support_vlan_range_str=False,
            support_multi_vlan_str=False,
        )
        logger.info("Start applying connectivity changes.")
        result = connectivity_operations.apply_connectivity_changes(
            request=request)
        logger.info("Apply Connectivity changes completed")
        return result
Exemple #24
0
    def orchestration_save(self, context: ResourceCommandContext, mode: str,
                           custom_params: str) -> str:
        """Save selected file to the provided destination.

        :param context: an object with all Resource Attributes inside
        :param mode: mode
        :param custom_params: json with custom save parameters
        :return str response: response json
        """
        if not mode:
            mode = "shallow"

        logger = LoggingSessionContext.get_logger_with_thread_id(context)
        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 = ConfigurationFlow(cli_handler=cli_handler,
                                               logger=logger,
                                               resource_config=resource_config)

        logger.info("Orchestration save started")
        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 completed")
        return response_json
    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))
    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')
    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([], [])
    def reconfigure_vm(
        self,
        context,
        ports,
        cancellation_context,
        vm_size,
        os_disk_size,
        os_disk_type,
        data_disks,
    ):
        """Reconfigure VM Size and Data Disks."""
        with LoggingSessionContext(context) as logger:
            logger.info("Starting Reconfigure VM command...")
            api = CloudShellSessionContext(context).get_api()
            resource_config = AzureResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api
            )

            reservation_info = AzureReservationInfo.from_remote_resource_context(
                context
            )
            cancellation_manager = CancellationContextManager(cancellation_context)

            azure_client = AzureAPIClient(
                azure_subscription_id=resource_config.azure_subscription_id,
                azure_tenant_id=resource_config.azure_tenant_id,
                azure_application_id=resource_config.azure_application_id,
                azure_application_key=resource_config.azure_application_key,
                logger=logger,
            )

            for deployed_app_cls in (
                AzureVMFromMarketplaceDeployedApp,
                AzureVMFromCustomImageDeployedApp,
                AzureVMFromSharedGalleryImageDeployedApp,
            ):
                DeployedVMActions.register_deployment_path(deployed_app_cls)

            resource = context.remote_endpoints[0]
            deployed_vm_actions = DeployedVMActions.from_remote_resource(
                resource=resource, cs_api=api
            )

            reconfigure_vm_flow = AzureReconfigureVMFlow(
                resource_config=resource_config,
                azure_client=azure_client,
                cs_api=api,
                reservation_info=reservation_info,
                cancellation_manager=cancellation_manager,
                logger=logger,
            )

            return reconfigure_vm_flow.reconfigure(
                deployed_app=deployed_vm_actions.deployed_app,
                vm_size=vm_size,
                os_disk_size=os_disk_size,
                os_disk_type=os_disk_type,
                data_disks=data_disks,
            )
    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
        """
        '''
        # parse the json strings into action objects
        actions = self.request_parser.convert_driver_request_to_actions(request)
        
        action_results = _my_prepare_connectivity(context, actions, cancellation_context)
        
        return DriverResponse(action_results).to_driver_response_json()    
        '''
        dump_context("prepare-sandbox-infra-context", context,
                     r"C:\temp\context")
        dump_context("prepare-sandbox-infra-request",
                     request,
                     r"C:\temp\context",
                     obj=False)

        with LoggingSessionContext(context) as logger:
            # parse the json strings into action objects
            api = CloudShellSessionContext(context).get_api()

            resource_config = KubernetesResourceConfig.from_context(
                self.SHELL_NAME, context, api)

            api_clients = ApiClientsProvider(logger).get_api_clients(
                resource_config)
            service_provider = ServiceProvider(
                api_clients, logger,
                CancellationContextManager(cancellation_context))
            tag_service = TagsService(context)

            request_actions = PrepareSandboxInfraRequestActions.from_request(
                request)

            flow = PrepareSandboxInfraFlow(logger, resource_config,
                                           service_provider, tag_service)
            return flow.prepare(request_actions)
    def remote_refresh_ip(self, context, ports, cancellation_context):
        """Called when reserving a sandbox during setup.

        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 = AzureResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api
            )

            reservation_info = AzureReservationInfo.from_remote_resource_context(
                context
            )
            cancellation_manager = CancellationContextManager(cancellation_context)

            azure_client = AzureAPIClient(
                azure_subscription_id=resource_config.azure_subscription_id,
                azure_tenant_id=resource_config.azure_tenant_id,
                azure_application_id=resource_config.azure_application_id,
                azure_application_key=resource_config.azure_application_key,
                logger=logger,
            )

            for deploy_app_cls in (
                AzureVMFromMarketplaceDeployedApp,
                AzureVMFromCustomImageDeployedApp,
                AzureVMFromSharedGalleryImageDeployedApp,
            ):
                DeployedVMActions.register_deployment_path(deploy_app_cls)

            resource = context.remote_endpoints[0]
            deployed_vm_actions = DeployedVMActions.from_remote_resource(
                resource=resource, cs_api=api
            )

            refresh_ip_flow = AzureRefreshIPFlow(
                resource_config=resource_config,
                azure_client=azure_client,
                cs_api=api,
                reservation_info=reservation_info,
                cancellation_manager=cancellation_manager,
                logger=logger,
            )

            return refresh_ip_flow.refresh_ip(
                deployed_app=deployed_vm_actions.deployed_app
            )