コード例 #1
0
def openwrt_edit_config(request):
    device = DBSession.query(OpenWrt).get(request.matchdict['uuid'])
    if not device:
        return exc.HTTPNotFound()
    conf = Uci()
    conf.load_tree(device.configuration);
    if request.POST:
        configsToBeUpdated=[]
        newConfig = {}
        for key, val in request.POST.dict_of_lists().items():
            if key != "submitted":
                val[0] = val[0].replace("'", '"') # for better json recognition
                packagename, configname, optionname = key.split()
                if not (packagename in newConfig.keys()):
                    newConfig[packagename] = {}
                    newConfig[packagename]['values'] = {}
                if not (configname in newConfig[packagename]['values'].keys()):
                    newConfig[packagename]['values'][configname] = {}
                try:
                    savevalue = json.loads(val[0])
                except ValueError:
                    savevalue = val[0]
                newConfig[packagename]['values'][configname][optionname] = savevalue
        newUci = Uci()
        newUci.load_tree(json.dumps(newConfig));
        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(conf.diff(newUci));
        device.configuration = newUci.export_json()
        transaction.commit()
        jobtask.update_config.delay(request.matchdict['uuid'])
        return HTTPFound(location=request.route_url('openwrt_list'))
    return{ 'hiddenOptions' : ['.index','.type','.name','.anonymous'],
            'config'        : conf,
           'devicename'     : device.name}
コード例 #2
0
    def update_config(device, DBSession):
        file_dir = os.path.dirname(os.path.abspath(__file__))
        filepath = os.path.join(file_dir, str(device.uuid) + ".txt")
        print(filepath)
        if os.path.exists(filepath):
            cur_conf = open(filepath).read()
        else:
            cur_conf = "{}"

        new_configuration = Uci()
        new_configuration.load_tree(device.configuration)

        cur_configuration = Uci()
        cur_configuration.load_tree(cur_conf)
        conf_diff = cur_configuration.diff(new_configuration)
        changed = diffChanged(conf_diff)

        if changed:
            device.append_diff(conf_diff, DBSession, "upload: ")

        print(device.configuration)
        print("going to write file")
        open(filepath, 'w').write(device.configuration)
        print("wrote to file")

        DBSession.commit()
        DBSession.close()
コード例 #3
0
 def setUp(self):
     path, filename = os.path.split(os.path.realpath(__file__))
     self.confstring = open(os.path.join(path, 'example_config')).read()
     self.confa = Uci()
     self.confb = Uci()
     self.confa.load_tree(self.confstring)
     self.confb.load_tree(self.confstring)
コード例 #4
0
ファイル: tasks.py プロジェクト: schuza/wrtmgmt
def update_config(uuid):
    DBSession = get_sql_session()
    device = DBSession.query(OpenWrt).get(uuid)
    new_configuration = Uci()
    new_configuration.load_tree(device.configuration)
    device_url = "http://" + device.address + "/ubus"
    cur_configuration = Uci()
    cur_configuration.load_tree(
        return_config_from_node_as_json(device_url, device.login,
                                        device.password))
    conf_diff = cur_configuration.diff(new_configuration)
    update_diff_conf = signature('openwifi.jobserver.tasks.diff_update_config',
                                 args=(conf_diff, device_url, device.login,
                                       device.password))
    DBSession.commit()
    DBSession.close()
    update_diff_conf.delay()
コード例 #5
0
    def get_config(device, DBSession):
        file_dir = os.path.dirname(os.path.abspath(__file__))
        filepath = os.path.join(file_dir, str(device.uuid) + ".txt")
        print(filepath)
        try:
            if os.path.exists(filepath):
                newConf = open(filepath).read()
            else:
                newConf = ""

            if device.configured:

                newUci = Uci()
                newUci.load_tree(newConf)

                oldUci = Uci()
                oldUci.load_tree(device.configuration)

                diff = oldUci.diff(newUci)

                if diffChanged(diff):
                    device.append_diff(diff, DBSession, "download: ")
                    device.configuration = newConf
            else:
                device.configuration = newConf
                device.configured = True

            DBSession.commit()
            DBSession.close()
            return True
        except Exception as thrownexpt:
            print(thrownexpt)
            device.configured = False
            DBSession.commit()
            DBSession.close()
            return False
