def sync(self): if not self.synced: try: redis.hset(DICT_LOVER_KISS, self.cid, dumps(self.value)) except: log.exception('cid:{0} status save failed. status:{1}.'.format( self.cid, self.value))
def _do_image(self, request): if request.method == 'POST': try: action = request.POST.get('action') if action == 'Start Play': uid = request.POST.get('uid') device_idx = request.POST.get('device_idx') airplay.send_image(uid, int(device_idx)) elif action == 'Refresh Device' and \ settings.get('airplay', 'enable') == 'True': airplay.discovery() except: log.exception('Fail to airplay send_image') self.args['id'] = str(request.GET.get('id', content.IMAGE)) self.args['devices'] = airplay.devices self._prepare_browse(request) if self.args['self'].get('child_container_count', 0) != 0: for row in self.args['rows']: self._pretty_format(request, row) else: self.args['view_mode'] = 'on' content.sort(self.args['rows'], 'ratio') for row in self.args['rows']: row['thumbnail_width'], row['thumbnail_height'] = \ get_resize(row.get('width', 0), row.get('height', 0), 180, 135) self.args['cur_menu'] = 'image' return ('image.html', self.args)
def gs_gm_sync_world_boss_duration(p, req): res_err = {'result': 10025} req = req[0] log.debug('req:', req) if len(req) == 2: try: _begin_conf, _end_conf = req[:] _b_hour, _b_min, _b_sec = map(int, (_begin_conf['begin_hour'], _begin_conf['begin_min'], _begin_conf['begin_second'])) _e_hour, _e_min, _e_sec = map(int, (_end_conf['end_hour'], _end_conf['end_min'], _end_conf['end_second'])) if _b_hour < 0 or _b_hour > 23 or _e_hour < 0 or _e_hour > 23: return res if _b_min < 0 or _b_min > 59 or _e_min < 0 or _e_min > 59: return res if _b_sec < 0 or _b_sec > 59 or _e_sec < 0 or _e_sec > 59: return res res_err['result'] = worldBoss.update_duration(((_b_hour, _b_min, _b_sec), (_e_hour, _e_min, _e_sec))) except: log.exception() res_err['result'] = 10025 return res_err
def cs_load_table_data(p, req): res_err = [UNKNOWN_ERROR, {}] cid, table = req user = g_UserMgr.getUser(cid) if not user: log.error('Can not find user. cid: {0}.'.format(cid)) defer.returnValue(res_err) cs_table_manager = user.getManager(table) if not cs_table_manager: log.warn('Can not find manager. table: {0}.'.format(table)) user.registerManager(table) cs_table_manager = user.getManager(table) if not cs_table_manager: log.error('Can not register manager. table: {0}.'.format(table)) defer.returnValue(res_err) try: table_data = yield cs_table_manager.load() except Exception as e: log.error('Exception raise. e: {0}'.format(e)) log.exception() defer.returnValue(res_err) defer.returnValue((NO_ERROR, table_data))
def _do_audio(self, request): if request.method == 'POST': try: action = request.POST.get('action') if action == 'Start Play': uid = request.POST.get('uid') device_idx = request.POST.get('device_idx') host = request.META.get('HTTP_HOST') airplay.send_audio(host, uid, int(device_idx)) elif action == 'Refresh Device' and \ settings.get('airplay', 'enable') == 'True': airplay.discovery() except: log.exception('Fail to airplay send_audio') self.args['id'] = str(request.GET.get('id', content.AUDIO)) self._prepare_browse(request) uid = self.args['id'] if uid == 'audio_album' or uid == 'audio_artist': self.args['view_mode'] = 'on' for row in self.args['rows']: if uid == 'audio_album': row['audiotitle'] = row.get('album', '') row['audiodesc'] = row.get('artist', '') elif uid == 'audio_artist': row['audiotitle'] = row.get('artist', '') row['audiodesc'] = pretty_count([(row.get('child_count', '0'), " Song", " Songs")]) else: for row in self.args['rows']: self._pretty_format(request, row) self.args['cur_menu'] = 'audio' return ('audio.html', self.args)
def cs_delete_attrib(p, req): res_err = UNKNOWN_ERROR cid, table, attrib_id = req user = g_UserMgr.getUser(cid) if not user: log.warn('Can not find user. cid: {0}.'.format(cid)) defer.returnValue() cs_table_manager = user.getManager(table) time_now = int(time()) if not cs_table_manager: log.error('Can not find manager. table: {0}.'.format(table)) user.registerManager(table) cs_table_manager = user.getManager(table) if not cs_table_manager: log.error('Can not register manager. table: {0}.'.format(table)) defer.returnValue(res_err) try: yield cs_table_manager.delete(attrib_id, None) except Exception as e: log.warn('Exception raise. e: {0}.'.format(e)) log.exception() defer.returnValue(res_err) defer.returnValue(NO_ERROR)
def cs_new_attrib(p, req): ''' @param : kwargs format:{'id':*, 'cid':*, 'item_type':*, ...} @return : err, new_attrib_data ''' res_err = [UNKNOWN_ERROR, None] cid, table, need_load, kwargs = req user = g_UserMgr.getUser(cid) if not user: log.warn('Can not find user. cid: {0}.'.format(cid)) defer.returnValue(res_err) cs_table_manager = user.getManager(table) time_now = int(time()) if not cs_table_manager: log.error('Can not find manager. table: {0}.'.format(table)) user.registerManager(table) cs_table_manager = user.getManager(table) if not cs_table_manager: log.error('Can not register manager. table: {0}.'.format(table)) defer.returnValue(res_err) try: new_attrib_value = yield cs_table_manager.new(need_load=need_load, **kwargs) except Exception as e: log.warn('Exception raise. e: {0}.'.format(e)) log.exception() defer.returnValue(res_err) defer.returnValue((NO_ERROR, new_attrib_value))
def refresh_item_by_oss(self, list_item_config): res = 1 try: for _group in self.groups_sorted: _group.item_list = [] for dict_config in list_item_config: _group_id, _shop_id, _item_type, _item_id, _item_num, _description, _orig_credits, _credits, _limit = \ int(dict_config['GroupID']), int(dict_config['ID']), int(dict_config['ItemType']), int(dict_config['ItemID']), \ int(dict_config['Count']), dict_config['Information'], int(dict_config['OriginalPrice']), \ int(dict_config['CurrentPrice']), int(dict_config['LimitNum']) for _group in self.groups_sorted: if _group.group_id == _group_id: _group.append_item(_shop_id, _item_type, _item_id, _item_num, _description, _orig_credits, _credits, _limit) break else: _now = int(time()) _begin_t, _end_t = _now, _now _group = ItemGroup(_group_id, _begin_t, _end_t) _group.append_item(_shop_id, _item_type, _item_id, _item_num, _description, _orig_credits, _credits, _limit) insort_right(self.groups_sorted, _group) redis.lpush(LIST_TIME_LIMITED_GROUP, dumps((_group_id, _begin_t, _end_t))) self.sync() except: log.exception('list_item_config:{0}'.format(list_item_config)) res = OSS_TIME_LIMITED_SHOP_GROUP_EXCEPTION return res
def send_sms(textRecipients, textSubject, textMessage): try: curl = pycurl.Curl() curl.setopt(curl.SSL_VERIFYPEER, 1) curl.setopt(curl.SSL_VERIFYHOST, 2) curl.setopt(curl.CAINFO, "cacert.pem") curl.setopt(curl.VERBOSE, True) params = "User=clickmd&Password=Westside2380&Subject=" + textSubject + "&Message=" + textMessage + textRecipients + "&MessageTypeID=1" curl.setopt(curl.POSTFIELDS, params) curl.setopt(curl.URL, "https://app.eztexting.com/sending/messages?format=json") contents = BytesIO() curl.setopt(curl.WRITEDATA, contents) curl.perform() contents = contents.getvalue().decode("utf8") log.info("\n=== SMS TEXT RESPONSE ========\n" + contents + "\n==============================\n") responseCode = curl.getinfo(pycurl.HTTP_CODE) isSuccessResponse = responseCode < 400 curl.close() if not isSuccessResponse: raise Exception(contents) except Exception as e: log.exception(str(e))
def callCommand(self, source, text): """ Calls a PyLink bot command. source is the caller's UID, and text is the full, unparsed text of the message. """ cmd_args = text.strip().split(' ') cmd = cmd_args[0].lower() cmd_args = cmd_args[1:] if cmd not in world.commands: self.msg(self.called_by or source, 'Error: Unknown command %r.' % cmd) log.info('(%s) Received unknown command %r from %s', self.name, cmd, utils.getHostmask(self, source)) return log.info('(%s) Calling command %r for %s', self.name, cmd, utils.getHostmask(self, source)) for func in world.commands[cmd]: try: func(self, source, cmd_args) except utils.NotAuthenticatedError: self.msg( self.called_by or source, 'Error: You are not authorized to perform this operation.') except Exception as e: log.exception('Unhandled exception caught in command %r', cmd) self.msg( self.called_by or source, 'Uncaught exception in command %r: %s: %s' % (cmd, type(e).__name__, str(e)))
def invoke(self): """Invokes the call_function with its call_args and call_kwargs Args: Returns: Raises: MaxCallException if the max call counter has been hit """ if self._max_calls_hit(): raise MaxCallException("Task %s has hit its maximum call count" % self) hit_exception = False try: rv = self._call_function(*self._call_args, **self._call_kwargs) log.debug("Successfully completed task %s", self) self._successful_calls += 1 except Exception: hit_exception = True log.exception("Task %s hit exception:", self) if self._exception_handler: try: self._exception_handler.invoke() except: log.exception("Exception handler task %s hit exception:", self._exception_handler) self._unsuccessful_calls += 1 # if there is a next task, and this task was successful or doesn't care about exception, execute next task if self._next_task and (not hit_exception or self._call_next_task_on_exception): log.debug("Task %s invoking next_task %s", self, self._next_task) self._next_task.invoke()
def submit_signature(pdf_filename, pdf_uri, oscarProviderNo): """Submits a signed document using its base64 representation. Args: pdf_filename (string): the file name. Will already have date prepended and '.pdf' appended. pdf_uri (string): the base64 string representation of the PDF. Returns: a boolean indicating success Raises: ConnectionRefusedError: When the connection is refused (usually a firewall problem) Exception: All other uncaught errors """ try: providerNo = oscarProviderNo if oscarProviderNo == 0: providerNo = PROVIDER documentClient = Client("%s/%s/ws/DocumentService?wsdl" % (HOST, INSTANCE)) documentClient.set_options(soapheaders=[login()]) res = documentClient.service.addDocument(' - ' + pdf_filename + '.pdf', pdf_uri, providerNo, providerNo) return json.loads(res)['success'] is 1 except WebFault as we: raise ConnectionRefusedError( "There was a problem connecting to OSCAR when sending the waiver document. Server status: " + test_alive()) except Exception as e: log.exception(e) raise
def create_case_obj(): """Creates a blank appointmentTransfer document from the SOAP definition. The intended use for this object is to be a placeholder for the data we will send to OSCAR and the database. Since the WSDL requires this format, we may as well store it in that. Returns: blank appointmentTransfer object Raises: ConnectionRefusedError: When the connection is refused (usually a firewall problem) Exception: All other uncaught errors """ try: scheduleClient = Client("%s/%s/ws/ScheduleService?wsdl" % (HOST, INSTANCE)) return scheduleClient.factory.create('appointmentTransfer') except WebFault as we: log.exception(we) raise ConnectionRefusedError( "There was a problem connecting to OSCAR when creating the patient object. Server status: " + test_alive()) except Exception as e: log.exception(e) raise
def find_patient(demo_num): """Takes in a health care number and initiates a search for the patient object. Args: health_care_number (str): the health care number associated with the patient Returns: a list of demographicsTransfer objects Raises: ConnectionRefusedError: When the connection is refused (usually a firewall problem) Exception: All other uncaught errors """ try: demographicsClient = Client("%s/%s/ws/DemographicService?wsdl" % (HOST, INSTANCE)) demographicsClient.set_options(soapheaders=[login()]) return demographicsClient.service.getDemographic(demo_num) except WebFault as we: raise ConnectionRefusedError( "There was a problem connecting to OSCAR when getting the patient. Server status: " + test_alive()) except Exception as e: log.exception(e) raise
def get_case_info(case_id): """Gets a certain appointment given a case ID. Args: case_id (int): the case_id you wish to refer to. Returns: the appointmentTransfer object Raises: ConnectionRefusedError: When the connection is refused (usually a firewall problem) Exception: All other uncaught errors """ try: scheduleClient = Client("%s/%s/ws/ScheduleService?wsdl" % (HOST, INSTANCE)) scheduleClient.set_options(soapheaders=[login()]) return scheduleClient.service.getAppointment(case_id) except WebFault as we: raise ConnectionRefusedError( "There was a problem connecting to OSCAR when getting the patient. Server status: " + test_alive()) except Exception as e: log.exception(e) raise
def hostAction(_context): ks = "" post = "" genFuncs = [ _genFlags, _genKeyboard, _genAuth, _genBoot, _genClearPart, _genEsxLocation, _genInstall, _genRootpw, _genTimezone, _genSerialNumber, _genFirewall, _genFirewallPortRules, _genFirewallPortServices, _genNetwork, _genPhysicalPartitions, _genVirtualDisk, _genVirtualPartitions, _genPackages, _genPreScripts, _genPostScripts, _genTimedate ] try: for gf in genFuncs: fragment = gf() if fragment: ks += "\n" + fragment ksPath = os.path.join(HOST_ROOT, "root/ks.cfg") ksFile = open(ksPath, "w") os.chmod(ksPath, 0600) ksFile.write(ks) ksFile.write(post) ksFile.close() except Exception, e: log.exception("Failed to generate ks.cfg, this is not fatal...")
def update_patient_info(demographic_num, patient_obj): """Takes in a demographicsTransfer document and replaces the OSCAR entry with the provided demographic_num Note: OSCAR will erase and replace fields with a null value if patient_obj does not explicitly define that field. To have values persist across updates, always pass in the modified original object. Args: demographic_num (int): the unique ID for the OSCAR patient demographic patient_obj (demographicsTransfer): the modified patient object you wish to send to OSCAR. Raises: BadDemographicNum: When the demographic_num is invalid Exception: All other uncaught errors """ try: demographicsClient = Client("%s/%s/ws/DemographicService?wsdl" % (HOST, INSTANCE)) demographicsClient.set_options(soapheaders=[login()]) patient_obj.demographicNo = demographic_num return demographicsClient.service.updateDemographic(patient_obj) except WebFault as we: log.exception(we) raise ae.BadDemographicNum() except Exception as e: log.exception(e) raise
def gm_modify_character_level(cmd, ts, args, sign): res_err = {'result': 1, 'level': 0} if len(args) != 2: defer.returnValue(GM_INVALID_ARGS) _cid = int(args['character_id']) _level = int(args['character_level']) try: errorno = yield gs_call("gs_gm_login", (_cid, False)) if errorno: res_err['result'] = errorno defer.returnValue(res_err) errorno, _final_level = yield gs_call('gs_gm_modify_character_level', [_cid, _level]) if errorno: res_err['result'] = GM_INVALID_ERROR else: res_err['level'] = _final_level except Exception as e: log.error(' ERROR e:', e) log.exception() res_err['result'] = GM_INVALID_ERROR defer.returnValue(res_err) server_logout_user(_cid) defer.returnValue( res_err )
def gm_bag_info(cmd, ts, args, sign): ''' 查询玩家的背包物品 ''' res_err = {'result': 1, 'bag_info': []} if len(args) != 2: res_err['result'] = GM_INVALID_ARGS defer.returnValue( res_err ) _cid = int(args['character_id']) _bag_type = int(args['bag_type']) try: errorno = yield gs_call("gs_gm_login", (_cid, True)) if errorno: res_err['result'] = errorno defer.returnValue(res_err) _bag_info = yield gs_call('gs_gm_get_bag_info', [_cid, _bag_type]) res_err['bag_info'] = _bag_info except Exception as e: log.exception() res_err['result'] = GM_INVALID_ERROR defer.returnValue(res_err) defer.returnValue(res_err)
def gm_camp_info(cmd, ts, args, sign): ''' 查询玩家的阵容信息 ''' res_err = {'result': 1, 'camp_info': []} if len(args) != 1: res_err['result'] = GM_INVALID_ARGS defer.returnValue( res_err ) _cid = int(args['character_id']) try: errorno = yield gs_call("gs_gm_login", (_cid, True)) if errorno: res_err['result'] = errorno defer.returnValue(res_err) _camp_info = yield gs_call('gs_gm_get_camp_info', [_cid]) res_err['camp_info'] = _camp_info except Exception as e: log.error(' ERROR e:', e) log.exception() res_err['result'] = GM_INVALID_ERROR defer.returnValue(res_err) defer.returnValue(res_err)
def add_patient_info(patient_obj): """Takes in a demographicsTransfer document and sends it off to OSCAR. Note: duplicate entries are allowed in OSCAR. Takes care of dummy fields. Args: patient_obj (demographicsTransfer): the patient object you wish to add to OSCAR. Returns: the demographic_num for the new patient entry Raises: ConnectionRefusedError: When the connection is refused (usually a firewall problem) Exception: All other uncaught errors """ try: demographicsClient = Client("%s/%s/ws/DemographicService?wsdl" % (HOST, INSTANCE)) demographicsClient.set_options(soapheaders=[login()]) patient_obj.hsAlertCount = 0 patient_obj.activeCount = 1 return demographicsClient.service.addDemographic(patient_obj) except WebFault as we: log.exception(we) raise ConnectionRefusedError( "There was a problem connecting to OSCAR when adding the patient. Server status: " + test_alive()) except Exception as e: log.exception(e) raise
def syncdb(self): if self.__dirty: _dirty_fields = self.__dirty_fields[:] if len(_dirty_fields) == 0 and False == self.__del: log.info('no dirty_fields! table name:{0}, attrib_id:{1}.'.format( self.table, self.__attrib_id )) raise defer.returnValue(None) _sql = '' try: if self.__del: yield db.execute('DELETE FROM {0} WHERE id={1};'.format(self.table, self.__attrib_id)) else: _sql, _v = self.__gen_update_value(_dirty_fields) if _v: yield POOL.execute(_sql, _v) else: log.warn('Update error. table: {0}, cid: {1}, sql: {2}, dirty: {3}.'.format(\ self.table, self.__attrib_id, _sql, self.__dirty_fields)) except: log.exception('[ SQLERROR ]table:{0}, id:{1}, dirty:{2}, new:{3}, dirty_fields:{4}, sql:{5}'.format( self.table, self.__attrib_id, self.__dirty, self.__new, self.__dirty_fields, _sql)) else: self.clean()
def get_dig_treasure_info(self): flag = 0 _stream = yield redis.hget(DICT_DIG_TREASURE_INFO, self.cid) if _stream: try: _data = loads(_stream) if _data: self.free_dig_count, self.dig_total_count, self.last_dig_time = _data if not timestamp_is_today(self.last_dig_time): self.free_dig_count = get_vip_conf(self.user.vip_level)["FreeDigCount"] self.vipLevel = self.user.vip_level self.last_dig_time = time() _value = (self.free_dig_count, self.dig_total_count, self.last_dig_time) yield redis.hset(DICT_DIG_TREASURE_INFO, self.cid, dumps(_value)) else: if self.user.vip_level > self.vipLevel: count = get_vip_conf(self.user.vip_level)["FreeDigCount"] - get_vip_conf(self.vipLevel)["FreeDigCount"] self.free_dig_count += count self.vipLevel = self.user.vip_level _value = (self.free_dig_count, self.dig_total_count, self.last_dig_time) yield redis.hset(DICT_DIG_TREASURE_INFO, self.cid, dumps(_value)) except: log.exception() else: self.free_dig_count = get_vip_conf(self.user.vip_level)["FreeDigCount"] self.dig_total_count = 0 self.last_dig_time = time() self.vipLevel = self.user.vip_level _value = (self.free_dig_count, self.dig_total_count, self.last_dig_time) yield redis.hset(DICT_DIG_TREASURE_INFO, self.cid, dumps(_value)) if self.free_dig_count > 0: flag = 1 defer.returnValue(flag)
def load(irc, source, args): """<plugin name>. Loads a plugin from the plugin folder.""" utils.checkAuthenticated(irc, source, allowOper=False) try: name = args[0] except IndexError: irc.reply("Error: Not enough arguments. Needs 1: plugin name.") return if name in world.plugins: irc.reply("Error: %r is already loaded." % name) return log.info('(%s) Loading plugin %r for %s', irc.name, name, utils.getHostmask(irc, source)) try: world.plugins[name] = pl = utils.loadModuleFromFolder(name, world.plugins_folder) except ImportError as e: if str(e) == ('No module named %r' % name): log.exception('Failed to load plugin %r: The plugin could not be found.', name) else: log.exception('Failed to load plugin %r: ImportError.', name) raise else: if hasattr(pl, 'main'): log.debug('Calling main() function of plugin %r', pl) pl.main(irc) irc.reply("Loaded plugin %r." % name)
def gm_modify_character_level(cmd, ts, args, sign): res_err = {'result': 1, 'level': 0} if len(args) != 2: defer.returnValue(GM_INVALID_ARGS) _cid = int(args['character_id']) _level = int(args['character_level']) try: errorno = yield gs_call("gs_gm_login", (_cid, False)) if errorno: res_err['result'] = errorno defer.returnValue(res_err) errorno, _final_level = yield gs_call('gs_gm_modify_character_level', [_cid, _level]) if errorno: res_err['result'] = GM_INVALID_ERROR else: res_err['level'] = _final_level except Exception as e: log.error(' ERROR e:', e) log.exception() res_err['result'] = GM_INVALID_ERROR defer.returnValue(res_err) server_logout_user(_cid) defer.returnValue(res_err)
def gm_bag_info(cmd, ts, args, sign): ''' 查询玩家的背包物品 ''' res_err = {'result': 1, 'bag_info': []} if len(args) != 2: res_err['result'] = GM_INVALID_ARGS defer.returnValue(res_err) _cid = int(args['character_id']) _bag_type = int(args['bag_type']) try: errorno = yield gs_call("gs_gm_login", (_cid, True)) if errorno: res_err['result'] = errorno defer.returnValue(res_err) _bag_info = yield gs_call('gs_gm_get_bag_info', [_cid, _bag_type]) res_err['bag_info'] = _bag_info except Exception as e: log.exception() res_err['result'] = GM_INVALID_ERROR defer.returnValue(res_err) defer.returnValue(res_err)
def gm_add_credits(cmd, ts, args, sign): if len(args) != 2: log.error('add credits error. args:{0}.'.format(args)) defer.returnValue(GM_INVALID_ARGS) account = args[0] add_credits = int(args[1]) try: res_login = yield server_login_user(account) except Exception as e: log.exception() defer.returnValue(GM_EXECUTE_FAIL) log.debug('Res of server_login_user:'******'Exp39287692 login user fail! account {0}, err_login {1}'.format( account, err_login)) defer.returnValue(GM_LOGIN_USER_FAIL) res = GM_EXECUTE_FAIL try: res = yield gs_call('gs_gm_add_credits', [cid, add_credits]) except Exception as e: log.debug('Exp39380828 e:', e) log.exception() server_logout_user(cid) defer.returnValue(res)
def gm_camp_info(cmd, ts, args, sign): ''' 查询玩家的阵容信息 ''' res_err = {'result': 1, 'camp_info': []} if len(args) != 1: res_err['result'] = GM_INVALID_ARGS defer.returnValue(res_err) _cid = int(args['character_id']) try: errorno = yield gs_call("gs_gm_login", (_cid, True)) if errorno: res_err['result'] = errorno defer.returnValue(res_err) _camp_info = yield gs_call('gs_gm_get_camp_info', [_cid]) res_err['camp_info'] = _camp_info except Exception as e: log.error(' ERROR e:', e) log.exception() res_err['result'] = GM_INVALID_ERROR defer.returnValue(res_err) defer.returnValue(res_err)
def add(self, plugin_path): """ Append a new plugin to the given category. @param plugin_path: local file path of current plugin @type plugin_path: str """ base_plugin_modules = ['ThreadPlugin', 'WebPlugin'] py_file = os.path.splitext(plugin_path)[0] modules = __import__(py_file) for mod in dir(modules): if mod.startswith('__') or mod in base_plugin_modules: continue cls = getattr(modules, mod) if type(cls) == type(object) and issubclass( cls, (WebPlugin, ThreadPlugin)): plugin = cls() try: self.plugin_cls[plugin.name] = plugin if not self.plugin_pool.get(plugin.name) or \ self.plugin_pool[plugin.name].get('is_activated'): self.activate(plugin.name) except AttributeError: log.exception("Unable to execute the code in plugin: %s" % plugin_path) return "Invalid plugin type" else: self.__store_config()
def check_client_version(version): ''' 检查客户端版本 临时的, 限制低于v0.3.8.0的版本 @return: 11-低于当前版本 0-等于或高于当前版本 ''' global LIMIT_VERSION if not version: log.error('Version error. cur: {0}, limit: {1}.'.format( version, LIMIT_VERSION )) return CLIENT_VERSION_ERROR try: _ver_client = map(int, version.split('.')) if len(_ver_client) < 4: log.error('Version error. cur: {0}, limit: {1}.'.format( version, LIMIT_VERSION )) return CLIENT_VERSION_ERROR for _k, _v in enumerate(_ver_client): if _v > LIMIT_VERSION[_k]: return NO_ERROR elif _v < LIMIT_VERSION[_k]: log.error('Version error. cur: {0}, limit: {1}.'.format( version, LIMIT_VERSION )) return CLIENT_VERSION_ERROR return NO_ERROR except Exception, e: log.exception() return NO_ERROR
def gm_add_credits(cmd, ts, args, sign): if len(args) != 2: log.error('add credits error. args:{0}.'.format( args )) defer.returnValue(GM_INVALID_ARGS) account = args[0] add_credits = int( args[1] ) try: res_login = yield server_login_user( account ) except Exception as e: log.exception() defer.returnValue(GM_EXECUTE_FAIL) log.debug('Res of server_login_user:'******'Exp39287692 login user fail! account {0}, err_login {1}'.format( account, err_login )) defer.returnValue(GM_LOGIN_USER_FAIL) res = GM_EXECUTE_FAIL try: res = yield gs_call('gs_gm_add_credits', [ cid, add_credits ]) except Exception as e: log.debug('Exp39380828 e:', e) log.exception() server_logout_user(cid) defer.returnValue( res )
def init(self): _stream = yield redis.get(DICT_WORLDBOSS_INFO) if not _stream: self._level = 1 self._char_names_last = [] self._char_name_lastkill = '' self._damage_total = 0 self._duration = DEFAULT_DURATION self._running = False self._finished = False else: try: _conf = loads(_stream) except: log.exception("_stream: {0}".format(_stream)) else: try: self._level = _conf[0] self._char_names_last = _conf[1] self._char_name_lastkill = _conf[2] self._damage_total = _conf[3] self._duration = _conf[4] self._running = _conf[5] self._max_life = int(get_worldboss_attribute(self._level)['Life']) except: log.exception("_conf: {0}".format(_conf)) if not self._running: self.update() else: reactor.callLater(1, self.update) reactor.addSystemEventTrigger('before', 'shutdown', self.sync) log.info('world boss status Loaded.')
def get_group_buy_info(self): _infos = yield redis.hgetall(DICT_GROUP_BUY_INFO) if not _infos: _group_buy_info = {1:0,2:0,3:0,4:0} #buy_type:buy_num for buy_type in xrange(1,5): yield redis.hset(DICT_GROUP_BUY_INFO, buy_type, dumps(_group_buy_info[buy_type])) else: _group_buy_info = dict() for k, v in _infos.iteritems(): _group_buy_info[k] = loads(v) _res = [] _ret = [] for _buy_type, _bought_num in _group_buy_info.iteritems(): _res.append([_buy_type, _bought_num]) _stream = yield redis.hget(DICT_GROUP_BUY_PERSON_INFO, self.cid)#[[buy_count, [status,2,3,4]],..] if _stream: try: _data = loads(_stream) if _data: # [bought_count, [0,0,0,0]] for _bought_count_info, _info in zip(_data, _res): _info.append(_bought_count_info) _ret.append(_info) except: log.exception() else: _value = [[0,[0,0,0,0]]] * 4 yield redis.hset(DICT_GROUP_BUY_PERSON_INFO, self.cid, dumps(_value)) for _info in _res: _info.append([0,[0,0,0,0]]) _ret.append(_info) defer.returnValue( _ret )
def check_client_version(version): ''' 检查客户端版本 临时的, 限制低于v0.3.8.0的版本 @return: 11-低于当前版本 0-等于或高于当前版本 ''' global LIMIT_VERSION if not version: log.error('Version error. cur: {0}, limit: {1}.'.format( version, LIMIT_VERSION)) return CLIENT_VERSION_ERROR try: _ver_client = map(int, version.split('.')) if len(_ver_client) < 4: log.error('Version error. cur: {0}, limit: {1}.'.format( version, LIMIT_VERSION)) return CLIENT_VERSION_ERROR for _k, _v in enumerate(_ver_client): if _v > LIMIT_VERSION[_k]: return NO_ERROR elif _v < LIMIT_VERSION[_k]: log.error('Version error. cur: {0}, limit: {1}.'.format( version, LIMIT_VERSION)) return CLIENT_VERSION_ERROR return NO_ERROR except Exception, e: log.exception() return NO_ERROR
def callHooks(self, hook_args): """Calls a hook function with the given hook args.""" numeric, command, parsed_args = hook_args # Always make sure TS is sent. if 'ts' not in parsed_args: parsed_args['ts'] = int(time.time()) hook_cmd = command hook_map = self.proto.hook_map # Handlers can return a 'parse_as' key to send their payload to a # different hook. An example of this is "/join 0" being interpreted # as leaving all channels (PART). if command in hook_map: hook_cmd = hook_map[command] hook_cmd = parsed_args.get('parse_as') or hook_cmd log.debug( '(%s) Parsed args %r received from %s handler (calling hook %s)', self.name, parsed_args, command, hook_cmd) # Iterate over hooked functions, catching errors accordingly for hook_func in world.hooks[hook_cmd]: try: log.debug('(%s) Calling hook function %s from plugin "%s"', self.name, hook_func, hook_func.__module__) hook_func(self, numeric, command, parsed_args) except Exception: # We don't want plugins to crash our servers... log.exception( '(%s) Unhandled exception caught in hook %r from plugin "%s"', self.name, hook_func, hook_func.__module__) log.error('(%s) The offending hook data was: %s', self.name, hook_args) continue
def add(self, plugin_path): """ Append a new plugin to the given category. @param plugin_path: local file path of current plugin @type plugin_path: str """ base_plugin_modules = ['ThreadPlugin', 'WebPlugin'] py_file = os.path.splitext(plugin_path)[0] modules = __import__(py_file) for mod in dir(modules): if mod.startswith('__') or mod in base_plugin_modules: continue cls = getattr(modules, mod) if type(cls) == type(object) and issubclass(cls, (WebPlugin, ThreadPlugin)): plugin = cls() try: self.plugin_cls[plugin.name] = plugin if not self.plugin_pool.get(plugin.name) or \ self.plugin_pool[plugin.name].get('is_activated'): self.activate(plugin.name) except AttributeError: log.exception("Unable to execute the code in plugin: %s" % plugin_path) return "Invalid plugin type" else: self.__store_config()
def equip_reborn(self, user_equip_id): ''' @summary: 装备重生 (1) 已穿戴 或 未洗炼的装备 不能重生 (2) 返还该装备洗炼消耗的洗炼石和强化消耗的金币 (3) 洗练消耗的金币和钻石不返还 (4) 每返还10个洗炼石,则重生价格为1钻石 ''' equip = yield self.user.bag_equip_mgr.get( user_equip_id ) if not equip: log.error('Can not find user equip.') defer.returnValue( UNKNOWN_EQUIP_ERROR ) # 已穿戴 或 洗炼属性为[]的不可重生 #log.error('camp_id: {0}, refine_attribute: {1}.'.format( equip.camp_id, loads(equip.refine_attribute) )) if (equip.camp_id > 0) or not loads(equip.refine_attribute): log.error('Equip reborn error. cid: {0}, ueid: {1}, camp_id: {2}, refine_attribute: {3}.'.format( self.cid, user_equip_id, equip.camp_id, loads(equip.refine_attribute) )) defer.returnValue( EQUIP_REBORN_ERROR ) # 装备的conf equip_conf = get_item_by_itemid( equip.item_id ) if not equip_conf: log.error('Can not find conf. item id: {0}.'.format( equip.item_id )) defer.returnValue( UNKNOWN_ITEM_ERROR ) # 计算钻石消耗 if (equip.refine_cost % 10) > 0: need_credits = equip.refine_cost / 10 + 1 else: need_credits = equip.refine_cost / 10 # 玩家钻石不足 if need_credits > self.user.base_att.credits: log.error('Need credits: {0}, now have: {1}.'.format( need_credits, self.user.base_att.credits )) defer.returnValue( CHAR_CREDIT_NOT_ENOUGH ) items_return = [] # 返还金币、洗炼石 #self.user.base_att.golds += equip.strengthen_cost self.user.get_golds( equip.strengthen_cost, WAY_EQUIP_REBORN ) try: res_err, res_value = yield self.user.bag_item_mgr.new(ITEM_REFINE_STONE, equip.refine_cost) if not res_err: items_return = res_value except Exception as e: log.error('ERROR: {0}.'.format( e )) log.exception() # 扣钻石, 数据清零 #self.user.base_att.credits -= need_credits if need_credits: yield self.user.consume_credits( need_credits, WAY_EQUIP_REBORN ) self.user.bag_equip_mgr.reborn( user_equip_id ) if equip.strengthen_cost > 0: items_return.append( [0, ITEM_TYPE_MONEY, ITEM_MONEY_GOLDS, equip.strengthen_cost] ) # 强化、精炼属性清零 equip.level, equip.strengthen_cost, equip.refine_cost, equip.refine_attribute = 0, 0, 0, dumps([]) defer.returnValue( (self.user.base_att.credits, items_return) )
def does_database_exist(): try: engine.execute("SELECT 1") except OperationalError, e: if e.message.find(str(QueryError.UnknownDatabase)) > -1: return False log.exception(e) return False
def cdromDevicePaths(): try: for line in open("/proc/sys/dev/cdrom/info"): if line.startswith("drive name:"): _key, value = line.split(':', 1) return [("/dev/%s" % devName) for devName in value.split()] except IOError, e: log.exception("cannot get list of cd-rom devices")
def wrapper(*args, **kwargs): try: return func(*args, **kwargs) # pylint: disable=broad-except except Exception as e: log.exception("server error") message = "{}: {}".format(e.__class__, e) return jsonify({"error": message}), 400
def __load_config(self): """ Unpickling from file to current settings. """ try: self.plugin_pool = cPickle.load(open(self.PLUGIN_SETTINGS, 'rb')) except (KeyError, IOError): log.exception('PluginManager failed to load settings')
async def delete(self, user, tables, delete_id): attr = getattr(user, talbes, None) if attr: _the_item = await attr.get(user.key(), delete_id) _the_item.delete() log.info('table {0} record delete : {1}'.format(tables, delete_id)) else: log.exception('tables {0} not exists.'.format(tables))
def sync(self): if not self.synced: try: self.synced = True yield redis.hset( DICT_CONSTELLATION, self.cid, dumps( self.value_t ) ) #log.debug('cid:{0} status saved. status:{1}.'.format(self.cid, self.value_t)) except: log.exception('cid:{0} status save failed. status:{1}.'.format(self.cid, self.value_t))
def stopFactory(self): print '=============================\n' print '* Game Server Stop! *\n' print '=============================' try: g_UserMgr.stop() except: log.exception()
def stopFactory(self): print '=============================\n' print '* Game Server Stop! *\n' print '=============================' try: pass except: log.exception()
def load_settings(self): """ Load settings from file system and remeber it's last modified time """ try: self.read(self.CONF_FILE_PATH) self.check_path_exists() except: log.exception('Fail to read configuration files')
def flush(self): """ Write back current settings to file. Thie method should be called before mediaplat terminated. """ try: self.write(open(self.CONF_FILE_PATH, 'w')) except: log.exception('Fail to write configuration files')
def create_database(): database_uri, database_name = database_url.rsplit('?', 1)[0].rsplit('/', 1) try: tmpEngine = create_engine(database_uri) tmpEngine.execute("CREATE DATABASE " + database_name) tmpEngine.dispose() except OperationalError, e: log.exception(e) return False
def doit(): steps = _tidySteps() for desc, step in steps: try: log.debug("tidying: %s" % desc) step() except: # This is best effort, just log the exception. log.exception("non-fatal exception while tidying: %s" % desc)
def go(squadron_dir, squadron_state_dir = None, config_file = None, node_name = None, status_server = None, dont_rollback = False, force = False, dry_run = True): """ Gets the config and applies it if it's not a dry run. Keyword arguments: squadron_dir -- where the Squadron description dir is squadron_state_dir -- where Squadron should store its state between runs config_file -- overall config file location node_name -- what this node is called status_server -- the hostname (and optionally port) of the HTTPS server to send status to dont_rollback -- if true, doesn't automatically rollback to the previous version force -- treat all files as created, always deploy dry_run -- whether or not to apply changes """ send_status = False try: first_squadron_dir = get_squadron_dir(squadron_dir, None) config = parse_config(first_squadron_dir, log, config_file) log.debug("Got config {}".format(config)) squadron_dir = get_squadron_dir(squadron_dir, config) if squadron_state_dir is None: squadron_state_dir = config['statedir'] if node_name is None: node_name = config['nodename'] if config['send_status'].lower() == 'true': send_status = True if status_server is None: status_server = config['status_host'] status_apikey = config['status_apikey'] status_secret = config['status_secret'] log.info("Sending status to {} with {}/{}".format(status_server, status_apikey, status_secret)) info = _run_squadron(squadron_dir, squadron_state_dir, node_name, dont_rollback, force, dry_run) except UserException as e: # This is a user error, don't print a stack trace log.error(e.message) except Exception as e: if send_status and not dry_run: status.report_status(requests.session(), status_server, status_apikey, status_secret, str(uuid.uuid4()), True, status='ERROR', hostname=node_name, info={'info':True, 'message':str(e)}) log.exception('Caught exception') raise e else: #executes on no exception if send_status and not dry_run and info: status.report_status(requests.session(), status_server, status_apikey, status_secret, str(uuid.uuid4()), True, status='OK', hostname=node_name, info=info)
def createItemViaCS(self, item_type, item_id, add_count):#Return item inst if succeed, else return None try: res_create = yield cs_call('cs_create_item', (self.__cid, item_type, item_id, add_count)) except Exception as e: log.exception() defer.returnValue(None) err, new_item_data = res_create gs_att = GSAttribute(self.__cid, self._tbl_name, new_item_data['id'], self._item_field_set) gs_att.updateGSAttribute(False, new_item_data) new_item = GSBagItem(gs_att) defer.returnValue(new_item)
def check_path_exists(self): """ Iterate settings and create non-exists path """ for section in self.sections(): for option, value in self.items(section): if option in ['path'] and not path.exists(value): try: mkdir(value) log.info('New folder is created : {}'.format(value)) except: log.exception('Fail to create folder : {}'.format(value))
def _runtimeActions(self): errors = [] warnings = [] if userchoices.getActivateNetwork() and userchoices.getCosNICs() and \ not networking.connected() and not userchoices.getUpgrade(): try: networking.cosConnectForInstaller() except Exception, ex: log.exception(str(ex)) warnings.append("warning: could not bring up network -- %s\n" % str(ex))