def handle_nickchg(event, message): if(message.source is None or message.source==""): #new nick usermodes=virtualhost=cloakedhost=nickipaddr=None nick,hopcount,timestamp,username,hostname,server,servicestamp=message.parameters[0:7] if(ffservices.protoctl["NICKv2"]): usermodes,virtualhost=message.parameters[7:9] if(ffservices.protoctl["CLK"]): cloakedhost=message.parameters[9] if(ffservices.protoctl["NICKIP"]): nickipaddr=message.parameters[10] else: if(ffservices.protoctl["NICKIP"]): nickipaddr=message.parameters[9] realname=message.parameters[-1] c=Client(nick, hopcount, timestamp, username, hostname, server, servicestamp, usermodes, virtualhost, cloakedhost, nickipaddr, realname) log.info("Client connecting at %s: %s (%s@%s[%s])", c.server, c.nick, c.username, c.ip, c.hostname) if(not Client.addClient(c)): #if we can't add the client, that means that nick already exists. If the #nick already exists, it is a services pseudoclient -- so we kill the #non-services client c.kill("Nick Collision") else: #nick change who=message.source newnick, timestamp=message.parameters client=Client.findByNick(who) if(client is None): return if(client.changeNick(newnick, timestamp)): return #nick collision client.kill("Nick Collision")
def select(self): """ 选择菜单 :return: """ current_level,current_menu = self.display() exit_flag = False while not exit_flag: _input = input('输入选择的编码:\n>>') if _input == '0': log.info('退出菜单' ) if len(self.menu_list) == 1: exit_flag = True else: self.menu_list.pop() #删除一级目录 return self.select() #递归调用 elif _input in current_level : log.info('选择菜单:%s'% current_level[_input]) if isinstance(current_menu[current_level[_input]],str): #判断value是否是字符串 是则到底 返回 return current_menu[current_level[_input]] else: self.menu_list.append(current_menu[current_level[_input]]) #添加当前级别目录 return self.select() #递归调用 选择当前级别目录 else: print("""您输入编号不存在。请输入正确的编号!~\n""") log.warn('输入编号错误 %s' %_input) return self.select()
def logout(self): log.info("Logging out...") try: self._logout() except MasterServerError, e: log.error(e) return False
async def handle_msg_private(event: Event): qq_num = int(event.sender['user_id']) if qq_num in config.admin_list: await handle_msg_group(event) else: log.info('屏蔽私聊', event.message, qq_num) await bot.send(event, f"您没有使用权限,请加群:{config.group_num}")
def open(self): if self.__db__ is not None: return True if self.locker: counter = 0 # check if db is locked and wait for freeing while os.path.exists( self.__locker_path__) and counter < self.__max_t__: counter += 1 log.info('wating for unlocking SQLite DB') time.sleep(1) # wait 1 second every time # check if duration if counter >= self.__max_t__: log.error( f'the sqlite DB is still locked after {self.__max_t__} seconds.' ) sys.exit(1) return False # lock db with open(self.__locker_path__, 'w') as file: file.write('locked') log.info(f"connecting to db: {self.db_path}") # connect to db self.__db__ = sqlite3.connect(self.db_path) self.__cursor__ = self.__db__.cursor() self.__db_init__() return True
def __reload_all(self): log.info("__reload_all is called") for patt, mw in self.method_wrappers: mw.wrap_method() for patt2, fw in self.function_wrappers: fw.wrap_function()
def handle_quit(event, message): client = Client.findByNick(message.source) if (client is None): return log.info("Client exiting at %s: %s!%s@%s[%s]: %s", client.server, client.nick, client.username, client.ip, client.hostname, " ".join(message.parameters)) Client.removeClient(client)
def __unload_all(self): log.info("__unload_all is called") for patt, mw in self.method_wrappers: mw.restore_method_aspect() for patt2, fw in self.function_wrappers: fw.restore_function_aspect()
def handle_nickchg(event, message): if (message.source is None or message.source == ""): #new nick usermodes = virtualhost = cloakedhost = nickipaddr = None nick, hopcount, timestamp, username, hostname, server, servicestamp = message.parameters[ 0:7] if (ffservices.protoctl["NICKv2"]): usermodes, virtualhost = message.parameters[7:9] if (ffservices.protoctl["CLK"]): cloakedhost = message.parameters[9] if (ffservices.protoctl["NICKIP"]): nickipaddr = message.parameters[10] else: if (ffservices.protoctl["NICKIP"]): nickipaddr = message.parameters[9] realname = message.parameters[-1] c = Client(nick, hopcount, timestamp, username, hostname, server, servicestamp, usermodes, virtualhost, cloakedhost, nickipaddr, realname) log.info("Client connecting at %s: %s (%s@%s[%s])", c.server, c.nick, c.username, c.ip, c.hostname) if (not Client.addClient(c)): #if we can't add the client, that means that nick already exists. If the #nick already exists, it is a services pseudoclient -- so we kill the #non-services client c.kill("Nick Collision") else: #nick change who = message.source newnick, timestamp = message.parameters client = Client.findByNick(who) if (client is None): return if (client.changeNick(newnick, timestamp)): return #nick collision client.kill("Nick Collision")
def http_request(url, params=None, method='get', timeout=1, is_json=True): begin_time = time.time() result = None try: r = None if method is 'get': if params is None: r = requests.get(url, timeout=timeout) else: r = requests.get(url, params=params, timeout=timeout) elif method is 'post': if params is None: r = requests.post(url, timeout=timeout) else: r = requests.post(url, data=params, timeout=timeout) if r is not None: if is_json is True: result = ('ok', r.status_code, r.json()) else: result = ('ok', r.status_code, r.json()) else: result = ('fail', '000', 'request failed') except requests.ConnectionError as e: log.info("[error_log] timeout - %s" % (url)) result = ('fail', '000', 'request failed') except Exception, e: log.info("[error_log] error - %s, e=%s" % (url, e.message)) result = ('fail', '000', 'request failed')
def do_stuff(): # time.sleep(2) headers = create_http_headers_for_new_span() r = requests.get('http://www.baidu.com', headers=headers) log.info(r) log.info(r.content) return 'OK'
def disconnect(self): log.info("Disconnecting...") try: self._chat_disconnect() except ChatServerError, e: log.error(e) return False
def do_register(self, msg): key = msg.get(1) if not key: log.error(0, 'invalid message: %s', msg) return if self.connect_key: log.error(0, '*%d has connected. key:%s', self.connect_key) self.send_msg([ 'connect rsp', 'error', 'has connected. key:%s' % self.connect_key ]) return if self.register_key: if self.register_key != key: log.error(0, '*%d has registered, key:%s', self.conn.index, self.register_key) self.send_msg( ['register rsp', 'error', 'has registered other']) else: self.send_msg(['register rsp', 'ok']) return if REGISTER.has_key(key): self.send_msg( ['register rsp', 'error', 'has registered. key:%s' % key]) return REGISTER[key] = self self.register_key = key log.info(0, '*%d add register: %s', self.conn.index, self.register_key) self.send_msg(['register rsp', 'ok'])
def wrapper(*args, **kwargs): log.info('function %s begin at %s' % (func.__name__, fmt_d(None))) try: return func(*args, **kwargs) finally: log.info(' function %s end at %s' % (func.__name__, fmt_d(None)))
def accept(self): try: if not is_cygwin: s, sockaddr = self.socket().accept() else: begin = time.time() s, sockaddr = self.socket().accept() end = time.time() if end - begin > 1: log.info(0, 'accept cost %f seconds', end - begin) exit(-1) except IOError as exc: err = exc.errno if err != errno.EAGAIN and err != errno.EINTR: log.error(exc, 'accept() fail') return None except Exception as exc: log.error(exc, 'accept() fail') return None c = Connection() c.socket(s) c.listening = self c.nonblocking() c.keepalive() c.addr = Addr(self.addr) c.addr.parse_sockaddr(sockaddr) log.debug(0, '*%d accept: %s', c.index, c.addr.text) self.handler(c) return self
def reload_class_methods(self, current_meths, new_meths): try: if not does_local_ip_matched(): return # in current_funcs, but not in new_funcs, need to restore profile diff_restore = list(set(current_meths).difference(set(new_meths))) for aa in diff_restore: arr = str(aa).split(',') patt = build_pattern(arr[0], arr[1], arr[2]) if patt in self.method_wrappers: mw = self.method_wrappers[patt] mw.restore_method_aspect() self.method_wrappers.pop(patt) if aa in new_meths: new_meths.remove(aa) # not in current_funcs, but in new_funcs, need to add profile # diff_profile = list(set(new_meths).difference(set(current_meths))) for aa in new_meths: arr = str(aa).split(',') self.profile_class_method(arr[0], arr[1], arr[2]) except: log.info("reload_class_methods %s , %s error: %s ", str(current_meths), str(new_meths), utils.current_exception_info())
def on_auth_accepted(self, *p): """ Authenticated, join the default channels and set up some base things. """ log.info("Connected as %s" % self.account.nickname) self.bot.nickname = self.account.nickname for channel in self.channels.keys(): self.join_channel(channel)
def jack2(): log.info('request.args %s', request.args) log.info('request.data %s', request.data) log.info('request.headers %s', request.headers) log.info('request.form %s', request.form) log.info('request.json %s', request.json) return 'jack'
def on_channel_message(self, account_id, channel_id, message): player = self.id_to_nick(account_id) channel = self.id_to_channel(channel_id) log.info("(%s) %s: %s" % (channel, player, message)) response = self.parse_message(MSG_N, player, channel, message) if response is not None: self.send_channel_message(response, channel_id) log.info("(%s) \033[96m%s\033[0m: %s" % (channel, self.bot.nickname, response))
def close(self): if self.__db__ is None: return True log.info(f"disconnecting to db: {self.host}:{self.port}/{self.dbname}") self.__db__.commit() self.__db__.close() self.__db__ = None self.__cursor__ = None return True
def login(self, username, password): log.info("Logging in..") if len(password) != 32: password = md5(password).hexdigest() try: self._login(username, password) except MasterServerError, e: log.error(e) return False
def __restore_clazz_other(self, patt2, kk, vv): if re.match(patt2, kk): na = kk[0:kk.rindex('.')] clz_name = kk[kk.rindex('.') + 1:] mo = get_module(na) # setattr(mo, clz_name, self.clazz_origin.pop(kk)) setattr(mo, clz_name, getattr(self.mod, clz_name)) self.clazz_origin.pop(kk) log.info("restore imported class %s at %s", kk, mo.__name__)
def handle_new_server(event, message): if(ffservices.protoctl["NS"]): source=Server.findByNumeric(message.source) server=Server(message.parameters[0], message.parameters[1], message.parameters[-1], message.parameters[2]) else: source=Server.findByName(message.source) server=Server(message.parameters[0], message.parameters[1], message.parameters[-1]) Server.addServer(server) log.info("Server connecting at %s: %s (numeric %d, %d hops): %s", source.name if source is not None else "[None]", server.name, server.numeric, server.hopcount, server.description)
def module_start(): global dev_null_serv dev_null_serv=Pseudoclient.create("DevNullServ", "DevNullServ", "devnull", "services.client", "Message sink") if(dev_null_serv in (False, None)): log.info("DevNullServ: Can't create pseudoclient!") return False dev_null_serv.help="""DevNullServ - Message sink. Any messages sent to DevNullServ (with the exception of HELP) will be ignored.""" return True
def __main__(): """main test entry point""" log.info('SNAP GPT Test Utils') args = __arguments__() __check_args__(args) # check if arguments are corrected properties = __load_properties__(args.properties) # load properties file __check_properties__(properties) # check if properties are correct exit_code = 0 if __run_tests__(args, properties) else 1 # run tests with given parameters exit(properties, exit_code) # if tests fails exit with status code
def login(self): """ Wrapper function for convience and logic, handles both logging in and connecting. """ log.info("Logging in...") try: self._login(config.username, config.password) except MasterServerError, e: log.error(e) return False
def logout(self): log.info("Disconnecting...") if not self.is_connected: self.logged_in = False return try: self._chat_disconnect() except ChatServerError, e: log.error(e)
def __restore_method_internal(self, patt, k, original_func): if re.match(patt, k): r_first_dot = k.rindex('.') func_name = k[r_first_dot + 1:] r_second_dot = str(k).rindex('.', 0, r_first_dot - 1) clz_name = k[r_second_dot + 1:r_first_dot] # setattr(self.mod, func_name, original_func) clz = getattr(self.mod, clz_name) setattr(clz, func_name, original_func) self.clazz_method_origin.pop(k) log.info("restore class method %s", k)
def set_timerange(self, create_version=False): # Set time range to that in MSSQL if we are creating a version for snapshot and the check # box for the menu entry that controls this is true otherwise, use the current frame range if create_version == True and menuItem("bz_PlayblastEditorialRangeChk", query=True, checkBox=True): log.info("Setting timerange to Editorial range stored in database") self.shot.set_timeline() else: log.info("Playblasting timerange currently set in Maya") self.min_frame = int(playbackOptions(minTime=True, query=True)) self.max_frame = int(playbackOptions(maxTime=True, query=True))
def open(self): if self.__db__ is not None: return True log.info(f"connecting to db: {self.host}:{self.port}/{self.dbname}") self.__db__ = pymysql.connect(host=self.host, port=int(self.port), user=self.user, password=self.password, db=self.dbname, cursorclass=pymysql.cursors.DictCursor) return True
def handle_cmd_register(source, command, c_text): global db_cursor, nickserv c_params=c_text.split() if(len(c_params)==0): nickserv.sendMsg(source, "The \x02register\x02 command required at least one argument.") return if(len(c_params)==1 and config.get("Services/ff_NickServ/Registration/RequireEmail")): nickserv.sendMsg(source, "A valid email address is required to register your nickname.") return try: #db_cursor.execute("select count(`nick`) from `ff_nickserv_core` where `nick` like %s", (source)) #existing_nick_count=db_cursor.fetchone()[0] #if(existing_nick_count>0): # nickserv.sendMsg(source, "The nick \x02%s\x02 is already registered.", source) # return if(nick_is_registered(source)): #will return true if an error is encountered to prevent registration of the same nick twice nickserv.sendMsg(source, "The nick \x02%s\x02 is already registered.", source) return conf_code=hashlib.md5(str(random.random())+str(time.time())).hexdigest() db_cursor.execute("""insert into `ff_nickserv_core` (`nick`,`password`,`email`,`time_registered`,`time_last_seen`,`email_confirmed`,`activated`,`disabled`,`group`,`confirmation_code`) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", ( source, hash_password(source, c_params[0]), c_params[1] if len(c_params)>1 else None, long(time.time()), long(time.time()), 0 if config.get("Services/ff_NickServ/Registration/RequireEmail Confirmation") else 1, 0 if config.get("Services/ff_NickServ/Registration/RequireOperActivation") else 1, 0, None, conf_code )) if(config.get("Services/ff_NickServ/Registration/RequireEmail Confirmation")): #todo: send email #if email fails, delete the nick and display an error nickserv.sendMsg(source, "An activation email has been sent to \x02%s\x02 with a confirmation code. When you have recieved the email, you will have to enter the command \x02/msg NickServ confirm \x1fconfirmationcode\x1f\x02. Until you do so, you will not be able to identify with this nickname.", c_params[1]) if(config.get("Services/ff_NickServ/Registration/RequireOperActivation")): nickserv.sendMsg(source, "You will not be able to identify using this nickname until an IRC operator has activated your account.") nickserv.sendMsg(source, "The nickname \x02%s\x02 has been registered using the password \x02%s\x02 - please memorize your password or keep it in a safe place, as it may be impossible to retrieve it.", source, c_params[0]) log.info("NickServ: Registering new nick and creating group for '%s' (email: %s)", source, c_params[1] if len(c_params)>1 else "none") except Exception as e: nickserv.sendMsg(source, "There was a problem registering your nickname.") log.error("Can't register nick %s: %s", source, str(e)) return False
def disable_scheduling(batch_client: batch.BatchServiceClient): """ Disable scheduling for the current node """ pool_id = config.pool_id node_id = config.node_id node = batch_client.compute_node.get(pool_id, node_id) if node.scheduling_state == batch.models.SchedulingState.enabled: batch_client.compute_node.disable_scheduling(pool_id, node_id) log.info("Disabled task scheduling for this node") else: log.info("Task scheduling is already disabled for this node")
def docker_tag_id(self, tag_name): """ Gets tag id from tag name. """ query = f"SELECT ID FROM dockerTags WHERE name='{tag_name}';" res = self.execute(query) if not res: log.info(f'inserting dockerTag `{tag_name}` into DB') query = f"INSERT INTO dockerTags (name) VALUES ('{tag_name}');" self.execute(query) return self.docker_tag_id(tag_name) return res[0][0]
def delete(self, grid): session = DBSession() session.query(self.model).filter(self.model.grid == grid).update( {'flag': 'D'}) try: session.commit() log.info("Comando executado com sucesso !") log.info(session) return session except Exception as e: log.debug("Ocorreu um erro ao salvar as configurações !\n" + e.__str__()) session.rollback() return None
def http_transport(encoded_span): # encoding prefix explained in https://github.com/Yelp/py_zipkin#transport #body = b"\x0c\x00\x00\x00\x01"+encoded_span body = encoded_span zipkin_url = "http://127.0.0.1:9411/api/v2/spans" zipkin_url = "http://{host}:{port}/api/v2/spans".format( host=app.config["ZIPKIN_HOST"], port=app.config["ZIPKIN_PORT"]) headers = {"Content-Type": "application/x-thrift"} r = requests.post(zipkin_url, data=body, headers=headers) log.info(type(encoded_span)) log.info(encoded_span) log.info(body) log.info(r) log.info(r.content)
def __wrap_method_internal(self): for k, v in self.mod.__dict__.items(): try: if not inspect.isclass(v) or getattr( v, '__module__') != self.mod.__name__: continue meta_dict = self.get_aspect_clazz_methods(k, v) if len(meta_dict) == 0: continue meta_clazz = v for kk, meth in meta_clazz.__dict__.items(): if kk.startswith("__"): continue # meth = getattr(meta_clazz, kk) meth_func = getattr(meta_clazz, kk) # print '11 ', kk, ', \t ', type(meth), ' \t, ', type(meth_func) if not is_function(meth) and not is_method(meth): continue func_name = kk if func_name not in meta_dict: continue if str(type(meth)).find('staticmethod') > -1: # setattr(meta_clazz, kk, profile_aspect()(meth_func, meta_clazz)) setattr(meta_clazz, kk, staticmethod(profile_aspect()(meth_func))) elif str(type(meth)).find('function') > -1: setattr(meta_clazz, kk, profile_aspect()(meth)) elif str(type(meth)).find('classmethod') > -1: # setattr(meta_clazz, kk, profile_aspect()(getattr(meth_func, 'im_func'), meta_clazz)) setattr( meta_clazz, kk, classmethod(profile_aspect()(getattr( meth_func, 'im_func')))) else: setattr(meta_clazz, kk, profile_aspect()(meth_func)) log.info("code profile for method - %s.%s.%s", meta_clazz.__module__, meta_clazz, func_name) setattr(self.mod, k, meta_clazz) self.aspect_clazzs[v] = meta_dict self.clazz_origin[self.mod.__name__ + "." + k] = v except: log.error('first aspect module class %s error: %s', self.mod.__name__, utils.current_exception_info())
def docker_tag_id(self, tag_name): """ Gets tag id from tag name. """ query = f"SELECT ID FROM dockerTags WHERE name='{tag_name}';" res = self.execute(query) if not res: new_id = self.execute( 'SELECT (MAX(ID)+1) AS id FROM dockerTags;')[0]['id'] log.info(f'inserting dockerTag `{tag_name}` into DB') query = f"INSERT INTO dockerTags (ID, name) VALUES ({new_id}, '{tag_name}');" self.execute(query) return self.docker_tag_id(tag_name) return res[0]['ID']
def daemon(): pid = os.fork() if pid != 0: exit(0) os.setsid() fd = os.open('/dev/null', os.O_RDWR) os.dup2(fd, sys.stdin.fileno()) os.dup2(fd, sys.stdout.fileno()) os.dup2(fd, sys.stderr.fileno()) os.close(fd) log.info(0, 'daemon process run')
def wrap_function(self): if not does_profile_switch_on() or not does_local_ip_matched(): log.info( 'code_profile_switch is False or does_local_ip_matched is False' ) return log.info('start profile method for %s pattern is %s', self.mod.__name__, self.function_pattern) for k, v in self.mod.__dict__.items(): self.__wrap_function_internal(k, v) # aspect functions that are imported by from .. import imported_modules = [] for na in all_module_names.copy(): mo = get_module(na) if mo is None: continue imported_modules.append(na) self.__wrap_other_function(mo) log.info("search imported module %s", str(imported_modules)) log.info('end profile method for %s pattern is %s', self.mod.__name__, self.function_pattern)
def close(self): if self.__db__ is None: return True log.info(f"disconnecting to db: {self.db_path}") self.__db__.commit() self.__db__.close() self.__db__ = None self.__cursor__ = None if self.locker: # remove locker os.remove(self.__locker_path__) return True
def chat_test(self): log.info("Testing chat server...") status = "" note = "" global down_count try: response = self._chat_connect() status = "Up" note = "Chat server is OK." down_count = 0 except ChatServerError, e: status = "Down" note = e.error down_count += 1
def __init__(self, shotfile): self.shotfile = shotfile self.shot = shotfile.shot self.show = shot.sequence.show log.info( "Getting data for playblast for %s.%s" % (self.sequence, self.shot)) self.min_frame = 0 self.max_frame = 0 self.local_pblast_name = "C:/temp/banzai_data/temp_playblast" # Path to RV executables self.rv_path = "C:/Program Files (x86)/Tweak/RV-3.10/bin" if not os.path.exists(self.rv_path): self.rv_path = "C:/Program Files (x86)/Tweak/RV-3.8/bin" if not os.path.exists(self.rv_path): log.error("Can't find the path to RV or RVIO - email [email protected]") self.rv_support_path = os.getenv('RV_SUPPORT_PATH')
def create_reply(self, message): """ Create a response from the bot's algorithms and returns that. """ response = self.get_reply(message) # During the early days of the bot's brain, he'd often just copy the sentence word for word. if response.lower() == message.lower(): log.info("Duplicate message, not responding") return if response == "I don't know enough to answer yet!": log.info("Not enough knowledge to answer yet") return # Don't send empty messages if response == "": return return response
def configure(self): """ Sets up the data from the database so it can be used for setting...settings. The DB structure sucks, so some extra processing to get the correct datatypes. TODO: Clean up, I'm writing this at 2AM.. """ log.info("Loading configuration from the database...") settings = dict(db.query("""SELECT `key`, `value` FROM settings""")) log.info("Config loaded") log.info("HoN Version: %s Chat Port: %s Protocol: %s" % (settings['honver'], settings['chatport'], settings['chatver'])) if 'username' in settings: acc_config['username'] = settings['username'] if 'password' in settings: acc_config['password'] = settings['password'] if 'invis' in settings: settings['invis'] = True if settings['invis'] == "True" else False if 'chatport' in settings: settings['chatport'] = int(settings['chatport']) if 'chatver' in settings: settings['chatver'] = int(settings['chatver']) for key in settings: if key in basic_config: basic_config[key] = settings[key] self._configure(chatport=settings['chatport'], protocol=settings['chatver'], invis=settings['invis'], masterserver=settings['masterserver'], basicserver=settings['basicserver'], honver=settings['honver'])
def login_test(self): """ The aim of this test is to retrieve the cookie and auth hash from the master server. First the master server should be checked for basic connectivity. A basic ping is likely not possible because the server would drop ICMP requests and can be seen in the results below. PING masterserver.hon.s2games.com (199.7.76.170) 56(84) bytes of data. --- masterserver.hon.s2games.com ping statistics --- 3 packets transmitted, 0 received, 100% packet loss, time 2008ms """ log.info("Testing login server...") status = "" note = "" try: response = self._login(acc_config['username'], acc_config['password']) status = "Up" note = "Login server is OK." except MasterServerError, e: status = "Down" note = e.error
def main(): """ The main event to call, the bot connects to HoN and starts processing events. Disconnects should be caught and automatic re-connection can be handled. """ honbot = HoNBot('bot-brain') client = HoNBotClient(honbot) def sigint_handler(signal, frame): log.info("SIGINT, quitting") client.logout() sys.exit() signal.signal(signal.SIGINT, sigint_handler) reconnect_attempts = 0 while not honbot.is_quitting: time.sleep(1) # Cooling.. client.login() while client.is_logged_in and not honbot.is_quitting: if client.is_connected is True: # Reset the number of attempts. reconnect_attempts = 0 # Do some stuff if I want time.sleep(1) else: reconnect_attempts += 1 log.info("Disconnected from chat server") log.info("Reconnecting in 30 seconds (Attempts %d of 5)" % reconnect_attempts) time.sleep(30) try: client.connect() except ChatServerError, e: log.error(e)
def main(): db.connect(config.dbhost, config.dbuser, config.dbpass, config.dbname) hon_monitor = HoNStatus() test_count = 1 while True: log.info("Running test #" + str(test_count)) # Reconfigure the monitor. hon_monitor.configure() login_status, login_reason = hon_monitor.login_test() log.info("Login server: %s - %s" % (login_status, login_reason)) chat_status, chat_reason = hon_monitor.chat_test() log.info("Chat Server: %s - %s" % (chat_status, chat_reason)) # MotD data can be checked each test, regardless of the server statuses. try: hon_monitor.motd_parser() except MasterServerError, e: if e.code == 108: log.error('Could not obtain MotD data from the Master server') # Check that all tests returned good, otherwise the test fails and should # be re-attempted in 90 seconds if login_status is "Up" and chat_status is "Up": hon_monitor.logged_in = True timer = 0 while hon_monitor.is_logged_in: timer += 1 if timer >= 300: hon_monitor.disconnect_logout() break else: time.sleep(1) # Client disconnected, cool down for a moment log.debug("Client disconnected, cooling..") time.sleep(2) else: # Start dropping the players online to zero once it's been determined that # the servers are down. if down_count > 5: db.execute("""INSERT INTO players (time, value) VALUES (%s, %s)""", [str(int(time.time())), 0]) time.sleep(90) # Loop increment test_count += 1 # And log back out again hon_monitor.logged_in = False
def handle_squit(event, message): servername=message.parameters[0] if(message.command=="ERROR" or servername==config.get("Server/Name")): log.info("Shutting down: %s", message.parameters[-1]) ffservices.shutdown(0) return server=Server.findByName(servername) if(server is None): return if(server.hopcount==1): log.info("Removing pseudoserver %s: requested by %s: %s", server.name, message.source, message.parameters[-1]) Server.removeServer(server) else: log.info("Server exiting: %s: SQUIT from %s: %s", server.name, message.source, message.parameters[-1]) #luckily as long as we don't specify NOQUIT in our protoctl, unreal will notify #us of each user that is going away BEFORE sending us the SQUIT message, meaning #that the existing code for removing users is used rather than having to figure #out which users are exiting here. Server.removeServer(server)
def sigint_handler(signal, frame): log.info("SIGINT, quitting") client.logout() sys.exit()
def on_private_message(self, player, message): log.info("\033[34m(Private message from %s)\033[0m %s" % (player, message)) response = self.parse_message(MSG_P, player, self.bot.nickname, message) if response is not None: self.send_private_message(player, response) log.info("\033[34m(Private message to %s)\033[0m %s" % (player, response))
def on_whisper(self, player, message): log.info("\033[94m(Whisper from %s)\033[0m %s" % (player, message)) response = self.parse_message(MSG_W, player, self.bot.nickname, message) if response is not None: self.send_whisper(player, response) log.info("\033[94m(Whispered to %s)\033[0m %s" % (player, response))
def on_entered_channel(self, channel_id, user): log.info("(%s) \033[32m%s entered the channel.\033[0m" % (self.id_to_channel(channel_id), user.nickname))
def on_left_channel(self, channel): log.info("\033[92mLeft\033[0m [%s]" % channel) del self.channels[channel]
def on_joined_channel(self, channel, channel_id, topic, operators, users): log.info("\033[92mJoined \033[0m[%s - %s]" % (channel, topic)) if channel not in self.channels: self.channels[channel] = {'speaking' : True, 'learning': True}
def execute(self, percent=100, textured=False, dynamics_enabled=False, create_version=False, comment=None, batch=False): debug = 0 # First, make sure we're in GUI mode - can't playblast otherwise from pymel.core.general import about if about(batch=True): log.warning( "Can't perform playblast in batch mode - requires GUI to run") return # We're in GUI mode, continue with playblast log.info( "Performing playblast of shot %s" % self.shot) # Create version if we're playblasting to snapshot for approvals if create_version: log.info( "Publishing shot %s prior to playblast" % self.shot) if not debug: if comment or batch: self.shot.vault() else: from internal.publishing import gui as publish_gui published = publish_gui.publish_shot_gui(self.shot) if not published: log.warning( "Playblast of %s was cancelled" % self.shot) return False # Store a list of selected objects, to restore at the end # Deselect all objects, so that no wireframes show selected = ls(selection=True) select(deselect=True) # Set the start and end timerange appropriately self.set_timerange(create_version = create_version) # Construct the window to playblast through - this stuff is in the # core.gui.animation module from core.gui import animation as anim_gui playblast_window, model_editor = anim_gui.playblast_window( self.shot.process, self.width, self.height, textured=textured, dynamics_enabled=dynamics_enabled) # Need to set then reset the image format in the render globals - for some stupid reason, Autodesk # uses this setting for playblasts as of 2011 - didn't for the last 15 years. default_render_globals = ls('defaultRenderGlobals')[0] prev_image_format = None if default_render_globals: log.info("Setting render globals to IFF for playblast") prev_image_format = default_render_globals.imageFormat.get() default_render_globals.imageFormat.set(7) # 7 == IFF # Do the actual playblast - have to defer the evaluation of the # command, to give the window time to draw playblast_finished = playblast(format="iff", filename=self.local_pblast_name, viewer=False, showOrnaments=False, fp=4, percent=100, fo=True, quality=100) # Reset the render globals to what the user had it set to before if prev_image_format: log.info("Resetting render globals to user defined value: %s" % prev_image_format) default_render_globals.imageFormat.set(prev_image_format) if not playblast_finished: log.warning("User cancelled the playblast for %s - not saving to snapshot" % self.shot) if selected: select(selected) return if create_version: # Publish the movie file to snapshot self.encode() self.publish() # Delete the playblast window now that we're done with it - # use deferred to ensure that the playblast is done before # deleting the window evalDeferred('from pymel.core import deleteUI; deleteUI("%s")' % playblast_window) # Restore selection if selected: select(selected) # Run RV on the resulting images - if we're in batch mode, # skip this, and if we're not creating a version in the DB, # then it's a local playblast - run RV on the local images # instead of on the movie in snapshot if not batch: if create_version: self.playback(movie=True) else: self.playback()
return False return True def logout(self): log.info("Disconnecting...") if not self.is_connected: self.logged_in = False return try: self._chat_disconnect() except ChatServerError, e: log.error(e) log.info("Logging out...") try: self._logout() except MasterServerError, e: log.error(e) self.logged_in = False def on_auth_accepted(self, *p): """ Authenticated, join the default channels and set up some base things. """ log.info("Connected as %s" % self.account.nickname) self.bot.nickname = self.account.nickname for channel in self.channels.keys(): self.join_channel(channel)
def publish(self): log.info("Publishing movie for %s to snapshot" % self.shot) # Get paths for the playblast from MSSQL log.info( "Getting playblast paths") self.local_file = "%s/%s" % (self.local_path, self.movie_file) self.server_file = "%s/%s" % (self.shotfile.playblast_server_path, self.movie_file) # Copy the movie file to the database, and log it with MSSQL log.info( "Saving movie for shot %s to snapshot and network file storage" % self.shot) try: from_file = "%s/%s" % (self.local_path, self.movie_file) to_file = "%s/%s" % (self.server_path, self.movie_file) log.info("Copying %s > %s" % (from_file, to_file)) shutil.copy(from_file, to_file) log.info( "Copied %s > %s" % (from_file, to_file)) from_file = "%s/%s" % (self.local_path, self.movie_file) to_file = "%s/%s" % (self.server_path_version, self.movie_file) log.info("Copying %s > %s" % (from_file, to_file)) shutil.copy(from_file, to_file) log.info( "Copied %s > %s" % (from_file, to_file)) except: log.error( "Could not copy playblast for shot %s to server paths %s and/or %s" % (self.shot, self.server_path, self.server_path_version)) else: # Store info in MSSQL sql.create_playblast_version(self.shot.show.code, self.shot.sequence.code, self.shot.code, self.shot.process, 1)
def encode(self): import subprocess, re # Encode movie file with RVIO to send to the snapshot log.info("Encoding movie to send to snapshot") progress = 0 # @note: progressWindow is bogus - can't set the size, to have to fake the ultimate size by setting the # status message really large, then overwriting it with the real status. progressWindow( title = "Playblast Movie Encode", progress = progress, status = "---------------------------------------------------------------------------------------------------", isInterruptable=False) try: log.info("Getting local and server paths for %s" % self.shot) self.local_path = ("C:/temp/banzai_data/projects/%s/movies/%s" % (self.shot.show.code, self.shot.sequence.code)) self.local_file = "%s/%s" % (self.local_path, self.movie_file) # Make sure the directories exist first - create it if not, and bail if we fail if not self.create_dirs(self.local_path): log.error("Could not create local %s dir for playblast of %s" % (self.local_path, self.shot)) return if not self.create_dirs(self.server_path): log.error("Could not create server %s dir for playblast of %s" % (self.server_path, self.shot)) return log.info("Created local and server paths for the playblast of %s" % self.shot) encode_sp = None burn_in = "" if self.rv_support_path: burn_in = RvioInfo(self.shotfile, self.shot, self.sequence, self.show).burn_in_string() # RVIO can fail if there's not enough memory - @todo : this needs to be # tuned over time. threads = 4 free_memory = memory(freeMemory=True) frames = self.shot.frame_out - self.shot.frame_in if free_memory < 2000 and frames > 50: threads = 1 elif free_memory < 3000 and frames > 50: threads = 2 log.info("Utilizing %s cores to playblast and encode" % threads) if not self.shot.audio.exists(): log.info("Playblasting to snapshot without audio") encode_sp = subprocess.Popen( ('"%s/rvio" %s.%s-%s@@@@.iff -o %s \ %s \ -codec avc1 -quality .75 \ -outgamma 0.65 -v -outfps %i \ -rthreads %s' % ( self.rv_path, self.local_pblast_name, self.min_frame, self.max_frame, self.local_file, burn_in, self.shot.get_fps(), threads)), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) else: log.info("Playblasting to snapshot with audio") log.info("Audio path: %s" % self.shot.audio.path) encode_sp = subprocess.Popen( ('"%s/rvio" [ %s.%s-%s@@@@.iff %s ] -o %s \ %s \ -codec avc1 -quality .75 \ -outgamma 0.65 -v -outfps %i \ -rthreads %s' % ( self.rv_path, self.local_pblast_name, self.min_frame, self.max_frame, self.shot.audio.path, self.local_file, burn_in, self.shot.get_fps(), threads)), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) log.info("Encoding playblast with RVIO for %s" % self.shot) while True and encode_sp: # Continue reading from stdout until RVIO is finished, then break next_line = encode_sp.stdout.readline() if not next_line: break # Search for a % marker in the RVIO output, then "decode" it to get the % done if re.search("%", next_line): tmp = next_line.split("(")[1] tmp = tmp.split("%")[0] progress = int(float(tmp)) progressWindow( edit=True, progress=progress, status=('Encode: ' + next_line)) log.info(next_line.strip()) progress += 1 except: log.error("Something failed during playblast of %s : %s" % (self.shot, sys.exc_info()[0])) raise finally: # Ensure that we close the progressWindow, and unlock Maya for use progressWindow(endProgress=True)