vn

来自「xen 3.2.2 源码」· 代码 · 共 905 行 · 第 1/2 页

TXT
905
字号
        fo.flush()    else:        fi = file("/proc/vnet/peers")        fo = None    try:        return sxp.parse(fi) or []    finally:        if fi: fi.close()        if fo: fo.close()class Opt:    """Declares command-line options for a command.    """    def getopt(klass, argv, opts, args):        """Get options and args from argv.        The value opts in the return value has an attribute for        eacho option or arg. The value args in the return value        is the remaining arguments.        @param argv arguments        @param opts option specifiers (list of Opt objects)        @param args arg specififiers (list of Arg objects)        @return (opts, args)        """        shortopts = "".join([ x.optShort() for x in opts ])        longopts  = [ x.optLong() for x in opts ]        (ovals, oargs) = getopt(argv[1:], shortopts, longopts)        odir = Opts()        for x in opts:            x.setDefault(odir)        for (k, v) in ovals:            for x in opts:                x.setOpt(k, v, odir)        argc = len(oargs)        if len(oargs) < len(args):            raise GetoptError("insufficient arguments for %s" % argv[0])        for (x, v) in zip(args, oargs):            x.setArg(v, odir)        return (odir, oargs[len(args): ])    getopt = classmethod(getopt)    def gethelp(klass, opts, args):        l = []        for x in opts:            l.append(x.help())        for x in args:            l.append(x.help())        return " ".join(l)    gethelp = classmethod(gethelp)    """A command=-line option.    @param name option name (this attribute is set to value in opts)    @param short short option flag (single-character string)    @param long long option name (defaults to option name, pass "" to suppress)    @param arg argument name (option has no arg if not specified)    """    def __init__(self, name, short=None, long=None, arg=False):        self.name = name        self.short = short        if long is None:            long = name        elif not long:            long = None        self.long = long        self.arg = arg    def help(self):        s = self.keyShort()        l = self.keyLong()        if s and l:            return "[%s | %s]" % (s, l)        else:            return s or l    def keyShort(self):        if self.short:            return "-%s" % self.short        else:            return None    def keyLong(self):        if self.long:            return "--%s" % self.long        else:            return None    def optLong(self):        if not self.long:            return None        if self.arg:            return "%s=" % self.long        else:            return self.long    def optShort(self):        if not self.short:            return None        if self.arg:            return "%s:" % self.short        else:            return self.short    def setDefault(self, vals):        if self.arg:            setattr(vals, self.name, None)        else:            setattr(vals, self.name, False)    def setOpt(self, k, v, vals):        if k in [ self.keyShort(), self.keyLong() ]:            if self.arg:                setattr(vals, self.name, v)            else:                if v not in [ None, '' ]:                    raise GetoptError("option %s does not take an argument" % k)                setattr(vals, self.name, True)class Arg:    """A command-line parameter. Args get their values from arguments    left over after option processing and are assigned in order.    The value is accessible as the attribute called 'name' in opts.    @param name argument name    """    def __init__(self, name):        self.name = name    def setArg(self, v, vals):        setattr(vals, self.name, v)    def help(self):        return "<%s>" % self.name            class VnMain:    """Methods beginning with this prefix are commands.    They must all have arguments like this:    op_foo(self, argv, args, opts)    argv: original command-line arguments    args: arguments left after option processing    opts: option and arg values (accessible as attributes)    Method options are specified by setting attribute    .opts on the method to a list of Option objects.    For args set .args to a list of Arg objects.    Use .use for short usage string, .help for long help.    Each option or arg defines an attribute in opts. For example    an option with name 'foo' is accessible as 'opts.foo'.    """    opPrefix = "op_"    def __init__(self, argv):        if argv:            self.name = argv[0]        else:            self.name = "vn"        self.argv = argv        self.argc = len(argv)    def error(self, v):        print >>sys.stderr, "%s: %s" % (self.name, v)        sys.exit(1)            def getFunction(self, opname):        key = self.opPrefix + opname.replace("-", "_")        fn = getattr(self, key, None)        if not fn:            raise ValueError("unknown command: %s" % opname)        return fn        def main(self):        if self.argc < 2:            args = ["help"]        else:            args = self.argv[1:]        try:            fn = self.getFunction(args[0])        except ValueError, ex:            self.error(ex)        try:            fnopts = self.getOpts(fn)            fnargs = self.getArgs(fn)            (opts, parms) = Opt.getopt(args, fnopts, fnargs)            return fn(args, parms, opts)        except GetoptError, ex:            self.error(ex)        except ValueError, ex:            self.error(ex)        except Exception, ex:            import traceback; traceback.print_exc()            self.error(ex)    def getOpts(self, meth):        return getattr(meth, "opts", [])        def getArgs(self, meth):        return getattr(meth, "args", [])        def getUse(self, meth):        return getattr(meth, "use", "")        def getHelp(self, meth):        return getattr(meth, "help", "") or self.getUse(meth)    def fnHelp(self, meth):        return Opt.gethelp(self.getOpts(meth), self.getArgs(meth))    def printHelp(self, fn, opt_long):        meth = getattr(self, fn)        opname = fn[len(self.opPrefix):].replace("_", "-")        if opt_long:            help = self.getHelp(meth)            print "\n  %s" % opname            if help:                print "%s" % help        else:            use = self.getUse(meth)            print "  %s %s" % (opname, self.fnHelp(meth))            if use:                print "\t\t%s" % use    def show_vnif(self, dev):        cmd(CMD_IFCONFIG, dev)        bridge = Bridge.getBridge(dev)        if bridge:            print "          Bridge:", bridge            interfaces = Bridge.getBridgeInterfaces(bridge)            if dev in interfaces:                interfaces.remove(dev)            if interfaces:                print "          Interfaces:", ", ".join(interfaces)            print    def op_help(self, argv, args, opts):        if opts.long:            print '%s <command> <options>' % self.name            print self.long_help        else:            print '%s:' % self.name        l = dir(self)        l.sort()        for fn in l:            if fn.startswith(self.opPrefix):                self.printHelp(fn, opts.long)        print    op_help.opts = [ Opt('long', short='l') ]    def op_vnets(self, argv, args, opts):        vnets = vnet_list(vnets=args or None)        for v in vnets:            prettyprint(v, width=50)            print            if not opts.long:                continue            vnif = sxp.child_value(v, "vnetif")            if not vnif:                continue            self.show_vnif(vnif)        if opts.all:            vnetids = {}            for v in vnets:                vnetids[sxp.child_value(v, "id")] = v            for v in vif_list():                vnet = sxp.child_value(v, "vnet")                if vnet not in vnetids:                    continue                prettyprint(v)                print            for v in varp_list():                prettyprint(v)                print    op_vnets.opts = [ Opt('all', short='a'), Opt('long', short='l') ]    def op_vnifs(self, argv, args, opts):        vnifs = vnif_list(vnets=args or None)        for vnif in vnifs:            self.show_vnif(vnif)    def op_vifs(self, argv, args, opts):        for v in vif_list():            prettyprint(v)            print    def op_varp(self, argv, args, opts):        for v in varp_list():            prettyprint(v)            print    def op_varp_flush(self, argv, args, opts):        varp_flush()    def op_vnet_create(self, argv, args, opts):        return vnet_create(opts.vnet,                           vnetif=opts.vnetif,                           bridge=opts.bridge,                           security=opts.security)    op_vnet_create.args = [ Arg('vnet') ]    op_vnet_create.opts = [ Opt('security', short='s', arg="SECURITY"),                            Opt('bridge', short='b', arg="BRIDGE"),                            Opt('vnetif', short='v', arg="VNETIF") ]    def op_vnet_delete(self, argv, args, opts):        vnetid = get_vnetid(opts.vnet)        return vnet_delete(vnetid, delbridge=opts.bridge)    op_vnet_delete.args = [ Arg('vnet') ]    op_vnet_delete.opts = [ Opt('bridge', short='b') ]    def op_vif_add(self, argv, args, opts):        vnetid = get_vnetid(opts.vnet)        if opts.interface:            vmac = get_mac(opts.vmac)            if not vmac:                raise ValueError("interface not found: %s" % opts.vmac)        else:            vmac = opts.vmac        return vif_add(vnetid, vmac)    op_vif_add.args = [ Arg('vnet'), Arg('vmac') ]    op_vif_add.opts = [ Opt('interface', short='i') ]    def op_vif_delete(self, argv, args, opts):        vnetid = get_vnetid(opts.vnet)        if opts.interface:            vmac = get_mac(opts.vmac)        else:            vmac = opts.vmac        return vif_del(vnetid, vmac)    op_vif_delete.args = [ Arg('vnet'), Arg('vmac') ]    op_vif_delete.opts = [ Opt('interface', short='i') ]    def op_peer_add(self, argv, args, opts):        addr = get_addr(opts.addr)        if(opts.port):            port = get_port(opts.port)        else:            port = None        return peer_add(addr, port)            op_peer_add.args = [ Arg('addr') ]    op_peer_add.opts = [ Opt('port', short='p') ]        def op_peer_delete(self, argv, args, opts):        addr = get_addr(opts.addr)        return peer_del(addr)    op_peer_delete.args = [ Arg('addr') ]        def op_peers(self, argv, args, opts):        for v in peer_list():            prettyprint(v)            print    def op_bridges(self, argv, args, opts):        if opts.long:            for bridge in Bridge.getBridges():                cmd(CMD_IFCONFIG, bridge)                interfaces = Bridge.getBridgeInterfaces(bridge)                if interfaces:                    print "          Interfaces:", ", ".join(interfaces)                    print        else:            for bridge in Bridge.getBridges():                print bridge,                interfaces = Bridge.getBridgeInterfaces(bridge)                if interfaces:                    print ":", ", ".join(interfaces)                else:                    print                op_bridges.opts = [ Opt('long', short='l') ]    def op_insmod(self, argv, args, opts):        """Insert the vnet kernel module."""        cmd("/etc/xen/scripts/vnet-insert", *args)    long_help          = """Control utility for vnets (virtual networking).Report bugs to Mike Wray <mike.wray@hp.com>."""    op_help.use        = "Print help."    op_help.help       = "Print help, long help if the option -l or --long is given."    op_vnets.use       = """Print vnets."""    op_vnets.help      = """Print vnet information, where options are:    -a, -all           Print vnets, vifs and varp info.    -l, --long         Print ifconfigs for vnet interfaces."""    op_vifs.use        = "Print vifs."    op_vnifs.use       = "Print ifconfigs for vnet network interfaces."    op_varp.use        = "Print varp info and entries in the varp cache."    op_varp_flush.use  = "Flush the varp cache."        op_vnet_create.use = "Create a vnet."    op_vnet_delete.use = "Delete a vnet."    op_vnet_delete.help = """Delete a vnet.    -b, --bridge       Delete the bridge the vnet interface is attached to.    """    op_vif_add.use     = "Add a vif to a vnet."    op_vif_add.help    = """Add a vif to a vnet. Not usually needed as vifsare added automatically.    -i, --interface    The vmac is the name of an interface to get the mac from."""    op_vif_delete.use  = "Delete a vif from a vnet."    op_vif_delete.help = """Delete a vif from a vnet. Not usually needed as vifsare removed periodically.    -i, --interface    The vmac is the name of an interface to get the mac from."""    op_peer_add.use    = "Add a peer."    op_peer_add.help   = """Add a peer: <addr> <port>Vnets use multicast to discover interfaces, but networks are often configurednot to forward multicast. Vnets forward multicasts to peers using UDP.Only add peers if multicasts are not working, check withping -b 224.10.0.1Only add peers at one machine in a subnet, otherwise you may cause forwardingloops."""    op_peer_delete.use = "Delete a peer."    op_peer_delete.help= "Delete a peer: <addr>"    op_peers.use       = "List peers."    op_peers.help      = "List peers."    op_bridges.use     = "Print bridges."    op_insmod.use      = "Insert the vnet kernel module, optionally with parameters."if __name__ == "__main__":    vn = VnMain(sys.argv)    vn.main()    

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?