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 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
def load_config(self, context, xena_configs_folder): reservation_id = context.reservation.reservation_id my_api = CloudShellSessionContext(context).get_api() reservation_ports = get_reservation_resources( my_api, reservation_id, 'Xena Chassis Shell 2G.GenericTrafficGeneratorPort') for reserved_port in reservation_ports: config = get_family_attribute(my_api, reserved_port, 'Logical Name').Value.strip() address = get_address(reserved_port) self.logger.debug( 'Configuration {} will be loaded on Physical location {}'. format(config, address)) chassis = my_api.GetResourceDetails( reserved_port.Name.split('/')[0]) encripted_password = my_api.GetAttributeValue( chassis.Name, 'Xena Chassis Shell 2G.Password').Value password = CloudShellSessionContext( context).get_api().DecryptPassword(encripted_password).Value tcp_port = my_api.GetAttributeValue( chassis.Name, 'Xena Chassis Shell 2G.Controller TCP Port').Value if not tcp_port: tcp_port = '22611' ip, module, port = address.split('/') self.xm.session.add_chassis(ip, int(tcp_port), password) xena_port = XenaPort(self.xm.session.chassis_list[ip], '{}/{}'.format(module, port)) xena_port.reserve(force=True) xena_port.load_config( path.join(xena_configs_folder, config) + '.xpc')
def GetVmDetails(self, context, requests, 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 VM Details pane Method queries cloud provider for instance operating system, specifications and networking information and returns that as a json serialized driver response containing a list of VmDetailsData. If the operation fails, method should raise an exception. :param ResourceCommandContext context: :param str requests: :param CancellationContext cancellation_context: :return: """ with LoggingSessionContext(context) as logger: logger.info(requests) api = CloudShellSessionContext(context).get_api() vm_details_data = [] requests_json = json.loads(requests) for refresh_request in requests_json["items"]: vm_name = refresh_request["deployedAppJson"]["name"] # deployment_service = refresh_request["appRequestJson"]["deploymentService"][ # "name"] resource_details = api.GetResourceDetails(vm_name) # logger.info(yaml.dump(resource_details)) ls_name = self._extract_attribute( resource_details.VmDetails.InstanceData, self.ATTRIBUTE.LS_NAME) logger.info("LS Name: {}".format(ls_name)) vm_inst_data = [ VmDetailsProperty(self.ATTRIBUTE.LS_NAME, ls_name) ] for res_info in resource_details.ChildResources: port_name = res_info.Name vnic = self._extract_attribute( res_info.ResourceAttributes, 'Juniper Virtual Router Shell.GenericVPort.Requested vNIC Name' ) vm_inst_data.append(VmDetailsProperty(port_name, vnic)) vm_details_data.append(VmDetailsData(vm_inst_data, [], vm_name)) return str(jsonpickle.encode(vm_details_data, unpicklable=False))
def restore(self, context, ports, path, configuration_type, restore_method, vrf_management_name): """Restore selected file to the provided destination :param ResourceCommandContext context: ResourceCommandContext object with all Resource Attributes inside :param path: source config file :param configuration_type: running or startup configs :param restore_method: append or override methods :param vrf_management_name: VRF management Name """ with LoggingSessionContext(context) as logger: api = CloudShellSessionContext(context).get_api() resource_config = JuniperCPResourceConfig.from_context( self.SHELL_NAME, context, api, self.SUPPORTED_OS) if not configuration_type: configuration_type = 'running' if not restore_method: restore_method = 'override' if not vrf_management_name: vrf_management_name = resource_config.vrf_management_name 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) configuration_operations = JuniperConfigurationFlow( resource_config, logger, ls_cli_configurator) logger.info('Restore for LS {} started'.format(ls_name)) configuration_operations.restore( path=path, restore_method=restore_method, configuration_type=configuration_type, vrf_management_name=vrf_management_name) logger.info('Restore for LS {} completed'.format(ls_name))
def save(self, context, ports, folder_path, configuration_type, vrf_management_name): """Save selected file to the provided destination :param ResourceCommandContext context: ResourceCommandContext object with all Resource Attributes inside :param configuration_type: source file, which will be saved :param folder_path: destination path where file will be saved :param vrf_management_name: VRF management Name :return str saved configuration file name: """ with LoggingSessionContext(context) as logger: api = CloudShellSessionContext(context).get_api() resource_config = JuniperCPResourceConfig.from_context( self.SHELL_NAME, context, api, self.SUPPORTED_OS) if not configuration_type: configuration_type = 'running' if not vrf_management_name: vrf_management_name = resource_config.vrf_management_name 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) configuration_operations = JuniperConfigurationFlow( resource_config, logger, ls_cli_configurator) logger.info('Save started') response += configuration_operations.save( folder_path=folder_path, configuration_type=configuration_type, vrf_management_name=vrf_management_name) + os.linesep logger.info('Save completed') return response
def Deploy(self, context, request=None, cancellation_context=None): """ :param ResourceCommandContext context: :param str request: json string to be parsed :param cancellation_context: :return: """ RESOURCE_POOL_ATTR = "App Pool Name" CP_RESTRICTED_ATTR = "Restricted App Model Pools" api = CloudShellSessionContext(context).get_api() res_id = context.reservation.reservation_id # VALIDATE THAT CLOUD PROVIDER RESOURCE HAS POOL LIST Attribute cp_attrs = context.resource.attributes try: cp_pool_list_val = cp_attrs[CP_RESTRICTED_ATTR] except KeyError: pass else: api.WriteMessageToReservationOutput(res_id, "=== full request json ===") api.WriteMessageToReservationOutput(res_id, request) request_obj = json.loads(request) request_action_params = request_obj["driverRequest"]["actions"][0][ "actionParams"] app_name = request_action_params["appName"] deployment = request_action_params["deployment"] app_resource = request_action_params["appResource"] app_resource_attrs = app_resource["attributes"] pool_attr_search = [ attr for attr in app_resource_attrs if attr["attributeName"] == RESOURCE_POOL_ATTR ] if pool_attr_search: app_pool_attr_val = pool_attr_search[0]["attributeValue"] restricted_attrs_dict = get_cp_restricted_attrs_dict( cp_pool_list_val) try: app_pool_limit = restricted_attrs_dict[app_pool_attr_val] except KeyError: not_found_msg = "{} pool name key not in cp restricted list {}".format( app_pool_attr_val, restricted_attrs_dict) api.WriteMessageToReservationOutput(res_id, not_found_msg) else: # count deployed apps all_generic_app_resources = api.FindResources( resourceFamily="Generic App Family").Resources # collect matching apps matching_apps = [] for resource in all_generic_app_resources: attrs = api.GetResourceDetails( resource.Name).ResourceAttributes attr_search = [ attr for attr in attrs if attr.Name == RESOURCE_POOL_ATTR ] if attr_search: attr_val = attr_search[0].Value if attr_val == app_pool_attr_val: matching_apps.append(resource) # PERFORM VALIDATION if len(matching_apps) >= int(app_pool_limit): matching_app_names = [r.Name for r in matching_apps] exc_msg = "Can not deploy '{}'. The pool '{}' has reached it's limit of {}. Current Apps in Pool: {}".format( app_name, app_pool_attr_val, app_pool_limit, matching_app_names) api.WriteMessageToReservationOutput( res_id, '<span style="color:red">{}</span>'.format( exc_msg)) raise AppLimitDeploymentError(exc_msg) actions = self.request_parser.convert_driver_request_to_actions( request) deploy_action = single(actions, lambda x: isinstance(x, DeployApp)) deployment_name = deploy_action.actionParams.deployment.deploymentPath if deployment_name in self.deployments.keys(): deploy_method = self.deployments[deployment_name] deploy_result = deploy_method(context, deploy_action, cancellation_context) return DriverResponse([deploy_result]).to_driver_response_json() else: raise Exception('Could not find the deployment')