openstack nova 基础知识——cfg

来源:互联网 发布:osi网络层 编辑:程序博客网 时间:2024/06/05 07:30

http://www.verydemo.com/demo_c161_i97125.html

纠结了两天,才把nova中的配置文件的管理和命令行的解析了解了一个大概,在nova中,很多地方都用到了cfg这个模块。

现在的分析,只是还在表面上,没有深入到实质性的内容,而且,有很多不清楚的地方,这个不清楚的地方,主要是不知道它用来是做什么的,以及怎么去用它。不过随着慢慢的深入,会越来越清楚的。


我觉得cfg模块的主要作用有两个:一个是对配置文件进行解析,一个是对命令行参数进行解析,但是我不清楚的是这个解析的命令行参数是怎么用的,在哪里用。

相应的,有两个较为核心的类:MultiConfigParser和OptionParser,前者是对配置文件进行解析的,这个类是nova自己写的,后者是对命令行进行解析的,用的是python库中的类。这两个类最终整合到ConfigOpts类中,然后又派生出了CommonConfigOpts类,就是通过这个类和外面进行交互的。


整理了一个类图,来看一下整体的结构:



类图只是把主要的类以及主要的方法和变量罗列出来,还有其它很多类这里就没有详细列举了,先举一个简单的例子,来看一下最核心的东西,其它的都是在围绕这个核心进行了加工处理,首先来看对命令行解析的这一个功能,核心的代码可举例如下:

查看文本打印?
  1. from optparse import OptionParser  
  2. [...]  
  3. parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")  
  4. parser.add_option("-f""--file", dest="filename",  
  5.                   help="write report to FILE", metavar="FILE")  
  6. parser.add_option("-q""--quiet",  
  7.                   action="store_false", dest="verbose", default=True,  
  8.                   help="don't print status messages to stdout")  
  9.   
  10. group = OptionGroup(parser, "Dangerous Options",  
  11.                     "Caution: use these options at your own risk.  "  
  12.                     "It is believed that some of them bite.")  
  13. group.add_option("-g", action="store_true", help="Group option.")  
  14.   
  15. parser.add_option_group(group)  
  16. (options, args) = parser.parse_args()  

OptionParser这个类,就是对一个命令的解析,包括这个命令的各个选项,这些选项如何处理。如果对这个地方不懂的,可以去python标准库中找optparse这个模块。

在cfg中,进行了如下封装:

1. 把选项(option)封装成了一个类Opt,并且对不同的选项类型分别派生出了StrOpt,BoolOpt等

2. 对OptionGroup进行了封装,即OptGroup,里面维护了一个OptionGroup对象和一个_opts字典(用来存放Opt对象)

3. ConfigOpts类封装了OptGroup和Opt类,以及一个OptionParser类,这样这三个主角就融合在一起了,并且提供了register_*()方法,供外部调用,来向OptionParser对象添加选项(option)或组(group)

至于对配置文件的解析,则主要是MultiConfigParser类和ConfigParser类,两者是聚合的关系,MultiConfigParser提供了read()和get()方法,前者是解析配置文件,后者是读取配置文件中的信息,最终也聚合在了ConfigOpts中。

主要就这些内容吧,来看一个简单的测试:

查看文本打印?
  1. import sys  
  2. from nova.openstack.common import cfg  
  3. import unittest  
  4.   
  5. global_opts = [  
  6.     cfg.StrOpt('aws_access_key_id',  
  7.                default='admin',  
  8.                help='AWS Access ID'),  
  9.     cfg.IntOpt('glance_port',  
  10.                default=9292,  
  11.                help='default glance port'),  
  12.     cfg.BoolOpt('api_rate_limit',  
  13.                 default=True,  
  14.                 help='whether to rate limit the api'),  
  15.     cfg.ListOpt('enabled_apis',  
  16.                 default=['ec2''osapi_compute''osapi_volume''metadata'],  
  17.                 help='a list of APIs to enable by default'),  
  18.     cfg.MultiStrOpt('osapi_compute_extension',  
  19.                     default=[  
  20.                       'nova.api.openstack.compute.contrib.standard_extensions'  
  21.                       ],  
  22.                     help='osapi compute extension to load'),  
  23. ]  
  24.   
  25. mycfg=cfg.CONF  
  26.   
  27. class TestCfg(unittest.TestCase):  
  28.       
  29.     def setup(self):  
  30.         pass  
  31.       
  32.     def test_find_config_files(self):  
  33.         config_files=cfg.find_config_files('nova')  
  34.         self.assertEqual(config_files, ['/etc/nova/nova.conf'])  
  35.       
  36.     def test_register_opts(self):  
  37.         mycfg.register_opts(global_opts)  
  38.         aws_access_key_id=mycfg.__getattr__('aws_access_key_id')  
  39.         self.assertEqual(aws_access_key_id, 'admin')  
  40.       
  41.     def test_cparser(self):  
  42.         mycfg([''],project='nova')  
  43.         print mycfg._cparser.parsed  
  44.         rabbit_host=mycfg._cparser.get('DEFAULT',['--rabbit_host'])  
  45.         self.assertEqual(rabbit_host, ['10.10.10.2'])  
  46.       
  47. suite = unittest.TestLoader().loadTestsFromTestCase(TestCfg)  
  48. unittest.TextTestRunner(verbosity=2).run(suite)  

加注释的源码():

