astconfigparser.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. """
  2. Copyright (C) 2016, Digium, Inc.
  3. This program is free software, distributed under the terms of
  4. the GNU General Public License Version 2.
  5. """
  6. import re
  7. import itertools
  8. from astdicts import OrderedDict
  9. from astdicts import MultiOrderedDict
  10. def merge_values(left, right, key):
  11. """Merges values from right into left."""
  12. if isinstance(left, list):
  13. vals0 = left
  14. else: # assume dictionary
  15. vals0 = left[key] if key in left else []
  16. vals1 = right[key] if key in right else []
  17. return vals0 + [i for i in vals1 if i not in vals0]
  18. ###############################################################################
  19. class Section(MultiOrderedDict):
  20. """
  21. A Section is a MultiOrderedDict itself that maintains a list of
  22. key/value options. However, in the case of an Asterisk config
  23. file a section may have other defaults sections that is can pull
  24. data from (i.e. templates). So when an option is looked up by key
  25. it first checks the base section and if not found looks in the
  26. added default sections. If not found at that point then a 'KeyError'
  27. exception is raised.
  28. """
  29. count = 0
  30. def __init__(self, defaults=None, templates=None):
  31. MultiOrderedDict.__init__(self)
  32. # track an ordered id of sections
  33. Section.count += 1
  34. self.id = Section.count
  35. self._defaults = [] if defaults is None else defaults
  36. self._templates = [] if templates is None else templates
  37. def __cmp__(self, other):
  38. """
  39. Use self.id as means of determining equality
  40. """
  41. return (self.id > other.id) - (self.id < other.id)
  42. def __eq__(self, other):
  43. """
  44. Use self.id as means of determining equality
  45. """
  46. return self.id == other.id
  47. def get(self, key, from_self=True, from_templates=True,
  48. from_defaults=True):
  49. """
  50. Get the values corresponding to a given key. The parameters to this
  51. function form a hierarchy that determines priority of the search.
  52. from_self takes priority over from_templates, and from_templates takes
  53. priority over from_defaults.
  54. Parameters:
  55. from_self - If True, search within the given section.
  56. from_templates - If True, search in this section's templates.
  57. from_defaults - If True, search within this section's defaults.
  58. """
  59. if from_self and key in self:
  60. return MultiOrderedDict.__getitem__(self, key)
  61. if from_templates:
  62. if self in self._templates:
  63. return []
  64. for t in self._templates:
  65. try:
  66. # fail if not found on the search - doing it this way
  67. # allows template's templates to be searched.
  68. return t.get(key, True, from_templates, from_defaults)
  69. except KeyError:
  70. pass
  71. if from_defaults:
  72. for d in self._defaults:
  73. try:
  74. return d.get(key, True, from_templates, from_defaults)
  75. except KeyError:
  76. pass
  77. raise KeyError(key)
  78. def __getitem__(self, key):
  79. """
  80. Get the value for the given key. If it is not found in the 'self'
  81. then check inside templates and defaults before declaring raising
  82. a KeyError exception.
  83. """
  84. return self.get(key)
  85. def keys(self, self_only=False):
  86. """
  87. Get the keys from this section. If self_only is True, then
  88. keys from this section's defaults and templates are not
  89. included in the returned value
  90. """
  91. res = MultiOrderedDict.keys(self)
  92. if self_only:
  93. return res
  94. for d in self._templates:
  95. for key in d.keys():
  96. if key not in res:
  97. res.append(key)
  98. for d in self._defaults:
  99. for key in d.keys():
  100. if key not in res:
  101. res.append(key)
  102. return res
  103. def add_defaults(self, defaults):
  104. """
  105. Add a list of defaults to the section. Defaults are
  106. sections such as 'general'
  107. """
  108. defaults.sort()
  109. for i in defaults:
  110. self._defaults.insert(0, i)
  111. def add_templates(self, templates):
  112. """
  113. Add a list of templates to the section.
  114. """
  115. templates.sort()
  116. for i in templates:
  117. self._templates.insert(0, i)
  118. def get_merged(self, key):
  119. """Return a list of values for a given key merged from default(s)"""
  120. # first merge key/values from defaults together
  121. merged = []
  122. for i in reversed(self._defaults):
  123. if not merged:
  124. merged = i
  125. continue
  126. merged = merge_values(merged, i, key)
  127. for i in reversed(self._templates):
  128. if not merged:
  129. merged = i
  130. continue
  131. merged = merge_values(merged, i, key)
  132. # then merge self in
  133. return merge_values(merged, self, key)
  134. ###############################################################################
  135. COMMENT = ';'
  136. COMMENT_START = ';--'
  137. COMMENT_END = '--;'
  138. DEFAULTSECT = 'general'
  139. def remove_comment(line, is_comment):
  140. """Remove any commented elements from the line."""
  141. if not line:
  142. return line, is_comment
  143. if is_comment:
  144. part = line.partition(COMMENT_END)
  145. if part[1]:
  146. # found multi-line comment end check string after it
  147. return remove_comment(part[2], False)
  148. return "", True
  149. part = line.partition(COMMENT_START)
  150. if part[1]:
  151. # found multi-line comment start check string before
  152. # it to make sure there wasn't an eol comment in it
  153. has_comment = part[0].partition(COMMENT)
  154. if has_comment[1]:
  155. # eol comment found return anything before it
  156. return has_comment[0], False
  157. # check string after it to see if the comment ends
  158. line, is_comment = remove_comment(part[2], True)
  159. if is_comment:
  160. # return possible string data before comment
  161. return part[0].strip(), True
  162. # otherwise it was an embedded comment so combine
  163. return ''.join([part[0].strip(), ' ', line]).rstrip(), False
  164. # find the first occurence of a comment that is not escaped
  165. match = re.match(r'.*?([^\\];)', line)
  166. if match:
  167. # the end of where the real string is is where the comment starts
  168. line = line[0:(match.end()-1)]
  169. if line.startswith(";"):
  170. # if the line is actually a comment just ignore it all
  171. line = ""
  172. return line.replace("\\", "").strip(), False
  173. def try_include(line):
  174. """
  175. Checks to see if the given line is an include. If so return the
  176. included filename, otherwise None.
  177. """
  178. match = re.match('^#include\s*[<"]?(.*)[>"]?$', line)
  179. return match.group(1) if match else None
  180. def try_section(line):
  181. """
  182. Checks to see if the given line is a section. If so return the section
  183. name, otherwise return 'None'.
  184. """
  185. # leading spaces were stripped when checking for comments
  186. if not line.startswith('['):
  187. return None, False, []
  188. section, delim, templates = line.partition(']')
  189. if not templates:
  190. return section[1:], False, []
  191. # strip out the parens and parse into an array
  192. templates = templates.replace('(', "").replace(')', "").split(',')
  193. # go ahead and remove extra whitespace
  194. templates = [i.strip() for i in templates]
  195. try:
  196. templates.remove('!')
  197. return section[1:], True, templates
  198. except:
  199. return section[1:], False, templates
  200. def try_option(line):
  201. """Parses the line as an option, returning the key/value pair."""
  202. data = re.split('=>?', line, 1)
  203. # should split in two (key/val), but either way use first two elements
  204. return data[0].rstrip(), data[1].lstrip()
  205. ###############################################################################
  206. def find_dict(mdicts, key, val):
  207. """
  208. Given a list of mult-dicts, return the multi-dict that contains
  209. the given key/value pair.
  210. """
  211. def found(d):
  212. return key in d and val in d[key]
  213. try:
  214. return [d for d in mdicts if found(d)][0]
  215. except IndexError:
  216. raise LookupError("Dictionary not located for key = %s, value = %s"
  217. % (key, val))
  218. def write_dicts(config_file, mdicts):
  219. """Write the contents of the mdicts to the specified config file"""
  220. for section, sect_list in mdicts.iteritems():
  221. # every section contains a list of dictionaries
  222. for sect in sect_list:
  223. config_file.write("[%s]\n" % section)
  224. for key, val_list in sect.iteritems():
  225. # every value is also a list
  226. for v in val_list:
  227. key_val = key
  228. if v is not None:
  229. key_val += " = " + str(v)
  230. config_file.write("%s\n" % (key_val))
  231. config_file.write("\n")
  232. ###############################################################################
  233. class MultiOrderedConfigParser:
  234. def __init__(self, parent=None):
  235. self._parent = parent
  236. self._defaults = MultiOrderedDict()
  237. self._sections = MultiOrderedDict()
  238. self._includes = OrderedDict()
  239. def find_value(self, sections, key):
  240. """Given a list of sections, try to find value(s) for the given key."""
  241. # always start looking in the last one added
  242. sections.sort(reverse=True)
  243. for s in sections:
  244. try:
  245. # try to find in section and section's templates
  246. return s.get(key, from_defaults=False)
  247. except KeyError:
  248. pass
  249. # wasn't found in sections or a section's templates so check in
  250. # defaults
  251. for s in sections:
  252. try:
  253. # try to find in section's defaultsects
  254. return s.get(key, from_self=False, from_templates=False)
  255. except KeyError:
  256. pass
  257. raise KeyError(key)
  258. def defaults(self):
  259. return self._defaults
  260. def default(self, key):
  261. """Retrieves a list of dictionaries for a default section."""
  262. return self.get_defaults(key)
  263. def add_default(self, key, template_keys=None):
  264. """
  265. Adds a default section to defaults, returning the
  266. default Section object.
  267. """
  268. if template_keys is None:
  269. template_keys = []
  270. return self.add_section(key, template_keys, self._defaults)
  271. def sections(self):
  272. return self._sections
  273. def section(self, key):
  274. """Retrieves a list of dictionaries for a section."""
  275. return self.get_sections(key)
  276. def get_sections(self, key, attr='_sections', searched=None):
  277. """
  278. Retrieve a list of sections that have values for the given key.
  279. The attr parameter can be used to control what part of the parser
  280. to retrieve values from.
  281. """
  282. if searched is None:
  283. searched = []
  284. if self in searched:
  285. return []
  286. sections = getattr(self, attr)
  287. res = sections[key] if key in sections else []
  288. searched.append(self)
  289. if self._includes:
  290. res.extend(list(itertools.chain(*[
  291. incl.get_sections(key, attr, searched)
  292. for incl in self._includes.itervalues()])))
  293. if self._parent:
  294. res += self._parent.get_sections(key, attr, searched)
  295. return res
  296. def get_defaults(self, key):
  297. """
  298. Retrieve a list of defaults that have values for the given key.
  299. """
  300. return self.get_sections(key, '_defaults')
  301. def add_section(self, key, template_keys=None, mdicts=None):
  302. """
  303. Create a new section in the configuration. The name of the
  304. new section is the 'key' parameter.
  305. """
  306. if template_keys is None:
  307. template_keys = []
  308. if mdicts is None:
  309. mdicts = self._sections
  310. res = Section()
  311. for t in template_keys:
  312. res.add_templates(self.get_defaults(t))
  313. res.add_defaults(self.get_defaults(DEFAULTSECT))
  314. mdicts.insert(0, key, res)
  315. return res
  316. def includes(self):
  317. return self._includes
  318. def add_include(self, filename, parser=None):
  319. """
  320. Add a new #include file to the configuration.
  321. """
  322. if filename in self._includes:
  323. return self._includes[filename]
  324. self._includes[filename] = res = \
  325. MultiOrderedConfigParser(self) if parser is None else parser
  326. return res
  327. def get(self, section, key):
  328. """Retrieves the list of values from a section for a key."""
  329. try:
  330. # search for the value in the list of sections
  331. return self.find_value(self.section(section), key)
  332. except KeyError:
  333. pass
  334. try:
  335. # section may be a default section so, search
  336. # for the value in the list of defaults
  337. return self.find_value(self.default(section), key)
  338. except KeyError:
  339. raise LookupError("key %r not found for section %r"
  340. % (key, section))
  341. def multi_get(self, section, key_list):
  342. """
  343. Retrieves the list of values from a section for a list of keys.
  344. This method is intended to be used for equivalent keys. Thus, as soon
  345. as any match is found for any key in the key_list, the match is
  346. returned. This does not concatenate the lookups of all of the keys
  347. together.
  348. """
  349. for i in key_list:
  350. try:
  351. return self.get(section, i)
  352. except LookupError:
  353. pass
  354. # Making it here means all lookups failed.
  355. raise LookupError("keys %r not found for section %r" %
  356. (key_list, section))
  357. def set(self, section, key, val):
  358. """Sets an option in the given section."""
  359. # TODO - set in multiple sections? (for now set in first)
  360. # TODO - set in both sections and defaults?
  361. if section in self._sections:
  362. self.section(section)[0][key] = val
  363. else:
  364. self.defaults(section)[0][key] = val
  365. def read(self, filename, sect=None):
  366. """Parse configuration information from a file"""
  367. try:
  368. with open(filename, 'rt') as config_file:
  369. self._read(config_file, sect)
  370. except IOError:
  371. print("Could not open file " + filename + " for reading")
  372. def _read(self, config_file, sect):
  373. """Parse configuration information from the config_file"""
  374. is_comment = False # used for multi-lined comments
  375. for line in config_file:
  376. line, is_comment = remove_comment(line, is_comment)
  377. if not line:
  378. # line was empty or was a comment
  379. continue
  380. include_name = try_include(line)
  381. if include_name:
  382. parser = self.add_include(include_name)
  383. parser.read(include_name, sect)
  384. continue
  385. section, is_template, templates = try_section(line)
  386. if section:
  387. if section == DEFAULTSECT or is_template:
  388. sect = self.add_default(section, templates)
  389. else:
  390. sect = self.add_section(section, templates)
  391. continue
  392. key, val = try_option(line)
  393. if sect is None:
  394. raise Exception("Section not defined before assignment")
  395. sect[key] = val
  396. def write(self, config_file):
  397. """Write configuration information out to a file"""
  398. try:
  399. for key, val in self._includes.iteritems():
  400. val.write(key)
  401. config_file.write('#include "%s"\n' % key)
  402. config_file.write('\n')
  403. write_dicts(config_file, self._defaults)
  404. write_dicts(config_file, self._sections)
  405. except:
  406. try:
  407. with open(config_file, 'wt') as fp:
  408. self.write(fp)
  409. except IOError:
  410. print("Could not open file " + config_file + " for writing")