component.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. # Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  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. import isc.bind10.sockcreator
  16. from isc.log_messages.bind10_messages import *
  17. import time
  18. from bind10_config import LIBEXECDIR
  19. import os
  20. logger = isc.log.Logger("boss")
  21. """
  22. Module for managing components (abstraction of process). It allows starting
  23. them in given order, handling when they crash (what happens depends on kind
  24. of component) and shutting down. It also handles the configuration of this.
  25. Dependencies between them are not yet handled. It might turn out they are
  26. needed, in that case they will be added sometime in future.
  27. """
  28. class Component:
  29. """
  30. This represents a single component. It has some defaults of behaviour,
  31. which should be reasonable for majority of ordinary components, but
  32. it might be inherited and modified for special-purpose components,
  33. like the core modules with different ways of starting up.
  34. """
  35. def __init__(self, process, boss, kind, address=None, params=None):
  36. """
  37. Creates the component in not running mode.
  38. The parameters are:
  39. - `process` is the name of the process to start.
  40. - `boss` the boss object to plug into. The component needs to plug
  41. into it to know when it failed, etc.
  42. - `kind` is the kind of component. It may be one of:
  43. * 'core' means the system can't run without it and it can't be
  44. safely restarted. If it does not start, the system is brought
  45. down. If it crashes, the system is turned off as well (with
  46. non-zero exit status).
  47. * 'needed' means the system is able to restart the component,
  48. but it is vital part of the service (like auth server). If
  49. it fails to start or crashes in less than 10s after the first
  50. startup, the system is brought down. If it crashes later on,
  51. it is restarted.
  52. * 'dispensable' means the component should be running, but if it
  53. doesn't start or crashes for some reason, the system simply tries
  54. to restart it and keeps running.
  55. """
  56. if kind not in ['core', 'needed', 'dispensable']:
  57. raise ValueError('Component kind can not be ' + kind)
  58. self.__running = False
  59. # Dead like really dead. No resurrection possible.
  60. self.__dead = False
  61. self.__kind = kind
  62. self._boss = boss
  63. self._process = process
  64. self._start_func = None
  65. self._address = address
  66. self._params = params
  67. def start(self):
  68. """
  69. Start the component for the first time or restart it. If you need to
  70. modify the way a component is started, do not replace this method,
  71. but start_internal. This one does some more bookkeeping around.
  72. If you try to start an already running component, it raises ValueError.
  73. """
  74. if self.__dead:
  75. raise ValueError("Can't resurrect already dead component")
  76. if self.running():
  77. raise ValueError("Can't start already running component")
  78. self.__running = True
  79. self.__start_time = time.time()
  80. try:
  81. self.start_internal()
  82. except:
  83. self.failed()
  84. raise
  85. def start_internal(self):
  86. """
  87. This method does the actual starting of a process. If you need to
  88. change the way the component is started, replace this method.
  89. """
  90. if self._start_func is not None:
  91. procinfo = self._start_func()
  92. else:
  93. # TODO Handle params, etc
  94. procinfo = self._boss.start_simple(self._process)
  95. self._procinfo = procinfo
  96. self._boss.register_process(procinfo.pid, self)
  97. def stop(self):
  98. """
  99. Stop the component. If you need to modify the way a component is
  100. stopped, do not replace this method, but stop_internal. This one
  101. does some more bookkeeping.
  102. If you try to stop a component that is not running, it raises
  103. ValueError.
  104. """
  105. if not self.running():
  106. raise ValueError("Can't stop a component which is not running")
  107. self.stop_internal()
  108. self.__running = False
  109. def stop_internal(self):
  110. """
  111. This is the method that does the actual stopping of a component.
  112. You can replace this method if you want a different way to do it.
  113. """
  114. self._boss.stop_process(self._process, self._address)
  115. def failed(self):
  116. """
  117. Notify the component it crashed. This will be called from boss object.
  118. If you try to call failed on a component that is not running,
  119. a ValueError is raised.
  120. """
  121. if not self.running():
  122. raise ValueError("Can't fail component that isn't running")
  123. self.failed_internal()
  124. self.__running = False
  125. # If it is a core component or the needed component failed to start
  126. # (including it stopped really soon)
  127. if self.__kind == 'core' or \
  128. (self.__kind == 'needed' and time.time() - 10 < self.__start_time):
  129. self.__dead = True
  130. self._boss.shutdown(1)
  131. # This means we want to restart
  132. else:
  133. self.start()
  134. def failed_internal(self):
  135. """
  136. This method is called from failed. You can replace it if you need
  137. some specific behaviour when the component crashes. The default
  138. implementation is empty.
  139. Do not raise exceptions from here, please. The propper shutdown
  140. would have not happened.
  141. """
  142. pass
  143. def running(self):
  144. """
  145. Informs if the component is currently running. It assumes the failed
  146. is called whenever the component really fails and there might be some
  147. time in between actual failure and the call.
  148. """
  149. return self.__running
  150. class SockCreator(Component):
  151. def start_internal(self):
  152. self._boss.curproc = 'b10-sockcreator'
  153. self.__creator = isc.bind10.sockcreator.Creator(LIBEXECDIR + ':' +
  154. os.environ['PATH'])
  155. self._boss.register_process(self.__creator.pid(), self)
  156. def stop_internal(self, kill=False):
  157. if self.__creator is None:
  158. return
  159. if kill:
  160. self.__creator.kill()
  161. else:
  162. self.sockcreator.terminate()
  163. self.__creator = None
  164. class Msgq(Component):
  165. def __init__(self, process, boss, kind, address, params):
  166. Component.__init__(self, process, boss, kind)
  167. self._start_func = boss.start_msgq
  168. def stop_internal(self):
  169. pass # Wait for the boss to actually kill it. There's no stop command.
  170. class CfgMgr(Component):
  171. def __init__(self, process, boss, kind, address, params):
  172. Component.__init__(self, process, boss, kind)
  173. self._start_func = boss.start_cfgmgr
  174. self._address = 'ConfigManager'
  175. class Auth(Component):
  176. def __init__(self, process, boss, kind, address, params):
  177. Component.__init__(self, process, boss, kind)
  178. self._start_func = boss.start_auth
  179. self._address = 'Auth'
  180. class Resolver(Component):
  181. def __init__(self, process, boss, kind, address, params):
  182. Component.__init__(self, process, boss, kind)
  183. self._start_func = boss.start_resolver
  184. self._address = 'Resolver'
  185. class CmdCtl(Component):
  186. def __init__(self, process, boss, kind, address, params):
  187. Component.__init__(self, process, boss, kind)
  188. self._start_func = boss.start_cmdctl
  189. self._address = 'Cmdctl'
  190. specials = {
  191. 'sockcreator': SockCreator,
  192. 'msgq': Msgq,
  193. 'cfgmgr': CfgMgr,
  194. # TODO: Should these be replaced by configuration in config manager only?
  195. # They should not have any parameters anyway
  196. 'auth': Auth,
  197. 'resolver': Resolver,
  198. 'cmdctl': CmdCtl
  199. }
  200. """
  201. List of specially started components. Each one should be the class than can
  202. be created for that component.
  203. """
  204. class Configurator:
  205. """
  206. This thing keeps track of configuration changes and starts and stops
  207. components as it goes. It also handles the inital startup and final
  208. shutdown.
  209. Note that this will allow you to stop (by invoking reconfigure) a core
  210. component. There should be some kind of layer protecting users from ever
  211. doing so (users must not stop the config manager, message queue and stuff
  212. like that or the system won't start again).
  213. """
  214. def __init__(self, boss):
  215. """
  216. Initializes the configurator, but nothing is started yet.
  217. The boss parameter is the boss object used to start and stop processes.
  218. """
  219. self.__boss = boss
  220. # These could be __private, but as we access them from within unittest,
  221. # it's more comfortable to have them just _protected.
  222. self._components = {}
  223. self._old_config = {}
  224. self._running = False
  225. def __reconfigure_internal(self, old, new):
  226. """
  227. Does a switch from one configuration to another.
  228. """
  229. self._run_plan(self._build_plan(old, new))
  230. self._old_config = new
  231. def startup(self, configuration):
  232. """
  233. Starts the first set of processes. This configuration is expected
  234. to be hardcoded from the boss itself to start the configuration
  235. manager and other similar things.
  236. """
  237. if self._running:
  238. raise ValueError("Trying to start the component configurator " +
  239. "twice")
  240. self.__reconfigure_internal({}, configuration)
  241. self._running = True
  242. def shutdown(self):
  243. """
  244. Shuts everything down.
  245. """
  246. if not self._running:
  247. raise ValueError("Trying to shutdown the component " +
  248. "configurator while it's not yet running")
  249. self.__reconfigure_internal(self._old_config, {})
  250. self._running = False
  251. def reconfigure(self, configuration):
  252. """
  253. Changes configuration from the current one to the provided. It
  254. starts and stops all the components as needed.
  255. """
  256. if not self._running:
  257. raise ValueError("Trying to reconfigure the component " +
  258. "configurator while it's not yet running")
  259. self.__reconfigure_internal(self._old_config, configuration)
  260. def _build_plan(self, old, new):
  261. """
  262. Builds a plan how to transfer from the old configuration to the new
  263. one. It'll be sorted by priority and it will contain the components
  264. (already created, but not started). Each command in the plan is a dict,
  265. so it can be extended any time in future to include whatever
  266. parameters each operation might need.
  267. Any configuration problems are expected to be handled here, so the
  268. plan is not yet run.
  269. """
  270. plan = []
  271. # Handle removals of old components
  272. for cname in old.keys():
  273. if cname not in new:
  274. component = self._components[cname]
  275. if component.running():
  276. plan.append({
  277. 'command': 'stop',
  278. 'component': component,
  279. 'name': cname
  280. })
  281. # Handle transitions of configuration of what is here
  282. for cname in new.keys():
  283. if cname in old:
  284. for option in ['special', 'process', 'kind']:
  285. if new[cname].get(option) != old[cname].get(option):
  286. raise NotImplementedError('Changing configuration of' +
  287. ' a running component is ' +
  288. 'not yet supported. Remove' +
  289. ' and re-add ' + cname +
  290. 'to get the same effect')
  291. # Handle introduction of new components
  292. plan_add = []
  293. for cname in new.keys():
  294. if cname not in old:
  295. params = new[cname]
  296. creator = Component
  297. if 'special' in params:
  298. # TODO: Better error handling
  299. creator = specials[params['special']]
  300. component = creator(params.get('process', cname), self.__boss,
  301. params['kind'], params.get('address'),
  302. params.get('params'))
  303. priority = params.get('priority', 0)
  304. # We store tuples, priority first, so we can easily sort
  305. plan_add.append((priority, {
  306. 'component': component,
  307. 'command': 'start',
  308. 'name': cname,
  309. }))
  310. # Push the starts there sorted by priority
  311. plan.extend([command for (_, command) in sorted(plan_add,
  312. reverse=True)])
  313. return plan
  314. def running(self):
  315. return self._running
  316. def _run_plan(self, plan):
  317. """
  318. Run a plan, created beforehead by _build_plan.
  319. With the start and stop commands, it also adds and removes components
  320. in _components.
  321. Currently implemented commands are:
  322. * start
  323. * stop
  324. """
  325. for task in plan:
  326. component = task['component']
  327. command = task['command']
  328. if command == 'start':
  329. component.start()
  330. self._components[task['name']] = component
  331. elif command == 'stop':
  332. if component.running():
  333. component.stop()
  334. del self._components[task['name']]
  335. else:
  336. # Can Not Happen (as the plans are generated by ourself).
  337. # Therefore not tested.
  338. raise NotImplementedError("Command unknown: " + command)