def __init__(self, stdin=sys.stdin, foreground=True): self.bridge = None # default bridge self.ipt = None self.nss = None self.dvr = None if foreground: self.prompt = color_str(PROMPT_KW, 'g') self.stdin = stdin self.in_poller = poll() self.in_poller.register(stdin) Cmd.__init__(self) output("***\n Welcome to EasyOVS %s, " "type help to see available cmds.\n***\n" % VERSION) info('*** Starting CLI:\n') debug("==Loading credentials==\n") debug("auth_url = %s\n" % os.getenv('OS_AUTH_URL') or cfg.CONF.OS.auth_url) debug("username = %s\n" % os.getenv('OS_USERNAME') or cfg.CONF.OS.username) passwd = os.getenv('OS_PASSWORD') or cfg.CONF.OS.password passwd = passwd[:len(passwd)/4] + "****" + passwd[-len(passwd)/4:] debug("password = %s\n" % passwd) debug("tenant_name = %s\n" % os.getenv('OS_TENANT_NAME') or cfg.CONF.OS.tenant_name) while True: try: #if self.isatty(): #quietRun( 'stty sane' ) self.cmdloop() break except KeyboardInterrupt: info('\nInterrupt\n')
def run(self, cmd, forced=False): ''' Run given commands from -m 'xxxx'. Treat this similar with CLI. :param args: :param forced: :return: ''' cmd_split = cmd.split() if cmd_split[0] in CMDS_ONE: # list func = cmd_split[0] getattr(self, 'do_' + func)() elif cmd_split[0] in CMDS_BR: if len(cmd_split) > 2: # e.g., delflow br0 9,10 func, args = cmd_split[0], ' '.join(cmd_split[1:]) debug("run do_%s(%s, %s)\n" % (func, args.replace(',', ' '), forced)) getattr(self, 'do_' + func)(args.replace(',', ' '), forced) else: # e.g., delbr br0 func, args = cmd_split[0], cmd_split[1] getattr(self, 'do_' + func)(args) elif cmd_split[0] in CMDS_OTHER: # e.g., ipt vm 10.0.0.1, 10.0.0.2 func, args = cmd_split[0], ' '.join(cmd_split[1:]) getattr(self, 'do_' + func)(args) else: output('Wrong command format is given\n')
def do_dvr(self, arg): """ Check the dvr rules dvr [check] dvr check compute dvr check net """ args = arg.split() if len(args) > 2: # only 1 is valid warn("Not correct parameters, use as:\n") warn("dvr [check]\n") warn("dvr check compute\n") warn("dvr check net\n") return self.dvr = DVR() if len(args) == 0: # default cmd for ns args.insert(0, 'check') cmd = args[0] if not hasattr(self.dvr, '%s' % cmd): error('Unsupported cmd=%s\n' % cmd) return if cmd == 'check': if len(args) == 1: # only check cmd is given debug('run self.dvr.%s()\n' % cmd) getattr(self.dvr, '%s' % cmd)() else: # node parameter is given debug('run self.dvr.%s(%s)\n' % (cmd, args[1])) getattr(self.dvr, '%s' % cmd)(args[1])
def cleanup(): """Clean up junk which might be left over from old runs; """ debug("*** Removing junk from /tmp\n") sh('rm -f /tmp/*.flows') debug("*** Cleanup complete.\n")
def do_dvr(self, arg): """ Check the dvr rules dvr [check] dvr check compute dvr check net """ args = arg.split() if len(args) > 2: # only 1 is valid warn("Not correct parameters, use as:\n") warn("dvr [check]\n") warn("dvr check compute\n") warn("dvr check net\n") return if len(args) == 0: # default cmd for ns args.insert(0, 'check') cmd = args[0] if not hasattr(self.dvr, '%s' % cmd): error('Unsupported cmd=%s\n' % cmd) return if cmd == 'check': if len(args) == 1: # only check cmd is given debug('run self.dvr.%s()\n' % cmd) getattr(self.dvr, '%s' % cmd)() else: # node parameter is given debug('run self.dvr.%s(%s)\n' % (cmd, args[1])) getattr(self.dvr, '%s' % cmd)(args[1])
def vm(self, ip): ''' list vm related rules :param ip: vm ip :return: ''' debug("Try to show vm rules, ip=%s\n" % ip) port_id = get_port_id_from_ip(ip) debug('The port id is %s\n' % port_id) if not port_id: warn('No port id is found for ip=%s\n' % ip) return br_port = find_br_ports(port_id) if not br_port: warn('No br port is found for ip=%s\n' % ip) return output(r('## IP = %s, port = %s\n' % (ip, br_port))) rules_dic = self._query_port_rules(br_port) if rules_dic: output( b(_format_str_iptables_rule_ % ('PKTS', 'IN', 'SOURCE', 'OUT', 'DESTINATION', 'PROT', 'TARGET', 'OTHER'))) for rule in rules_dic: output(b('%s:\n' % rule)) self._fmt_show_rules(rules_dic[rule])
def vm(self, ip): ''' list vm related rules :param ip: vm ip :return: ''' debug("Try to show vm rules, ip=%s\n" % ip) port_id = get_port_id_from_ip(ip) debug('The port id is %s\n' % port_id) if not port_id: warn('No port id is found for ip=%s\n' % ip) return br_port = find_br_ports(port_id) if not br_port: warn('No br port is found for ip=%s\n' % ip) return output(r('## IP = %s, port = %s\n' % (ip, br_port))) rules_dic = self._query_port_rules(br_port) if rules_dic: output(b( _format_str_iptables_rule_ % ( 'PKTS', 'IN', 'SOURCE', 'OUT', 'DESTINATION', 'PROT', 'TARGET', 'OTHER'))) for rule in rules_dic: output(b('%s:\n' % rule)) self._fmt_show_rules(rules_dic[rule])
def __init__(self, stdin=sys.stdin, foreground=True): self.bridge = None # default bridge self.ipt = IPtables() if foreground: output('EasyOVS %s, type help for information\n' % VERSION) self.prompt = color_str(PROMPT_KW, 'g') self.stdin = stdin self.in_poller = poll() self.in_poller.register(stdin) Cmd.__init__(self) output("***\n Welcome to EasyOVS," "type help to see available commands.\n***\n") info('*** Starting CLI:\n') debug("==Loading credentials==\n") debug("auth_url = %s\n" % os.getenv('OS_AUTH_URL') or cfg.CONF.OS.auth_url) debug("username = %s\n" % os.getenv('OS_USERNAME') or cfg.CONF.OS.username) passwd = os.getenv('OS_PASSWORD') or cfg.CONF.OS.password passwd = passwd[:len(passwd) / 4] + "****" + passwd[-len(passwd) / 4:] debug("password = %s\n" % passwd) debug("tenant_name = %s\n" % os.getenv('OS_TENANT_NAME') or cfg.CONF.OS.tenant_name) while True: try: #if self.isatty(): #quietRun( 'stty sane' ) self.cmdloop() break except KeyboardInterrupt: info('\nInterrupt\n')
def cleanup(): """Clean up junk which might be left over from old runs; """ sh('pkill -9 -f "neutron port-list"') debug("*** Removing junk from /tmp\n") sh('rm -f /tmp/tmp_switch_* /tmp/vlogs* /tmp/*.out /tmp/*.log') debug("*** Cleanup complete.\n")
def get_flows(self): """ Return a dict of flows in the bridge. """ debug('Bridge:get_flow()\n') self.load_flows() if len(self.flows) > 0: return self.flows else: return {}
def br_dump(bridge_name): """ Dump the port information of a given bridges. """ flows = ovs_lib.OVSBridge(bridge_name).dump_flows() debug('br_dump: len flows=%u\n' % len(flows)) if flows: Flow.banner_output() for f in flows: f.fmt_output()
def show(self, table='filter', chain=None): ''' Show the content. :param table: which table to show, None for all :param chain: which chain to show, None for all. :return: ''' debug("Show table=%s, chain=%s\n" % (table, chain or 'None')) if table in self.valid_tables: self.tables[table].show(chain)
def br_dump(bridge): """ Dump the port information of a given bridges. """ flows = br_getflows(bridge) debug('br_dump: len flows=%u\n' % len(flows)) if flows: Flow.banner_output() for f in flows: f.fmt_output()
def get_flows(self): """ Return a dict of flows in the bridge in order of table:priority. """ debug('Bridge:get_flow()\n') self.load_flows() if len(self.flows) > 0: return self.flows else: return {}
def _query_port_rules(self, br_port): """ Return the dict of the related security rules on a given port. { 'NAME':[iptables rules], } will load rules first """ results = {} if br_port.startswith('qvo'): # vm port debug('qvo should be vm port\n') #self._load(table='filter') chain_tag = br_port[3:13] i_rules = self._get_rules(chain='neutron-openvswi-i' + chain_tag) out = self._get_rules(chain='neutron-openvswi-o' + chain_tag) filter = self._get_rules(chain='neutron-openvswi-s' + chain_tag) if i_rules: results['IN'] = i_rules if out: results['OUT'] = out if filter: results['SRC_FILTER'] = filter else: # maybe at Network Node debug('Should be network function port\n') ns = self.nss.get_intf_by_name(br_port) if not ns: warn("port %s not in namespaces\n" % br_port) else: output('ns=%s\n' % ns) self._load(table='nat', ns=ns) if br_port.startswith('tap'): # dhcp return None elif br_port.startswith('qr-') or br_port.startswith('qg-'): pre = self._get_rules(table='nat', chain='neutron-l3-agent-PREROUTING') out = self._get_rules(table='nat', chain='neutron-l3-agent-OUTPUT') float_snat = self._get_rules(table='nat', chain='neutron-l3-agent-float-snat') snat = self._get_rules(table='nat', chain='neutron-l3-agent-snat') if pre: results['PRE'] = pre if out: results['OUT'] = out if float_snat: results['FLOAT'] = float_snat if snat: results['SNAT'] = snat return results
def do_ipt(self, arg): """ Show the iptables rules, e.g., ipt vm vm1,vm2 ipt show nat,raw,filter [INPUT] ipt check nat,raw,filter """ args = arg.split() if len(args) < 1 or len(args) > 3: # only 1-3 is valid warn("Not correct parameters, use as:\n") warn("ipt vm vm_ip\n") warn("ipt show|check [filter] [INPUT]\n") return cmd = args[0] if not hasattr(self.ipt, '%s' % cmd): error('Unsupported cmd=%s\n' % cmd) return if cmd == 'vm': if len(args) == 1: error('No vm ip is given\n') return else: for vm_ip in args[1:]: debug('run self.ipt.%s(%s)\n' % (cmd, vm_ip)) getattr(self.ipt, '%s' % cmd)(vm_ip) elif cmd in ['check', 'show']: ns = None if args[-1] in NameSpaces().get_ids(): ns = args.pop() if len(args) == 1: # show debug('run self.ipt.%s(ns=%s)\n' % (cmd, ns)) getattr(self.ipt, '%s' % cmd)(ns=ns) return elif len(args) == 2: # filter|INPUT if args[1] in self.ipt.get_valid_tables(): # filter debug('run self.ipt.%s(table=%s,ns=%s)\n' % (cmd, args[1], ns)) getattr(self.ipt, '%s' % cmd)(table=args[1], ns=ns) else: # INPUT debug('run self.ipt.%s(chain=%s, ns=%s)\n' % (cmd, args[1], ns)) getattr(self.ipt, '%s' % cmd)(chain=args[1], ns=ns) elif len(args) == 3: if args[1] in self.ipt.get_valid_tables(): # filter INPUT debug('run self.ipt.%s(table=%s, chain=%s, ns=%s\n)' % (cmd, args[1], args[2], ns)) getattr(self.ipt, '%s' % cmd)(table=args[1], chain=args[2], ns=ns) else: warn("Unknown table, table=%s\n" % args[1])
def do_ipt(self, arg): """ Show the iptables rules, e.g., ipt vm vm1,vm2 ipt show nat,raw,filter [INPUT] ipt check nat,raw,filter """ args = arg.split() if len(args) < 1 or len(args) > 3: # only 1-3 is valid warn("Not correct parameters, use as:\n") warn("ipt vm vm_ip\n") warn("ipt show|check [filter] [INPUT]\n") return self.ipt = IPtables() cmd = args[0] if not hasattr(self.ipt, '%s' % cmd): error('Unsupported cmd=%s\n' % cmd) return if cmd == 'vm': if len(args) == 1: error('No vm ip is given\n') return else: for vm_ip in args[1:]: debug('run self.ipt.%s(%s)\n' % (cmd, vm_ip)) getattr(self.ipt, '%s' % cmd)(vm_ip) elif cmd in ['check', 'show']: ns = None if args[-1] in NameSpaces().get_ids(): ns = args.pop() if len(args) == 1: # show debug('run self.ipt.%s(ns=%s)\n' % (cmd, ns)) getattr(self.ipt, '%s' % cmd)(ns=ns) return elif len(args) == 2: # filter|INPUT if args[1] in self.ipt.get_valid_tables(): # filter debug('run self.ipt.%s(table=%s,ns=%s)\n' % (cmd, args[1], ns)) getattr(self.ipt, '%s' % cmd)(table=args[1], ns=ns) else: # INPUT debug('run self.ipt.%s(chain=%s, ns=%s)\n' % (cmd, args[1], ns)) getattr(self.ipt, '%s' % cmd)(chain=args[1], ns=ns) elif len(args) == 3: if args[1] in self.ipt.get_valid_tables(): # filter INPUT debug('run self.ipt.%s(table=%s, chain=%s, ns=%s\n)' % (cmd, args[1], args[2], ns)) getattr(self.ipt, '%s' % cmd)(table=args[1], chain=args[2], ns=ns) else: warn("Unknown table, table=%s\n" % args[1])
def _query_port_rules(self, br_port): """ Return the dict of the related security rules on a given port. { 'NAME':[iptables rules], } will load rules first """ results = {} if br_port.startswith('qvo'): # vm port debug('qvo should be vm port\n') #self._load(table='filter') chain_tag = br_port[3:13] i_rules = self._get_rules(chain='neutron-openvswi-i' + chain_tag) out = self._get_rules(chain='neutron-openvswi-o' + chain_tag) filter = self._get_rules(chain='neutron-openvswi-s' + chain_tag) if i_rules: results['IN'] = i_rules if out: results['OUT'] = out if filter: results['SRC_FILTER'] = filter else: # maybe at Network Node debug('Should be network function port\n') ns = self.nss.get_intf_by_name(br_port) if not ns: warn("port %s not in namespaces\n" % br_port) else: output('ns=%s\n' % ns) self._load(table='nat', ns=ns) if br_port.startswith('tap'): # dhcp return None elif br_port.startswith('qr-') or br_port.startswith('qg-'): pre = self._get_rules(table='nat', chain='neutron-l3-agent-PREROUTING') out = self._get_rules(table='nat', chain='neutron-l3-agent-OUTPUT') float_snat = self._get_rules( table='nat', chain='neutron-l3-agent-float-snat') snat = self._get_rules(table='nat', chain='neutron-l3-agent-snat') if pre: results['PRE'] = pre if out: results['OUT'] = out if float_snat: results['FLOAT'] = float_snat if snat: results['SNAT'] = snat return results
def dump_flows(self): """ Dump out the flows of this bridge :return: """ self.load_flows() debug('br_dump: len flows=%u\n' % len(self.flows)) table = 0 if self.flows: Flow.banner_output() for f in self.flows: if f.table != table: output('\n') table = f.table f.fmt_output()
def br_show(name): """ Show information of a given bridges. """ ovs_ports = Bridge(name).get_ports() if not ovs_ports: return neutron_ports = neutron_handler.get_neutron_ports() debug('get neutron_ports\n') content = [] mac_ip_show = False for intf in ovs_ports: # e.g., qvo-xxx, int-br-eth0, qr-xxx, tapxxx port, tag, intf_type = \ ovs_ports[intf]['port'], ovs_ports[intf]['vlan'], ovs_ports[ intf]['type'] if neutron_ports and intf[3:] in neutron_ports: p = neutron_ports[intf[3:]] vm_ips = ','.join( map(lambda x: x.get('ip_address'), p['fixed_ips'])) vm_mac = p.get('mac_address') mac_ip_show = True else: vm_ips, vm_mac = '', '' content.append((intf, port, tag, intf_type, vm_ips, vm_mac)) # output('%-20s%-8s%-16s%-24s%-8s\n' %(intf,port,vmIP,vmMac,tag)) content.sort(key=lambda x: x[1]) # sort by port content.sort(key=lambda x: x[4]) # sort by vm_ip content.sort(key=lambda x: x[3]) # sort by type output( color_str('%-20s%-12s%-8s%-12s' % ('Intf', 'Port', 'Vlan', 'Type'), 'r')) if mac_ip_show: output(color_str('%-16s%-24s\n' % ('vmIP', 'vmMAC'), 'r')) else: output('\n') i = 0 for _ in content: #color = ['w','g'][i%2] color = 'b' output( color_str('%-20s%-12s%-8s%-12s' % (_[0], _[1], _[2], _[3]), color)) if mac_ip_show: output(color_str('%-16s%-24s\n' % (_[4], _[5]), color)) else: output('\n') i += 1
def br_show(bridge_name): """ Show information of a given bridges. """ ovs_ports = ovs_lib.OVSBridge(bridge_name).get_ports() if not ovs_ports: return neutron_ports = neutron_handler.get_neutron_ports() debug('get neutron_ports\n') content = [] mac_ip_show = False for intf in ovs_ports: # e.g., qvo-xxx, int-br-eth0, qr-xxx, tapxxx port, tag, intf_type = \ ovs_ports[intf]['port'], ovs_ports[intf]['vlan'], ovs_ports[ intf]['type'] if neutron_ports and intf[3:] in neutron_ports: p = neutron_ports[intf[3:]] vm_ips = ','.join(map(lambda x: x.get('ip_address'), p['fixed_ips'])) vm_mac = p.get('mac_address') mac_ip_show = True else: vm_ips, vm_mac = '', '' content.append((intf, port, tag, intf_type, vm_ips, vm_mac)) # output('%-20s%-8s%-16s%-24s%-8s\n' %(intf,port,vmIP,vmMac,tag)) content.sort(key=lambda x: x[1]) # sort by port content.sort(key=lambda x: x[4]) # sort by vm_ip content.sort(key=lambda x: x[3]) # sort by type output(color_str('%-20s%-12s%-8s%-12s' % ('Intf', 'Port', 'Vlan', 'Type'), 'r')) if mac_ip_show: output(color_str('%-16s%-24s\n' % ('vmIP', 'vmMAC'), 'r')) else: output('\n') i = 0 for _ in content: #color = ['w','g'][i%2] color = 'b' output(color_str('%-20s%-12s%-8s%-12s' % (_[0], _[1], _[2], _[3]), color)) if mac_ip_show: output(color_str('%-16s%-24s\n' % (_[4], _[5]), color)) else: output('\n') i += 1
def load_flows(self, db=False): """ Load the OpenvSwitch table rules into self.flows, and also to db if enabled. """ debug('load_flows():\n') cmd = "ovs-ofctl dump-flows %s" % self.bridge flow_id, flows, f = 0, [], None if db: f = open(self.flows_db, 'w') result, error = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True).communicate() if error: return for l in result.split('\n'): l = l.strip() if l.startswith('cookie='): debug('%s\n' % l) flow = self.parse_flow(l) if flow: flows.append(flow) if db: f.write('%s\n' % l) if db: f.close() flows.sort(reverse=True) for i in range(len(flows)): flows[i].id = i self.flows = flows debug('load_flows:len flows=%u\n' % len(self.flows))
def fmt_flow_str(raw_str): """ Return a valid flow string or None based on given string. >>> fmt_flow_str(' ip udp, proto=2,actions=OUTPUT:2') 'ip,udp,proto=2 actions=OUTPUT:2' >>> fmt_flow_str(' "ip,proto=2 actions=OUTPUT:2,NORMAL,"') 'ip,proto=2 actions=OUTPUT:2,NORMAL' >>> fmt_flow_str(' ip proto=2 actions=OUTPUT:2 NORMAL') 'ip,proto=2 actions=OUTPUT:2,NORMAL' """ if 'actions=' not in raw_str: debug(raw_str) return None fmt_str = raw_str.replace('"', '').replace("'", "").strip() i = fmt_str.index('actions=') actions = fmt_str[i:].strip(',').replace(',', ' ').split() match = fmt_str[:i].strip(',').replace(',', ' ').split() if not match or not actions: debug(match) debug(actions) return None match = ','.join(match) actions = ','.join(actions) flow = match + ' ' + actions return flow
def vm(self, ip): """ list vm related rules :param ip: vm ip :return: """ debug("Try to show vm rules, ip=%s\n" % ip) port_id = get_port_id_from_ip(ip) debug('The port id is %s\n' % port_id) if not port_id: warn('No port id is found for ip=%s\n' % ip) return output(color_str('## IP = %s, port = %s\n' % (ip, port_id), 'r')) br_port = find_br_ports(port_id) if not br_port: warn('No br port is found for ip=%s\n' % ip) return debug('The br port is %s\n' % br_port) rules_dic = self._query_port_rules(br_port) if rules_dic: output(color_str( _format_str_iptables_rule_ % ( 'PKTS', 'SOURCE', 'DESTINATION', 'PROT', 'OTHER'), 'b')) for r in rules_dic: if rules_dic[r]: output('%s:\n' % r) self._fmt_show_rules(rules_dic[r])
def br_show(name): """ Show information of a given bridges. """ ovs_ports = Bridge(name).get_ports() if not ovs_ports: return neutron_ports = neutron_handler.get_neutron_ports() debug("get neutron_ports\n") content = [] mac_ip_show = False for intf in ovs_ports: # e.g., qvo-xxx, int-br-eth0, qr-xxx, tapxxx port, tag, intf_type = ovs_ports[intf]["port"], ovs_ports[intf]["vlan"], ovs_ports[intf]["type"] if neutron_ports and intf[3:] in neutron_ports: p = neutron_ports[intf[3:]] vm_ips = ",".join(map(lambda x: x.get("ip_address"), p["fixed_ips"])) vm_mac = p.get("mac_address") mac_ip_show = True else: vm_ips, vm_mac = "", "" content.append((intf, port, tag, intf_type, vm_ips, vm_mac)) # output('%-20s%-8s%-16s%-24s%-8s\n' %(intf,port,vmIP,vmMac,tag)) content.sort(key=lambda x: x[1]) # sort by port content.sort(key=lambda x: x[4]) # sort by vm_ip content.sort(key=lambda x: x[3]) # sort by type output(color_str("%-20s%-12s%-8s%-12s" % ("Intf", "Port", "Vlan", "Type"), "r")) if mac_ip_show: output(color_str("%-16s%-24s\n" % ("vmIP", "vmMAC"), "r")) else: output("\n") i = 0 for _ in content: # color = ['w','g'][i%2] color = "b" output(color_str("%-20s%-12s%-8s%-12s" % (_[0], _[1], _[2], _[3]), color)) if mac_ip_show: output(color_str("%-16s%-24s\n" % (_[4], _[5]), color)) else: output("\n") i += 1
def __init__(self, bridge=None, stdin=sys.stdin): self.prompt = color_str('g', PROMPT_KW) self.bridge = bridge self.stdin = stdin self.in_poller = poll() self.in_poller.register(stdin) Cmd.__init__(self) output("***\n Welcome to EasyOVS, type help to see available commands.\n***\n") info('*** Starting CLI:\n') debug("==cfg.ADMIN==\n") debug("auth_url = %s\n" % cfg.CONF.OS.auth_url) debug("username = %s\n" % cfg.CONF.OS.username) debug("password = %s\n" % cfg.CONF.OS.password) debug("tenant_name = %s\n" % cfg.CONF.OS.tenant_name) while True: try: #if self.isatty(): #quietRun( 'stty sane' ) self.cmdloop() break except KeyboardInterrupt: info('\nInterrupt\n')
def __init__(self, bridge=None, stdin=sys.stdin): self.prompt = color_str("g", PROMPT_KW) self.bridge = bridge self.stdin = stdin self.in_poller = poll() self.in_poller.register(stdin) Cmd.__init__(self) output("***\n Welcome to EasyOVS, type help to see available commands.\n***\n") info("*** Starting CLI:\n") debug("==cfg.ADMIN==\n") debug("auth_url = %s\n" % cfg.CONF.OS.auth_url) debug("username = %s\n" % cfg.CONF.OS.username) debug("password = %s\n" % cfg.CONF.OS.password) debug("tenant_name = %s\n" % cfg.CONF.OS.tenant_name) while True: try: # if self.isatty(): # quietRun( 'stty sane' ) self.cmdloop() break except KeyboardInterrupt: info("\nInterrupt\n")
def do_ns(self, arg): """ Show the network namespace content, e.g., ns list ns show id_prefix ns find pattern """ args = arg.split() if len(args) > 2: # only 1-2 is valid warn("Not correct parameters, use as:\n") warn("ns [list]\n") warn("ns show id_prefix (lo intf is ignored)\n") warn("ns find pattern\n") return self.nss = NameSpaces() if len(args) == 0: # default cmd for ns args.insert(0, 'list') cmd = args[0] if not hasattr(self.nss, '%s' % cmd): error('Unsupported cmd=%s\n' % cmd) return if cmd in ['list', 'clean']: if len(args) != 1: error('No param should be given\n') return else: debug('run self.nss.%s()\n' % cmd) getattr(self.nss, '%s' % cmd)() elif cmd in ['show', 'find', 'route']: if len(args) == 2: # debug('run self.nss.%s(%s)\n' % (cmd, args[1])) getattr(self.nss, '%s' % cmd)(args[1]) else: warn("Invalid param number, no reach here, %s\n" % arg) return else: error("Unknown cmd, cmd= %s\n" % arg)
def do_ns(self, arg): """ Show the network namespace content, e.g., ns list ns show id_prefix ns find pattern """ args = arg.split() if len(args) > 2: # only 1-2 is valid warn("Not correct parameters, use as:\n") warn("ns [list]\n") warn("ns show id_prefix (lo intf is ignored)\n") warn("ns find pattern\n") return if len(args) == 0: # default cmd for ns args.insert(0, 'list') cmd = args[0] if not hasattr(self.nss, '%s' % cmd): error('Unsupported cmd=%s\n' % cmd) return if cmd == 'list': if len(args) != 1: error('No param should be given\n') return else: debug('run self.nss.%s(...)\n' % cmd) getattr(self.nss, '%s' % cmd)() elif cmd in ['show', 'find', 'route']: if len(args) == 2: # debug('run self.nss.%s(%s)\n' % (cmd, args[1])) getattr(self.nss, '%s' % cmd)(args[1]) else: warn("Invalid param number, no reach here, %s\n" % arg) return else: error("Unknown cmd, cmd= %s\n" % arg)
def do_ns(self, arg): """ Show the network namespace content, e.g., ns list ns show id_prefix ns find pattern """ args = arg.split() if len(args) > 2: # only 1-2 is valid warn("Not correct parameters, use as:\n") warn("ns [list]\n") warn("ns show id_prefix (lo intf is ignored)\n") warn("ns find pattern\n") return if len(args) == 0: # default cmd for ns args.insert(0, "list") cmd = args[0] if not hasattr(self.nss, "%s" % cmd): error("Unsupported cmd=%s\n" % cmd) return if cmd == "list": if len(args) != 1: error("No param should be given\n") return else: debug("run self.nss.%s(...)\n" % cmd) getattr(self.nss, "%s" % cmd)() elif cmd in ["show", "find", "route"]: if len(args) == 2: # debug("run self.nss.%s(%s)\n" % (cmd, args[1])) getattr(self.nss, "%s" % cmd)(args[1]) else: warn("Invalid param number, no reach here, %s\n" % arg) return else: error("Unknown cmd, cmd= %s\n" % arg)
def _query_port_rules(self, br_port): """ Return the dict of the related security rules on a given port. { 'NAME':[iptables rules], } will load rules first """ if br_port.startswith('qvo'): # vm port debug('qvo should be vm port\n') self.load(table='filter') chain_tag = br_port[3:13] i_rules = self.get_rules(chain='neutron-openvswi-i' + chain_tag) o_rules = self.get_rules(chain='neutron-openvswi-o' + chain_tag) s_rules = self.get_rules(chain='neutron-openvswi-s' + chain_tag) return {'IN': i_rules, 'OUT': o_rules, 'SRC_FILTER': s_rules} else: # maybe at Network Node debug('Should be network function port\n') ns = find_ns(br_port) if not ns: debug("port %s not in namespaces\n" % br_port) self.load(table='nat', ns=ns) if br_port.startswith('tap'): # dhcp return None elif br_port.startswith('qr-') or br_port.startswith('qg-'): pre = self.get_rules(table='nat', chain='neutron-l3-agent-PREROUTING') out = self.get_rules(table='nat', chain='neutron-l3-agent-OUTPUT') float = self.get_rules(table='nat', chain='neutron-l3-agent-float-snat') snat = self.get_rules(table='nat', chain='neutron-l3-agent-snat') return {'PRE': pre, 'OUT': out, 'FLOAT': float, 'SNAT': snat} else: return None
def del_flow(self, flow_ids): """ Return True or False to del a flow from given list. """ if len(flow_ids) <= 0: return False if not self.flows: self.load_flows() del_flows = [] fd = sys.stdin.fileno() old = termios.tcgetattr(fd) for flow_id in flow_ids: if isinstance(flow_id, str) and flow_id.isdigit(): flow_id = int(flow_id) else: continue if flow_id >= len(self.flows): continue else: del_flow = self.flows[flow_id] Flow.banner_output() del_flow.fmt_output() output('Del the flow? [Y/n]: ') new = termios.tcgetattr(fd) new[3] = new[3] & ~termios.ICANON try: termios.tcsetattr(fd, termios.TCSADRAIN, new) while True: in_ch = sys.stdin.read(1) if in_ch == 'n' or in_ch == 'N': output('\tCancel the deletion.\n') break elif in_ch == 'y' or in_ch == 'Y' or in_ch != '\n': del_flows.append(del_flow) output('\n') break else: output('\nWrong, please input [Y/n]: ') continue finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) if not del_flows: return False self.load_flows(True) flows_db_new = self.flows_db + '.new' f, f_new = open(self.flows_db, 'r'), open(flows_db_new, 'w') while True: lines = f.readlines(1000) if not lines: break for line in lines: flow = self.parse_flow(line) if flow not in del_flows: f_new.write('%s' % line) else: debug("Del the flow:\n") #del_flow.fmt_output() f.close() f_new.close() replace_cmd = "ovs-ofctl replace-flows %s %s" % (self.bridge, flows_db_new) error = Popen(replace_cmd, stdout=PIPE, stderr=PIPE, shell=True).communicate()[1] if error: output(error) return False else: self.load_flows() return True
def br_delflow(bridge_name, ids, forced=False): debug('br_delflow: %s: %s\n' % (bridge_name, ','.join(ids))) br = ovs_lib.OVSBridge(bridge_name) if type(ids) == str and ids.isdigit(): return br.delete_flows([ids], forced)
def br_delflow(bridge, ids): debug('br_delflow: %s: %s\n' % (bridge, ','.join(ids))) if type(ids) == str and ids.isdigit(): return Bridge(bridge).del_flow([ids]) else: return Bridge(bridge).del_flow(ids)
def br_delflow(bridge, ids, forced=False): debug("br_delflow: %s: %s\n" % (bridge, ",".join(ids))) if type(ids) == str and ids.isdigit(): return Bridge(bridge).del_flow([ids], forced) else: return Bridge(bridge).del_flow(ids, forced)