ccsession.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 UICCSession classes,
  24. as well as a set of utility functions to create and parse messages
  25. 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 UICCSession to connect
  30. to b10-cmdctl, and receive and send configuration and commands
  31. 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):
  154. """Check whether there is a command or configuration update
  155. on the channel. Call the corresponding callback function if
  156. there is."""
  157. msg, env = self._session.group_recvmsg(False)
  158. # should we default to an answer? success-by-default? unhandled error?
  159. if msg and not 'result' in msg:
  160. answer = None
  161. try:
  162. module_name = env['group']
  163. cmd, arg = isc.config.ccsession.parse_command(msg)
  164. if cmd == COMMAND_CONFIG_UPDATE:
  165. new_config = arg
  166. # If the target channel was not this module
  167. # it might be in the remote_module_configs
  168. if module_name != self._module_name:
  169. if module_name in self._remote_module_configs:
  170. # no checking for validity, that's up to the
  171. # module itself.
  172. newc = self._remote_module_configs[module_name].get_local_config()
  173. isc.cc.data.merge(newc, new_config)
  174. self._remote_module_configs[module_name].set_local_config(newc)
  175. return
  176. # ok, so apparently this update is for us.
  177. errors = []
  178. if not self._config_handler:
  179. answer = create_answer(2, self._module_name + " has no config handler")
  180. elif not self.get_module_spec().validate_config(False, new_config, errors):
  181. answer = create_answer(1, " ".join(errors))
  182. else:
  183. isc.cc.data.remove_identical(new_config, self.get_local_config())
  184. answer = self._config_handler(new_config)
  185. rcode, val = parse_answer(answer)
  186. if rcode == 0:
  187. newc = self.get_local_config()
  188. isc.cc.data.merge(newc, new_config)
  189. self.set_local_config(newc)
  190. else:
  191. # ignore commands for 'remote' modules
  192. if module_name == self._module_name:
  193. if self._command_handler:
  194. answer = self._command_handler(cmd, arg)
  195. else:
  196. answer = create_answer(2, self._module_name + " has no command handler")
  197. except Exception as exc:
  198. answer = create_answer(1, str(exc))
  199. if answer:
  200. self._session.group_reply(env, answer)
  201. def set_config_handler(self, config_handler):
  202. """Set the config handler for this module. The handler is a
  203. function that takes the full configuration and handles it.
  204. It should return an answer created with create_answer()"""
  205. self._config_handler = config_handler
  206. # should we run this right now since we've changed the handler?
  207. def set_command_handler(self, command_handler):
  208. """Set the command handler for this module. The handler is a
  209. function that takes a command as defined in the .spec file
  210. and return an answer created with create_answer()"""
  211. self._command_handler = command_handler
  212. def add_remote_config(self, spec_file_name):
  213. """Gives access to the configuration of a different module.
  214. These remote module options can at this moment only be
  215. accessed through get_remote_config_value(). This function
  216. also subscribes to the channel of the remote module name
  217. to receive the relevant updates. It is not possible to
  218. specify your own handler for this right now.
  219. Returns the name of the module."""
  220. module_spec = isc.config.module_spec_from_file(spec_file_name)
  221. module_cfg = ConfigData(module_spec)
  222. module_name = module_spec.get_module_name()
  223. self._session.group_subscribe(module_name);
  224. # Get the current config for that module now
  225. seq = self._session.group_sendmsg(create_command(COMMAND_GET_CONFIG, { "module_name": module_name }), "ConfigManager")
  226. answer, env = self._session.group_recvmsg(False, seq)
  227. if answer:
  228. rcode, value = parse_answer(answer)
  229. if rcode == 0:
  230. if value != None and self.get_module_spec().validate_config(False, value):
  231. module_cfg.set_local_config(value);
  232. # all done, add it
  233. self._remote_module_configs[module_name] = module_cfg
  234. return module_name
  235. def remove_remote_config(self, module_name):
  236. """Removes the remote configuration access for this module"""
  237. if module_name in self._remote_module_configs:
  238. self._session.group_unsubscribe(module_name)
  239. del self._remote_module_configs[module_name]
  240. def get_remote_config_value(self, module_name, identifier):
  241. """Returns the current setting for the given identifier at the
  242. given module. If the module has not been added with
  243. add_remote_config, a ModuleCCSessionError is raised"""
  244. if module_name in self._remote_module_configs:
  245. return self._remote_module_configs[module_name].get_value(identifier)
  246. else:
  247. raise ModuleCCSessionError("Remote module " + module_name +
  248. " not found")
  249. def __send_spec(self):
  250. """Sends the data specification to the configuration manager"""
  251. msg = create_command(COMMAND_MODULE_SPEC, self.get_module_spec().get_full_spec())
  252. seq = self._session.group_sendmsg(msg, "ConfigManager")
  253. answer, env = self._session.group_recvmsg(False, seq)
  254. def __request_config(self):
  255. """Asks the configuration manager for the current configuration, and call the config handler if set.
  256. Raises a ModuleCCSessionError if there is no answer from the configuration manager"""
  257. seq = self._session.group_sendmsg(create_command(COMMAND_GET_CONFIG, { "module_name": self._module_name }), "ConfigManager")
  258. answer, env = self._session.group_recvmsg(False, seq)
  259. if answer:
  260. rcode, value = parse_answer(answer)
  261. if rcode == 0:
  262. if value != None and self.get_module_spec().validate_config(False, value):
  263. self.set_local_config(value);
  264. if self._config_handler:
  265. self._config_handler(value)
  266. else:
  267. # log error
  268. print("[" + self._module_name + "] Error requesting configuration: " + value)
  269. else:
  270. raise ModuleCCSessionError("No answer from configuration manager")
  271. class UIModuleCCSession(MultiConfigData):
  272. """This class is used in a configuration user interface. It contains
  273. specific functions for getting, displaying, and sending
  274. configuration settings through the b10-cmdctl module."""
  275. def __init__(self, conn):
  276. """Initialize a UIModuleCCSession. The conn object that is
  277. passed must have send_GET and send_POST functions"""
  278. MultiConfigData.__init__(self)
  279. self._conn = conn
  280. self.request_specifications()
  281. self.request_current_config()
  282. def request_specifications(self):
  283. """Request the module specifications from b10-cmdctl"""
  284. # this step should be unnecessary but is the current way cmdctl returns stuff
  285. # so changes are needed there to make this clean (we need a command to simply get the
  286. # full specs for everything, including commands etc, not separate gets for that)
  287. specs = self._conn.send_GET('/module_spec')
  288. for module in specs.keys():
  289. self.set_specification(isc.config.ModuleSpec(specs[module]))
  290. def update_specs_and_config(self):
  291. self.request_specifications();
  292. self.request_current_config();
  293. def request_current_config(self):
  294. """Requests the current configuration from the configuration
  295. manager through b10-cmdctl, and stores those as CURRENT"""
  296. config = self._conn.send_GET('/config_data')
  297. if 'version' not in config or config['version'] != BIND10_CONFIG_DATA_VERSION:
  298. raise ModuleCCSessionError("Bad config version")
  299. self._set_current_config(config)
  300. def add_value(self, identifier, value_str):
  301. """Add a value to a configuration list. Raises a DataTypeError
  302. if the value does not conform to the list_item_spec field
  303. of the module config data specification"""
  304. module_spec = self.find_spec_part(identifier)
  305. if (type(module_spec) != dict or "list_item_spec" not in module_spec):
  306. raise isc.cc.data.DataNotFoundError(str(identifier) + " is not a list")
  307. value = isc.cc.data.parse_value_str(value_str)
  308. cur_list, status = self.get_value(identifier)
  309. if not cur_list:
  310. cur_list = []
  311. if value not in cur_list:
  312. cur_list.append(value)
  313. self.set_value(identifier, cur_list)
  314. def remove_value(self, identifier, value_str):
  315. """Remove a value from a configuration list. The value string
  316. must be a string representation of the full item. Raises
  317. a DataTypeError if the value at the identifier is not a list,
  318. or if the given value_str does not match the list_item_spec
  319. """
  320. module_spec = self.find_spec_part(identifier)
  321. if (type(module_spec) != dict or "list_item_spec" not in module_spec):
  322. raise isc.cc.data.DataNotFoundError(str(identifier) + " is not a list")
  323. value = isc.cc.data.parse_value_str(value_str)
  324. isc.config.config_data.check_type(module_spec, [value])
  325. cur_list, status = self.get_value(identifier)
  326. #if not cur_list:
  327. # cur_list = isc.cc.data.find_no_exc(self.config.data, identifier)
  328. if not cur_list:
  329. cur_list = []
  330. if value in cur_list:
  331. cur_list.remove(value)
  332. self.set_value(identifier, cur_list)
  333. def commit(self):
  334. """Commit all local changes, send them through b10-cmdctl to
  335. the configuration manager"""
  336. if self.get_local_changes():
  337. self._conn.send_POST('/ConfigManager/set_config', [ self.get_local_changes() ])
  338. # todo: check result
  339. self.request_current_config()
  340. self.clear_local_changes()