cmdctl.py.in 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. ''' cmdctl module is the configuration entry point for all commands from bindctl
  17. or some other web tools client of bind10. cmdctl is pure https server which provi-
  18. des RESTful API. When command client connecting with cmdctl, it should first login
  19. with legal username and password.
  20. When cmdctl starting up, it will collect command specification and
  21. configuration specification/data of other available modules from configmanager, then
  22. wait for receiving request from client, parse the request and resend the request to
  23. the proper module. When getting the request result from the module, send back the
  24. resut to client.
  25. '''
  26. import sys; sys.path.append ('@@PYTHONPATH@@')
  27. import os
  28. import socketserver
  29. import http.server
  30. import urllib.parse
  31. import json
  32. import re
  33. import ssl, socket
  34. import isc
  35. import pprint
  36. import select
  37. import csv
  38. import random
  39. import time
  40. import signal
  41. from isc.config import ccsession
  42. import isc.util.process
  43. import isc.net.parse
  44. from optparse import OptionParser, OptionValueError
  45. from hashlib import sha1
  46. from isc.util import socketserver_mixin
  47. from isc.log_messages.cmdctl_messages import *
  48. # TODO: these debug-levels are hard-coded here; we are planning on
  49. # creating a general set of debug levels, see ticket #1074. When done,
  50. # we should remove these values and use the general ones in the
  51. # logger.debug calls
  52. # Debug level for communication with BIND10
  53. DBG_CMDCTL_MESSAGING = 30
  54. isc.log.init("b10-cmdctl")
  55. logger = isc.log.Logger("cmdctl")
  56. try:
  57. import threading
  58. except ImportError:
  59. import dummy_threading as threading
  60. isc.util.process.rename()
  61. __version__ = 'BIND10'
  62. URL_PATTERN = re.compile('/([\w]+)(?:/([\w]+))?/?')
  63. CONFIG_DATA_URL = 'config_data'
  64. MODULE_SPEC_URL = 'module_spec'
  65. # If B10_FROM_BUILD is set in the environment, we use data files
  66. # from a directory relative to that, otherwise we use the ones
  67. # installed on the system
  68. if "B10_FROM_BUILD" in os.environ:
  69. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/cmdctl"
  70. else:
  71. PREFIX = "@prefix@"
  72. DATAROOTDIR = "@datarootdir@"
  73. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  74. SPECFILE_LOCATION = SPECFILE_PATH + os.sep + "cmdctl.spec"
  75. class CmdctlException(Exception):
  76. pass
  77. class SecureHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
  78. '''https connection request handler.
  79. Currently only GET and POST are supported. '''
  80. def do_GET(self):
  81. '''The client should send its session id in header with
  82. the name 'cookie'
  83. '''
  84. self.session_id = self.headers.get('cookie')
  85. rcode, reply = http.client.OK, []
  86. if self._is_session_valid():
  87. if self._is_user_logged_in():
  88. rcode, reply = self._handle_get_request()
  89. else:
  90. rcode, reply = http.client.UNAUTHORIZED, ["please login"]
  91. else:
  92. rcode = http.client.BAD_REQUEST
  93. self.send_response(rcode)
  94. self.end_headers()
  95. self.wfile.write(json.dumps(reply).encode())
  96. def _handle_get_request(self):
  97. '''Currently only support the following three url GET request '''
  98. id, module = self._parse_request_path()
  99. return self.server.get_reply_data_for_GET(id, module)
  100. def _is_session_valid(self):
  101. return self.session_id
  102. def _is_user_logged_in(self):
  103. login_time = self.server.user_sessions.get(self.session_id)
  104. if not login_time:
  105. return False
  106. idle_time = time.time() - login_time
  107. if idle_time > self.server.idle_timeout:
  108. return False
  109. # Update idle time
  110. self.server.user_sessions[self.session_id] = time.time()
  111. return True
  112. def _parse_request_path(self):
  113. '''Parse the url, the legal url should like /ldh or /ldh/ldh '''
  114. groups = URL_PATTERN.match(self.path)
  115. if not groups:
  116. return (None, None)
  117. else:
  118. return (groups.group(1), groups.group(2))
  119. def do_POST(self):
  120. '''Process POST request. '''
  121. '''Process user login and send command to proper module
  122. The client should send its session id in header with
  123. the name 'cookie'
  124. '''
  125. self.session_id = self.headers.get('cookie')
  126. rcode, reply = http.client.OK, []
  127. if self._is_session_valid():
  128. if self.path == '/login':
  129. rcode, reply = self._handle_login()
  130. elif self._is_user_logged_in():
  131. rcode, reply = self._handle_post_request()
  132. else:
  133. rcode, reply = http.client.UNAUTHORIZED, ["please login"]
  134. else:
  135. rcode, reply = http.client.BAD_REQUEST, ["session isn't valid"]
  136. self.send_response(rcode)
  137. self.end_headers()
  138. self.wfile.write(json.dumps(reply).encode())
  139. def _handle_login(self):
  140. if self._is_user_logged_in():
  141. return http.client.OK, ["user has already login"]
  142. is_user_valid, error_info = self._check_user_name_and_pwd()
  143. if is_user_valid:
  144. self.server.save_user_session_id(self.session_id)
  145. return http.client.OK, ["login success "]
  146. else:
  147. return http.client.UNAUTHORIZED, error_info
  148. def _check_user_name_and_pwd(self):
  149. '''Check user name and its password '''
  150. length = self.headers.get('Content-Length')
  151. if not length:
  152. return False, ["invalid username or password"]
  153. try:
  154. user_info = json.loads((self.rfile.read(int(length))).decode())
  155. except:
  156. return False, ["invalid username or password"]
  157. user_name = user_info.get('username')
  158. if not user_name:
  159. return False, ["need user name"]
  160. if not self.server.get_user_info(user_name):
  161. logger.info(CMDCTL_NO_SUCH_USER, user_name)
  162. return False, ["username or password error"]
  163. user_pwd = user_info.get('password')
  164. if not user_pwd:
  165. return False, ["need password"]
  166. local_info = self.server.get_user_info(user_name)
  167. pwd_hashval = sha1((user_pwd + local_info[1]).encode())
  168. if pwd_hashval.hexdigest() != local_info[0]:
  169. logger.info(CMDCTL_BAD_PASSWORD, user_name)
  170. return False, ["username or password error"]
  171. return True, None
  172. def _handle_post_request(self):
  173. '''Handle all the post request from client. '''
  174. mod, cmd = self._parse_request_path()
  175. if (not mod) or (not cmd):
  176. return http.client.BAD_REQUEST, ['malformed url']
  177. param = None
  178. len = self.headers.get('Content-Length')
  179. if len:
  180. try:
  181. post_str = str(self.rfile.read(int(len)).decode())
  182. param = json.loads(post_str)
  183. except:
  184. pass
  185. rcode, reply = self.server.send_command_to_module(mod, cmd, param)
  186. ret = http.client.OK
  187. if rcode != 0:
  188. ret = http.client.BAD_REQUEST
  189. return ret, reply
  190. def log_request(self, code='-', size='-'):
  191. '''Rewrite the log request function, log nothing.'''
  192. pass
  193. class CommandControl():
  194. '''Get all modules' config data/specification from configmanager.
  195. receive command from client and resend it to proper module.
  196. '''
  197. def __init__(self, httpserver, verbose = False):
  198. ''' httpserver: the http server which use the object of
  199. CommandControl to communicate with other modules. '''
  200. self._verbose = verbose
  201. self._httpserver = httpserver
  202. self._lock = threading.Lock()
  203. self._setup_session()
  204. self.modules_spec = self._get_modules_specification()
  205. self._config_data = self._get_config_data_from_config_manager()
  206. self._serving = True
  207. self._start_msg_handle_thread()
  208. def _setup_session(self):
  209. '''Setup the session for receving the commands
  210. sent from other modules. There are two sessions
  211. for cmdctl, one(self.module_cc) is used for receiving
  212. commands sent from other modules, another one (self._cc)
  213. is used to send the command from Bindctl or other tools
  214. to proper modules.'''
  215. self._cc = isc.cc.Session()
  216. self._module_cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  217. self.config_handler,
  218. self.command_handler)
  219. self._module_name = self._module_cc.get_module_spec().get_module_name()
  220. self._cmdctl_config_data = self._module_cc.get_full_config()
  221. self._module_cc.start()
  222. def _accounts_file_check(self, filepath):
  223. ''' Check whether the accounts file is valid, each row
  224. should be a list with 3 items.'''
  225. csvfile = None
  226. errstr = None
  227. try:
  228. csvfile = open(filepath)
  229. reader = csv.reader(csvfile)
  230. for row in reader:
  231. a = (row[0], row[1], row[2])
  232. except (IOError, IndexError) as e:
  233. errstr = 'Invalid accounts file: ' + str(e)
  234. finally:
  235. if csvfile:
  236. csvfile.close()
  237. return errstr
  238. def _config_data_check(self, new_config):
  239. ''' Check whether the new config data is valid or
  240. not. '''
  241. errstr = None
  242. for key in new_config:
  243. if key == 'version':
  244. continue
  245. elif key in ['key_file', 'cert_file']:
  246. #TODO, only check whether the file exist,
  247. # further check need to be done: eg. whether
  248. # the private/certificate is valid.
  249. path = new_config[key]
  250. if not os.path.exists(path):
  251. errstr = "the file doesn't exist: " + path
  252. elif key == 'accounts_file':
  253. errstr = self._accounts_file_check(new_config[key])
  254. else:
  255. errstr = 'unknown config item: ' + key
  256. if errstr != None:
  257. logger.error(CMDCTL_BAD_CONFIG_DATA, errstr);
  258. return ccsession.create_answer(1, errstr)
  259. return ccsession.create_answer(0)
  260. def config_handler(self, new_config):
  261. answer = self._config_data_check(new_config)
  262. rcode, val = ccsession.parse_answer(answer)
  263. if rcode != 0:
  264. return answer
  265. with self._lock:
  266. for key in new_config:
  267. if key in self._cmdctl_config_data:
  268. self._cmdctl_config_data[key] = new_config[key]
  269. return answer
  270. def command_handler(self, command, args):
  271. answer = ccsession.create_answer(0)
  272. if command == ccsession.COMMAND_MODULE_SPECIFICATION_UPDATE:
  273. with self._lock:
  274. self.modules_spec[args[0]] = args[1]
  275. elif command == ccsession.COMMAND_SHUTDOWN:
  276. #When cmdctl get 'shutdown' command from boss,
  277. #shutdown the outer httpserver.
  278. self._httpserver.shutdown()
  279. self._serving = False
  280. elif command == 'print_settings':
  281. answer = ccsession.create_answer(0, self._cmdctl_config_data)
  282. else:
  283. answer = ccsession.create_answer(1, 'unknown command: ' + command)
  284. return answer
  285. def _start_msg_handle_thread(self):
  286. ''' Start one thread to handle received message from msgq.'''
  287. td = threading.Thread(target=self._handle_msg_from_msgq)
  288. td.daemon = True
  289. td.start()
  290. def _handle_msg_from_msgq(self):
  291. '''Process all the received commands with module session. '''
  292. while self._serving:
  293. self._module_cc.check_command(False)
  294. def _parse_command_result(self, rcode, reply):
  295. '''Ignore the error reason when command rcode isn't 0, '''
  296. if rcode != 0:
  297. return {}
  298. return reply
  299. def _get_config_data_from_config_manager(self):
  300. '''Get config data for all modules from configmanager '''
  301. rcode, reply = self.send_command('ConfigManager', ccsession.COMMAND_GET_CONFIG)
  302. return self._parse_command_result(rcode, reply)
  303. def _update_config_data(self, module_name, command_name):
  304. '''Get lastest config data for all modules from configmanager '''
  305. if module_name == 'ConfigManager' and command_name == ccsession.COMMAND_SET_CONFIG:
  306. data = self._get_config_data_from_config_manager()
  307. with self._lock:
  308. self._config_data = data
  309. def get_config_data(self):
  310. with self._lock:
  311. data = self._config_data
  312. return data
  313. def get_modules_spec(self):
  314. with self._lock:
  315. spec = self.modules_spec
  316. return spec
  317. def _get_modules_specification(self):
  318. '''Get all the modules' specification files. '''
  319. rcode, reply = self.send_command('ConfigManager', ccsession.COMMAND_GET_MODULE_SPEC)
  320. return self._parse_command_result(rcode, reply)
  321. def send_command_with_check(self, module_name, command_name, params = None):
  322. '''Before send the command to modules, check if module_name, command_name
  323. parameters are legal according the spec file of the module.
  324. Return rcode, dict. TODO, the rcode should be defined properly.
  325. rcode = 0: dict is the correct returned value.
  326. rcode > 0: dict is : { 'error' : 'error reason' }
  327. '''
  328. # core module ConfigManager does not have a specification file
  329. if module_name == 'ConfigManager':
  330. return self.send_command(module_name, command_name, params)
  331. specs = self.get_modules_spec()
  332. if module_name not in specs.keys():
  333. return 1, {'error' : 'unknown module'}
  334. spec_obj = isc.config.module_spec.ModuleSpec(specs[module_name], False)
  335. errors = []
  336. if not spec_obj.validate_command(command_name, params, errors):
  337. return 1, {'error': errors[0]}
  338. return self.send_command(module_name, command_name, params)
  339. def send_command(self, module_name, command_name, params = None):
  340. '''Send the command from bindctl to proper module. '''
  341. errstr = 'unknown error'
  342. answer = None
  343. logger.debug(DBG_CMDCTL_MESSAGING, CMDCTL_SEND_COMMAND,
  344. command_name, module_name)
  345. if module_name == self._module_name:
  346. # Process the command sent to cmdctl directly.
  347. answer = self.command_handler(command_name, params)
  348. else:
  349. msg = ccsession.create_command(command_name, params)
  350. seq = self._cc.group_sendmsg(msg, module_name)
  351. logger.debug(DBG_CMDCTL_MESSAGING, CMDCTL_COMMAND_SENT,
  352. command_name, module_name)
  353. #TODO, it may be blocked, msqg need to add a new interface waiting in timeout.
  354. try:
  355. answer, env = self._cc.group_recvmsg(False, seq)
  356. except isc.cc.session.SessionTimeout:
  357. errstr = "Module '%s' not responding" % module_name
  358. if answer:
  359. try:
  360. rcode, arg = ccsession.parse_answer(answer)
  361. if rcode == 0:
  362. self._update_config_data(module_name, command_name)
  363. if arg != None:
  364. return rcode, arg
  365. else:
  366. return rcode, {}
  367. else:
  368. errstr = str(answer['result'][1])
  369. except ccsession.ModuleCCSessionError as mcse:
  370. errstr = str("Error in ccsession answer:") + str(mcse)
  371. logger.error(CMDCTL_COMMAND_ERROR, command_name, module_name, errstr)
  372. return 1, {'error': errstr}
  373. def get_cmdctl_config_data(self):
  374. ''' If running in source code tree, use keyfile, certificate
  375. and user accounts file in source code. '''
  376. if "B10_FROM_SOURCE" in os.environ:
  377. sysconf_path = os.environ["B10_FROM_SOURCE"] + "/src/bin/cmdctl/"
  378. accountsfile = sysconf_path + "cmdctl-accounts.csv"
  379. keyfile = sysconf_path + "cmdctl-keyfile.pem"
  380. certfile = sysconf_path + "cmdctl-certfile.pem"
  381. return (keyfile, certfile, accountsfile)
  382. with self._lock:
  383. keyfile = self._cmdctl_config_data.get('key_file')
  384. certfile = self._cmdctl_config_data.get('cert_file')
  385. accountsfile = self._cmdctl_config_data.get('accounts_file')
  386. return (keyfile, certfile, accountsfile)
  387. class SecureHTTPServer(socketserver_mixin.NoPollMixIn,
  388. socketserver.ThreadingMixIn,
  389. http.server.HTTPServer):
  390. '''Make the server address can be reused.'''
  391. allow_reuse_address = True
  392. def __init__(self, server_address, RequestHandlerClass,
  393. CommandControlClass,
  394. idle_timeout = 1200, verbose = False):
  395. '''idle_timeout: the max idle time for login'''
  396. socketserver_mixin.NoPollMixIn.__init__(self)
  397. try:
  398. http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass)
  399. logger.debug(DBG_CMDCTL_MESSAGING, CMDCTL_STARTED,
  400. server_address[0], server_address[1])
  401. except socket.error as err:
  402. raise CmdctlException("Error creating server, because: %s \n" % str(err))
  403. self.user_sessions = {}
  404. self.idle_timeout = idle_timeout
  405. self.cmdctl = CommandControlClass(self, verbose)
  406. self._verbose = verbose
  407. self._lock = threading.Lock()
  408. self._user_infos = {}
  409. self._accounts_file = None
  410. def _create_user_info(self, accounts_file):
  411. '''Read all user's name and its' salt, hashed password
  412. from accounts file.'''
  413. if (self._accounts_file == accounts_file) and (len(self._user_infos) > 0):
  414. return
  415. with self._lock:
  416. self._user_infos = {}
  417. csvfile = None
  418. try:
  419. csvfile = open(accounts_file)
  420. reader = csv.reader(csvfile)
  421. for row in reader:
  422. self._user_infos[row[0]] = [row[1], row[2]]
  423. except (IOError, IndexError) as e:
  424. logger.error(CMDCTL_USER_DATABASE_READ_ERROR,
  425. accounts_file, e)
  426. finally:
  427. if csvfile:
  428. csvfile.close()
  429. self._accounts_file = accounts_file
  430. if len(self._user_infos) == 0:
  431. logger.error(CMDCTL_NO_USER_ENTRIES_READ)
  432. def get_user_info(self, username):
  433. '''Get user's salt and hashed string. If the user
  434. doesn't exist, return None, or else, the list
  435. [salt, hashed password] will be returned.'''
  436. with self._lock:
  437. info = self._user_infos.get(username)
  438. return info
  439. def save_user_session_id(self, session_id):
  440. ''' Record user's id and login time. '''
  441. self.user_sessions[session_id] = time.time()
  442. def _check_key_and_cert(self, key, cert):
  443. # TODO, check the content of key/certificate file
  444. if not os.path.exists(key):
  445. raise CmdctlException("key file '%s' doesn't exist " % key)
  446. if not os.path.exists(cert):
  447. raise CmdctlException("certificate file '%s' doesn't exist " % cert)
  448. def _wrap_socket_in_ssl_context(self, sock, key, cert):
  449. try:
  450. self._check_key_and_cert(key, cert)
  451. ssl_sock = ssl.wrap_socket(sock,
  452. server_side = True,
  453. certfile = cert,
  454. keyfile = key,
  455. ssl_version = ssl.PROTOCOL_SSLv23)
  456. return ssl_sock
  457. except (ssl.SSLError, CmdctlException) as err :
  458. logger.info(CMDCTL_SSL_SETUP_FAILURE_USER_DENIED, err)
  459. self.close_request(sock)
  460. # raise socket error to finish the request
  461. raise socket.error
  462. def get_request(self):
  463. '''Get client request socket and wrap it in SSL context. '''
  464. key, cert, account_file = self.cmdctl.get_cmdctl_config_data()
  465. self._create_user_info(account_file)
  466. newsocket, fromaddr = self.socket.accept()
  467. ssl_sock = self._wrap_socket_in_ssl_context(newsocket, key, cert)
  468. return (ssl_sock, fromaddr)
  469. def get_reply_data_for_GET(self, id, module):
  470. '''Currently only support the following three url GET request '''
  471. rcode, reply = http.client.NO_CONTENT, []
  472. if not module:
  473. if id == CONFIG_DATA_URL:
  474. rcode, reply = http.client.OK, self.cmdctl.get_config_data()
  475. elif id == MODULE_SPEC_URL:
  476. rcode, reply = http.client.OK, self.cmdctl.get_modules_spec()
  477. return rcode, reply
  478. def send_command_to_module(self, module_name, command_name, params):
  479. return self.cmdctl.send_command_with_check(module_name, command_name, params)
  480. httpd = None
  481. def signal_handler(signal, frame):
  482. if httpd:
  483. httpd.shutdown()
  484. sys.exit(0)
  485. def set_signal_handler():
  486. signal.signal(signal.SIGTERM, signal_handler)
  487. signal.signal(signal.SIGINT, signal_handler)
  488. def run(addr = 'localhost', port = 8080, idle_timeout = 1200, verbose = False):
  489. ''' Start cmdctl as one https server. '''
  490. httpd = SecureHTTPServer((addr, port), SecureHTTPRequestHandler,
  491. CommandControl, idle_timeout, verbose)
  492. httpd.serve_forever()
  493. def check_port(option, opt_str, value, parser):
  494. try:
  495. parser.values.port = isc.net.parse.port_parse(value)
  496. except ValueError as e:
  497. raise OptionValueError(str(e))
  498. def check_addr(option, opt_str, value, parser):
  499. try:
  500. isc.net.parse.addr_parse(value)
  501. parser.values.addr = value
  502. except ValueError as e:
  503. raise OptionValueError(str(e))
  504. def set_cmd_options(parser):
  505. parser.add_option('-p', '--port', dest = 'port', type = 'int',
  506. action = 'callback', callback=check_port,
  507. default = '8080', help = 'port cmdctl will use')
  508. parser.add_option('-a', '--address', dest = 'addr', type = 'string',
  509. action = 'callback', callback=check_addr,
  510. default = '127.0.0.1', help = 'IP address cmdctl will use')
  511. parser.add_option('-i', '--idle-timeout', dest = 'idle_timeout', type = 'int',
  512. default = '1200', help = 'login idle time out')
  513. parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
  514. help="display more about what is going on")
  515. if __name__ == '__main__':
  516. set_signal_handler()
  517. parser = OptionParser(version = __version__)
  518. set_cmd_options(parser)
  519. (options, args) = parser.parse_args()
  520. result = 1 # in case of failure
  521. try:
  522. if options.verbose:
  523. logger.set_severity("DEBUG", 99)
  524. run(options.addr, options.port, options.idle_timeout, options.verbose)
  525. result = 0
  526. except isc.cc.SessionError as err:
  527. logger.fatal(CMDCTL_CC_SESSION_ERROR, err)
  528. except isc.cc.SessionTimeout:
  529. logger.fatal(CMDCTL_CC_SESSION_TIMEOUT)
  530. except KeyboardInterrupt:
  531. logger.info(CMDCTL_STOPPED_BY_KEYBOARD)
  532. except CmdctlException as err:
  533. logger.fatal(CMDCTL_UNCAUGHT_EXCEPTION, err);
  534. if httpd:
  535. httpd.shutdown()
  536. sys.exit(result)