ccsession.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. # Copyright (C) 2009 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. # Client-side functionality for configuration and commands
  17. #
  18. # It keeps a cc-channel session with the configuration manager daemon,
  19. # and handles configuration updates and direct commands
  20. # modeled after ccsession.h/cc 'protocol' changes here need to be
  21. # made there as well
  22. """Classes and functions for handling configuration and commands
  23. This module provides the ModuleCCSession and UIModuleCCSession
  24. classes, as well as a set of utility functions to create and parse
  25. messages related to commands and configuration
  26. Modules should use the ModuleCCSession class to connect to the
  27. configuration manager, and receive updates and commands from
  28. other modules.
  29. Configuration user interfaces should use the UIModuleCCSession
  30. to connect to b10-cmdctl, and receive and send configuration and
  31. commands through that to the configuration manager.
  32. """
  33. from isc.cc import Session
  34. from isc.config.config_data import ConfigData, MultiConfigData, BIND10_CONFIG_DATA_VERSION
  35. import isc
  36. class ModuleCCSessionError(Exception): pass
  37. def parse_answer(msg):
  38. """Returns a tuple (rcode, value), where value depends on the
  39. command that was called. If rcode != 0, value is a string
  40. containing an error message"""
  41. if type(msg) != dict:
  42. raise ModuleCCSessionError("Answer message is not a dict: " + str(msg))
  43. if 'result' not in msg:
  44. raise ModuleCCSessionError("answer message does not contain 'result' element")
  45. elif type(msg['result']) != list:
  46. raise ModuleCCSessionError("wrong result type in answer message")
  47. elif len(msg['result']) < 1:
  48. raise ModuleCCSessionError("empty result list in answer message")
  49. elif type(msg['result'][0]) != int:
  50. raise ModuleCCSessionError("wrong rcode type in answer message")
  51. else:
  52. if len(msg['result']) > 1:
  53. if (msg['result'][0] != 0 and type(msg['result'][1]) != str):
  54. raise ModuleCCSessionError("rcode in answer message is non-zero, value is not a string")
  55. return msg['result'][0], msg['result'][1]
  56. else:
  57. return msg['result'][0], None
  58. def create_answer(rcode, arg = None):
  59. """Creates an answer packet for config&commands. rcode must be an
  60. integer. If rcode == 0, arg is an optional value that depends
  61. on what the command or option was. If rcode != 0, arg must be
  62. a string containing an error message"""
  63. if type(rcode) != int:
  64. raise ModuleCCSessionError("rcode in create_answer() must be an integer")
  65. if rcode != 0 and type(arg) != str:
  66. raise ModuleCCSessionError("arg in create_answer for rcode != 0 must be a string describing the error")
  67. if arg != None:
  68. return { 'result': [ rcode, arg ] }
  69. else:
  70. return { 'result': [ rcode ] }
  71. # 'fixed' commands
  72. """Fixed names for command and configuration messages"""
  73. COMMAND_CONFIG_UPDATE = "config_update"
  74. COMMAND_MODULE_SPECIFICATION_UPDATE = "module_specification_update"
  75. COMMAND_GET_COMMANDS_SPEC = "get_commands_spec"
  76. COMMAND_GET_CONFIG = "get_config"
  77. COMMAND_SET_CONFIG = "set_config"
  78. COMMAND_GET_MODULE_SPEC = "get_module_spec"
  79. COMMAND_MODULE_SPEC = "module_spec"
  80. COMMAND_SHUTDOWN = "shutdown"
  81. def parse_command(msg):
  82. """Parses what may be a command message. If it looks like one,
  83. the function returns (command, value) where command is a
  84. string. If it is not, this function returns None, None"""
  85. if type(msg) == dict and len(msg.items()) == 1:
  86. cmd, value = msg.popitem()
  87. if cmd == "command" and type(value) == list:
  88. if len(value) == 1 and type(value[0]) == str:
  89. return value[0], None
  90. elif len(value) > 1 and type(value[0]) == str:
  91. return value[0], value[1]
  92. return None, None
  93. def create_command(command_name, params = None):
  94. """Creates a module command message with the given command name (as
  95. specified in the module's specification, and an optional params
  96. object"""
  97. # TODO: validate_command with spec
  98. if type(command_name) != str:
  99. raise ModuleCCSessionError("command in create_command() not a string")
  100. cmd = [ command_name ]
  101. if params:
  102. cmd.append(params)
  103. msg = { 'command': cmd }
  104. return msg
  105. class ModuleCCSession(ConfigData):
  106. """This class maintains a connection to the command channel, as
  107. well as configuration options for modules. The module provides
  108. a specification file that contains the module name, configuration
  109. options, and commands. It also gives the ModuleCCSession two callback
  110. functions, one to call when there is a direct command to the
  111. module, and one to update the configuration run-time. These
  112. callbacks are called when 'check_command' is called on the
  113. ModuleCCSession"""
  114. def __init__(self, spec_file_name, config_handler, command_handler, cc_session = None):
  115. """Initialize a ModuleCCSession. This does *NOT* send the
  116. specification and request the configuration yet. Use start()
  117. for that once the ModuleCCSession has been initialized.
  118. specfile_name is the path to the specification file
  119. config_handler and command_handler are callback functions,
  120. see set_config_handler and set_command_handler for more
  121. information on their signatures."""
  122. module_spec = isc.config.module_spec_from_file(spec_file_name)
  123. ConfigData.__init__(self, module_spec)
  124. self._module_name = module_spec.get_module_name()
  125. self.set_config_handler(config_handler)
  126. self.set_command_handler(command_handler)
  127. if not cc_session:
  128. self._session = Session()
  129. else:
  130. self._session = cc_session
  131. self._session.group_subscribe(self._module_name, "*")
  132. self._remote_module_configs = {}
  133. def __del__(self):
  134. self._session.group_unsubscribe(self._module_name, "*")
  135. for module_name in self._remote_module_configs:
  136. self._session.group_unsubscribe(module_name)
  137. def start(self):
  138. """Send the specification for this module to the configuration
  139. manager, and request the current non-default configuration.
  140. The config_handler will be called with that configuration"""
  141. self.__send_spec()
  142. self.__request_config()
  143. def get_socket(self):
  144. """Returns the socket from the command channel session. This
  145. should *only* be used for select() loops to see if there
  146. is anything on the channel. If that loop is not completely
  147. time-critical, it is strongly recommended to only use
  148. check_command(), and not look at the socket at all."""
  149. return self._session._socket
  150. def close(self):
  151. """Close the session to the command channel"""
  152. self._session.close()
  153. def check_command(self, nonblock=True):
  154. """Check whether there is a command or configuration update on
  155. the channel. This function does a read on the cc session, and
  156. returns nothing.
  157. It calls check_command_without_recvmsg()
  158. to parse the received message.
  159. If nonblock is True, it just checks if there's a command
  160. and does nothing if there isn't. If nonblock is False, it
  161. waits until it arrives. It temporarily sets timeout to infinity,
  162. because commands may not come in arbitrary long time."""
  163. timeout_orig = self._session.get_timeout()
  164. self._session.set_timeout(0)
  165. try:
  166. msg, env = self._session.group_recvmsg(nonblock)
  167. finally:
  168. self._session.set_timeout(timeout_orig)
  169. self.check_command_without_recvmsg(msg, env)
  170. def check_command_without_recvmsg(self, msg, env):
  171. """Parse the given message to see if there is a command or a
  172. configuration update. Calls the corresponding handler
  173. functions if present. Responds on the channel if the
  174. handler returns a message."""
  175. # should we default to an answer? success-by-default? unhandled error?
  176. if msg is not None and not 'result' in msg:
  177. answer = None
  178. try:
  179. module_name = env['group']
  180. cmd, arg = isc.config.ccsession.parse_command(msg)
  181. if cmd == COMMAND_CONFIG_UPDATE:
  182. new_config = arg
  183. # If the target channel was not this module
  184. # it might be in the remote_module_configs
  185. if module_name != self._module_name:
  186. if module_name in self._remote_module_configs:
  187. # no checking for validity, that's up to the
  188. # module itself.
  189. newc = self._remote_module_configs[module_name].get_local_config()
  190. isc.cc.data.merge(newc, new_config)
  191. self._remote_module_configs[module_name].set_local_config(newc)
  192. # For other modules, we're not supposed to answer
  193. return
  194. # ok, so apparently this update is for us.
  195. errors = []
  196. if not self._config_handler:
  197. answer = create_answer(2, self._module_name + " has no config handler")
  198. elif not self.get_module_spec().validate_config(False, new_config, errors):
  199. answer = create_answer(1, ", ".join(errors))
  200. else:
  201. isc.cc.data.remove_identical(new_config, self.get_local_config())
  202. answer = self._config_handler(new_config)
  203. rcode, val = parse_answer(answer)
  204. if rcode == 0:
  205. newc = self.get_local_config()
  206. isc.cc.data.merge(newc, new_config)
  207. self.set_local_config(newc)
  208. else:
  209. # ignore commands for 'remote' modules
  210. if module_name == self._module_name:
  211. if self._command_handler:
  212. answer = self._command_handler(cmd, arg)
  213. else:
  214. answer = create_answer(2, self._module_name + " has no command handler")
  215. except Exception as exc:
  216. answer = create_answer(1, str(exc))
  217. if answer:
  218. self._session.group_reply(env, answer)
  219. def set_config_handler(self, config_handler):
  220. """Set the config handler for this module. The handler is a
  221. function that takes the full configuration and handles it.
  222. It should return an answer created with create_answer()"""
  223. self._config_handler = config_handler
  224. # should we run this right now since we've changed the handler?
  225. def set_command_handler(self, command_handler):
  226. """Set the command handler for this module. The handler is a
  227. function that takes a command as defined in the .spec file
  228. and return an answer created with create_answer()"""
  229. self._command_handler = command_handler
  230. def add_remote_config(self, spec_file_name):
  231. """Gives access to the configuration of a different module.
  232. These remote module options can at this moment only be
  233. accessed through get_remote_config_value(). This function
  234. also subscribes to the channel of the remote module name
  235. to receive the relevant updates. It is not possible to
  236. specify your own handler for this right now.
  237. start() must have been called on this CCSession
  238. prior to the call to this method.
  239. Returns the name of the module."""
  240. module_spec = isc.config.module_spec_from_file(spec_file_name)
  241. module_cfg = ConfigData(module_spec)
  242. module_name = module_spec.get_module_name()
  243. self._session.group_subscribe(module_name);
  244. # Get the current config for that module now
  245. seq = self._session.group_sendmsg(create_command(COMMAND_GET_CONFIG, { "module_name": module_name }), "ConfigManager")
  246. try:
  247. answer, env = self._session.group_recvmsg(False, seq)
  248. except isc.cc.SessionTimeout:
  249. raise ModuleCCSessionError("No answer from ConfigManager when "
  250. "asking about Remote module " +
  251. module_name)
  252. if answer:
  253. rcode, value = parse_answer(answer)
  254. if rcode == 0:
  255. if value != None and module_spec.validate_config(False, value):
  256. module_cfg.set_local_config(value);
  257. # all done, add it
  258. self._remote_module_configs[module_name] = module_cfg
  259. return module_name
  260. def remove_remote_config(self, module_name):
  261. """Removes the remote configuration access for this module"""
  262. if module_name in self._remote_module_configs:
  263. self._session.group_unsubscribe(module_name)
  264. del self._remote_module_configs[module_name]
  265. def get_remote_config_value(self, module_name, identifier):
  266. """Returns the current setting for the given identifier at the
  267. given module. If the module has not been added with
  268. add_remote_config, a ModuleCCSessionError is raised"""
  269. if module_name in self._remote_module_configs:
  270. return self._remote_module_configs[module_name].get_value(identifier)
  271. else:
  272. raise ModuleCCSessionError("Remote module " + module_name +
  273. " not found")
  274. def __send_spec(self):
  275. """Sends the data specification to the configuration manager"""
  276. msg = create_command(COMMAND_MODULE_SPEC, self.get_module_spec().get_full_spec())
  277. seq = self._session.group_sendmsg(msg, "ConfigManager")
  278. try:
  279. answer, env = self._session.group_recvmsg(False, seq)
  280. except isc.cc.SessionTimeout:
  281. # TODO: log an error?
  282. pass
  283. def __request_config(self):
  284. """Asks the configuration manager for the current configuration, and call the config handler if set.
  285. Raises a ModuleCCSessionError if there is no answer from the configuration manager"""
  286. seq = self._session.group_sendmsg(create_command(COMMAND_GET_CONFIG, { "module_name": self._module_name }), "ConfigManager")
  287. try:
  288. answer, env = self._session.group_recvmsg(False, seq)
  289. if answer:
  290. rcode, value = parse_answer(answer)
  291. if rcode == 0:
  292. if value != None and self.get_module_spec().validate_config(False, value):
  293. self.set_local_config(value);
  294. if self._config_handler:
  295. self._config_handler(value)
  296. else:
  297. # log error
  298. print("[" + self._module_name + "] Error requesting configuration: " + value)
  299. else:
  300. raise ModuleCCSessionError("No answer from configuration manager")
  301. except isc.cc.SessionTimeout:
  302. raise ModuleCCSessionError("CC Session timeout waiting for configuration manager")
  303. class UIModuleCCSession(MultiConfigData):
  304. """This class is used in a configuration user interface. It contains
  305. specific functions for getting, displaying, and sending
  306. configuration settings through the b10-cmdctl module."""
  307. def __init__(self, conn):
  308. """Initialize a UIModuleCCSession. The conn object that is
  309. passed must have send_GET and send_POST functions"""
  310. MultiConfigData.__init__(self)
  311. self._conn = conn
  312. self.request_specifications()
  313. self.request_current_config()
  314. def request_specifications(self):
  315. """Request the module specifications from b10-cmdctl"""
  316. # this step should be unnecessary but is the current way cmdctl returns stuff
  317. # so changes are needed there to make this clean (we need a command to simply get the
  318. # full specs for everything, including commands etc, not separate gets for that)
  319. specs = self._conn.send_GET('/module_spec')
  320. for module in specs.keys():
  321. self.set_specification(isc.config.ModuleSpec(specs[module]))
  322. def update_specs_and_config(self):
  323. self.request_specifications();
  324. self.request_current_config();
  325. def request_current_config(self):
  326. """Requests the current configuration from the configuration
  327. manager through b10-cmdctl, and stores those as CURRENT"""
  328. config = self._conn.send_GET('/config_data')
  329. if 'version' not in config or config['version'] != BIND10_CONFIG_DATA_VERSION:
  330. raise ModuleCCSessionError("Bad config version")
  331. self._set_current_config(config)
  332. def add_value(self, identifier, value_str = None):
  333. """Add a value to a configuration list. Raises a DataTypeError
  334. if the value does not conform to the list_item_spec field
  335. of the module config data specification. If value_str is
  336. not given, we add the default as specified by the .spec
  337. file."""
  338. module_spec = self.find_spec_part(identifier)
  339. if (type(module_spec) != dict or "list_item_spec" not in module_spec):
  340. raise isc.cc.data.DataNotFoundError(str(identifier) + " is not a list")
  341. cur_list, status = self.get_value(identifier)
  342. if not cur_list:
  343. cur_list = []
  344. # Hmm. Do we need to check for duplicates?
  345. value = None
  346. if value_str is not None:
  347. value = isc.cc.data.parse_value_str(value_str)
  348. else:
  349. if "item_default" in module_spec["list_item_spec"]:
  350. value = module_spec["list_item_spec"]["item_default"]
  351. if value is None:
  352. raise isc.cc.data.DataNotFoundError("No value given and no default for " + str(identifier))
  353. if value not in cur_list:
  354. cur_list.append(value)
  355. self.set_value(identifier, cur_list)
  356. def remove_value(self, identifier, value_str):
  357. """Remove a value from a configuration list. The value string
  358. must be a string representation of the full item. Raises
  359. a DataTypeError if the value at the identifier is not a list,
  360. or if the given value_str does not match the list_item_spec
  361. """
  362. module_spec = self.find_spec_part(identifier)
  363. if (type(module_spec) != dict or "list_item_spec" not in module_spec):
  364. raise isc.cc.data.DataNotFoundError(str(identifier) + " is not a list")
  365. if value_str is None:
  366. # we are directly removing an list index
  367. id, list_indices = isc.cc.data.split_identifier_list_indices(identifier)
  368. if list_indices is None:
  369. raise DataTypeError("identifier in remove_value() does not contain a list index, and no value to remove")
  370. else:
  371. self.set_value(identifier, None)
  372. else:
  373. value = isc.cc.data.parse_value_str(value_str)
  374. isc.config.config_data.check_type(module_spec, [value])
  375. cur_list, status = self.get_value(identifier)
  376. #if not cur_list:
  377. # cur_list = isc.cc.data.find_no_exc(self.config.data, identifier)
  378. if not cur_list:
  379. cur_list = []
  380. if value in cur_list:
  381. cur_list.remove(value)
  382. self.set_value(identifier, cur_list)
  383. def commit(self):
  384. """Commit all local changes, send them through b10-cmdctl to
  385. the configuration manager"""
  386. if self.get_local_changes():
  387. response = self._conn.send_POST('/ConfigManager/set_config',
  388. [ self.get_local_changes() ])
  389. answer = isc.cc.data.parse_value_str(response.read().decode())
  390. # answer is either an empty dict (on success), or one
  391. # containing errors
  392. if answer == {}:
  393. self.request_current_config()
  394. self.clear_local_changes()
  395. elif "error" in answer:
  396. print("Error: " + answer["error"])
  397. print("Configuration not committed")
  398. else:
  399. raise ModuleCCSessionError("Unknown format of answer in commit(): " + str(answer))