Пример #1
0
    def get_inventory(self, context):
        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')]

        autoload_details = AutoLoadDetails(sub_resources,attributes)
        migrated_details = LegacyUtils().migrate_autoload_details(autoload_details, context)

        return migrated_details.create_autoload_details()
Пример #2
0
    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 _autoload_resources_by_rpc(self):
     resources = [
         AutoLoadResource('Generic Power Socket', 'Socket ' + str(x + 1),
                          str(x + 1))
         for x, val in enumerate(self.get_outlets())
     ]
     return resources
Пример #4
0
    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)
Пример #5
0
    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)
Пример #6
0
    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)
Пример #7
0
    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)
Пример #8
0
 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
Пример #9
0
    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
Пример #10
0
    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_resource(self):
     if self.name:
         return AutoLoadResource(
             model=self.resource_model,
             name=self.name,
             relative_address=self.relative_address,
             unique_identifier=self.unique_id,
         )
Пример #12
0
    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)
Пример #13
0
    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(':', '-')))
Пример #14
0
    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)
Пример #15
0
    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)
Пример #16
0
    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))
Пример #17
0
    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']))
Пример #18
0
    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))))
Пример #19
0
    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'))
Пример #20
0
    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)
Пример #21
0
    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'))
Пример #22
0
    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
Пример #24
0
    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 set_result(self, relative_path, autoload_details):
     autoload_details.resources.append(AutoLoadResource())
     autoload_details.attributes.append(build_attributes())
 def autoload_resource(self):
     return AutoLoadResource(self.model, self.name, self.relative_address,
                             self.unique_identifier)
Пример #27
0
    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)
Пример #29
0
    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
Пример #30
0
    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