查看文本打印?
  1. # -*- coding: cp936 -*-  
  2. # vim: tabstop=4 shiftwidth=4 softtabstop=4  
  3.   
  4. # Copyright 2012 Red Hat, Inc.  
  5. #  
  6. #    Licensed under the Apache License, Version 2.0 (the "License"); you may  
  7. #    not use this file except in compliance with the License. You may obtain  
  8. #    a copy of the License at  
  9. #  
  10. #         http://www.apache.org/licenses/LICENSE-2.0  
  11. #  
  12. #    Unless required by applicable law or agreed to in writing, software  
  13. #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT  
  14. #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the  
  15. #    License for the specific language governing permissions and limitations  
  16. #    under the License.  
  17.   
  18.   
  19. r""" 
  20. Configuration options which may be set on the command line or in config files. 
  21.  
  22. The schema for each option is defined using the Opt sub-classes, e.g.: 
  23.  
  24. :: 
  25.  
  26.     common_opts = [ 
  27.         cfg.StrOpt('bind_host', 
  28.                    default='0.0.0.0', 
  29.                    help='IP address to listen on'), 
  30.         cfg.IntOpt('bind_port', 
  31.                    default=9292, 
  32.                    help='Port number to listen on') 
  33.     ] 
  34.  
  35. Options can be strings, integers, floats, booleans, lists or 'multi strings':: 
  36.  
  37.     enabled_apis_opt = cfg.ListOpt('enabled_apis', 
  38.                                    default=['ec2', 'osapi_compute'], 
  39.                                    help='List of APIs to enable by default') 
  40.  
  41.     DEFAULT_EXTENSIONS = [ 
  42.         'nova.api.openstack.compute.contrib.standard_extensions' 
  43.     ] 
  44.     osapi_compute_extension_opt = cfg.MultiStrOpt('osapi_compute_extension', 
  45.                                                   default=DEFAULT_EXTENSIONS) 
  46.  
  47. Option schemas are registered with the config manager at runtime, but before 
  48. the option is referenced:: 
  49.  
  50.     class ExtensionManager(object): 
  51.  
  52.         enabled_apis_opt = cfg.ListOpt(...) 
  53.  
  54.         def __init__(self, conf): 
  55.             self.conf = conf 
  56.             self.conf.register_opt(enabled_apis_opt) 
  57.             ... 
  58.  
  59.         def _load_extensions(self): 
  60.             for ext_factory in self.conf.osapi_compute_extension: 
  61.                 .... 
  62.  
  63. A common usage pattern is for each option schema to be defined in the module or 
  64. class which uses the option:: 
  65.  
  66.     opts = ... 
  67.  
  68.     def add_common_opts(conf): 
  69.         conf.register_opts(opts) 
  70.  
  71.     def get_bind_host(conf): 
  72.         return conf.bind_host 
  73.  
  74.     def get_bind_port(conf): 
  75.         return conf.bind_port 
  76.  
  77. An option may optionally be made available via the command line. Such options 
  78. must registered with the config manager before the command line is parsed (for 
  79. the purposes of --help and CLI arg validation):: 
  80.  
  81.     cli_opts = [ 
  82.         cfg.BoolOpt('verbose', 
  83.                     short='v', 
  84.                     default=False, 
  85.                     help='Print more verbose output'), 
  86.         cfg.BoolOpt('debug', 
  87.                     short='d', 
  88.                     default=False, 
  89.                     help='Print debugging output'), 
  90.     ] 
  91.  
  92.     def add_common_opts(conf): 
  93.         conf.register_cli_opts(cli_opts) 
  94.  
  95. The config manager has two CLI options defined by default, --config-file 
  96. and --config-dir:: 
  97.  
  98.     class ConfigOpts(object): 
  99.  
  100.         def __call__(self, ...): 
  101.  
  102.             opts = [ 
  103.                 MultiStrOpt('config-file', 
  104.                         ...), 
  105.                 StrOpt('config-dir', 
  106.                        ...), 
  107.             ] 
  108.  
  109.             self.register_cli_opts(opts) 
  110.  
  111. Option values are parsed from any supplied config files using 
  112. openstack.common.iniparser. If none are specified, a default set is used 
  113. e.g. glance-api.conf and glance-common.conf:: 
  114.  
  115.     glance-api.conf: 
  116.       [DEFAULT] 
  117.       bind_port = 9292 
  118.  
  119.     glance-common.conf: 
  120.       [DEFAULT] 
  121.       bind_host = 0.0.0.0 
  122.  
  123. Option values in config files override those on the command line. Config files 
  124. are parsed in order, with values in later files overriding those in earlier 
  125. files. 
  126.  
  127. The parsing of CLI args and config files is initiated by invoking the config 
  128. manager e.g.:: 
  129.  
  130.     conf = ConfigOpts() 
  131.     conf.register_opt(BoolOpt('verbose', ...)) 
  132.     conf(sys.argv[1:]) 
  133.     if conf.verbose: 
  134.         ... 
  135.  
  136. Options can be registered as belonging to a group:: 
  137.  
  138.     rabbit_group = cfg.OptGroup(name='rabbit', 
  139.                                 title='RabbitMQ options') 
  140.  
  141.     rabbit_host_opt = cfg.StrOpt('host', 
  142.                                  default='localhost', 
  143.                                  help='IP/hostname to listen on'), 
  144.     rabbit_port_opt = cfg.IntOpt('port', 
  145.                                  default=5672, 
  146.                                  help='Port number to listen on') 
  147.  
  148.     def register_rabbit_opts(conf): 
  149.         conf.register_group(rabbit_group) 
  150.         # options can be registered under a group in either of these ways: 
  151.         conf.register_opt(rabbit_host_opt, group=rabbit_group) 
  152.         conf.register_opt(rabbit_port_opt, group='rabbit') 
  153.  
  154. If it no group attributes are required other than the group name, the group 
  155. need not be explicitly registered e.g. 
  156.  
  157.     def register_rabbit_opts(conf): 
  158.         # The group will automatically be created, equivalent calling:: 
  159.         #   conf.register_group(OptGroup(name='rabbit')) 
  160.         conf.register_opt(rabbit_port_opt, group='rabbit') 
  161.  
  162. If no group is specified, options belong to the 'DEFAULT' section of config 
  163. files:: 
  164.  
  165.     glance-api.conf: 
  166.       [DEFAULT] 
  167.       bind_port = 9292 
  168.       ... 
  169.  
  170.       [rabbit] 
  171.       host = localhost 
  172.       port = 5672 
  173.       use_ssl = False 
  174.       userid = guest 
  175.       password = guest 
  176.       virtual_host = / 
  177.  
  178. Command-line options in a group are automatically prefixed with the 
  179. group name:: 
  180.  
  181.     --rabbit-host localhost --rabbit-port 9999 
  182.  
  183. Option values in the default group are referenced as attributes/properties on 
  184. the config manager; groups are also attributes on the config manager, with 
  185. attributes for each of the options associated with the group:: 
  186.  
  187.     server.start(app, conf.bind_port, conf.bind_host, conf) 
  188.  
  189.     self.connection = kombu.connection.BrokerConnection( 
  190.         hostname=conf.rabbit.host, 
  191.         port=conf.rabbit.port, 
  192.         ...) 
  193.  
  194. Option values may reference other values using PEP 292 string substitution:: 
  195.  
  196.     opts = [ 
  197.         cfg.StrOpt('state_path', 
  198.                    default=os.path.join(os.path.dirname(__file__), '../'), 
  199.                    help='Top-level directory for maintaining nova state'), 
  200.         cfg.StrOpt('sqlite_db', 
  201.                    default='nova.sqlite', 
  202.                    help='file name for sqlite'), 
  203.         cfg.StrOpt('sql_connection', 
  204.                    default='sqlite:///$state_path/$sqlite_db', 
  205.                    help='connection string for sql database'), 
  206.     ] 
  207.  
  208. Note that interpolation can be avoided by using '$$'. 
  209.  
  210. For command line utilities that dispatch to other command line utilities, the 
  211. disable_interspersed_args() method is available. If this this method is called, 
  212. then parsing e.g.:: 
  213.  
  214.   script --verbose cmd --debug /tmp/mything 
  215.  
  216. will no longer return:: 
  217.  
  218.   ['cmd', '/tmp/mything'] 
  219.  
  220. as the leftover arguments, but will instead return:: 
  221.  
  222.   ['cmd', '--debug', '/tmp/mything'] 
  223.  
  224. i.e. argument parsing is stopped at the first non-option argument. 
  225.  
  226. Options may be declared as required so that an error is raised if the user 
  227. does not supply a value for the option. 
  228.  
  229. Options may be declared as secret so that their values are not leaked into 
  230. log files: 
  231.  
  232.      opts = [ 
  233.         cfg.StrOpt('s3_store_access_key', secret=True), 
  234.         cfg.StrOpt('s3_store_secret_key', secret=True), 
  235.         ... 
  236.      ] 
  237.  
  238. This module also contains a global instance of the CommonConfigOpts class 
  239. in order to support a common usage pattern in OpenStack: 
  240.  
  241.   from openstack.common import cfg 
  242.  
  243.   opts = [ 
  244.     cfg.StrOpt('bind_host' default='0.0.0.0'), 
  245.     cfg.IntOpt('bind_port', default=9292), 
  246.   ] 
  247.  
  248.   CONF = cfg.CONF 
  249.   CONF.register_opts(opts) 
  250.  
  251.   def start(server, app): 
  252.       server.start(app, CONF.bind_port, CONF.bind_host) 
  253.  
  254. """  
  255.   
  256. import collections  
  257. import copy  
  258. import functools  
  259. import glob  
  260. import optparse  
  261. import os  
  262. import string  
  263. import sys  
  264.   
  265. from nova.openstack.common import iniparser  
  266.   
  267.   
  268. class Error(Exception):  
  269.     """Base class for cfg exceptions."""  
  270.   
  271.     def __init__(self, msg=None):  
  272.         self.msg = msg  
  273.   
  274.     def __str__(self):  
  275.         return self.msg  
  276.   
  277.   
  278. class ArgsAlreadyParsedError(Error):  
  279.     """Raised if a CLI opt is registered after parsing."""  
  280.   
  281.     def __str__(self):  
  282.         ret = "arguments already parsed"  
  283.         if self.msg:  
  284.             ret += ": " + self.msg  
  285.         return ret  
  286.   
  287.   
  288. class NoSuchOptError(Error, AttributeError):  
  289.     """Raised if an opt which doesn't exist is referenced."""  
  290.   
  291.     def __init__(self, opt_name, group=None):  
  292.         self.opt_name = opt_name  
  293.         self.group = group  
  294.   
  295.     def __str__(self):  
  296.         if self.group is None:  
  297.             return "no such option: %s" % self.opt_name  
  298.         else:  
  299.             return "no such option in group %s: %s" % (self.group.name,  
  300.                                                        self.opt_name)  
  301.   
  302.   
  303. class NoSuchGroupError(Error):  
  304.     """Raised if a group which doesn't exist is referenced."""  
  305.   
  306.     def __init__(self, group_name):  
  307.         self.group_name = group_name  
  308.   
  309.     def __str__(self):  
  310.         return "no such group: %s" % self.group_name  
  311.   
  312.   
  313. class DuplicateOptError(Error):  
  314.     """Raised if multiple opts with the same name are registered."""  
  315.   
  316.     def __init__(self, opt_name):  
  317.         self.opt_name = opt_name  
  318.   
  319.     def __str__(self):  
  320.         return "duplicate option: %s" % self.opt_name  
  321.   
  322.   
  323. class RequiredOptError(Error):  
  324.     """Raised if an option is required but no value is supplied by the user."""  
  325.   
  326.     def __init__(self, opt_name, group=None):  
  327.         self.opt_name = opt_name  
  328.         self.group = group  
  329.   
  330.     def __str__(self):  
  331.         if self.group is None:  
  332.             return "value required for option: %s" % self.opt_name  
  333.         else:  
  334.             return "value required for option: %s.%s" % (self.group.name,  
  335.                                                          self.opt_name)  
  336.   
  337.   
  338. class TemplateSubstitutionError(Error):  
  339.     """Raised if an error occurs substituting a variable in an opt value."""  
  340.   
  341.     def __str__(self):  
  342.         return "template substitution error: %s" % self.msg  
  343.   
  344.   
  345. class ConfigFilesNotFoundError(Error):  
  346.     """Raised if one or more config files are not found."""  
  347.   
  348.     def __init__(self, config_files):  
  349.         self.config_files = config_files  
  350.   
  351.     def __str__(self):  
  352.         return ('Failed to read some config files: %s' %  
  353.                 string.join(self.config_files, ','))  
  354.   
  355.   
  356. class ConfigFileParseError(Error):  
  357.     """Raised if there is an error parsing a config file."""  
  358.   
  359.     def __init__(self, config_file, msg):  
  360.         self.config_file = config_file  
  361.         self.msg = msg  
  362.   
  363.     def __str__(self):  
  364.         return 'Failed to parse %s: %s' % (self.config_file, self.msg)  
  365.   
  366.   
  367. class ConfigFileValueError(Error):  
  368.     """Raised if a config file value does not match its opt type."""  
  369.     pass  
  370.   
  371.   
  372. def _get_config_dirs(project=None):  
  373.     """Return a list of directors where config files may be located. 
  374.  
  375.     :param project: an optional project name 
  376.  
  377.     If a project is specified, following directories are returned:: 
  378.  
  379.       ~/.${project}/ 
  380.       ~/ 
  381.       /etc/${project}/ 
  382.       /etc/ 
  383.  
  384.     Otherwise, these directories:: 
  385.  
  386.       ~/ 
  387.       /etc/ 
  388.     """  
  389.     fix_path = lambda p: os.path.abspath(os.path.expanduser(p))#获得p目录的绝对路径  
  390.   
  391.     #os.path.join()是将两个参数用“/”连接起来,如~/.nova  
  392.     #if project else None,如果project为空,那么就将列表中的这一项置为None,在return时,会用filter过滤掉这个None项  
  393.     cfg_dirs = [  
  394.         fix_path(os.path.join('~''.' + project)) if project else None,  
  395.         fix_path('~'),  
  396.         os.path.join('/etc', project) if project else None,  
  397.         '/etc'  
  398.     ]  
  399.   
  400.     return filter(bool, cfg_dirs)  
  401.   
  402.   
  403. def _search_dirs(dirs, basename, extension=""):  
  404.     """Search a list of directories for a given filename. 
  405.  
  406.     Iterator over the supplied directories, returning the first file 
  407.     found with the supplied name and extension. 
  408.  
  409.     :param dirs: a list of directories 
  410.     :param basename: the filename, e.g. 'glance-api' 
  411.     :param extension: the file extension, e.g. '.conf' 
  412.     :returns: the path to a matching file, or None 
  413.     """  
  414.     #给定一个文件名和一组可能包含这个文件的目录,在这些目录中搜索这个文件所在的目录  
  415.     #返回找到的第一个文件所在的目录,返回的是一个相对路径,但包含文件名  
  416.     #e.g. /etc/nova/nova.conf  
  417.     for d in dirs:  
  418.         path = os.path.join(d, '%s%s' % (basename, extension))  
  419.         if os.path.exists(path):  
  420.             return path  
  421.   
  422.   
  423. def find_config_files(project=None, prog=None, extension='.conf'):  
  424.     """Return a list of default configuration files. 
  425.  
  426.     :param project: an optional project name 
  427.     :param prog: the program name, defaulting to the basename of sys.argv[0] 
  428.     :param extension: the type of the config file 
  429.  
  430.     We default to two config files: [${project}.conf, ${prog}.conf] 
  431.  
  432.     And we look for those config files in the following directories:: 
  433.  
  434.       ~/.${project}/ 
  435.       ~/ 
  436.       /etc/${project}/ 
  437.       /etc/ 
  438.  
  439.     We return an absolute path for (at most) one of each the default config 
  440.     files, for the topmost directory it exists in. 
  441.  
  442.     For example, if project=foo, prog=bar and /etc/foo/foo.conf, /etc/bar.conf 
  443.     and ~/.foo/bar.conf all exist, then we return ['/etc/foo/foo.conf', 
  444.     '~/.foo/bar.conf'] 
  445.  
  446.     If no project name is supplied, we only look for ${prog.conf}. 
  447.     """  
  448.     if prog is None:  
  449.         prog = os.path.basename(sys.argv[0])  
  450.   
  451.     cfg_dirs = _get_config_dirs(project)  
  452.   
  453.     config_files = []  
  454.     if project:  
  455.         config_files.append(_search_dirs(cfg_dirs, project, extension))  
  456.     config_files.append(_search_dirs(cfg_dirs, prog, extension))  
  457.   
  458.     #返回的是包含文件名在内的所有配置文件所在的目录的一个列表  
  459.     return filter(bool, config_files)  
  460.   
  461.   
  462. def _is_opt_registered(opts, opt):  
  463.     """Check whether an opt with the same name is already registered. 
  464.  
  465.     The same opt may be registered multiple times, with only the first 
  466.     registration having any effect. However, it is an error to attempt 
  467.     to register a different opt with the same name. 
  468.  
  469.     :param opts: the set of opts already registered 
  470.     :param opt: the opt to be registered 
  471.     :returns: True if the opt was previously registered, False otherwise 
  472.     :raises: DuplicateOptError if a naming conflict is detected 
  473.     """  
  474.     if opt.dest in opts:  
  475.         if opts[opt.dest]['opt'is not opt:  
  476.             raise DuplicateOptError(opt.name)  
  477.         return True  
  478.     else:  
  479.         return False  
  480.   
  481. # Opt的一个对象,代表了一个选项,即一个option  
  482. # 可调用里面的_add_to_cli()方法,将这个选项添加到一个组或者是一个解析器中。  
  483. class Opt(object):  
  484.   
  485.     """Base class for all configuration options. 
  486.  
  487.     An Opt object has no public methods, but has a number of public string 
  488.     properties: 
  489.  
  490.       name: 
  491.         the name of the option, which may include hyphens 
  492.       dest: 
  493.         the (hyphen-less) ConfigOpts property which contains the option value 
  494.       short: 
  495.         a single character CLI option name 
  496.       default: 
  497.         the default value of the option 
  498.       metavar: 
  499.         the name shown as the argument to a CLI option in --help output 
  500.       help: 
  501.         an string explaining how the options value is used 
  502.     """  
  503.     multi = False  
  504.   
  505.     def __init__(self, name, dest=None, short=None, default=None,  
  506.                  metavar=None, help=None, secret=False, required=False,  
  507.                  deprecated_name=None):  
  508.         """Construct an Opt object. 
  509.  
  510.         The only required parameter is the option's name. However, it is 
  511.         common to also supply a default and help string for all options. 
  512.  
  513.         :param name: the option's name 
  514.         :param dest: the name of the corresponding ConfigOpts property 
  515.         :param short: a single character CLI option name 
  516.         :param default: the default value of the option 
  517.         :param metavar: the option argument to show in --help 
  518.         :param help: an explanation of how the option is used 
  519.         :param secret: true iff the value should be obfuscated in log output 
  520.         :param required: true iff a value must be supplied for this option 
  521.         :param deprecated_name: deprecated name option.  Acts like an alias 
  522.         """  
  523.         self.name = name  
  524.         if dest is None:  
  525.             self.dest = self.name.replace('-''_')  
  526.         else:  
  527.             self.dest = dest  
  528.         self.short = short  
  529.         self.default = default  
  530.         self.metavar = metavar  
  531.         self.help = help  
  532.         self.secret = secret  
  533.         self.required = required  
  534.         if deprecated_name is not None:  
  535.             self.deprecated_name = deprecated_name.replace('-''_')  
  536.         else:  
  537.             self.deprecated_name = None  
  538.   
  539.     def _get_from_config_parser(self, cparser, section):  
  540.         """Retrieves the option value from a MultiConfigParser object. 
  541.  
  542.         This is the method ConfigOpts uses to look up the option value from 
  543.         config files. Most opt types override this method in order to perform 
  544.         type appropriate conversion of the returned value. 
  545.  
  546.         :param cparser: a ConfigParser object 
  547.         :param section: a section name 
  548.         """  
  549.         return self._cparser_get_with_deprecated(cparser, section)  
  550.       
  551.     #从所有配置文件生成的sections中,找section下的dest或者是deprecated_name所对应的值  
  552.     def _cparser_get_with_deprecated(self, cparser, section):  
  553.         """If cannot find option as dest try deprecated_name alias."""  
  554.         if self.deprecated_name is not None:  
  555.             return cparser.get(section, [self.dest, self.deprecated_name])  
  556.         return cparser.get(section, [self.dest])  
  557.   
  558.     #这个函数的最终结果是给组(OptionGroup)或者是解析器(parser)添加一个选项(option)  
  559.     #如果指定了组,那么就添加到组中,否则添加到解析器(parser)中  
  560.     #container,即OptionContainer,是OptionGroup和OptionParser的父类  
  561.     def _add_to_cli(self, parser, group=None):  
  562.         """Makes the option available in the command line interface. 
  563.  
  564.         This is the method ConfigOpts uses to add the opt to the CLI interface 
  565.         as appropriate for the opt type. Some opt types may extend this method, 
  566.         others may just extend the helper methods it uses. 
  567.  
  568.         :param parser: the CLI option parser 
  569.         :param group: an optional OptGroup object 
  570.         """  
  571.         container = self._get_optparse_container(parser, group)  
  572.           
  573.         kwargs = self._get_optparse_kwargs(group)#kwargs={  
  574.                                                  #    'dest':group.name+'_'+self.dest  
  575.                                                  #    'metavar':self.metavar  
  576.                                                  #    'help':self.help  
  577.                                                  #}  
  578.                                                    
  579.         prefix = self._get_optparse_prefix('', group)#这里prefix为: group.name+'-'  
  580.           
  581.         self._add_to_optparse(container, self.name, self.short, kwargs, prefix,  
  582.                               self.deprecated_name)  
  583.   
  584.     def _add_to_optparse(self, container, name, short, kwargs, prefix='',  
  585.                          deprecated_name=None):  
  586.         """Add an option to an optparse parser or group. 
  587.  
  588.         :param container: an optparse.OptionContainer object 
  589.         :param name: the opt name 
  590.         :param short: the short opt name 
  591.         :param kwargs: the keyword arguments for add_option() 
  592.         :param prefix: an optional prefix to prepend to the opt name 
  593.         :raises: DuplicateOptError if a naming confict is detected 
  594.         """  
  595.         args = ['--' + prefix + name]  
  596.         if short:  
  597.             args += ['-' + short]  
  598.         if deprecated_name:  
  599.             args += ['--' + prefix + deprecated_name]  
  600.         for a in args:  
  601.             if container.has_option(a):  
  602.                 raise DuplicateOptError(a)  
  603.         container.add_option(*args, **kwargs)  
  604.   
  605.     #group是一个OptGroup对象,这个函数的作用是获得OptGroup对象中的OptionGroup对象,  
  606.     #OptionGroup对象才是核心要操作的东西。  
  607.     def _get_optparse_container(self, parser, group):  
  608.         """Returns an optparse.OptionContainer. 
  609.  
  610.         :param parser: an optparse.OptionParser 
  611.         :param group: an (optional) OptGroup object 
  612.         :returns: an optparse.OptionGroup if a group is given, else the parser 
  613.         """  
  614.         #如果要给选项建立一个组的话,那么就新生成一个OptionGroup对象,或者是用已经建好的对象  
  615.         #如果不给选项建立组的话,那么就直接返回这个解析器,把选项直接放到这个解析器里  
  616.           
  617.         #此处parser作为参数传递过去的作用有2个:  
  618.         #1. 若没有指定组,则直接返回这个parser  
  619.         #2. 若指定了组,在获得这个组中的OptionGroup对象的时候,如果这个对象还没有创建,则创建的时候要  
  620.         #   用到parser,如果已经创建,则直接返回创建好的这个OptionGroup对象,parser就没有用到了。  
  621.         if group is not None:  
  622.             return group._get_optparse_group(parser)  
  623.         else:  
  624.             return parser  
  625.       
  626.     #主要是在dest前加上组名,然后重新组成一个kwargs字典,返回  
  627.     #字典中就包含三项内容:dest, metavar, help  
  628.     def _get_optparse_kwargs(self, group, **kwargs):  
  629.         """Build a dict of keyword arguments for optparse's add_option(). 
  630.  
  631.         Most opt types extend this method to customize the behaviour of the 
  632.         options added to optparse. 
  633.  
  634.         :param group: an optional group 
  635.         :param kwargs: optional keyword arguments to add to 
  636.         :returns: a dict of keyword arguments 
  637.         """  
  638.         dest = self.dest  
  639.         if group is not None:  
  640.             dest = group.name + '_' + dest  
  641.         kwargs.update({'dest': dest,  
  642.                        'metavar'self.metavar,  
  643.                        'help'self.help, })  
  644.         return kwargs  
  645.   
  646.     def _get_optparse_prefix(self, prefix, group):  
  647.         """Build a prefix for the CLI option name, if required. 
  648.  
  649.         CLI options in a group are prefixed with the group's name in order 
  650.         to avoid conflicts between similarly named options in different 
  651.         groups. 
  652.  
  653.         :param prefix: an existing prefix to append to (e.g. 'no' or '') 
  654.         :param group: an optional OptGroup object 
  655.         :returns: a CLI option prefix including the group name, if appropriate 
  656.         """  
  657.         if group is not None:  
  658.             return group.name + '-' + prefix  
  659.         else:  
  660.             return prefix  
  661.   
  662.   
  663. class StrOpt(Opt):  
  664.     """ 
  665.     String opts do not have their values transformed and are returned as 
  666.     str objects. 
  667.     """  
  668.     pass  
  669.   
  670.   
  671. class BoolOpt(Opt):  
  672.   
  673.     """ 
  674.     Bool opts are set to True or False on the command line using --optname or 
  675.     --noopttname respectively. 
  676.  
  677.     In config files, boolean values are case insensitive and can be set using 
  678.     1/0, yes/no, true/false or on/off. 
  679.     """  
  680.   
  681.     _boolean_states = {'1'True'yes'True'true'True'on'True,  
  682.                        '0'False'no'False'false'False'off'False}  
  683.   
  684.     def _get_from_config_parser(self, cparser, section):  
  685.         """Retrieve the opt value as a boolean from ConfigParser."""  
  686.         def convert_bool(v):  
  687.             value = self._boolean_states.get(v.lower())  
  688.             if value is None:  
  689.                 raise ValueError('Unexpected boolean value %r' % v)  
  690.   
  691.             return value  
  692.   
  693.         return [convert_bool(v) for v in  
  694.                 self._cparser_get_with_deprecated(cparser, section)]  
  695.   
  696.     def _add_to_cli(self, parser, group=None):  
  697.         """Extends the base class method to add the --nooptname option."""  
  698.         super(BoolOpt, self)._add_to_cli(parser, group)  
  699.         self._add_inverse_to_optparse(parser, group)  
  700.   
  701.     def _add_inverse_to_optparse(self, parser, group):  
  702.         """Add the --nooptname option to the option parser."""  
  703.         container = self._get_optparse_container(parser, group)  
  704.         kwargs = self._get_optparse_kwargs(group, action='store_false')  
  705.         prefix = self._get_optparse_prefix('no', group)  
  706.         kwargs["help"] = "The inverse of --" + self.name  
  707.         self._add_to_optparse(container, self.name, None, kwargs, prefix,  
  708.                               self.deprecated_name)  
  709.   
  710.     def _get_optparse_kwargs(self, group, action='store_true', **kwargs):  
  711.         """Extends the base optparse keyword dict for boolean options."""  
  712.         return super(BoolOpt,  
  713.                      self)._get_optparse_kwargs(group, action=action, **kwargs)  
  714.   
  715.   
  716. class IntOpt(Opt):  
  717.   
  718.     """Int opt values are converted to integers using the int() builtin."""  
  719.   
  720.     def _get_from_config_parser(self, cparser, section):  
  721.         """Retrieve the opt value as a integer from ConfigParser."""  
  722.         return [int(v) for v in self._cparser_get_with_deprecated(cparser,  
  723.                 section)]  
  724.   
  725.     def _get_optparse_kwargs(self, group, **kwargs):  
  726.         """Extends the base optparse keyword dict for integer options."""  
  727.         return super(IntOpt,  
  728.                      self)._get_optparse_kwargs(group, type='int', **kwargs)  
  729.   
  730.   
  731. class FloatOpt(Opt):  
  732.   
  733.     """Float opt values are converted to floats using the float() builtin."""  
  734.   
  735.     def _get_from_config_parser(self, cparser, section):  
  736.         """Retrieve the opt value as a float from ConfigParser."""  
  737.         return [float(v) for v in  
  738.                 self._cparser_get_with_deprecated(cparser, section)]  
  739.   
  740.     def _get_optparse_kwargs(self, group, **kwargs):  
  741.         """Extends the base optparse keyword dict for float options."""  
  742.         return super(FloatOpt,  
  743.                      self)._get_optparse_kwargs(group, type='float', **kwargs)  
  744.   
  745.   
  746. class ListOpt(Opt):  
  747.   
  748.     """ 
  749.     List opt values are simple string values separated by commas. The opt value 
  750.     is a list containing these strings. 
  751.     """  
  752.   
  753.     def _get_from_config_parser(self, cparser, section):  
  754.         """Retrieve the opt value as a list from ConfigParser."""  
  755.         return [v.split(','for v in  
  756.                 self._cparser_get_with_deprecated(cparser, section)]  
  757.   
  758.     def _get_optparse_kwargs(self, group, **kwargs):  
  759.         """Extends the base optparse keyword dict for list options."""  
  760.         return super(ListOpt,  
  761.                      self)._get_optparse_kwargs(group,  
  762.                                                 type='string',  
  763.                                                 action='callback',  
  764.                                                 callback=self._parse_list,  
  765.                                                 **kwargs)  
  766.   
  767.     def _parse_list(self, option, opt, value, parser):  
  768.         """An optparse callback for parsing an option value into a list."""  
  769.         setattr(parser.values, self.dest, value.split(','))  
  770.   
  771.   
  772. class MultiStrOpt(Opt):  
  773.   
  774.     """ 
  775.     Multistr opt values are string opts which may be specified multiple times. 
  776.     The opt value is a list containing all the string values specified. 
  777.     """  
  778.     multi = True  
  779.   
  780.     def _get_optparse_kwargs(self, group, **kwargs):  
  781.         """Extends the base optparse keyword dict for multi str options."""  
  782.         return super(MultiStrOpt,  
  783.                      self)._get_optparse_kwargs(group, action='append')  
  784.   
  785.     def _cparser_get_with_deprecated(self, cparser, section):  
  786.         """If cannot find option as dest try deprecated_name alias."""  
  787.         if self.deprecated_name is not None:  
  788.             return cparser.get(section, [self.dest, self.deprecated_name],  
  789.                                multi=True)  
  790.         return cparser.get(section, [self.dest], multi=True)  
  791.   
  792.   
  793. class OptGroup(object):  
  794.   
  795.     """ 
  796.     Represents a group of opts. 
  797.  
  798.     CLI opts in the group are automatically prefixed with the group name. 
  799.  
  800.     Each group corresponds to a section in config files. 
  801.  
  802.     An OptGroup object has no public methods, but has a number of public string 
  803.     properties: 
  804.  
  805.       name: 
  806.         the name of the group 
  807.       title: 
  808.         the group title as displayed in --help 
  809.       help: 
  810.         the group description as displayed in --help 
  811.     """  
  812.   
  813.     def __init__(self, name, title=None, help=None):  
  814.         """Constructs an OptGroup object. 
  815.  
  816.         :param name: the group name 
  817.         :param title: the group title for --help 
  818.         :param help: the group description for --help 
  819.         """  
  820.         self.name = name  
  821.         if title is None:  
  822.             self.title = "%s options" % title  
  823.         else:  
  824.             self.title = title  
  825.         self.help = help  
  826.   
  827.         self._opts = {}  # dict of dicts of (opt:, override:, default:)  
  828.         self._optparse_group = None  
  829.   
  830.     def _register_opt(self, opt):  
  831.         """Add an opt to this group. 
  832.  
  833.         :param opt: an Opt object 
  834.         :returns: False if previously registered, True otherwise 
  835.         :raises: DuplicateOptError if a naming conflict is detected 
  836.         """  
  837.         if _is_opt_registered(self._opts, opt):  
  838.             return False  
  839.   
  840.         self._opts[opt.dest] = {'opt': opt, 'override'None'default'None}  
  841.   
  842.         return True  
  843.   
  844.     def _unregister_opt(self, opt):  
  845.         """Remove an opt from this group. 
  846.  
  847.         :param opt: an Opt object 
  848.         """  
  849.         if opt.dest in self._opts:  
  850.             del self._opts[opt.dest]  
  851.   
  852.     def _get_optparse_group(self, parser):  
  853.         """Build an optparse.OptionGroup for this group."""  
  854.         if self._optparse_group is None:  
  855.             self._optparse_group = optparse.OptionGroup(parser, self.title,  
  856.                                                         self.help)  
  857.         return self._optparse_group  
  858.   
  859.     def _clear(self):  
  860.         """Clear this group's option parsing state."""  
  861.         self._optparse_group = None  
  862.   
  863.   
  864. class ParseError(iniparser.ParseError):  
  865.     def __init__(self, msg, lineno, line, filename):  
  866.         super(ParseError, self).__init__(msg, lineno, line)  
  867.         self.filename = filename  
  868.   
  869.     def __str__(self):  
  870.         return 'at %s:%d, %s: %r' % (self.filename, self.lineno,  
  871.                                      self.msg, self.line)  
  872.   
  873.   
  874. class ConfigParser(iniparser.BaseParser):  
  875.     def __init__(self, filename, sections):  
  876.         super(ConfigParser, self).__init__()  
  877.         self.filename = filename  
  878.         self.sections = sections  
  879.         self.section = None  
  880.       
  881.     # 覆盖父类方法,打开filename文件,并对其内容进行解析  
  882.     def parse(self):  
  883.         with open(self.filename) as f:  
  884.             return super(ConfigParser, self).parse(f)  
  885.           
  886.     # 覆盖父类方法,在sections中添加一项,并将其值置为{},即新增一个section  
  887.     #sections中若有section这个key,则将其值置为{},  
  888.     #若没有,则将section这个key,添加到sections中,并将其值置为{}  
  889.     def new_section(self, section):  
  890.         self.section = section  
  891.         self.sections.setdefault(self.section, {})  
  892.       
  893.     # 覆盖父类方法,添加键值对到sections中的section中  
  894.     def assignment(self, key, value):  
  895.         if not self.section:  
  896.             raise self.error_no_section()  
  897.   
  898.         self.sections[self.section].setdefault(key, [])  
  899.         self.sections[self.section][key].append('\n'.join(value))  
  900.       
  901.     #新增方法  
  902.     def parse_exc(self, msg, lineno, line=None):  
  903.         return ParseError(msg, lineno, line, self.filename)  
  904.       
  905.     #新增方法  
  906.     def error_no_section(self):  
  907.         return self.parse_exc('Section must be started before assignment',  
  908.                               self.lineno)  
  909.   
  910.   
  911. #对所有配置文件取出每一区域中每一项的值,放到parsed列表中  
  912. class MultiConfigParser(object):  
  913.     def __init__(self):  
  914.         self.parsed = []  
  915.   
  916.     def read(self, config_files):  
  917.         read_ok = []  
  918.   
  919.         for filename in config_files:  
  920.             sections = {} #相对于一个文件中的sections  
  921.             parser = ConfigParser(filename, sections)#操作级别是一个文件中的所有区域  
  922.   
  923.             try:  
  924.                 parser.parse()  
  925.             except IOError:  
  926.                 continue  
  927.             self.parsed.insert(0, sections)  
  928.             read_ok.append(filename)  
  929.   
  930.         return read_ok  
  931.       
  932.     #要从所有的配置文件所生成的sections中找到section中的names的值,并返回,返回值的类型是一个列表  
  933.     #但多数情况下,这个列表中的元素只有一个  
  934.     def get(self, section, names, multi=False):  
  935.         rvalue = []  
  936.         for sections in self.parsed:  
  937.             if section not in sections:  
  938.                 continue  
  939.             for name in names:  
  940.                 if name in sections[section]:  
  941.                     if multi:  
  942.                         rvalue = sections[section][name] + rvalue  
  943.                     else:  
  944.                         return sections[section][name]  
  945.         if multi and rvalue != []:  
  946.             return rvalue  
  947.         raise KeyError  
  948.   
  949.   
  950. class ConfigOpts(collections.Mapping):  
  951.   
  952.     """ 
  953.     Config options which may be set on the command line or in config files. 
  954.  
  955.     ConfigOpts is a configuration option manager with APIs for registering 
  956.     option schemas, grouping options, parsing option values and retrieving 
  957.     the values of options. 
  958.     """  
  959.   
  960.     def __init__(self):  
  961.         """Construct a ConfigOpts object."""  
  962.         self._opts = {}  # dict of dicts of (opt:, override:, default:)  
  963.         self._groups = {}  
  964.   
  965.         self._args = None  
  966.         self._oparser = None  
  967.         self._cparser = None  
  968.         self._cli_values = {}  
  969.         self.__cache = {}  
  970.         self._config_opts = []  
  971.         self._disable_interspersed_args = False  
  972.   
  973.     def _setup(self, project, prog, version, usage, default_config_files):  
  974.         """Initialize a ConfigOpts object for option parsing."""  
  975.         if prog is None:  
  976.             prog = os.path.basename(sys.argv[0]) #prog==''  
  977.   
  978.         #找到所有的配置文件所在的目录,包括文件名  
  979.         if default_config_files is None:  
  980.             default_config_files = find_config_files(project, prog)  
  981.   
  982.         #定义了一个optparse对象,是对命令行和配置文件的解析器  
  983.         self._oparser = optparse.OptionParser(prog=prog,  
  984.                                               version=version,  
  985.                                               usage=usage)  
  986.         #默认的是设置允许命令行的参数散置,即 prog -a -b arg1 arg2 也是可以被正确处理的  
  987.         if self._disable_interspersed_args:  
  988.             self._oparser.disable_interspersed_args()  
  989.   
  990.         self._config_opts = [  
  991.             MultiStrOpt('config-file',  
  992.                         default=default_config_files,  
  993.                         metavar='PATH',  
  994.                         help='Path to a config file to use. Multiple config '  
  995.                              'files can be specified, with values in later '  
  996.                              'files taking precedence. The default files '  
  997.                              ' used are: %s' % (default_config_files, )),  
  998.             StrOpt('config-dir',  
  999.                    metavar='DIR',  
  1000.                    help='Path to a config directory to pull *.conf '  
  1001.                         'files from. This file set is sorted, so as to '  
  1002.                         'provide a predictable parse order if individual '  
  1003.                         'options are over-ridden. The set is parsed after '  
  1004.                         'the file(s), if any, specified via --config-file, '  
  1005.                         'hence over-ridden options in the directory take '  
  1006.                         'precedence.'),  
  1007.         ]  
  1008.         self.register_cli_opts(self._config_opts)  
  1009.   
  1010.         self.project = project  
  1011.         self.prog = prog  
  1012.         self.version = version  
  1013.         self.usage = usage  
  1014.         self.default_config_files = default_config_files  
  1015.   
  1016.     #这里定义了一个装饰器,functools.wraps(f)的作用是使被装饰的方法,仍然保留自己的特殊属性  
  1017.     #pop()的意思是除去clear_cache这个键值对,并且返回这个键的值,如果没有这个键,就返回第二个参数True  
  1018.     #总之,就是一定要清空__cache  
  1019.     def __clear_cache(f):  
  1020.         @functools.wraps(f)  
  1021.         def __inner(self, *args, **kwargs):  
  1022.             if kwargs.pop('clear_cache'True):  
  1023.                 self.__cache.clear()  
  1024.             return f(self, *args, **kwargs)  
  1025.   
  1026.         return __inner  
  1027.       
  1028.     # 这个函数的作用是解析命令行参数和配置文件,把选项的值赋值给ConfigOpts对象的属性。  
  1029.     # 主要赋值的对象属性是_args, _cli_values(这两个有一个对应关系,_args----->_cli_values),_cparser  
  1030.     # 其它赋值的还有_setup()中赋值的那些值  
  1031.     def __call__(self,  
  1032.                  args=None,  
  1033.                  project=None,  
  1034.                  prog=None,  
  1035.                  version=None,  
  1036.                  usage=None,  
  1037.                  default_config_files=None):  
  1038.         """Parse command line arguments and config files. 
  1039.  
  1040.         Calling a ConfigOpts object causes the supplied command line arguments 
  1041.         and config files to be parsed, causing opt values to be made available 
  1042.         as attributes of the object. 
  1043.  
  1044.         The object may be called multiple times, each time causing the previous 
  1045.         set of values to be overwritten. 
  1046.  
  1047.         Automatically registers the --config-file option with either a supplied 
  1048.         list of default config files, or a list from find_config_files(). 
  1049.  
  1050.         If the --config-dir option is set, any *.conf files from this 
  1051.         directory are pulled in, after all the file(s) specified by the 
  1052.         --config-file option. 
  1053.  
  1054.         :param args: command line arguments (defaults to sys.argv[1:]) 
  1055.         :param project: the toplevel project name, used to locate config files 
  1056.         :param prog: the name of the program (defaults to sys.argv[0] basename) 
  1057.         :param version: the program version (for --version) 
  1058.         :param usage: a usage string (%prog will be expanded) 
  1059.         :param default_config_files: config files to use by default 
  1060.         :returns: the list of arguments left over after parsing options 
  1061.         :raises: SystemExit, ConfigFilesNotFoundError, ConfigFileParseError, 
  1062.                  RequiredOptError, DuplicateOptError 
  1063.         """  
  1064.         self.clear()  
  1065.           
  1066.         # 主要做了三件事:找到默认的配置文件,生成一个OptionParser对象,  
  1067.         # 注册了config-file和config-dir的opt对象到_opts中。  
  1068.         self._setup(project, prog, version, usage, default_config_files)  
  1069.           
  1070.         # 解析命令行参数,返回命令行中选项的键值对,存储到_cli_values中。  
  1071.         self._cli_values, leftovers = self._parse_cli_opts(args)  
  1072.           
  1073.         # 生成了_cparser=MutilConfigParser(),解析所有的默认配置文件,如nova.conf,存储到  
  1074.         # _cparser对象中的parsed属性中,是一个列表  
  1075.         self._parse_config_files()  
  1076.   
  1077.         self._check_required_opts()  
  1078.   
  1079.         return leftovers  
  1080.   
  1081.     # 得到一个opt的值,并以字符串的方式返回  
  1082.     def __getattr__(self, name):  
  1083.         """Look up an option value and perform string substitution. 
  1084.  
  1085.         :param name: the opt name (or 'dest', more precisely) 
  1086.         :returns: the option value (after string subsititution) or a GroupAttr 
  1087.         :raises: NoSuchOptError,ConfigFileValueError,TemplateSubstitutionError 
  1088.         """  
  1089.         return self._get(name)  
  1090.       
  1091.     # 同__getattr__(),key指的也就是dest  
  1092.     def __getitem__(self, key):  
  1093.         """Look up an option value and perform string substitution."""  
  1094.         return self.__getattr__(key)  
  1095.   
  1096.     def __contains__(self, key):  
  1097.         """Return True if key is the name of a registered opt or group."""  
  1098.         return key in self._opts or key in self._groups  
  1099.   
  1100.     def __iter__(self):  
  1101.         """Iterate over all registered opt and group names."""  
  1102.         for key in self._opts.keys() + self._groups.keys():  
  1103.             yield key  
  1104.   
  1105.     def __len__(self):  
  1106.         """Return the number of options and option groups."""  
  1107.         return len(self._opts) + len(self._groups)  
  1108.       
  1109.     # 把_opts和_groups中的值都清空,但键仍保留  
  1110.     # 把类的属性也都重置为最初始的状态,键也都清空了  
  1111.     def reset(self):  
  1112.         """Clear the object state and unset overrides and defaults."""  
  1113.         self._unset_defaults_and_overrides()  
  1114.         self.clear()  
  1115.  
  1116.     @__clear_cache  
  1117.     def clear(self):  
  1118.         """Clear the state of the object to before it was called."""  
  1119.         self._args = None  
  1120.         self._cli_values.clear()  
  1121.         self._oparser = None  
  1122.         self._cparser = None  
  1123.         self.unregister_opts(self._config_opts)  
  1124.         for group in self._groups.values():  
  1125.             group._clear()  
  1126.   
  1127.     #将opt放到组中的_opts中,或是放到本类中的_opts中  
  1128.     @__clear_cache  
  1129.     def register_opt(self, opt, group=None):  
  1130.         """Register an option schema. 
  1131.  
  1132.         Registering an option schema makes any option value which is previously 
  1133.         or subsequently parsed from the command line or config files available 
  1134.         as an attribute of this object. 
  1135.  
  1136.         :param opt: an instance of an Opt sub-class 
  1137.         :param group: an optional OptGroup object or group name 
  1138.         :return: False if the opt was already register, True otherwise 
  1139.         :raises: DuplicateOptError 
  1140.         """  
  1141.         if group is not None:  
  1142.             return self._get_group(group, autocreate=True)._register_opt(opt)  
  1143.   
  1144.         if _is_opt_registered(self._opts, opt):  
  1145.             return False  
  1146.   
  1147.         self._opts[opt.dest] = {'opt': opt, 'override'None'default'None}  
  1148.   
  1149.         return True  
  1150.  
  1151.     @__clear_cache  
  1152.     def register_opts(self, opts, group=None):  
  1153.         """Register multiple option schemas at once."""  
  1154.         for opt in opts:  
  1155.             self.register_opt(opt, group, clear_cache=False)  
  1156.  
  1157.     @__clear_cache  
  1158.     def register_cli_opt(self, opt, group=None):  
  1159.         """Register a CLI option schema. 
  1160.  
  1161.         CLI option schemas must be registered before the command line and 
  1162.         config files are parsed. This is to ensure that all CLI options are 
  1163.         show in --help and option validation works as expected. 
  1164.  
  1165.         :param opt: an instance of an Opt sub-class 
  1166.         :param group: an optional OptGroup object or group name 
  1167.         :return: False if the opt was already register, True otherwise 
  1168.         :raises: DuplicateOptError, ArgsAlreadyParsedError 
  1169.         """  
  1170.         if self._args is not None:  
  1171.             raise ArgsAlreadyParsedError("cannot register CLI option")  
  1172.   
  1173.         return self.register_opt(opt, group, clear_cache=False)  
  1174.  
  1175.     @__clear_cache  
  1176.     def register_cli_opts(self, opts, group=None):  
  1177.         """Register multiple CLI option schemas at once."""  
  1178.         for opt in opts:  
  1179.             self.register_cli_opt(opt, group, clear_cache=False)  
  1180.   
  1181.     def register_group(self, group):  
  1182.         """Register an option group. 
  1183.  
  1184.         An option group must be registered before options can be registered 
  1185.         with the group. 
  1186.  
  1187.         :param group: an OptGroup object 
  1188.         """  
  1189.         if group.name in self._groups:  
  1190.             return  
  1191.   
  1192.         self._groups[group.name] = copy.copy(group)  
  1193.  
  1194.     @__clear_cache  
  1195.     def unregister_opt(self, opt, group=None):  
  1196.         """Unregister an option. 
  1197.  
  1198.         :param opt: an Opt object 
  1199.         :param group: an optional OptGroup object or group name 
  1200.         :raises: ArgsAlreadyParsedError, NoSuchGroupError 
  1201.         """  
  1202.         if self._args is not None:  
  1203.             raise ArgsAlreadyParsedError("reset before unregistering options")  
  1204.   
  1205.         if group is not None:  
  1206.             self._get_group(group)._unregister_opt(opt)  
  1207.         elif opt.dest in self._opts:  
  1208.             del self._opts[opt.dest]  
  1209.  
  1210.     @__clear_cache  
  1211.     def unregister_opts(self, opts, group=None):  
  1212.         """Unregister multiple CLI option schemas at once."""  
  1213.         for opt in opts:  
  1214.             self.unregister_opt(opt, group, clear_cache=False)  
  1215.  
  1216.     @__clear_cache  
  1217.     def set_override(self, name, override, group=None):  
  1218.         """Override an opt value. 
  1219.  
  1220.         Override the command line, config file and default values of a 
  1221.         given option. 
  1222.  
  1223.         :param name: the name/dest of the opt 
  1224.         :param override: the override value 
  1225.         :param group: an option OptGroup object or group name 
  1226.         :raises: NoSuchOptError, NoSuchGroupError 
  1227.         """  
  1228.         opt_info = self._get_opt_info(name, group)  
  1229.         opt_info['override'] = override  
  1230.  
  1231.     @__clear_cache  
  1232.     def set_default(self, name, default, group=None):  
  1233.         """Override an opt's default value. 
  1234.  
  1235.         Override the default value of given option. A command line or 
  1236.         config file value will still take precedence over this default. 
  1237.  
  1238.         :param name: the name/dest of the opt 
  1239.         :param default: the default value 
  1240.         :param group: an option OptGroup object or group name 
  1241.         :raises: NoSuchOptError, NoSuchGroupError 
  1242.         """  
  1243.         opt_info = self._get_opt_info(name, group)  
  1244.         opt_info['default'] = default  
  1245.       
  1246.     # 遍历分组和未分组中每一个选项所在的Item,在分组中选项也存储在_opts的字典中  
  1247.     def _all_opt_infos(self):  
  1248.         """A generator function for iteration opt infos."""  
  1249.         for info in self._opts.values():  
  1250.             yield info, None  
  1251.         for group in self._groups.values():  
  1252.             for info in group._opts.values():  
  1253.                 yield info, group  
  1254.       
  1255.     # 这里是从每一项中,取出选项对象,即opt和opt所在的分组  
  1256.     # 如:{'opt': opt, 'override': None, 'default': None}是_opts中的一项,  
  1257.     # 这个函数就是遍历所有的项,从中取出opt对象。  
  1258.     def _all_opts(self):  
  1259.         """A generator function for iteration opts."""  
  1260.         for info, group in self._all_opt_infos():  
  1261.             yield info['opt'], group  
  1262.   
  1263.     def _unset_defaults_and_overrides(self):  
  1264.         """Unset any default or override on all options."""  
  1265.         for info, group in self._all_opt_infos():  
  1266.             info['default'] = None  
  1267.             info['override'] = None  
  1268.   
  1269.     def disable_interspersed_args(self):  
  1270.         """Set parsing to stop on the first non-option. 
  1271.  
  1272.         If this this method is called, then parsing e.g. 
  1273.  
  1274.           script --verbose cmd --debug /tmp/mything 
  1275.  
  1276.         will no longer return: 
  1277.  
  1278.           ['cmd', '/tmp/mything'] 
  1279.  
  1280.         as the leftover arguments, but will instead return: 
  1281.  
  1282.           ['cmd', '--debug', '/tmp/mything'] 
  1283.  
  1284.         i.e. argument parsing is stopped at the first non-option argument. 
  1285.         """  
  1286.         self._disable_interspersed_args = True  
  1287.   
  1288.     def enable_interspersed_args(self):  
  1289.         """Set parsing to not stop on the first non-option. 
  1290.  
  1291.         This it the default behaviour."""  
  1292.         self._disable_interspersed_args = False  
  1293.   
  1294.     def find_file(self, name):  
  1295.         """Locate a file located alongside the config files. 
  1296.  
  1297.         Search for a file with the supplied basename in the directories 
  1298.         which we have already loaded config files from and other known 
  1299.         configuration directories. 
  1300.  
  1301.         The directory, if any, supplied by the config_dir option is 
  1302.         searched first. Then the config_file option is iterated over 
  1303.         and each of the base directories of the config_files values 
  1304.         are searched. Failing both of these, the standard directories 
  1305.         searched by the module level find_config_files() function is 
  1306.         used. The first matching file is returned. 
  1307.  
  1308.         :param basename: the filename, e.g. 'policy.json' 
  1309.         :returns: the path to a matching file, or None 
  1310.         """  
  1311.         dirs = []  
  1312.         if self.config_dir:  
  1313.             dirs.append(self.config_dir)  
  1314.   
  1315.         for cf in reversed(self.config_file):  
  1316.             dirs.append(os.path.dirname(cf))  
  1317.   
  1318.         dirs.extend(_get_config_dirs(self.project))  
  1319.   
  1320.         return _search_dirs(dirs, name)  
  1321.   
  1322.     def log_opt_values(self, logger, lvl):  
  1323.         """Log the value of all registered opts. 
  1324.  
  1325.         It's often useful for an app to log its configuration to a log file at 
  1326.         startup for debugging. This method dumps to the entire config state to 
  1327.         the supplied logger at a given log level. 
  1328.  
  1329.         :param logger: a logging.Logger object 
  1330.         :param lvl: the log level (e.g. logging.DEBUG) arg to logger.log() 
  1331.         """  
  1332.         logger.log(lvl, "*" * 80)  
  1333.         logger.log(lvl, "Configuration options gathered from:")  
  1334.         logger.log(lvl, "command line args: %s"self._args)  
  1335.         logger.log(lvl, "config files: %s"self.config_file)  
  1336.         logger.log(lvl, "=" * 80)  
  1337.   
  1338.         def _sanitize(opt, value):  
  1339.             """Obfuscate values of options declared secret"""  
  1340.             return value if not opt.secret else '*' * len(str(value))  
  1341.   
  1342.         for opt_name in sorted(self._opts):  
  1343.             opt = self._get_opt_info(opt_name)['opt']  
  1344.             logger.log(lvl, "%-30s = %s", opt_name,  
  1345.                        _sanitize(opt, getattr(self, opt_name)))  
  1346.   
  1347.         for group_name in self._groups:  
  1348.             group_attr = self.GroupAttr(selfself._get_group(group_name))  
  1349.             for opt_name in sorted(self._groups[group_name]._opts):  
  1350.                 opt = self._get_opt_info(opt_name, group_name)['opt']  
  1351.                 logger.log(lvl, "%-30s = %s",  
  1352.                            "%s.%s" % (group_name, opt_name),  
  1353.                            _sanitize(opt, getattr(group_attr, opt_name)))  
  1354.   
  1355.         logger.log(lvl, "*" * 80)  
  1356.   
  1357.     def print_usage(self, file=None):  
  1358.         """Print the usage message for the current program."""  
  1359.         self._oparser.print_usage(file)  
  1360.   
  1361.     def print_help(self, file=None):  
  1362.         """Print the help message for the current program."""  
  1363.         self._oparser.print_help(file)  
  1364.       
  1365.       
  1366.     def _get(self, name, group=None):  
  1367.         if isinstance(group, OptGroup):  
  1368.             key = (group.name, name)  
  1369.         else:  
  1370.             key = (group, name)  
  1371.           
  1372.         # 如果这个key在__cache中存在,则返回其对应的值,  
  1373.         # 如果不存在这个key,那么在__cache中就新生成一个key,并为其赋值  
  1374.         try:  
  1375.             return self.__cache[key]  
  1376.         except KeyError:  
  1377.             value = self._substitute(self._do_get(name, group))  
  1378.             self.__cache[key] = value  
  1379.             return value  
  1380.   
  1381.     def _do_get(self, name, group=None):  
  1382.         """Look up an option value. 
  1383.  
  1384.         :param name: the opt name (or 'dest', more precisely) 
  1385.         :param group: an OptGroup 
  1386.         :returns: the option value, or a GroupAttr object 
  1387.         :raises: NoSuchOptError, NoSuchGroupError, ConfigFileValueError, 
  1388.                  TemplateSubstitutionError 
  1389.         """  
  1390.         if group is None and name in self._groups:  
  1391.             return self.GroupAttr(selfself._get_group(name))  
  1392.           
  1393.         # info是存储在_opts中的由dest作为键的值,是一个字典,形式是这样的:  
  1394.         # {'opt':opt,'default':default,'override':override}  
  1395.         # 此处的name,其实就是opt的dest  
  1396.         info = self._get_opt_info(name, group)  
  1397.         default, opt, override = [info[k] for k in sorted(info.keys())]  
  1398.   
  1399.         if override is not None:  
  1400.             return override  
  1401.   
  1402.         values = []  
  1403.         if self._cparser is not None:  
  1404.             #group的name,其实就是section的名字  
  1405.             section = group.name if group is not None else 'DEFAULT'   
  1406.             try:  
  1407.                 # 从sections中的section中得到这个opt所对应的值  
  1408.                 value = opt._get_from_config_parser(self._cparser, section)  
  1409.             except KeyError:  
  1410.                 pass  
  1411.             except ValueError as ve:  
  1412.                 raise ConfigFileValueError(str(ve))  
  1413.             else:  
  1414.                 if not opt.multi:  
  1415.                     # No need to continue since the last value wins  
  1416.                     return value[-1]  
  1417.                 values.extend(value)  
  1418.           
  1419.         #如果配置文件没有进行解析,即_cparser为空,则从_cli_values中找opt的值  
  1420.         name = name if group is None else group.name + '_' + name  
  1421.         value = self._cli_values.get(name)  
  1422.         if value is not None:  
  1423.             if not opt.multi:  
  1424.                 return value  
  1425.   
  1426.             return value + values  
  1427.   
  1428.         if values:  
  1429.             return values  
  1430.   
  1431.         if default is not None:  
  1432.             return default  
  1433.   
  1434.         return opt.default  
  1435.   
  1436.     def _substitute(self, value):  
  1437.         """Perform string template substitution. 
  1438.  
  1439.         Substitute any template variables (e.g. $foo, ${bar}) in the supplied 
  1440.         string value(s) with opt values. 
  1441.  
  1442.         :param value: the string value, or list of string values 
  1443.         :returns: the substituted string(s) 
  1444.         """  
  1445.         if isinstance(value, list):  
  1446.             return [self._substitute(i) for i in value]  
  1447.         elif isinstance(value, str):  
  1448.             tmpl = string.Template(value)  
  1449.             return tmpl.safe_substitute(self.StrSubWrapper(self))  
  1450.         else:  
  1451.             return value  
  1452.       
  1453.     # group_or_name如果是一个OptGroup对象的话,就直接将这个对象放到_groups中,  
  1454.     # 如果是一个组名的话,那么就根据这个组名创建一个OptGroup对象,将这个对放到_groups中。  
  1455.     def _get_group(self, group_or_name, autocreate=False):  
  1456.         """Looks up a OptGroup object. 
  1457.  
  1458.         Helper function to return an OptGroup given a parameter which can 
  1459.         either be the group's name or an OptGroup object. 
  1460.  
  1461.         The OptGroup object returned is from the internal dict of OptGroup 
  1462.         objects, which will be a copy of any OptGroup object that users of 
  1463.         the API have access to. 
  1464.  
  1465.         :param group_or_name: the group's name or the OptGroup object itself 
  1466.         :param autocreate: whether to auto-create the group if it's not found 
  1467.         :raises: NoSuchGroupError 
  1468.         """  
  1469.         group = group_or_name if isinstance(group_or_name, OptGroup) else None  
  1470.         group_name = group.name if group else group_or_name  
  1471.   
  1472.         if not group_name in self._groups:  
  1473.             if not group is None or not autocreate:  
  1474.                 raise NoSuchGroupError(group_name)  
  1475.   
  1476.             self.register_group(OptGroup(name=group_name))  
  1477.   
  1478.         return self._groups[group_name]  
  1479.   
  1480.     def _get_opt_info(self, opt_name, group=None):  
  1481.         """Return the (opt, override, default) dict for an opt. 
  1482.  
  1483.         :param opt_name: an opt name/dest 
  1484.         :param group: an optional group name or OptGroup object 
  1485.         :raises: NoSuchOptError, NoSuchGroupError 
  1486.         """  
  1487.         if group is None:  
  1488.             opts = self._opts  
  1489.         else:  
  1490.             group = self._get_group(group)  
  1491.             opts = group._opts  
  1492.   
  1493.         if not opt_name in opts:  
  1494.             raise NoSuchOptError(opt_name, group)  
  1495.   
  1496.         return opts[opt_name]  
  1497.       
  1498.     # 即解析default_config_files中的所有配置文件  
  1499.     def _parse_config_files(self):  
  1500.         """Parse the config files from --config-file and --config-dir. 
  1501.  
  1502.         :raises: ConfigFilesNotFoundError, ConfigFileParseError 
  1503.         """  
  1504.         config_files = list(self.config_file)  
  1505.   
  1506.         if self.config_dir:  
  1507.             config_dir_glob = os.path.join(self.config_dir, '*.conf')  
  1508.             config_files += sorted(glob.glob(config_dir_glob))  
  1509.   
  1510.         self._cparser = MultiConfigParser()  
  1511.           
  1512.         #解析所有的配置文件,解析出来的内容存放在_cparser中的parsed属性中,是一个列表  
  1513.         try:  
  1514.             read_ok = self._cparser.read(config_files)   
  1515.         except iniparser.ParseError as pe:  
  1516.             raise ConfigFileParseError(pe.filename, str(pe))  
  1517.   
  1518.         if read_ok != config_files:  
  1519.             not_read_ok = filter(lambda f: f not in read_ok, config_files)  
  1520.             raise ConfigFilesNotFoundError(not_read_ok)  
  1521.   
  1522.     def _check_required_opts(self):  
  1523.         """Check that all opts marked as required have values specified. 
  1524.  
  1525.         :raises: RequiredOptError 
  1526.         """  
  1527.         for info, group in self._all_opt_infos():  
  1528.             default, opt, override = [info[k] for k in sorted(info.keys())]  
  1529.   
  1530.             if opt.required:  
  1531.                 if (default is not None or override is not None):  
  1532.                     continue  
  1533.   
  1534.                 if self._get(opt.name, group) is None:  
  1535.                     raise RequiredOptError(opt.name, group)  
  1536.       
  1537.     # 解析命令行的参数  
  1538.     def _parse_cli_opts(self, args):  
  1539.         """Parse command line options. 
  1540.  
  1541.         Initializes the command line option parser and parses the supplied 
  1542.         command line arguments. 
  1543.  
  1544.         :param args: the command line arguments 
  1545.         :returns: a dict of parsed option values 
  1546.         :raises: SystemExit, DuplicateOptError 
  1547.  
  1548.         """  
  1549.         self._args = args  
  1550.           
  1551.         # 这个循环的作用是调用OptionContainer.add_option()把所有的选项添加到一个解析器或者是组中。  
  1552.         for opt, group in self._all_opts():  
  1553.             opt._add_to_cli(self._oparser, group)  
  1554.           
  1555.         # 解析,示例  
  1556.         # parser.add_option("-n", type="int", dest="num")  
  1557.         # (options, args) = parser.parse_args(["-n42"])  
  1558.         # print vars(options)  
  1559.         # 输出: {'num': 42}  
  1560.         values, leftovers = self._oparser.parse_args(args)  
  1561.   
  1562.         return vars(values), leftovers  
  1563.   
  1564.     class GroupAttr(collections.Mapping):  
  1565.   
  1566.         """ 
  1567.         A helper class representing the option values of a group as a mapping 
  1568.         and attributes. 
  1569.         """  
  1570.   
  1571.         def __init__(self, conf, group):  
  1572.             """Construct a GroupAttr object. 
  1573.  
  1574.             :param conf: a ConfigOpts object 
  1575.             :param group: an OptGroup object 
  1576.             """  
  1577.             self.conf = conf  
  1578.             self.group = group  
  1579.   
  1580.         def __getattr__(self, name):  
  1581.             """Look up an option value and perform template substitution."""  
  1582.             return self.conf._get(name, self.group)  
  1583.   
  1584.         def __getitem__(self, key):  
  1585.             """Look up an option value and perform string substitution."""  
  1586.             return self.__getattr__(key)  
  1587.   
  1588.         def __contains__(self, key):  
  1589.             """Return True if key is the name of a registered opt or group."""  
  1590.             return key in self.group._opts  
  1591.   
  1592.         def __iter__(self):  
  1593.             """Iterate over all registered opt and group names."""  
  1594.             for key in self.group._opts.keys():  
  1595.                 yield key  
  1596.   
  1597.         def __len__(self):  
  1598.             """Return the number of options and option groups."""  
  1599.             return len(self.group._opts)  
  1600.   
  1601.     class StrSubWrapper(object):  
  1602.   
  1603.         """ 
  1604.         A helper class exposing opt values as a dict for string substitution. 
  1605.         """  
  1606.   
  1607.         def __init__(self, conf):  
  1608.             """Construct a StrSubWrapper object. 
  1609.  
  1610.             :param conf: a ConfigOpts object 
  1611.             """  
  1612.             self.conf = conf  
  1613.   
  1614.         def __getitem__(self, key):  
  1615.             """Look up an opt value from the ConfigOpts object. 
  1616.  
  1617.             :param key: an opt name 
  1618.             :returns: an opt value 
  1619.             :raises: TemplateSubstitutionError if attribute is a group 
  1620.             """  
  1621.             value = getattr(self.conf, key)  
  1622.             if isinstance(value, self.conf.GroupAttr):  
  1623.                 raise TemplateSubstitutionError(  
  1624.                     'substituting group %s not supported' % key)  
  1625.             return value  
  1626.   
  1627.   
  1628. class CommonConfigOpts(ConfigOpts):  
  1629.   
  1630.     DEFAULT_LOG_FORMAT = "%(asctime)s %(levelname)8s [%(name)s] %(message)s"  
  1631.     DEFAULT_LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"  
  1632.   
  1633.     common_cli_opts = [  
  1634.         BoolOpt('debug',  
  1635.                 short='d',  
  1636.                 default=False,  
  1637.                 help='Print debugging output'),  
  1638.         BoolOpt('verbose',  
  1639.                 short='v',  
  1640.                 default=False,  
  1641.                 help='Print more verbose output'),  
  1642.     ]  
  1643.   
  1644.     logging_cli_opts = [  
  1645.         StrOpt('log-config',  
  1646.                metavar='PATH',  
  1647.                help='If this option is specified, the logging configuration '  
  1648.                     'file specified is used and overrides any other logging '  
  1649.                     'options specified. Please see the Python logging module '  
  1650.                     'documentation for details on logging configuration '  
  1651.                     'files.'),  
  1652.         StrOpt('log-format',  
  1653.                default=DEFAULT_LOG_FORMAT,  
  1654.                metavar='FORMAT',  
  1655.                help='A logging.Formatter log message format string which may '  
  1656.                     'use any of the available logging.LogRecord attributes. '  
  1657.                     'Default: %default'),  
  1658.         StrOpt('log-date-format',  
  1659.                default=DEFAULT_LOG_DATE_FORMAT,  
  1660.                metavar='DATE_FORMAT',  
  1661.                help='Format string for %(asctime)s in log records. '  
  1662.                     'Default: %default'),  
  1663.         StrOpt('log-file',  
  1664.                metavar='PATH',  
  1665.                help='(Optional) Name of log file to output to. '  
  1666.                     'If not set, logging will go to stdout.'),  
  1667.         StrOpt('log-dir',  
  1668.                help='(Optional) The directory to keep log files in '  
  1669.                     '(will be prepended to --logfile)'),  
  1670.         BoolOpt('use-syslog',  
  1671.                 default=False,  
  1672.                 help='Use syslog for logging.'),  
  1673.         StrOpt('syslog-log-facility',  
  1674.                default='LOG_USER',  
  1675.                help='syslog facility to receive log lines')  
  1676.     ]  
  1677.   
  1678.     def __init__(self):  
  1679.         super(CommonConfigOpts, self).__init__()  
  1680.         self.register_cli_opts(self.common_cli_opts)  
  1681.         self.register_cli_opts(self.logging_cli_opts)  
  1682.   
  1683.   
  1684. CONF = CommonConfigOpts()  
  1685.       
  1686.       


革命尚未成功,同志仍需努力!