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)
Esempio n. 2
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
Esempio n. 3
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)
    def discover(self):
        validation_actions = ValidationActions(azure_client=self._azure_client,
                                               logger=self._logger)

        validation_actions.register_azure_providers()
        validation_actions.validate_azure_region(
            region=self._resource_config.region)
        validation_actions.validate_azure_mgmt_resource_group(
            mgmt_resource_group_name=self._resource_config.
            management_group_name,
            region=self._resource_config.region,
        )

        validation_actions.validate_azure_sandbox_network(
            mgmt_resource_group_name=self._resource_config.
            management_group_name)

        validation_actions.validate_azure_vm_size(
            vm_size=self._resource_config.vm_size,
            region=self._resource_config.region)

        validation_actions.validate_azure_additional_networks(
            mgmt_networks=self._resource_config.additional_mgmt_networks)

        validation_actions.validate_custom_tags(
            custom_tags=self._resource_config.custom_tags)

        return AutoLoadDetails([], [])
Esempio n. 5
0
    def __init__(self, autoload_data):
        """
        :param autoload_data: dict(defaultdict(list)):
        """

        self.autoload_data = autoload_data
        self._autoload_details = AutoLoadDetails([], [])
Esempio n. 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, this code will be preceded by SNMP/other calls to the resource details and will not be static
        # run 'shellfoundry generate' in order to create classes that represent your data model

        '''
        resource = {{cookiecutter.model_name}}.create_from_context(context)
        resource.vendor = 'specify the shell vendor'
        resource.model = 'specify the shell model'

        chassis1 = GenericChassis('Chassis 1')
        chassis1.model = 'WS-X4232-GB-RJ'
        chassis1.serial_number = 'JAE053002JD'
        resource.add_sub_resource('1', chassis1)

        module1 = GenericModule('Module 1')
        module1.model = 'WS-X5561-GB-AB'
        module1.serial_number = 'TGA053972JD'
        chassis1.add_sub_resource('1', module1)

        port1 = GenericPort('Port 1')
        port1.mac_address = 'fe80::e10c:f055:f7f1:bb7t16'
        port1.ipv4_address = '192.168.10.7'
        module1.add_sub_resource('1', port1)

        return resource.create_autoload_details()
        '''
        return AutoLoadDetails([], [])
    def get_inventory(self, context):
        """
        Called when the cloud provider resource is created
        in the inventory.

        Method validates the values of the cloud provider attributes, entered by the user as part of the cloud provider resource creation.
        In addition, this would be the place to assign values programmatically to optional attributes that were not given a value by the user.

        If one of the validations failed, the method should raise an exception

        :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
        """

        with LoggingSessionContext(context) as logger:
            logger.info("Starting Autoload command...")
            api = CloudShellSessionContext(context).get_api()
            resource_config = KubernetesResourceConfig.from_context(
                shell_name=self.SHELL_NAME, context=context, api=api)
            api_clients = ApiClientsProvider(logger).get_api_clients(
                resource_config)
            autoload_flow = AutolaodFlow(api_clients)
            autoload_flow.validate_config(resource_config)

        return AutoLoadDetails([], [])
