config_data.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. # Copyright (C) 2010 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. """
  16. Classes to store configuration data and module specifications
  17. Used by the config manager, (python) modules, and UI's (those last
  18. two through the classes in ccsession)
  19. """
  20. import isc.cc.data
  21. import isc.config.module_spec
  22. import ast
  23. class ConfigDataError(Exception): pass
  24. BIND10_CONFIG_DATA_VERSION = 2
  25. def check_type(spec_part, value):
  26. """Does nothing if the value is of the correct type given the
  27. specification part relevant for the value. Raises an
  28. isc.cc.data.DataTypeError exception if not. spec_part can be
  29. retrieved with find_spec_part()"""
  30. if type(spec_part) == dict and 'item_type' in spec_part:
  31. data_type = spec_part['item_type']
  32. else:
  33. raise isc.cc.data.DataTypeError(str("Incorrect specification part for type checking"))
  34. if data_type == "integer" and type(value) != int:
  35. raise isc.cc.data.DataTypeError(str(value) + " is not an integer")
  36. elif data_type == "real" and type(value) != float:
  37. raise isc.cc.data.DataTypeError(str(value) + " is not a real")
  38. elif data_type == "boolean" and type(value) != bool:
  39. raise isc.cc.data.DataTypeError(str(value) + " is not a boolean")
  40. elif data_type == "string" and type(value) != str:
  41. raise isc.cc.data.DataTypeError(str(value) + " is not a string")
  42. elif data_type == "list":
  43. if type(value) != list:
  44. raise isc.cc.data.DataTypeError(str(value) + " is not a list")
  45. else:
  46. for element in value:
  47. check_type(spec_part['list_item_spec'], element)
  48. elif data_type == "map" and type(value) != dict:
  49. # todo: check types of map contents too
  50. raise isc.cc.data.DataTypeError(str(value) + " is not a map")
  51. def convert_type(spec_part, value):
  52. """Convert the given value(type is string) according specification
  53. part relevant for the value. Raises an isc.cc.data.DataTypeError
  54. exception if conversion failed.
  55. """
  56. if type(spec_part) == dict and 'item_type' in spec_part:
  57. data_type = spec_part['item_type']
  58. else:
  59. raise isc.cc.data.DataTypeError(str("Incorrect specification part for type conversion"))
  60. try:
  61. if data_type == "integer":
  62. return int(value)
  63. elif data_type == "real":
  64. return float(value)
  65. elif data_type == "boolean":
  66. return str.lower(str(value)) != 'false'
  67. elif data_type == "string":
  68. return str(value)
  69. elif data_type == "list":
  70. ret = []
  71. if type(value) == list:
  72. for item in value:
  73. ret.append(convert_type(spec_part['list_item_spec'], item))
  74. elif type(value) == str:
  75. value = value.split(',')
  76. for item in value:
  77. sub_value = item.split()
  78. for sub_item in sub_value:
  79. ret.append(convert_type(spec_part['list_item_spec'],
  80. sub_item))
  81. if ret == []:
  82. raise isc.cc.data.DataTypeError(str(value) + " is not a list")
  83. return ret
  84. elif data_type == "map":
  85. map = ast.literal_eval(value)
  86. if type(map) == dict:
  87. # todo: check types of map contents too
  88. return map
  89. else:
  90. raise isc.cc.data.DataTypeError(
  91. "Value in convert_type not a string "
  92. "specifying a dict")
  93. else:
  94. return value
  95. except ValueError as err:
  96. raise isc.cc.data.DataTypeError(str(err))
  97. except TypeError as err:
  98. raise isc.cc.data.DataTypeError(str(err))
  99. def find_spec_part(element, identifier):
  100. """find the data definition for the given identifier
  101. returns either a map with 'item_name' etc, or a list of those"""
  102. if identifier == "":
  103. return element
  104. id_parts = identifier.split("/")
  105. id_parts[:] = (value for value in id_parts if value != "")
  106. cur_el = element
  107. for id_part in id_parts:
  108. # strip list selector part
  109. # don't need it for the spec part, so just drop it
  110. id, list_indices = isc.cc.data.split_identifier_list_indices(id_part)
  111. if type(cur_el) == dict and 'map_item_spec' in cur_el.keys():
  112. found = False
  113. for cur_el_item in cur_el['map_item_spec']:
  114. if cur_el_item['item_name'] == id:
  115. cur_el = cur_el_item
  116. found = True
  117. if not found:
  118. raise isc.cc.data.DataNotFoundError(id + " in " + str(cur_el))
  119. elif type(cur_el) == list:
  120. found = False
  121. for cur_el_item in cur_el:
  122. if cur_el_item['item_name'] == id:
  123. cur_el = cur_el_item
  124. found = True
  125. if not found:
  126. raise isc.cc.data.DataNotFoundError(id + " in " + str(cur_el))
  127. else:
  128. raise isc.cc.data.DataNotFoundError("Not a correct config specification")
  129. return cur_el
  130. def spec_name_list(spec, prefix="", recurse=False):
  131. """Returns a full list of all possible item identifiers in the
  132. specification (part). Raises a ConfigDataError if spec is not
  133. a correct spec (as returned by ModuleSpec.get_config_spec()"""
  134. result = []
  135. if prefix != "" and not prefix.endswith("/"):
  136. prefix += "/"
  137. if type(spec) == dict:
  138. if 'map_item_spec' in spec:
  139. for map_el in spec['map_item_spec']:
  140. name = map_el['item_name']
  141. if map_el['item_type'] == 'map':
  142. name += "/"
  143. if recurse and 'map_item_spec' in map_el:
  144. result.extend(spec_name_list(map_el['map_item_spec'], prefix + map_el['item_name'], recurse))
  145. else:
  146. result.append(prefix + name)
  147. else:
  148. for name in spec:
  149. result.append(prefix + name + "/")
  150. if recurse:
  151. result.extend(spec_name_list(spec[name],name, recurse))
  152. elif type(spec) == list:
  153. for list_el in spec:
  154. if 'item_name' in list_el:
  155. if list_el['item_type'] == "map" and recurse:
  156. result.extend(spec_name_list(list_el['map_item_spec'], prefix + list_el['item_name'], recurse))
  157. else:
  158. name = list_el['item_name']
  159. result.append(prefix + name)
  160. else:
  161. raise ConfigDataError("Bad specification")
  162. else:
  163. raise ConfigDataError("Bad specication")
  164. return result
  165. class ConfigData:
  166. """This class stores the module specs and the current non-default
  167. config values. It provides functions to get the actual value or
  168. the default value if no non-default value has been set"""
  169. def __init__(self, specification):
  170. """Initialize a ConfigData instance. If specification is not
  171. of type ModuleSpec, a ConfigDataError is raised."""
  172. if type(specification) != isc.config.ModuleSpec:
  173. raise ConfigDataError("specification is of type " + str(type(specification)) + ", not ModuleSpec")
  174. self.specification = specification
  175. self.data = {}
  176. def get_value(self, identifier):
  177. """Returns a tuple where the first item is the value at the
  178. given identifier, and the second item is a bool which is
  179. true if the value is an unset default. Raises an
  180. isc.cc.data.DataNotFoundError if the identifier is bad"""
  181. value = isc.cc.data.find_no_exc(self.data, identifier)
  182. if value != None:
  183. return value, False
  184. spec = find_spec_part(self.specification.get_config_spec(), identifier)
  185. if spec and 'item_default' in spec:
  186. return spec['item_default'], True
  187. return None, False
  188. def get_module_spec(self):
  189. """Returns the ModuleSpec object associated with this ConfigData"""
  190. return self.specification
  191. def set_local_config(self, data):
  192. """Set the non-default config values, as passed by cfgmgr"""
  193. self.data = data
  194. def get_local_config(self):
  195. """Returns the non-default config values in a dict"""
  196. return self.data;
  197. def get_item_list(self, identifier = None, recurse = False):
  198. """Returns a list of strings containing the full identifiers of
  199. all 'sub'options at the given identifier. If recurse is True,
  200. it will also add all identifiers of all children, if any"""
  201. if identifier:
  202. spec = find_spec_part(self.specification.get_config_spec(), identifier)
  203. return spec_name_list(spec, identifier + "/")
  204. return spec_name_list(self.specification.get_config_spec(), "", recurse)
  205. def get_full_config(self):
  206. """Returns a dict containing identifier: value elements, for
  207. all configuration options for this module. If there is
  208. a local setting, that will be used. Otherwise the value
  209. will be the default as specified by the module specification.
  210. If there is no default and no local setting, the value will
  211. be None"""
  212. items = self.get_item_list(None, True)
  213. result = {}
  214. for item in items:
  215. value, default = self.get_value(item)
  216. result[item] = value
  217. return result
  218. # should we just make a class for these?
  219. def _create_value_map_entry(name, type, value, status = None):
  220. entry = {}
  221. entry['name'] = name
  222. entry['type'] = type
  223. entry['value'] = value
  224. entry['modified'] = False
  225. entry['default'] = False
  226. if status == MultiConfigData.LOCAL:
  227. entry['modified'] = True
  228. if status == MultiConfigData.DEFAULT:
  229. entry['default'] = True
  230. return entry
  231. class MultiConfigData:
  232. """This class stores the module specs, current non-default
  233. configuration values and 'local' (uncommitted) changes for
  234. multiple modules"""
  235. LOCAL = 1
  236. CURRENT = 2
  237. DEFAULT = 3
  238. NONE = 4
  239. def __init__(self):
  240. self._specifications = {}
  241. self._current_config = {}
  242. self._local_changes = {}
  243. def set_specification(self, spec):
  244. """Add or update a ModuleSpec. Raises a ConfigDataError is spec is not a ModuleSpec"""
  245. if type(spec) != isc.config.ModuleSpec:
  246. raise ConfigDataError("not a datadef: " + str(type(spec)))
  247. self._specifications[spec.get_module_name()] = spec
  248. def remove_specification(self, module_name):
  249. """Removes the specification with the given module name. Does nothing if it wasn't there."""
  250. if module_name in self._specifications:
  251. del self._specifications[module_name]
  252. def have_specification(self, module_name):
  253. """Returns True if we have a specification for the module with the given name.
  254. Returns False if we do not."""
  255. return module_name in self._specifications
  256. def get_module_spec(self, module):
  257. """Returns the ModuleSpec for the module with the given name.
  258. If there is no such module, it returns None"""
  259. if module in self._specifications:
  260. return self._specifications[module]
  261. else:
  262. return None
  263. def find_spec_part(self, identifier):
  264. """Returns the specification for the item at the given
  265. identifier, or None if not found. The first part of the
  266. identifier (up to the first /) is interpreted as the module
  267. name. Returns None if not found, or if identifier is not a
  268. string."""
  269. if type(identifier) != str or identifier == "":
  270. return None
  271. if identifier[0] == '/':
  272. identifier = identifier[1:]
  273. module, sep, id = identifier.partition("/")
  274. try:
  275. return find_spec_part(self._specifications[module].get_config_spec(), id)
  276. except isc.cc.data.DataNotFoundError as dnfe:
  277. return None
  278. except KeyError as ke:
  279. return None
  280. # this function should only be called by __request_config
  281. def _set_current_config(self, config):
  282. """Replace the full current config values."""
  283. self._current_config = config
  284. def get_current_config(self):
  285. """Returns the current configuration as it is known by the
  286. configuration manager. It is a dict where the first level is
  287. the module name, and the value is the config values for
  288. that module"""
  289. return self._current_config
  290. def get_local_changes(self):
  291. """Returns the local config changes, i.e. those that have not
  292. been committed yet and are not known by the configuration
  293. manager or the modules."""
  294. return self._local_changes
  295. def clear_local_changes(self):
  296. """Reverts all local changes"""
  297. self._local_changes = {}
  298. def get_local_value(self, identifier):
  299. """Returns a specific local (uncommitted) configuration value,
  300. as specified by the identifier. If the local changes do not
  301. contain a new setting for this identifier, or if the
  302. identifier cannot be found, None is returned. See
  303. get_value() for a general way to find a configuration value
  304. """
  305. return isc.cc.data.find_no_exc(self._local_changes, identifier)
  306. def get_current_value(self, identifier):
  307. """Returns the current non-default value as known by the
  308. configuration manager, or None if it is not set.
  309. See get_value() for a general way to find a configuration
  310. value
  311. """
  312. return isc.cc.data.find_no_exc(self._current_config, identifier)
  313. def get_default_value(self, identifier):
  314. """Returns the default value for the given identifier as
  315. specified by the module specification, or None if there is
  316. no default or the identifier could not be found.
  317. See get_value() for a general way to find a configuration
  318. value
  319. """
  320. if identifier[0] == '/':
  321. identifier = identifier[1:]
  322. module, sep, id = identifier.partition("/")
  323. try:
  324. spec = find_spec_part(self._specifications[module].get_config_spec(), id)
  325. if 'item_default' in spec:
  326. id, list_indices = isc.cc.data.split_identifier_list_indices(id)
  327. if list_indices is not None and \
  328. type(spec['item_default']) == list:
  329. if len(list_indices) == 1:
  330. default_list = spec['item_default']
  331. index = list_indices[0]
  332. if index < len(default_list):
  333. return default_list[index]
  334. else:
  335. return None
  336. else:
  337. return spec['item_default']
  338. else:
  339. return None
  340. except isc.cc.data.DataNotFoundError as dnfe:
  341. return None
  342. def get_value(self, identifier, default = True):
  343. """Returns a tuple containing value,status.
  344. The value contains the configuration value for the given
  345. identifier. The status reports where this value came from;
  346. it is one of: LOCAL, CURRENT, DEFAULT or NONE, corresponding
  347. (local change, current setting, default as specified by the
  348. specification, or not found at all). Does not check and
  349. set DEFAULT if the argument 'default' is False (default
  350. defaults to True)"""
  351. value = self.get_local_value(identifier)
  352. if value != None:
  353. return value, self.LOCAL
  354. value = self.get_current_value(identifier)
  355. if value != None:
  356. return value, self.CURRENT
  357. if default:
  358. value = self.get_default_value(identifier)
  359. if value != None:
  360. return value, self.DEFAULT
  361. return None, self.NONE
  362. def get_value_maps(self, identifier = None):
  363. """Returns a list of dicts, containing the following values:
  364. name: name of the entry (string)
  365. type: string containing the type of the value (or 'module')
  366. value: value of the entry if it is a string, int, double or bool
  367. modified: true if the value is a local change
  368. default: true if the value has been changed
  369. TODO: use the consts for those last ones
  370. Throws DataNotFoundError if the identifier is bad
  371. """
  372. result = []
  373. if not identifier:
  374. # No identifier, so we need the list of current modules
  375. for module in self._specifications.keys():
  376. entry = _create_value_map_entry(module, 'module', None)
  377. result.append(entry)
  378. else:
  379. if identifier[0] == '/':
  380. identifier = identifier[1:]
  381. module, sep, id = identifier.partition('/')
  382. spec = self.get_module_spec(module)
  383. if spec:
  384. spec_part = find_spec_part(spec.get_config_spec(), id)
  385. if type(spec_part) == list:
  386. # list of items to show
  387. for item in spec_part:
  388. value, status = self.get_value("/" + identifier\
  389. + "/" + item['item_name'])
  390. entry = _create_value_map_entry(item['item_name'],
  391. item['item_type'],
  392. value, status)
  393. result.append(entry)
  394. elif type(spec_part) == dict:
  395. # Sub-specification
  396. item = spec_part
  397. if item['item_type'] == 'list':
  398. li_spec = item['list_item_spec']
  399. value, status = self.get_value("/" + identifier)
  400. if type(value) == list:
  401. for list_value in value:
  402. result_part2 = _create_value_map_entry(
  403. li_spec['item_name'],
  404. li_spec['item_type'],
  405. list_value)
  406. result.append(result_part2)
  407. elif value is not None:
  408. entry = _create_value_map_entry(
  409. li_spec['item_name'],
  410. li_spec['item_type'],
  411. value, status)
  412. result.append(entry)
  413. else:
  414. value, status = self.get_value("/" + identifier)
  415. if value is not None:
  416. entry = _create_value_map_entry(
  417. item['item_name'],
  418. item['item_type'],
  419. value, status)
  420. result.append(entry)
  421. return result
  422. def set_value(self, identifier, value):
  423. """Set the local value at the given identifier to value. If
  424. there is a specification for the given identifier, the type
  425. is checked."""
  426. spec_part = self.find_spec_part(identifier)
  427. if spec_part is not None and value is not None:
  428. id, list_indices = isc.cc.data.split_identifier_list_indices(identifier)
  429. if list_indices is not None \
  430. and spec_part['item_type'] == 'list':
  431. spec_part = spec_part['list_item_spec']
  432. check_type(spec_part, value)
  433. # Since we do not support list diffs (yet?), we need to
  434. # copy the currently set list of items to _local_changes
  435. # if we want to modify an element in there
  436. # (for any list indices specified in the full identifier)
  437. id_parts = isc.cc.data.split_identifier(identifier)
  438. cur_id_part = '/'
  439. for id_part in id_parts:
  440. id, list_indices = isc.cc.data.split_identifier_list_indices(id_part)
  441. if list_indices is not None:
  442. cur_list, status = self.get_value(cur_id_part + id)
  443. if status != MultiConfigData.LOCAL:
  444. isc.cc.data.set(self._local_changes,
  445. cur_id_part + id,
  446. cur_list)
  447. cur_id_part = cur_id_part + id_part + "/"
  448. isc.cc.data.set(self._local_changes, identifier, value)
  449. def get_config_item_list(self, identifier = None, recurse = False):
  450. """Returns a list of strings containing the item_names of
  451. the child items at the given identifier. If no identifier is
  452. specified, returns a list of module names. The first part of
  453. the identifier (up to the first /) is interpreted as the
  454. module name"""
  455. if identifier and identifier != "/":
  456. if identifier.startswith("/"):
  457. identifier = identifier[1:]
  458. spec = self.find_spec_part(identifier)
  459. return spec_name_list(spec, identifier + "/", recurse)
  460. else:
  461. if recurse:
  462. id_list = []
  463. for module in self._specifications.keys():
  464. id_list.extend(spec_name_list(self.find_spec_part(module), module, recurse))
  465. return id_list
  466. else:
  467. return list(self._specifications.keys())