def __init__(self, args):
        settings, args = SynthesisServer.process_command_line(args)
        self.dbconn = DBConnector()
        self.basevm_list = self.check_basevm()

        Synthesis_Const.LOCAL_IPADDRESS = "0.0.0.0"
        server_address = (Synthesis_Const.LOCAL_IPADDRESS, Synthesis_Const.SERVER_PORT_NUMBER)

        self.allow_reuse_address = True
        try:
            SocketServer.TCPServer.__init__(self, server_address, SynthesisHandler)
        except socket.error as e:
            sys.stderr.write(str(e))
            sys.stderr.write("Check IP/Port : %s\n" % (str(server_address)))
            sys.exit(1)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        Log.write("* Server configuration\n")
        Log.write(" - Open TCP Server at %s\n" % (str(server_address)))
        Log.write(" - Disable Nalge(No TCP delay)  : %s\n" \
                % str(self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY)))
        Log.write("-"*50)
        Log.write("\n")

        # Start UPnP Server
        try:
            self.upnp_server = UPnPServer()
            self.upnp_server.start()
        except UPnPError as e:
            Log.write(str(e))
            Log.write("[Warning] Cannot start UPnP Server\n")
            self.upnp_server = None
        Log.write("[INFO] Start UPnP Server\n")

        # Start registration client
        if settings.register_server:
            try:
                self.register_client = RegisterThread(
                        settings.register_server,
                        log=Log,
                        update_period=Synthesis_Const.DIRECTORY_UPDATE_PERIOD)
                self.register_client.start()
                Log.write("[INFO] Register to Cloudlet direcory service\n")
            except RegisterError as e:
                Log.write(str(e))
                Log.write("[Warning] Cannot register Cloudlet to central server\n")

        # cloudlet machine monitor
        try:
            self.resource_monitor = ResourceMonitorThread(log=Log) 
            self.resource_monitor.start()
        except ResourceMonitorError as e:
            Log.write(str(e))
            Log.write("[Warning] Cannot register Cloudlet to central server\n")
        Log.flush()
class SynthesisServer(SocketServer.TCPServer):

    def __init__(self, args):
        settings, args = SynthesisServer.process_command_line(args)
        self.dbconn = DBConnector()
        self.basevm_list = self.check_basevm()

        Synthesis_Const.LOCAL_IPADDRESS = "0.0.0.0"
        server_address = (Synthesis_Const.LOCAL_IPADDRESS, Synthesis_Const.SERVER_PORT_NUMBER)

        self.allow_reuse_address = True
        try:
            SocketServer.TCPServer.__init__(self, server_address, SynthesisHandler)
        except socket.error as e:
            sys.stderr.write(str(e))
            sys.stderr.write("Check IP/Port : %s\n" % (str(server_address)))
            sys.exit(1)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        Log.write("* Server configuration\n")
        Log.write(" - Open TCP Server at %s\n" % (str(server_address)))
        Log.write(" - Disable Nalge(No TCP delay)  : %s\n" \
                % str(self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY)))
        Log.write("-"*50)
        Log.write("\n")

        # Start UPnP Server
        try:
            self.upnp_server = UPnPServer()
            self.upnp_server.start()
        except UPnPError as e:
            Log.write(str(e))
            Log.write("[Warning] Cannot start UPnP Server\n")
            self.upnp_server = None
        Log.write("[INFO] Start UPnP Server\n")

        # Start registration client
        if settings.register_server:
            try:
                self.register_client = RegisterThread(
                        settings.register_server,
                        log=Log,
                        update_period=Synthesis_Const.DIRECTORY_UPDATE_PERIOD)
                self.register_client.start()
                Log.write("[INFO] Register to Cloudlet direcory service\n")
            except RegisterError as e:
                Log.write(str(e))
                Log.write("[Warning] Cannot register Cloudlet to central server\n")

        # cloudlet machine monitor
        try:
            self.resource_monitor = ResourceMonitorThread(log=Log) 
            self.resource_monitor.start()
        except ResourceMonitorError as e:
            Log.write(str(e))
            Log.write("[Warning] Cannot register Cloudlet to central server\n")
        Log.flush()

    def handle_error(self, request, client_address):
        #SocketServer.TCPServer.handle_error(self, request, client_address)
        #sys.stderr.write("handling error from client %s\n" % (str(client_address)))
        pass

    def expire_all_sessions(self):
        from db.table_def import Session

        Log.write("[TERMINATE] Close all running sessions\n")
        session_list = self.dbconn.list_item(Session)
        for item in session_list:
            if item.status == Session.STATUS_RUNNING:
                item.terminate(Session.STATUS_UNEXPECT_CLOSE)
        self.dbconn.session.commit()


    def terminate(self):
        # expire all existing session
        self.expire_all_sessions()

        # close all thread
        if self.socket != -1:
            self.socket.close()
        if hasattr(self, 'upnp_server') and self.upnp_server != None:
            Log.write("[TERMINATE] Terminate UPnP Server\n")
            self.upnp_server.terminate()
            self.upnp_server.join()
        if hasattr(self, 'register_client') and self.register_client != None:
            Log.write("[TERMINATE] Deregister from directory service\n")
            self.register_client.terminate()
            self.register_client.join()
        if hasattr(self, 'resource_monitor') and self.resource_monitor != None:
            Log.write("[TERMINATE] Terminate resource monitor\n")
            self.resource_monitor.terminate()
            self.resource_monitor.join()
        Log.write("[TERMINATE] Finish synthesis server connection\n")

    @staticmethod
    def process_command_line(argv):
        global operation_mode

        parser = OptionParser(usage="usage: %prog " + " [option]",
                version="Rapid VM Synthesis(piping) 0.1")
        parser.add_option(
                '-r', '--register-server', action='store', dest='register_server',
                default=None, help= 'Domain address for registration server.\n \
                        Specify this if you like to register your \
                        Cloudlet to registration server.')
        settings, args = parser.parse_args(argv)
        return settings, args

    def check_basevm(self):
        basevm_list = self.dbconn.list_item(BaseVM)
        ret_list = list()
        print "-"*50
        print "* Base VM Configuration"
        for index, item in enumerate(basevm_list):
            # check file location
            (base_diskmeta, base_mempath, base_memmeta) = \
                    Cloudlet_Const.get_basepath(item.disk_path)
            if not os.path.exists(item.disk_path):
                Log.write("[Warning] disk image (%s) is not exist\n" % (item.disk_path))
                continue
            if not os.path.exists(base_mempath):
                Log.write("[Warning] memory snapshot (%s) is not exist\n" % (base_mempath))
                continue

            # add to list
            ret_list.append(item)
            print " %d : %s (Disk %d MB, Memory %d MB)" % \
                    (index, item.disk_path, os.path.getsize(item.disk_path)/1024/1024, \
                    os.path.getsize(base_mempath)/1024/1024)
        print "-"*50

        if len(ret_list) == 0:
            Log.write("[Error] NO valid Base VM\n")
            sys.exit(2)
        return ret_list