Esempio n. 8
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()
    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
        """
        logger = get_logger_with_thread_id(context)
        logger.info("Autoload command started")

        with ErrorHandlingContext(logger):
            resource_config = VyOSResource.from_context(context=context,
                                                        shell_type=SHELL_TYPE,
                                                        shell_name=SHELL_NAME)
            cs_api = get_api(context)

            if not resource_config.address or resource_config.address.upper(
            ) == "NA":
                logger.info("No IP configured, skipping Autoload")
                return AutoLoadDetails([], [])

            cli_handler = VyOSCliHandler(cli=self._cli,
                                         resource_config=resource_config,
                                         api=cs_api,
                                         logger=logger)

            if resource_config.config_file:
                self._execute_load_config_flow(resource_config=resource_config,
                                               cli_handler=cli_handler,
                                               cs_api=cs_api,
                                               logger=logger)

            return self._execute_autoload_flow(resource_config=resource_config,
                                               cli_handler=cli_handler,
                                               logger=logger)
Esempio n. 10
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
    def discover(self, ip, model, vendor, snmp_params):
        """
        :param str ip: The device IP address
        :param str model: The device model in CloudShell
        :param str vendor: The device vendor
        :param SNMPParams snmp_params: The device vendor
        :return: The loaded resources and attributes
        :rtype: AutoLoadDetails
        """

        logger = get_qs_logger()

        self.snmp = QualiSnmp(ip=ip, snmp_version=snmp_params.snmp_version,
                              snmp_user=snmp_params.snmp_v3_user,
                              snmp_password=snmp_params.snmp_v3_password,
                              snmp_community=snmp_params.snmp_read_community,
                              snmp_private_key=snmp_params.snmp_v3_privatekey,
                              logger=logger)


        self.attributes=[]
        self.exclusion_list=[]
        self.chassis_list=[]
        self.port_exclude_pattern='TEST'
        self.port_mapping ={}
        self.port_list =[]
        self.power_supply_list=[]
        self.entity_table_black_list=[]
        self._excluded_models = []
        self.relative_path = {}
        self.module_list = []
        self.resources = []

        self._get_device_details(model, vendor)
        self._load_snmp_tables()

        if(len(self.chassis_list)<1):
            print 'Empty Chasis List Found'
            exit(1)

        for chassis in self.chassis_list:
            if chassis not in self.exclusion_list:
                chassis_id = self._get_resource_id(chassis)
                if chassis_id == '-1':
                    chassis_id = '0'
                self.relative_path[chassis] = chassis_id
        # to add custom MIBSs
        #snmp_handler.update_mib_sources()

        self._filter_lower_bay_containers()
        self.get_module_list()
        self.add_relative_paths()
        self._get_chassis_attributes(self.chassis_list)
        self._get_ports_attributes()
        self._get_module_attributes()

        result = AutoLoadDetails(resources=self.resources, attributes=self.attributes)

        print result #an Object you can play with it
Esempio n. 12
0
 def get_inventory(self, context):
     """
     Autoload inventory
     Return device structure with all standard attributes
     :type context: cloudshell.shell.core.driver_context.AutoLoadCommandContext
     :rtype: cloudshell.shell.core.driver_context.AutoLoadDetails
     """
     return AutoLoadDetails([], [])
 def get_inventory(self, context: AutoLoadCommandContext) -> AutoLoadDetails:
     """Check connection to OpenStack."""
     with LoggingSessionContext(context) as logger:
         logger.info("Starting Autoload command")
         api = CloudShellSessionContext(context).get_api()
         conf = OSResourceConfig.from_context(self.SHELL_NAME, context, api)
         os_api = OSApi(conf, logger)
         validate_conf_and_connection(os_api, conf)
         return AutoLoadDetails([], [])
Esempio n. 14
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
     return AutoLoadDetails([], [])
    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
        """
        self.logger.info('inside get_inventory')
        # run 'shellfoundry generate' in order to create classes that represent your data model

        return AutoLoadDetails([], [])
    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
Esempio n. 17
0
    def get_inventory(self, context):
        """Discovers the resource structure and attributes.

        :param cloudshell.shell.core.driver_context.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: cloudshell.shell.core.driver_context.AutoLoadDetails
        """
        logger = get_logger_with_thread_id(context)
        logger.info('Autoload started')

        with ErrorHandlingContext(logger):
            return AutoLoadDetails([], [])
Esempio n. 18
0
 def discover(self):
     if not self._is_valid_device_os():
         raise Exception(
             self.__class__.__name__,
             'Unsupported device OS, see logs for more details')
     self._build_root_elements()
     self._build_chassis_elements()
     self._build_ports()
     self._build_port_channels()
     self._root.build_relative_path()
     autoload_details = AutoLoadDetails(self._root.get_resources(),
                                        self._root.get_attributes())
     return autoload_details
