Commit cc002a46 authored by Likun Zhang's avatar Likun Zhang
Browse files

Add verbose option for the messages printted by module cmdctl and xfrin.

git-svn-id: svn://bind10.isc.org/svn/bind10/trunk@1475 e5f2f494-b856-4b98-b285-d166d9295462
parent 1e1f5433
......@@ -155,6 +155,7 @@ class SecureHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
def _check_user_name_and_pwd(self):
'''Check user name and its password '''
length = self.headers.get('Content-Length')
if not length:
return False, ["invalid username or password"]
......@@ -196,7 +197,9 @@ class SecureHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
pass
rcode, reply = self.server.send_command_to_module(mod, cmd, param)
print('b10-cmdctl finish send message \'%s\' to module %s' % (cmd, mod))
if self.server._verbose:
print('[b10-cmdctl] Finish send message \'%s\' to module %s' % (cmd, mod))
ret = http.client.OK
if rcode != 0:
ret = http.client.BAD_REQUEST
......@@ -212,10 +215,10 @@ class CommandControl():
receive command from client and resend it to proper module.
'''
def __init__(self):
def __init__(self, verbose = False):
self._verbose = verbose
self.cc = isc.cc.Session()
self.cc.group_subscribe('Cmd-Ctrld')
#self.cc.group_subscribe('Boss', 'Cmd-Ctrld')
self.command_spec = self.get_cmd_specification()
self.config_spec = self.get_data_specification()
self.config_data = self.get_config_data()
......@@ -235,6 +238,7 @@ class CommandControl():
rcode, reply = self.send_command('ConfigManager', isc.config.ccsession.COMMAND_GET_CONFIG)
return self._parse_command_result(rcode, reply)
def update_config_data(self, module_name, command_name):
'''Get lastest config data for all modules from configmanager '''
if module_name == 'ConfigManager' and command_name == isc.config.ccsession.COMMAND_SET_CONFIG:
......@@ -293,7 +297,8 @@ class CommandControl():
'''Send the command from bindctl to proper module. '''
errstr = 'no error'
print('b10-cmdctl send command \'%s\' to %s' %(command_name, module_name))
if self._verbose:
self.log_info('[b10-cmdctl] send command \'%s\' to %s\n' %(command_name, module_name))
try:
msg = isc.config.ccsession.create_command(command_name, params)
seq = self.cc.group_sendmsg(msg, module_name)
......@@ -313,19 +318,21 @@ class CommandControl():
errstr = str(answer['result'][1])
except isc.config.ccsession.ModuleCCSessionError as mcse:
errstr = str("Error in ccsession answer:") + str(mcse)
print(answer)
self.log_info(answer)
except Exception as e:
errstr = str(e)
print(e, ':b10-cmdctl fail send command \'%s\' to %s' % (command_name, module_name))
self.log_info('\'%s\':[b10-cmdctl] fail send command \'%s\' to %s\n' % (e, command_name, module_name))
return 1, {'error': errstr}
def log_info(self, msg):
sys.stdout.write(msg)
class SecureHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
'''Make the server address can be reused.'''
allow_reuse_address = True
def __init__(self, server_address, RequestHandlerClass, idle_timeout = 1200):
def __init__(self, server_address, RequestHandlerClass, idle_timeout = 1200, verbose = False):
'''idle_timeout: the max idle time for login'''
http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass)
self.user_sessions = {}
......@@ -333,6 +340,7 @@ class SecureHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
self.cmdctrl = CommandControl()
self.__is_shut_down = threading.Event()
self.__serving = False
self._verbose = verbose
self.user_infos = {}
self._read_user_info()
......@@ -345,7 +353,7 @@ class SecureHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
for row in reader:
self.user_infos[row[0]] = [row[1], row[2]]
except Exception as e:
print("Fail to read user information ", e)
self.log_info('[b10-cmdctl] Fail to read user information :\'%s\'\n' % e)
finally:
if csvfile:
csvfile.close()
......@@ -365,7 +373,7 @@ class SecureHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
ssl_version = ssl.PROTOCOL_SSLv23)
return (connstream, fromaddr)
except ssl.SSLError as e :
print("cmdctl: deny client's invalid connection", e)
self.log_info('[b10-cmdctl] deny client\'s invalid connection:\'%s\'\n' % e)
self.close_request(newsocket)
# raise socket error to finish the request
raise socket.error
......@@ -406,6 +414,9 @@ class SecureHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
def send_command_to_module(self, module_name, command_name, params):
return self.cmdctrl.send_command_with_check(module_name, command_name, params)
def log_info(self, msg):
sys.stdout.write(msg)
httpd = None
......@@ -418,10 +429,11 @@ def set_signal_handler():
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
def run(addr = 'localhost', port = 8080, idle_timeout = 1200):
def run(addr = 'localhost', port = 8080, idle_timeout = 1200, verbose = False):
''' Start cmdctl as one https server. '''
print("b10-cmdctl module is starting on :%s port:%d" %(addr, port))
httpd = SecureHTTPServer((addr, port), SecureHTTPRequestHandler, idle_timeout)
if verbose:
sys.stdout.write("[b10-cmdctl] starting on :%s port:%d\n" %(addr, port))
httpd = SecureHTTPServer((addr, port), SecureHTTPRequestHandler, idle_timeout, verbose)
httpd.serve_forever()
def check_port(option, opt_str, value, parser):
......@@ -463,10 +475,10 @@ if __name__ == '__main__':
set_signal_handler()
run(options.addr, options.port, options.idle_timeout)
except isc.cc.SessionError as se:
print("[b10-cmdctl] Error creating b10-cmdctl, "
"is the command channel daemon running?")
sys.stderr.write("[b10-cmdctl] Error creating b10-cmdctl, "
"is the command channel daemon running?\n")
except KeyboardInterrupt:
print("exit http server")
sys.stderr.write("[b10-cmdctl] exit http server\n")
if httpd:
httpd.shutdown()
......
......@@ -25,6 +25,7 @@ import struct
import threading
import socket
import random
from optparse import OptionParser, OptionValueError
from isc.config.ccsession import *
try:
from bind10_message import *
......@@ -56,6 +57,12 @@ XFRIN_QUERY_SOA = 1
XFRIN_FIRST_AXFR = 2
XFRIN_FIRST_IXFR = 3
def log_error(msg):
sys.stderr.write("[b10-xfrin] ")
sys.stderr.write(msg)
sys.stderr.write('\n')
class XfrinException(Exception):
pass
......@@ -68,7 +75,8 @@ class XfrinConnection(asyncore.dispatcher):
master_addr,
port = 53,
check_soa = True,
idle_timeout = 60):
verbose = False,
idle_timeout = 60):
''' idle_timeout: max idle time for read data from socket.
db_file: specify the data source file.
check_soa: when it's true, check soa first before sending xfr query
......@@ -82,7 +90,7 @@ class XfrinConnection(asyncore.dispatcher):
self.setblocking(1)
self.connect((master_addr, port))
self._shutdown_event = shutdown_event
self._verbose = verbose
def _create_query(self, query_type):
'''Create dns query message. '''
......@@ -115,7 +123,7 @@ class XfrinConnection(asyncore.dispatcher):
self._send_data(header_len)
self._send_data(obuf.get_data())
def _get_request_response(self, size):
recv_size = 0
data = b''
......@@ -152,23 +160,22 @@ class XfrinConnection(asyncore.dispatcher):
#serial
return XFRIN_OK
def do_xfrin(self, check_soa, ixfr_first = False):
try:
ret = XFRIN_OK
if check_soa:
ret = self._check_soa_serial()
print('[xfrin] transfer of \'%s\': AXFR started' % self._zone_name)
self.log_msg('transfer of \'%s\': AXFR started' % self._zone_name)
if ret == XFRIN_OK:
self._send_query(rr_type.AXFR())
ret = self._handle_xfrin_response()
self._insert_record_to_sqlite3(self._records)
print('[xfrin] transfer of \'%s\' AXFR ended' % self._zone_name)
self.log_msg('transfer of \'%s\' AXFR ended' % self._zone_name)
except XfrinException as e:
print(e)
print('[xfrin] Error happened during xfrin!')
self.log_msg(e)
self.log_msg('Error happened during xfrin!')
#TODO, recover data source.
finally:
self.close()
......@@ -252,20 +259,25 @@ class XfrinConnection(asyncore.dispatcher):
return False
def log_info(self, msg, type = ''):
def log_info(self, msg):
# Overwrite the log function, log nothing
pass
def log_msg(self, msg):
sys.stdout.write('[b10-xfrin] ')
sys.stdout.write(msg)
sys.stdout.write('\n')
def process_xfrin(xfrin_recorder, zone_name, db_file,
shutdown_event, master_addr, port, check_soa):
shutdown_event, master_addr, port, check_soa, verbose):
xfrin_recorder.increment(name)
try:
conn = XfrinConnection(zone_name, db_file, shutdown_event,
master_addr, int(port), check_soa)
master_addr, int(port), check_soa, verbose)
conn.do_xfrin(False)
except Exception as e:
print('[xfrin] Error happened:', e)
log_error(e)
xfrin_recorder.decrement(zone_name)
......@@ -299,12 +311,13 @@ class XfrinRecorder():
return ret
class Xfrin():
def __init__(self):
def __init__(self, verbose = False):
self._cc = isc.config.ModuleCCSession(SPECFILE_LOCATION, self.config_handler, self.command_handler)
self._cc.start()
self._max_transfers_in = 10
self.recorder = XfrinRecorder()
self._shutdown_event = threading.Event()
self._verbose = verbose
def config_handler(self, new_config):
......@@ -400,7 +413,8 @@ class Xfrin():
db_file,
self._shutdown_event,
master_addr,
port, check_soa))
port, check_soa, self._verbose))
xfrin_thread.start()
return (0, 'zone xfrin is started')
......@@ -431,18 +445,27 @@ def check_addr(ipstr):
raise XfrinException("%s invalid ip address" % ipstr)
def set_cmd_options(parser):
parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
help="display more about what is going on")
if __name__ == '__main__':
try:
parser = OptionParser(version = __version__)
set_cmd_options(parser)
(options, args) = parser.parse_args()
set_signal_handler()
xfrind = Xfrin()
xfrind = Xfrin(verbose = options.verbose)
xfrind.startup()
except KeyboardInterrupt:
print("exit http server")
log_error("exit b10-xfrin")
except isc.cc.session.SessionError as e:
print(e)
print('[b10-xfrin] Error happened! is the command channel daemon running?')
log_error(e)
log_error('Error happened! is the command channel daemon running?')
except Exception as e:
print(e)
log_error(e)
if xfrind:
xfrind.shutdown()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment