config_data.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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. # Helper functions
  26. def spec_part_is_list(spec_part):
  27. """Returns True if the given spec_part is a dict that contains a
  28. list specification, and False otherwise."""
  29. return (type(spec_part) == dict and 'list_item_spec' in spec_part)
  30. def spec_part_is_map(spec_part):
  31. """Returns True if the given spec_part is a dict that contains a
  32. map specification, and False otherwise."""
  33. return (type(spec_part) == dict and 'map_item_spec' in spec_part)
  34. def spec_part_is_named_set(spec_part):
  35. """Returns True if the given spec_part is a dict that contains a
  36. named_set specification, and False otherwise."""
  37. return (type(spec_part) == dict and 'named_map_item_spec' in spec_part)
  38. def check_type(spec_part, value):
  39. """Does nothing if the value is of the correct type given the
  40. specification part relevant for the value. Raises an
  41. isc.cc.data.DataTypeError exception if not. spec_part can be
  42. retrieved with find_spec_part()"""
  43. if type(spec_part) == dict and 'item_type' in spec_part:
  44. data_type = spec_part['item_type']
  45. else:
  46. raise isc.cc.data.DataTypeError(str("Incorrect specification part for type checking"))
  47. if data_type == "integer" and type(value) != int:
  48. raise isc.cc.data.DataTypeError(str(value) + " is not an integer")
  49. elif data_type == "real" and type(value) != float:
  50. raise isc.cc.data.DataTypeError(str(value) + " is not a real")
  51. elif data_type == "boolean" and type(value) != bool:
  52. raise isc.cc.data.DataTypeError(str(value) + " is not a boolean")
  53. elif data_type == "string" and type(value) != str:
  54. raise isc.cc.data.DataTypeError(str(value) + " is not a string")
  55. elif data_type == "list":
  56. if type(value) != list:
  57. raise isc.cc.data.DataTypeError(str(value) + " is not a list")
  58. else:
  59. for element in value:
  60. check_type(spec_part['list_item_spec'], element)
  61. elif data_type == "map" and type(value) != dict:
  62. # todo: check types of map contents too
  63. raise isc.cc.data.DataTypeError(str(value) + " is not a map")
  64. def convert_type(spec_part, value):
  65. """Convert the given value(type is string) according specification
  66. part relevant for the value. Raises an isc.cc.data.DataTypeError
  67. exception if conversion failed.
  68. """
  69. if type(spec_part) == dict and 'item_type' in spec_part:
  70. data_type = spec_part['item_type']
  71. else:
  72. raise isc.cc.data.DataTypeError(str("Incorrect specification part for type conversion"))
  73. try:
  74. if data_type == "integer":
  75. return int(value)
  76. elif data_type == "real":
  77. return float(value)
  78. elif data_type == "boolean":
  79. return str.lower(str(value)) != 'false'
  80. elif data_type == "string":
  81. return str(value)
  82. elif data_type == "list":
  83. ret = []
  84. if type(value) == list:
  85. for item in value:
  86. ret.append(convert_type(spec_part['list_item_spec'], item))
  87. elif type(value) == str:
  88. value = value.split(',')
  89. for item in value:
  90. sub_value = item.split()
  91. for sub_item in sub_value:
  92. ret.append(convert_type(spec_part['list_item_spec'],
  93. sub_item))
  94. if ret == []:
  95. raise isc.cc.data.DataTypeError(str(value) + " is not a list")
  96. return ret
  97. elif data_type == "map":
  98. map = ast.literal_eval(value)
  99. if type(map) == dict:
  100. # todo: check types of map contents too
  101. return map
  102. else:
  103. raise isc.cc.data.DataTypeError(
  104. "Value in convert_type not a string "
  105. "specifying a dict")
  106. else:
  107. return value
  108. except ValueError as err:
  109. raise isc.cc.data.DataTypeError(str(err))
  110. except TypeError as err:
  111. raise isc.cc.data.DataTypeError(str(err))
  112. def _get_map_or_list(spec_part):
  113. """Returns the list or map specification if this is a list or a
  114. map specification part. If not, returns the given spec_part
  115. itself"""
  116. if spec_part_is_map(spec_part):
  117. return spec_part["map_item_spec"]
  118. elif spec_part_is_list(spec_part):
  119. return spec_part["list_item_spec"]
  120. else:
  121. return spec_part
  122. def _find_spec_part_single(cur_spec, id_part):
  123. """Find the spec part for the given (partial) name. This partial
  124. name does not contain separators ('/'), and the specification
  125. part should be a direct child of the given specification part.
  126. id_part may contain list selectors, which will be ignored.
  127. Returns the child part.
  128. Raises DataNotFoundError if it was not found."""
  129. # strip list selector part
  130. # don't need it for the spec part, so just drop it
  131. id, list_indices = isc.cc.data.split_identifier_list_indices(id_part)
  132. # The specification we want a sub-part for should be either a
  133. # list or a map, which is internally represented by a dict with
  134. # an element 'map_item_spec', a dict with an element 'list_item_spec',
  135. # or a list (when it is the 'main' config_data element of a module).
  136. if spec_part_is_map(cur_spec):
  137. for cur_spec_item in cur_spec['map_item_spec']:
  138. if cur_spec_item['item_name'] == id:
  139. return cur_spec_item
  140. # not found
  141. raise isc.cc.data.DataNotFoundError(id + " not found")
  142. elif spec_part_is_list(cur_spec):
  143. if cur_spec['item_name'] == id:
  144. return cur_spec['list_item_spec']
  145. # not found
  146. raise isc.cc.data.DataNotFoundError(id + " not found")
  147. elif type(cur_spec) == dict and 'named_set_item_spec' in cur_spec.keys():
  148. return cur_spec['named_set_item_spec']
  149. elif type(cur_spec) == list:
  150. for cur_spec_item in cur_spec:
  151. if cur_spec_item['item_name'] == id:
  152. return cur_spec_item
  153. # not found
  154. raise isc.cc.data.DataNotFoundError(id + " not found")
  155. else:
  156. raise isc.cc.data.DataNotFoundError("Not a correct config specification")
  157. def find_spec_part(element, identifier, strict_identifier = True):
  158. """find the data definition for the given identifier
  159. returns either a map with 'item_name' etc, or a list of those
  160. Parameters:
  161. element: The specification element to start the search in
  162. identifier: The element to find (relative to element above)
  163. strict_identifier: If True (the default), additional checking occurs.
  164. Currently the only check is whether a list index is
  165. specified (except for the last part of the
  166. identifier)
  167. Raises a DataNotFoundError if the data is not found, or if
  168. strict_identifier is True and any non-final identifier parts
  169. (i.e. before the last /) identify a list element and do not contain
  170. an index.
  171. Returns the spec element identified by the given identifier.
  172. """
  173. if identifier == "":
  174. return element
  175. id_parts = identifier.split("/")
  176. id_parts[:] = (value for value in id_parts if value != "")
  177. cur_el = element
  178. # up to the last element, if the result is a map or a list,
  179. # we want its subspecification (i.e. list_item_spec or
  180. # map_item_spec). For the last element in the identifier we
  181. # always want the 'full' spec of the item
  182. for id_part in id_parts[:-1]:
  183. cur_el = _find_spec_part_single(cur_el, id_part)
  184. if strict_identifier and spec_part_is_list(cur_el) and\
  185. not isc.cc.data.identifier_has_list_index(id_part):
  186. raise isc.cc.data.DataNotFoundError(id_part +
  187. " is a list and needs an index")
  188. cur_el = _get_map_or_list(cur_el)
  189. cur_el = _find_spec_part_single(cur_el, id_parts[-1])
  190. return cur_el
  191. def spec_name_list(spec, prefix="", recurse=False):
  192. """Returns a full list of all possible item identifiers in the
  193. specification (part). Raises a ConfigDataError if spec is not
  194. a correct spec (as returned by ModuleSpec.get_config_spec()"""
  195. result = []
  196. if prefix != "" and not prefix.endswith("/"):
  197. prefix += "/"
  198. if type(spec) == dict:
  199. if spec_part_is_map(spec):
  200. for map_el in spec['map_item_spec']:
  201. name = map_el['item_name']
  202. if map_el['item_type'] == 'map':
  203. name += "/"
  204. if recurse and spec_part_is_map(map_el):
  205. result.extend(spec_name_list(map_el['map_item_spec'], prefix + map_el['item_name'], recurse))
  206. else:
  207. result.append(prefix + name)
  208. elif 'named_set_item_spec' in spec:
  209. # we added a '/' above, but in this one case we don't want it
  210. result.append(prefix[:-1])
  211. else:
  212. for name in spec:
  213. result.append(prefix + name + "/")
  214. if recurse:
  215. result.extend(spec_name_list(spec[name], name, recurse))
  216. elif type(spec) == list:
  217. for list_el in spec:
  218. if 'item_name' in list_el:
  219. if list_el['item_type'] == "map" and recurse:
  220. result.extend(spec_name_list(list_el['map_item_spec'], prefix + list_el['item_name'], recurse))
  221. else:
  222. name = list_el['item_name']
  223. result.append(prefix + name)
  224. else:
  225. raise ConfigDataError("Bad specification")
  226. else:
  227. raise ConfigDataError("Bad specification")
  228. return result
  229. class ConfigData:
  230. """This class stores the module specs and the current non-default
  231. config values. It provides functions to get the actual value or
  232. the default value if no non-default value has been set"""
  233. def __init__(self, specification):
  234. """Initialize a ConfigData instance. If specification is not
  235. of type ModuleSpec, a ConfigDataError is raised."""
  236. if type(specification) != isc.config.ModuleSpec:
  237. raise ConfigDataError("specification is of type " + str(type(specification)) + ", not ModuleSpec")
  238. self.specification = specification
  239. self.data = {}
  240. def get_value(self, identifier):
  241. """Returns a tuple where the first item is the value at the
  242. given identifier, and the second item is a bool which is
  243. true if the value is an unset default. Raises an
  244. isc.cc.data.DataNotFoundError if the identifier is bad"""
  245. value = isc.cc.data.find_no_exc(self.data, identifier)
  246. if value != None:
  247. return value, False
  248. spec = find_spec_part(self.specification.get_config_spec(), identifier)
  249. if spec and 'item_default' in spec:
  250. return spec['item_default'], True
  251. return None, False
  252. def get_default_value(self, identifier):
  253. """Returns the default from the specification, or None if there
  254. is no default"""
  255. # We are searching for the default value, so we can set
  256. # strict_identifier to false (in fact, we need to; we may not know
  257. # some list indices, or they may not exist, we are looking for
  258. # a default value for a reason here).
  259. spec = find_spec_part(self.specification.get_config_spec(),
  260. identifier, False)
  261. if spec and 'item_default' in spec:
  262. return spec['item_default']
  263. else:
  264. return None
  265. def get_module_spec(self):
  266. """Returns the ModuleSpec object associated with this ConfigData"""
  267. return self.specification
  268. def set_local_config(self, data):
  269. """Set the non-default config values, as passed by cfgmgr"""
  270. self.data = data
  271. def get_local_config(self):
  272. """Returns the non-default config values in a dict"""
  273. return self.data
  274. def get_item_list(self, identifier = None, recurse = False):
  275. """Returns a list of strings containing the full identifiers of
  276. all 'sub'options at the given identifier. If recurse is True,
  277. it will also add all identifiers of all children, if any"""
  278. if identifier:
  279. spec = find_spec_part(self.specification.get_config_spec(), identifier)
  280. return spec_name_list(spec, identifier + "/")
  281. return spec_name_list(self.specification.get_config_spec(), "", recurse)
  282. def get_full_config(self):
  283. """Returns a dict containing identifier: value elements, for
  284. all configuration options for this module. If there is
  285. a local setting, that will be used. Otherwise the value
  286. will be the default as specified by the module specification.
  287. If there is no default and no local setting, the value will
  288. be None"""
  289. items = self.get_item_list(None, True)
  290. result = {}
  291. for item in items:
  292. value, default = self.get_value(item)
  293. result[item] = value
  294. return result
  295. # should we just make a class for these?
  296. def _create_value_map_entry(name, type, value, status = None):
  297. entry = {}
  298. entry['name'] = name
  299. entry['type'] = type
  300. entry['value'] = value
  301. entry['modified'] = False
  302. entry['default'] = False
  303. if status == MultiConfigData.LOCAL:
  304. entry['modified'] = True
  305. if status == MultiConfigData.DEFAULT:
  306. entry['default'] = True
  307. return entry
  308. class MultiConfigData:
  309. """This class stores the module specs, current non-default
  310. configuration values and 'local' (uncommitted) changes for
  311. multiple modules"""
  312. LOCAL = 1
  313. CURRENT = 2
  314. DEFAULT = 3
  315. NONE = 4
  316. def __init__(self):
  317. self._specifications = {}
  318. self._current_config = {}
  319. self._local_changes = {}
  320. def clear_specifications(self):
  321. """Remove all known module specifications"""
  322. self._specifications = {}
  323. def set_specification(self, spec):
  324. """Add or update a ModuleSpec. Raises a ConfigDataError is spec is not a ModuleSpec"""
  325. if type(spec) != isc.config.ModuleSpec:
  326. raise ConfigDataError("not a datadef: " + str(type(spec)))
  327. self._specifications[spec.get_module_name()] = spec
  328. def remove_specification(self, module_name):
  329. """Removes the specification with the given module name. Does nothing if it wasn't there."""
  330. if module_name in self._specifications:
  331. del self._specifications[module_name]
  332. def have_specification(self, module_name):
  333. """Returns True if we have a specification for the module with the given name.
  334. Returns False if we do not."""
  335. return module_name in self._specifications
  336. def get_module_spec(self, module):
  337. """Returns the ModuleSpec for the module with the given name.
  338. If there is no such module, it returns None"""
  339. if module in self._specifications:
  340. return self._specifications[module]
  341. else:
  342. return None
  343. def find_spec_part(self, identifier):
  344. """Returns the specification for the item at the given
  345. identifier, or None if not found. The first part of the
  346. identifier (up to the first /) is interpreted as the module
  347. name. Returns None if not found, or if identifier is not a
  348. string."""
  349. if type(identifier) != str or identifier == "":
  350. return None
  351. if identifier[0] == '/':
  352. identifier = identifier[1:]
  353. module, sep, id = identifier.partition("/")
  354. try:
  355. return find_spec_part(self._specifications[module].get_config_spec(), id)
  356. except isc.cc.data.DataNotFoundError as dnfe:
  357. return None
  358. except KeyError as ke:
  359. return None
  360. # this function should only be called by __request_config
  361. def _set_current_config(self, config):
  362. """Replace the full current config values."""
  363. self._current_config = config
  364. def get_current_config(self):
  365. """Returns the current configuration as it is known by the
  366. configuration manager. It is a dict where the first level is
  367. the module name, and the value is the config values for
  368. that module"""
  369. return self._current_config
  370. def get_local_changes(self):
  371. """Returns the local config changes, i.e. those that have not
  372. been committed yet and are not known by the configuration
  373. manager or the modules."""
  374. return self._local_changes
  375. def clear_local_changes(self):
  376. """Reverts all local changes"""
  377. self._local_changes = {}
  378. def get_local_value(self, identifier):
  379. """Returns a specific local (uncommitted) configuration value,
  380. as specified by the identifier. If the local changes do not
  381. contain a new setting for this identifier, or if the
  382. identifier cannot be found, None is returned. See
  383. get_value() for a general way to find a configuration value
  384. """
  385. return isc.cc.data.find_no_exc(self._local_changes, identifier)
  386. def get_current_value(self, identifier):
  387. """Returns the current non-default value as known by the
  388. configuration manager, or None if it is not set.
  389. See get_value() for a general way to find a configuration
  390. value
  391. """
  392. return isc.cc.data.find_no_exc(self._current_config, identifier)
  393. def get_default_value(self, identifier):
  394. """Returns the default value for the given identifier as
  395. specified by the module specification, or None if there is
  396. no default or the identifier could not be found.
  397. See get_value() for a general way to find a configuration
  398. value
  399. """
  400. try:
  401. if identifier[0] == '/':
  402. identifier = identifier[1:]
  403. module, sep, id = identifier.partition("/")
  404. # if there is a 'higher-level' list index specified, we need
  405. # to check if that list specification has a default that
  406. # overrides the more specific default in the final spec item
  407. # (ie. list_default = [1, 2, 3], list_item_spec=int, default=0)
  408. # def default list[1] should return 2, not 0
  409. id_parts = isc.cc.data.split_identifier(id)
  410. id_prefix = ""
  411. while len(id_parts) > 0:
  412. id_part = id_parts.pop(0)
  413. item_id, list_indices = isc.cc.data.split_identifier_list_indices(id_part)
  414. id_list = module + "/" + id_prefix + "/" + item_id
  415. id_prefix += "/" + id_part
  416. part_spec = find_spec_part(self._specifications[module].get_config_spec(), id_prefix)
  417. if part_spec['item_type'] == 'named_set':
  418. # For named sets, the identifier is partly defined
  419. # by which values are actually present, and not
  420. # purely by the specification.
  421. # So if there is a part of the identifier left,
  422. # we need to look up the value, then see if that
  423. # contains the next part of the identifier we got
  424. if len(id_parts) == 0:
  425. if 'item_default' in part_spec:
  426. return part_spec['item_default']
  427. else:
  428. return None
  429. id_part = id_parts.pop(0)
  430. named_set_value, type = self.get_value(id_list)
  431. if id_part in named_set_value:
  432. if len(id_parts) > 0:
  433. # we are looking for the *default* value.
  434. # so if not present in here, we need to
  435. # lookup the one from the spec
  436. rest_of_id = "/".join(id_parts)
  437. result = isc.cc.data.find_no_exc(named_set_value[id_part], rest_of_id)
  438. if result is None:
  439. spec_part = self.find_spec_part(identifier)
  440. if 'item_default' in spec_part:
  441. return spec_part['item_default']
  442. return result
  443. else:
  444. return named_set_value[id_part]
  445. else:
  446. return None
  447. elif list_indices is not None:
  448. # there's actually two kinds of default here for
  449. # lists; they can have a default value (like an
  450. # empty list), but their elements can also have
  451. # default values.
  452. # So if the list item *itself* is a default,
  453. # we need to get the value out of that. If not, we
  454. # need to find the default for the specific element.
  455. list_value, type = self.get_value(id_list)
  456. list_spec = find_spec_part(self._specifications[module].get_config_spec(), id_prefix)
  457. if type == self.DEFAULT:
  458. if 'item_default' in list_spec:
  459. list_value = list_spec['item_default']
  460. for i in list_indices:
  461. if i < len(list_value):
  462. list_value = list_value[i]
  463. else:
  464. # out of range, return None
  465. return None
  466. if len(id_parts) > 0:
  467. rest_of_id = "/".join(id_parts)
  468. return isc.cc.data.find(list_value, rest_of_id)
  469. else:
  470. return list_value
  471. else:
  472. # we do have a non-default list, see if our indices
  473. # exist
  474. for i in list_indices:
  475. if i < len(list_value):
  476. list_value = list_value[i]
  477. else:
  478. # out of range, return None
  479. return None
  480. spec = find_spec_part(self._specifications[module].get_config_spec(), id)
  481. if 'item_default' in spec:
  482. # one special case, named_set
  483. if spec['item_type'] == 'named_set':
  484. print("is " + id_part + " in named set?")
  485. return spec['item_default']
  486. else:
  487. return spec['item_default']
  488. else:
  489. return None
  490. except isc.cc.data.DataNotFoundError as dnfe:
  491. return None
  492. def get_value(self, identifier, default = True):
  493. """Returns a tuple containing value,status.
  494. The value contains the configuration value for the given
  495. identifier. The status reports where this value came from;
  496. it is one of: LOCAL, CURRENT, DEFAULT or NONE, corresponding
  497. (local change, current setting, default as specified by the
  498. specification, or not found at all). Does not check and
  499. set DEFAULT if the argument 'default' is False (default
  500. defaults to True)"""
  501. value = self.get_local_value(identifier)
  502. if value != None:
  503. return value, self.LOCAL
  504. value = self.get_current_value(identifier)
  505. if value != None:
  506. return value, self.CURRENT
  507. if default:
  508. value = self.get_default_value(identifier)
  509. if value is not None:
  510. return value, self.DEFAULT
  511. return None, self.NONE
  512. def _append_value_item(self, result, spec_part, identifier, all, first = False):
  513. # Look at the spec; it is a list of items, or a map containing 'item_name' etc
  514. if type(spec_part) == list:
  515. for spec_part_element in spec_part:
  516. spec_part_element_name = spec_part_element['item_name']
  517. self._append_value_item(result, spec_part_element, identifier + "/" + spec_part_element_name, all)
  518. elif type(spec_part) == dict:
  519. # depending on item type, and the value of argument 'all'
  520. # we need to either add an item, or recursively go on
  521. # In the case of a list that is empty, we do need to show that
  522. item_name = spec_part['item_name']
  523. item_type = spec_part['item_type']
  524. if item_type == "list" and (all or first):
  525. spec_part_list = spec_part['list_item_spec']
  526. list_value, status = self.get_value(identifier)
  527. if list_value is None:
  528. raise isc.cc.data.DataNotFoundError(identifier + " not found")
  529. if type(list_value) != list:
  530. # the identifier specified a single element
  531. self._append_value_item(result, spec_part_list, identifier, all)
  532. else:
  533. list_len = len(list_value)
  534. if len(list_value) == 0 and (all or first):
  535. entry = _create_value_map_entry(identifier,
  536. item_type,
  537. [], status)
  538. result.append(entry)
  539. else:
  540. for i in range(len(list_value)):
  541. self._append_value_item(result, spec_part_list, "%s[%d]" % (identifier, i), all)
  542. elif item_type == "map":
  543. value, status = self.get_value(identifier)
  544. # just show the specific contents of a map, we are
  545. # almost never interested in just its name
  546. spec_part_map = spec_part['map_item_spec']
  547. self._append_value_item(result, spec_part_map, identifier, all)
  548. elif item_type == "named_set":
  549. value, status = self.get_value(identifier)
  550. # show just the one entry, when either the map is empty,
  551. # or when this is element is not requested specifically
  552. if len(value.keys()) == 0:
  553. entry = _create_value_map_entry(identifier,
  554. item_type,
  555. {}, status)
  556. result.append(entry)
  557. elif not first and not all:
  558. entry = _create_value_map_entry(identifier,
  559. item_type,
  560. None, status)
  561. result.append(entry)
  562. else:
  563. spec_part_named_set = spec_part['named_set_item_spec']
  564. for entry in value:
  565. self._append_value_item(result,
  566. spec_part_named_set,
  567. identifier + "/" + entry,
  568. all)
  569. else:
  570. value, status = self.get_value(identifier)
  571. if status == self.NONE and not spec_part['item_optional']:
  572. raise isc.cc.data.DataNotFoundError(identifier + " not found")
  573. entry = _create_value_map_entry(identifier,
  574. item_type,
  575. value, status)
  576. result.append(entry)
  577. return
  578. def get_value_maps(self, identifier = None, all = False):
  579. """Returns a list of dicts, containing the following values:
  580. name: name of the entry (string)
  581. type: string containing the type of the value (or 'module')
  582. value: value of the entry if it is a string, int, double or bool
  583. modified: true if the value is a local change that has not
  584. been committed
  585. default: true if the value has not been changed (i.e. the
  586. value is the default from the specification)
  587. TODO: use the consts for those last ones
  588. Throws DataNotFoundError if the identifier is bad
  589. """
  590. result = []
  591. if not identifier or identifier == "/":
  592. # No identifier, so we need the list of current modules
  593. for module in self._specifications.keys():
  594. if all:
  595. spec = self.get_module_spec(module)
  596. if spec:
  597. spec_part = spec.get_config_spec()
  598. self._append_value_item(result, spec_part, module, all, True)
  599. else:
  600. entry = _create_value_map_entry(module, 'module', None)
  601. result.append(entry)
  602. else:
  603. # Strip off start and end slashes, if they are there
  604. if len(identifier) > 0 and identifier[0] == '/':
  605. identifier = identifier[1:]
  606. if len(identifier) > 0 and identifier[-1] == '/':
  607. identifier = identifier[:-1]
  608. module, sep, id = identifier.partition('/')
  609. spec = self.get_module_spec(module)
  610. if spec:
  611. spec_part = find_spec_part(spec.get_config_spec(), id)
  612. self._append_value_item(result, spec_part, identifier, all, True)
  613. return result
  614. def set_value(self, identifier, value):
  615. """Set the local value at the given identifier to value. If
  616. there is a specification for the given identifier, the type
  617. is checked."""
  618. spec_part = self.find_spec_part(identifier)
  619. if spec_part is not None:
  620. if value is not None:
  621. id, list_indices = isc.cc.data.split_identifier_list_indices(identifier)
  622. if list_indices is not None \
  623. and spec_part['item_type'] == 'list':
  624. spec_part = spec_part['list_item_spec']
  625. check_type(spec_part, value)
  626. else:
  627. raise isc.cc.data.DataNotFoundError(identifier + " not found")
  628. # Since we do not support list diffs (yet?), we need to
  629. # copy the currently set list of items to _local_changes
  630. # if we want to modify an element in there
  631. # (for any list indices specified in the full identifier)
  632. id_parts = isc.cc.data.split_identifier(identifier)
  633. cur_id_part = '/'
  634. for id_part in id_parts:
  635. id, list_indices = isc.cc.data.split_identifier_list_indices(id_part)
  636. cur_value, status = self.get_value(cur_id_part + id)
  637. # Check if the value was there in the first place
  638. # If we are at the final element, we do not care whether we found
  639. # it, since if we have reached this point and it did not exist,
  640. # it was apparently an optional value without a default.
  641. if status == MultiConfigData.NONE and cur_id_part != "/" and\
  642. cur_id_part + id != identifier:
  643. raise isc.cc.data.DataNotFoundError(id_part +
  644. " not found in " +
  645. cur_id_part)
  646. if list_indices is not None:
  647. # And check if we don't set something outside of any
  648. # list
  649. cur_list = cur_value
  650. for list_index in list_indices:
  651. if list_index >= len(cur_list):
  652. raise isc.cc.data.DataNotFoundError("No item " +
  653. str(list_index) + " in " + id_part)
  654. else:
  655. cur_list = cur_list[list_index]
  656. if status != MultiConfigData.LOCAL:
  657. isc.cc.data.set(self._local_changes,
  658. cur_id_part + id,
  659. cur_value)
  660. cur_id_part = cur_id_part + id_part + "/"
  661. isc.cc.data.set(self._local_changes, identifier, value)
  662. def _get_list_items(self, item_name):
  663. """This method is used in get_config_item_list, to add list
  664. indices and named_set names to the completion list. If
  665. the given item_name is for a list or named_set, it'll
  666. return a list of those (appended to item_name), otherwise
  667. the list will only contain the item_name itself."""
  668. spec_part = self.find_spec_part(item_name)
  669. if 'item_type' in spec_part and \
  670. spec_part['item_type'] == 'named_set':
  671. subslash = ""
  672. if spec_part['named_set_item_spec']['item_type'] == 'map' or\
  673. spec_part['named_set_item_spec']['item_type'] == 'named_set':
  674. subslash = "/"
  675. values, status = self.get_value(item_name)
  676. if len(values) > 0:
  677. return [ item_name + "/" + v + subslash for v in values.keys() ]
  678. else:
  679. return [ item_name ]
  680. else:
  681. return [ item_name ]
  682. def get_config_item_list(self, identifier = None, recurse = False):
  683. """Returns a list of strings containing the item_names of
  684. the child items at the given identifier. If no identifier is
  685. specified, returns a list of module names. The first part of
  686. the identifier (up to the first /) is interpreted as the
  687. module name"""
  688. if identifier and identifier != "/":
  689. if identifier.startswith("/"):
  690. identifier = identifier[1:]
  691. spec = self.find_spec_part(identifier)
  692. spec_list = spec_name_list(spec, identifier + "/", recurse)
  693. result_list = []
  694. for spec_name in spec_list:
  695. result_list.extend(self._get_list_items(spec_name))
  696. return result_list
  697. else:
  698. if recurse:
  699. id_list = []
  700. for module in self._specifications.keys():
  701. id_list.extend(spec_name_list(self.find_spec_part(module), module, recurse))
  702. return id_list
  703. else:
  704. return list(self._specifications.keys())