def _get_port_ixn(self, card_relative_address, port_id, port): """ Get port resource and attributes. """ relative_address = card_relative_address + '/P' + str(port_id) resource = AutoLoadResource(model='Generic Traffic Generator Port', name='Port' + str(port_id), relative_address=relative_address) self.resources.append(resource)
def _get_power_supply(self, power_supply): """ get power supplies resource and attributes. """ relative_address = 'PP' + power_supply.attributes['Index'] resource = AutoLoadResource(model='Generic Power Port', name='PP' + power_supply.attributes['Index'], relative_address=relative_address) self.resources.append(resource)
def _get_test_ip(self, endpoint, test_ip): """ Get port group resource and attributes. """ relative_address = endpoint + '/' + test_ip.address self.resources.append(AutoLoadResource(model='Traffic Generator Test IP', name=test_ip.address.replace(':', '-'), relative_address=relative_address)) self.attributes.append(AutoLoadAttribute(relative_address=relative_address, attribute_name='Abstraction Selector', attribute_value=test_ip.address.replace(':', '-')))
def _get_port_group(self, module_address, port_group): """ Get port group resource and attributes. """ relative_address = module_address + '/PG' + port_group.attributes[ 'Index'] resource = AutoLoadResource(model='Generic Port Group', name='PG' + port_group.attributes['Index'], relative_address=relative_address) self.resources.append(resource) for port in port_group.ports.values(): self._get_port(relative_address, port)
def _get_endpoint(self, endpoint): """ Get module resource and attributes. """ relative_address = 'EP' + endpoint.managementIp.address self.resources.append(AutoLoadResource(model='IxChariot Endpoint', name=endpoint.name, relative_address=relative_address)) self.attributes.append(AutoLoadAttribute(relative_address=relative_address, attribute_name='OS Version', attribute_value=endpoint.operatingSystem)) for test_ip in endpoint.ips: self.logger.info('test IP = {}'.format(test_ip)) self._get_test_ip(relative_address, test_ip)
def _get_port(self, port_group_address, port): """ Get port resource and attributes. """ relative_address = port_group_address + '/P' + port.attributes['Index'] resource = AutoLoadResource(model='Generic Traffic Generator Port', name='Port' + port.attributes['Index'], relative_address=relative_address) self.resources.append(resource) max_speed = self._get_max_speed( port.obj_parent().obj_parent().attributes['SupportedSpeeds']) self.attributes.append( AutoLoadAttribute(relative_address=relative_address, attribute_name='Max Speed', attribute_value=max_speed))
def _get_port(self, card_relative_address, port_id, port): """ Get port resource and attributes. """ relative_address = card_relative_address + '/P' + str(port_id) resource = AutoLoadResource( model='Xena Chassis Shell 2G.GenericTrafficGeneratorPort', name='Port' + str(port_id), relative_address=relative_address) self.resources.append(resource) self.attributes.append( AutoLoadAttribute( relative_address=relative_address, attribute_name='CS_TrafficGeneratorPort.Max Speed', attribute_value=port.p_info['p_speed']))
def _get_port_ixos(self, card_relative_address, port_id, port): """ Get port resource and attributes. """ relative_address = card_relative_address + '/P' + str(port_id) resource = AutoLoadResource(model='Generic Traffic Generator Port', name='Port' + str(port_id), relative_address=relative_address) self.resources.append(resource) supported_speeds = port.supported_speeds() if port.supported_speeds( ) else ['1000'] self.attributes.append( AutoLoadAttribute(relative_address=relative_address, attribute_name='Max Speed', attribute_value=int( max(supported_speeds, key=int))))
def _get_test_ip(self, endpoint, test_ip): """ Get port group resource and attributes. """ relative_address = endpoint + '/' + test_ip.address.encode('utf-8') model = 'IxChariot Server Shell 2G.GenericTrafficGeneratorPort' self.resources.append( AutoLoadResource(model=model, name=test_ip.address.encode('utf-8').replace( ':', '-'), relative_address=relative_address)) self.attributes.append( AutoLoadAttribute( relative_address=relative_address, attribute_name='CS_TrafficGeneratorPort.Model Name', attribute_value='IxChariot Test IP'))
def _get_module(self, module): """ Get module resource and attributes. """ relative_address = 'M' + module.attributes['Index'] resource = AutoLoadResource(model='Generic Traffic Generator Module', name='Module' + module.attributes['Index'], relative_address=relative_address) self.resources.append(resource) self._get_attributes( relative_address, { 'Model': module.attributes['Model'], 'Serial Number': module.attributes['SerialNum'], 'Version': module.attributes['FirmwareVersion'] }) for port_group in module.pgs.values(): self._get_port_group(relative_address, port_group)
def create_autoload_details(self, relative_path=''): """ :param relative_path: :type relative_path: str :return """ resources = [AutoLoadResource(model=self.resources[r].cloudshell_model_name, name=self.resources[r].name, relative_address=self._get_relative_path(r, relative_path)) for r in self.resources] attributes = [AutoLoadAttribute(relative_path, a, self.attributes[a]) for a in self.attributes] autoload_details = AutoLoadDetails(resources, attributes) for r in self.resources: curr_path = relative_path + '/' + r if relative_path else r curr_auto_load_details = self.resources[r].create_autoload_details(curr_path) autoload_details = self._merge_autoload_details(autoload_details, curr_auto_load_details) return autoload_details
def _get_port_ixos(self, card_relative_address, port_id, port): """ Get port resource and attributes. """ relative_address = card_relative_address + '/P' + str(port_id) resource = AutoLoadResource(model='Ixia Chassis Shell 2G.GenericTrafficGeneratorPort', name='Port' + str(port_id), relative_address=relative_address) self.resources.append(resource) supported_speeds = port.supported_speeds() if not supported_speeds: supported_speeds = ['0'] self.attributes.append(AutoLoadAttribute(relative_address=relative_address, attribute_name='CS_TrafficGeneratorPort.Max Speed', attribute_value=int(max(supported_speeds, key=int)))) self.attributes.append(AutoLoadAttribute(relative_address=relative_address, attribute_name='CS_TrafficGeneratorPort.Configured Controllers', attribute_value='IxLoad'))
def _get_module_ixos(self, card_id, card): """ Get module resource and attributes. """ relative_address = 'M' + str(card_id) model = 'Ixia Chassis Shell 2G.GenericTrafficGeneratorModule' resource = AutoLoadResource(model=model, name='Module' + str(card_id), relative_address=relative_address) self.resources.append(resource) self.attributes.append(AutoLoadAttribute(relative_address=relative_address, attribute_name='CS_TrafficGeneratorModule.Model Name', attribute_value=card.typeName)) self.attributes.append(AutoLoadAttribute(relative_address=relative_address, attribute_name=model + '.Serial Number', attribute_value=card.serialNumber.strip())) self.attributes.append(AutoLoadAttribute(relative_address=relative_address, attribute_name=model + '.Version', attribute_value=card.hwVersion)) for port_id, port in card.ports.items(): self._get_port_ixos(relative_address, port_id, port)
def _build_branch(self, resource): """Build a branch. :param cloudshell.shell.standards.core.autoload.resource_model.AbstractResource resource: # noqa: E501 :rtype: cloudshell.shell.core.driver_context.AutoLoadDetails """ resource.shell_name = resource.shell_name or self.resource_model.shell_name relative_address = str(resource.relative_address) unique_identifier = get_unique_id(self._cs_resource_id, resource) autoload_details = AutoLoadDetails([], []) if relative_address: autoload_details.resources = [ AutoLoadResource( model=resource.cloudshell_model_name, name=resource.name, relative_address=relative_address, unique_identifier=unique_identifier, ) ] autoload_details.attributes = [ AutoLoadAttribute( relative_address=relative_address, attribute_name=str(name), attribute_value=str(value), ) for name, value in resource.attributes.items() if value is not None ] for child_resource in resource.extract_sub_resources(): # skip modules and sub modules without children if self._filter_empty_modules and is_module_without_children( child_resource ): continue child_details = self._build_branch(child_resource) autoload_details.resources.extend(child_details.resources) autoload_details.attributes.extend(child_details.attributes) return autoload_details
def _get_module_ixn(self, module_id, module): """ Get module resource and attributes. """ relative_address = 'M' + str(module_id) resource = AutoLoadResource(model='Generic Traffic Generator Module', name='Module' + str(module_id), relative_address=relative_address) self.resources.append(resource) self.attributes.append( AutoLoadAttribute( relative_address=relative_address, attribute_name='Model', attribute_value=module.attributes['description'])) self.attributes.append( AutoLoadAttribute(relative_address=relative_address, attribute_name='Serial Number', attribute_value='')) self.attributes.append( AutoLoadAttribute(relative_address=relative_address, attribute_name='Version', attribute_value='')) for port_id, port in module.ports.items(): self._get_port_ixn(relative_address, port_id, port)
def autoload_resource(self): return AutoLoadResource(self.model, self.name, self.relative_address, self.unique_identifier)
def get_inventory(self, context): """ Discovers the resource structure and attributes. :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 """ # See below some example code demonstrating how to return the resource structure # and attributes. In real life, of course, if the actual values are not static, # this code would be preceded by some SNMP/other calls to get the actual resource information ''' # Add sub resources details sub_resources = [ AutoLoadResource(model ='Generic Chassis',name= 'Chassis 1', relative_address='1'), AutoLoadResource(model='Generic Module',name= 'Module 1',relative_address= '1/1'), AutoLoadResource(model='Generic Port',name= 'Port 1', relative_address='1/1/1'), AutoLoadResource(model='Generic Port', name='Port 2', relative_address='1/1/2'), AutoLoadResource(model='Generic Power Port', name='Power Port', relative_address='1/PP1')] attributes = [ AutoLoadAttribute(relative_address='', attribute_name='Location', attribute_value='Santa Clara Lab'), AutoLoadAttribute('', 'Model', 'Catalyst 3850'), AutoLoadAttribute('', 'Vendor', 'Cisco'), AutoLoadAttribute('1', 'Serial Number', 'JAE053002JD'), AutoLoadAttribute('1', 'Model', 'WS-X4232-GB-RJ'), AutoLoadAttribute('1/1', 'Model', 'WS-X4233-GB-EJ'), AutoLoadAttribute('1/1', 'Serial Number', 'RVE056702UD'), AutoLoadAttribute('1/1/1', 'MAC Address', 'fe80::e10c:f055:f7f1:bb7t16'), AutoLoadAttribute('1/1/1', 'IPv4 Address', '192.168.10.7'), AutoLoadAttribute('1/1/2', 'MAC Address', 'te67::e40c:g755:f55y:gh7w36'), AutoLoadAttribute('1/1/2', 'IPv4 Address', '192.168.10.9'), AutoLoadAttribute('1/PP1', 'Model', 'WS-X4232-GB-RJ'), AutoLoadAttribute('1/PP1', 'Port Description', 'Power'), AutoLoadAttribute('1/PP1', 'Serial Number', 'RVE056702UD')] return AutoLoadDetails(sub_resources,attributes) ''' ssh, channel, _ = self._connect(context) sub_resources = [] attributes = [AutoLoadAttribute('', "Vendor", 'Gigamon')] for line in self._ssh_command(context, ssh, channel, 'show version', '[^[#]# ').split('\n'): if 'Version summary:' in line: attributes.append( AutoLoadAttribute( '', "OS Version", line.replace('Version summary:', '').strip())) if 'Product model:' in line: m = line.replace('Product model:', '').strip() m = { 'gvcc2': 'GigaVUE-HD8', }.get(m, m) attributes.append(AutoLoadAttribute('', "Model", m)) chassisaddr = 'bad_chassis_addr' patt2attr = {} for line in self._ssh_command(context, ssh, channel, 'show chassis', '[^[#]# ').split('\n'): if 'Box ID' in line: chassisaddr = line.replace('Box ID', '').replace(':', '').replace('*', '').strip() if chassisaddr == '-': continue sub_resources.append( AutoLoadResource(model='Generic Chassis', name='Chassis ' + chassisaddr, relative_address=chassisaddr)) patt2attr = {'HW Type': 'Model', 'Serial Num': 'Serial Number'} for patt in list(patt2attr.keys()): if patt in line: attributes.append( AutoLoadAttribute( chassisaddr, patt2attr[patt], line.replace(patt, '').replace(':', '').strip())) patt2attr.pop(patt, None) chassisaddr = 'bad_chassis_addr' for line in self._ssh_command(context, ssh, channel, 'show card', '[^[#]# ').split('\n'): if 'Oper Status' in line: continue if 'Box ID' in line: chassisaddr = line.replace('Box ID', '').replace(':', '').replace('*', '').strip() if chassisaddr.lower() == 'not configured': chassisaddr = 'bad_chassis_addr' # 1 yes up PRT-HC0-X24 132-00BD 1BD0-0189 A1-a2 m = re.match( r'(?P<slot>\S+)\s+' r'(?P<config>\S+)\s+' r'(?P<oper_status>\S+)\s+' r'(?P<hw_type>\S+)\s+' r'(?P<product_code>\S+)\s+' r'(?P<serial_num>\S+)\s+' r'(?P<hw_rev>\S+)', line) if m and chassisaddr != 'bad_chassis_addr': d = m.groupdict() cardaddr = chassisaddr + '/' + d['slot'] sub_resources.append( AutoLoadResource(model='Generic Module', name='Card ' + d['slot'], relative_address=cardaddr)) attributes.append( AutoLoadAttribute(cardaddr, "Model", d['hw_type'] + ' - ' + d['product_code'])) attributes.append( AutoLoadAttribute(cardaddr, "Version", d['hw_rev'])) attributes.append( AutoLoadAttribute(cardaddr, "Serial Number", d['serial_num'])) try: o = self._ssh_command(context, ssh, channel, 'show port alias', '[^[#]# ') except Exception as e: if 'no port alias configured' not in str( e) and 'no chassis configured' not in str(e): raise e o = '' addr2alias = {} if o: o = o.replace('\r', '') # self.log('o1=<<<' + o + '>>>') o = '\n'.join(o.split('----\n')[1:]).split('\n----')[0] for aliasline in o.split('\n'): m = re.match( r'(?P<address>\S+)\s+' r'(?P<type>\S+)\s+' r'(?P<alias>\S.*)', aliasline) if not m: continue d = m.groupdict() addr2alias[d['address']] = d['alias'] self._fulladdr2alias = {} try: o = self._ssh_command(context, ssh, channel, 'show port', '[^[#]# ') except Exception as e: if 'no chassis configured' not in str(e): raise e o = '' if o: o = o.replace('\r', '') # self.log('o1=<<<' + o + '>>>') o = '\n'.join(o.split('----\n')[1:]).split('\n----')[0] # self.log('o2=<<<' + o + '>>>') for portline in o.split('\n'): m = re.match( r'(?P<address>\S+)\s+' r'(?P<type>\S+)\s+' r'(?P<alias>\S+)\s+' r'(?P<admin_enabled>enabled|disabled)\s+' r'(?P<link_status>down|up|-)\s+' r'(?P<min_max_thld_power>[-0-9. ]+)\s+' r'(?P<xcvr_type>.+)\s+' r'(?P<auto_neg>on|off|N/A)\s+' r'(?P<speed>[-0-9]+)\s+' r'(?P<duplex>\S+)\s+' r'(?P<force_up>on|off)\s+' r'(?P<port_relay>\S+)\s*' r'(?P<discovery>\S*)', portline) if not m: m = re.match( r'(?P<address>\S+)\s+' r'(?P<type>\S+)\s+' r'(?P<admin_enabled>enabled|disabled)\s+' r'(?P<link_status>down|up|-)\s+' r'(?P<min_max_thld_power>[-0-9. ]+)\s+' r'(?P<xcvr_type>.+)\s+' r'(?P<auto_neg>on|off|N/A)\s+' r'(?P<speed>[-0-9]+)\s+' r'(?P<duplex>\S+)\s+' r'(?P<force_up>on|off)\s+' r'(?P<port_relay>\S+)\s*' r'(?P<discovery>\S*)', portline) if not m: if portline: self._log( context, 'regex failure on line <<<' + portline + '>>>') continue # raise Exception('Failed to parse "show port" data: Line: <<<%s>>> All output: <<<%s>>>' % (portline, o)) d = m.groupdict() portaddr = d['address'] portnum = portaddr.split('/')[-1] self._log(context, 'Port ' + portaddr) sub_resources.append( AutoLoadResource(model='Generic Port', name='Port ' + portnum, relative_address=portaddr)) attributes.append( AutoLoadAttribute(portaddr, "Port Role", d['type'].strip())) if portaddr in addr2alias: attributes.append( AutoLoadAttribute(portaddr, "Alias", addr2alias[portaddr])) self._fulladdr2alias[context.resource.address + '/' + portaddr] = addr2alias[portaddr] else: attributes.append(AutoLoadAttribute(portaddr, "Alias", '')) attributes.append( AutoLoadAttribute(portaddr, "Transceiver Type", d['xcvr_type'].strip())) if re.match(r'[0-9]+', d['speed']): attributes.append( AutoLoadAttribute(portaddr, "Bandwidth", d['speed'])) attributes.append( AutoLoadAttribute( portaddr, "Duplex", 'Full' if d['duplex'] == 'full' else 'Half')) attributes.append( AutoLoadAttribute( portaddr, "Auto Negotiation", 'True' if d['auto_neg'] == 'on' else 'False')) rv = AutoLoadDetails(sub_resources, attributes) for res in rv.resources: self._log( context, 'model=%s name=%s address=%s uniqueid=%s' % (res.model, res.name, res.relative_address, res.unique_identifier)) for attr in rv.attributes: self._log( context, '%s: %s = %s' % (attr.relative_address, attr.attribute_name, attr.attribute_value)) self._disconnect(context, ssh, channel) return rv
def get_inventory(self, context): """ Discovers the resource structure and attributes. :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 """ # See below some example code demonstrating how to return the resource structure # and attributes. In real life, of course, if the actual values are not static, # this code would be preceded by some SNMP/other calls to get the actual resource information ''' # Add sub resources details sub_resources = [ AutoLoadResource(model ='Generic Chassis',name= 'Chassis 1', relative_address='1'), AutoLoadResource(model='Generic Module',name= 'Module 1',relative_address= '1/1'), AutoLoadResource(model='Generic Port',name= 'Port 1', relative_address='1/1/1'), AutoLoadResource(model='Generic Port', name='Port 2', relative_address='1/1/2'), AutoLoadResource(model='Generic Power Port', name='Power Port', relative_address='1/PP1')] attributes = [ AutoLoadAttribute(relative_address='', attribute_name='Location', attribute_value='Santa Clara Lab'), AutoLoadAttribute('', 'Model', 'Catalyst 3850'), AutoLoadAttribute('', 'Vendor', 'Cisco'), AutoLoadAttribute('1', 'Serial Number', 'JAE053002JD'), AutoLoadAttribute('1', 'Model', 'WS-X4232-GB-RJ'), AutoLoadAttribute('1/1', 'Model', 'WS-X4233-GB-EJ'), AutoLoadAttribute('1/1', 'Serial Number', 'RVE056702UD'), AutoLoadAttribute('1/1/1', 'MAC Address', 'fe80::e10c:f055:f7f1:bb7t16'), AutoLoadAttribute('1/1/1', 'IPv4 Address', '192.168.10.7'), AutoLoadAttribute('1/1/2', 'MAC Address', 'te67::e40c:g755:f55y:gh7w36'), AutoLoadAttribute('1/1/2', 'IPv4 Address', '192.168.10.9'), AutoLoadAttribute('1/PP1', 'Model', 'WS-X4232-GB-RJ'), AutoLoadAttribute('1/PP1', 'Port Description', 'Power'), AutoLoadAttribute('1/PP1', 'Serial Number', 'RVE056702UD')] return AutoLoadDetails(sub_resources,attributes) ''' resources = [] attributes = [] attributes.append( AutoLoadAttribute('', 'replication_address', self.get_replication_address(context))) attributes.append( AutoLoadAttribute('', 'connection_key', self.get_connection_key(context))) networks = self._get_newtork_interfaces(context) controllers = self._get_controllers(context) ports = self._get_ports(context) model = None for controller in controllers: resources.append( AutoLoadResource(model='Generic Storage Controller', name=controller['name'], relative_address=controller['name'])) if model is None: model = controller['model'] attributes.append(AutoLoadAttribute('', 'Model', model)) for network in networks: net_name = network['name'] controller = net_name.split('.')[0] if 'vir0' in controller or 'vir1' in controller: attributes.append( AutoLoadAttribute('', str(controller + '_address'), str(network['address']))) continue if 'management' not in network['services']: continue resources.append( AutoLoadResource(model='Storage Network Port', name=net_name, relative_address=controller.upper() + '/' + network['address'])) for port in ports: if port['iqn'] is not None: port_name = port['name'] controller = port_name.split('.')[0] resources.append( AutoLoadResource(model='iSCSI Storage Port', name=port['name'], relative_address=controller + '/' + port['portal'])) attributes.append( AutoLoadAttribute(controller + '/' + port['portal'], 'iqn', port['iqn'])) elif port['wwn'] is not None: port_name = port['name'] controller = port_name.split('.')[0] resources.append( AutoLoadResource(model='FC Storage Port', name=port['name'], relative_address=controller + '/' + port['name'].split('.')[1])) attributes.append( AutoLoadAttribute( controller + '/' + port['name'].split('.')[1], 'wwn', port['wwn'])) return AutoLoadDetails(resources, attributes)
def makeres(self, name, model, relative_address, unique_identifier): return AutoLoadResource(name=name, model=model, relative_address=relative_address, unique_identifier=unique_identifier)
def set_result(self, relative_path, autoload_details): autoload_details.resources.append(AutoLoadResource()) autoload_details.attributes.append(build_attributes())
def get_inventory(self, context): """ Will locate vm in vcenter and fill its uuid """ logger = get_logger_with_thread_id(context) logger.info("Start Autoload process") session = self.cs_helper.get_session( context.connectivity.server_address, context.connectivity.admin_auth_token, self.DOMAIN) vcenter_vblade = context.resource.attributes[ "{}.vFirewall vCenter VM".format(self.SHELL_NAME)].replace( "\\", "/") vcenter_name = context.resource.attributes["{}.vCenter Name".format( self.SHELL_NAME)] logger.info("Start AutoLoading VM_Path: {0} on vCenter: {1}".format( vcenter_vblade, vcenter_name)) vcenter_api_res = session.GetResourceDetails(vcenter_name) vcenter_resource = self.model_parser.convert_to_vcenter_model( vcenter_api_res) si = None try: logger.info("Connecting to vCenter ({0})".format( vcenter_api_res.Address)) si = self._get_connection_to_vcenter(self.pv_service, session, vcenter_resource, vcenter_api_res.Address) logger.info("Loading VMs UUID") vm_loader = VMLoader(self.pv_service) vfw_uuid = vm_loader.load_vm_uuid_by_name(si, vcenter_resource, vcenter_vblade) logger.info("PanOS vFirewall VM UUID: {0}".format(vfw_uuid)) logger.info("Loading the IP of the PanOS vFirewall VM") vfw_ip = self._try_get_ip(self.pv_service, si, vfw_uuid, vcenter_resource, logger) if vfw_ip: session.UpdateResourceAddress(context.resource.name, vfw_ip) else: raise Exception( "Determination of PanOS vFirewall IP address failed." "Please, verify that VM is up and running") vm = self.pv_service.get_vm_by_uuid(si, vfw_uuid) phys_interfaces = [] for device in vm.config.hardware.device: if isinstance(device, vim.vm.device.VirtualEthernetCard): phys_interfaces.append(device) resources = [] attributes = [] for port_number, phys_interface in enumerate(phys_interfaces): if port_number == 0: # First interface (port number 0) should be Management continue network_adapter_number = phys_interface.deviceInfo.label.lower( ).strip("network adapter ") unique_id = hash(phys_interface.macAddress) relative_address = "P{}".format(port_number) resources.append( AutoLoadResource(model="{}.{}".format( self.SHELL_NAME, self.PORT_MODEL), name="Port {}".format(port_number), relative_address=relative_address, unique_identifier=unique_id)) attributes.append( AutoLoadAttribute( attribute_name="{}.{}.MAC Address".format( self.SHELL_NAME, self.PORT_MODEL), attribute_value=phys_interface.macAddress, relative_address=relative_address)) attributes.append( AutoLoadAttribute( attribute_name="{}.{}.Requested vNIC Name".format( self.SHELL_NAME, self.PORT_MODEL), attribute_value=network_adapter_number, relative_address=relative_address)) attributes.append( AutoLoadAttribute( attribute_name="{}.{}.Logical Name".format( self.SHELL_NAME, self.PORT_MODEL), attribute_value="Interface {}".format(port_number), relative_address=relative_address)) attributes.append( AutoLoadAttribute("", "VmDetails", self._get_vm_details(vfw_uuid, vcenter_name))) autoload_details = AutoLoadDetails(resources=resources, attributes=attributes) except Exception: logger.exception("Get inventory command failed") raise finally: if si: self.pv_service.disconnect(si) return autoload_details
def get_inventory(self, context): """ Will locate vm in vcenter and fill its uuid :type context: cloudshell.shell.core.context.ResourceCommandContext """ logger = get_logger_with_thread_id(context) logger.info("Start Autoload process") # session = self.cs_helper.get_session(context.connectivity.server_address, # context.connectivity.admin_auth_token, # self.DOMAIN) session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=self.DOMAIN) vcenter_vblade = context.resource.attributes[ "{}.vBlade vCenter VM".format(self.SHELL_NAME)].replace("\\", "/") vcenter_vchassis = context.resource.attributes[ "{}.vChassis vCenter VM".format(self.SHELL_NAME)].replace( "\\", "/") username = context.resource.attributes["{}.User".format( self.SHELL_NAME)] password = self._decrypt_password( session, context.resource.attributes["{}.Password".format(self.SHELL_NAME)]) vcenter_name = context.resource.attributes["{}.vCenter Name".format( self.SHELL_NAME)] logger.info("Start AutoLoading VM_Path: {0} on vCenter: {1}".format( vcenter_vblade, vcenter_name)) vcenter_api_res = session.GetResourceDetails(vcenter_name) vcenter_resource = self.model_parser.convert_to_vcenter_model( vcenter_api_res) si = None try: logger.info("Connecting to vCenter ({0})".format( vcenter_api_res.Address)) si = self._get_connection_to_vcenter(self.pv_service, session, vcenter_resource, vcenter_api_res.Address) logger.info("Loading VMs UUID") vm_loader = VMLoader(self.pv_service) vchassis_uuid = vm_loader.load_vm_uuid_by_name( si, vcenter_resource, vcenter_vchassis) logger.info("vChassis VM UUID: {0}".format(vchassis_uuid)) logger.info("Loading the IP of the vChassis VM") vchassis_ip = self._try_get_ip(self.pv_service, si, vchassis_uuid, vcenter_resource, logger) if vchassis_ip: bp_api = BP_API(ip=vchassis_ip, username=username, password=password, logger=logger) bp_api.login() modules_position = { module[self.IP_KEY]: module[self.ID_KEY] for module in bp_api.get_modules() if module[self.IP_KEY] } bp_api.logout() logger.debug("Modules position: {}".format(modules_position)) else: raise Exception( "Determination of vChassis IP address failed. Please, verify that VM is up and running" ) vblade_uuid = vm_loader.load_vm_uuid_by_name( si, vcenter_resource, vcenter_vblade) logger.info("vBlade VM UUID: {0}".format(vblade_uuid)) logger.info("Loading the IP of the vBlade VM") vblade_ip = self._try_get_ip(self.pv_service, si, vblade_uuid, vcenter_resource, logger) if vblade_ip: module_id = modules_position.get(vblade_ip) if module_id is None: raise Exception( "Provided vBlade IP incorrect or vBlade isn't connect to vChassis" ) session.UpdateResourceAddress( context.resource.name, "{blade_ip}\{chassis_ip}\M{module_id}".format( blade_ip=vblade_ip, chassis_ip=vchassis_ip, module_id=module_id)) else: raise Exception( "Determination of vBlade IP address failed. Please, verify that VM is up and running" ) vm = self.pv_service.get_vm_by_uuid(si, vblade_uuid) phys_interfaces = [] for device in vm.config.hardware.device: if isinstance(device, vim.vm.device.VirtualEthernetCard): phys_interfaces.append(device) resources = [] attributes = [] for port_number, phys_interface in enumerate(phys_interfaces): if port_number == 0: # First interface (port number 0) should be Management continue network_adapter_number = phys_interface.deviceInfo.label.lower( ).strip("network adapter ") unique_id = hash(phys_interface.macAddress) relative_address = "P{}".format(port_number) resources.append( AutoLoadResource(model="{}.{}".format( self.SHELL_NAME, self.PORT_MODEL), name="Port {}".format(port_number), relative_address=relative_address, unique_identifier=unique_id)) attributes.append( AutoLoadAttribute( attribute_name="{}.{}.MAC Address".format( self.SHELL_NAME, self.PORT_MODEL), attribute_value=phys_interface.macAddress, relative_address=relative_address)) attributes.append( AutoLoadAttribute( attribute_name="{}.{}.Requested vNIC Name".format( self.SHELL_NAME, self.PORT_MODEL), attribute_value=network_adapter_number, relative_address=relative_address)) attributes.append( AutoLoadAttribute( attribute_name="{}.{}.Logical Name".format( self.SHELL_NAME, self.PORT_MODEL), attribute_value="Interface {}".format(port_number), relative_address=relative_address)) attributes.append( AutoLoadAttribute( "", "VmDetails", self._get_vm_details(vblade_uuid, vcenter_name))) autoload_details = AutoLoadDetails(resources=resources, attributes=attributes) except Exception: logger.exception("Get inventory command failed") raise finally: if si: self.pv_service.disconnect(si) return autoload_details