Esempio n. 19
0
    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
        """

        self.resources = []
        self.attributes = []
        self.xm.session.inventory()
        self._get_chassis(self.xm.session.chassis_list[self.address])
        details = AutoLoadDetails(self.resources, self.attributes)
        return details
Esempio n. 20
0
    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
        """

        self.resources = []
        self.attributes = []
        self.ixia.discover()
        self._get_chassis_ixos(self.ixia.chassis_chain.values()[0])
        details = AutoLoadDetails(self.resources, self.attributes)
        return details
Esempio n. 21
0
    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
        """

        self.attributes = []
        self.resources = []
        session = self.connection.createSession('ixchariot')
        session.startSession()
        self._get_server(session)

        return AutoLoadDetails(self.resources, self.attributes)
Esempio n. 22
0
    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)
Esempio n. 23
0
    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
        """

        self.resources = []
        self.attributes = []
        address = context.resource.address
        chassis = self.stc.hw.get_chassis(address)
        chassis.get_inventory()
        self._get_chassis(chassis)
        details = AutoLoadDetails(self.resources, self.attributes)
        return details
Esempio n. 24
0
    def autoload(self):
        rv = AutoLoadDetails(resources=[], attributes=[])

        sysobject = self.snmp_handler.get_property('SNMPv2-MIB',
                                                   'sysObjectID',
                                                   0,
                                                   return_type="str")
        if sysobject != 'Sentry3-MIB::sentry3':
            raise AssertionError("Device does not appear to be a Sentry3")

        rv.attributes.append(
            self.makeattr(
                '', 'CS_PDU.Location',
                self.snmp_handler.get_property('SNMPv2-MIB', 'sysLocation',
                                               0)))
        # rv.attributes.append(self.makeattr('', 'Location', self.snmp_handler.get_property('SNMPv2-MIB', 'systemLocation', 0)))
        rv.attributes.append(
            self.makeattr(
                '', 'CS_PDU.Model',
                self.snmp_handler.get_property('Sentry3-MIB',
                                               'towerModelNumber', 0)))
        rv.attributes.append(
            self.makeattr(
                '', 'SentryPdu.Serial Number',
                self.snmp_handler.get_property('Sentry3-MIB', 'towerProductSN',
                                               0)))
        rv.attributes.append(self.makeattr('', 'CS_PDU.Vendor', 'Sentry'))
        rv.attributes.append(
            self.makeattr(
                '', 'SentryPdu.System Version',
                self.snmp_handler.get_property('Sentry3-MIB', 'systemVersion',
                                               0)))

        pdu_name = self.snmp_handler.get_property('SNMPv2-MIB', 'sysName', 0)

        outlet_table = self.snmp_handler.get_table('Sentry3-MIB',
                                                   'outletTable')
        for index, attribute in outlet_table.iteritems():
            name = 'Outlet %s' % attribute['outletID']
            relative_address = index
            unique_identifier = '%s.%s' % (pdu_name, index)

            rv.resources.append(
                self.makeres(name, 'SentryPdu.PowerSocket', relative_address,
                             unique_identifier))
            #rv.attributes.append(self.makeattr(relative_address, 'CS_PowerSocket.Model Name', attribute['outletName']))

        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
     # run 'shellfoundry generate' in order to create classes that represent your data model
     '''
     resource = DeployedAppDemo.create_from_context(context)
     resource.vendor = 'Vendor'
     resource.model = 'Model'
     return resource.create_autoload_details()
     '''
     return AutoLoadDetails([], [])
