component.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. - `address` is the address on message bus. It is used to ask it to
  56. shut down at the end. If you specialize the class for a component
  57. that is shut down differently, it might be None.
  58. - `params` is a list of parameters to pass to the process when it
  59. starts. It is currently unused and this support is left out for
  60. now.
  61. """
  62. if kind not in ['core', 'needed', 'dispensable']:
  63. raise ValueError('Component kind can not be ' + kind)
  64. self.__running = False
  65. # Dead like really dead. No resurrection possible.
  66. self.__dead = False
  67. self.__kind = kind
  68. self._boss = boss
  69. self._process = process
  70. self._start_func = None
  71. self._address = address
  72. self._params = params
  73. def start(self):
  74. """
  75. Start the component for the first time or restart it. If you need to
  76. modify the way a component is started, do not replace this method,
  77. but start_internal. This one does some more bookkeeping around.
  78. If you try to start an already running component, it raises ValueError.
  79. """
  80. if self.__dead:
  81. raise ValueError("Can't resurrect already dead component")
  82. if self.running():
  83. raise ValueError("Can't start already running component")
  84. self.__running = True
  85. self.__start_time = time.time()
  86. try:
  87. self.start_internal()
  88. except:
  89. self.failed()
  90. raise
  91. def start_internal(self):
  92. """
  93. This method does the actual starting of a process. If you need to
  94. change the way the component is started, replace this method.
  95. """
  96. # This one is not tested. For one, it starts a real process
  97. # which is out of scope of unit tests, for another, it just
  98. # delegates the starting to other function in boss (if a derived
  99. # class does not provide an override function), which is tested
  100. # by use.
  101. if self._start_func is not None:
  102. procinfo = self._start_func()
  103. else:
  104. # TODO Handle params, etc
  105. procinfo = self._boss.start_simple(self._process)
  106. self._procinfo = procinfo
  107. self._boss.register_process(self.pid(), self)
  108. def stop(self):
  109. """
  110. Stop the component. If you need to modify the way a component is
  111. stopped, do not replace this method, but stop_internal. This one
  112. does some more bookkeeping.
  113. If you try to stop a component that is not running, it raises
  114. ValueError.
  115. """
  116. # This is not tested. It talks with the outher world, which is out
  117. # of scope of unittests.
  118. if not self.running():
  119. raise ValueError("Can't stop a component which is not running")
  120. self.__running = False
  121. self.stop_internal()
  122. def stop_internal(self):
  123. """
  124. This is the method that does the actual stopping of a component.
  125. You can replace this method if you want a different way to do it.
  126. """
  127. self._boss.stop_process(self._process, self._address)
  128. def failed(self):
  129. """
  130. Notify the component it crashed. This will be called from boss object.
  131. If you try to call failed on a component that is not running,
  132. a ValueError is raised.
  133. """
  134. if not self.running():
  135. raise ValueError("Can't fail component that isn't running")
  136. self.failed_internal()
  137. self.__running = False
  138. self.failed_internal()
  139. # If it is a core component or the needed component failed to start
  140. # (including it stopped really soon)
  141. if self.__kind == 'core' or \
  142. (self.__kind == 'needed' and time.time() - 10 < self.__start_time):
  143. self.__dead = True
  144. self._boss.component_shutdown(1)
  145. # This means we want to restart
  146. else:
  147. self.start()
  148. def failed_internal(self):
  149. """
  150. This method is called from failed. You can replace it if you need
  151. some specific behaviour when the component crashes. The default
  152. implementation is empty.
  153. Do not raise exceptions from here, please. The propper shutdown
  154. would have not happened.
  155. """
  156. pass
  157. def running(self):
  158. """
  159. Informs if the component is currently running. It assumes the failed
  160. is called whenever the component really fails and there might be some
  161. time in between actual failure and the call.
  162. """
  163. return self.__running
  164. def name(self):
  165. """
  166. Returns human-readable name of the component. This is usually the
  167. name of the executable, but it might be something different in a
  168. derived class.
  169. """
  170. return self._process
  171. def pid(self):
  172. """
  173. Provides a PID of a process, if the component is real running process.
  174. This implementation expects it to be a real process, but derived class
  175. may return None in case the component is something else.
  176. """
  177. return self._procinfo.pid
  178. # These are specialized components. Some of them are components which need
  179. # special care (like the message queue or socket creator) or they need
  180. # some parameters constructed from Boss's command line. They are not tested
  181. # currently, because it is not clear what to test on them anyway and they just
  182. # delegate the work for the boss
  183. class SockCreator(Component):
  184. """
  185. The socket creator component. Will start and stop the socket creator
  186. accordingly.
  187. """
  188. def start_internal(self):
  189. self._boss.curproc = 'b10-sockcreator'
  190. self.__creator = isc.bind10.sockcreator.Creator(LIBEXECDIR + ':' +
  191. os.environ['PATH'])
  192. self._boss.register_process(self.pid(), self)
  193. def stop_internal(self):
  194. if self.__creator is None:
  195. return
  196. self.__creator.terminate()
  197. self.__creator = None
  198. def pid(self):
  199. """
  200. Pid of the socket creator. It is provided differently from a usual
  201. component.
  202. """
  203. return self.__creator.pid()
  204. class Msgq(Component):
  205. <<<<<<< HEAD
  206. """
  207. The message queue. Starting is passed to boss, stopping is not supported
  208. and we leave the boss kill it by signal.
  209. """
  210. def __init__(self, process, boss, kind, address, params):
  211. Component.__init__(self, process, boss, kind)
  212. self._start_func = boss.start_msgq
  213. def stop_internal(self):
  214. pass # Wait for the boss to actually kill it. There's no stop command.
  215. class CfgMgr(Component):
  216. def __init__(self, process, boss, kind, address, params):
  217. Component.__init__(self, process, boss, kind)
  218. self._start_func = boss.start_cfgmgr
  219. self._address = 'ConfigManager'
  220. class Auth(Component):
  221. def __init__(self, process, boss, kind, address, params):
  222. Component.__init__(self, process, boss, kind)
  223. self._start_func = boss.start_auth
  224. self._address = 'Auth'
  225. class Resolver(Component):
  226. def __init__(self, process, boss, kind, address, params):
  227. Component.__init__(self, process, boss, kind)
  228. self._start_func = boss.start_resolver
  229. self._address = 'Resolver'
  230. class CmdCtl(Component):
  231. def __init__(self, process, boss, kind, address, params):
  232. Component.__init__(self, process, boss, kind)
  233. self._start_func = boss.start_cmdctl
  234. self._address = 'Cmdctl'
  235. specials = {
  236. 'sockcreator': SockCreator,
  237. 'msgq': Msgq,
  238. 'cfgmgr': CfgMgr,
  239. # TODO: Should these be replaced by configuration in config manager only?
  240. # They should not have any parameters anyway
  241. 'auth': Auth,
  242. 'resolver': Resolver,
  243. 'cmdctl': CmdCtl
  244. }
  245. """
  246. List of specially started components. Each one should be the class than can
  247. be created for that component.
  248. """
  249. class Configurator:
  250. """
  251. This thing keeps track of configuration changes and starts and stops
  252. components as it goes. It also handles the inital startup and final
  253. shutdown.
  254. Note that this will allow you to stop (by invoking reconfigure) a core
  255. component. There should be some kind of layer protecting users from ever
  256. doing so (users must not stop the config manager, message queue and stuff
  257. like that or the system won't start again).
  258. """
  259. def __init__(self, boss):
  260. """
  261. Initializes the configurator, but nothing is started yet.
  262. The boss parameter is the boss object used to start and stop processes.
  263. """
  264. self.__boss = boss
  265. # These could be __private, but as we access them from within unittest,
  266. # it's more comfortable to have them just _protected.
  267. self._components = {}
  268. self._old_config = {}
  269. self._running = False
  270. def __reconfigure_internal(self, old, new):
  271. """
  272. Does a switch from one configuration to another.
  273. """
  274. self._run_plan(self._build_plan(old, new))
  275. self._old_config = new
  276. def startup(self, configuration):
  277. """
  278. Starts the first set of processes. This configuration is expected
  279. to be hardcoded from the boss itself to start the configuration
  280. manager and other similar things.
  281. """
  282. if self._running:
  283. raise ValueError("Trying to start the component configurator " +
  284. "twice")
  285. self.__reconfigure_internal({}, configuration)
  286. self._running = True
  287. def shutdown(self):
  288. """
  289. Shuts everything down.
  290. """
  291. if not self._running:
  292. raise ValueError("Trying to shutdown the component " +
  293. "configurator while it's not yet running")
  294. self.__reconfigure_internal(self._old_config, {})
  295. self._running = False
  296. def reconfigure(self, configuration):
  297. """
  298. Changes configuration from the current one to the provided. It
  299. starts and stops all the components as needed.
  300. """
  301. if not self._running:
  302. raise ValueError("Trying to reconfigure the component " +
  303. "configurator while it's not yet running")
  304. self.__reconfigure_internal(self._old_config, configuration)
  305. def _build_plan(self, old, new):
  306. """
  307. Builds a plan how to transfer from the old configuration to the new
  308. one. It'll be sorted by priority and it will contain the components
  309. (already created, but not started). Each command in the plan is a dict,
  310. so it can be extended any time in future to include whatever
  311. parameters each operation might need.
  312. Any configuration problems are expected to be handled here, so the
  313. plan is not yet run.
  314. """
  315. plan = []
  316. # Handle removals of old components
  317. for cname in old.keys():
  318. if cname not in new:
  319. component = self._components[cname]
  320. if component.running():
  321. plan.append({
  322. 'command': 'stop',
  323. 'component': component,
  324. 'name': cname
  325. })
  326. # Handle transitions of configuration of what is here
  327. for cname in new.keys():
  328. if cname in old:
  329. for option in ['special', 'process', 'kind']:
  330. if new[cname].get(option) != old[cname].get(option):
  331. raise NotImplementedError('Changing configuration of' +
  332. ' a running component is ' +
  333. 'not yet supported. Remove' +
  334. ' and re-add ' + cname +
  335. 'to get the same effect')
  336. # Handle introduction of new components
  337. plan_add = []
  338. for cname in new.keys():
  339. if cname not in old:
  340. params = new[cname]
  341. creator = Component
  342. if 'special' in params:
  343. # TODO: Better error handling
  344. creator = specials[params['special']]
  345. component = creator(params.get('process', cname), self.__boss,
  346. params['kind'], params.get('address'),
  347. params.get('params'))
  348. priority = params.get('priority', 0)
  349. # We store tuples, priority first, so we can easily sort
  350. plan_add.append((priority, {
  351. 'component': component,
  352. 'command': 'start',
  353. 'name': cname,
  354. }))
  355. # Push the starts there sorted by priority
  356. plan.extend([command for (_, command) in sorted(plan_add,
  357. reverse=True)])
  358. return plan
  359. def running(self):
  360. return self._running
  361. def _run_plan(self, plan):
  362. """
  363. Run a plan, created beforehead by _build_plan.
  364. With the start and stop commands, it also adds and removes components
  365. in _components.
  366. Currently implemented commands are:
  367. * start
  368. * stop
  369. """
  370. for task in plan:
  371. component = task['component']
  372. command = task['command']
  373. if command == 'start':
  374. component.start()
  375. self._components[task['name']] = component
  376. elif command == 'stop':
  377. if component.running():
  378. component.stop()
  379. del self._components[task['name']]
  380. else:
  381. # Can Not Happen (as the plans are generated by ourself).
  382. # Therefore not tested.
  383. raise NotImplementedError("Command unknown: " + command)