def start_up(self): Context.Log.info('init tasklet run ...') params = { 'redis.config': { 'host': self.redis_host, 'port': self.redis_port, 'db': self.redis_db, } } from framework import init_context init_context(params['redis.config']) self.gdata.server = self self.gdata.server_id = self.server_id Context.GData.init_data() if Context.GData.server_type != FlagType.flag_type_sdk: from lemon import init_game init_game(Context.GData.server_type) if self.innerProtocol: self.connect_service() if Context.GData.server_type not in (FlagType.flag_type_http, FlagType.flag_type_shell): self.listen_inner_tcp(self.listen_port) if self.httpFactory: self.listen_http(self.listen_port) if self.outerProtocol: self.listen_tcp(self.listen_port + 1) key = 'script:%s:%s:%s' % (self.redis_host, self.redis_port, self.redis_db) Context.RedisConfig.hash_set(key, self.proc_key, Context.Time.current_time()) TaskManager.set_interval(self.server_heart_beat, 3, 10) Context.Log.info('service start success ...')
def server_heart_beat(self): self.__heart_beat += 1 if self.innerProtocol: if getattr(self.innerProtocol, 'makeTasklet', None): t = self.innerProtocol().makeTasklet(0, None, None) if getattr(t, 'on_server_heart_beat', None): TaskManager.add_task(t.on_server_heart_beat) TaskManager.add_simple_task(Context.Configure.reload)
def receiveDone(self, request): try: tasklet = self.makeTasklet(request) TaskManager.add_task(tasklet.run) TaskManager.schedule() except Exception, e: Logger.exception() body, content_type = http_response_500(self.request) Logger.debug('<====', self.request.path, content_type, repr(body))
def terminate_connection(self): if self.userId > 0: if self.userId in Context.GData.map_client_connect: del Context.GData.map_client_connect[self.userId] msg = MsgPack(Message.MSG_INNER_BROKEN) msg.set_param('userId', self.userId) if self.gameId > 0: msg.set_param('gameId', self.gameId) tasklet = self.makeTasklet(Message.MSG_INNER_BROKEN, msg, self) TaskManager.run_task(tasklet) self.logout() self.transport.loseConnection()
def gm_notice_global(self, gid, mi, request): led = mi.get_param('led') start = mi.get_param('start') end = mi.get_param('end') now_ts = Time.current_ts() if now_ts > end: return MsgPack(0) Context.RedisCache.hash_mset('global.notice', 'led', led, 'start', start, 'end', end) if now_ts >= start: self._do_notice(led, end) return MsgPack(0) TaskManager.set_timeout(self.do_notice, start-now_ts, led, end) return MsgPack(0)
def main(): if sys.argv[1] not in ('game', 'sdk', 'shell'): raise Exception('game, sdk or shell please !!!') service_type = sys.argv[1] params = parse_cmd_lines() if params.get('help'): useage() else: get_user_name(params) tasks = [] if 'service_file' in params: tasks.append('load_server') tasks.append('log_conf') tasks.append('copy_file') tasks.append('build_shell') tasks.append('load_config') tasks.append('init_context') tasks.append('load_lua') tasks.append('make_end') action = params.get('action') if action == 'start': tasks.append('stop') tasks.append('push_config') if service_type == 'game': tasks.append('make_clear') tasks.append('start') elif service_type == 'sdk': tasks.append('start') elif service_type == 'shell': tasks.append('start') elif action == 'stop': tasks.append('stop') if not tasks: useage() else: Log.log('begin start') Log.log('=================================================') for step, task in enumerate(tasks, 1): Log.log('---------%2s/%s: %s_%s' % (step, len(tasks), service_type, task)) func = None exec 'from task.task_%s import %s_%s as func' % ( task, service_type, task) if func(params): raise Exception('start failed !!!') Log.log('=================================================') Log.log('start done') TaskManager.add_simple_task(TaskManager.end_loop)
def dataReceived(self, data): self._data += data while len(self._data) > 8: cmd, msg_len = struct.unpack('II', self._data[:8]) if msg_len > len(self._data) - 8: return body_data = self._data[8:8 + msg_len] self._data = self._data[8 + msg_len:] try: self.access_ts = Time.current_ts() tasklet = self.makeTasklet(cmd, body_data, self) TaskManager.add_task(tasklet.run, peer=self.peer_key) except Exception, e: Logger.exception(body_data) self.transport.loseConnection()
def setInterval(self, interval, param, delay=None, *args, **kwargs): self.type = self.TIMER_LOOP self.second = interval msg = MsgPack(Message.MSG_INNER_TIMER, param) uid = msg.get_param('userId') gid = msg.get_param('gameId') msg = MsgLine(msg.pack(), gid, target=uid).pack() task = self.tasklet(Message.to_inner(Message.MSG_INNER_TIMER), msg, None).run if delay is None: self.timer = TaskManager.call_later(self.__timeout, self.second, msg, task, *args, **kwargs) else: self.timer = TaskManager.call_later(self.__timeout, delay, msg, task, *args, **kwargs) return True
def execute(self, *args, **kwargs): tasklet = TaskManager.current() # d = self.__redisPool__.execute_command(*args, **kwargs) d = self.__redisPool__.client.send(*args) result = tasklet.wait_for_deferred(d) Logger.debug_redis(self.__redis_key__, args, kwargs, '=>', result) return result
def connect(self, *args): if len(args) == 1: host = str(args[0]['host']) port = int(args[0]['port']) db = int(args[0]['db']) elif len(args) == 3: host = str(args[0]) port = int(args[1]) db = int(args[2]) else: raise Exception( "error args, connect(ip, port, db) or connect({'host': host, 'port': port, 'db': db}" ) self.__redis_key__ = 'redis:%s:%s:%s' % (host, port, db) if self.__redis_key__ in self.__CONNECT_REDIS__: self.__redisPool__ = self.__CONNECT_REDIS__[ self.__redis_key__].__redisPool__ self.__sha_map__ = self.__CONNECT_REDIS__[ self.__redis_key__].__sha_map__ return self.__CONNECT_REDIS__[self.__redis_key__] else: tasklet = TaskManager.current() factory = RedisClientFactory(db=db) reactor.connectTCP(host, port, factory) tasklet.wait_for_deferred(factory.deferred) self.__redisPool__ = factory self.__CONNECT_REDIS__[self.__redis_key__] = self return self.__CONNECT_REDIS__[self.__redis_key__]
def connectionLost(self, reason=connectionDone): try: Logger.info('ConnectionLost', 'userId =', self.userId) if self.userId > 0: msg = MsgPack(Message.MSG_INNER_BROKEN) if self.userId in Context.GData.map_client_connect: del Context.GData.map_client_connect[self.userId] msg.set_param('userId', self.userId) if self.gameId > 0: msg.set_param('gameId', self.gameId) tasklet = self.makeTasklet(Message.MSG_INNER_BROKEN, msg, self) TaskManager.add_task(tasklet.run) else: Logger.debug_network('empty user connection lost ... ') except Exception, e: Logger.exception()
def setTimeout(self, second, param, *args, **kwargs): self.type = self.TIMER_ONCE self.second = second msg = MsgPack(Message.MSG_INNER_TIMER, param) uid = msg.get_param('userId') gid = msg.get_param('gameId') msg = MsgLine(msg.pack(), gid, target=uid).pack() task = self.tasklet(Message.to_inner(Message.MSG_INNER_TIMER), msg, None).run self.timer = TaskManager.call_later(self.__timeout, second, msg, task, *args, **kwargs) return True
def start(self): Context.Log.info('service starting ...') Context.Log.info('InitParams log file =', self.log_path) Context.Log.info('InitParams proc key =', self.proc_key) Context.Log.info('InitParams redis host =', self.redis_host) Context.Log.info('InitParams redis port =', self.redis_port) Context.Log.info('InitParams redis db =', self.redis_db) Context.Log.info('InitParams listen port =', self.listen_port) Context.Log.info('InitParams server id =', self.server_id) Context.Log.info('InitParams tcpProtocol =', self.innerProtocol) Context.Log.info('InitParams udpProtocol =', self.outerProtocol) Context.Log.info('InitParams httpFactory =', self.httpFactory) Context.Log.info('init tasklet startup ...') try: TaskManager.add_simple_task(self.start_up) TaskManager.start_loop() Context.Log.info('service stop ...') except Exception, e: Context.Log.exception()
class ServerTcpProtocol(BasicTcpProtocol, _PauseableMixin): def __init__(self): BasicTcpProtocol.__init__(self) self._data = '' self.access_ts = Time.current_ts() def dataReceived(self, data): self._data += data while len(self._data) > 8: cmd, msg_len = struct.unpack('II', self._data[:8]) if msg_len > len(self._data) - 8: return body_data = self._data[8:8 + msg_len] self._data = self._data[8 + msg_len:] try: self.access_ts = Time.current_ts() tasklet = self.makeTasklet(cmd, body_data, self) TaskManager.add_task(tasklet.run, peer=self.peer_key) except Exception, e: Logger.exception(body_data) self.transport.loseConnection() TaskManager.schedule() return False
def __timeout(self, msg, task, *args, **kwargs): try: TaskManager.add_task(task) except Exception, e: Logger.exception(args)
def do_notice(self, led, end): TaskManager.add_simple_task(self._do_notice, led, end)
def tasklet(self): from framework.entity.manager import TaskManager return TaskManager.current()
class GameTimer(object): TIMER_ONCE = 1 TIMER_LOOP = 2 def __init__(self, tasklet=None): self.type = None self.second = None self.timer = None if tasklet is None: from lemon.tasklet.game import GameTasklet self.tasklet = GameTasklet else: self.tasklet = tasklet def setTimeout(self, second, param, *args, **kwargs): self.type = self.TIMER_ONCE self.second = second msg = MsgPack(Message.MSG_INNER_TIMER, param) uid = msg.get_param('userId') gid = msg.get_param('gameId') msg = MsgLine(msg.pack(), gid, target=uid).pack() task = self.tasklet(Message.to_inner(Message.MSG_INNER_TIMER), msg, None).run self.timer = TaskManager.call_later(self.__timeout, second, msg, task, *args, **kwargs) return True def setInterval(self, interval, param, delay=None, *args, **kwargs): self.type = self.TIMER_LOOP self.second = interval msg = MsgPack(Message.MSG_INNER_TIMER, param) uid = msg.get_param('userId') gid = msg.get_param('gameId') msg = MsgLine(msg.pack(), gid, target=uid).pack() task = self.tasklet(Message.to_inner(Message.MSG_INNER_TIMER), msg, None).run if delay is None: self.timer = TaskManager.call_later(self.__timeout, self.second, msg, task, *args, **kwargs) else: self.timer = TaskManager.call_later(self.__timeout, delay, msg, task, *args, **kwargs) return True def getTimerType(self): return self.type def getLeftTime(self): if self.type is None: return None else: return self.timer.getTime() def getInterval(self): if self.type is None: return None return self.second def delay(self, second): try: return self.timer.delay(second) except: return None def reset(self, second): try: self.timer.reset(second) self.second = second return True except: return False def cancel(self): try: if self.timer: self.timer.cancel() self.type = None return True except: return False def IsActive(self): try: return self.timer.active() except: return False def __timeout(self, msg, task, *args, **kwargs): try: TaskManager.add_task(task) except Exception, e: Logger.exception(args) if self.type == self.TIMER_LOOP: self.timer = TaskManager.call_later(self.__timeout, self.second, msg, task, *args, **kwargs)
tasks.append('make_clear') tasks.append('start') elif service_type == 'sdk': tasks.append('start') elif service_type == 'shell': tasks.append('start') elif action == 'stop': tasks.append('stop') if not tasks: useage() else: Log.log('begin start') Log.log('=================================================') for step, task in enumerate(tasks, 1): Log.log('---------%2s/%s: %s_%s' % (step, len(tasks), service_type, task)) func = None exec 'from task.task_%s import %s_%s as func' % ( task, service_type, task) if func(params): raise Exception('start failed !!!') Log.log('=================================================') Log.log('start done') TaskManager.add_simple_task(TaskManager.end_loop) if __name__ == '__main__': TaskManager.add_simple_task(main) TaskManager.start_loop()