cfgmgr.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. """This is the BIND 10 configuration manager, run by b10-cfgmgr.
  16. It stores the system configuration, and sends updates of the
  17. configuration to the modules that need them.
  18. """
  19. import isc
  20. import signal
  21. import ast
  22. import os
  23. import copy
  24. import tempfile
  25. import json
  26. import errno
  27. from isc.cc import data
  28. from isc.config import ccsession, config_data
  29. class ConfigManagerDataReadError(Exception):
  30. """This exception is thrown when there is an error while reading
  31. the current configuration on startup."""
  32. pass
  33. class ConfigManagerDataEmpty(Exception):
  34. """This exception is thrown when the currently stored configuration
  35. is not found, or appears empty."""
  36. pass
  37. class ConfigManagerData:
  38. """This class hold the actual configuration information, and
  39. reads it from and writes it to persistent storage"""
  40. def __init__(self, data_path, file_name):
  41. """Initialize the data for the configuration manager, and
  42. set the version and path for the data store. Initializing
  43. this does not yet read the database, a call to
  44. read_from_file is needed for that.
  45. In case the file_name is absolute, data_path is ignored
  46. and the directory where the file_name lives is used instead.
  47. """
  48. self.data = {}
  49. self.data['version'] = config_data.BIND10_CONFIG_DATA_VERSION
  50. if os.path.isabs(file_name):
  51. self.db_filename = file_name
  52. self.data_path = os.path.dirname(file_name)
  53. else:
  54. self.db_filename = data_path + os.sep + file_name
  55. self.data_path = data_path
  56. def read_from_file(data_path, file_name):
  57. """Read the current configuration found in the file file_name.
  58. If file_name is absolute, data_path is ignored. Otherwise
  59. we look for the file_name in data_path directory.
  60. If the file does not exist, a ConfigManagerDataEmpty exception is
  61. raised. If there is a parse error, or if the data in the file has
  62. the wrong version, a ConfigManagerDataReadError is raised. In the
  63. first case, it is probably safe to log and ignore. In the case of
  64. the second exception, the best way is probably to report the error
  65. and stop loading the system.
  66. """
  67. config = ConfigManagerData(data_path, file_name)
  68. file = None
  69. try:
  70. file = open(config.db_filename, 'r')
  71. file_config = json.loads(file.read())
  72. # handle different versions here
  73. # If possible, we automatically convert to the new
  74. # scheme and update the configuration
  75. # If not, we raise an exception
  76. if 'version' in file_config:
  77. if file_config['version'] == config_data.BIND10_CONFIG_DATA_VERSION:
  78. config.data = file_config
  79. elif file_config['version'] == 1:
  80. # only format change, no other changes necessary
  81. file_config['version'] = 2
  82. print("[b10-cfgmgr] Updating configuration database version from 1 to 2")
  83. config.data = file_config
  84. else:
  85. if config_data.BIND10_CONFIG_DATA_VERSION > file_config['version']:
  86. raise ConfigManagerDataReadError("Cannot load configuration file: version %d no longer supported" % file_config['version'])
  87. else:
  88. raise ConfigManagerDataReadError("Cannot load configuration file: version %d not yet supported" % file_config['version'])
  89. else:
  90. raise ConfigManagerDataReadError("No version information in configuration file " + config.db_filename)
  91. except IOError as ioe:
  92. # if IOError is 'no such file or directory', then continue
  93. # (raise empty), otherwise fail (raise error)
  94. if ioe.errno == errno.ENOENT:
  95. raise ConfigManagerDataEmpty("No configuration file found")
  96. else:
  97. raise ConfigManagerDataReadError("Can't read configuration file: " + str(ioe))
  98. except ValueError:
  99. raise ConfigManagerDataReadError("Configuration file out of date or corrupt, please update or remove " + config.db_filename)
  100. finally:
  101. if file:
  102. file.close();
  103. return config
  104. def write_to_file(self, output_file_name = None):
  105. """Writes the current configuration data to a file. If
  106. output_file_name is not specified, the file used in
  107. read_from_file is used."""
  108. filename = None
  109. try:
  110. file = tempfile.NamedTemporaryFile(mode='w',
  111. prefix="b10-config.db.",
  112. dir=self.data_path,
  113. delete=False)
  114. filename = file.name
  115. file.write(json.dumps(self.data))
  116. file.write("\n")
  117. file.close()
  118. if output_file_name:
  119. os.rename(filename, output_file_name)
  120. else:
  121. os.rename(filename, self.db_filename)
  122. except IOError as ioe:
  123. # TODO: log this (level critical)
  124. print("[b10-cfgmgr] Unable to write configuration file; configuration not stored: " + str(ioe))
  125. # TODO: debug option to keep file?
  126. except OSError as ose:
  127. # TODO: log this (level critical)
  128. print("[b10-cfgmgr] Unable to write configuration file; configuration not stored: " + str(ose))
  129. try:
  130. if filename and os.path.exists(filename):
  131. os.remove(filename)
  132. except OSError:
  133. # Ok if we really can't delete it anymore, leave it
  134. pass
  135. def __eq__(self, other):
  136. """Returns True if the data contained is equal. data_path and
  137. db_filename may be different."""
  138. if type(other) != type(self):
  139. return False
  140. return self.data == other.data
  141. class ConfigManager:
  142. """Creates a configuration manager. The data_path is the path
  143. to the directory containing the configuraton file,
  144. database_filename points to the configuration file.
  145. If session is set, this will be used as the communication
  146. channel session. If not, a new session will be created.
  147. The ability to specify a custom session is for testing purposes
  148. and should not be needed for normal usage."""
  149. def __init__(self, data_path, database_filename, session=None):
  150. """Initialize the configuration manager. The data_path string
  151. is the path to the directory where the configuration is
  152. stored (in <data_path>/<database_filename> or in
  153. <database_filename>, if it is absolute). The dabase_filename
  154. is the config file to load. Session is an optional
  155. cc-channel session. If this is not given, a new one is
  156. created."""
  157. self.data_path = data_path
  158. self.database_filename = database_filename
  159. self.module_specs = {}
  160. # Virtual modules are the ones which have no process running. The
  161. # checking of validity is done by functions presented here instead
  162. # of some other process
  163. self.virtual_modules = {}
  164. self.config = ConfigManagerData(data_path, database_filename)
  165. if session:
  166. self.cc = session
  167. else:
  168. self.cc = isc.cc.Session()
  169. self.cc.group_subscribe("ConfigManager")
  170. self.cc.group_subscribe("Boss", "ConfigManager")
  171. self.running = False
  172. def notify_boss(self):
  173. """Notifies the Boss module that the Config Manager is running"""
  174. self.cc.group_sendmsg({"running": "configmanager"}, "Boss")
  175. def set_module_spec(self, spec):
  176. """Adds a ModuleSpec"""
  177. self.module_specs[spec.get_module_name()] = spec
  178. def set_virtual_module(self, spec, check_func):
  179. """Adds a virtual module with its spec and checking function."""
  180. self.module_specs[spec.get_module_name()] = spec
  181. self.virtual_modules[spec.get_module_name()] = check_func
  182. def remove_module_spec(self, module_name):
  183. """Removes the full ModuleSpec for the given module_name.
  184. Also removes the virtual module check function if it
  185. was present.
  186. Does nothing if the module was not present."""
  187. if module_name in self.module_specs:
  188. del self.module_specs[module_name]
  189. if module_name in self.virtual_modules:
  190. del self.virtual_modules[module_name]
  191. def get_module_spec(self, module_name = None):
  192. """Returns the full ModuleSpec for the module with the given
  193. module_name. If no module name is given, a dict will
  194. be returned with 'name': module_spec values. If the
  195. module name is given, but does not exist, an empty dict
  196. is returned"""
  197. if module_name:
  198. if module_name in self.module_specs:
  199. return self.module_specs[module_name].get_full_spec()
  200. else:
  201. # TODO: log error?
  202. return {}
  203. else:
  204. result = {}
  205. for module in self.module_specs:
  206. result[module] = self.module_specs[module].get_full_spec()
  207. return result
  208. def get_config_spec(self, name = None):
  209. """Returns a dict containing 'module_name': config_spec for
  210. all modules. If name is specified, only that module will
  211. be included"""
  212. config_data = {}
  213. if name:
  214. if name in self.module_specs:
  215. config_data[name] = self.module_specs[name].get_config_spec()
  216. else:
  217. for module_name in self.module_specs.keys():
  218. config_data[module_name] = self.module_specs[module_name].get_config_spec()
  219. return config_data
  220. def get_commands_spec(self, name = None):
  221. """Returns a dict containing 'module_name': commands_spec for
  222. all modules. If name is specified, only that module will
  223. be included"""
  224. commands = {}
  225. if name:
  226. if name in self.module_specs:
  227. commands[name] = self.module_specs[name].get_commands_spec()
  228. else:
  229. for module_name in self.module_specs.keys():
  230. commands[module_name] = self.module_specs[module_name].get_commands_spec()
  231. return commands
  232. def read_config(self):
  233. """Read the current configuration from the file specificied at init()"""
  234. try:
  235. self.config = ConfigManagerData.read_from_file(self.data_path,
  236. self.\
  237. database_filename)
  238. except ConfigManagerDataEmpty:
  239. # ok, just start with an empty config
  240. self.config = ConfigManagerData(self.data_path,
  241. self.database_filename)
  242. def write_config(self):
  243. """Write the current configuration to the file specificied at init()"""
  244. self.config.write_to_file()
  245. def _handle_get_module_spec(self, cmd):
  246. """Private function that handles the 'get_module_spec' command"""
  247. answer = {}
  248. if cmd != None:
  249. if type(cmd) == dict:
  250. if 'module_name' in cmd and cmd['module_name'] != '':
  251. module_name = cmd['module_name']
  252. spec = self.get_module_spec(cmd['module_name'])
  253. if type(spec) != type({}):
  254. # this is a ModuleSpec object. Extract the
  255. # internal spec.
  256. spec = spec.get_full_spec()
  257. answer = ccsession.create_answer(0, spec)
  258. else:
  259. answer = ccsession.create_answer(1, "Bad module_name in get_module_spec command")
  260. else:
  261. answer = ccsession.create_answer(1, "Bad get_module_spec command, argument not a dict")
  262. else:
  263. answer = ccsession.create_answer(0, self.get_module_spec())
  264. return answer
  265. def _handle_get_config_dict(self, cmd):
  266. """Private function that handles the 'get_config' command
  267. where the command has been checked to be a dict"""
  268. if 'module_name' in cmd and cmd['module_name'] != '':
  269. module_name = cmd['module_name']
  270. try:
  271. return ccsession.create_answer(0, data.find(self.config.data, module_name))
  272. except data.DataNotFoundError as dnfe:
  273. # no data is ok, that means we have nothing that
  274. # deviates from default values
  275. return ccsession.create_answer(0, { 'version': config_data.BIND10_CONFIG_DATA_VERSION })
  276. else:
  277. return ccsession.create_answer(1, "Bad module_name in get_config command")
  278. def _handle_get_config(self, cmd):
  279. """Private function that handles the 'get_config' command"""
  280. if cmd != None:
  281. if type(cmd) == dict:
  282. return self._handle_get_config_dict(cmd)
  283. else:
  284. return ccsession.create_answer(1, "Bad get_config command, argument not a dict")
  285. else:
  286. return ccsession.create_answer(0, self.config.data)
  287. def _handle_set_config_module(self, module_name, cmd):
  288. # the answer comes (or does not come) from the relevant module
  289. # so we need a variable to see if we got it
  290. answer = None
  291. # todo: use api (and check the data against the definition?)
  292. old_data = copy.deepcopy(self.config.data)
  293. conf_part = data.find_no_exc(self.config.data, module_name)
  294. update_cmd = None
  295. use_part = None
  296. if conf_part:
  297. data.merge(conf_part, cmd)
  298. use_part = conf_part
  299. else:
  300. conf_part = data.set(self.config.data, module_name, {})
  301. data.merge(conf_part[module_name], cmd)
  302. use_part = conf_part[module_name]
  303. # The command to send
  304. update_cmd = ccsession.create_command(ccsession.COMMAND_CONFIG_UPDATE,
  305. use_part)
  306. # TODO: This design might need some revisiting. We might want some
  307. # polymorphism instead of branching. But it just might turn out it
  308. # will get solved by itself when we move everything to virtual modules
  309. # (which is possible solution to the offline configuration problem)
  310. # or when we solve the incorect behaviour here when a config is
  311. # rejected (spying modules don't know it was rejected and some modules
  312. # might have been commited already).
  313. if module_name in self.virtual_modules:
  314. # The module is virtual, so call it to get the answer
  315. try:
  316. error = self.virtual_modules[module_name](use_part)
  317. if error is None:
  318. answer = ccsession.create_answer(0)
  319. # OK, it is successful, send the notify, but don't wait
  320. # for answer
  321. seq = self.cc.group_sendmsg(update_cmd, module_name)
  322. else:
  323. answer = ccsession.create_answer(1, error)
  324. # Make sure just a validating plugin don't kill the whole manager
  325. except Exception as excp:
  326. # Provide answer
  327. answer = ccsession.create_answer(1, "Exception: " + str(excp))
  328. else:
  329. # Real module, send it over the wire to it
  330. # send out changed info and wait for answer
  331. seq = self.cc.group_sendmsg(update_cmd, module_name)
  332. try:
  333. # replace 'our' answer with that of the module
  334. answer, env = self.cc.group_recvmsg(False, seq)
  335. except isc.cc.SessionTimeout:
  336. answer = ccsession.create_answer(1, "Timeout waiting for answer from " + module_name)
  337. if answer:
  338. rcode, val = ccsession.parse_answer(answer)
  339. if rcode == 0:
  340. self.write_config()
  341. else:
  342. self.config.data = old_data
  343. return answer
  344. def _handle_set_config_all(self, cmd):
  345. old_data = copy.deepcopy(self.config.data)
  346. got_error = False
  347. err_list = []
  348. # The format of the command is a dict with module->newconfig
  349. # sets, so we simply call set_config_module for each of those
  350. for module in cmd:
  351. if module != "version":
  352. answer = self._handle_set_config_module(module, cmd[module])
  353. if answer == None:
  354. got_error = True
  355. err_list.append("No answer message from " + module)
  356. else:
  357. rcode, val = ccsession.parse_answer(answer)
  358. if rcode != 0:
  359. got_error = True
  360. err_list.append(val)
  361. if not got_error:
  362. self.write_config()
  363. return ccsession.create_answer(0)
  364. else:
  365. # TODO rollback changes that did get through, should we re-send update?
  366. self.config.data = old_data
  367. return ccsession.create_answer(1, " ".join(err_list))
  368. def _handle_set_config(self, cmd):
  369. """Private function that handles the 'set_config' command"""
  370. answer = None
  371. if cmd == None:
  372. return ccsession.create_answer(1, "Wrong number of arguments")
  373. if len(cmd) == 2:
  374. answer = self._handle_set_config_module(cmd[0], cmd[1])
  375. elif len(cmd) == 1:
  376. answer = self._handle_set_config_all(cmd[0])
  377. else:
  378. answer = ccsession.create_answer(1, "Wrong number of arguments")
  379. if not answer:
  380. answer = ccsession.create_answer(1, "No answer message from " + cmd[0])
  381. return answer
  382. def _handle_module_spec(self, spec):
  383. """Private function that handles the 'module_spec' command"""
  384. # todo: validate? (no direct access to spec as
  385. # todo: use ModuleSpec class
  386. # todo: error checking (like keyerrors)
  387. answer = {}
  388. self.set_module_spec(spec)
  389. # We should make one general 'spec update for module' that
  390. # passes both specification and commands at once
  391. spec_update = ccsession.create_command(ccsession.COMMAND_MODULE_SPECIFICATION_UPDATE,
  392. [ spec.get_module_name(), spec.get_full_spec() ])
  393. self.cc.group_sendmsg(spec_update, "Cmdctl")
  394. return ccsession.create_answer(0)
  395. def handle_msg(self, msg):
  396. """Handle a command from the cc channel to the configuration manager"""
  397. answer = {}
  398. cmd, arg = ccsession.parse_command(msg)
  399. if cmd:
  400. if cmd == ccsession.COMMAND_GET_COMMANDS_SPEC:
  401. answer = ccsession.create_answer(0, self.get_commands_spec())
  402. elif cmd == ccsession.COMMAND_GET_MODULE_SPEC:
  403. answer = self._handle_get_module_spec(arg)
  404. elif cmd == ccsession.COMMAND_GET_CONFIG:
  405. answer = self._handle_get_config(arg)
  406. elif cmd == ccsession.COMMAND_SET_CONFIG:
  407. answer = self._handle_set_config(arg)
  408. elif cmd == ccsession.COMMAND_SHUTDOWN:
  409. # TODO: logging
  410. #print("[b10-cfgmgr] Received shutdown command")
  411. self.running = False
  412. answer = ccsession.create_answer(0)
  413. elif cmd == ccsession.COMMAND_MODULE_SPEC:
  414. try:
  415. answer = self._handle_module_spec(isc.config.ModuleSpec(arg))
  416. except isc.config.ModuleSpecError as dde:
  417. answer = ccsession.create_answer(1, "Error in data definition: " + str(dde))
  418. else:
  419. answer = ccsession.create_answer(1, "Unknown command: " + str(cmd))
  420. else:
  421. answer = ccsession.create_answer(1, "Unknown message format: " + str(msg))
  422. return answer
  423. def run(self):
  424. """Runs the configuration manager."""
  425. self.running = True
  426. while (self.running):
  427. # we just wait eternally for any command here, so disable
  428. # timeouts for this specific recv
  429. self.cc.set_timeout(0)
  430. msg, env = self.cc.group_recvmsg(False)
  431. # and set it back to whatever we default to
  432. self.cc.set_timeout(isc.cc.Session.MSGQ_DEFAULT_TIMEOUT)
  433. # ignore 'None' value (even though they should not occur)
  434. # and messages that are answers to questions we did
  435. # not ask
  436. if msg is not None and not 'result' in msg:
  437. answer = self.handle_msg(msg);
  438. self.cc.group_reply(env, answer)