zonemgr.py.in 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. #!@PYTHON@
  2. # Copyright (C) 2010 Internet Systems Consortium.
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  9. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  10. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  11. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  13. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  14. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  15. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """
  17. This file implements the Secondary Manager program.
  18. The secondary manager is one of the co-operating processes
  19. of BIND10, which keeps track of timers and other information
  20. necessary for BIND10 to act as a slave.
  21. """
  22. import sys; sys.path.append ('@@PYTHONPATH@@')
  23. import os
  24. import time
  25. import signal
  26. import isc
  27. import isc.dns
  28. import random
  29. import threading
  30. import select
  31. import socket
  32. import errno
  33. from isc.datasrc import sqlite3_ds
  34. from optparse import OptionParser, OptionValueError
  35. from isc.config.ccsession import *
  36. import isc.util.process
  37. from isc.log_messages.zonemgr_messages import *
  38. from isc.notify import notify_out
  39. # Initialize logging for called modules.
  40. isc.log.init("b10-zonemgr", buffer=True)
  41. logger = isc.log.Logger("zonemgr")
  42. # Pending system-wide debug level definitions, the ones we
  43. # use here are hardcoded for now
  44. DBG_PROCESS = logger.DBGLVL_TRACE_BASIC
  45. DBG_COMMANDS = logger.DBGLVL_TRACE_DETAIL
  46. # Constants for debug levels.
  47. DBG_START_SHUT = logger.DBGLVL_START_SHUT
  48. DBG_ZONEMGR_COMMAND = logger.DBGLVL_COMMAND
  49. DBG_ZONEMGR_BASIC = logger.DBGLVL_TRACE_BASIC
  50. isc.util.process.rename()
  51. # If B10_FROM_BUILD is set in the environment, we use data files
  52. # from a directory relative to that, otherwise we use the ones
  53. # installed on the system
  54. if "B10_FROM_BUILD" in os.environ:
  55. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/zonemgr"
  56. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  57. else:
  58. PREFIX = "@prefix@"
  59. DATAROOTDIR = "@datarootdir@"
  60. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  61. AUTH_SPECFILE_PATH = SPECFILE_PATH
  62. SPECFILE_LOCATION = SPECFILE_PATH + "/zonemgr.spec"
  63. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + "/auth.spec"
  64. __version__ = "BIND10"
  65. # define module name
  66. XFRIN_MODULE_NAME = 'Xfrin'
  67. AUTH_MODULE_NAME = 'Auth'
  68. # define command name
  69. ZONE_REFRESH_COMMAND = 'refresh_from_zonemgr'
  70. ZONE_NOTIFY_COMMAND = 'notify'
  71. # define zone state
  72. ZONE_OK = 0
  73. ZONE_REFRESHING = 1
  74. ZONE_EXPIRED = 2
  75. # offsets of fields in the SOA RDATA
  76. REFRESH_OFFSET = 3
  77. RETRY_OFFSET = 4
  78. EXPIRED_OFFSET = 5
  79. class ZonemgrException(Exception):
  80. pass
  81. class ZonemgrRefresh:
  82. """This class will maintain and manage zone refresh info.
  83. It also provides methods to keep track of zone timers and
  84. do zone refresh.
  85. Zone timers can be started by calling run_timer(), and it
  86. can be stopped by calling shutdown() in another thread.
  87. """
  88. def __init__(self, db_file, slave_socket, module_cc_session):
  89. self._mccs = module_cc_session
  90. self._check_sock = slave_socket
  91. self._db_file = db_file
  92. self._zonemgr_refresh_info = {}
  93. self._lowerbound_refresh = None
  94. self._lowerbound_retry = None
  95. self._max_transfer_timeout = None
  96. self._refresh_jitter = None
  97. self._reload_jitter = None
  98. self.update_config_data(module_cc_session.get_full_config(),
  99. module_cc_session)
  100. self._running = False
  101. def _random_jitter(self, max, jitter):
  102. """Imposes some random jitters for refresh and
  103. retry timers to avoid many zones need to do refresh
  104. at the same time.
  105. The value should be between (max - jitter) and max.
  106. """
  107. if 0 == jitter:
  108. return max
  109. return random.uniform(max - jitter, max)
  110. def _get_current_time(self):
  111. return time.time()
  112. def _set_zone_timer(self, zone_name_class, max, jitter):
  113. """Set zone next refresh time.
  114. jitter should not be bigger than half the original value."""
  115. self._set_zone_next_refresh_time(zone_name_class, self._get_current_time() + \
  116. self._random_jitter(max, jitter))
  117. def _set_zone_refresh_timer(self, zone_name_class):
  118. """Set zone next refresh time after zone refresh success.
  119. now + refresh - refresh_jitter <= next_refresh_time <= now + refresh
  120. """
  121. zone_refresh_time = float(self._get_zone_soa_rdata(zone_name_class).split(" ")[REFRESH_OFFSET])
  122. zone_refresh_time = max(self._lowerbound_refresh, zone_refresh_time)
  123. self._set_zone_timer(zone_name_class, zone_refresh_time, self._refresh_jitter * zone_refresh_time)
  124. def _set_zone_retry_timer(self, zone_name_class):
  125. """Set zone next refresh time after zone refresh fail.
  126. now + retry - retry_jitter <= next_refresh_time <= now + retry
  127. """
  128. if (self._get_zone_soa_rdata(zone_name_class) is not None):
  129. zone_retry_time = float(self._get_zone_soa_rdata(zone_name_class).split(" ")[RETRY_OFFSET])
  130. else:
  131. zone_retry_time = 0.0
  132. zone_retry_time = max(self._lowerbound_retry, zone_retry_time)
  133. self._set_zone_timer(zone_name_class, zone_retry_time, self._refresh_jitter * zone_retry_time)
  134. def _set_zone_notify_timer(self, zone_name_class):
  135. """Set zone next refresh time after receiving notify
  136. next_refresh_time = now
  137. """
  138. self._set_zone_timer(zone_name_class, 0, 0)
  139. def _zone_not_exist(self, zone_name_class):
  140. """ Zone doesn't belong to zonemgr"""
  141. return not zone_name_class in self._zonemgr_refresh_info
  142. def zone_refresh_success(self, zone_name_class):
  143. """Update zone info after zone refresh success"""
  144. if (self._zone_not_exist(zone_name_class)):
  145. logger.error(ZONEMGR_UNKNOWN_ZONE_SUCCESS, zone_name_class[0], zone_name_class[1])
  146. raise ZonemgrException("[b10-zonemgr] Zone (%s, %s) doesn't "
  147. "belong to zonemgr" % zone_name_class)
  148. self.zonemgr_reload_zone(zone_name_class)
  149. self._set_zone_refresh_timer(zone_name_class)
  150. self._set_zone_state(zone_name_class, ZONE_OK)
  151. self._set_zone_last_refresh_time(zone_name_class, self._get_current_time())
  152. def zone_refresh_fail(self, zone_name_class):
  153. """Update zone info after zone refresh fail"""
  154. if (self._zone_not_exist(zone_name_class)):
  155. logger.error(ZONEMGR_UNKNOWN_ZONE_FAIL, zone_name_class[0], zone_name_class[1])
  156. raise ZonemgrException("[b10-zonemgr] Zone (%s, %s) doesn't "
  157. "belong to zonemgr" % zone_name_class)
  158. # Is zone expired?
  159. if ((self._get_zone_soa_rdata(zone_name_class) is None) or
  160. self._zone_is_expired(zone_name_class)):
  161. self._set_zone_state(zone_name_class, ZONE_EXPIRED)
  162. else:
  163. self._set_zone_state(zone_name_class, ZONE_OK)
  164. self._set_zone_retry_timer(zone_name_class)
  165. def zone_handle_notify(self, zone_name_class, master):
  166. """Handle zone notify"""
  167. if (self._zone_not_exist(zone_name_class)):
  168. logger.error(ZONEMGR_UNKNOWN_ZONE_NOTIFIED, zone_name_class[0],
  169. zone_name_class[1], master)
  170. raise ZonemgrException("[b10-zonemgr] Notified zone (%s, %s) "
  171. "doesn't belong to zonemgr" % zone_name_class)
  172. self._set_zone_notifier_master(zone_name_class, master)
  173. self._set_zone_notify_timer(zone_name_class)
  174. def zonemgr_reload_zone(self, zone_name_class):
  175. """ Reload a zone."""
  176. zone_soa = sqlite3_ds.get_zone_soa(str(zone_name_class[0]), self._db_file)
  177. self._zonemgr_refresh_info[zone_name_class]["zone_soa_rdata"] = zone_soa[7]
  178. def zonemgr_add_zone(self, zone_name_class):
  179. """ Add a zone into zone manager."""
  180. logger.debug(DBG_ZONEMGR_BASIC, ZONEMGR_LOAD_ZONE, zone_name_class[0], zone_name_class[1])
  181. zone_info = {}
  182. zone_soa = sqlite3_ds.get_zone_soa(str(zone_name_class[0]), self._db_file)
  183. if zone_soa is None:
  184. logger.warn(ZONEMGR_NO_SOA, zone_name_class[0], zone_name_class[1])
  185. zone_info["zone_soa_rdata"] = None
  186. zone_reload_time = 0.0
  187. else:
  188. zone_info["zone_soa_rdata"] = zone_soa[7]
  189. zone_reload_time = float(zone_soa[7].split(" ")[RETRY_OFFSET])
  190. zone_info["zone_state"] = ZONE_OK
  191. zone_info["last_refresh_time"] = self._get_current_time()
  192. self._zonemgr_refresh_info[zone_name_class] = zone_info
  193. # Imposes some random jitters to avoid many zones need to do refresh at the same time.
  194. zone_reload_time = max(self._lowerbound_retry, zone_reload_time)
  195. self._set_zone_timer(zone_name_class, zone_reload_time, self._reload_jitter * zone_reload_time)
  196. def _zone_is_expired(self, zone_name_class):
  197. """Judge whether a zone is expired or not."""
  198. zone_expired_time = float(self._get_zone_soa_rdata(zone_name_class).split(" ")[EXPIRED_OFFSET])
  199. zone_last_refresh_time = self._get_zone_last_refresh_time(zone_name_class)
  200. if (ZONE_EXPIRED == self._get_zone_state(zone_name_class) or
  201. zone_last_refresh_time + zone_expired_time <= self._get_current_time()):
  202. return True
  203. return False
  204. def _get_zone_soa_rdata(self, zone_name_class):
  205. return self._zonemgr_refresh_info[zone_name_class]["zone_soa_rdata"]
  206. def _get_zone_last_refresh_time(self, zone_name_class):
  207. return self._zonemgr_refresh_info[zone_name_class]["last_refresh_time"]
  208. def _set_zone_last_refresh_time(self, zone_name_class, time):
  209. self._zonemgr_refresh_info[zone_name_class]["last_refresh_time"] = time
  210. def _get_zone_notifier_master(self, zone_name_class):
  211. if ("notify_master" in self._zonemgr_refresh_info[zone_name_class].keys()):
  212. return self._zonemgr_refresh_info[zone_name_class]["notify_master"]
  213. return None
  214. def _set_zone_notifier_master(self, zone_name_class, master_addr):
  215. self._zonemgr_refresh_info[zone_name_class]["notify_master"] = master_addr
  216. def _clear_zone_notifier_master(self, zone_name_class):
  217. if ("notify_master" in self._zonemgr_refresh_info[zone_name_class].keys()):
  218. del self._zonemgr_refresh_info[zone_name_class]["notify_master"]
  219. def _get_zone_state(self, zone_name_class):
  220. return self._zonemgr_refresh_info[zone_name_class]["zone_state"]
  221. def _set_zone_state(self, zone_name_class, zone_state):
  222. self._zonemgr_refresh_info[zone_name_class]["zone_state"] = zone_state
  223. def _get_zone_refresh_timeout(self, zone_name_class):
  224. return self._zonemgr_refresh_info[zone_name_class]["refresh_timeout"]
  225. def _set_zone_refresh_timeout(self, zone_name_class, time):
  226. self._zonemgr_refresh_info[zone_name_class]["refresh_timeout"] = time
  227. def _get_zone_next_refresh_time(self, zone_name_class):
  228. return self._zonemgr_refresh_info[zone_name_class]["next_refresh_time"]
  229. def _set_zone_next_refresh_time(self, zone_name_class, time):
  230. self._zonemgr_refresh_info[zone_name_class]["next_refresh_time"] = time
  231. def _send_command(self, module_name, command_name, params):
  232. """Send command between modules."""
  233. try:
  234. self._mccs.rpc_call(command_name, module_name, params=params)
  235. except socket.error:
  236. # FIXME: WTF? Where does socket.error come from? And how do we ever
  237. # dare ignore such serious error? It can only be broken link to
  238. # msgq, we need to terminate then.
  239. logger.error(ZONEMGR_SEND_FAIL, module_name)
  240. except (isc.cc.session.SessionTimeout, isc.config.RPCError):
  241. pass # for now we just ignore the failure
  242. def _find_need_do_refresh_zone(self):
  243. """Find the first zone need do refresh, if no zone need
  244. do refresh, return the zone with minimum next_refresh_time.
  245. """
  246. zone_need_refresh = None
  247. for zone_name_class in self._zonemgr_refresh_info.keys():
  248. zone_state = self._get_zone_state(zone_name_class)
  249. # If hasn't received refresh response but are within refresh
  250. # timeout, skip the zone
  251. if (ZONE_REFRESHING == zone_state and
  252. (self._get_zone_refresh_timeout(zone_name_class) > self._get_current_time())):
  253. continue
  254. # Get the zone with minimum next_refresh_time
  255. if ((zone_need_refresh is None) or
  256. (self._get_zone_next_refresh_time(zone_name_class) <
  257. self._get_zone_next_refresh_time(zone_need_refresh))):
  258. zone_need_refresh = zone_name_class
  259. # Find the zone need do refresh
  260. if (self._get_zone_next_refresh_time(zone_need_refresh) < self._get_current_time()):
  261. break
  262. return zone_need_refresh
  263. def _do_refresh(self, zone_name_class):
  264. """Do zone refresh."""
  265. logger.debug(DBG_ZONEMGR_BASIC, ZONEMGR_REFRESH_ZONE, zone_name_class[0], zone_name_class[1])
  266. self._set_zone_state(zone_name_class, ZONE_REFRESHING)
  267. self._set_zone_refresh_timeout(zone_name_class, self._get_current_time() + self._max_transfer_timeout)
  268. notify_master = self._get_zone_notifier_master(zone_name_class)
  269. # If the zone has notify master, send notify command to xfrin module
  270. if notify_master:
  271. param = {"zone_name" : zone_name_class[0],
  272. "zone_class" : zone_name_class[1],
  273. "master" : notify_master
  274. }
  275. self._send_command(XFRIN_MODULE_NAME, ZONE_NOTIFY_COMMAND, param)
  276. self._clear_zone_notifier_master(zone_name_class)
  277. # Send refresh command to xfrin module
  278. else:
  279. param = {"zone_name" : zone_name_class[0],
  280. "zone_class" : zone_name_class[1]
  281. }
  282. self._send_command(XFRIN_MODULE_NAME, ZONE_REFRESH_COMMAND, param)
  283. def _zone_mgr_is_empty(self):
  284. """Does zone manager has no zone?"""
  285. if not len(self._zonemgr_refresh_info):
  286. return True
  287. return False
  288. def _run_timer(self, start_event):
  289. while self._running:
  290. # Notify run_timer that we already started and are inside the loop.
  291. # It is set only once, but when it was outside the loop, there was
  292. # a race condition and _running could be set to false before we
  293. # could enter it
  294. if start_event:
  295. start_event.set()
  296. start_event = None
  297. # If zonemgr has no zone, set timer timeout to self._lowerbound_retry.
  298. if self._zone_mgr_is_empty():
  299. timeout = self._lowerbound_retry
  300. else:
  301. zone_need_refresh = self._find_need_do_refresh_zone()
  302. # If don't get zone with minimum next refresh time, set timer timeout to self._lowerbound_retry.
  303. if not zone_need_refresh:
  304. timeout = self._lowerbound_retry
  305. else:
  306. timeout = self._get_zone_next_refresh_time(zone_need_refresh) - self._get_current_time()
  307. if (timeout < 0):
  308. self._do_refresh(zone_need_refresh)
  309. continue
  310. """ Wait for the socket notification for a maximum time of timeout
  311. in seconds (as float)."""
  312. try:
  313. rlist, wlist, xlist = select.select([self._check_sock, self._read_sock], [], [], timeout)
  314. except select.error as e:
  315. if e.args[0] == errno.EINTR:
  316. (rlist, wlist, xlist) = ([], [], [])
  317. else:
  318. logger.error(ZONEMGR_SELECT_ERROR, e);
  319. break
  320. for fd in rlist:
  321. if fd == self._read_sock: # awaken by shutdown socket
  322. # self._running will be False by now, if it is not a false
  323. # alarm (linux kernel is said to trigger spurious wakeup
  324. # on a filehandle that is not really readable).
  325. continue
  326. if fd == self._check_sock: # awaken by check socket
  327. self._check_sock.recv(32)
  328. def run_timer(self, daemon=False):
  329. """
  330. Keep track of zone timers. Spawns and starts a thread. The thread object
  331. is returned.
  332. You can stop it by calling shutdown().
  333. """
  334. # Small sanity check
  335. if self._running:
  336. logger.error(ZONEMGR_TIMER_THREAD_RUNNING)
  337. raise RuntimeError("Trying to run the timers twice at the same time")
  338. # Prepare the launch
  339. self._running = True
  340. (self._read_sock, self._write_sock) = socket.socketpair()
  341. start_event = threading.Event()
  342. # Start the thread
  343. self._thread = threading.Thread(target = self._run_timer,
  344. args = (start_event,))
  345. if daemon:
  346. self._thread.setDaemon(True)
  347. self._thread.start()
  348. start_event.wait()
  349. # Return the thread to anyone interested
  350. return self._thread
  351. def shutdown(self):
  352. """
  353. Stop the run_timer() thread. Block until it finished. This must be
  354. called from a different thread.
  355. """
  356. if not self._running:
  357. logger.error(ZONEMGR_NO_TIMER_THREAD)
  358. raise RuntimeError("Trying to shutdown, but not running")
  359. # Ask the thread to stop
  360. self._running = False
  361. self._write_sock.send(b'shutdown') # make self._read_sock readble
  362. # Wait for it to actually finnish
  363. self._thread.join()
  364. # Wipe out what we do not need
  365. self._thread = None
  366. self._read_sock.close()
  367. self._write_sock.close()
  368. self._read_sock = None
  369. self._write_sock = None
  370. def update_config_data(self, new_config, module_cc_session):
  371. """ update ZonemgrRefresh config """
  372. # Get a new value, but only if it is defined (commonly used below)
  373. # We don't use "value or default", because if value would be
  374. # 0, we would take default
  375. def val_or_default(value, default):
  376. if value is not None:
  377. return value
  378. else:
  379. return default
  380. self._lowerbound_refresh = val_or_default(
  381. new_config.get('lowerbound_refresh'), self._lowerbound_refresh)
  382. self._lowerbound_retry = val_or_default(
  383. new_config.get('lowerbound_retry'), self._lowerbound_retry)
  384. self._max_transfer_timeout = val_or_default(
  385. new_config.get('max_transfer_timeout'), self._max_transfer_timeout)
  386. self._refresh_jitter = val_or_default(
  387. new_config.get('refresh_jitter'), self._refresh_jitter)
  388. self._reload_jitter = val_or_default(
  389. new_config.get('reload_jitter'), self._reload_jitter)
  390. try:
  391. required = {}
  392. secondary_zones = new_config.get('secondary_zones')
  393. if secondary_zones is not None:
  394. # Add new zones
  395. for secondary_zone in new_config.get('secondary_zones'):
  396. if 'name' not in secondary_zone:
  397. raise ZonemgrException("Secondary zone specified "
  398. "without a name")
  399. name = secondary_zone['name']
  400. # Convert to Name and back (both to check and to normalize)
  401. try:
  402. name = isc.dns.Name(name, True).to_text()
  403. # Name() can raise a number of different exceptions, just
  404. # catch 'em all.
  405. except Exception as isce:
  406. raise ZonemgrException("Bad zone name '" + name +
  407. "': " + str(isce))
  408. # Currently we use an explicit get_default_value call
  409. # in case the class hasn't been set. Alternatively, we
  410. # could use
  411. # module_cc_session.get_value('secondary_zones[INDEX]/class')
  412. # To get either the value that was set, or the default if
  413. # it wasn't set.
  414. # But the real solution would be to make new_config a type
  415. # that contains default values itself
  416. # (then this entire method can be simplified a lot, and we
  417. # wouldn't need direct access to the ccsession object)
  418. if 'class' in secondary_zone:
  419. rr_class = secondary_zone['class']
  420. else:
  421. rr_class = module_cc_session.get_default_value(
  422. 'secondary_zones/class')
  423. # Convert rr_class to and from RRClass to check its value
  424. try:
  425. name_class = (name, isc.dns.RRClass(rr_class).to_text())
  426. except isc.dns.InvalidRRClass:
  427. raise ZonemgrException("Bad RR class '" +
  428. rr_class +
  429. "' for zone " + name)
  430. required[name_class] = True
  431. # Add it only if it isn't there already
  432. if not name_class in self._zonemgr_refresh_info:
  433. # If we are not able to find it in database, log an warning
  434. self.zonemgr_add_zone(name_class)
  435. # Drop the zones that are no longer there
  436. # Do it in two phases, python doesn't like deleting while iterating
  437. to_drop = []
  438. for old_zone in self._zonemgr_refresh_info:
  439. if not old_zone in required:
  440. to_drop.append(old_zone)
  441. for drop in to_drop:
  442. del self._zonemgr_refresh_info[drop]
  443. except:
  444. raise
  445. class Zonemgr:
  446. """Zone manager class."""
  447. def __init__(self):
  448. self._zone_refresh = None
  449. self._setup_session()
  450. self._db_file = self.get_db_file()
  451. # Create socket pair for communicating between main thread and zonemgr timer thread
  452. self._master_socket, self._slave_socket = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
  453. self._zone_refresh = ZonemgrRefresh(self._db_file, self._slave_socket, self._module_cc)
  454. self._zone_refresh.run_timer()
  455. self._lock = threading.Lock()
  456. self._shutdown_event = threading.Event()
  457. self.running = False
  458. def _setup_session(self):
  459. """Setup two sessions for zonemgr, one(self._module_cc) is used for receiving
  460. commands and config data sent from other modules, another one (self._cc)
  461. is used to send commands to proper modules."""
  462. self._module_cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  463. self.config_handler,
  464. self.command_handler)
  465. self._module_cc.add_remote_config(AUTH_SPECFILE_LOCATION)
  466. self._config_data = self._module_cc.get_full_config()
  467. self._config_data_check(self._config_data)
  468. self._module_cc.start()
  469. def get_db_file(self):
  470. db_file, is_default = self._module_cc.get_remote_config_value(AUTH_MODULE_NAME, "database_file")
  471. # this too should be unnecessary, but currently the
  472. # 'from build' override isn't stored in the config
  473. # (and we don't have indirect python access to datasources yet)
  474. if is_default and "B10_FROM_BUILD" in os.environ:
  475. db_file = os.environ["B10_FROM_BUILD"] + "/bind10_zones.sqlite3"
  476. return db_file
  477. def shutdown(self):
  478. """Shutdown the zonemgr process. The thread which is keeping track of
  479. zone timers should be terminated.
  480. """
  481. self._zone_refresh.shutdown()
  482. self._slave_socket.close()
  483. self._master_socket.close()
  484. self._shutdown_event.set()
  485. self.running = False
  486. def config_handler(self, new_config):
  487. """ Update config data. """
  488. answer = create_answer(0)
  489. ok = True
  490. complete = self._config_data.copy()
  491. for key in new_config:
  492. if key not in complete:
  493. answer = create_answer(1, "Unknown config data: " + str(key))
  494. ok = False
  495. continue
  496. complete[key] = new_config[key]
  497. self._config_data_check(complete)
  498. if self._zone_refresh is not None:
  499. try:
  500. self._zone_refresh.update_config_data(complete, self._module_cc)
  501. except Exception as e:
  502. answer = create_answer(1, str(e))
  503. ok = False
  504. if ok:
  505. self._config_data = complete
  506. return answer
  507. def _config_data_check(self, config_data):
  508. """Check whether the new config data is valid or
  509. not. It contains only basic logic, not full check against
  510. database."""
  511. # jitter should not be bigger than half of the original value
  512. if config_data.get('refresh_jitter') > 0.5:
  513. config_data['refresh_jitter'] = 0.5
  514. logger.warn(ZONEMGR_JITTER_TOO_BIG)
  515. def _parse_cmd_params(self, args, command):
  516. zone_name = args.get("zone_name")
  517. if not zone_name:
  518. logger.error(ZONEMGR_NO_ZONE_NAME)
  519. raise ZonemgrException("zone name should be provided")
  520. zone_class = args.get("zone_class")
  521. if not zone_class:
  522. logger.error(ZONEMGR_NO_ZONE_CLASS)
  523. raise ZonemgrException("zone class should be provided")
  524. if (command != ZONE_NOTIFY_COMMAND):
  525. return (zone_name, zone_class)
  526. master_str = args.get("master")
  527. if not master_str:
  528. logger.error(ZONEMGR_NO_MASTER_ADDRESS)
  529. raise ZonemgrException("master address should be provided")
  530. return ((zone_name, zone_class), master_str)
  531. def command_handler(self, command, args):
  532. """Handle command receivd from command channel.
  533. ZONE_NOTIFY_COMMAND is issued by Auth process;
  534. ZONE_NEW_DATA_READY_CMD and ZONE_XFRIN_FAILED are issued by
  535. Xfrin process;
  536. shutdown is issued by a user or Init process. """
  537. answer = create_answer(0)
  538. if command == ZONE_NOTIFY_COMMAND:
  539. """ Handle Auth notify command"""
  540. # master is the source sender of the notify message.
  541. zone_name_class, master = self._parse_cmd_params(args, command)
  542. logger.debug(DBG_ZONEMGR_COMMAND, ZONEMGR_RECEIVE_NOTIFY, zone_name_class[0], zone_name_class[1])
  543. with self._lock:
  544. self._zone_refresh.zone_handle_notify(zone_name_class, master)
  545. # Send notification to zonemgr timer thread
  546. self._master_socket.send(b" ")# make self._slave_socket readble
  547. elif command == notify_out.ZONE_NEW_DATA_READY_CMD:
  548. """ Handle xfrin success command"""
  549. zone_name_class = self._parse_cmd_params(args, command)
  550. logger.debug(DBG_ZONEMGR_COMMAND, ZONEMGR_RECEIVE_XFRIN_SUCCESS, zone_name_class[0], zone_name_class[1])
  551. with self._lock:
  552. self._zone_refresh.zone_refresh_success(zone_name_class)
  553. self._master_socket.send(b" ")# make self._slave_socket readble
  554. elif command == notify_out.ZONE_XFRIN_FAILED:
  555. """ Handle xfrin fail command"""
  556. zone_name_class = self._parse_cmd_params(args, command)
  557. logger.debug(DBG_ZONEMGR_COMMAND, ZONEMGR_RECEIVE_XFRIN_FAILED, zone_name_class[0], zone_name_class[1])
  558. with self._lock:
  559. self._zone_refresh.zone_refresh_fail(zone_name_class)
  560. self._master_socket.send(b" ")# make self._slave_socket readble
  561. elif command == "shutdown":
  562. logger.debug(DBG_ZONEMGR_COMMAND, ZONEMGR_RECEIVE_SHUTDOWN)
  563. self.shutdown()
  564. else:
  565. logger.warn(ZONEMGR_RECEIVE_UNKNOWN, str(command))
  566. answer = create_answer(1, "Unknown command:" + str(command))
  567. return answer
  568. def run(self):
  569. logger.debug(DBG_PROCESS, ZONEMGR_STARTED)
  570. self.running = True
  571. try:
  572. while not self._shutdown_event.is_set():
  573. self._module_cc.check_command(False)
  574. finally:
  575. self._module_cc.send_stopping()
  576. zonemgrd = None
  577. def signal_handler(signal, frame):
  578. if zonemgrd:
  579. zonemgrd.shutdown()
  580. sys.exit(0)
  581. def set_signal_handler():
  582. signal.signal(signal.SIGTERM, signal_handler)
  583. signal.signal(signal.SIGINT, signal_handler)
  584. def set_cmd_options(parser):
  585. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  586. help="display more about what is going on")
  587. if '__main__' == __name__:
  588. try:
  589. logger.debug(DBG_START_SHUT, ZONEMGR_STARTING)
  590. parser = OptionParser()
  591. set_cmd_options(parser)
  592. (options, args) = parser.parse_args()
  593. if options.verbose:
  594. logger.set_severity("DEBUG", 99)
  595. set_signal_handler()
  596. zonemgrd = Zonemgr()
  597. zonemgrd.run()
  598. except KeyboardInterrupt:
  599. logger.info(ZONEMGR_KEYBOARD_INTERRUPT)
  600. except isc.cc.session.SessionError as e:
  601. logger.error(ZONEMGR_SESSION_ERROR)
  602. except isc.cc.session.SessionTimeout as e:
  603. logger.error(ZONEMGR_SESSION_TIMEOUT)
  604. except isc.config.ModuleCCSessionError as e:
  605. logger.error(ZONEMGR_CCSESSION_ERROR, str(e))
  606. if zonemgrd and zonemgrd.running:
  607. zonemgrd.shutdown()
  608. logger.info(ZONEMGR_SHUTDOWN)