コード例 #6
0
def archive_edit_config(request):
    archiveConfig = DBSession.query(ConfigArchive).get(request.matchdict['id'])
    if not archiveConfig:
        return exc.HTTPNotFound()
    device = DBSession.query(OpenWrt).get(archiveConfig.router_uuid)
    if not device:
        return exc.HTTPNotFound()
    conf = Uci()
    conf.load_tree(archiveConfig.configuration);
    if request.POST:
        configsToBeUpdated=[]
        newConfig = {}
        for key, val in request.POST.dict_of_lists().items():
            if key != "submitted":
                val[0] = val[0].replace("'", '"') # for better json recognition
                packagename, configname, optionname = key.split()
                if not (packagename in newConfig.keys()):
                    newConfig[packagename] = {}
                    newConfig[packagename]['values'] = {}
                if not (configname in newConfig[packagename]['values'].keys()):
                    newConfig[packagename]['values'][configname] = {}
                try:
                    savevalue = json.loads(val[0])
                except ValueError:
                    savevalue = val[0]
                newConfig[packagename]['values'][configname][optionname] = savevalue
        confToBeArchivedNew = ConfigArchive(datetime.now(),
                                            json.dumps(newConfig),
                                            archiveConfig.router_uuid,
                                            id_generator())
        DBSession.add(confToBeArchivedNew)
        return HTTPFound(location=request.route_url('confarchive'))
    return{ 'hiddenOptions' : ['.index','.type','.name','.anonymous'],
            'config'        : conf,
            'routerName'    : device.name,
            'date'          : archiveConfig.date}
コード例 #7
0
ファイル: tasks.py プロジェクト: schuza/wrtmgmt
def update_template(openwrtConfJSON, templateJSON):
    openwrt_config = Uci()
    openwrt_config.load_tree(openwrtConfJSON)
    metaconf = json.loads(templateJSON)['metaconf']
    for package in metaconf['change']['add']:  # packages to be added
        if package not in openwrt_config.packages.keys():
            openwrt_config.add_package(package)
    for package in metaconf['change']['del']:  # packages to be deleted
        if package in openwrt_config.packages.keys():
            openwrt_config.packages.pop(package)
    packages = metaconf['packages']
    for package_match in packages:
        if not package_match['type'] == 'package':
            raise MetaconfWrongFormat('first level should be type: \
                     package, but found: ' + cur_package_match['type'])
        package = package_match['matchvalue']
        # scan for packages to be added and add
        for config in package_match['change']['add']:
            nameMismatch = True
            typeMismatch = True
            # match names
            if config[0] in openwrt_config.packages[package].keys():
                nameMismatch = False
            # match types
            for confname, conf in openwrt_config.packages[package].items():
                if conf.uci_type == config[1]:
                    typeMismatch = False
                    break
            if (config[2] == 'always') or\
               (config[2] == 'typeMismatch' and typeMismatch) or\
               (config[2] == 'nameMismatch' and nameMismatch) or\
               (config[2] == 'bothMismatch' and typeMismatch and nameMismatch):
                openwrt_config.packages[package][config[0]] = Config(
                    config[1], config[0],
                    config[0] == '')  #Config(ucitype, name, anon)
        # scan for packages to be removed and delete
        for config in package_match['change']['del']:
            confmatch = config[2]
            # match names
            if config[0] in openwrt_config.packages[package].keys():
                if confmatch == 'always' or confmatch == 'nameMatch':
                    openwrt_config.packages[package].pop(config[0])
            # match types
            for confname, conf in openwrt_config.packages[package].items():
                if conf.uci_type == config[1]:
                    if confmatch == 'always' or confmatch == 'typeMatch':
                        openwrt_config.packages[package].pop(confname)
                    if confmatch == 'bothMatch' and confname == conf[0]:
                        openwrt_config.packages[package].pop(confname)
        # go into config matches
        for conf_match in package_match['config']:
            matched_configs = []
            configs_to_be_matched = list(
                openwrt_config.packages[package].values())
            while conf_match != '' and configs_to_be_matched:
                for config in configs_to_be_matched:
                    if conf_match['matchtype'] == 'name':
                        if config.name == conf_match['matchvalue']:
                            matched_configs.append(config)
                    if conf_match['matchtype'] == 'type':
                        if config.uci_type == conf_match['ucitype']:
                            matched_configs.append(config)
                for mconfig in matched_configs:
                    for option in conf_match['change']['add']:
                        mconfig.keys[option[0]] = option[1]
                    for option in conf_match['change']['del']:
                        try:
                            mconfig.keys.pop(option)
                        except KeyError:
                            pass
                configs_to_be_matched = matched_configs
                conf_match = conf_match['next']
    return openwrt_config