1# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. 2# Copyright (C) 2014 YAMAMOTO Takashi <yamamoto at valinux co jp> 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 13# implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17import argparse 18import os.path 19import sys 20 21from ryu import cfg 22from ryu import utils 23from ryu import version 24 25 26subcommands = { 27 'run': 'ryu.cmd.manager', 28 'of-config-cli': 'ryu.cmd.of_config_cli', 29 'rpc-cli': 'ryu.cmd.rpc_cli', 30} 31 32 33class RemainderOpt(cfg.MultiStrOpt): 34 def _get_argparse_kwargs(self, group, **kwargs): 35 kwargs = cfg.MultiStrOpt._get_argparse_kwargs(self, group, **kwargs) 36 kwargs['nargs'] = argparse.REMAINDER 37 return kwargs 38 39 40base_conf = cfg.ConfigOpts() 41base_conf.register_cli_opt(cfg.StrOpt('subcommand', positional=True, 42 required=True, 43 help='[%s]' % '|'.join( 44 list(subcommands.keys())))) 45base_conf.register_cli_opt(RemainderOpt('subcommand_args', default=[], 46 positional=True, 47 help='subcommand specific arguments')) 48 49 50class SubCommand(object): 51 def __init__(self, name, entry): 52 self.name = name 53 self.entry = entry 54 55 def run(self, args): 56 prog = '%s %s' % (os.path.basename(sys.argv[0]), self.name,) 57 self.entry(args=args, prog=prog) 58 59 60def main(): 61 try: 62 base_conf(project='ryu', version='ryu %s' % version) 63 except cfg.RequiredOptError as e: 64 base_conf.print_help() 65 raise SystemExit(1) 66 subcmd_name = base_conf.subcommand 67 try: 68 subcmd_mod_name = subcommands[subcmd_name] 69 except KeyError: 70 base_conf.print_help() 71 raise SystemExit('Unknown subcommand %s' % subcmd_name) 72 subcmd_mod = utils.import_module(subcmd_mod_name) 73 subcmd = SubCommand(name=subcmd_name, entry=subcmd_mod.main) 74 subcmd.run(base_conf.subcommand_args) 75