def main():
    this_parser = argparse.ArgumentParser()
    populate_parser(this_parser)
    args = this_parser.parse_args()

    vservice = VlanService(db_name=DB_NAME)

    device_params = get_params_from_env()
    sw = cisco_switch(**device_params)

    if args.cmd is not None:
        cmd = args.cmd

        if cmd == "add":
            #add_vlan(args)
            tvlan = vlan(id=args.vlanid,
                         name=args.name,
                         description=args.description)
            vservice.add_vlan(vlan_obj=tvlan, device_obj=sw)

        elif cmd == "del":
            #del_vlan(args)
            vservice.del_vlan(vlan_id=args.vlanid, device_obj=sw)

        elif cmd == "dumpdb":
            vservice.dump_db(device_obj=sw)

        elif cmd == "checksync":
            sync = vservice.check_sync(device_obj=sw)

            print(f"In Sync = {sync.data}")
        elif cmd == "syncfrom":

            vservice.sync_from(device_obj=sw, )
        elif cmd == "syncto":
            vservice.sync_to(device_obj=sw)
        elif cmd == "dumprouter":
            vlan_result = vservice.get_vlans_from_device(device_obj=sw)
            if vlan_result.success:
                for id, vlanobj in vlan_result.data.items():
                    print(vlanobj.id, vlanobj.name)
            else:
                print(f"Error getting vlans from device: {vlan_result.errmsg}")

        elif cmd == "canmerge":

            mergeable_result = vservice.can_merge(device_obj=sw)
            print(f"Can merge == {mergeable_result.data}")

        elif cmd == "update":
            tvlan = vlan(id=args.vlanid,
                         name=args.name,
                         description=args.description)
            vservice.update_vlan(vlan_obj=tvlan, device_obj=sw)
        elif cmd == "merge":
            mresult = vservice.merge(device_obj=sw)
            print(
                f"Successful merge = {mresult.success}, {mresult.error}, {mresult.errmsg}"
            )
Beispiel #2
0
    def get_all_vlans_from_db(self):

        try:
            conn = sqlite3.connect(self.database_name)
            cur = conn.cursor()
            cur.execute("SELECT * FROM VLANS")
            rows = cur.fetchall()

            vlan_map = {}
            for row in rows:
                #import ipdb; ipdb.set_trace()
                vlan_map[row[0]] = vlan(id=row[0],
                                        name=row[1],
                                        description=row[2])

            #return vlan_map
            res = action_result(
                success=1,
                error=0,
            )
            res.data = vlan_map
            return res

        except Exception as err:
            logger.error(f"Error getting vlans from db")
            logger.error(repr(err))
            res = action_result(success=0, error=1, errmsg=repr(err))
            return res
Beispiel #3
0
def add_vlan(v: Vlan, vlanid):
    logger.info(f"adding vlan {vlanid} through api")
    this_vlan = vlan(id=v.id, name=v.name, description=v.description)

    vservice = VlanService(db_name=DB_URI)
    sw = cisco_switch(**get_params_from_env())
    add_result = vservice.add_vlan(vlan_obj=this_vlan, device_obj=sw)
    return add_result
Beispiel #4
0
def update_vlan(v: Vlan, vlanid):
    logger.info(f"Updating vlan {vlanid} in api")
    this_vlan = vlan(id=v.id, name=v.name, description=v.description)

    vservice = VlanService(db_name=DB_URI)
    sw = cisco_switch(**get_params_from_env())
    update_result = vservice.update_vlan(vlan_obj=this_vlan, device_obj=sw)
    return update_result
Beispiel #5
0
    def merge_from_device(self, device_obj, vlans: Optional[List] = None):
        """

        merge the vlans from the device into the database
        :param device_obj:
        :return:
        """
        logging.info("merge from device called")
        # now get list of vlans that are missing from the db.
        device_vlan_result = self.get_vlans_from_device(device_obj=device_obj)

        db_helper = VlanDatabaseHelper(db_name=self.database_name)
        db_vlan_result = db_helper.get_all_vlans_from_db()

        device_vlans = device_vlan_result.data
        db_vlans = db_vlan_result.data

        missing_from_db = []
        merge_vlans = []

        if vlans and len(vlans) > 0:
            for vid, vobj in device_vlans.items():
                if vid in vlans:
                    merge_vlans.append(vobj)

        else:
            merge_vlans = [vobj for _, vobj in device_vlans.items()]

        for vobj in merge_vlans:
            if vobj.id not in db_vlans.keys():
                logger.info(f"Flagging vlan {vobj.id} to be merged to db")
                missing_from_db.append(
                    vlan(id=vobj.id,
                         name=vobj.name,
                         description=vobj.description))

        if len(missing_from_db) == 0:
            logger.info("No vlans to merge from device to db")
            return action_result(success=1, error=0)

        for vlan_obj in missing_from_db:
            logger.info("Adding vlan {vlan_obj.id} to db for merge")
            db_helper.add_vlan_to_db(vlan_id=vlan_obj.id,
                                     vlan_name=vlan_obj.name,
                                     description=vlan_obj.description)

        return action_result(success=1, error=0)
Beispiel #6
0
    def get_vlans_from_device(self, device_obj=None):
        """
        Get the vlans from the device
        :param self:
        :param device_obj:
        :return:
        """
        logger.info("Getting vlans from device")
        vlan_command_dict = {
            "cisco_nxos": {
                "cmd":
                "show vlan",
                "textfsm_template":
                "textfsm_templates/cisco_nxos_show_vlan.textfsm"
            },
            "cisco_ios": {
                "cmd": "show vlans",
                "textfsm_template":
                "textfsm_templates/cisco_ios_show_vlan.textfsm"
            }
        }

        try:

            conn = get_device_driver(host_name=device_obj.hostname,
                                     username=device_obj.user,
                                     psswd=device_obj.psswd,
                                     device_type=device_obj.platform)

            cmd_detail = vlan_command_dict[device_obj.platform]
            cmd = cmd_detail['cmd']
            templ = cmd_detail['textfsm_template']

            c_path = os.path.dirname(
                os.path.abspath(sys.modules[self.__module__].__file__))
            pth = pathlib.Path(c_path)
            newpath = pth / templ
            logger.info(f"Current path = {c_path}")
            op = conn.send_command(cmd,
                                   use_textfsm=True,
                                   textfsm_template=newpath)
            logging.info(op)
            # hack.  the nxos is parsed as a dict instead of a list if thre
            # is only 1 vlan
            if isinstance(op, dict):
                op = [op]

            logger.info(op)
            configured_vlans = {}

            for vlandict in op:
                if isinstance(vlandict, dict):
                    configured_vlans[int(vlandict['vlan_id'])] = vlan(
                        id=int(vlandict['vlan_id']), name=vlandict['name'])

            res = action_result(
                success=1,
                error=0,
            )
            res.data = configured_vlans
            return res

        except Exception as err:
            logger.error(f"Excpetion getting vlans from device: {repr(err)}")
            return action_result(success=0, error=1, errmsg=repr(err))
Beispiel #7
0
def test_vlan_instantiation():
    this_vlan = vlan(id=1, name="vlanone", description="default vlan")
    assert this_vlan.id == 1
    assert this_vlan.name == "vlanone"
    assert this_vlan.description == "default vlan"
Beispiel #8
0
def test_no_desc():
    this_vlan = vlan(id=1, name="vlanone")
    assert this_vlan.id == 1
    assert this_vlan.name == "vlanone"
    assert this_vlan.description == None