Esempio n. 26
0
    def get_inventory(self, context):
        """  """

        with LoggingSessionContext(context) as logger:
            resource_config = ShellResource.create_from_context(context)

            logger.info("Configuration Templates Location: {path}"
                        "Username: {username}\n"
                        "Password: {password}\n"
                        "Host: {host}\n"
                        "STD: {std_port}\n"
                        "UWM: {uwm_port}".format(
                            path=resource_config.templates_path,
                            host=resource_config.address,
                            std_port=resource_config.std_port,
                            uwm_port=resource_config.uwm_port,
                            username=resource_config.username,
                            password=resource_config.password))

            if resource_config.templates_path and not os.path.exists(
                    resource_config.templates_path):
                msg = "Wrong path provided for device configuration templates"
                logger.error("{msg}. Provided path: {path}".format(
                    msg=msg, path=resource_config.templates_path))
                raise VIRLShellError(msg)

            virl_api = VIRL_API(host=resource_config.address,
                                std_port=resource_config.std_port,
                                uwm_port=resource_config.uwm_port,
                                username=resource_config.username,
                                password=resource_config.password)

            try:
                avail_networks = virl_api.get_all_avail_networks()
                if resource_config.mgmt_network not in avail_networks:
                    raise VIRLShellError(
                        "Provided Management Network <{mgmt_network}> doesn't exist. "
                        "Available networks: {avail_networks}".format(
                            mgmt_network=resource_config.mgmt_network,
                            avail_networks=avail_networks))
                # virl_api.health_check()
            except HTTPError as err:
                raise VIRLShellError(
                    "Can not connect to VIRL Server. Please, verify provided credentials."
                    "Error: {}".format(err))

            return AutoLoadDetails([], [])
Esempio n. 27
0
    def _get_autoload_details(self):
        """
        Read device structure and attributes:
        chassis, modules, submodules, ports, port-channels and power supplies

        :return: AutoLoadDetails object or Exception
        """

        if not self._is_valid_device_os():
            raise Exception("Unsupported device OS")

        self.logger.info("*" * 70)
        self.logger.info("Start SNMP discovery process .....")

        self.load_additional_mibs()
        self.snmp.update_mib_sources(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "mibs")))

        self.snmp.load_mib(["FOUNDRY-SN-AGENT-MIB", "FOUNDRY-SN-SWITCH-GROUP-MIB", "FOUNDRY-SN-STACKING-MIB",
                            "FOUNDRY-SN-IP-MIB"])

        self.lldp_local_table = self.snmp.get_table('LLDP-MIB', 'lldpLocPortDesc')
        self.lldp_remote_table = self.snmp.get_table('LLDP-MIB', 'lldpRemTable')
        self.ip_v4_table = self.snmp.get_table('IP-MIB', 'ipAddrTable')
        self.ip_v6_table = self.snmp.get_table('IPV6-MIB', 'ipv6AddrEntry')

        self._get_device_details()
        self._get_chassis_info()
        self._get_power_ports_info()
        self._get_modules_info()
        self._get_ports_info()

        result = AutoLoadDetails(resources=self.resources, attributes=self.attributes)
        self.logger.info("*" * 50)
        self.logger.info("SNMP discovery Completed.")
        self.logger.info("The following platform structure detected:\nModel, Name, Relative Path, Unique Id")

        for resource in self.resources:
            self.logger.info("{0},\t\t{1},\t\t{2},\t\t{3}".format(resource.model, resource.name,
                                                                  resource.relative_address, resource.unique_identifier))
        self.logger.info("-" * 30)
        for attribute in self.attributes:
            self.logger.info("{0},\t\t{1},\t\t{2}".format(attribute.relative_address, attribute.attribute_name,
                                                          attribute.attribute_value))
        self.logger.info("*" * 50)

        return result
Esempio n. 28
0
    def get_inventory(self, context):
        """
        Called when the cloud provider resource is created
        in the inventory.

        Method validates the values of the cloud provider attributes, entered by the user as part of the cloud provider resource creation.
        In addition, this would be the place to assign values programmatically to optional attributes that were not given a value by the user.

        If one of the validations failed, the method should raise an exception

        :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
        """

        # run 'shellfoundry generate' in order to create classes that represent your data model

        return AutoLoadDetails([], [])
    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, this code will be preceded by SNMP/other calls to the resource details and will not be static
        # run 'shellfoundry generate' in order to create classes that represent your data model

        '''
        resource = {{cookiecutter.model_name}}.create_from_context(context)
        resource.vendor = 'specify the shell vendor'
        resource.model = 'specify the shell model'

        return resource.create_autoload_details()
        '''
        return AutoLoadDetails([], [])
    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