cmdctl.py.in 24 KB

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