def _get_chassis(self, chassis): self.attributes.append( AutoLoadAttribute( relative_address='', attribute_name='CS_TrafficGeneratorChassis.Model Name', attribute_value=chassis.c_info['c_model'])) self.attributes.append( AutoLoadAttribute( relative_address='', attribute_name='Xena Chassis Shell 2G.Serial Number', attribute_value=chassis.c_info['c_serialno'])) self.attributes.append( AutoLoadAttribute( relative_address='', attribute_name='Xena Chassis Shell 2G.Server Description', attribute_value='')) self.attributes.append( AutoLoadAttribute( relative_address='', attribute_name='CS_TrafficGeneratorChassis.Vendor', attribute_value='Xena')) self.attributes.append( AutoLoadAttribute( relative_address='', attribute_name='CS_TrafficGeneratorChassis.Version', attribute_value=chassis.c_info['c_versionno'])) for module_id, module in chassis.modules.items(): self._get_module(module_id, module)
def _get_chassis_ixos(self, chassis): """ Get chassis resource and attributes. """ self.attributes.append( AutoLoadAttribute(relative_address='', attribute_name='Model', attribute_value=chassis.typeName)) self.attributes.append( AutoLoadAttribute(relative_address='', attribute_name='Serial Number', attribute_value='')) self.attributes.append( AutoLoadAttribute(relative_address='', attribute_name='Server Description', attribute_value='')) self.attributes.append( AutoLoadAttribute(relative_address='', attribute_name='Vendor', attribute_value='Ixia')) self.attributes.append( AutoLoadAttribute(relative_address='', attribute_name='Version', attribute_value=chassis.ixServerVersion)) for card_id, card in chassis.cards.items(): self._get_module_ixos(card_id, card)
def _get_module(self, module_id, module): """ Get module resource and attributes. """ relative_address = 'M' + str(module_id) model = 'Xena Chassis Shell 2G.GenericTrafficGeneratorModule' resource = AutoLoadResource(model=model, name='Module' + str(module_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=module.m_info['m_model'])) self.attributes.append( AutoLoadAttribute(relative_address=relative_address, attribute_name=model + '.Serial Number', attribute_value=module.m_info['m_serialno'])) self.attributes.append( AutoLoadAttribute(relative_address=relative_address, attribute_name=model + '.Version', attribute_value=module.m_info['m_versionno'])) for port_id, port in module.ports.items(): self._get_port(relative_address, port_id, port)
def _get_chassis_ixn(self, chassis): self.attributes.append( AutoLoadAttribute( relative_address='', attribute_name='Model', attribute_value=chassis.attributes['chassisType'])) self.attributes.append( AutoLoadAttribute(relative_address='', attribute_name='Serial Number', attribute_value='')) self.attributes.append( AutoLoadAttribute(relative_address='', attribute_name='Server Description', attribute_value='')) self.attributes.append( AutoLoadAttribute(relative_address='', attribute_name='Vendor', attribute_value='Ixia')) self.attributes.append( AutoLoadAttribute( relative_address='', attribute_name='Version', attribute_value=chassis.attributes['chassisVersion'])) for module_id, module in chassis.cards.items(): self._get_module_ixn(module_id, module)
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 number_of_ports = int(context.resource.attributes[ATTR_NUMBER_OF_PORTS]) + 1 resources = [] attributes = [] for i in range(number_of_ports): address = str(i) attributes.append(AutoLoadAttribute(address, 'Requested vNIC Name', 'Network adapter ' + str(i + 1))) if i == 0: port_name = IXIA_MANAGEMENT_PORT else: port_name = 'Port ' + address attributes.append(AutoLoadAttribute(address, ATTR_LOGICAL_NAME, address)) resources.append(AutoLoadResource(model=MODEL_PORT, name=port_name, relative_address=address)) return AutoLoadDetails(resources, attributes)
def _get_endpoint(self, endpoint): """ Get endpoint resource and attributes. """ relative_address = 'EP' + endpoint.name.encode('utf-8') model = 'IxChariot Server Shell 2G.GenericTrafficGeneratorModule' self.resources.append( AutoLoadResource(model=model, name=endpoint.name.encode('utf-8'), relative_address=relative_address)) self.attributes.append( AutoLoadAttribute( relative_address=relative_address, attribute_name='CS_TrafficGeneratorModule.Model Name', attribute_value='IxChariot Endpoint')) self.attributes.append( AutoLoadAttribute(relative_address=relative_address, attribute_name=model + '.Management IP', attribute_value=endpoint.managementIp.address)) self.attributes.append( AutoLoadAttribute(relative_address=relative_address, attribute_name=model + '.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_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 :rtype: AutoLoadDetails """ session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain="Global") pw = session.DecryptPassword( context.resource.attributes['Password']).Value un = context.resource.attributes["User"] ip = context.resource.address port = str(context.resource.attributes["API Port"]) prefix = str(context.resource.attributes["API Access"]) url = prefix + "://" + ip + ":" + port + "/api" sub_resources = [] attributes = [ AutoLoadAttribute('', 'Model', 'Ixia 58xx'), AutoLoadAttribute('', 'Vendor', 'Ixia') ] # get all ports requests.packages.urllib3.disable_warnings(InsecureRequestWarning) portsRequest = requests.get(url + '/ports', auth=HTTPBasicAuth(un, pw), verify=False) portsObj = json.loads(portsRequest.text) # loop thru each port and learn more for port in portsObj: portRequest = requests.get(url + '/ports/' + str(port['id']), auth=HTTPBasicAuth(un, pw), verify=False) portObj = json.loads(portRequest.text) sub_resources.append( AutoLoadResource(model='NTO Port', name=portObj['default_name'], relative_address=str(port['id']))) attributes.append( AutoLoadAttribute(str(port['id']), 'Port Speed', portObj['media_type'])) attributes.append( AutoLoadAttribute(str(port['id']), 'Serial Number', portObj['uuid'])) attributes.append( AutoLoadAttribute( str(port['id']), 'Port Description', str(portObj['name']) + " " + str(portObj['description']))) return AutoLoadDetails(sub_resources, attributes) pass
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 ip_address = context.resource.address if not ip_address or ip_address == "NA": return AutoLoadDetails([], []) else: username = context.resource.attributes["User"] api = get_api(context) password = api.DecryptPassword( context.resource.attributes["Password"]).Value autoload_operations = CiscoTRexAutoloadRunner( cli=self._cli, resource_address=ip_address, username=username, password=password) trex_ports = autoload_operations.trex_autoload_ports() resources = [] attributes = [] # Add TRex Management port attributes.append( AutoLoadAttribute("0", "Requested vNIC Name", "Network adapter 1")) resources.append( AutoLoadResource(model=MODEL_PORT, name=MANAGEMENT_PORT, relative_address="0")) # Add TRex test ports for i, uid in enumerate(trex_ports, start=1): address = str(i) attributes.append( AutoLoadAttribute( address, "Requested vNIC Name", "Network adapter {id}".format(id=str(i + 1)))) # attributes.append(AutoLoadAttribute(address, "TRex Port UID", uid)) attributes.append( AutoLoadAttribute(address, ATTR_LOGICAL_NAME, address)) resources.append( AutoLoadResource(model=MODEL_PORT, name="Port {}".format(address), relative_address=address)) return AutoLoadDetails(resources, attributes)
def _build_autoload_details(self, autoload_data, relative_path=""): """ Build autoload details :param autoload_data: dict: :param relative_path: str: full relative path of current autoload resource """ self._autoload_details.attributes.extend([ AutoLoadAttribute(relative_address=relative_path, attribute_name=attribute_name, attribute_value=attribute_value) for attribute_name, attribute_value in autoload_data.attributes.iteritems() ]) for resource_relative_path, resource in self._validate_build_resource_structure( autoload_data.resources).iteritems(): full_relative_path = posixpath.join(relative_path, resource_relative_path) self._autoload_details.resources.append( AutoLoadResource(model=resource.cloudshell_model_name, name=resource.name, relative_address=full_relative_path, unique_identifier=resource.unique_identifier)) self._build_autoload_details(autoload_data=resource, relative_path=full_relative_path)
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_attributes(self, relative_address, attributes): """ Get attributes. """ for attribute_name, attribute_value in attributes.items(): self.attributes.append( AutoLoadAttribute(relative_address=relative_address, attribute_name=attribute_name, attribute_value=attribute_value))
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_attributes(self): result = [] for name, value in self.attributes.items(): result.append( AutoLoadAttribute( relative_address=self.relative_address, attribute_name=name, attribute_value=value, )) return result
def get_inventory(self): handler = self._get_handler() try: metadata = handler.getMetaData() except HttpException as e: if 'unauthorized' in e.message.lower(): error_msg = 'User is unauthorized to access PDU. Check if username and or password valid' else: error_msg = 'Unable to access PDU. Check if PDU address is valid.' raise Exception(error_msg) resources = self._autoload_resources_by_rpc() attributes = [ AutoLoadAttribute('', 'Firmware Version', metadata.fwRevision), AutoLoadAttribute('', 'Vendor', metadata.nameplate.manufacturer), AutoLoadAttribute('', 'Model', metadata.nameplate.model) ] result = AutoLoadDetails(resources, attributes) return result
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 _get_server(self, session): """ Get server resource and attributes. """ self.attributes.append(AutoLoadAttribute(relative_address='', attribute_name='Vendor', attribute_value='Ixia')) endpoints = session.parentConvention.httpGet("ixchariot/resources/endpoint") for endpoint in endpoints: self.logger.info('endpoint = {}'.format(endpoint)) self._get_endpoint(endpoint)
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_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") vcenter_vm_name = context.resource.attributes["{}.vCenter VM".format(self.SHELL_NAME)] vcenter_vm_name = vcenter_vm_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_vm_name, vcenter_name)) # 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_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 VM UUID") vm_loader = VMLoader(self.pv_service) uuid = vm_loader.load_vm_uuid_by_name(si, vcenter_resource, vcenter_vm_name) logger.info("VM UUID: {0}".format(uuid)) logger.info("Loading the IP of the VM") ip = self._try_get_ip(self.pv_service, si, uuid, vcenter_resource, logger) if ip: session.UpdateResourceAddress(context.resource.name, ip) autoload_atts = [AutoLoadAttribute("", "VmDetails", self._get_vm_details(uuid, vcenter_name))] return AutoLoadDetails([], autoload_atts) except Exception: logger.exception("Get inventory command failed") raise finally: if si: self.pv_service.disconnect(si)
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(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_inventory(self, context): """ Return device structure with all standard attributes :type context: cloudshell.shell.core.driver_context.AutoLoadCommandContext :rtype: cloudshell.shell.core.driver_context.AutoLoadDetails """ resource_config = GenericTrafficChassisResource.from_context( self.SHELL_NAME, self.SUPPORTED_OS, context) logger = get_logger_with_thread_id(context) api = get_api(context) autoload_runner = BPAutoloadRunner(resource_config, self.SHELL_NAME, api, logger) auto_load_details = autoload_runner.discover() # Here comes PS... address = context.resource.address user = context.resource.attributes['{}.User'.format( PerfectStorm2GDriver.SHELL_NAME)] encripted_password = context.resource.attributes['{}.Password'.format( PerfectStorm2GDriver.SHELL_NAME)] password = get_api(context).DecryptPassword(encripted_password).Value import paramiko self.ssh = paramiko.SSHClient() self.ssh.load_system_host_keys() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname=address, username=user, password=password) self.chan = self.ssh.invoke_shell() self.ssh_call('bpsh') self.ssh_call('set chassis [$bps getChassis]') modules = {} for resource in auto_load_details.resources: if resource.model == '{}.GenericTrafficGeneratorModule'.format( PerfectStorm2GDriver.SHELL_NAME): relative_address = resource.relative_address modules[relative_address] = self.ssh_call( '$chassis getCardMode ' + relative_address[1:]).split()[0] for resource in auto_load_details.resources: if resource.model == '{}.GenericTrafficGeneratorPort'.format( PerfectStorm2GDriver.SHELL_NAME): port_module = resource.relative_address.split('/')[0] if port_module in modules.keys(): auto_load_details.attributes.append( AutoLoadAttribute( relative_address=resource.relative_address, attribute_name= 'CS_TrafficGeneratorPort.Configured Controllers', attribute_value=modules[port_module])) return auto_load_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='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_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 _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 _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_inventory(self, context): """ Return device structure with all standard attributes :type context: cloudshell.shell.core.driver_context.AutoLoadCommandContext :rtype: cloudshell.shell.core.driver_context.AutoLoadDetails """ auto_load_details = self.autoload_runner.discover() address = context.resource.address user = context.resource.attributes['User'] password = get_api(context).DecryptPassword( context.resource.attributes['Password']).Value import paramiko self.ssh = paramiko.SSHClient() self.ssh.load_system_host_keys() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname=address, username=user, password=password) self.chan = self.ssh.invoke_shell() self.ssh_call('bpsh') self.ssh_call('set chassis [$bps getChassis]') modules = {} for resource in auto_load_details.resources: if resource.model == 'Generic Traffic Generator Module': relative_address = resource.relative_address modules[relative_address] = self.ssh_call( '$chassis getCardMode ' + relative_address[1:]).split()[0] for resource in auto_load_details.resources: if resource.model == 'Generic Traffic Generator Port': port_module = resource.relative_address.split('/')[0] if port_module in modules.keys(): auto_load_details.attributes.append( AutoLoadAttribute( relative_address=resource.relative_address, attribute_name='Supported Controller', attribute_value=modules[port_module])) return auto_load_details
def makeattr(self, relative_address, attribute_name, attribute_value): return AutoLoadAttribute(relative_address=relative_address, attribute_name=attribute_name, attribute_value=attribute_value)
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)