OpenStack library for config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cfg.py 114KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228
  1. # Copyright 2012 Red Hat, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. # not use this file except in compliance with the License. You may obtain
  5. # a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. """Primary module in oslo_config.
  15. """
  16. import argparse
  17. import collections
  18. # TODO(smcginnis) update this once six has support for collections.abc
  19. # (https://github.com/benjaminp/six/pull/241) or clean up once we drop py2.7.
  20. try:
  21. from collections.abc import Mapping
  22. except ImportError:
  23. from collections import Mapping
  24. import copy
  25. import errno
  26. import functools
  27. import glob
  28. import inspect
  29. import itertools
  30. import logging
  31. import os
  32. import string
  33. import sys
  34. import enum
  35. import six
  36. # NOTE(bnemec): oslo.log depends on oslo.config, so we can't
  37. # have a hard dependency on oslo.log. However, in most cases
  38. # oslo.log will be installed so we can use it.
  39. try:
  40. import oslo_log
  41. except ImportError:
  42. oslo_log = None
  43. from oslo_config import iniparser
  44. from oslo_config import sources
  45. # Absolute import to avoid circular import in Python 2.7
  46. import oslo_config.sources._environment as _environment
  47. from oslo_config import types
  48. import stevedore
  49. LOG = logging.getLogger(__name__)
  50. _SOURCE_DRIVER_OPTION_HELP = (
  51. 'The name of the driver that can load this '
  52. 'configuration source.'
  53. )
  54. class Locations(enum.Enum):
  55. opt_default = (1, False)
  56. set_default = (2, False)
  57. set_override = (3, False)
  58. user = (4, True)
  59. command_line = (5, True)
  60. environment = (6, True)
  61. def __init__(self, num, is_user_controlled):
  62. self.num = num
  63. self.is_user_controlled = is_user_controlled
  64. LocationInfo = collections.namedtuple('LocationInfo', ['location', 'detail'])
  65. class Error(Exception):
  66. """Base class for cfg exceptions."""
  67. def __init__(self, msg=None):
  68. self.msg = msg
  69. def __str__(self):
  70. return self.msg
  71. class NotInitializedError(Error):
  72. """Raised if parser is not initialized yet."""
  73. def __str__(self):
  74. return "call expression on parser has not been invoked"
  75. class ArgsAlreadyParsedError(Error):
  76. """Raised if a CLI opt is registered after parsing."""
  77. def __str__(self):
  78. ret = "arguments already parsed"
  79. if self.msg:
  80. ret += ": " + self.msg
  81. return ret
  82. class NoSuchOptError(Error, AttributeError):
  83. """Raised if an opt which doesn't exist is referenced."""
  84. def __init__(self, opt_name, group=None):
  85. self.opt_name = opt_name
  86. self.group = group
  87. def __str__(self):
  88. group_name = 'DEFAULT' if self.group is None else self.group.name
  89. return "no such option %s in group [%s]" % (self.opt_name, group_name)
  90. class NoSuchGroupError(Error):
  91. """Raised if a group which doesn't exist is referenced."""
  92. def __init__(self, group_name):
  93. self.group_name = group_name
  94. def __str__(self):
  95. return "no such group [%s]" % self.group_name
  96. class DuplicateOptError(Error):
  97. """Raised if multiple opts with the same name are registered."""
  98. def __init__(self, opt_name):
  99. self.opt_name = opt_name
  100. def __str__(self):
  101. return "duplicate option: %s" % self.opt_name
  102. class RequiredOptError(Error):
  103. """Raised if an option is required but no value is supplied by the user."""
  104. def __init__(self, opt_name, group=None):
  105. self.opt_name = opt_name
  106. self.group = group
  107. def __str__(self):
  108. group_name = 'DEFAULT' if self.group is None else self.group.name
  109. return "value required for option %s in group [%s]" % (self.opt_name,
  110. group_name)
  111. class TemplateSubstitutionError(Error):
  112. """Raised if an error occurs substituting a variable in an opt value."""
  113. def __str__(self):
  114. return "template substitution error: %s" % self.msg
  115. class ConfigFilesNotFoundError(Error):
  116. """Raised if one or more config files are not found."""
  117. def __init__(self, config_files):
  118. self.config_files = config_files
  119. def __str__(self):
  120. return ('Failed to find some config files: %s' %
  121. ",".join(self.config_files))
  122. class ConfigFilesPermissionDeniedError(Error):
  123. """Raised if one or more config files are not readable."""
  124. def __init__(self, config_files):
  125. self.config_files = config_files
  126. def __str__(self):
  127. return ('Failed to open some config files: %s' %
  128. ",".join(self.config_files))
  129. class ConfigDirNotFoundError(Error):
  130. """Raised if the requested config-dir is not found."""
  131. def __init__(self, config_dir):
  132. self.config_dir = config_dir
  133. def __str__(self):
  134. return ('Failed to read config file directory: %s' % self.config_dir)
  135. class ConfigFileParseError(Error):
  136. """Raised if there is an error parsing a config file."""
  137. def __init__(self, config_file, msg):
  138. self.config_file = config_file
  139. self.msg = msg
  140. def __str__(self):
  141. return 'Failed to parse %s: %s' % (self.config_file, self.msg)
  142. class ConfigSourceValueError(Error, ValueError):
  143. """Raised if a config source value does not match its opt type."""
  144. pass
  145. class ConfigFileValueError(ConfigSourceValueError):
  146. """Raised if a config file value does not match its opt type."""
  147. pass
  148. class DefaultValueError(Error, ValueError):
  149. """Raised if a default config type does not fit the opt type."""
  150. def _fixpath(p):
  151. """Apply tilde expansion and absolutization to a path."""
  152. return os.path.abspath(os.path.expanduser(p))
  153. def _get_config_dirs(project=None):
  154. """Return a list of directories where config files may be located.
  155. :param project: an optional project name
  156. If a project is specified, following directories are returned::
  157. ~/.${project}/
  158. ~/
  159. /etc/${project}/
  160. /etc/
  161. If a project is specified and installed from a snap package, following
  162. directories are also returned:
  163. ${SNAP_COMMON}/etc/${project}
  164. ${SNAP}/etc/${project}
  165. Otherwise, if project is not specified, these directories are returned:
  166. ~/
  167. /etc/
  168. """
  169. snap = os.environ.get('SNAP')
  170. snap_c = os.environ.get('SNAP_COMMON')
  171. cfg_dirs = [
  172. _fixpath(os.path.join('~', '.' + project)) if project else None,
  173. _fixpath('~'),
  174. os.path.join('/etc', project) if project else None,
  175. '/etc',
  176. os.path.join(snap_c, "etc", project) if snap_c and project else None,
  177. os.path.join(snap, "etc", project) if snap and project else None,
  178. ]
  179. return [x for x in cfg_dirs if x]
  180. def _search_dirs(dirs, basename, extension=""):
  181. """Search a list of directories for a given filename or directory name.
  182. Iterator over the supplied directories, returning the first file
  183. found with the supplied name and extension.
  184. :param dirs: a list of directories
  185. :param basename: the filename or directory name, for example 'glance-api'
  186. :param extension: the file extension, for example '.conf'
  187. :returns: the path to a matching file or directory, or None
  188. """
  189. for d in dirs:
  190. path = os.path.join(d, '%s%s' % (basename, extension))
  191. if os.path.exists(path):
  192. return path
  193. def _find_config_files(project, prog, extension):
  194. if prog is None:
  195. prog = os.path.basename(sys.argv[0])
  196. if prog.endswith(".py"):
  197. prog = prog[:-3]
  198. cfg_dirs = _get_config_dirs(project)
  199. config_files = (_search_dirs(cfg_dirs, p, extension)
  200. for p in [project, prog] if p)
  201. return [x for x in config_files if x]
  202. def find_config_files(project=None, prog=None, extension='.conf'):
  203. """Return a list of default configuration files.
  204. :param project: an optional project name
  205. :param prog: the program name, defaulting to the basename of
  206. sys.argv[0], without extension .py
  207. :param extension: the type of the config file
  208. We default to two config files: [${project}.conf, ${prog}.conf]
  209. And we look for those config files in the following directories::
  210. ~/.${project}/
  211. ~/
  212. /etc/${project}/
  213. /etc/
  214. ${SNAP_COMMON}/etc/${project}
  215. ${SNAP}/etc/${project}
  216. We return an absolute path for (at most) one of each the default config
  217. files, for the topmost directory it exists in.
  218. For example, if project=foo, prog=bar and /etc/foo/foo.conf, /etc/bar.conf
  219. and ~/.foo/bar.conf all exist, then we return ['/etc/foo/foo.conf',
  220. '~/.foo/bar.conf']
  221. If no project name is supplied, we only look for ${prog}.conf.
  222. """
  223. return _find_config_files(project, prog, extension)
  224. def find_config_dirs(project=None, prog=None, extension='.conf.d'):
  225. """Return a list of default configuration dirs.
  226. :param project: an optional project name
  227. :param prog: the program name, defaulting to the basename of
  228. sys.argv[0], without extension .py
  229. :param extension: the type of the config directory. Defaults to '.conf.d'
  230. We default to two config dirs: [${project}.conf.d/, ${prog}.conf.d/].
  231. If no project name is supplied, we only look for ${prog.conf.d/}.
  232. And we look for those config dirs in the following directories::
  233. ~/.${project}/
  234. ~/
  235. /etc/${project}/
  236. /etc/
  237. ${SNAP_COMMON}/etc/${project}
  238. ${SNAP}/etc/${project}
  239. We return an absolute path for each of the two config dirs,
  240. in the first place we find it (iff we find it).
  241. For example, if project=foo, prog=bar and /etc/foo/foo.conf.d/,
  242. /etc/bar.conf.d/ and ~/.foo/bar.conf.d/ all exist, then we return
  243. ['/etc/foo/foo.conf.d/', '~/.foo/bar.conf.d/']
  244. """
  245. return _find_config_files(project, prog, extension)
  246. def _is_opt_registered(opts, opt):
  247. """Check whether an opt with the same name is already registered.
  248. The same opt may be registered multiple times, with only the first
  249. registration having any effect. However, it is an error to attempt
  250. to register a different opt with the same name.
  251. :param opts: the set of opts already registered
  252. :param opt: the opt to be registered
  253. :returns: True if the opt was previously registered, False otherwise
  254. :raises: DuplicateOptError if a naming conflict is detected
  255. """
  256. if opt.dest in opts:
  257. if opts[opt.dest]['opt'] != opt:
  258. raise DuplicateOptError(opt.name)
  259. return True
  260. else:
  261. return False
  262. _show_caller_details = bool(os.environ.get(
  263. 'OSLO_CONFIG_SHOW_CODE_LOCATIONS'))
  264. def _get_caller_detail(n=2):
  265. """Return a string describing where this is being called from.
  266. :param n: Number of steps up the stack to look. Defaults to ``2``.
  267. :type n: int
  268. :returns: str
  269. """
  270. if not _show_caller_details:
  271. return None
  272. s = inspect.stack()[:n + 1]
  273. try:
  274. frame = s[n]
  275. try:
  276. return frame[1]
  277. # WARNING(dhellmann): Using frame.lineno to include the
  278. # line number in the return value causes some sort of
  279. # memory or stack corruption that manifests in values not
  280. # being cleaned up in the cfgfilter tests.
  281. # return '%s:%s' % (frame[1], frame[2])
  282. finally:
  283. del frame
  284. finally:
  285. del s
  286. def set_defaults(opts, **kwargs):
  287. for opt in opts:
  288. if opt.dest in kwargs:
  289. opt.default = kwargs[opt.dest]
  290. opt._set_location = LocationInfo(Locations.set_default,
  291. _get_caller_detail())
  292. def _normalize_group_name(group_name):
  293. if group_name == 'DEFAULT':
  294. return group_name
  295. return group_name.lower()
  296. def _report_deprecation(format_str, format_dict):
  297. """Report use of a deprecated option
  298. Uses versionutils from oslo.log if it is available. If not, logs
  299. a simple warning message.
  300. :param format_str: The message to use for the report
  301. :param format_dict: A dict containing keys for any parameters in format_str
  302. """
  303. if oslo_log:
  304. # We can't import versionutils at the module level because of circular
  305. # imports. Importing just oslo_log at the module level and
  306. # versionutils locally allows us to unit test this and still avoid the
  307. # circular problem.
  308. from oslo_log import versionutils
  309. versionutils.report_deprecated_feature(LOG, format_str,
  310. format_dict)
  311. else:
  312. LOG.warning(format_str, format_dict)
  313. @functools.total_ordering
  314. class Opt(object):
  315. """Base class for all configuration options.
  316. The only required parameter is the option's name. However, it is
  317. common to also supply a default and help string for all options.
  318. :param name: the option's name
  319. :param type: the option's type. Must be a callable object that takes string
  320. and returns converted and validated value
  321. :param dest: the name of the corresponding :class:`.ConfigOpts` property
  322. :param short: a single character CLI option name
  323. :param default: the default value of the option
  324. :param positional: True if the option is a positional CLI argument
  325. :param metavar: the option argument to show in --help
  326. :param help: an explanation of how the option is used
  327. :param secret: true if the value should be obfuscated in log output
  328. :param required: true if a value must be supplied for this option
  329. :param deprecated_name: deprecated name option. Acts like an alias
  330. :param deprecated_group: the group containing a deprecated alias
  331. :param deprecated_opts: list of :class:`.DeprecatedOpt`
  332. :param sample_default: a default string for sample config files
  333. :param deprecated_for_removal: indicates whether this opt is planned for
  334. removal in a future release
  335. :param deprecated_reason: indicates why this opt is planned for removal in
  336. a future release. Silently ignored if
  337. deprecated_for_removal is False
  338. :param deprecated_since: indicates which release this opt was deprecated
  339. in. Accepts any string, though valid version
  340. strings are encouraged. Silently ignored if
  341. deprecated_for_removal is False
  342. :param mutable: True if this option may be reloaded
  343. :param advanced: a bool True/False value if this option has advanced usage
  344. and is not normally used by the majority of users
  345. An Opt object has no public methods, but has a number of public properties:
  346. .. py:attribute:: name
  347. the name of the option, which may include hyphens
  348. .. py:attribute:: type
  349. a callable object that takes string and returns converted and
  350. validated value. Default types are available from
  351. :class:`oslo_config.types`
  352. .. py:attribute:: dest
  353. the (hyphen-less) :class:`.ConfigOpts` property which contains the
  354. option value
  355. .. py:attribute:: short
  356. a single character CLI option name
  357. .. py:attribute:: default
  358. the default value of the option
  359. .. py:attribute:: sample_default
  360. a sample default value string to include in sample config files
  361. .. py:attribute:: positional
  362. True if the option is a positional CLI argument
  363. .. py:attribute:: metavar
  364. the name shown as the argument to a CLI option in --help output
  365. .. py:attribute:: help
  366. a string explaining how the option's value is used
  367. .. py:attribute:: advanced
  368. in sample files, a bool value indicating the option is advanced
  369. .. versionchanged:: 1.2
  370. Added *deprecated_opts* parameter.
  371. .. versionchanged:: 1.4
  372. Added *sample_default* parameter.
  373. .. versionchanged:: 1.9
  374. Added *deprecated_for_removal* parameter.
  375. .. versionchanged:: 2.7
  376. An exception is now raised if the default value has the wrong type.
  377. .. versionchanged:: 3.2
  378. Added *deprecated_reason* parameter.
  379. .. versionchanged:: 3.5
  380. Added *mutable* parameter.
  381. .. versionchanged:: 3.12
  382. Added *deprecated_since* parameter.
  383. .. versionchanged:: 3.15
  384. Added *advanced* parameter and attribute.
  385. """
  386. multi = False
  387. def __init__(self, name, type=None, dest=None, short=None,
  388. default=None, positional=False, metavar=None, help=None,
  389. secret=False, required=False,
  390. deprecated_name=None, deprecated_group=None,
  391. deprecated_opts=None, sample_default=None,
  392. deprecated_for_removal=False, deprecated_reason=None,
  393. deprecated_since=None, mutable=False, advanced=False):
  394. if name.startswith('_'):
  395. raise ValueError('illegal name %s with prefix _' % (name,))
  396. self.name = name
  397. if type is None:
  398. type = types.String()
  399. if not callable(type):
  400. raise TypeError('type must be callable')
  401. self.type = type
  402. if dest is None:
  403. self.dest = self.name.replace('-', '_')
  404. else:
  405. self.dest = dest
  406. self.short = short
  407. self.default = default
  408. self.sample_default = sample_default
  409. self.positional = positional
  410. self.metavar = metavar
  411. self.help = help
  412. self.secret = secret
  413. self.required = required
  414. self.deprecated_for_removal = deprecated_for_removal
  415. self.deprecated_reason = deprecated_reason
  416. self.deprecated_since = deprecated_since
  417. self._logged_deprecation = False
  418. if self.__class__ is Opt:
  419. stack_depth = 2 # someone instantiated Opt directly
  420. else:
  421. stack_depth = 3 # skip the call to the child class constructor
  422. self._set_location = LocationInfo(
  423. Locations.opt_default,
  424. _get_caller_detail(stack_depth),
  425. )
  426. self.deprecated_opts = copy.deepcopy(deprecated_opts) or []
  427. for o in self.deprecated_opts:
  428. if '-' in o.name:
  429. self.deprecated_opts.append(DeprecatedOpt(
  430. o.name.replace('-', '_'),
  431. group=o.group))
  432. if deprecated_name is not None or deprecated_group is not None:
  433. self.deprecated_opts.append(DeprecatedOpt(deprecated_name,
  434. group=deprecated_group))
  435. if deprecated_name and '-' in deprecated_name:
  436. self.deprecated_opts.append(DeprecatedOpt(
  437. deprecated_name.replace('-', '_'),
  438. group=deprecated_group))
  439. self._check_default()
  440. self.mutable = mutable
  441. self.advanced = advanced
  442. def _default_is_ref(self):
  443. """Check if default is a reference to another var."""
  444. if isinstance(self.default, six.string_types):
  445. tmpl = self.default.replace(r'\$', '').replace('$$', '')
  446. return '$' in tmpl
  447. return False
  448. def _check_default(self):
  449. if (self.default is not None
  450. and not self._default_is_ref()):
  451. try:
  452. self.type(self.default)
  453. except Exception:
  454. raise DefaultValueError("Error processing default value "
  455. "%(default)s for Opt type of %(opt)s."
  456. % {'default': self.default,
  457. 'opt': self.type})
  458. def _vars_for_cmp(self):
  459. # NOTE(dhellmann): Get the instance variables of this Opt and
  460. # then make a new dictionary so we can modify the contents
  461. # before returning it without removing any attributes of the
  462. # object.
  463. v = dict(vars(self))
  464. # NOTE(dhellmann): Ignore the location where the option is
  465. # defined when comparing them. Ideally we could use this to
  466. # detect duplicate settings in code bases, but as long as the
  467. # options match otherwise they should be safe.
  468. if '_set_location' in v:
  469. del v['_set_location']
  470. return v
  471. def __ne__(self, another):
  472. return self._vars_for_cmp() != another._vars_for_cmp()
  473. def __eq__(self, another):
  474. return self._vars_for_cmp() == another._vars_for_cmp()
  475. __hash__ = object.__hash__
  476. def _get_from_namespace(self, namespace, group_name):
  477. """Retrieves the option value from a _Namespace object.
  478. :param namespace: a _Namespace object
  479. :param group_name: a group name
  480. """
  481. names = [(group_name, self.dest)]
  482. current_name = (group_name, self.name)
  483. for opt in self.deprecated_opts:
  484. dname, dgroup = opt.name, opt.group
  485. if dname or dgroup:
  486. names.append((dgroup if dgroup else group_name,
  487. dname if dname else self.dest))
  488. value, loc = namespace._get_value(
  489. names, multi=self.multi,
  490. positional=self.positional, current_name=current_name)
  491. # The previous line will raise a KeyError if no value is set in the
  492. # config file, so we'll only log deprecations for set options.
  493. if self.deprecated_for_removal and not self._logged_deprecation:
  494. self._logged_deprecation = True
  495. pretty_group = group_name or 'DEFAULT'
  496. if self.deprecated_reason:
  497. pretty_reason = ' ({})'.format(self.deprecated_reason)
  498. else:
  499. pretty_reason = ''
  500. format_str = ('Option "%(option)s" from group "%(group)s" is '
  501. 'deprecated for removal%(reason)s. Its value may '
  502. 'be silently ignored in the future.')
  503. format_dict = {'option': self.dest,
  504. 'group': pretty_group,
  505. 'reason': pretty_reason}
  506. _report_deprecation(format_str, format_dict)
  507. return (value, loc)
  508. def _add_to_cli(self, parser, group=None):
  509. """Makes the option available in the command line interface.
  510. This is the method ConfigOpts uses to add the opt to the CLI interface
  511. as appropriate for the opt type. Some opt types may extend this method,
  512. others may just extend the helper methods it uses.
  513. :param parser: the CLI option parser
  514. :param group: an optional OptGroup object
  515. """
  516. container = self._get_argparse_container(parser, group)
  517. kwargs = self._get_argparse_kwargs(group)
  518. prefix = self._get_argparse_prefix('', group.name if group else None)
  519. deprecated_names = []
  520. for opt in self.deprecated_opts:
  521. deprecated_name = self._get_deprecated_cli_name(opt.name,
  522. opt.group)
  523. if deprecated_name is not None:
  524. deprecated_names.append(deprecated_name)
  525. self._add_to_argparse(parser, container, self.name, self.short,
  526. kwargs, prefix,
  527. self.positional, deprecated_names)
  528. def _add_to_argparse(self, parser, container, name, short, kwargs,
  529. prefix='', positional=False, deprecated_names=None):
  530. """Add an option to an argparse parser or group.
  531. :param container: an argparse._ArgumentGroup object
  532. :param name: the opt name
  533. :param short: the short opt name
  534. :param kwargs: the keyword arguments for add_argument()
  535. :param prefix: an optional prefix to prepend to the opt name
  536. :param positional: whether the option is a positional CLI argument
  537. :param deprecated_names: list of deprecated option names
  538. """
  539. def hyphen(arg):
  540. return arg if not positional else ''
  541. args = [hyphen('--') + prefix + name]
  542. if short:
  543. args.append(hyphen('-') + short)
  544. for deprecated_name in deprecated_names:
  545. args.append(hyphen('--') + deprecated_name)
  546. parser.add_parser_argument(container, *args, **kwargs)
  547. def _get_argparse_container(self, parser, group):
  548. """Returns an argparse._ArgumentGroup.
  549. :param parser: an argparse.ArgumentParser
  550. :param group: an (optional) OptGroup object
  551. :returns: an argparse._ArgumentGroup if group is given, else parser
  552. """
  553. if group is not None:
  554. return group._get_argparse_group(parser)
  555. else:
  556. return parser
  557. def _get_argparse_kwargs(self, group, **kwargs):
  558. r"""Build a dict of keyword arguments for argparse's add_argument().
  559. Most opt types extend this method to customize the behaviour of the
  560. options added to argparse.
  561. :param group: an optional group
  562. :param \*\*kwargs: optional keyword arguments to add to
  563. :returns: a dict of keyword arguments
  564. """
  565. if not self.positional:
  566. dest = self.dest
  567. if group is not None:
  568. dest = group.name + '_' + dest
  569. kwargs['dest'] = dest
  570. else:
  571. kwargs['nargs'] = '?'
  572. kwargs.update({'default': None,
  573. 'metavar': self.metavar,
  574. 'help': self.help, })
  575. return kwargs
  576. def _get_argparse_prefix(self, prefix, group_name):
  577. """Build a prefix for the CLI option name, if required.
  578. CLI options in a group are prefixed with the group's name in order
  579. to avoid conflicts between similarly named options in different
  580. groups.
  581. :param prefix: an existing prefix to append to (for example 'no' or '')
  582. :param group_name: an optional group name
  583. :returns: a CLI option prefix including the group name, if appropriate
  584. """
  585. if group_name is not None:
  586. return group_name + '-' + prefix
  587. else:
  588. return prefix
  589. def _get_deprecated_cli_name(self, dname, dgroup, prefix=''):
  590. """Build a CLi arg name for deprecated options.
  591. Either a deprecated name or a deprecated group or both or
  592. neither can be supplied:
  593. dname, dgroup -> dgroup + '-' + dname
  594. dname -> dname
  595. dgroup -> dgroup + '-' + self.name
  596. neither -> None
  597. :param dname: a deprecated name, which can be None
  598. :param dgroup: a deprecated group, which can be None
  599. :param prefix: an prefix to append to (for example 'no' or '')
  600. :returns: a CLI argument name
  601. """
  602. if dgroup == 'DEFAULT':
  603. dgroup = None
  604. if dname is None and dgroup is None:
  605. return None
  606. if dname is None:
  607. dname = self.name
  608. return self._get_argparse_prefix(prefix, dgroup) + dname
  609. def __lt__(self, another):
  610. return hash(self) < hash(another)
  611. class DeprecatedOpt(object):
  612. """Represents a Deprecated option.
  613. Here's how you can use it::
  614. oldopts = [cfg.DeprecatedOpt('oldopt1', group='group1'),
  615. cfg.DeprecatedOpt('oldopt2', group='group2')]
  616. cfg.CONF.register_group(cfg.OptGroup('group1'))
  617. cfg.CONF.register_opt(cfg.StrOpt('newopt', deprecated_opts=oldopts),
  618. group='group1')
  619. For options which have a single value (like in the example above),
  620. if the new option is present ("[group1]/newopt" above), it will override
  621. any deprecated options present ("[group1]/oldopt1" and "[group2]/oldopt2"
  622. above).
  623. If no group is specified for a DeprecatedOpt option (i.e. the group is
  624. None), lookup will happen within the same group the new option is in.
  625. For example, if no group was specified for the second option 'oldopt2' in
  626. oldopts list::
  627. oldopts = [cfg.DeprecatedOpt('oldopt1', group='group1'),
  628. cfg.DeprecatedOpt('oldopt2')]
  629. cfg.CONF.register_group(cfg.OptGroup('group1'))
  630. cfg.CONF.register_opt(cfg.StrOpt('newopt', deprecated_opts=oldopts),
  631. group='group1')
  632. then lookup for that option will happen in group 'group1'.
  633. If the new option is not present and multiple deprecated options are
  634. present, the option corresponding to the first element of deprecated_opts
  635. will be chosen.
  636. Multi-value options will return all new and deprecated
  637. options. So if we have a multi-value option "[group1]/opt1" whose
  638. deprecated option is "[group2]/opt2", and the conf file has both these
  639. options specified like so::
  640. [group1]
  641. opt1=val10,val11
  642. [group2]
  643. opt2=val21,val22
  644. Then the value of "[group1]/opt1" will be ['val10', 'val11', 'val21',
  645. 'val22'].
  646. .. versionadded:: 1.2
  647. """
  648. def __init__(self, name, group=None):
  649. """Constructs an DeprecatedOpt object.
  650. :param name: the name of the option
  651. :param group: the group of the option
  652. """
  653. self.name = name
  654. self.group = group
  655. def __key(self):
  656. return (self.name, self.group)
  657. def __eq__(self, other):
  658. return self.__key() == other.__key()
  659. def __hash__(self):
  660. return hash(self.__key())
  661. class StrOpt(Opt):
  662. r"""Option with String type
  663. Option with ``type`` :class:`oslo_config.types.String`
  664. :param name: the option's name
  665. :param choices: Optional sequence of either valid values or tuples of valid
  666. values with descriptions.
  667. :param quotes: If True and string is enclosed with single or double
  668. quotes, will strip those quotes.
  669. :param regex: Optional regular expression (string or compiled
  670. regex) that the value must match on an unanchored
  671. search.
  672. :param ignore_case: If True case differences (uppercase vs. lowercase)
  673. between 'choices' or 'regex' will be ignored.
  674. :param max_length: If positive integer, the value must be less than or
  675. equal to this parameter.
  676. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  677. .. versionchanged:: 2.7
  678. Added *quotes* parameter
  679. .. versionchanged:: 2.7
  680. Added *regex* parameter
  681. .. versionchanged:: 2.7
  682. Added *ignore_case* parameter
  683. .. versionchanged:: 2.7
  684. Added *max_length* parameter
  685. .. versionchanged:: 5.2
  686. The *choices* parameter will now accept a sequence of tuples, where each
  687. tuple is of form (*choice*, *description*)
  688. """
  689. def __init__(self, name, choices=None, quotes=None,
  690. regex=None, ignore_case=False, max_length=None, **kwargs):
  691. super(StrOpt, self).__init__(name,
  692. type=types.String(
  693. choices=choices,
  694. quotes=quotes,
  695. regex=regex,
  696. ignore_case=ignore_case,
  697. max_length=max_length),
  698. **kwargs)
  699. def _get_choice_text(self, choice):
  700. if choice is None:
  701. return '<None>'
  702. elif choice == '':
  703. return "''"
  704. return six.text_type(choice)
  705. def _get_argparse_kwargs(self, group, **kwargs):
  706. """Extends the base argparse keyword dict for the config dir option."""
  707. kwargs = super(StrOpt, self)._get_argparse_kwargs(group)
  708. if getattr(self.type, 'choices', None):
  709. choices_text = ', '.join([self._get_choice_text(choice)
  710. for choice in self.type.choices])
  711. if kwargs['help'] is None:
  712. kwargs['help'] = ''
  713. kwargs['help'].rstrip('\n')
  714. kwargs['help'] += '\n Allowed values: %s\n' % choices_text
  715. return kwargs
  716. class BoolOpt(Opt):
  717. r"""Boolean options.
  718. Bool opts are set to True or False on the command line using --optname or
  719. --nooptname respectively.
  720. In config files, boolean values are cast with Boolean type.
  721. :param name: the option's name
  722. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  723. """
  724. def __init__(self, name, **kwargs):
  725. if 'positional' in kwargs:
  726. raise ValueError('positional boolean args not supported')
  727. super(BoolOpt, self).__init__(name, type=types.Boolean(), **kwargs)
  728. def _add_to_cli(self, parser, group=None):
  729. """Extends the base class method to add the --nooptname option."""
  730. super(BoolOpt, self)._add_to_cli(parser, group)
  731. self._add_inverse_to_argparse(parser, group)
  732. def _add_inverse_to_argparse(self, parser, group):
  733. """Add the --nooptname option to the option parser."""
  734. container = self._get_argparse_container(parser, group)
  735. kwargs = self._get_argparse_kwargs(group, action='store_false')
  736. prefix = self._get_argparse_prefix('no', group.name if group else None)
  737. deprecated_names = []
  738. for opt in self.deprecated_opts:
  739. deprecated_name = self._get_deprecated_cli_name(opt.name,
  740. opt.group,
  741. prefix='no')
  742. if deprecated_name is not None:
  743. deprecated_names.append(deprecated_name)
  744. kwargs["help"] = "The inverse of --" + self.name
  745. self._add_to_argparse(parser, container, self.name, None, kwargs,
  746. prefix, self.positional, deprecated_names)
  747. def _get_argparse_kwargs(self, group, action='store_true', **kwargs):
  748. """Extends the base argparse keyword dict for boolean options."""
  749. kwargs = super(BoolOpt, self)._get_argparse_kwargs(group, **kwargs)
  750. # type has no effect for BoolOpt, it only matters for
  751. # values that came from config files
  752. if 'type' in kwargs:
  753. del kwargs['type']
  754. # metavar has no effect for BoolOpt
  755. if 'metavar' in kwargs:
  756. del kwargs['metavar']
  757. kwargs['action'] = action
  758. return kwargs
  759. class IntOpt(Opt):
  760. r"""Option with Integer type
  761. Option with ``type`` :class:`oslo_config.types.Integer`
  762. :param name: the option's name
  763. :param min: minimum value the integer can take
  764. :param max: maximum value the integer can take
  765. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  766. .. versionchanged:: 1.15
  767. Added *min* and *max* parameters.
  768. """
  769. def __init__(self, name, min=None, max=None, **kwargs):
  770. super(IntOpt, self).__init__(name, type=types.Integer(min, max),
  771. **kwargs)
  772. class FloatOpt(Opt):
  773. r"""Option with Float type
  774. Option with ``type`` :class:`oslo_config.types.Float`
  775. :param name: the option's name
  776. :param min: minimum value the float can take
  777. :param max: maximum value the float can take
  778. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  779. .. versionchanged:: 3.14
  780. Added *min* and *max* parameters.
  781. """
  782. def __init__(self, name, min=None, max=None, **kwargs):
  783. super(FloatOpt, self).__init__(name, type=types.Float(min, max),
  784. **kwargs)
  785. class ListOpt(Opt):
  786. r"""Option with List(String) type
  787. Option with ``type`` :class:`oslo_config.types.List`
  788. :param name: the option's name
  789. :param item_type: type of items (see :class:`oslo_config.types`)
  790. :param bounds: if True the value should be inside "[" and "]" pair
  791. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  792. .. versionchanged:: 2.5
  793. Added *item_type* and *bounds* parameters.
  794. """
  795. def __init__(self, name, item_type=None, bounds=None, **kwargs):
  796. super(ListOpt, self).__init__(name,
  797. type=types.List(item_type=item_type,
  798. bounds=bounds),
  799. **kwargs)
  800. class DictOpt(Opt):
  801. r"""Option with Dict(String) type
  802. Option with ``type`` :class:`oslo_config.types.Dict`
  803. :param name: the option's name
  804. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  805. .. versionadded:: 1.2
  806. """
  807. def __init__(self, name, **kwargs):
  808. super(DictOpt, self).__init__(name, type=types.Dict(), **kwargs)
  809. class IPOpt(Opt):
  810. r"""Opt with IPAddress type
  811. Option with ``type`` :class:`oslo_config.types.IPAddress`
  812. :param name: the option's name
  813. :param version: one of either ``4``, ``6``, or ``None`` to specify
  814. either version.
  815. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  816. .. versionadded:: 1.4
  817. """
  818. def __init__(self, name, version=None, **kwargs):
  819. super(IPOpt, self).__init__(name, type=types.IPAddress(version),
  820. **kwargs)
  821. class PortOpt(Opt):
  822. r"""Option for a TCP/IP port number. Ports can range from 0 to 65535.
  823. Option with ``type`` :class:`oslo_config.types.Integer`
  824. :param name: the option's name
  825. :param min: minimum value the port can take
  826. :param max: maximum value the port can take
  827. :param choices: Optional sequence of either valid values or tuples of valid
  828. values with descriptions.
  829. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  830. .. versionadded:: 2.6
  831. .. versionchanged:: 3.2
  832. Added *choices* parameter.
  833. .. versionchanged:: 3.4
  834. Allow port number with 0.
  835. .. versionchanged:: 3.16
  836. Added *min* and *max* parameters.
  837. .. versionchanged:: 5.2
  838. The *choices* parameter will now accept a sequence of tuples, where each
  839. tuple is of form (*choice*, *description*)
  840. """
  841. def __init__(self, name, min=None, max=None, choices=None, **kwargs):
  842. type = types.Port(min=min, max=max, choices=choices,
  843. type_name='port value')
  844. super(PortOpt, self).__init__(name, type=type, **kwargs)
  845. class HostnameOpt(Opt):
  846. r"""Option for a hostname. Only accepts valid hostnames.
  847. Option with ``type`` :class:`oslo_config.types.Hostname`
  848. :param name: the option's name
  849. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  850. .. versionadded:: 3.8
  851. """
  852. def __init__(self, name, **kwargs):
  853. super(HostnameOpt, self).__init__(name, type=types.Hostname(),
  854. **kwargs)
  855. class HostAddressOpt(Opt):
  856. r"""Option for either an IP or a hostname.
  857. Accepts valid hostnames and valid IP addresses.
  858. Option with ``type`` :class:`oslo_config.types.HostAddress`
  859. :param name: the option's name
  860. :param version: one of either ``4``, ``6``, or ``None`` to specify
  861. either version.
  862. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  863. .. versionadded:: 3.22
  864. """
  865. def __init__(self, name, version=None, **kwargs):
  866. super(HostAddressOpt, self).__init__(name,
  867. type=types.HostAddress(version),
  868. **kwargs)
  869. class URIOpt(Opt):
  870. r"""Opt with URI type
  871. Option with ``type`` :class:`oslo_config.types.URI`
  872. :param name: the option's name
  873. :param max_length: If positive integer, the value must be less than or
  874. equal to this parameter.
  875. :param schemes: list of valid URI schemes, e.g. 'https', 'ftp', 'git'
  876. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  877. .. versionadded:: 3.12
  878. .. versionchanged:: 3.14
  879. Added *max_length* parameter
  880. .. versionchanged:: 3.18
  881. Added *schemes* parameter
  882. """
  883. def __init__(self, name, max_length=None, schemes=None, **kwargs):
  884. type = types.URI(max_length=max_length, schemes=schemes)
  885. super(URIOpt, self).__init__(name, type=type, **kwargs)
  886. class MultiOpt(Opt):
  887. r"""Multi-value option.
  888. Multi opt values are typed opts which may be specified multiple times.
  889. The opt value is a list containing all the values specified.
  890. :param name: the option's name
  891. :param item_type: Type of items (see :class:`oslo_config.types`)
  892. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`Opt`
  893. For example::
  894. cfg.MultiOpt('foo',
  895. item_type=types.Integer(),
  896. default=None,
  897. help="Multiple foo option")
  898. The command line ``--foo=1 --foo=2`` would result in ``cfg.CONF.foo``
  899. containing ``[1,2]``
  900. .. versionadded:: 1.3
  901. """
  902. multi = True
  903. def __init__(self, name, item_type, **kwargs):
  904. super(MultiOpt, self).__init__(name, item_type, **kwargs)
  905. def _get_argparse_kwargs(self, group, **kwargs):
  906. """Extends the base argparse keyword dict for multi value options."""
  907. kwargs = super(MultiOpt, self)._get_argparse_kwargs(group)
  908. if not self.positional:
  909. kwargs['action'] = 'append'
  910. else:
  911. kwargs['nargs'] = '*'
  912. return kwargs
  913. class MultiStrOpt(MultiOpt):
  914. r"""MultiOpt with a MultiString ``item_type``.
  915. MultiOpt with a default :class:`oslo_config.types.MultiString` item
  916. type.
  917. :param name: the option's name
  918. :param \*\*kwargs: arbitrary keyword arguments passed to :class:`MultiOpt`
  919. """
  920. def __init__(self, name, **kwargs):
  921. super(MultiStrOpt, self).__init__(name,
  922. item_type=types.MultiString(),
  923. **kwargs)
  924. class SubCommandOpt(Opt):
  925. """Sub-command options.
  926. Sub-command options allow argparse sub-parsers to be used to parse
  927. additional command line arguments.
  928. The handler argument to the SubCommandOpt constructor is a callable
  929. which is supplied an argparse subparsers object. Use this handler
  930. callable to add sub-parsers.
  931. The opt value is SubCommandAttr object with the name of the chosen
  932. sub-parser stored in the 'name' attribute and the values of other
  933. sub-parser arguments available as additional attributes.
  934. :param name: the option's name
  935. :param dest: the name of the corresponding :class:`.ConfigOpts` property
  936. :param handler: callable which is supplied subparsers object when invoked
  937. :param title: title of the sub-commands group in help output
  938. :param description: description of the group in help output
  939. :param help: a help string giving an overview of available sub-commands
  940. """
  941. def __init__(self, name, dest=None, handler=None,
  942. title=None, description=None, help=None):
  943. """Construct an sub-command parsing option.
  944. This behaves similarly to other Opt sub-classes but adds a
  945. 'handler' argument. The handler is a callable which is supplied
  946. an subparsers object when invoked. The add_parser() method on
  947. this subparsers object can be used to register parsers for
  948. sub-commands.
  949. """
  950. super(SubCommandOpt, self).__init__(name, type=types.String(),
  951. dest=dest, help=help)
  952. self.handler = handler
  953. self.title = title
  954. self.description = description
  955. def _add_to_cli(self, parser, group=None):
  956. """Add argparse sub-parsers and invoke the handler method."""
  957. dest = self.dest
  958. if group is not None:
  959. dest = group.name + '_' + dest
  960. subparsers = parser.add_subparsers(dest=dest,
  961. title=self.title,
  962. description=self.description,
  963. help=self.help)
  964. # NOTE(jd) Set explicitly to True for Python 3
  965. # See http://bugs.python.org/issue9253 for context
  966. subparsers.required = True
  967. if self.handler is not None:
  968. self.handler(subparsers)
  969. class _ConfigFileOpt(Opt):
  970. """The --config-file option.
  971. This is an private option type which handles the special processing
  972. required for --config-file options.
  973. As each --config-file option is encountered on the command line, we
  974. parse the file and store the parsed values in the _Namespace object.
  975. This allows us to properly handle the precedence of --config-file
  976. options over previous command line arguments, but not over subsequent
  977. arguments.
  978. .. versionadded:: 1.2
  979. """
  980. class ConfigFileAction(argparse.Action):
  981. """An argparse action for --config-file.
  982. As each --config-file option is encountered, this action adds the
  983. value to the config_file attribute on the _Namespace object but also
  984. parses the configuration file and stores the values found also in
  985. the _Namespace object.
  986. """
  987. def __call__(self, parser, namespace, values, option_string=None):
  988. """Handle a --config-file command line argument.
  989. :raises: ConfigFileParseError, ConfigFileValueError
  990. """
  991. if getattr(namespace, self.dest, None) is None:
  992. setattr(namespace, self.dest, [])
  993. items = getattr(namespace, self.dest)
  994. items.append(values)
  995. ConfigParser._parse_file(values, namespace)
  996. def __init__(self, name, **kwargs):
  997. super(_ConfigFileOpt, self).__init__(name, lambda x: x, **kwargs)
  998. def _get_argparse_kwargs(self, group, **kwargs):
  999. """Extends the base argparse keyword dict for the config file opt."""
  1000. kwargs = super(_ConfigFileOpt, self)._get_argparse_kwargs(group)
  1001. kwargs['action'] = self.ConfigFileAction
  1002. return kwargs
  1003. class _ConfigDirOpt(Opt):
  1004. """The --config-dir option.
  1005. This is an private option type which handles the special processing
  1006. required for --config-dir options.
  1007. As each --config-dir option is encountered on the command line, we
  1008. parse the files in that directory and store the parsed values in the
  1009. _Namespace object. This allows us to properly handle the precedence of
  1010. --config-dir options over previous command line arguments, but not
  1011. over subsequent arguments.
  1012. .. versionadded:: 1.2
  1013. """
  1014. class ConfigDirAction(argparse.Action):
  1015. """An argparse action for --config-dir.
  1016. As each --config-dir option is encountered, this action sets the
  1017. config_dir attribute on the _Namespace object but also parses the
  1018. configuration files and stores the values found also in the
  1019. _Namespace object.
  1020. """
  1021. def __call__(self, parser, namespace, values, option_string=None):
  1022. """Handle a --config-dir command line argument.
  1023. :raises: ConfigFileParseError, ConfigFileValueError,
  1024. ConfigDirNotFoundError
  1025. """
  1026. namespace._config_dirs.append(values)
  1027. setattr(namespace, self.dest, values)
  1028. values = os.path.expanduser(values)
  1029. if not os.path.exists(values):
  1030. raise ConfigDirNotFoundError(values)
  1031. config_dir_glob = os.path.join(values, '*.conf')
  1032. for config_file in sorted(glob.glob(config_dir_glob)):
  1033. ConfigParser._parse_file(config_file, namespace)
  1034. def __init__(self, name, **kwargs):
  1035. super(_ConfigDirOpt, self).__init__(name, type=types.List(),
  1036. **kwargs)
  1037. def _get_argparse_kwargs(self, group, **kwargs):
  1038. """Extends the base argparse keyword dict for the config dir option."""
  1039. kwargs = super(_ConfigDirOpt, self)._get_argparse_kwargs(group)
  1040. kwargs['action'] = self.ConfigDirAction
  1041. return kwargs
  1042. class OptGroup(object):
  1043. """Represents a group of opts.
  1044. CLI opts in the group are automatically prefixed with the group name.
  1045. Each group corresponds to a section in config files.
  1046. An OptGroup object has no public methods, but has a number of public string
  1047. properties:
  1048. .. py:attribute:: name
  1049. the name of the group
  1050. .. py:attribute:: title
  1051. the group title as displayed in --help
  1052. .. py:attribute:: help
  1053. the group description as displayed in --help
  1054. :param name: the group name
  1055. :type name: str
  1056. :param title: the group title for --help
  1057. :type title: str
  1058. :param help: the group description for --help
  1059. :type help: str
  1060. :param dynamic_group_owner: The name of the option that controls
  1061. repeated instances of this group.
  1062. :type dynamic_group_owner: str
  1063. :param driver_option: The name of the option within the group that
  1064. controls which driver will register options.
  1065. :type driver_option: str
  1066. """
  1067. def __init__(self, name, title=None, help=None,
  1068. dynamic_group_owner='',
  1069. driver_option=''):
  1070. """Constructs an OptGroup object."""
  1071. self.name = name
  1072. self.title = "%s options" % name if title is None else title
  1073. self.help = help
  1074. self.dynamic_group_owner = dynamic_group_owner
  1075. self.driver_option = driver_option
  1076. self._opts = {} # dict of dicts of (opt:, override:, default:)
  1077. self._argparse_group = None
  1078. self._driver_opts = {} # populated by the config generator
  1079. def _save_driver_opts(self, opts):
  1080. """Save known driver opts.
  1081. :param opts: mapping between driver name and list of opts
  1082. :type opts: dict
  1083. """
  1084. self._driver_opts.update(opts)
  1085. def _get_generator_data(self):
  1086. "Return a dict with data for the sample generator."
  1087. return {
  1088. 'help': self.help or '',
  1089. 'dynamic_group_owner': self.dynamic_group_owner,
  1090. 'driver_option': self.driver_option,
  1091. 'driver_opts': self._driver_opts,
  1092. }
  1093. def _register_opt(self, opt, cli=False):
  1094. """Add an opt to this group.
  1095. :param opt: an Opt object
  1096. :param cli: whether this is a CLI option
  1097. :returns: False if previously registered, True otherwise
  1098. :raises: DuplicateOptError if a naming conflict is detected
  1099. """
  1100. if _is_opt_registered(self._opts, opt):
  1101. return False
  1102. self._opts[opt.dest] = {'opt': opt, 'cli': cli}
  1103. return True
  1104. def _unregister_opt(self, opt):
  1105. """Remove an opt from this group.
  1106. :param opt: an Opt object
  1107. """
  1108. if opt.dest in self._opts:
  1109. del self._opts[opt.dest]
  1110. def _get_argparse_group(self, parser):
  1111. if self._argparse_group is None:
  1112. """Build an argparse._ArgumentGroup for this group."""
  1113. self._argparse_group = parser.add_argument_group(self.title,
  1114. self.help)
  1115. return self._argparse_group
  1116. def _clear(self):
  1117. """Clear this group's option parsing state."""
  1118. self._argparse_group = None
  1119. def __str__(self):
  1120. return self.name
  1121. class ParseError(iniparser.ParseError):
  1122. def __init__(self, msg, lineno, line, filename):
  1123. super(ParseError, self).__init__(msg, lineno, line)
  1124. self.filename = filename
  1125. def __str__(self):
  1126. return 'at %s:%d, %s: %r' % (self.filename, self.lineno,
  1127. self.msg, self.line)
  1128. class ConfigParser(iniparser.BaseParser):
  1129. """Parses a single config file, populating 'sections' to look like::
  1130. {'DEFAULT': {'key': [value, ...], ...},
  1131. ...}
  1132. Also populates self._normalized which looks the same but with normalized
  1133. section names.
  1134. """
  1135. def __init__(self, filename, sections):
  1136. super(ConfigParser, self).__init__()
  1137. self.filename = filename
  1138. self.sections = sections
  1139. self._normalized = None
  1140. self.section = None
  1141. def _add_normalized(self, normalized):
  1142. self._normalized = normalized
  1143. def parse(self):
  1144. with open(self.filename) as f:
  1145. return super(ConfigParser, self).parse(f)
  1146. def new_section(self, section):
  1147. self.section = section
  1148. self.sections.setdefault(self.section, {})
  1149. if self._normalized is not None:
  1150. self._normalized.setdefault(_normalize_group_name(self.section),
  1151. {})
  1152. def assignment(self, key, value):
  1153. if not self.section:
  1154. raise self.error_no_section()
  1155. value = '\n'.join(value)
  1156. def append(sections, section):
  1157. sections[section].setdefault(key, [])
  1158. sections[section][key].append(value)
  1159. append(self.sections, self.section)
  1160. if self._normalized is not None:
  1161. append(self._normalized, _normalize_group_name(self.section))
  1162. def parse_exc(self, msg, lineno, line=None):
  1163. return ParseError(msg, lineno, line, self.filename)
  1164. def error_no_section(self):
  1165. return self.parse_exc('Section must be started before assignment',
  1166. self.lineno)
  1167. @classmethod
  1168. def _parse_file(cls, config_file, namespace):
  1169. """Parse a config file and store any values in the namespace.
  1170. :raises: ConfigFileParseError, ConfigFileValueError
  1171. """
  1172. config_file = _fixpath(config_file)
  1173. sections = {}
  1174. normalized = {}
  1175. parser = cls(config_file, sections)
  1176. parser._add_normalized(normalized)
  1177. try:
  1178. parser.parse()
  1179. except iniparser.ParseError as pe:
  1180. raise ConfigFileParseError(pe.filename, str(pe))
  1181. except IOError as err:
  1182. if err.errno == errno.ENOENT:
  1183. namespace._file_not_found(config_file)
  1184. return
  1185. if err.errno == errno.EACCES:
  1186. namespace._file_permission_denied(config_file)
  1187. return
  1188. raise
  1189. namespace._add_parsed_config_file(config_file, sections, normalized)
  1190. namespace._parse_cli_opts_from_config_file(
  1191. config_file, sections, normalized)
  1192. class _Namespace(argparse.Namespace):
  1193. """An argparse namespace which also stores config file values.
  1194. As we parse command line arguments, the values get set as attributes
  1195. on a namespace object. However, we also want to parse config files as
  1196. they are specified on the command line and collect the values alongside
  1197. the option values parsed from the command line.
  1198. Note, we don't actually assign values from config files as attributes
  1199. on the namespace because config file options be registered after the
  1200. command line has been parsed, so we may not know how to properly parse
  1201. or convert a config file value at this point.
  1202. """
  1203. _deprecated_opt_message = ('Option "%(dep_option)s" from group '
  1204. '"%(dep_group)s" is deprecated. Use option '
  1205. '"%(option)s" from group "%(group)s".')
  1206. def __init__(self, conf):
  1207. self._conf = conf
  1208. self._parsed = []
  1209. self._normalized = []
  1210. self._emitted_deprecations = set()
  1211. self._files_not_found = []
  1212. self._files_permission_denied = []
  1213. self._config_dirs = []
  1214. self._sections_to_file = {}
  1215. def _parse_cli_opts_from_config_file(self, config_file, sections,
  1216. normalized):
  1217. """Parse CLI options from a config file.
  1218. CLI options are special - we require they be registered before the
  1219. command line is parsed. This means that as we parse config files, we
  1220. can go ahead and apply the appropriate option-type specific conversion
  1221. to the values in config files for CLI options. We can't do this for
  1222. non-CLI options, because the schema describing those options may not be
  1223. registered until after the config files are parsed.
  1224. This method relies on that invariant in order to enforce proper
  1225. priority of option values - i.e. that the order in which an option
  1226. value is parsed, whether the value comes from the CLI or a config file,
  1227. determines which value specified for a given option wins.
  1228. The way we implement this ordering is that as we parse each config
  1229. file, we look for values in that config file for CLI options only. Any
  1230. values for CLI options found in the config file are treated like they
  1231. had appeared on the command line and set as attributes on the namespace
  1232. objects. Values in later config files or on the command line will
  1233. override values found in this file.
  1234. """
  1235. namespace = _Namespace(self._conf)
  1236. namespace._add_parsed_config_file(config_file, sections, normalized)
  1237. for opt, group in self._conf._all_cli_opts():
  1238. group_name = group.name if group is not None else None
  1239. try:
  1240. value, loc = opt._get_from_namespace(namespace, group_name)
  1241. except KeyError:
  1242. continue
  1243. except ValueError as ve:
  1244. raise ConfigFileValueError(
  1245. "Value for option %s is not valid: %s"
  1246. % (opt.name, str(ve)))
  1247. if group_name is None:
  1248. dest = opt.dest
  1249. else:
  1250. dest = group_name + '_' + opt.dest
  1251. if opt.multi:
  1252. if getattr(self, dest, None) is None:
  1253. setattr(self, dest, [])
  1254. values = getattr(self, dest)
  1255. values.extend(value)
  1256. else:
  1257. setattr(self, dest, value)
  1258. def _add_parsed_config_file(self, filename, sections, normalized):
  1259. """Add a parsed config file to the list of parsed files.
  1260. :param filename: the full name of the file that was parsed
  1261. :param sections: a mapping of section name to dicts of config values
  1262. :param normalized: sections mapping with section names normalized
  1263. :raises: ConfigFileValueError
  1264. """
  1265. for s in sections:
  1266. self._sections_to_file[s] = filename
  1267. self._parsed.insert(0, sections)
  1268. self._normalized.insert(0, normalized)
  1269. def _file_not_found(self, config_file):
  1270. """Record that we were unable to open a config file.
  1271. :param config_file: the path to the failed file
  1272. """
  1273. self._files_not_found.append(config_file)
  1274. def _file_permission_denied(self, config_file):
  1275. """Record that we have no permission to open a config file.
  1276. :param config_file: the path to the failed file
  1277. """
  1278. self._files_permission_denied.append(config_file)
  1279. def _get_cli_value(self, names, positional=False):
  1280. """Fetch a CLI option value.
  1281. Look up the value of a CLI option. The value itself may have come from
  1282. parsing the command line or parsing config files specified on the
  1283. command line. Type conversion have already been performed for CLI
  1284. options at this point.
  1285. :param names: a list of (section, name) tuples
  1286. :param positional: whether this is a positional option
  1287. """
  1288. for group_name, name in names:
  1289. name = name if group_name is None else group_name + '_' + name
  1290. value = getattr(self, name, None)
  1291. if value is not None:
  1292. # argparse ignores default=None for nargs='*' and returns []
  1293. if positional and not value:
  1294. continue
  1295. return value
  1296. raise KeyError
  1297. def _get_file_value(
  1298. self, names, multi=False, normalized=False, current_name=None):
  1299. """Fetch a config file value from the parsed files.
  1300. :param names: a list of (section, name) tuples
  1301. :param multi: a boolean indicating whether to return multiple values
  1302. :param normalized: whether to normalize group names to lowercase
  1303. :param current_name: current name in tuple being checked
  1304. """
  1305. rvalue = []
  1306. def normalize(name):
  1307. if name is None:
  1308. name = 'DEFAULT'
  1309. return _normalize_group_name(name) if normalized else name
  1310. names = [(normalize(section), name) for section, name in names]
  1311. loc = None
  1312. for sections in (self._normalized if normalized else self._parsed):
  1313. for section, name in names:
  1314. if section not in sections:
  1315. continue
  1316. if name in sections[section]:
  1317. current_name = current_name or names[0]
  1318. self._check_deprecated((section, name), current_name,
  1319. names[1:])
  1320. val = sections[section][name]
  1321. if loc is None:
  1322. loc = LocationInfo(
  1323. Locations.user,
  1324. self._sections_to_file.get(section, ''),
  1325. )
  1326. if multi:
  1327. rvalue = val + rvalue
  1328. else:
  1329. return (val, loc)
  1330. if multi and rvalue != []:
  1331. return (rvalue, loc)
  1332. raise KeyError
  1333. def _check_deprecated(self, name, current, deprecated):
  1334. """Check for usage of deprecated names.
  1335. :param name: A tuple of the form (group, name) representing the group
  1336. and name where an opt value was found.
  1337. :param current: A tuple of the form (group, name) representing the
  1338. current name for an option.
  1339. :param deprecated: A list of tuples with the same format as the name
  1340. param which represent any deprecated names for an option.
  1341. If the name param matches any entries in this list a
  1342. deprecation warning will be logged.
  1343. """
  1344. if name in deprecated and name not in self._emitted_deprecations:
  1345. self._emitted_deprecations.add(name)
  1346. current = (current[0] or 'DEFAULT', current[1])
  1347. format_dict = {'dep_option': name[1], 'dep_group': name[0],
  1348. 'option': current[1], 'group': current[0]}
  1349. _report_deprecation(self._deprecated_opt_message, format_dict)
  1350. def _get_value(self, names, multi=False, positional=False,
  1351. current_name=None, normalized=True):
  1352. """Fetch a value from config files.
  1353. Multiple names for a given configuration option may be supplied so
  1354. that we can transparently handle files containing deprecated option
  1355. names or groups.
  1356. :param names: a list of (section, name) tuples
  1357. :param positional: whether this is a positional option
  1358. :param multi: a boolean indicating whether to return multiple values
  1359. :param normalized: whether to normalize group names to lowercase
  1360. """
  1361. # NOTE(dhellmann): We don't have a way to track which options
  1362. # that are registered as command line values show up on the
  1363. # command line or in the configuration files. So we look up
  1364. # the value in the file first to get the location, and then
  1365. # try looking it up as a CLI value in case it was set there.
  1366. # Set a default location indicating that the value came from
  1367. # the command line. This will be overridden if we find a value
  1368. # in a file.
  1369. loc = LocationInfo(Locations.command_line, '')
  1370. try:
  1371. file_names = [(g if g is not None else 'DEFAULT', n)
  1372. for g, n in names]
  1373. values, loc = self._get_file_value(
  1374. file_names, multi=multi, normalized=normalized,
  1375. current_name=current_name)
  1376. except KeyError:
  1377. # If we receive a KeyError when looking for the CLI, just
  1378. # go ahead and throw it because we know we don't have a
  1379. # value.
  1380. raise_later = True
  1381. else:
  1382. raise_later = False
  1383. # Now try the CLI
  1384. try:
  1385. value = self._get_cli_value(names, positional)
  1386. return (value, loc)
  1387. except KeyError:
  1388. if raise_later:
  1389. # Re-raise to indicate that we haven't found the value
  1390. # anywhere.
  1391. raise
  1392. # Return the value we found in the file.
  1393. return (values if multi else values[-1], loc)
  1394. def _sections(self):
  1395. for sections in self._parsed:
  1396. for section in sections:
  1397. yield section
  1398. class _CachedArgumentParser(argparse.ArgumentParser):
  1399. """class for caching/collecting command line arguments.
  1400. It also sorts the arguments before initializing the ArgumentParser.
  1401. We need to do this since ArgumentParser by default does not sort
  1402. the argument options and the only way to influence the order of
  1403. arguments in '--help' is to ensure they are added in the sorted
  1404. order.
  1405. """
  1406. def __init__(self, prog=None, usage=None, **kwargs):
  1407. super(_CachedArgumentParser, self).__init__(prog, usage, **kwargs)
  1408. self._args_cache = {}
  1409. def add_parser_argument(self, container, *args, **kwargs):
  1410. values = []
  1411. if container in self._args_cache:
  1412. values = self._args_cache[container]
  1413. values.append({'args': args, 'kwargs': kwargs})
  1414. self._args_cache[container] = values
  1415. def initialize_parser_arguments(self):
  1416. # NOTE(mfedosin): The code below looks a little bit weird, but
  1417. # it's done because we need to sort only optional opts and do
  1418. # not touch positional. For the reason optional opts go first in
  1419. # the values we only need to find an index of the first positional
  1420. # option and then sort the values slice.
  1421. for container, values in self._args_cache.items():
  1422. index = 0
  1423. has_positional = False
  1424. for index, argument in enumerate(values):
  1425. if not argument['args'][0].startswith('-'):
  1426. has_positional = True
  1427. break
  1428. size = index if has_positional else len(values)
  1429. values[:size] = sorted(values[:size], key=lambda x: x['args'])
  1430. for argument in values:
  1431. try:
  1432. container.add_argument(*argument['args'],
  1433. **argument['kwargs'])
  1434. except argparse.ArgumentError:
  1435. options = ','.join(argument['args'])
  1436. raise DuplicateOptError(options)
  1437. self._args_cache = {}
  1438. def parse_args(self, args=None, namespace=None):
  1439. self.initialize_parser_arguments()
  1440. return super(_CachedArgumentParser, self).parse_args(args, namespace)
  1441. def print_help(self, file=None):
  1442. self.initialize_parser_arguments()
  1443. super(_CachedArgumentParser, self).print_help(file)
  1444. def print_usage(self, file=None):
  1445. self.initialize_parser_arguments()
  1446. super(_CachedArgumentParser, self).print_usage(file)
  1447. class ConfigOpts(Mapping):
  1448. """Config options which may be set on the command line or in config files.
  1449. ConfigOpts is a configuration option manager with APIs for registering
  1450. option schemas, grouping options, parsing option values and retrieving
  1451. the values of options.
  1452. It has built-in support for :oslo.config:option:`config_file` and
  1453. :oslo.config:option:`config_dir` options.
  1454. """
  1455. disallow_names = ('project', 'prog', 'version',
  1456. 'usage', 'default_config_files', 'default_config_dirs')
  1457. # NOTE(dhellmann): This instance is reused by list_opts().
  1458. _config_source_opt = ListOpt(
  1459. 'config_source',
  1460. metavar='SOURCE',
  1461. default=[],
  1462. help=('Lists configuration groups that provide more '
  1463. 'details for accessing configuration settings '
  1464. 'from locations other than local files.'),
  1465. )
  1466. def __init__(self):
  1467. """Construct a ConfigOpts object."""
  1468. self._opts = {} # dict of dicts of (opt:, override:, default:)
  1469. self._groups = {}
  1470. self._deprecated_opts = {}
  1471. self._args = None
  1472. self._oparser = None
  1473. self._namespace = None
  1474. self._mutable_ns = None
  1475. self._mutate_hooks = set([])
  1476. self.__cache = {}
  1477. self.__drivers_cache = {}
  1478. self._config_opts = []
  1479. self._cli_opts = collections.deque()
  1480. self._validate_default_values = False
  1481. self._sources = []
  1482. self._ext_mgr = None
  1483. # Though the env_driver is a Source, we load it by default.
  1484. self._use_env = True
  1485. self._env_driver = _environment.EnvironmentConfigurationSource()
  1486. self.register_opt(self._config_source_opt)
  1487. def _pre_setup(self, project, prog, version, usage, description, epilog,
  1488. default_config_files, default_config_dirs):
  1489. """Initialize a ConfigCliParser object for option parsing."""
  1490. if prog is None:
  1491. prog = os.path.basename(sys.argv[0])
  1492. if prog.endswith(".py"):
  1493. prog = prog[:-3]
  1494. if default_config_files is None:
  1495. default_config_files = find_config_files(project, prog)
  1496. if default_config_dirs is None:
  1497. default_config_dirs = find_config_dirs(project, prog)
  1498. self._oparser = _CachedArgumentParser(
  1499. prog=prog, usage=usage, description=description, epilog=epilog)
  1500. if version is not None:
  1501. self._oparser.add_parser_argument(self._oparser,
  1502. '--version',
  1503. action='version',
  1504. version=version)
  1505. return prog, default_config_files, default_config_dirs
  1506. @staticmethod
  1507. def _make_config_options(default_config_files, default_config_dirs):
  1508. return [
  1509. _ConfigFileOpt('config-file',
  1510. default=default_config_files,
  1511. metavar='PATH',
  1512. help=('Path to a config file to use. Multiple '
  1513. 'config files can be specified, with values '
  1514. 'in later files taking precedence. Defaults '
  1515. 'to %(default)s. This option must be set '
  1516. 'from the command-line.')),
  1517. _ConfigDirOpt('config-dir',
  1518. metavar='DIR',
  1519. default=default_config_dirs,
  1520. help='Path to a config directory to pull `*.conf` '
  1521. 'files from. This file set is sorted, so as to '
  1522. 'provide a predictable parse order if '
  1523. 'individual options are over-ridden. The set '
  1524. 'is parsed after the file(s) specified via '
  1525. 'previous --config-file, arguments hence '
  1526. 'over-ridden options in the directory take '
  1527. 'precedence. This option must be set from '
  1528. 'the command-line.'),
  1529. ]
  1530. @classmethod
  1531. def _list_options_for_discovery(cls,
  1532. default_config_files,
  1533. default_config_dirs):
  1534. "Return options to be used by list_opts() for the sample generator."
  1535. options = cls._make_config_options(default_config_files,
  1536. default_config_dirs)
  1537. options.append(cls._config_source_opt)
  1538. return options
  1539. def _setup(self, project, prog, version, usage, default_config_files,
  1540. default_config_dirs, use_env):
  1541. """Initialize a ConfigOpts object for option parsing."""
  1542. self._config_opts = self._make_config_options(default_config_files,
  1543. default_config_dirs)
  1544. self.register_cli_opts(self._config_opts)
  1545. self.project = project
  1546. self.prog = prog
  1547. self.version = version
  1548. self.usage = usage
  1549. self.default_config_files = default_config_files
  1550. self.default_config_dirs = default_config_dirs
  1551. self._use_env = use_env
  1552. def __clear_cache(f):
  1553. @functools.wraps(f)
  1554. def __inner(self, *args, **kwargs):
  1555. if kwargs.pop('clear_cache', True):
  1556. result = f(self, *args, **kwargs)
  1557. self.__cache.clear()
  1558. return result
  1559. else:
  1560. return f(self, *args, **kwargs)
  1561. return __inner
  1562. def __clear_drivers_cache(f):
  1563. @functools.wraps(f)
  1564. def __inner(self, *args, **kwargs):
  1565. if kwargs.pop('clear_drivers_cache', True):
  1566. result = f(self, *args, **kwargs)
  1567. self.__drivers_cache.clear()
  1568. return result
  1569. else:
  1570. return f(self, *args, **kwargs)
  1571. return __inner
  1572. def __call__(self,
  1573. args=None,
  1574. project=None,
  1575. prog=None,
  1576. version=None,
  1577. usage=None,
  1578. default_config_files=None,
  1579. default_config_dirs=None,
  1580. validate_default_values=False,
  1581. description=None,
  1582. epilog=None,
  1583. use_env=True):
  1584. """Parse command line arguments and config files.
  1585. Calling a ConfigOpts object causes the supplied command line arguments
  1586. and config files to be parsed, causing opt values to be made available
  1587. as attributes of the object.
  1588. The object may be called multiple times, each time causing the previous
  1589. set of values to be overwritten.
  1590. Automatically registers the --config-file option with either a supplied
  1591. list of default config files, or a list from find_config_files().
  1592. If the --config-dir option is set, any *.conf files from this
  1593. directory are pulled in, after all the file(s) specified by the
  1594. --config-file option.
  1595. :param args: command line arguments (defaults to sys.argv[1:])
  1596. :param project: the toplevel project name, used to locate config files
  1597. :param prog: the name of the program (defaults to sys.argv[0]
  1598. basename, without extension .py)
  1599. :param version: the program version (for --version)
  1600. :param usage: a usage string (%prog will be expanded)
  1601. :param description: A description of what the program does
  1602. :param epilog: Text following the argument descriptions
  1603. :param default_config_files: config files to use by default
  1604. :param default_config_dirs: config dirs to use by default
  1605. :param validate_default_values: whether to validate the default values
  1606. :param use_env: If True (the default) look in the environment as one
  1607. source of option values.
  1608. :raises: SystemExit, ConfigFilesNotFoundError, ConfigFileParseError,
  1609. ConfigFilesPermissionDeniedError,
  1610. RequiredOptError, DuplicateOptError
  1611. """
  1612. self.clear()
  1613. self._validate_default_values = validate_default_values
  1614. prog, default_config_files, default_config_dirs = self._pre_setup(
  1615. project, prog, version, usage, description, epilog,
  1616. default_config_files, default_config_dirs)
  1617. self._setup(project, prog, version, usage, default_config_files,
  1618. default_config_dirs, use_env)
  1619. self._namespace = self._parse_cli_opts(args if args is not None
  1620. else sys.argv[1:])
  1621. if self._namespace._files_not_found:
  1622. raise ConfigFilesNotFoundError(self._namespace._files_not_found)
  1623. if self._namespace._files_permission_denied:
  1624. raise ConfigFilesPermissionDeniedError(
  1625. self._namespace._files_permission_denied)
  1626. self._load_alternative_sources()
  1627. self._check_required_opts()
  1628. def _load_alternative_sources(self):
  1629. # Look for other sources of option data.
  1630. for source_group_name in self.config_source:
  1631. source = self._open_source_from_opt_group(source_group_name)
  1632. if source is not None:
  1633. self._sources.append(source)
  1634. def _open_source_from_opt_group(self, group_name):
  1635. if not self._ext_mgr:
  1636. self._ext_mgr = stevedore.ExtensionManager(
  1637. "oslo.config.driver",
  1638. invoke_on_load=True)
  1639. self.register_opt(
  1640. StrOpt('driver',
  1641. choices=self._ext_mgr.names(),
  1642. help=_SOURCE_DRIVER_OPTION_HELP),
  1643. group=group_name)
  1644. try:
  1645. driver_name = self[group_name].driver
  1646. except ConfigFileValueError as err:
  1647. LOG.error(
  1648. "could not load configuration from %r. %s",
  1649. group_name, err.msg)
  1650. return None
  1651. if driver_name is None:
  1652. LOG.error(
  1653. "could not load configuration from %r, no 'driver' is set.",
  1654. group_name)
  1655. return None
  1656. LOG.info('loading configuration from %r using %r',
  1657. group_name, driver_name)
  1658. driver = self._ext_mgr[driver_name].obj
  1659. try:
  1660. return driver.open_source_from_opt_group(self, group_name)
  1661. except Exception as err:
  1662. LOG.error(
  1663. "could not load configuration from %r using %s driver: %s",
  1664. group_name, driver_name, err)
  1665. return None
  1666. def __getattr__(self, name):
  1667. """Look up an option value and perform string substitution.
  1668. :param name: the opt name (or 'dest', more precisely)
  1669. :returns: the option value (after string substitution) or a GroupAttr
  1670. :raises: ValueError or NoSuchOptError
  1671. """
  1672. try:
  1673. return self._get(name)
  1674. except ValueError:
  1675. raise
  1676. except Exception:
  1677. raise NoSuchOptError(name)
  1678. def __getitem__(self, key):
  1679. """Look up an option value and perform string substitution."""
  1680. return self.__getattr__(key)
  1681. def __contains__(self, key):
  1682. """Return True if key is the name of a registered opt or group."""
  1683. return key in self._opts or key in self._groups
  1684. def __iter__(self):
  1685. """Iterate over all registered opt and group names."""
  1686. for key in itertools.chain(list(self._opts.keys()),
  1687. list(self._groups.keys())):
  1688. yield key
  1689. def __len__(self):
  1690. """Return the number of options and option groups."""
  1691. return len(self._opts) + len(self._groups)
  1692. def reset(self):
  1693. """Clear the object state and unset overrides and defaults."""
  1694. self._unset_defaults_and_overrides()
  1695. self.clear()
  1696. @__clear_cache
  1697. def clear(self):
  1698. """Reset the state of the object to before options were registered.
  1699. This method removes all registered options and discards the data
  1700. from the command line and configuration files.
  1701. Any subparsers added using the add_cli_subparsers() will also be
  1702. removed as a side-effect of this method.
  1703. """
  1704. self._args = None
  1705. self._oparser = None
  1706. self._namespace = None
  1707. self._mutable_ns = None
  1708. # Keep _mutate_hooks
  1709. self._validate_default_values = False
  1710. self.unregister_opts(self._config_opts)
  1711. for group in self._groups.values():
  1712. group._clear()
  1713. def _add_cli_opt(self, opt, group):
  1714. if {'opt': opt, 'group': group} in self._cli_opts:
  1715. return
  1716. if opt.positional:
  1717. self._cli_opts.append({'opt': opt, 'group': group})
  1718. else:
  1719. self._cli_opts.appendleft({'opt': opt, 'group': group})
  1720. def _track_deprecated_opts(self, opt, group=None):
  1721. if hasattr(opt, 'deprecated_opts'):
  1722. for dep_opt in opt.deprecated_opts:
  1723. dep_group = dep_opt.group or 'DEFAULT'
  1724. dep_dest = dep_opt.name
  1725. if dep_dest:
  1726. dep_dest = dep_dest.replace('-', '_')
  1727. if dep_group not in self._deprecated_opts:
  1728. self._deprecated_opts[dep_group] = {
  1729. dep_dest: {
  1730. 'opt': opt,
  1731. 'group': group
  1732. }
  1733. }
  1734. else:
  1735. self._deprecated_opts[dep_group][dep_dest] = {
  1736. 'opt': opt,
  1737. 'group': group
  1738. }
  1739. @__clear_cache
  1740. def register_opt(self, opt, group=None, cli=False):
  1741. """Register an option schema.
  1742. Registering an option schema makes any option value which is previously
  1743. or subsequently parsed from the command line or config files available
  1744. as an attribute of this object.
  1745. :param opt: an instance of an Opt sub-class
  1746. :param group: an optional OptGroup object or group name
  1747. :param cli: whether this is a CLI option
  1748. :return: False if the opt was already registered, True otherwise
  1749. :raises: DuplicateOptError
  1750. """
  1751. if group is not None:
  1752. group = self._get_group(group, autocreate=True)
  1753. if cli:
  1754. self._add_cli_opt(opt, group)
  1755. self._track_deprecated_opts(opt, group=group)
  1756. return group._register_opt(opt, cli)
  1757. # NOTE(gcb) We can't use some names which are same with attributes of
  1758. # Opts in default group. They includes project, prog, version, usage,
  1759. # default_config_files and default_config_dirs.
  1760. if group is None:
  1761. if opt.name in self.disallow_names:
  1762. raise ValueError('Name %s was reserved for oslo.config.'
  1763. % opt.name)
  1764. if cli:
  1765. self._add_cli_opt(opt, None)
  1766. if _is_opt_registered(self._opts, opt):
  1767. return False
  1768. self._opts[opt.dest] = {'opt': opt, 'cli': cli}
  1769. self._track_deprecated_opts(opt)
  1770. return True
  1771. @__clear_cache
  1772. def register_opts(self, opts, group=None):
  1773. """Register multiple option schemas at once."""
  1774. for opt in opts:
  1775. self.register_opt(opt, group, clear_cache=False)
  1776. @__clear_cache
  1777. def register_cli_opt(self, opt, group=None):
  1778. """Register a CLI option schema.
  1779. CLI option schemas must be registered before the command line and
  1780. config files are parsed. This is to ensure that all CLI options are
  1781. shown in --help and option validation works as expected.
  1782. :param opt: an instance of an Opt sub-class
  1783. :param group: an optional OptGroup object or group name
  1784. :return: False if the opt was already registered, True otherwise
  1785. :raises: DuplicateOptError, ArgsAlreadyParsedError
  1786. """
  1787. if self._args is not None:
  1788. raise ArgsAlreadyParsedError("cannot register CLI option")
  1789. return self.register_opt(opt, group, cli=True, clear_cache=False)
  1790. @__clear_cache
  1791. def register_cli_opts(self, opts, group=None):
  1792. """Register multiple CLI option schemas at once."""
  1793. for opt in opts:
  1794. self.register_cli_opt(opt, group, clear_cache=False)
  1795. def register_group(self, group):
  1796. """Register an option group.
  1797. An option group must be registered before options can be registered
  1798. with the group.
  1799. :param group: an OptGroup object
  1800. """
  1801. if group.name in self._groups:
  1802. return
  1803. self._groups[group.name] = copy.copy(group)
  1804. @__clear_cache
  1805. def unregister_opt(self, opt, group=None):
  1806. """Unregister an option.
  1807. :param opt: an Opt object
  1808. :param group: an optional OptGroup object or group name
  1809. :raises: ArgsAlreadyParsedError, NoSuchGroupError
  1810. """
  1811. if self._args is not None:
  1812. raise ArgsAlreadyParsedError("reset before unregistering options")
  1813. remitem = None
  1814. for item in self._cli_opts:
  1815. if (item['opt'].dest == opt.dest and
  1816. (group is None or
  1817. self._get_group(group).name == item['group'].name)):
  1818. remitem = item
  1819. break
  1820. if remitem is not None:
  1821. self._cli_opts.remove(remitem)
  1822. if group is not None:
  1823. self._get_group(group)._unregister_opt(opt)
  1824. elif opt.dest in self._opts:
  1825. del self._opts[opt.dest]
  1826. @__clear_cache
  1827. def unregister_opts(self, opts, group=None):
  1828. """Unregister multiple CLI option schemas at once."""
  1829. for opt in opts:
  1830. self.unregister_opt(opt, group, clear_cache=False)
  1831. def import_opt(self, name, module_str, group=None):
  1832. """Import an option definition from a module.
  1833. Import a module and check that a given option is registered.
  1834. This is intended for use with global configuration objects
  1835. like cfg.CONF where modules commonly register options with
  1836. CONF at module load time. If one module requires an option
  1837. defined by another module it can use this method to explicitly
  1838. declare the dependency.
  1839. :param name: the name/dest of the opt
  1840. :param module_str: the name of a module to import
  1841. :param group: an option OptGroup object or group name
  1842. :raises: NoSuchOptError, NoSuchGroupError
  1843. """
  1844. __import__(module_str)
  1845. self._get_opt_info(name, group)
  1846. def import_group(self, group, module_str):
  1847. """Import an option group from a module.
  1848. Import a module and check that a given option group is registered.
  1849. This is intended for use with global configuration objects
  1850. like cfg.CONF where modules commonly register options with
  1851. CONF at module load time. If one module requires an option group
  1852. defined by another module it can use this method to explicitly
  1853. declare the dependency.
  1854. :param group: an option OptGroup object or group name
  1855. :param module_str: the name of a module to import
  1856. :raises: ImportError, NoSuchGroupError
  1857. """
  1858. __import__(module_str)
  1859. self._get_group(group)
  1860. @__clear_cache
  1861. def set_override(self, name, override, group=None):
  1862. """Override an opt value.
  1863. Override the command line, config file and default values of a
  1864. given option.
  1865. :param name: the name/dest of the opt
  1866. :param override: the override value
  1867. :param group: an option OptGroup object or group name
  1868. :raises: NoSuchOptError, NoSuchGroupError
  1869. """
  1870. opt_info = self._get_opt_info(name, group)
  1871. opt_info['override'] = self._get_enforced_type_value(
  1872. opt_info['opt'], override)
  1873. opt_info['location'] = LocationInfo(
  1874. Locations.set_override,
  1875. _get_caller_detail(3), # this function has a decorator to skip
  1876. )
  1877. @__clear_cache
  1878. def set_default(self, name, default, group=None):
  1879. """Override an opt's default value.
  1880. Override the default value of given option. A command line or
  1881. config file value will still take precedence over this default.
  1882. :param name: the name/dest of the opt
  1883. :param default: the default value
  1884. :param group: an option OptGroup object or group name
  1885. :raises: NoSuchOptError, NoSuchGroupError
  1886. """
  1887. opt_info = self._get_opt_info(name, group)
  1888. opt_info['default'] = self._get_enforced_type_value(
  1889. opt_info['opt'], default)
  1890. opt_info['location'] = LocationInfo(
  1891. Locations.set_default,
  1892. _get_caller_detail(3), # this function has a decorator to skip
  1893. )
  1894. def _get_enforced_type_value(self, opt, value):
  1895. if value is None:
  1896. return None
  1897. return self._convert_value(value, opt)
  1898. @__clear_cache
  1899. def clear_override(self, name, group=None):
  1900. """Clear an override an opt value.
  1901. Clear a previously set override of the command line, config file
  1902. and default values of a given option.
  1903. :param name: the name/dest of the opt
  1904. :param group: an option OptGroup object or group name
  1905. :raises: NoSuchOptError, NoSuchGroupError
  1906. """
  1907. opt_info = self._get_opt_info(name, group)
  1908. opt_info.pop('override', None)
  1909. @__clear_cache
  1910. def clear_default(self, name, group=None):
  1911. """Clear an override an opt's default value.
  1912. Clear a previously set override of the default value of given option.
  1913. :param name: the name/dest of the opt
  1914. :param group: an option OptGroup object or group name
  1915. :raises: NoSuchOptError, NoSuchGroupError
  1916. """
  1917. opt_info = self._get_opt_info(name, group)
  1918. opt_info.pop('default', None)
  1919. def _all_opt_infos(self):
  1920. """A generator function for iteration opt infos."""
  1921. for info in self._opts.values():
  1922. yield info, None
  1923. for group in self._groups.values():
  1924. for info in group._opts.values():
  1925. yield info, group
  1926. def _all_cli_opts(self):
  1927. """A generator function for iterating CLI opts."""
  1928. for item in self._cli_opts:
  1929. yield item['opt'], item['group']
  1930. def _unset_defaults_and_overrides(self):
  1931. """Unset any default or override on all options."""
  1932. for info, group in self._all_opt_infos():
  1933. info.pop('default', None)
  1934. info.pop('override', None)
  1935. @property
  1936. def config_dirs(self):
  1937. if self._namespace is None:
  1938. return []
  1939. return self._namespace._config_dirs
  1940. def find_file(self, name):
  1941. """Locate a file located alongside the config files.
  1942. Search for a file with the supplied basename in the directories
  1943. which we have already loaded config files from and other known
  1944. configuration directories.
  1945. The directory, if any, supplied by the config_dir option is
  1946. searched first. Then the config_file option is iterated over
  1947. and each of the base directories of the config_files values
  1948. are searched. Failing both of these, the standard directories
  1949. searched by the module level find_config_files() function is
  1950. used. The first matching file is returned.
  1951. :param name: the filename, for example 'policy.json'
  1952. :returns: the path to a matching file, or None
  1953. """
  1954. if not self._namespace:
  1955. raise NotInitializedError()
  1956. dirs = []
  1957. if self._namespace._config_dirs:
  1958. for directory in self._namespace._config_dirs:
  1959. dirs.append(_fixpath(directory))
  1960. for cf in reversed(self.config_file):
  1961. dirs.append(os.path.dirname(_fixpath(cf)))
  1962. dirs.extend(_get_config_dirs(self.project))
  1963. return _search_dirs(dirs, name)
  1964. def log_opt_values(self, logger, lvl):
  1965. """Log the value of all registered opts.
  1966. It's often useful for an app to log its configuration to a log file at
  1967. startup for debugging. This method dumps to the entire config state to
  1968. the supplied logger at a given log level.
  1969. :param logger: a logging.Logger object
  1970. :param lvl: the log level (for example logging.DEBUG) arg to
  1971. logger.log()
  1972. """
  1973. logger.log(lvl, "*" * 80)
  1974. logger.log(lvl, "Configuration options gathered from:")
  1975. logger.log(lvl, "command line args: %s", self._args)
  1976. logger.log(lvl, "config files: %s",
  1977. hasattr(self, 'config_file') and self.config_file or [])
  1978. logger.log(lvl, "=" * 80)
  1979. def _sanitize(opt, value):
  1980. """Obfuscate values of options declared secret."""
  1981. return value if not opt.secret else '*' * 4
  1982. for opt_name in sorted(self._opts):
  1983. opt = self._get_opt_info(opt_name)['opt']
  1984. logger.log(lvl, "%-30s = %s", opt_name,
  1985. _sanitize(opt, getattr(self, opt_name)))
  1986. for group_name in self._groups:
  1987. group_attr = self.GroupAttr(self, self._get_group(group_name))
  1988. for opt_name in sorted(self._groups[group_name]._opts):
  1989. opt = self._get_opt_info(opt_name, group_name)['opt']
  1990. logger.log(lvl, "%-30s = %s",
  1991. "%s.%s" % (group_name, opt_name),
  1992. _sanitize(opt, getattr(group_attr, opt_name)))
  1993. logger.log(lvl, "*" * 80)
  1994. def print_usage(self, file=None):
  1995. """Print the usage message for the current program.
  1996. This method is for use after all CLI options are known
  1997. registered using __call__() method. If this method is called
  1998. before the __call__() is invoked, it throws NotInitializedError
  1999. :param file: the File object (if None, output is on sys.stdout)
  2000. :raises: NotInitializedError
  2001. """
  2002. if not self._oparser:
  2003. raise NotInitializedError()
  2004. self._oparser.print_usage(file)
  2005. def print_help(self, file=None):
  2006. """Print the help message for the current program.
  2007. This method is for use after all CLI options are known
  2008. registered using __call__() method. If this method is called
  2009. before the __call__() is invoked, it throws NotInitializedError
  2010. :param file: the File object (if None, output is on sys.stdout)
  2011. :raises: NotInitializedError
  2012. """
  2013. if not self._oparser:
  2014. raise NotInitializedError()
  2015. self._oparser.print_help(file)
  2016. def _get(self, name, group=None, namespace=None):
  2017. if isinstance(group, OptGroup):
  2018. key = (group.name, name)
  2019. else:
  2020. key = (group, name)
  2021. if namespace is None:
  2022. try:
  2023. return self.__cache[key]
  2024. except KeyError: # nosec: Valid control flow instruction
  2025. pass
  2026. value, loc = self._do_get(name, group, namespace)
  2027. self.__cache[key] = value
  2028. return value
  2029. def _do_get(self, name, group=None, namespace=None):
  2030. """Look up an option value.
  2031. :param name: the opt name (or 'dest', more precisely)
  2032. :param group: an OptGroup
  2033. :param namespace: the namespace object to get the option value from
  2034. :returns: 2-tuple of the option value or a GroupAttr object
  2035. and LocationInfo or None
  2036. :raises: NoSuchOptError, NoSuchGroupError, ConfigFileValueError,
  2037. TemplateSubstitutionError
  2038. """
  2039. if group is None and name in self._groups:
  2040. return (self.GroupAttr(self, self._get_group(name)), None)
  2041. info = self._get_opt_info(name, group)
  2042. opt = info['opt']
  2043. if 'location' in info:
  2044. loc = info['location']
  2045. else:
  2046. loc = opt._set_location
  2047. if isinstance(opt, SubCommandOpt):
  2048. return (self.SubCommandAttr(self, group, opt.dest), None)
  2049. if 'override' in info:
  2050. return (self._substitute(info['override']), loc)
  2051. def convert(value):
  2052. return self._convert_value(
  2053. self._substitute(value, group, namespace), opt)
  2054. group_name = group.name if group else None
  2055. key = (group_name, name)
  2056. # If use_env is true, get a value from the environment but don't use
  2057. # it yet. We will look at the command line first, below.
  2058. env_val = (sources._NoValue, None)
  2059. if self._use_env:
  2060. env_val = self._env_driver.get(group_name, name, opt)
  2061. if opt.mutable and namespace is None:
  2062. namespace = self._mutable_ns
  2063. if namespace is None:
  2064. namespace = self._namespace
  2065. if namespace is not None:
  2066. try:
  2067. try:
  2068. val, alt_loc = opt._get_from_namespace(namespace,
  2069. group_name)
  2070. # Try command line first
  2071. if (val != sources._NoValue
  2072. and alt_loc.location == Locations.command_line):
  2073. return (convert(val), alt_loc)
  2074. # Environment source second
  2075. if env_val[0] != sources._NoValue:
  2076. return (convert(env_val[0]), env_val[1])
  2077. # Default file source third
  2078. if val != sources._NoValue:
  2079. return (convert(val), alt_loc)
  2080. except KeyError: # nosec: Valid control flow instruction
  2081. # If there was a KeyError looking at config files or
  2082. # command line, retry the env_val.
  2083. if env_val[0] != sources._NoValue:
  2084. return (convert(env_val[0]), env_val[1])
  2085. except ValueError as ve:
  2086. message = "Value for option %s from %s is not valid: %s" % (
  2087. opt.name, alt_loc, str(ve))
  2088. # Preserve backwards compatibility for file-based value
  2089. # errors.
  2090. if alt_loc.location == Locations.user:
  2091. raise ConfigFileValueError(message)
  2092. raise ConfigSourceValueError(message)
  2093. try:
  2094. return self.__drivers_cache[key]
  2095. except KeyError: # nosec: Valid control flow instruction
  2096. pass
  2097. for source in self._sources:
  2098. val = source.get(group_name, name, opt)
  2099. if val[0] != sources._NoValue:
  2100. result = (convert(val[0]), val[1])
  2101. self.__drivers_cache[key] = result
  2102. return result
  2103. if 'default' in info:
  2104. return (self._substitute(info['default']), loc)
  2105. if self._validate_default_values:
  2106. if opt.default is not None:
  2107. try:
  2108. convert(opt.default)
  2109. except ValueError as e:
  2110. raise ConfigFileValueError(
  2111. "Default value for option %s is not valid: %s"
  2112. % (opt.name, str(e)))
  2113. if opt.default is not None:
  2114. return (convert(opt.default), loc)
  2115. return (None, None)
  2116. def _substitute(self, value, group=None, namespace=None):
  2117. """Perform string template substitution.
  2118. Substitute any template variables (for example $foo, ${bar}) in
  2119. the supplied string value(s) with opt values.
  2120. :param value: the string value, or list of string values
  2121. :param group: the group that retrieves the option value from
  2122. :param namespace: the namespace object that retrieves the option
  2123. value from
  2124. :returns: the substituted string(s)
  2125. """
  2126. if isinstance(value, list):
  2127. return [self._substitute(i, group=group, namespace=namespace)
  2128. for i in value]
  2129. elif isinstance(value, str):
  2130. # Treat a backslash followed by the dollar sign "\$"
  2131. # the same as the string template escape "$$" as it is
  2132. # a bit more natural for users
  2133. if r'\$' in value:
  2134. value = value.replace(r'\$', '$$')
  2135. tmpl = self.Template(value)
  2136. ret = tmpl.safe_substitute(
  2137. self.StrSubWrapper(self, group=group, namespace=namespace))
  2138. return ret
  2139. elif isinstance(value, dict):
  2140. # Substitute template variables in both key and value
  2141. return {self._substitute(key, group=group, namespace=namespace):
  2142. self._substitute(val, group=group, namespace=namespace)
  2143. for key, val in value.items()}
  2144. else:
  2145. return value
  2146. class Template(string.Template):
  2147. idpattern = r'[_a-z][\._a-z0-9]*'
  2148. def _convert_value(self, value, opt):
  2149. """Perform value type conversion.
  2150. Converts values using option's type. Handles cases when value is
  2151. actually a list of values (for example for multi opts).
  2152. :param value: the string value, or list of string values
  2153. :param opt: option definition (instance of Opt class or its subclasses)
  2154. :returns: converted value
  2155. """
  2156. if opt.multi:
  2157. return [opt.type(v) for v in value]
  2158. else:
  2159. return opt.type(value)
  2160. def _get_group(self, group_or_name, autocreate=False):
  2161. """Looks up a OptGroup object.
  2162. Helper function to return an OptGroup given a parameter which can
  2163. either be the group's name or an OptGroup object.
  2164. The OptGroup object returned is from the internal dict of OptGroup
  2165. objects, which will be a copy of any OptGroup object that users of
  2166. the API have access to.
  2167. If autocreate is True, the group will be created if it's not found. If
  2168. group is an instance of OptGroup, that same instance will be
  2169. registered, otherwise a new instance of OptGroup will be created.
  2170. :param group_or_name: the group's name or the OptGroup object itself
  2171. :param autocreate: whether to auto-create the group if it's not found
  2172. :raises: NoSuchGroupError
  2173. """
  2174. group = group_or_name if isinstance(group_or_name, OptGroup) else None
  2175. group_name = group.name if group else group_or_name
  2176. if group_name not in self._groups:
  2177. if not autocreate:
  2178. raise NoSuchGroupError(group_name)
  2179. self.register_group(group or OptGroup(name=group_name))
  2180. return self._groups[group_name]
  2181. def _find_deprecated_opts(self, opt_name, group=None):
  2182. real_opt_name = None
  2183. real_group_name = None
  2184. group_name = group or 'DEFAULT'
  2185. if hasattr(group_name, 'name'):
  2186. group_name = group_name.name
  2187. dep_group = self._deprecated_opts.get(group_name)
  2188. if dep_group:
  2189. real_opt_dict = dep_group.get(opt_name)
  2190. if real_opt_dict:
  2191. real_opt_name = real_opt_dict['opt'].name
  2192. if real_opt_dict['group']:
  2193. real_group_name = real_opt_dict['group'].name
  2194. return real_opt_name, real_group_name
  2195. def _get_opt_info(self, opt_name, group=None):
  2196. """Return the (opt, override, default) dict for an opt.
  2197. :param opt_name: an opt name/dest
  2198. :param group: an optional group name or OptGroup object
  2199. :raises: NoSuchOptError, NoSuchGroupError
  2200. """
  2201. if group is None:
  2202. opts = self._opts
  2203. else:
  2204. group = self._get_group(group)
  2205. opts = group._opts
  2206. if opt_name not in opts:
  2207. real_opt_name, real_group_name = self._find_deprecated_opts(
  2208. opt_name, group=group)
  2209. if not real_opt_name:
  2210. raise NoSuchOptError(opt_name, group)
  2211. log_real_group_name = real_group_name or 'DEFAULT'
  2212. dep_message = ('Config option %(dep_group)s.%(dep_option)s '
  2213. ' is deprecated. Use option %(group)s.'
  2214. '%(option)s instead.')
  2215. LOG.warning(dep_message, {'dep_option': opt_name,
  2216. 'dep_group': group,
  2217. 'option': real_opt_name,
  2218. 'group': log_real_group_name})
  2219. opt_name = real_opt_name
  2220. if real_group_name:
  2221. group = self._get_group(real_group_name)
  2222. opts = group._opts
  2223. return opts[opt_name]
  2224. def _check_required_opts(self, namespace=None):
  2225. """Check that all opts marked as required have values specified.
  2226. :param namespace: the namespace object be checked the required options
  2227. :raises: RequiredOptError
  2228. """
  2229. for info, group in self._all_opt_infos():
  2230. opt = info['opt']
  2231. if opt.required:
  2232. if 'default' in info or 'override' in info:
  2233. continue
  2234. if self._get(opt.dest, group, namespace) is None:
  2235. raise RequiredOptError(opt.name, group)
  2236. def _parse_cli_opts(self, args):
  2237. """Parse command line options.
  2238. Initializes the command line option parser and parses the supplied
  2239. command line arguments.
  2240. :param args: the command line arguments
  2241. :returns: a _Namespace object containing the parsed option values
  2242. :raises: SystemExit, DuplicateOptError
  2243. ConfigFileParseError, ConfigFileValueError
  2244. """
  2245. self._args = args
  2246. for opt, group in self._all_cli_opts():
  2247. opt._add_to_cli(self._oparser, group)
  2248. return self._parse_config_files()
  2249. def _parse_config_files(self):
  2250. """Parse configure files options.
  2251. :raises: SystemExit, ConfigFilesNotFoundError, ConfigFileParseError,
  2252. ConfigFilesPermissionDeniedError,
  2253. RequiredOptError, DuplicateOptError
  2254. """
  2255. namespace = _Namespace(self)
  2256. # handle --config-file args or the default_config_files
  2257. for arg in self._args:
  2258. if arg == '--config-file' or arg.startswith('--config-file='):
  2259. break
  2260. else:
  2261. for config_file in self.default_config_files:
  2262. ConfigParser._parse_file(config_file, namespace)
  2263. # handle --config-dir args or the default_config_dirs
  2264. for arg in self._args:
  2265. if arg == '--config-dir' or arg.startswith('--config-dir='):
  2266. break
  2267. else:
  2268. for config_dir in self.default_config_dirs:
  2269. # for the default config-dir directories we just continue
  2270. # if the directories do not exist. This is different to the
  2271. # case where --config-dir is given on the command line.
  2272. if not os.path.exists(config_dir):
  2273. continue
  2274. config_dir_glob = os.path.join(config_dir, '*.conf')
  2275. for config_file in sorted(glob.glob(config_dir_glob)):
  2276. ConfigParser._parse_file(config_file, namespace)
  2277. self._oparser.parse_args(self._args, namespace)
  2278. self._validate_cli_options(namespace)
  2279. return namespace
  2280. def _validate_cli_options(self, namespace):
  2281. for opt, group in sorted(self._all_cli_opts(),
  2282. key=lambda x: x[0].name):
  2283. group_name = group.name if group else None
  2284. try:
  2285. value, loc = opt._get_from_namespace(namespace, group_name)
  2286. except KeyError:
  2287. continue
  2288. value = self._substitute(value, group=group, namespace=namespace)
  2289. try:
  2290. self._convert_value(value, opt)
  2291. except ValueError:
  2292. sys.stderr.write("argument --%s: Invalid %s value: %s\n" % (
  2293. opt.dest, repr(opt.type), value))
  2294. raise SystemExit
  2295. def _reload_config_files(self):
  2296. namespace = self._parse_config_files()
  2297. if namespace._files_not_found:
  2298. raise ConfigFilesNotFoundError(namespace._files_not_found)
  2299. if namespace._files_permission_denied:
  2300. raise ConfigFilesPermissionDeniedError(
  2301. namespace._files_permission_denied)
  2302. self._check_required_opts(namespace)
  2303. return namespace
  2304. @__clear_cache
  2305. @__clear_drivers_cache
  2306. def reload_config_files(self):
  2307. """Reload configure files and parse all options
  2308. :return: False if reload configure files failed or else return True
  2309. """
  2310. try:
  2311. namespace = self._reload_config_files()
  2312. except SystemExit as exc:
  2313. LOG.warning("Caught SystemExit while reloading configure "
  2314. "files with exit code: %d", exc.code)
  2315. return False
  2316. except Error as err:
  2317. LOG.warning("Caught Error while reloading configure files: "
  2318. "%s", err)
  2319. return False
  2320. else:
  2321. self._namespace = namespace
  2322. return True
  2323. def register_mutate_hook(self, hook):
  2324. """Registers a hook to be called by mutate_config_files.
  2325. :param hook: a function accepting this ConfigOpts object and a dict of
  2326. config mutations, as returned by mutate_config_files.
  2327. :return: None
  2328. """
  2329. self._mutate_hooks.add(hook)
  2330. def mutate_config_files(self):
  2331. """Reload configure files and parse all options.
  2332. Only options marked as 'mutable' will appear to change.
  2333. Hooks are called in a NON-DETERMINISTIC ORDER. Do not expect hooks to
  2334. be called in the same order as they were added.
  2335. :return: {(None or 'group', 'optname'): (old_value, new_value), ... }
  2336. :raises: Error if reloading fails
  2337. """
  2338. self.__cache.clear()
  2339. old_mutate_ns = self._mutable_ns or self._namespace
  2340. self._mutable_ns = self._reload_config_files()
  2341. self._warn_immutability()
  2342. fresh = self._diff_ns(old_mutate_ns, self._mutable_ns)
  2343. def key_fn(item):
  2344. # Py3 won't sort heterogeneous types. Sort None as TAB which has a
  2345. # very low ASCII value.
  2346. (groupname, optname) = item[0]
  2347. return item[0] if groupname else ('\t', optname)
  2348. sorted_fresh = sorted(fresh.items(), key=key_fn)
  2349. for (groupname, optname), (old, new) in sorted_fresh:
  2350. groupname = groupname if groupname else 'DEFAULT'
  2351. LOG.info("Option %(group)s.%(option)s changed from "
  2352. "[%(old_val)s] to [%(new_val)s]",
  2353. {'group': groupname,
  2354. 'option': optname,
  2355. 'old_val': old,
  2356. 'new_val': new})
  2357. for hook in self._mutate_hooks:
  2358. hook(self, fresh)
  2359. return fresh
  2360. def _warn_immutability(self):
  2361. """Check immutable opts have not changed.
  2362. _do_get won't return the new values but presumably someone changed the
  2363. config file expecting them to change so we should warn them they won't.
  2364. """
  2365. for info, group in self._all_opt_infos():
  2366. opt = info['opt']
  2367. if opt.mutable:
  2368. continue
  2369. groupname = group.name if group else 'DEFAULT'
  2370. try:
  2371. old, _ = opt._get_from_namespace(self._namespace, groupname)
  2372. except KeyError:
  2373. old = None
  2374. try:
  2375. new, _ = opt._get_from_namespace(self._mutable_ns, groupname)
  2376. except KeyError:
  2377. new = None
  2378. if old != new:
  2379. LOG.warning("Ignoring change to immutable option "
  2380. "%(group)s.%(option)s",
  2381. {"group": groupname, "option": opt.name})
  2382. def _diff_ns(self, old_ns, new_ns):
  2383. """Compare mutable option values between two namespaces.
  2384. This can be used to only reconfigure stateful sessions when necessary.
  2385. :return {(None or 'group', 'optname'): (old_value, new_value), ... }
  2386. """
  2387. diff = {}
  2388. for info, group in self._all_opt_infos():
  2389. opt = info['opt']
  2390. if not opt.mutable:
  2391. continue
  2392. groupname = group.name if group else None
  2393. try:
  2394. old, _ = opt._get_from_namespace(old_ns, groupname)
  2395. except KeyError:
  2396. old = None
  2397. try:
  2398. new, _ = opt._get_from_namespace(new_ns, groupname)
  2399. except KeyError:
  2400. new = None
  2401. if old != new:
  2402. diff[(groupname, opt.name)] = (old, new)
  2403. return diff
  2404. def list_all_sections(self):
  2405. """List all sections from the configuration.
  2406. Returns a sorted list of all section names found in the
  2407. configuration files, whether declared beforehand or not.
  2408. """
  2409. s = set([])
  2410. if self._mutable_ns:
  2411. s |= set(self._mutable_ns._sections())
  2412. if self._namespace:
  2413. s |= set(self._namespace._sections())
  2414. return sorted(s)
  2415. def get_location(self, name, group=None):
  2416. """Return the location where the option is being set.
  2417. :param name: The name of the option.
  2418. :type name: str
  2419. :param group: The name of the group of the option. Defaults to
  2420. ``'DEFAULT'``.
  2421. :type group: str
  2422. :return: LocationInfo
  2423. .. seealso::
  2424. :doc:`/reference/locations`
  2425. .. versionadded:: 5.3.0
  2426. """
  2427. opt_group = OptGroup(group) if group is not None else None
  2428. value, loc = self._do_get(name, opt_group, None)
  2429. return loc
  2430. class GroupAttr(Mapping):
  2431. """Helper class.
  2432. Represents the option values of a group as a mapping and attributes.
  2433. """
  2434. def __init__(self, conf, group):
  2435. """Construct a GroupAttr object.
  2436. :param conf: a ConfigOpts object
  2437. :param group: an OptGroup object
  2438. """
  2439. self._conf = conf
  2440. self._group = group
  2441. def __getattr__(self, name):
  2442. """Look up an option value and perform template substitution."""
  2443. return self._conf._get(name, self._group)
  2444. def __getitem__(self, key):
  2445. """Look up an option value and perform string substitution."""
  2446. return self.__getattr__(key)
  2447. def __contains__(self, key):
  2448. """Return True if key is the name of a registered opt or group."""
  2449. return key in self._group._opts
  2450. def __iter__(self):
  2451. """Iterate over all registered opt and group names."""
  2452. for key in self._group._opts.keys():
  2453. yield key
  2454. def __len__(self):
  2455. """Return the number of options and option groups."""
  2456. return len(self._group._opts)
  2457. class SubCommandAttr(object):
  2458. """Helper class.
  2459. Represents the name and arguments of an argparse sub-parser.
  2460. """
  2461. def __init__(self, conf, group, dest):
  2462. """Construct a SubCommandAttr object.
  2463. :param conf: a ConfigOpts object
  2464. :param group: an OptGroup object
  2465. :param dest: the name of the sub-parser
  2466. """
  2467. self._conf = conf
  2468. self._group = group
  2469. self._dest = dest
  2470. def __getattr__(self, name):
  2471. """Look up a sub-parser name or argument value."""
  2472. if name == 'name':
  2473. name = self._dest
  2474. if self._group is not None:
  2475. name = self._group.name + '_' + name
  2476. return getattr(self._conf._namespace, name)
  2477. if name in self._conf:
  2478. raise DuplicateOptError(name)
  2479. try:
  2480. return getattr(self._conf._namespace, name)
  2481. except AttributeError:
  2482. raise NoSuchOptError(name)
  2483. class StrSubWrapper(object):
  2484. """Helper class.
  2485. Exposes opt values as a dict for string substitution.
  2486. """
  2487. def __init__(self, conf, group=None, namespace=None):
  2488. """Construct a StrSubWrapper object.
  2489. :param conf: a ConfigOpts object
  2490. :param group: an OptGroup object
  2491. :param namespace: the namespace object that retrieves the option
  2492. value from
  2493. """
  2494. self.conf = conf
  2495. self.group = group
  2496. self.namespace = namespace
  2497. def __getitem__(self, key):
  2498. """Look up an opt value from the ConfigOpts object.
  2499. :param key: an opt name
  2500. :returns: an opt value
  2501. """
  2502. try:
  2503. group_name, option = key.split(".", 1)
  2504. except ValueError:
  2505. group = self.group
  2506. option = key
  2507. else:
  2508. group = OptGroup(name=group_name)
  2509. try:
  2510. value = self.conf._get(option, group=group,
  2511. namespace=self.namespace)
  2512. except NoSuchOptError:
  2513. value = self.conf._get(key, namespace=self.namespace)
  2514. if isinstance(value, self.conf.GroupAttr):
  2515. raise TemplateSubstitutionError(
  2516. 'substituting group %s not supported' % key)
  2517. if value is None:
  2518. return ''
  2519. return value
  2520. CONF = ConfigOpts()