def delete(): if _vni and _vid_: raise ModelError("vid still exists") if _vid and (_ip_dvr_ or _ip_vhost_ or _peers_ or _ports_ or _default_gw_): raise ModelError("the other params still exits") __n__['logger'].info('Deleting a subnet(vlan): ' + str(_vid)) _flow_entries('delete') _delete_subnets()
def validate_input_params(self, input_params): revolution_period = utils.to_int(input_params['revolution_period']) if revolution_period <= 0: raise ModelError('Период обращения должен быть больше 0.') orbital_inclination = utils.to_int(input_params['orbital_inclination']) if not 0 < orbital_inclination < 90: raise ModelError( 'Наклонение орбиты должно лежать в пределах [0;90].') return { 'revolution_period': revolution_period, 'orbital_inclination': orbital_inclination }
def validate_input_params(self, input_params): clean_input_params = {} if input_params['dimensions'] in ('2D', '3D'): clean_input_params['dimensions'] = input_params['dimensions'] else: raise ModelError('Неверный пространственный охват, ' 'обратитесь к техническому специалисту.') if input_params['device_class'] in CAPACITORS.keys(): clean_input_params['device_class'] = input_params['device_class'] else: raise ModelError('Неверный пользовательский класс, ' 'обратитесь к техническому специалисту.') return clean_input_params
def add(): if _vni_ and _vid_: __n__['logger'].info('Adding a vpls(vlan): ' + str(_vid)) _add_vpls() _flow_entries('add') else: raise ModelError("requires at least _vni and _vid")
def update(): if not rip_ or not _network: raise ModelError('requires rip_ and _network') else: __n__['logger'].info('Updating a gateway router: rip') args = """ configure terminal interface {0} no link-detect exit interface {1} link-detect exit router rip no network {0} network {1} exit exit write exit """.format(network_, _network_) _vtysh(args)
def validate_components(self, components): if not components['critical_errors_control'] == 'True': raise ModelError('Ваша система должна включать модуль ' 'контроля критических помех.') security_quality = utils.to_int(components['security_quality']) return {'security_quality': security_quality}
def validate_model_params(model_params, input_params): clean_model_params = {} vector_length = utils.to_float(model_params['vector_length']) if vector_length > 0: clean_model_params['vector_length'] = vector_length else: raise ModelError('Длина вектора не может быть ниже 0.') clean_model_params['alpha_x'] = utils.to_float(model_params['alpha_x']) clean_model_params['beta_y'] = utils.to_float(model_params['beta_y']) if input_params['dimensions'] == '3D': clean_model_params['gamma_z'] = utils.to_float( model_params['gamma_z']) # Not needed, but can be useful if power_capacity of a component is # a single integer, not an interval # if model_params['power_capacity'] in CAPACITORS.values(): # clean_model_params['power_capacity'] = map( # int, # re.match( # '(\d+)-(\d+)', model_params['power_capacity']).groups()) team_args = ('base_station', 'point_of_interest', 'p1', 'p2', 'center_shift', 'matrix') for name in team_args: clean_model_params[name] = json.loads(model_params[name]) return clean_model_params
def add(): nodes = ptn_nodes.get_nodes(_id) br_tun = nodes['ptn'] br_int = nodes['l2sw'] if not _local_ip_: raise ModelError('"_local_ip_" is mandatory') if _remote_ips: for remote_ip in _remote_ips: inf = ''.join([num.zfill(3) for num in remote_ip.split('.')]) __n__['logger'].info('Adding a VXLAN tunnel: ' + inf) cmdp('ovs-vsctl add-port', br_tun, inf, '-- set interface', inf, 'type=vxlan options:in_key=flow', 'options:local_ip=' + _local_ip, 'options:out_key=flow', 'options:remote_ip=' + remote_ip) vxlan_ports = get_vxlan_ports() for vxlan_port in vxlan_ports: cmd( 'ovs-ofctl add-flow', br_tun, 'table=0,priority=1,in_port=' + vxlan_port + ',actions=resubmit(,2)') cmd('ip link set dev', br_tun, 'up') cmd('ip link set dev', br_int, 'up')
def update(): if _vni or _vid: raise ModelError('update not allowed for vni and vid') __n__['logger'].info('Updating a subnet(vlan): ' + str(_vid)) _flow_entries('delete') _delete_subnets() _add_subnets() _flow_entries('add')
def delete(): if _vni and _vid_: raise ModelError("vid still exists") __n__['logger'].info('Deleting vlan: ' + str(_vid)) nodes = ptn_nodes.get_nodes(_id) br_tun = nodes['ptn'] br_int = nodes['l2sw'] _flow_entries('delete', br_tun) _delete_vpls(br_int)
def validate_model_params(self, model_params): blend = model_params['oxidizer'], model_params['fuel'] if blend not in FUEL_RECIPES: raise ModelError("Выбранная вами топливная смесь непригодна" " для использования в ракетном двигателе.") if utils.to_float(model_params['combustion_heat']) < 0: raise ModelError("Рассчетное значение теплоты сгорания" " не может быть ниже 0.") if utils.to_float(model_params['radicals_amount']) < 0: raise ModelError( "Рассчетное значение образования свободных радикалов" " не может быть ниже 0.") return { 'oxidizer': model_params['oxidizer'], 'fuel': model_params['fuel'], 'combustion_heat': utils.to_float(model_params['combustion_heat']), 'radicals_amount': utils.to_float(model_params['radicals_amount']) }
def add(): if _vni_ and _vid_: __n__['logger'].info('Adding vlan: ' + str(_vid)) nodes = ptn_nodes.get_nodes(_id) br_tun = nodes['ptn'] br_int = nodes['l2sw'] _add_vpls(br_int) _flow_entries('add', br_tun) else: raise ModelError("requires at least _vni and _vid")
def _dnsmasq(ifname, enable, ipaddr, mask, start='100', limit='150', leasetime='12h'): if __n__['platform'] == 'openwrt': cmd = cmdutil.check_cmd network_dvr = 'network.' + ifname mask = network_address('255.255.255.255', 24) if enable: # Modifies /etc/config/network by using uci cmd('uci set', network_dvr+'=interface') cmd('uci set', network_dvr+'.ifname='+ifname) cmd('uci set', network_dvr+'.proto=static') cmd('uci set', network_dvr+'.ipaddr='+ipaddr) cmd('uci set', network_dvr+'.netmask='+mask) # Modifies /etc/config/dhcp by using uci cmd('uci set', 'dhcp.'+ifname+'=dhcp') cmd('uci set', 'dhcp.'+ifname+'.interface='+ifname) cmd('uci set', 'dhcp.'+ifname+'.start='+start) cmd('uci set', 'dhcp.'+ifname+'.limit='+limit) cmd('uci set', 'dhcp.'+ifname+'.leasetime='+leasetime) # Commits the changes cmd('uci commit') # Restart network cmd('/etc/init.d/network restart') # Restarts dnsmasq cmd('/etc/init.d/dnsmasq restart') else: # Modifies /etc/config/network by using uci cmd('uci delete', network_dvr) # Modifies /etc/config/dhcp by using uci cmd('uci delete', 'dhcp.'+ifname) # Commits the changes cmd('uci commit') # Restart network cmd('/etc/init.d/network restart') # Restarts dnsmasq cmd('/etc/init.d/dnsmasq restart') else: raise ModelError("ip_dvr DHCP server option is supported by 'openwrt' platform only")
def validate_model_params(self, model_params): orbit_radius = utils.to_float(model_params['orbit_radius']) if orbit_radius <= 0: raise ModelError('Проектный радиус орбиты должен быть больше 0.') pos_crit_accel = utils.to_float(model_params['pos_crit_accel']) if pos_crit_accel <= 0: raise ModelError('Критическое нормальное положительное ускорение ' 'должно быть больше 0.') neg_crit_accel = utils.to_float(model_params['neg_crit_accel']) if neg_crit_accel <= 0: raise ModelError('Критическое нормальное отрицательное ускорение ' 'должно быть больше 0.') permissible_variation = utils.to_int('model_params') return { 'orbit_radius': orbit_radius, 'pos_crit_accel': pos_crit_accel, 'neg_crit_accel': neg_crit_accel, 'permissible_variation': permissible_variation }
def validate_components(self, components, input_params): clean_components = {} if not components['critical_errors_control'] == 'True': raise ModelError('Ваша система должна включать модуль ' 'контроля критических помех.') clean_components['security_quality'] = utils.to_int( components['security_quality']) clean_components['capacitor_quality'] = utils.to_int( components['capacitor_quality']) clean_components['right_capacitor'] = (CAPACITORS[ input_params['device_class']] == components['power_capacity']) return clean_components
def add(): if not _local_ip_: raise ModelError('"_local_ip_" is mandatory') if _remote_ips: for remote_ip in _remote_ips: #inf = 'vxlan_' + remote_ip inf = ''.join([num.zfill(3) for num in remote_ip.split('.')]) __n__['logger'].info('Adding a VXLAN tunnel: ' + inf) cmdp('ovs-vsctl add-port br-tun', inf, '-- set interface', inf, 'type=vxlan options:in_key=flow', 'options:local_ip='+_local_ip, 'options:out_key=flow', 'options:remote_ip='+remote_ip) # vxlan_ports = get_vxlan_ports(_remote_ips) # TODO: yamldiff.py does not work on list parameters very well. vxlan_ports = get_vxlan_ports() for vxlan_port in vxlan_ports: cmd('ovs-ofctl add-flow br-tun', 'table=0,priority=1,in_port='+vxlan_port+',actions=resubmit(,2)')
def delete(): if _remote_ips: # vxlan_ports = get_vxlan_ports(_remote_ips) # TODO: yamldiff.py does not work on list parameters very well. vxlan_ports = get_vxlan_ports() for vxlan_port in vxlan_ports: cmd('ovs-ofctl del-flows br-tun table=0,in_port={vxlan_port}'.format(vxlan_port=vxlan_port)) for remote_ip in _remote_ips: #inf = 'vxlan_' + remote_ip inf = ''.join([num.zfill(3) for num in remote_ip.split('.')]) __n__['logger'].info('Deleting a VXLAN tunnel: ' + inf) cmd('ovs-vsctl del-port br-tun', inf) if _local_ip: # All remote IPs must be deleted before deleting local IP if remote_ips_: if not (set(_remote_ips) == set(remote_ips_)): raise ModelError('"local_ip" cannot be deleted')
def delete(): nodes = ptn_nodes.get_nodes(_id) br_tun = nodes['ptn'] br_int = nodes['l2sw'] if _remote_ips: vxlan_ports = get_vxlan_ports() for vxlan_port in vxlan_ports: cmd('ovs-ofctl del-flows', br_tun, 'table=0,in_port={vxlan_port}'.format(vxlan_port=vxlan_port)) for remote_ip in _remote_ips: inf = ''.join([num.zfill(3) for num in remote_ip.split('.')]) __n__['logger'].info('Deleting a VXLAN tunnel: ' + inf) cmd('ovs-vsctl del-port', br_tun, inf) if _local_ip: # All remote IPs must be deleted before deleting local IP if remote_ips_: if not (set(_remote_ips) == set(remote_ips_)): raise ModelError('"local_ip" cannot be deleted')
def delete(): if not _rip or not _network: raise ModelError('requires both _rip and _network') else: __n__['logger'].info('Deleting a gateway router: rip') args = """ configure terminal interface {0} no link-detect exit router rip no version 2 no redistribute connected no network {0} exit exit write exit """.format(_network) _vtysh(args)
def add(): __n__['logger'].info('Adding bridges: br-int and br-tun') if _ovs_bridges: cmdp('ovs-vsctl add-br br-int') cmdp('ovs-vsctl add-br br-tun') # Default flows must be cleared. cmd('ovs-ofctl del-flows br-tun') cmdp( 'ovs-vsctl add-port br-int patch-int -- set interface patch-int type=patch options:peer=patch-tun' ) cmdp( 'ovs-vsctl add-port br-tun patch-tun -- set interface patch-tun type=patch options:peer=patch-int' ) if _ovs_bridges and not _controller: _add_flow_entries() elif _controller and _ovs_bridges_: # OpenFlow Controller cmd('ovs-ofctl del-flows br-tun') cmdp('ovs-vsctl set-controller br-tun ' + _controller) elif _controller and not _ovs_bridges_: raise ModelError(message='cannot add _controller w/o _ovs_bridges_')
def add(): if _network and _vhosts: __n__['logger'].info('Adding vhosts: ' + str(_network)) _add_vhosts() else: raise ModelError("requires both _network and _vhosts")
def delete(): if _network and _vhosts: __n__['logger'].info('Deleting vhosts: ' + str(_network)) _delete_vhosts() else: raise ModelError("requires both _network and _vhosts")
def update(): raise ModelError('update not allowed for this model')
def validate_input_params(self, input_params): if input_params['error_control'] not in ('True', 'False'): raise ModelError('Что-то пошло не так с галочкой модуля ' 'контроля критических помех.') return {'error_control': input_params['error_control'] == 'True'}
def update(): raise ModelError('update not allowed for vni and vid')
def _flow_entries(ope): # serarch Open_vSwitch table if not search('Controller', ['target']): # no OpenFlow Controller params = {} if ope == 'add': params['svni'] = str(_vni_) params['svid'] = str(_vid_) if _ip_dvr: params['defaultgw'] = _ip_dvr['addr'].split('/')[0] else: # 'delete' params['svni'] = str(vni_) params['svid'] = str(vid_) if _ip_dvr: params['defaultgw'] = ip_dvr_['addr'].split('/')[0] int_dvr = "int_dvr" + params['svni'] int_br = "int_br" + params['svni'] cmd = cmdutil.check_cmd if _vid: if ope: cmd('ovs-ofctl add-flow br-tun table=2,priority=1,tun_id={svni},actions=mod_vlan_vid:{svid},resubmit(,10)'.format(**params)) else: cmd('ovs-ofctl del-flows br-tun table=2,tun_id={svni}'.format(**params)) if _ip_dvr and 'mode' not in _ip_dvr: raise ModelError('requires "mode"') if _ip_dvr and _ip_dvr['mode'] == 'dvr': if ope: cmd('ovs-ofctl add-flow br-tun', 'table=19,priority=1,dl_type=0x0806,dl_vlan={svid},nw_dst={defaultgw},actions=drop'.format(**params)) else: cmd('ovs-ofctl del-flows br-tun', 'table=19,dl_type=0x0806,dl_vlan={svid},nw_dst={defaultgw}'.format(**params)) # Redirects a packet to int_dvr port if nw_dst is a private ip address elif _ip_dvr and _ip_dvr['mode'] == 'spoke_dvr': mask = _ip_dvr['addr'].split('/')[1] #address = params['defaultgw'].split('.') nw_dst = network_address(params['defaultgw'], mask)+'/'+mask output = cmdutil.output_cmd('ip link show dev', int_dvr).split('\n')[1] dl_dst = output.split()[1] r = OvsdbRow('Interface', ('name', int_dvr)) outport = str(r['ofport']) r = OvsdbRow('Interface', ('name', int_br)) inport = str(r['ofport']) params['inport'] = inport params['outport'] = outport params['dl_type'] = '0x0800' params['dl_dst'] = dl_dst params['nw_dst'] = nw_dst params['nw_dst10'] = nw_dst10 params['nw_dst172'] = nw_dst172 params['nw_dst192'] = nw_dst192 params['cmdadd'] = 'ovs-ofctl add-flow br-int' params['cmddel'] = 'ovs-ofctl del-flows br-int' if ope: cmd('{cmdadd} table=0,priority=2,in_port={inport},dl_type={dl_type},nw_dst={nw_dst},actions=normal'.format(**params)) cmd('{cmdadd} table=0,priority=1,in_port={inport},dl_type={dl_type},nw_dst={nw_dst10},actions=resubmit(,1)'.format(**params)) cmd('{cmdadd} table=0,priority=1,in_port={inport},dl_type={dl_type},nw_dst={nw_dst172},actions=resubmit(,1)'.format(**params)) cmd('{cmdadd} table=0,priority=1,in_port={inport},dl_type={dl_type},nw_dst={nw_dst192},actions=resubmit(,1)'.format(**params)) # ARP, opcode = 2, TPA = defaultgw cmd('{cmdadd} table=0,priority=1,in_port={outport},dl_type=0x0806,nw_src={defaultgw},nw_proto=2,actions=drop'.format(**params)) cmd('{cmdadd} table=1,priority=0,in_port={inport},actions=set_field:{dl_dst}->dl_dst,output:{outport}'.format(**params)) else: cmd('{cmddel} table=0,in_port={inport},dl_type={dl_type},nw_dst={nw_dst}'.format(**params)) cmd('{cmddel} table=0,in_port={inport},dl_type={dl_type},nw_dst={nw_dst10}'.format(**params)) cmd('{cmddel} table=0,in_port={inport},dl_type={dl_type},nw_dst={nw_dst172}'.format(**params)) cmd('{cmddel} table=0,in_port={inport},dl_type={dl_type},nw_dst={nw_dst192}'.format(**params)) # ARP, opcode = 2, TPA = defaultgw cmd('{cmddel} table=0,in_port={outport},dl_type=0x0806,nw_src={defaultgw},nw_proto=2'.format(**params)) cmd('{cmddel} table=1,in_port={inport}'.format(**params)) elif _ip_dvr and _ip_dvr['mode'] == 'hub' or 'spoke': pass else: pass if _peers: # Broadcast tree for each vni output_ports = '' vxlan_ports = get_vxlan_ports(_peers) for vxlan_port in vxlan_ports: output_ports = output_ports+',output:'+vxlan_port if ope: cmd('ovs-ofctl add-flow br-tun table=21,priority=1,dl_vlan={svid},actions=strip_vlan,set_tunnel:{svni}'.format(**params)+output_ports) else: cmd('ovs-ofctl del-flow br-tun table=21,dl_vlan={svid}'.format(**params))
def delete(): if _vni and _vid_: raise ModelError("vid still exists") __n__['logger'].info('Deleting a subnet(vlan): ' + str(_vid)) _flow_entries('delete') _delete_vpls()
def _route(operation, data): exit = 0 if operation in ('add', 'update', 'delete', 'get'): # Calls config modules from oputil import CRUD if __n__['init'] != 'start': if isinstance(data, str) and (data.startswith('OrderedDict') or data.startswith('{')): data = eval(data) _data = copy.deepcopy(data) error = None module = None _index = None try: # Model integrity check before the CRUD operation if operation != 'get': import patterns for mod, model in data.iteritems(): if mod in __n__['indexes']: for _model in model: (b, m) = patterns.check_model(operation, mod, _model) if not b: __n__['logger'].info( "Model integrity check failure") raise ModelError(message=m, model=_model) else: (b, m) = patterns.check_model(operation, mod, model) if not b: __n__['logger'].info( "Model integrity check failure") raise ModelError(message=m, model=model) # CRUD operation starts from here for module, model in data.iteritems(): if operation == 'get': # CRUD get operation import ovsdb __n__['logger'].info('function:{0}.{1}, model:{2}'.format( module, operation, str(model))) result = ovsdb.get_state(module, model) mime_multipart(result, content_type='application/x-nlan', content_description='CRUD get', x_nlan_type='crud_response') else: # CRUD add/update/delete operation _mod = __import__('config.' + module, globals(), locals(), [operation], -1) call = _mod.__dict__[operation] if module in __n__['indexes']: for _model in model: _index = _model['_index'] del _model['_index'] __n__['logger'].info( 'function:{0}.{1}, index:{3}, model:{2}'. format(module, operation, str(_model), str(_index))) # Routes a requested model to a config module ### with CRUD(operation, module, _model, _index, gl=_mod.__dict__): call() else: __n__['logger'].info( 'function:{0}.{1}, model:{2}'.format( module, operation, str(model))) # Routes a requested model to a config module ### with CRUD(operation, module, model, gl=_mod.__dict__): call() except CmdError as e: exit = 1 error = OrderedDict() error['exception'] = 'CmdError' error['message'] = e.message error['traceback'] = traceback.format_exc() error['command'] = e.command error['stdout'] = e.out error['exit'] = e.returncode error['operation'] = operation if operation != 'get': error['progress'] = _progress(_data, module, _index) __n__['logger'].debug(str(error)) except ModelError as e: exit = 1 error = OrderedDict() error['exception'] = 'ModelError' error['message'] = e.message error['traceback'] = traceback.format_exc() error['exit'] = 1 error['operation'] = operation if operation != 'get': error['progress'] = _progress(_data, module, _index) __n__['logger'].debug(str(error)) except Exception as e: exit = 1 error = OrderedDict() error['exception'] = type(e).__name__ error['message'] = 'See the traceback message' error['traceback'] = traceback.format_exc() error['exit'] = 1 error['operation'] = operation if operation != 'get': error['progress'] = _progress(_data, module, _index) __n__['logger'].debug(str(error)) finally: if error: mime_multipart(error, content_type='application/x-nlan', content_description='NLAN Response', x_nlan_type='nlan_response') else: if __n__['init'] != 'start': completed = OrderedDict() completed['message'] = 'Execution completed' completed['exit'] = 0 mime_multipart(completed, content_type='application/x-nlan', content_description='NLAN Response', x_nlan_type='nlan_response') elif operation in ('rpc_dict', 'rpc_args'): # Calls a rpc module rpc = None func = None args = None kwargs = {} error = None if operation == 'rpc_args': s = data[0].split('.') rpc = '.'.join(s[:-1]) func = s[-1] args = tuple(data[1:]) elif operation == 'rpc_dict': try: d = eval(data) if isinstance(d, OrderedDict): rpc = d['module'] func = d['func'] args = d['args'] kwargs = d['kwargs'] else: raise Exception except: raise Exception("Illegal RPC request: {}".format(data)) try: _mod = __import__('rpc.' + rpc, globals(), locals(), [func], -1) call = _mod.__dict__[func] __n__['logger'].info( 'function:{0}.{1}, args:{2}, kwargs:{3}'.format( rpc, func, str(args), str(kwargs))) result = call(*args, **kwargs) if result: mime_multipart(result, content_type='application/x-nlan', content_description='RPC Response', x_nlan_type='rpc_response') except CmdError as e: exit = 1 error = OrderedDict() error['exception'] = 'CmdError' error['message'] = e.message error['command'] = e.command error['stdout'] = e.out error['exit'] = e.returncode except Exception as e: exit = 1 error = OrderedDict() error['exception'] = 'Exception' error['message'] = 'See the traceback message' error['exit'] = 1 error['traceback'] = traceback.format_exc() finally: if error: mime_multipart(error, content_type='application/x-nlan', content_description='NLAN Response', x_nlan_type='nlan_response') else: completed = OrderedDict() completed['message'] = 'Execution completed' completed['exit'] = 0 mime_multipart(completed, content_type='application/x-nlan', content_description='NLAN Response', x_nlan_type='nlan_response') else: error = OrderedDict() error['exception'] = 'NlanException' error['message'] = 'Unsupported NLAN operation, {}'.format(operation) error['exit'] = 1 mime_multipart(error, content_type='application/x-nlan', content_description='NLAN Response', x_nlan_type='nlan_response') return exit