config_data.py 33 KB

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