def get_vm_details(self, si, logger, resource_context, requests, cancellation_context): results = [] for request in requests: if cancellation_context.is_cancelled: break app_name = request.deployedAppJson.name try: vm = self.pyvmomi_service.find_by_uuid(si, request.deployedAppJson.vmdetails.uid) self._wait_for_vm_to_be_ready(vm, request, logger) result = self.vm_details_provider.create( vm=vm, name=app_name, reserved_networks=resource_context.attributes.get('Reserved Networks', '').split(';'), ip_regex=next((p.value for p in request.deployedAppJson.vmdetails.vmCustomParams if p.name=='ip_regex'), None), deployment_details_provider=DeploymentDetailsProviderFromAppJson(request.appRequestJson.deploymentService), logger=logger) except Exception as e: logger.error("Error getting vm details for '{0}': {1}".format(app_name, traceback.format_exc())) result = VmDetailsData(errorMessage=e.message) result.appName = app_name results.append(result) return results
def get_vm_details(self, context, cancellation_context, requests_json): """# noqa Get vm details for specific deployed app :type context: ResourceCommandContext :rtype str """ results = [] vm_details_requests = [ VmDetailsRequest(item) for item in DeployDataHolder( jsonpickle.decode(requests_json)).items ] for request in vm_details_requests: if cancellation_context.is_cancelled: break try: with AwsShellContext(context=context, aws_session_manager=self. aws_session_manager) as shell_context: shell_context.logger.info("Get VmDetails") vm_details = self.vm_details_operation.get_vm_details( request.uuid, shell_context.aws_api.ec2_session) vm_details.appName = request.app_name results.append(vm_details) except Exception as e: result = VmDetailsData() result.appName = request.app_name result.error = str(e) results.append(result) return self.command_result_parser.set_command_result(results)
def get_vm_details(self, openstack_session, requests, cancellation_context, logger, management_vlan_id): """ :param management_vlan_id: :param requests: :param keystoneauth1.session.Session openstack_session: :param cancellation_context: :param logging.Logger logger: """ results = [] for request in requests: if cancellation_context.is_cancelled: break vm_name = request.deployedAppJson.name instance_id = request.deployedAppJson.vmdetails.uid try: vm = self.instance_service.get_instance_from_instance_id(openstack_session=openstack_session, instance_id=instance_id, logger=logger) result = self.vm_details_provider.create(vm, openstack_session, management_vlan_id, logger) except Exception as e: logger.error("Error getting vm details for '{0}': {1}".format(vm_name, traceback.format_exc())) result = VmDetailsData(errorMessage=e.message) result.appName = vm_name results.append(result) return results
def get_vm_details(self, compute_client, group_name, requests, logger, network_client, model_parser, cancellation_context): """ :param cancellation_context: :param model_parser: :param requests: :param network_client: :param compute_client: azure.mgmt.compute.ComputeManagementClient instance :param group_name: Azure resource group name (reservation id) :param logging.Logger logger: :return: cloudshell.cp.azure.domain.common.vm_details_provider.VmDetails """ results = [] for request in requests: if cancellation_context.is_cancelled: break vm_name = request.deployedAppJson.name deployment_service = request.appRequestJson.deploymentService is_market_place = filter(lambda x: x.name == "Image SKU", deployment_service.attributes) try: vm = self.vm_service.get_vm(compute_client, group_name, vm_name) result = self.vm_details_provider.create(vm, is_market_place, logger, network_client, group_name) except Exception as e: logger.error("Error getting vm details for '{0}': {1}".format(vm_name, traceback.format_exc())) result = VmDetailsData(errorMessage=e.message) result.appName = vm_name results.append(result) return results
def get_vm_details(self, context, cancellation_context, requests_json): """ Get vm details for specific deployed app :type context: ResourceCommandContext :rtype str """ results = [] vm_details_requests = [VmDetailsRequest(item) for item in DeployDataHolder(jsonpickle.decode(requests_json)).items] for request in vm_details_requests: if cancellation_context.is_cancelled: break try: with AwsShellContext(context=context, aws_session_manager=self.aws_session_manager) as shell_context: with ErrorHandlingContext(shell_context.logger): shell_context.logger.info('Get VmDetails') vm_details = self.vm_details_operation.get_vm_details(request.uuid, shell_context.aws_api.ec2_session) vm_details.appName = request.app_name results.append(vm_details) except Exception as e: result = VmDetailsData() result.appName = request.app_name result.error = e.message results.append(result) return self.command_result_parser.set_command_result(results)
def create(self, instance, is_market_place, logger, network_client, group_name): """ :param group_name: :param network_client: :param instance: azure.mgmt.compute.models.VirtualMachine :param is_market_place: bool :param logging.Logger logger: :return: """ vm_instance_data = None vm_network_data = None if is_market_place: vm_instance_data = self._get_vm_instance_data_for_market_place( instance) vm_network_data = self._get_vm_network_data( instance, network_client, group_name, logger) logger.info("VM {} was created via market place.".format( instance.name)) else: vm_instance_data = self._get_vm_instance_data_for_custom_image( instance) vm_network_data = self._get_vm_network_data( instance, network_client, group_name, logger) logger.info("VM {} was created via custom image.".format( instance.name)) return VmDetailsData(vmInstanceData=vm_instance_data, vmNetworkData=vm_network_data)
def create_vm_details(vm_name, mgmt_network, node_type, node_ifaces): """ Create the VM Details results used for both Deployment and Refresh VM Details """ vm_instance_data = [ VmDetailsProperty("Instance Type", node_type) # IOSv, NX-OSv etc ] vm_network_data = [] for iface in node_ifaces: network = iface.get("network") exclusion_network_name = f"{vm_name}-unconnected" if not network \ or network == mgmt_network\ or network.lower().startswith(exclusion_network_name.lower()): continue vm_nic = VmDetailsNetworkInterface() vm_nic.interfaceId = iface.get("port_id") vm_nic.networkId = network vm_nic.networkData.append( VmDetailsProperty("IP", iface.get("ipv4", ""))) vm_nic.networkData.append( VmDetailsProperty("IPv6", iface.get("ipv6", ""))) vm_nic.networkData.append( VmDetailsProperty("MAC Address", iface.get("mac", ""))) vm_nic.isPrimary = iface.get("mgmt", False) vm_nic.isPredefined = iface.get("mgmt", False) vm_network_data.append(vm_nic) return VmDetailsData(vm_instance_data, vm_network_data, vm_name)
def create(self, instance, deploy_app_name=""): vm_instance_data = self._get_vm_instance_data(instance, instance.vpc_id) vm_network_data = self._get_vm_network_data(instance) return VmDetailsData(vmInstanceData=vm_instance_data, vmNetworkData=vm_network_data, appName=deploy_app_name)
def extract_vm_details(vm_instance): vm_instance_data = VmDetailsCreator.extract_vm_instance_data( vm_instance) vm_network_data = VmDetailsCreator.extract_vm_instance_network_data( vm_instance) return VmDetailsData(vmInstanceData=vm_instance_data, vmNetworkData=vm_network_data)
def create(self, vm, name, reserved_networks, ip_regex, deployment_details_provider, logger): """""" vm_instance_data = self._get_vm_instance_data( vm, deployment_details_provider) vm_network_data = self._get_vm_network_data(vm, reserved_networks, ip_regex, logger) return VmDetailsData(vmInstanceData=vm_instance_data, vmNetworkData=vm_network_data)
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 extract_vm_details(self, vm_uuid): '''vm_detail_url = self.nutanix_base_url + '/vms/' + vm_uuid + '?include_vm_nic_config=true' in_progress = True while in_progress: response = self.session.get(vm_detail_url) if response.status_code != 200: raise StandardError("Unable to extract VM details. uid: {}".format(vm_uuid)) json_response = response.json() if 'vm_nics' in json_response and json_response['vm_nics'] != [] and 'ip_address' in json_response['vm_nics']: in_progress = False else: time.sleep(5)''' vm_detail_url = self.nutanix_base_url + '/vms/' + vm_uuid + '?include_vm_nic_config=true' response = self.session.get(vm_detail_url) if response.status_code != 200 and response.status_code != 201: raise StandardError( "Unable to extract VM details. uid: {}".format(vm_uuid)) json_response = response.json() vm_name = json_response['name'] vm_instance_data = [ VmDetailsProperty(key='Instance Name', value=json_response['name']) ] vm_network_data = [] i = 0 for nic in json_response['vm_nics']: network_data = [ VmDetailsProperty(key='MAC Address', value=nic['mac_address']), ] current_interface = VmDetailsNetworkInterface( interfaceId=i, networkId=nic['network_uuid'], isPredefined=True, networkData=network_data) i += 1 vm_network_data.append(current_interface) return VmDetailsData(vmInstanceData=vm_instance_data, vmNetworkData=vm_network_data)
def _get_vm_data(self, vm_uid, vm_name): """ :param str vm_uid: :param str vm_name: :return: """ machine = self._maas_client.machines.get(vm_uid) vm_network_data = [] data = [ VmDetailsProperty(key="Architecture", value=machine.architecture), VmDetailsProperty(key="HWE Kernel", value=machine.hwe_kernel), VmDetailsProperty(key="CPU Cores", value=machine.cpus), VmDetailsProperty(key="RAM GiB", value=machine.memory // 1024), VmDetailsProperty(key="Disks", value=len(machine.block_devices)), VmDetailsProperty(key="Distro Series", value=machine.distro_series), VmDetailsProperty(key="Operation System", value=machine.osystem), ] for iface in machine.interfaces: network_data = [ VmDetailsProperty(key="MAC Address", value=iface.mac_address), ] for link in iface.links: iface_id = hash(f"{iface.id }_{link.id}") interface = VmDetailsNetworkInterface( interfaceId=iface_id, networkId=iface_id, isPredefined=True, networkData=network_data, privateIpAddress=link.ip_address, ) vm_network_data.append(interface) vm_details_data = VmDetailsData(vmInstanceData=data, vmNetworkData=vm_network_data, appName=vm_name) return vm_details_data
def get_vm_details(self, vm_name, vm_uuid): vm_detail_url = self.nutanix_base_url + '/vms/' + vm_uuid + '?include_vm_nic_config=true' response = self.session.get(vm_detail_url) if response.status_code != 200 and response.status_code != 201: raise StandardError( "Unable to get VM details. uid: {}".format(vm_uuid)) json_response = response.json() vm_name = json_response['name'] vm_instance_data = [ VmDetailsProperty(key='Instance Name', value=json_response['name']) ] vm_network_data = [] i = 0 for nic in json_response['vm_nics']: network_data = [ VmDetailsProperty(key='MAC Address', value=nic['mac_address']), ] current_interface = VmDetailsNetworkInterface( interfaceId=i, networkId=nic['network_uuid'], isPrimary=i == 0, isPredefined=True, networkData=network_data, privateIpAddress=nic['ip_address']) vm_network_data.append(current_interface) i += 1 return VmDetailsData(vmInstanceData=vm_instance_data, vmNetworkData=vm_network_data, appName=vm_name)
def create(self, vm, name, reserved_networks, ip_regex, deployment_details_provider, wait_for_ip, logger): """ creates the details provider :param vm: :param name: :param reserved_networks: :param ip_regex: :param deployment_details_provider: :param wait_for_ip: type: string contains 'True' or 'False' :param logger: :return: """ logger.info('waiting for ip = {0}'.format(wait_for_ip)) vm_instance_data = self._get_vm_instance_data( vm, deployment_details_provider) vm_network_data = self._get_vm_network_data(vm, reserved_networks, ip_regex, wait_for_ip, logger) return VmDetailsData(vmInstanceData=vm_instance_data, vmNetworkData=vm_network_data)
def Deploy(self, context, request, cancellation_context=None): """ Called when reserving a sandbox during setup, a call for each app in the sandbox. Method creates the compute resource in the cloud provider - VM instance or container. If App deployment fails, return a "success false" action result. :param ResourceCommandContext context: :param str request: A JSON string with the list of requested deployment actions :param CancellationContext cancellation_context: :return: :rtype: str """ ''' # parse the json strings into action objects actions = self.request_parser.convert_driver_request_to_actions(request) # extract DeployApp action deploy_action = single(actions, lambda x: isinstance(x, DeployApp)) # if we have multiple supported deployment options use the 'deploymentPath' property # to decide which deployment option to use. deployment_name = deploy_action.actionParams.deployment.deploymentPath deploy_result = _my_deploy_method(context, actions, cancellation_context) return DriverResponse(deploy_result).to_driver_response_json() ''' with LoggingSessionContext(context) as logger: logger.info(request) api = CloudShellSessionContext(context).get_api() resource_config = JuniperCPResourceConfig.from_context( self.SHELL_NAME, context, api, self.SUPPORTED_OS) cli_configurator = JuniperCliConfigurator(CLI(self._session_pool), resource_config, logger) ls_flow = CreateRemoveLSFlow(cli_configurator, logger) actions = DriverRequestParser().convert_driver_request_to_actions( request) reservation_details = api.GetReservationDetails( context.reservation.reservation_id, disableCache=True).ReservationDescription results = [] for deploy_action in actions: app_name = deploy_action.actionParams.appName int_list = self._get_int_names(reservation_details, app_name) logger.info("{}:{}".format(app_name, str(int_list))) if not int_list: raise Exception( "Failed to deploy Logical System without interfaces. " "Please create appropriate connections") vm_uuid = self._build_uuid(app_name, context.reservation.reservation_id) ls_name = "VR-{}".format(vm_uuid) vm_name = "{}-{}".format(app_name, ls_name) int_list = ls_flow.create_ls(ls_name, int_list) vm_instance_data = [ VmDetailsProperty(self.ATTRIBUTE.INST_UUID, vm_uuid), VmDetailsProperty(self.ATTRIBUTE.LS_NAME, ls_name), ] vm_interfaces_data = [ VmDetailsProperty("vNIC {} Name".format(i), int_list[i]) for i in range(len(int_list)) ] vm_instance_data.extend(vm_interfaces_data) deploy_result = DeployAppResult( actionId=deploy_action.actionId, infoMessage="Deployment Completed Successfully", vmUuid=vm_uuid, vmName=vm_name, deployedAppAddress="", deployedAppAttributes=[], vmDetailsData=VmDetailsData(vm_instance_data)) results.append(deploy_result) return DriverResponse(results).to_driver_response_json()