zonemgr.py.in 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. #!@PYTHON@
  2. # Copyright (C) 2010 Internet Systems Consortium.
  3. # Copyright (C) 2010 CZ NIC
  4. #
  5. # Permission to use, copy, modify, and distribute this software for any
  6. # purpose with or without fee is hereby granted, provided that the above
  7. # copyright notice and this permission notice appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  10. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  11. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  12. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  13. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  14. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  15. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  16. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. """
  18. This file implements the Secondary Manager program.
  19. The secondary manager is one of the co-operating processes
  20. of BIND10, which keeps track of timers and other information
  21. necessary for BIND10 to act as a slave.
  22. """
  23. import sys; sys.path.append ('@@PYTHONPATH@@')
  24. import os
  25. import time
  26. import signal
  27. import isc
  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. isc.util.process.rename()
  38. # If B10_FROM_BUILD is set in the environment, we use data files
  39. # from a directory relative to that, otherwise we use the ones
  40. # installed on the system
  41. if "B10_FROM_BUILD" in os.environ:
  42. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/zonemgr"
  43. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  44. else:
  45. PREFIX = "@prefix@"
  46. DATAROOTDIR = "@datarootdir@"
  47. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  48. AUTH_SPECFILE_PATH = SPECFILE_PATH
  49. SPECFILE_LOCATION = SPECFILE_PATH + "/zonemgr.spec"
  50. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + "/auth.spec"
  51. __version__ = "BIND10"
  52. # define module name
  53. XFRIN_MODULE_NAME = 'Xfrin'
  54. AUTH_MODULE_NAME = 'Auth'
  55. # define command name
  56. ZONE_XFRIN_FAILED_COMMAND = 'zone_xfrin_failed'
  57. ZONE_XFRIN_SUCCESS_COMMAND = 'zone_new_data_ready'
  58. ZONE_REFRESH_COMMAND = 'refresh_from_zonemgr'
  59. ZONE_NOTIFY_COMMAND = 'notify'
  60. # define zone state
  61. ZONE_OK = 0
  62. ZONE_REFRESHING = 1
  63. ZONE_EXPIRED = 2
  64. # offsets of fields in the SOA RDATA
  65. REFRESH_OFFSET = 3
  66. RETRY_OFFSET = 4
  67. EXPIRED_OFFSET = 5
  68. # verbose mode
  69. VERBOSE_MODE = False
  70. def log_msg(msg):
  71. if VERBOSE_MODE:
  72. sys.stdout.write("[b10-zonemgr] %s\n" % str(msg))
  73. class ZonemgrException(Exception):
  74. pass
  75. class ZonemgrRefresh:
  76. """This class will maintain and manage zone refresh info.
  77. It also provides methods to keep track of zone timers and
  78. do zone refresh.
  79. Zone timers can be started by calling run_timer(), and it
  80. can be stopped by calling shutdown() in another thread.
  81. """
  82. def __init__(self, cc, db_file, slave_socket, config_data):
  83. self._cc = cc
  84. self._check_sock = slave_socket
  85. self._db_file = db_file
  86. self.update_config_data(config_data)
  87. self._zonemgr_refresh_info = {}
  88. self._build_zonemgr_refresh_info()
  89. self._running = False
  90. def _random_jitter(self, max, jitter):
  91. """Imposes some random jitters for refresh and
  92. retry timers to avoid many zones need to do refresh
  93. at the same time.
  94. The value should be between (max - jitter) and max.
  95. """
  96. if 0 == jitter:
  97. return max
  98. return random.uniform(max - jitter, max)
  99. def _get_current_time(self):
  100. return time.time()
  101. def _set_zone_timer(self, zone_name_class, max, jitter):
  102. """Set zone next refresh time.
  103. jitter should not be bigger than half the original value."""
  104. self._set_zone_next_refresh_time(zone_name_class, self._get_current_time() + \
  105. self._random_jitter(max, jitter))
  106. def _set_zone_refresh_timer(self, zone_name_class):
  107. """Set zone next refresh time after zone refresh success.
  108. now + refresh - jitter <= next_refresh_time <= now + refresh
  109. """
  110. zone_refresh_time = float(self._get_zone_soa_rdata(zone_name_class).split(" ")[REFRESH_OFFSET])
  111. zone_refresh_time = max(self._lowerbound_refresh, zone_refresh_time)
  112. self._set_zone_timer(zone_name_class, zone_refresh_time, self._jitter_scope * zone_refresh_time)
  113. def _set_zone_retry_timer(self, zone_name_class):
  114. """Set zone next refresh time after zone refresh fail.
  115. now + retry - jitter <= next_refresh_time <= now + retry
  116. """
  117. zone_retry_time = float(self._get_zone_soa_rdata(zone_name_class).split(" ")[RETRY_OFFSET])
  118. zone_retry_time = max(self._lowerbound_retry, zone_retry_time)
  119. self._set_zone_timer(zone_name_class, zone_retry_time, self._jitter_scope * zone_retry_time)
  120. def _set_zone_notify_timer(self, zone_name_class):
  121. """Set zone next refresh time after receiving notify
  122. next_refresh_time = now
  123. """
  124. self._set_zone_timer(zone_name_class, 0, 0)
  125. def _zone_not_exist(self, zone_name_class):
  126. """ Zone doesn't belong to zonemgr"""
  127. if zone_name_class in self._zonemgr_refresh_info.keys():
  128. return False
  129. return True
  130. def zone_refresh_success(self, zone_name_class):
  131. """Update zone info after zone refresh success"""
  132. if (self._zone_not_exist(zone_name_class)):
  133. raise ZonemgrException("[b10-zonemgr] Zone (%s, %s) doesn't "
  134. "belong to zonemgr" % zone_name_class)
  135. return
  136. self.zonemgr_reload_zone(zone_name_class)
  137. self._set_zone_refresh_timer(zone_name_class)
  138. self._set_zone_state(zone_name_class, ZONE_OK)
  139. self._set_zone_last_refresh_time(zone_name_class, self._get_current_time())
  140. def zone_refresh_fail(self, zone_name_class):
  141. """Update zone info after zone refresh fail"""
  142. if (self._zone_not_exist(zone_name_class)):
  143. raise ZonemgrException("[b10-zonemgr] Zone (%s, %s) doesn't "
  144. "belong to zonemgr" % zone_name_class)
  145. return
  146. # Is zone expired?
  147. if (self._zone_is_expired(zone_name_class)):
  148. self._set_zone_state(zone_name_class, ZONE_EXPIRED)
  149. else:
  150. self._set_zone_state(zone_name_class, ZONE_OK)
  151. self._set_zone_retry_timer(zone_name_class)
  152. def zone_handle_notify(self, zone_name_class, master):
  153. """Handle zone notify"""
  154. if (self._zone_not_exist(zone_name_class)):
  155. raise ZonemgrException("[b10-zonemgr] Notified zone (%s, %s) "
  156. "doesn't belong to zonemgr" % zone_name_class)
  157. return
  158. self._set_zone_notifier_master(zone_name_class, master)
  159. self._set_zone_notify_timer(zone_name_class)
  160. def zonemgr_reload_zone(self, zone_name_class):
  161. """ Reload a zone."""
  162. zone_soa = sqlite3_ds.get_zone_soa(str(zone_name_class[0]), self._db_file)
  163. self._zonemgr_refresh_info[zone_name_class]["zone_soa_rdata"] = zone_soa[7]
  164. def zonemgr_add_zone(self, zone_name_class):
  165. """ Add a zone into zone manager."""
  166. zone_info = {}
  167. zone_soa = sqlite3_ds.get_zone_soa(str(zone_name_class[0]), self._db_file)
  168. if not zone_soa:
  169. raise ZonemgrException("[b10-zonemgr] zone (%s, %s) doesn't have soa." % zone_name_class)
  170. zone_info["zone_soa_rdata"] = zone_soa[7]
  171. zone_info["zone_state"] = ZONE_OK
  172. zone_info["last_refresh_time"] = self._get_current_time()
  173. zone_info["next_refresh_time"] = self._get_current_time() + \
  174. float(zone_soa[7].split(" ")[REFRESH_OFFSET])
  175. self._zonemgr_refresh_info[zone_name_class] = zone_info
  176. def _build_zonemgr_refresh_info(self):
  177. """ Build zonemgr refresh info map."""
  178. log_msg("Start loading zone into zonemgr.")
  179. for zone_name, zone_class in sqlite3_ds.get_zones_info(self._db_file):
  180. zone_name_class = (zone_name, zone_class)
  181. self.zonemgr_add_zone(zone_name_class)
  182. log_msg("Finish loading zone into zonemgr.")
  183. def _zone_is_expired(self, zone_name_class):
  184. """Judge whether a zone is expired or not."""
  185. zone_expired_time = float(self._get_zone_soa_rdata(zone_name_class).split(" ")[EXPIRED_OFFSET])
  186. zone_last_refresh_time = self._get_zone_last_refresh_time(zone_name_class)
  187. if (ZONE_EXPIRED == self._get_zone_state(zone_name_class) or
  188. zone_last_refresh_time + zone_expired_time <= self._get_current_time()):
  189. return True
  190. return False
  191. def _get_zone_soa_rdata(self, zone_name_class):
  192. return self._zonemgr_refresh_info[zone_name_class]["zone_soa_rdata"]
  193. def _get_zone_last_refresh_time(self, zone_name_class):
  194. return self._zonemgr_refresh_info[zone_name_class]["last_refresh_time"]
  195. def _set_zone_last_refresh_time(self, zone_name_class, time):
  196. self._zonemgr_refresh_info[zone_name_class]["last_refresh_time"] = time
  197. def _get_zone_notifier_master(self, zone_name_class):
  198. if ("notify_master" in self._zonemgr_refresh_info[zone_name_class].keys()):
  199. return self._zonemgr_refresh_info[zone_name_class]["notify_master"]
  200. return None
  201. def _set_zone_notifier_master(self, zone_name_class, master_addr):
  202. self._zonemgr_refresh_info[zone_name_class]["notify_master"] = master_addr
  203. def _clear_zone_notifier_master(self, zone_name_class):
  204. if ("notify_master" in self._zonemgr_refresh_info[zone_name_class].keys()):
  205. del self._zonemgr_refresh_info[zone_name_class]["notify_master"]
  206. def _get_zone_state(self, zone_name_class):
  207. return self._zonemgr_refresh_info[zone_name_class]["zone_state"]
  208. def _set_zone_state(self, zone_name_class, zone_state):
  209. self._zonemgr_refresh_info[zone_name_class]["zone_state"] = zone_state
  210. def _get_zone_refresh_timeout(self, zone_name_class):
  211. return self._zonemgr_refresh_info[zone_name_class]["refresh_timeout"]
  212. def _set_zone_refresh_timeout(self, zone_name_class, time):
  213. self._zonemgr_refresh_info[zone_name_class]["refresh_timeout"] = time
  214. def _get_zone_next_refresh_time(self, zone_name_class):
  215. return self._zonemgr_refresh_info[zone_name_class]["next_refresh_time"]
  216. def _set_zone_next_refresh_time(self, zone_name_class, time):
  217. self._zonemgr_refresh_info[zone_name_class]["next_refresh_time"] = time
  218. def _send_command(self, module_name, command_name, params):
  219. """Send command between modules."""
  220. msg = create_command(command_name, params)
  221. try:
  222. seq = self._cc.group_sendmsg(msg, module_name)
  223. try:
  224. answer, env = self._cc.group_recvmsg(False, seq)
  225. except isc.cc.session.SessionTimeout:
  226. pass # for now we just ignore the failure
  227. except socket.error:
  228. sys.stderr.write("[b10-zonemgr] Failed to send to module %s, the session has been closed." % module_name)
  229. def _find_need_do_refresh_zone(self):
  230. """Find the first zone need do refresh, if no zone need
  231. do refresh, return the zone with minimum next_refresh_time.
  232. """
  233. zone_need_refresh = None
  234. for zone_name_class in self._zonemgr_refresh_info.keys():
  235. zone_state = self._get_zone_state(zone_name_class)
  236. # If hasn't received refresh response but are within refresh timeout, skip the zone
  237. if (ZONE_REFRESHING == zone_state and
  238. (self._get_zone_refresh_timeout(zone_name_class) > self._get_current_time())):
  239. continue
  240. # Get the zone with minimum next_refresh_time
  241. if ((zone_need_refresh is None) or
  242. (self._get_zone_next_refresh_time(zone_name_class) <
  243. self._get_zone_next_refresh_time(zone_need_refresh))):
  244. zone_need_refresh = zone_name_class
  245. # Find the zone need do refresh
  246. if (self._get_zone_next_refresh_time(zone_need_refresh) < self._get_current_time()):
  247. break
  248. return zone_need_refresh
  249. def _do_refresh(self, zone_name_class):
  250. """Do zone refresh."""
  251. log_msg("Do refresh for zone (%s, %s)." % zone_name_class)
  252. self._set_zone_state(zone_name_class, ZONE_REFRESHING)
  253. self._set_zone_refresh_timeout(zone_name_class, self._get_current_time() + self._max_transfer_timeout)
  254. notify_master = self._get_zone_notifier_master(zone_name_class)
  255. # If the zone has notify master, send notify command to xfrin module
  256. if notify_master:
  257. param = {"zone_name" : zone_name_class[0],
  258. "zone_class" : zone_name_class[1],
  259. "master" : notify_master
  260. }
  261. self._send_command(XFRIN_MODULE_NAME, ZONE_NOTIFY_COMMAND, param)
  262. self._clear_zone_notifier_master(zone_name_class)
  263. # Send refresh command to xfrin module
  264. else:
  265. param = {"zone_name" : zone_name_class[0],
  266. "zone_class" : zone_name_class[1]
  267. }
  268. self._send_command(XFRIN_MODULE_NAME, ZONE_REFRESH_COMMAND, param)
  269. def _zone_mgr_is_empty(self):
  270. """Does zone manager has no zone?"""
  271. if not len(self._zonemgr_refresh_info):
  272. return True
  273. return False
  274. def _run_timer(self, start_event):
  275. while self._running:
  276. # Notify run_timer that we already started and are inside the loop.
  277. # It is set only once, but when it was outside the loop, there was
  278. # a race condition and _running could be set to false before we
  279. # could enter it
  280. if start_event:
  281. start_event.set()
  282. start_event = None
  283. # If zonemgr has no zone, set timer timeout to self._lowerbound_retry.
  284. if self._zone_mgr_is_empty():
  285. timeout = self._lowerbound_retry
  286. else:
  287. zone_need_refresh = self._find_need_do_refresh_zone()
  288. # If don't get zone with minimum next refresh time, set timer timeout to self._lowerbound_retry.
  289. if not zone_need_refresh:
  290. timeout = self._lowerbound_retry
  291. else:
  292. timeout = self._get_zone_next_refresh_time(zone_need_refresh) - self._get_current_time()
  293. if (timeout < 0):
  294. self._do_refresh(zone_need_refresh)
  295. continue
  296. """ Wait for the socket notification for a maximum time of timeout
  297. in seconds (as float)."""
  298. try:
  299. rlist, wlist, xlist = select.select([self._check_sock, self._read_sock], [], [], timeout)
  300. except select.error as e:
  301. if e.args[0] == errno.EINTR:
  302. (rlist, wlist, xlist) = ([], [], [])
  303. else:
  304. sys.stderr.write("[b10-zonemgr] Error with select(); %s\n" % e)
  305. break
  306. for fd in rlist:
  307. if fd == self._read_sock: # awaken by shutdown socket
  308. # self._running will be False by now, if it is not a false
  309. # alarm (linux kernel is said to trigger spurious wakeup
  310. # on a filehandle that is not really readable).
  311. continue
  312. if fd == self._check_sock: # awaken by check socket
  313. self._check_sock.recv(32)
  314. def run_timer(self, daemon=False):
  315. """
  316. Keep track of zone timers. Spawns and starts a thread. The thread object is returned.
  317. You can stop it by calling shutdown().
  318. """
  319. # Small sanity check
  320. if self._running:
  321. raise RuntimeError("Trying to run the timers twice at the same time")
  322. # Prepare the launch
  323. self._running = True
  324. (self._read_sock, self._write_sock) = socket.socketpair()
  325. start_event = threading.Event()
  326. # Start the thread
  327. self._thread = threading.Thread(target = self._run_timer,
  328. args = (start_event,))
  329. if daemon:
  330. self._thread.setDaemon(True)
  331. self._thread.start()
  332. start_event.wait()
  333. # Return the thread to anyone interested
  334. return self._thread
  335. def shutdown(self):
  336. """
  337. Stop the run_timer() thread. Block until it finished. This must be
  338. called from a different thread.
  339. """
  340. if not self._running:
  341. raise RuntimeError("Trying to shutdown, but not running")
  342. # Ask the thread to stop
  343. self._running = False
  344. self._write_sock.send(b'shutdown') # make self._read_sock readble
  345. # Wait for it to actually finnish
  346. self._thread.join()
  347. # Wipe out what we do not need
  348. self._thread = None
  349. self._read_sock = None
  350. self._write_sock = None
  351. def update_config_data(self, new_config):
  352. """ update ZonemgrRefresh config """
  353. self._lowerbound_refresh = new_config.get('lowerbound_refresh')
  354. self._lowerbound_retry = new_config.get('lowerbound_retry')
  355. self._max_transfer_timeout = new_config.get('max_transfer_timeout')
  356. self._jitter_scope = new_config.get('jitter_scope')
  357. class Zonemgr:
  358. """Zone manager class."""
  359. def __init__(self):
  360. self._zone_refresh = None
  361. self._setup_session()
  362. self._db_file = self.get_db_file()
  363. # Create socket pair for communicating between main thread and zonemgr timer thread
  364. self._master_socket, self._slave_socket = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
  365. self._zone_refresh = ZonemgrRefresh(self._cc, self._db_file, self._slave_socket, self._config_data)
  366. self._zone_refresh.run_timer()
  367. self._lock = threading.Lock()
  368. self._shutdown_event = threading.Event()
  369. self.running = False
  370. def _setup_session(self):
  371. """Setup two sessions for zonemgr, one(self._module_cc) is used for receiving
  372. commands and config data sent from other modules, another one (self._cc)
  373. is used to send commands to proper modules."""
  374. self._cc = isc.cc.Session()
  375. self._module_cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  376. self.config_handler,
  377. self.command_handler)
  378. self._module_cc.add_remote_config(AUTH_SPECFILE_LOCATION)
  379. self._config_data = self._module_cc.get_full_config()
  380. self._config_data_check(self._config_data)
  381. self._module_cc.start()
  382. def get_db_file(self):
  383. db_file, is_default = self._module_cc.get_remote_config_value(AUTH_MODULE_NAME, "database_file")
  384. # this too should be unnecessary, but currently the
  385. # 'from build' override isn't stored in the config
  386. # (and we don't have indirect python access to datasources yet)
  387. if is_default and "B10_FROM_BUILD" in os.environ:
  388. db_file = os.environ["B10_FROM_BUILD"] + "/bind10_zones.sqlite3"
  389. return db_file
  390. def shutdown(self):
  391. """Shutdown the zonemgr process. the thread which is keeping track of zone
  392. timers should be terminated.
  393. """
  394. self._zone_refresh.shutdown()
  395. self._slave_socket.close()
  396. self._master_socket.close()
  397. self._shutdown_event.set()
  398. self.running = False
  399. def config_handler(self, new_config):
  400. """ Update config data. """
  401. answer = create_answer(0)
  402. for key in new_config:
  403. if key not in self._config_data:
  404. answer = create_answer(1, "Unknown config data: " + str(key))
  405. continue
  406. self._config_data[key] = new_config[key]
  407. self._config_data_check(self._config_data)
  408. if (self._zone_refresh):
  409. self._zone_refresh.update_config_data(self._config_data)
  410. return answer
  411. def _config_data_check(self, config_data):
  412. """Check whether the new config data is valid or
  413. not. """
  414. # jitter should not be bigger than half of the original value
  415. if config_data.get('jitter_scope') > 0.5:
  416. config_data['jitter_scope'] = 0.5
  417. log_msg("[b10-zonemgr] jitter_scope is too big, its value will "
  418. "be set to 0.5")
  419. def _parse_cmd_params(self, args, command):
  420. zone_name = args.get("zone_name")
  421. if not zone_name:
  422. raise ZonemgrException("zone name should be provided")
  423. zone_class = args.get("zone_class")
  424. if not zone_class:
  425. raise ZonemgrException("zone class should be provided")
  426. if (command != ZONE_NOTIFY_COMMAND):
  427. return (zone_name, zone_class)
  428. master_str = args.get("master")
  429. if not master_str:
  430. raise ZonemgrException("master address should be provided")
  431. return ((zone_name, zone_class), master_str)
  432. def command_handler(self, command, args):
  433. """Handle command receivd from command channel.
  434. ZONE_NOTIFY_COMMAND is issued by Auth process; ZONE_XFRIN_SUCCESS_COMMAND
  435. and ZONE_XFRIN_FAILED_COMMAND are issued by Xfrin process; shutdown is issued
  436. by a user or Boss process. """
  437. answer = create_answer(0)
  438. if command == ZONE_NOTIFY_COMMAND:
  439. """ Handle Auth notify command"""
  440. # master is the source sender of the notify message.
  441. zone_name_class, master = self._parse_cmd_params(args, command)
  442. log_msg("Received notify command for zone (%s, %s)." % zone_name_class)
  443. with self._lock:
  444. self._zone_refresh.zone_handle_notify(zone_name_class, master)
  445. # Send notification to zonemgr timer thread
  446. self._master_socket.send(b" ")# make self._slave_socket readble
  447. elif command == ZONE_XFRIN_SUCCESS_COMMAND:
  448. """ Handle xfrin success command"""
  449. zone_name_class = self._parse_cmd_params(args, command)
  450. with self._lock:
  451. self._zone_refresh.zone_refresh_success(zone_name_class)
  452. self._master_socket.send(b" ")# make self._slave_socket readble
  453. elif command == ZONE_XFRIN_FAILED_COMMAND:
  454. """ Handle xfrin fail command"""
  455. zone_name_class = self._parse_cmd_params(args, command)
  456. with self._lock:
  457. self._zone_refresh.zone_refresh_fail(zone_name_class)
  458. self._master_socket.send(b" ")# make self._slave_socket readble
  459. elif command == "shutdown":
  460. self.shutdown()
  461. else:
  462. answer = create_answer(1, "Unknown command:" + str(command))
  463. return answer
  464. def run(self):
  465. self.running = True
  466. while not self._shutdown_event.is_set():
  467. self._module_cc.check_command(False)
  468. zonemgrd = None
  469. def signal_handler(signal, frame):
  470. if zonemgrd:
  471. zonemgrd.shutdown()
  472. sys.exit(0)
  473. def set_signal_handler():
  474. signal.signal(signal.SIGTERM, signal_handler)
  475. signal.signal(signal.SIGINT, signal_handler)
  476. def set_cmd_options(parser):
  477. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  478. help="display more about what is going on")
  479. if '__main__' == __name__:
  480. try:
  481. parser = OptionParser()
  482. set_cmd_options(parser)
  483. (options, args) = parser.parse_args()
  484. VERBOSE_MODE = options.verbose
  485. set_signal_handler()
  486. zonemgrd = Zonemgr()
  487. zonemgrd.run()
  488. except KeyboardInterrupt:
  489. sys.stderr.write("[b10-zonemgr] exit zonemgr process\n")
  490. except isc.cc.session.SessionError as e:
  491. sys.stderr.write("[b10-zonemgr] Error creating zonemgr, "
  492. "is the command channel daemon running?\n")
  493. except isc.cc.session.SessionTimeout as e:
  494. sys.stderr.write("[b10-zonemgr] Error creating zonemgr, "
  495. "is the configuration manager running?\n")
  496. except isc.config.ModuleCCSessionError as e:
  497. sys.stderr.write("[b10-zonemgr] exit zonemgr process: %s\n" % str(e))
  498. if zonemgrd and zonemgrd.running:
  499. zonemgrd.shutdown()