什么是oslo.config?
oslo.config是OpenStack用于解析配置文件和命令行参数的工具,大概是封装了argparse和configparse,令配置应用更方便。
官方文档:http://docs.openstack.org/developer/oslo.config
目前打算在项目sora中引入该库,简化程序配置方式
测试:
准备:安装oslo.config及组织相关目录
- pip install oslo.config
- mkdir oslo
- cd oslo
- touch app.conf
- touch registry.py
目录树:
相关代码:
- #app.conf
- [DEFAULT]
- #defautl这个section有的时候并不需要,但是如果注册的opts没有指定一个group,则会属于default组,建议写上
-
- [schedule]
- scheduler = simple
- enable = True
-
- [service]
- service_name = sora_compute
- service_id = 1213
- endpoint_ip = 10.20.10.70
- #registry.py
- from oslo.config import cfg
-
- schedule_opt_group = cfg.OptGroup(name='schedule',
- title='Scheduler Configuration') #注册一个组,name与app.conf中的schedule section对应
-
- scheduler_opts = [ #注册属于schedule_opt_group的配置选项,这里使用了StrOpt与BoolOpt
- cfg.StrOpt('scheduler',
- default='memory',
- help='The type of scheduler'),
- cfg.BoolOpt('enable',
- default='True',
- help='Enable the scheduler'),
- ]
-
- service_opt_group = cfg.OptGroup(name='service', #注册service组
- title='The service which use the scheduler')
-
- service_opts = [ #注册属于service_opts组的配置选项,用了StrOpt、IntOpt和IPOpt
- cfg.StrOpt('service',
- default='sora_compute',
- help='The default user service'),
- cfg.IntOpt('service_id',
- help='The service id'),
- cfg.IPOpt('endpoint_ip',
- help='The service endpoint ip'),
- ]
-
- MYCONF = cfg.CONF #注册一个对象,作为容器
- MYCONF.register_group(schedule_opt_group) #注册组
- MYCONF.register_group(service_opt_group)
- MYCONF.register_opts(scheduler_opts,group=schedule_opt_group) #注册以字典格式的配置选项,用group指定所属组
- MYCONF.register_opts(service_opts,group=service_opt_group)
- MYCONF(default_config_files=['/root/oslo/app.conf']) #注册配置文件,如果没有这个,将会使用default中的数据,配置文件可以为多个,用字典指定。注意绝对路径
使用oslo.config获取配置:
- >>> from oslo.config import cfg
- >>> import registry
- >>> print cfg.CONF.schedule.scheduler
- simple
- >>> print cfg.CONF.schedule.enable
- True
- >>> print cfg.CONF.service.service_id
- 1213
- >>> print cfg.CONF.service.endpoint_ip
- 10.20.10.70
可能的疑问:为什么导入了registry却不直接用它?
回答:这的确是一种奇怪的方式,但它可以工作。我们可以用一种更直观的方式使用registry:
- #例子来源于OpenStack源码
- from oslo.config import cfg
- cfg.CONF.import_opt('host','service') #指定从service.py(一个配置注册文件,类似上面的registry)导入host这个配置选项
- hostname = cfg.CONF.host
关于oslo.config所支持的配置选项有:
StrOpt:字符串类型
BoolOpt:布尔型
IntOpt:整数型
FloatOpt:浮点数型
ListOpt:字符串列表类型
DictOpt:字典类型,要求字典中的值为字符串类型
MultiStrOpt:可以分多次配置的字符串列表
IPOpt:Ip地址类型
OptGroup:组类型
在新的oslo.config中,还支持进行类型检查,不过目前大多数的OpenStack项目都用上文的方式配置,故不详细说明。
测试过程中的坑:
在注册配置选项时,如果像:
- enabled_apis_opt = cfg.ListOpt('enabled_apis',
- default=['ec2', 'osapi_compute'],
- help='List of APIs to enable by default.')
这样的单条配置选项,注册时用CONF.register_opt()
而多条配置选项时,需要用CONF.register_opts()。否则会报错
看到没?就差一个's',坑爹啊!
另外,在注册组中的配置项前,必须先注册组。
参考:
http://docs.openstack.org/developer/oslo.config
*http://www.lihuai.net/program/python/1698.html
http://www.sdnlab.com/5484.html
http://www.360doc.com/content/13/0814/22/3038654_307194414.shtml
http://blog.csdn.net/alvine008/article/details/24364243