component.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. """
  16. Module for managing components (abstraction of process). It allows starting
  17. them in given order, handling when they crash (what happens depends on kind
  18. of component) and shutting down. It also handles the configuration of this.
  19. Dependencies between them are not yet handled. It might turn out they are
  20. needed, in that case they will be added sometime in future.
  21. """
  22. import isc.log
  23. from isc.log_messages.bind10_messages import *
  24. import time
  25. logger = isc.log.Logger("boss")
  26. DBG_TRACE_DATA = 20
  27. DBG_TRACE_DETAILED = 80
  28. START_CMD = 'start'
  29. STOP_CMD = 'stop'
  30. STARTED_OK_TIME = 10
  31. STATE_DEAD = 'dead'
  32. STATE_STOPPED = 'stopped'
  33. STATE_RUNNING = 'running'
  34. class Component:
  35. """
  36. This represents a single component. It has some defaults of behaviour,
  37. which should be reasonable for majority of ordinary components, but
  38. it might be inherited and modified for special-purpose components,
  39. like the core modules with different ways of starting up. Another
  40. way to tweak only the start of the component (eg. by providing some
  41. command line parameters) is to set _start_func function from within
  42. inherited class.
  43. The methods are marked if it is expected for them to be overridden.
  44. The component is in one of the three states:
  45. - Stopped - it is either not started yet or it was explicitly stopped.
  46. The component is created in this state (it must be asked to start
  47. explicitly).
  48. - Running - after start() was called, it started successfully and is
  49. now running.
  50. - Dead - it failed and can not be resurrected.
  51. Init
  52. | stop()
  53. | +-----------------------+
  54. | | |
  55. v | start() success |
  56. Stopped --------+--------> Running <----------+
  57. | | |
  58. |failure | failed() |
  59. | | |
  60. v | |
  61. +<-----------+ |
  62. | |
  63. | kind == dispensable or kind|== needed and failed late
  64. +-----------------------------+
  65. |
  66. | kind == core or kind == needed and it failed too soon
  67. v
  68. Dead
  69. """
  70. def __init__(self, process, boss, kind, address=None, params=None):
  71. """
  72. Creates the component in not running mode.
  73. The parameters are:
  74. - `process` is the name of the process to start.
  75. - `boss` the boss object to plug into. The component needs to plug
  76. into it to know when it failed, etc.
  77. - `kind` is the kind of component. It may be one of:
  78. * 'core' means the system can't run without it and it can't be
  79. safely restarted. If it does not start, the system is brought
  80. down. If it crashes, the system is turned off as well (with
  81. non-zero exit status).
  82. * 'needed' means the system is able to restart the component,
  83. but it is vital part of the service (like auth server). If
  84. it fails to start or crashes in less than 10s after the first
  85. startup, the system is brought down. If it crashes later on,
  86. it is restarted.
  87. * 'dispensable' means the component should be running, but if it
  88. doesn't start or crashes for some reason, the system simply tries
  89. to restart it and keeps running.
  90. - `address` is the address on message bus. It is used to ask it to
  91. shut down at the end. If you specialize the class for a component
  92. that is shut down differently, it might be None.
  93. - `params` is a list of parameters to pass to the process when it
  94. starts. It is currently unused and this support is left out for
  95. now.
  96. """
  97. if kind not in ['core', 'needed', 'dispensable']:
  98. raise ValueError('Component kind can not be ' + kind)
  99. self.__state = STATE_STOPPED
  100. self._kind = kind
  101. self._boss = boss
  102. self._process = process
  103. self._start_func = None
  104. self._address = address
  105. self._params = params
  106. self._procinfo = None
  107. def start(self):
  108. """
  109. Start the component for the first time or restart it. If you need to
  110. modify the way a component is started, do not replace this method,
  111. but _start_internal. This one does some more bookkeeping around.
  112. If you try to start an already running component, it raises ValueError.
  113. """
  114. if self.__state == STATE_DEAD:
  115. raise ValueError("Can't resurrect already dead component")
  116. if self.running():
  117. raise ValueError("Can't start already running component")
  118. logger.info(BIND10_COMPONENT_START, self.name())
  119. self.__state = STATE_RUNNING
  120. self.__start_time = time.time()
  121. try:
  122. self._start_internal()
  123. except Exception as e:
  124. logger.error(BIND10_COMPONENT_START_EXCEPTION, self.name(), e)
  125. self.failed()
  126. raise
  127. def _start_internal(self):
  128. """
  129. This method does the actual starting of a process. If you need to
  130. change the way the component is started, replace this method.
  131. You can change the "core" of this function by setting self._start_func
  132. to a function without parameters. Such function should start the
  133. process and return the procinfo object describing the running process.
  134. If you don't provide the _start_func, the usual startup by calling
  135. boss.start_simple is performed.
  136. If you override the method completely, you should consider overriding
  137. pid and _stop_internal (and possibly _failed_internal and name) as well.
  138. You should also register any processes started within boss.
  139. """
  140. # This one is not tested. For one, it starts a real process
  141. # which is out of scope of unit tests, for another, it just
  142. # delegates the starting to other function in boss (if a derived
  143. # class does not provide an override function), which is tested
  144. # by use.
  145. if self._start_func is not None:
  146. procinfo = self._start_func()
  147. else:
  148. # TODO Handle params, etc
  149. procinfo = self._boss.start_simple(self._process)
  150. self._procinfo = procinfo
  151. self._boss.register_process(self.pid(), self)
  152. def stop(self):
  153. """
  154. Stop the component. If you need to modify the way a component is
  155. stopped, do not replace this method, but _stop_internal. This one
  156. does some more bookkeeping.
  157. If you try to stop a component that is not running, it raises
  158. ValueError.
  159. """
  160. # This is not tested. It talks with the outher world, which is out
  161. # of scope of unittests.
  162. if not self.running():
  163. raise ValueError("Can't stop a component which is not running")
  164. logger.info(BIND10_COMPONENT_STOP, self.name())
  165. self.__state = STATE_STOPPED
  166. self._stop_internal()
  167. def _stop_internal(self):
  168. """
  169. This is the method that does the actual stopping of a component.
  170. You can replace this method if you want a different way to do it.
  171. If you're overriding this one, you probably want to replace the
  172. _start_internal and pid methods (and maybe _failed_internal and
  173. name as well).
  174. """
  175. self._boss.stop_process(self._process, self._address)
  176. def failed(self):
  177. """
  178. Notify the component it crashed. This will be called from boss object.
  179. If you try to call failed on a component that is not running,
  180. a ValueError is raised.
  181. If it is a core component or needed component and it was started only
  182. recently, the component will become dead and will ask the boss to shut
  183. down with error exit status. A dead component can't be started again.
  184. Otherwise the component will try to restart.
  185. """
  186. if not self.running():
  187. raise ValueError("Can't fail component that isn't running")
  188. self.__state = STATE_STOPPED
  189. self._failed_internal()
  190. # If it is a core component or the needed component failed to start
  191. # (including it stopped really soon)
  192. if self._kind == 'core' or \
  193. (self._kind == 'needed' and time.time() - STARTED_OK_TIME <
  194. self.__start_time):
  195. self.__state = STATE_DEAD
  196. logger.fatal(BIND10_COMPONENT_UNSATISFIED, self.name())
  197. self._boss.component_shutdown(1)
  198. # This means we want to restart
  199. else:
  200. logger.warn(BIND10_COMPONENT_RESTART, self.name())
  201. self.start()
  202. def _failed_internal(self):
  203. """
  204. This method is called from failed. You can replace it if you need
  205. some specific behaviour when the component crashes. The default
  206. implementation is empty.
  207. Do not raise exceptions from here, please. The propper shutdown
  208. would have not happened.
  209. """
  210. pass
  211. def running(self):
  212. """
  213. Informs if the component is currently running. It assumes the failed
  214. is called whenever the component really fails and there might be some
  215. time in between actual failure and the call.
  216. It is not expected for this method to be overriden.
  217. """
  218. return self.__state == STATE_RUNNING
  219. def name(self):
  220. """
  221. Returns human-readable name of the component. This is usually the
  222. name of the executable, but it might be something different in a
  223. derived class (in case it is overriden).
  224. """
  225. return self._process
  226. def pid(self):
  227. """
  228. Provides a PID of a process, if the component is real running process.
  229. This implementation expects it to be a real process, but derived class
  230. may return None in case the component is something else.
  231. This returns None in case it is not yet running.
  232. You probably want to override this method if you're providing custom
  233. _start_internal.
  234. """
  235. return self._procinfo.pid if self._procinfo else None
  236. class Configurator:
  237. """
  238. This thing keeps track of configuration changes and starts and stops
  239. components as it goes. It also handles the inital startup and final
  240. shutdown.
  241. Note that this will allow you to stop (by invoking reconfigure) a core
  242. component. There should be some kind of layer protecting users from ever
  243. doing so (users must not stop the config manager, message queue and stuff
  244. like that or the system won't start again).
  245. The parameters are:
  246. * `boss`: The boss we are managing for.
  247. * `specials`: Dict of specially started components. Each item is a class
  248. representing the component.
  249. The configuration passed to it (by startup() and reconfigure()) is a
  250. dictionary, each item represents one component that should be running.
  251. The key is an unique identifier used to reference the component. The
  252. value is a dictionary describing the component. All items in the
  253. description is optional and they are as follows:
  254. * `special` - Some components are started in a special way. If it is
  255. present, it specifies which class from the specials parameter should
  256. be used to create the component. In that case, some of the following
  257. items might be irrelevant, depending on the special component choosen.
  258. If it is not there, the basic Component class is used.
  259. * `process` - Name of the executable to start. If it is not present,
  260. it defaults to the identifier of the component.
  261. * `kind` - The kind of component, either of 'core', 'needed' and
  262. 'dispensable'. This specifies what happens if the component fails.
  263. Defaults to despensable.
  264. * `address` - The address of the component on message bus. It is used
  265. to shut down the component. All special components currently either
  266. know their own address or don't need one and ignore it. The common
  267. components should provide this.
  268. * `params` - The command line parameters of the executable. Defaults
  269. to no parameters. It is currently unused.
  270. * `priority` - When starting the component, the components with higher
  271. priority are started before the ones with lower priority. If it is
  272. not present, it defaults to 0.
  273. """
  274. def __init__(self, boss, specials = {}):
  275. """
  276. Initializes the configurator, but nothing is started yet.
  277. The boss parameter is the boss object used to start and stop processes.
  278. """
  279. self.__boss = boss
  280. # These could be __private, but as we access them from within unittest,
  281. # it's more comfortable to have them just _protected.
  282. self._components = {}
  283. self._old_config = {}
  284. self._running = False
  285. self.__specials = specials
  286. def __reconfigure_internal(self, old, new):
  287. """
  288. Does a switch from one configuration to another.
  289. """
  290. self._run_plan(self._build_plan(old, new))
  291. self._old_config = new
  292. def startup(self, configuration):
  293. """
  294. Starts the first set of processes. This configuration is expected
  295. to be hardcoded from the boss itself to start the configuration
  296. manager and other similar things.
  297. """
  298. if self._running:
  299. raise ValueError("Trying to start the component configurator " +
  300. "twice")
  301. logger.info(BIND10_CONFIGURATOR_START)
  302. self.__reconfigure_internal({}, configuration)
  303. self._running = True
  304. def shutdown(self):
  305. """
  306. Shuts everything down.
  307. """
  308. if not self._running:
  309. raise ValueError("Trying to shutdown the component " +
  310. "configurator while it's not yet running")
  311. logger.info(BIND10_CONFIGURATOR_STOP)
  312. self._running = False
  313. self.__reconfigure_internal(self._old_config, {})
  314. def reconfigure(self, configuration):
  315. """
  316. Changes configuration from the current one to the provided. It
  317. starts and stops all the components as needed (eg. if there's
  318. a component that was not in the original configuration, it is
  319. started, any component that was in the old and is not in the
  320. new one is stopped).
  321. """
  322. if not self._running:
  323. raise ValueError("Trying to reconfigure the component " +
  324. "configurator while it's not yet running")
  325. logger.info(BIND10_CONFIGURATOR_RECONFIGURE)
  326. self.__reconfigure_internal(self._old_config, configuration)
  327. def _build_plan(self, old, new):
  328. """
  329. Builds a plan how to transfer from the old configuration to the new
  330. one. It'll be sorted by priority and it will contain the components
  331. (already created, but not started). Each command in the plan is a dict,
  332. so it can be extended any time in future to include whatever
  333. parameters each operation might need.
  334. Any configuration problems are expected to be handled here, so the
  335. plan is not yet run.
  336. """
  337. logger.debug(DBG_TRACE_DATA, BIND10_CONFIGURATOR_BUILD, old, new)
  338. plan = []
  339. # Handle removals of old components
  340. for cname in old.keys():
  341. if cname not in new:
  342. component = self._components[cname]
  343. if component.running():
  344. plan.append({
  345. 'command': STOP_CMD,
  346. 'component': component,
  347. 'name': cname
  348. })
  349. # Handle transitions of configuration of what is here
  350. for cname in new.keys():
  351. if cname in old:
  352. for option in ['special', 'process', 'kind', 'address',
  353. 'params']:
  354. if new[cname].get(option) != old[cname].get(option):
  355. raise NotImplementedError('Changing configuration of' +
  356. ' a running component is ' +
  357. 'not yet supported. Remove' +
  358. ' and re-add ' + cname +
  359. 'to get the same effect')
  360. # Handle introduction of new components
  361. plan_add = []
  362. for cname in new.keys():
  363. if cname not in old:
  364. component_spec = new[cname]
  365. creator = Component
  366. if 'special' in component_spec:
  367. # TODO: Better error handling
  368. creator = self.__specials[component_spec['special']]
  369. component = creator(component_spec.get('process', cname),
  370. self.__boss,
  371. component_spec.get('kind', 'dispensable'),
  372. component_spec.get('address'),
  373. component_spec.get('params'))
  374. priority = component_spec.get('priority', 0)
  375. # We store tuples, priority first, so we can easily sort
  376. plan_add.append((priority, {
  377. 'component': component,
  378. 'command': START_CMD,
  379. 'name': cname,
  380. }))
  381. # Push the starts there sorted by priority
  382. plan.extend([command for (_, command) in sorted(plan_add,
  383. reverse=True,
  384. key=lambda command:
  385. command[0])])
  386. return plan
  387. def running(self):
  388. """
  389. Returns if the configurator is running (eg. was started by startup and
  390. not yet stopped by shutdown).
  391. """
  392. return self._running
  393. def _run_plan(self, plan):
  394. """
  395. Run a plan, created beforehand by _build_plan.
  396. With the start and stop commands, it also adds and removes components
  397. in _components.
  398. Currently implemented commands are:
  399. * start
  400. * stop
  401. The plan is a list of tasks, each task is a dictionary. It must contain
  402. at last 'component' (a component object to work with) and 'command'
  403. (the command to do). Currently, both existing commands need 'name' of
  404. the component as well (the identifier from configuration).
  405. """
  406. done = 0
  407. try:
  408. logger.debug(DBG_TRACE_DATA, BIND10_CONFIGURATOR_RUN, len(plan))
  409. for task in plan:
  410. component = task['component']
  411. command = task['command']
  412. logger.debug(DBG_TRACE_DETAILED, BIND10_CONFIGURATOR_TASK,
  413. command, component.name())
  414. if command == START_CMD:
  415. component.start()
  416. self._components[task['name']] = component
  417. elif command == STOP_CMD:
  418. if component.running():
  419. component.stop()
  420. del self._components[task['name']]
  421. else:
  422. # Can Not Happen (as the plans are generated by ourselves).
  423. # Therefore not tested.
  424. raise NotImplementedError("Command unknown: " + command)
  425. done += 1
  426. except:
  427. logger.error(BIND10_CONFIGURATOR_PLAN_INTERRUPTED, done, len(plan))
  428. raise