def update(params): assert (type(params).__name__ == "UpdateParams") device = params.device testset = params.config.get(device.name, "testset") auth = params.auth update = params.update assert (type(update).__name__ == "ImageDescription") try: _wait_ping_response(device, 10) except NoConnectionError: common.log("Device %s not powered, booting" % device.name) _reboot_device(config, device, hard=True, downtime=30) try: _flash_image(params.config, device, auth, update.zip_url) common.log("Installed new images on %s" % device.name) return update.new_image except common.RunShError as e: common.error(str(e)) common.log("Failed to install any images on %s" % device.name) return None except NoConnectionError: common.error("No network connection to %s, probably failed to flash" % device.name) return None
def add_text(self, text): lines = text.split("\n") if not all([line.strip().startswith("#") or line.strip() == "" for line in lines]): error("invalid text: lines must be prefixed with" " # (as comment) or empty") self._lines.extend(lines)
def capture_packets(params, tag='src', src_tag=None): if tag == 'src': port_info = src_info elif tag == 'dst': port_info = dst_info else: error('tag has to be one of [src, dst]!') return # XXX TODO # If src_tag and dst_tag are the same, then we need to monitor on just # br-int. Else, we will need to monitor on qr- ports (router ports) port_info['pids'] = [] for port in port_info['ports'].keys(): intf = port_info['ports'][port] filename = '%s.tcpdump.%s.txt' % (tag, intf) if os.path.isfile(filename): os.remove(filename) cmd = 'sudo tcpdump -v icmp -i %s -c %d -l > %s 2>&1' % ( intf, params['count'], filename) pid = subprocess.Popen(cmd, shell=True).pid port_info['pids'].append(pid) status_update( '%s: tcpdump launched with pid %d for interface %s' % (tag, pid, intf))
def _get_patternish_paths_from_diff(self, diff_fp): patternish_paths = set() for line in diff_fp: m = re.match(r"[AMD] {7}(?P<path_or_url>\S+)", line) if m: path_or_url = m.group("path_or_url") if path_or_url.startswith("http://"): patternish_paths.add(create_pattern_from_url(path_or_url)) continue else: path = path_or_url else: m = re.match( r"\+\+\+ (?P<path>\S+)(\s*\((?P<context>[^)]+)\))?", line) if not m: continue path, context = m.group("path", "context") if context and "working copy" not in context: error("cannot recognize the origin of the diff, please" " pass the --summarize option to svn and try again") path_info = self._svn.get_wc_path_info(path) if path_info is None: error( "the diff/patch modifies the file \"{0}\", which does not" " exist relative to the current working directory (make" " sure you are located in the directory in which the diff" " was created)".format(path)) patternish_paths.add( self._get_patternish_paths(".", [path]).keys()[0]) return patternish_paths
def do_downloads_by_server(self, arg): """List the movies requested by servers and number of requests.""" args = arg.split() if len(args) != 0: common.error('`downloads_by_server` doesn\'t' 'expect any arguments.') else: servers = self.central_server.download_service.get_servers() requests = self.central_server.client_service.get_requests() if not servers.is_empty(): print("%i server(s):" % len( servers.servers)) print('') for server in servers.servers: print('server:') print(str(server)) print('downloads:') server_requests = requests.get_requests_from_server(server) if server_requests: print(tabulate( [request.to_row() for request in server_requests], headers=['Movie', 'Client'], tablefmt="psql")) print('') else: print('No downloads\n') else: print('There\'s no available servers')
def parse(self, model, root_node, fields): attrs = tools.node_attributes(root_node) self.title = attrs.get('string', 'Unknown') on_write = '' #attrs.get('on_write', '') axis = [] axis_data = {} for node in root_node.childNodes: node_attrs = tools.node_attributes(node) if node.localName == 'field': axis.append(str(node_attrs['name'])) axis_data[str(node_attrs['name'])] = node_attrs # # TODO: parse root_node to fill in axis # try: import graph view = graph.ViewGraph(model, axis, fields, axis_data, attrs) except Exception, e: import common import traceback import sys tb_s = reduce(lambda x, y: x + y, traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback)) common.error('Graph', _('Can not generate graph !'), details=tb_s, parent=self.window) view = EmptyGraph(model, axis, fields, axis_data, attrs)
def get_bridge_entry(br): bridge_dict = info['bridges'] if not bridge_dict.has_key(br): error('Bridge ' + br + ' does not exist! Supported bridges: ' + str(bridge_dict.keys())) return None return bridge_dict.get(br)
def save(self): try: with open(self._filepath, 'w') as f: f.write(str(self)) f.write("\n") except IOError as e: error("Could not write review state: %s" % e)
def get_random_associations(self) : random_associations = [] for i in range(self.amount_different_cards) : for association in self.associations : if (association.selected == False) : association.selected = True random_associations.append(association) break else : # if all the associations were selected and we still need one, there's a setup problem ! common.error("Not enough associations available. Please check your XML setup.") return (None, None) # we position images and texts which might be displayed # (in case there would be more than one in some associations) for association in random_associations : association.select_random_image() return random_associations
def clscall(cls, mtd, *args, **kwargs): """ Executes a class method referred like strings that is published into a package which is part of the running environment. :param cls: class name. could the name of the class of the instance :param mtd: method name :return: tuples value containing the status and the output of the called function """ try: if isinstance(cls, str): sig = type(cls, (), {}) object = sig() else: object = cls common.debug("Calling method %s from class %s" % (mtd, type(object)), "clscall") method = getattr(object, mtd) _output = method(*args, **kwargs) _status = True if _output is not None: _output = _output.strip() except BaseException as err: common.error("Error while executing class function: %s" % str(err), "clscall") _status = False _output = str(err) if common.istrace: traceback.print_exc() return _status, _output
def getText(element, i18n_dict = None, lang = None): # returns the text inside an XML tag nodelist = element.childNodes rc = u"" key = element.getAttribute("key") if (cmp(key, "") != 0) : if (i18n_dict != None) : rc = i18n_dict.get(lang, key) else : common.error("Got an element with an i18n key, but no dictionary is available") else : for node in nodelist: if node.nodeType == node.TEXT_NODE: nd = node.data # suppresses new line characters (\r\n) # suppresses tabs # suppresses spaces nd = nd.strip(u"\r\n\t ") rc = rc + nd return rc
def invoke(cmd, ctx): """Launch the given command in the current shell.""" if cmd == "None": cmd() # print command line = make_line(cmd) ctx.print_command(line) # prepare process proc = subprocess.Popen(line, shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE) # prepare handling if out, err map = { proc.stdout: ctx.out, proc.stderr: ctx.err } ins = [proc.stdout, proc.stderr] while ins: useds, x, y = select.select(ins, [], []) for used in useds: line = used.readline() if line: map[used].write(line) else: ins.remove(used) # wait end of called process r = proc.wait() if r <> 0: common.error("build failed")
def start(base): # TODO: Check when two clients are running common.exit_cleanly() # http://stackoverflow.com/questions/11423225 signal.signal(signal.SIGPIPE, signal.SIG_DFL) plugins = os.path.join(base, "plugins") if not os.path.isdir(plugins): common.error("no plugins directory: `%s`" % plugins, E_NO_PLUGINS) # TODO: Check for broken symlinks common.populate(saxo_path, base) opt = configparser.ConfigParser(interpolation=None) config = os.path.join(base, "config") opt.read(config) # TODO: Defaulting? # TODO: Warn if the config file is widely readable? sockname = os.path.join(base, "client.sock") serve(sockname, incoming) os.chmod(sockname, 0o600) # NOTE: If using os._exit, this doesn't work def remove_sock(sockname): if os.path.exists(sockname): os.remove(sockname) atexit.register(remove_sock, sockname) common.thread(scheduler.start, base, incoming) saxo = Saxo(base, opt) saxo.run()
def load(self, content): if content.strip() == "": self.reset() return try: state = json.loads(content) if state[STATE_VERSION] == 1: if type(state[STATE_DIFF_CHECKSUMS]) != dict \ or type(state[STATE_UNCOMMITTED]) != bool: error("malformed state file") elif state[STATE_VERSION] == 2: if type(state[STATE_DIFF_CHECKSUMS]) != dict \ or type(state[STATE_UNCOMMITTED]) != bool \ or type(state[STATE_UNPUSHED]) != bool: error("malformed state file") if type(state[STATE_BRANCH_PARENT]) not in [unicode, str] \ and state[STATE_BRANCH_PARENT] is not None: error("malformed state file") else: error("unsupported state file version, please use a newer" " version of devtools.") except (ValueError, KeyError): error("malformed state file") self._state = state
def check_required_elements(topology): invalid_topo = False for rq in ['nodes', 'defaults']: if not rq in topology: common.error("Missing '%s' element" % rq, category=common.MissingValue, module="topology") invalid_topo = True if invalid_topo: common.fatal("Fatal topology errors, aborting") if not 'name' in topology: topo_name = os.path.basename( os.path.dirname(os.path.realpath(topology['input'][0]))) topology.name = topo_name topology.defaults.name = topology.name topo_elements = topo_main_elements + topo_internal_elements if topology.get('module'): topology.defaults.module = topology.module topo_elements = topo_elements + topology.module for k in topology.keys(): if not k in topo_elements: common.error("Unknown top-level element %s" % k, category=common.IncorrectValue, module="topology")
def review_id(self, id): if id == "new": id = None if id is None or (hasattr(id, "isdigit") and id.isdigit()): self._review_id = id else: error("invalid review_id argument")
def fail(self, msg = None): """Called to record a failed configuration.""" self.result = False if self.blocking: common.error("cannot configure %s: %s" % self.name, msg) else: self.ctx.print_action_failure(msg)
def do_movies_by_server(self, arg): """List the available movies by server.""" args = arg.split() if len(args) != 0: common.error('`movies_by_server` doesn\'t expect any arguments.') else: movies, servers = \ self.central_server.download_service.movies_by_server() if not servers.is_empty(): print("%i available server(s):" % len( servers.servers)) print('') for server in servers.servers: print('server:') print(str(server)) print('movies:') if not movies.is_empty(): print(tabulate( [movie.to_row() for movie in movies.movies if server in movies.get_servers(movie).servers], headers=['Id', 'Title', 'Size'], tablefmt="psql")) print('') else: print('No movies\n') else: print('There\'s no available servers')
def filesize(files): abort = False limit = int(common.get_option('filesize-hook.max-size', default=1024**2)) check_all_files = common.get_option('filesize-hook.type', "all").strip().lower() != "binary" too_big_files = [] common.note('Checking files size...') count = 0 for f in files: check_file = check_all_files or common.binary(f.contents) if check_file: common.trace('Checking ' + str(f.path) + ' size...') count += 1 if f.size > limit: too_big_files.append(f) common.note('%d file(s) checked.' % count) if too_big_files: common.error(WARNING % limit) for f in too_big_files: common.error(FILEWARN % (f.path, f.size, limit)) abort = True return abort
def do_clients_by_server(self, arg): """List the clients handled by each server""" args = arg.split() if len(args) != 0: common.error('`clients_by_server` doesn\'t expect any arguments.') else: servers = self.central_server.download_service.get_servers() if not servers.is_empty(): print("%i server(s):" % len( servers.servers)) print('') for server in servers.servers: print('server:') print(str(server)) print('clients:') if server.clients: clients = [client[0] for client in server.clients] print(tabulate( [[c.username, c.host, str(c.port)] for c in clients], headers=['Username', 'Host', 'Port'], tablefmt="psql")) print('') else: print('No clients\n') else: print('There\'s no available servers')
def update_line_access_token(self, new_access_token): try: line = 'p4l.line.accessToken={0}\n'.format(new_access_token) with open(self.LINE_ACCESS_TOKEN_PATH, 'w') as configfile: configfile.write(line) except Exception, e: error(e)
def new_user(): username = request.json.get('username') password = request.json.get('password') email = request.json.get('email') first_name = request.json.get('fname') last_name = request.json.get('lname') if not username or not password or not email: return error(400, 1010,'Some login information was not provided') hash = pbkdf2_sha256.encrypt(password, rounds=200000, salt_size=16) if db.session.query(db.Users).filter_by(username = username).first() is not None: return error(400, 1020,'This username is not available') # existing user if db.session.query(db.Users).filter_by(email = email).first() is not None: return error(400, 1040,'A user with this email already exists') # existing user user = db.Users(username = username) user.password = hash user.email = email user.first_name = first_name user.last_name = last_name db.session.begin() db.session.add(user) db.session.commit() return jsonify({'redirectUrl':'/',"params":"successful=true"})
def get_data_from_line(self, payload): retry_time = 0 while True: if retry_time == self.MAX_RETRY_TIME: error( 'Retrying too many times, so it will stop get data of {0}'. format(str(payload))) return None url = self.line_api_url line_token = self.read_line_access_token() headers = { 'Authorization': 'Bearer ' + line_token, 'Content-Type': 'application/json' } response = requests.post(url, headers=headers, data=json.dumps(payload), stream=True) result_code = response.status_code #token is expired if result_code == 401: self.check_and_renew_token() #if your token cannot access accountId, it do not need to retry elif result_code == 200 or "can't access to accountId with your token." in response.content: return response else: retry_time += 1 info('Retry at ' + str(retry_time)) sleep(1)
def cmd_group_add(self, name): try: self._server.add_group(name) self._output("Group {0} added. Make sure that the group exists in" " Review Board too.".format(name)) except ResourceConflict: error("Group {0} already exists".format(name))
def getText(element, i18n_dict=None, lang=None): # returns the text inside an XML tag nodelist = element.childNodes rc = u"" key = element.getAttribute("key") if (cmp(key, "") != 0): if (i18n_dict != None): rc = i18n_dict.get(lang, key) else: common.error( "Got an element with an i18n key, but no dictionary is available" ) else: for node in nodelist: if node.nodeType == node.TEXT_NODE: nd = node.data # suppresses new line characters (\r\n) # suppresses tabs # suppresses spaces nd = nd.strip(u"\r\n\t ") rc = rc + nd return rc
def calc_condition(self, model, cond): cond_main = cond[:] try: return ConditionExpr(cond).eval(model) except Exception, e: import common common.error('Wrong attrs Implementation!','You have wrongly specified conditions in attrs %s' %(cond_main,))
def delete_one(self, collection, query): coll = self.use_coll(collection) try: coll.remove(query) except: error('failed to delete documets: %s' % query) pass
def doanload_updates(self): release = self.check_updates() if release is not None: url = release["url"] file = url[url.rfind("/") + 1:len(url)] if not os.path.exists(self.UPDATE): os.makedirs(self.UPDATE) file = os.path.join(self.UPDATE, file) try: self.debug("Downloading new release: %s" % url) data = common.urlcall(url, output='binary') handler = open(file, 'wb') handler.write(data) handler.close() self.trace('Successfully wrote data to file: %s' % file) return True except IOError as e: common.error('Unable to write data to [%s] file: %s' % (file, str(e))) return False except Exception as e: common.error( 'Unknown error while downloading/writing data to [%s] file: %s' % (file, str(e))) return False else: return False
def parse(self, model, root_node, fields): attrs = tools.node_attributes(root_node) self.title = attrs.get("string", "Unknown") on_write = "" # attrs.get('on_write', '') axis = [] axis_data = {} for node in root_node: node_attrs = tools.node_attributes(node) if node.tag == "field": axis.append(str(node_attrs["name"])) axis_data[str(node_attrs["name"])] = node_attrs # # TODO: parse root_node to fill in axis # try: import graph view = graph.ViewGraph(model, axis, fields, axis_data, attrs) except Exception, e: import common import traceback import sys tb_s = reduce( lambda x, y: x + y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback) ) common.error("Graph", _("Can not generate graph !"), details=tb_s, parent=self.window) view = EmptyGraph(model, axis, fields, axis_data, attrs)
def ovs_ofctl_show_br_parser (bridge, parse_this): bridge_dict = info['bridges'] if not bridge_dict.has_key(bridge): error('Skipping bridge [' + bridge + ']! Supported bridges: ' + str(bridge_dict.keys())) return bridge_entry = bridge_dict.get(bridge) pprint.pprint(bridge_entry) for line in parse_this: m = re.search('(\d+)\((\S+)\):\s+addr:(\S+)', line) if m: port_id = m.group(1) port = m.group(2) port_mac = m.group(3) if not bridge_entry['ports'].has_key(port): bridge_entry['ports'][port] = {} port_entry = bridge_entry['ports'][port] port_entry['id'] = port_id port_entry['mac'] = port_mac continue m = re.search('(\w+)\((\S+)\):\s+addr:(\S+)', line) if m: port_id = m.group(1) port = m.group(2) port_mac = m.group(3) if not bridge_entry['ports'].has_key(port): bridge_entry['ports'][port] = {} port_entry = bridge_entry['ports'][port] port_entry['id'] = port_id port_entry['mac'] = port_mac pass
def get_random_associations(self): random_associations = [] for i in range(self.amount_different_cards): for association in self.associations: if (association.selected == False): association.selected = True random_associations.append(association) break else: # if all the associations were selected and we still need one, there's a setup problem ! common.error( "Not enough associations available. Please check your XML setup." ) return (None, None) # we position images and texts which might be displayed # (in case there would be more than one in some associations) for association in random_associations: association.select_random_image() return random_associations
def rpc_exec_auth(self, obj, method, *args): if self._open: try: sock = self._gw(self._url, self.db, self.uid, self._passwd, obj) return sock.exec_auth(method, *args) except socket.error, e: common.message(_('Unable to reach to OpenERP server !\nYou should check your connection to the network and the OpenERP server.'), _('Connection Error'), type=gtk.MESSAGE_ERROR) raise rpc_exception(69, 'Connection refused!') except Exception, e: if isinstance(e, (xmlrpclib.Fault, tiny_socket.Myexception)): a = rpc_exception(e.faultCode, e.faultString) if isinstance(e.faultCode, int): a.type = 'UserError' a.message = 'Error %s' % e.faultCode a.data = e.faultString if a.type in ('warning','UserError'): if a.message in ('ConcurrencyException') and len(args) > 4: if common.concurrency(args[0], args[2][0], args[4]): if CONCURRENCY_CHECK_FIELD in args[4]: del args[4][CONCURRENCY_CHECK_FIELD] return self.rpc_exec_auth(obj, method, *args) else: common.warning(a.data, a.message) else: common.error(_('Application Error'), e.faultCode, e.faultString) else: common.error(_('Application Error'), _('View details'), str(e)) #TODO Must propagate the exception? raise
def run(provider, context=None): try: if not context: context = Context() runner = Runner() context.debug('Starting module shell..') py_version = 'Python %s' % str(platform.python_version()) cx_version = context.getSystemVersion() context.notice( 'Starting %s (%s) on %s with %s' % (context.getName(), context.getVersion(), cx_version, py_version)) context.debug('Execution details: path = %s, parameters = %s' % (context.getPath(), str(context.getParams()))) # Run provider runner.run(provider, context) context.debug('Shutting down module shell..') except BaseException as bex: traceback.print_exc() common.error("Error running module shell: " + str(bex)) if context is not None: context.getUI().closeBusyDialog() context.getUI().onOk(context.getName(), "Error in module shell: " + str(bex)) else: common.OkDialog("Error in module shell: " + str(bex)) pass
def process_captures(tag='src'): if tag == 'src': port_info = src_info elif tag == 'dst': port_info = dst_info else: error('tag has to be one of [src, dst]!') return port_info['counts'] = {} port_info['pass'] = [] port_info['fail'] = [] for key in port_info['ports'].keys(): intf = port_info['ports'][key] # Assume tcpdump did not capture anything port_info['counts'][key] = 0 port_info['fail'].append(intf) filename = '%s.tcpdump.%s.txt' % (tag, intf) if not os.path.isfile(filename): continue with open(filename) as f: lines = f.readlines() for line in lines: m = re.search('(\d+)\s+packets captured', line) if m: port_info['counts'][key] = int(m.group(1)) port_info['pass'].append(intf) break
def handle_query(): """Outputs the results of the query or an error message.""" if args.json: try: result, info = do_query() print json.dumps({ 'status' : 'ok', 'result' : result }) except pymoira.BaseError as e: print json.dumps({ 'status' : 'error', 'message' : str(e) }) else: try: # Those are not real queries, and QueryInfo() would fail for them if args.query == '_help': show_help() return if args.query == '_list_queries': show_queries_list() return if args.query == '_list_users': show_user_list() return result, info = do_query() for row in result: fields = [ (field_name, row[field_name]) for field_name in info.outputs ] common.show_fields(*fields) print "" except pymoira.BaseError as err: common.error(err)
def parse(self, model, root_node, fields): attrs = tools.node_attributes(root_node) self.title = attrs.get('string', 'Unknown') on_write = '' #attrs.get('on_write', '') axis = [] axis_data = {} for node in root_node: node_attrs = tools.node_attributes(node) if node.tag == 'field': axis.append(str(node_attrs['name'])) axis_data[str(node_attrs['name'])] = node_attrs # # TODO: parse root_node to fill in axis # try: import graph view = graph.ViewGraph(model, axis, fields, axis_data, attrs) except Exception, e: import common import traceback import sys tb_s = reduce( lambda x, y: x + y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) common.error('Graph', _('Can not generate graph !'), details=tb_s, parent=self.window) view = EmptyGraph(model, axis, fields, axis_data, attrs)
def ovs_ofctl_show_br_parser(bridge, parse_this): bridge_dict = info['bridges'] if not bridge_dict.has_key(bridge): error('Skipping bridge [' + bridge + ']! Supported bridges: ' + str(bridge_dict.keys())) return bridge_entry = bridge_dict.get(bridge) pprint.pprint(bridge_entry) for line in parse_this: m = re.search('(\d+)\((\S+)\):\s+addr:(\S+)', line) if m: port_id = m.group(1) port = m.group(2) port_mac = m.group(3) if not bridge_entry['ports'].has_key(port): bridge_entry['ports'][port] = {} port_entry = bridge_entry['ports'][port] port_entry['id'] = port_id port_entry['mac'] = port_mac continue m = re.search('(\w+)\((\S+)\):\s+addr:(\S+)', line) if m: port_id = m.group(1) port = m.group(2) port_mac = m.group(3) if not bridge_entry['ports'].has_key(port): bridge_entry['ports'][port] = {} port_entry = bridge_entry['ports'][port] port_entry['id'] = port_id port_entry['mac'] = port_mac pass
def checkBadInput(self): badInputFilePath = os.path.join(common.getTestsPath(), u"{}.bad".format(self.path)) for line in self.iterFileLines(badInputFilePath): if self.passes(line): common.error(u"O corrector aceptou «{}».".format(line)) common.details(self.analyze(line)) self.errors += 1
def ArenaEnd(optId, UserId, ServerId, **para): '''战斗结束''' FightObj = mod.is_in_arena(UserId, ServerId) # 获取战斗对象 # 注意:由于返回的是弱引用,使用的时候应该加括号:FightObj() if not FightObj: return common.error(optId, -(optId * 1000 + 1)) #不在战斗中,无法结束战斗。 fight_result = FightObj().fight_over() if fight_result == False: #没有达到战斗结束的条件 return common.error(optId, -(optId * 1000 + 2)) #处理战斗结果 # + 发送消息给分服 RabbitMod.rm.send(optId, ServerId, copy.deepcopy(fight_result[(UserId, ServerId)])) # + 更新荣誉表 HonourMod.addHonour(UserId, ServerId, fight_result[(UserId, ServerId)]['gainHonour'], time.time()) #从竞技场中退出 stat = mod.leave_arena(UserId, ServerId) if stat: #返回战斗结果给玩家 return common.out( optId, body={'FightResult': fight_result[(UserId, ServerId)]}) #成功 return common.error(optId, -(optId * 1000 + 3)) #不在竞技场战斗中
def capture_packets(params, tag='src', src_tag=None): if tag == 'src': port_info = src_info elif tag == 'dst': port_info = dst_info else: error('tag has to be one of [src, dst]!') return # XXX TODO # If src_tag and dst_tag are the same, then we need to monitor on just # br-int. Else, we will need to monitor on qr- ports (router ports) port_info['pids'] = [] for port in port_info['ports'].keys(): intf = port_info['ports'][port] filename = '%s.tcpdump.%s.txt' % (tag, intf) if os.path.isfile(filename): os.remove(filename) cmd = 'sudo tcpdump -v icmp -i %s -c %d -l > %s 2>&1' % ( intf, params['count'], filename) pid = subprocess.Popen(cmd, shell=True).pid port_info['pids'].append(pid) status_update('%s: tcpdump launched with pid %d for interface %s' % (tag, pid, intf))
def stop(args): base = base_option(args) if "." in __name__: from .saxo import client else: from saxo import client try: client("quit", base=base) except: ... pidfile = os.path.join(base, "pid") if not os.path.exists(pidfile): common.error("There is no bot currently running") with open(pidfile, encoding="ascii") as f: text = f.read() pid = int(text.rstrip("\n")) # TODO: Make this less crude # This can give a ProcessLookupError: [Errno 3] No such process try: os.kill(pid, signal.SIGTERM) except ProcessLookupError: ... # os.kill(pid, signal.SIGKILL) return 0
def select_random_differences(self) : # the differences which will have to be found by the user self.differences_to_find = [] # the differences which will be masked (copy the rect from the original image) self.differences_to_mask = [] self.differences = common.randomize_list(self.differences) self.amount_differences = self.min_differences + random.randint(0, self.max_differences-self.min_differences) if (len(self.differences) < self.amount_differences) : common.error("Not enough differences available. Please check your XML setup : the value of the 'max_differences' tag is too high.") raise common.BadXMLException() for i in range(self.amount_differences) : difference = self.differences[0] self.differences.remove(self.differences[0]) self.differences_to_find.append(difference) # at this point, only differences which have to be masked are yet in the self.differences list self.differences_to_mask = self.differences
def rpc_exec_auth(self, obj, method, *args): if self._open: try: sock = self._gw(self._url, self.db, self.uid, self._passwd, obj) return sock.exec_auth(method, *args) except socket.error, e: common.message(_('Unable to reach to OpenERP server !\nYou should check your connection to the network and the OpenERP server.'), _('Connection Error'), type=gtk.MESSAGE_ERROR) raise rpc_exception(69, 'Connection refused!') except Exception, e: if isinstance(e, xmlrpclib.Fault) \ or isinstance(e, tiny_socket.Myexception): a = rpc_exception(e.faultCode, e.faultString) if a.type in ('warning','UserError'): if a.message in ('ConcurrencyException') and len(args) > 4: if common.concurrency(args[0], args[2][0], args[4]): if CONCURRENCY_CHECK_FIELD in args[4]: del args[4][CONCURRENCY_CHECK_FIELD] return self.rpc_exec_auth(obj, method, *args) else: common.warning(a.data, a.message) else: common.error(_('Application Error'), e.faultCode, e.faultString) else: common.error(_('Application Error'), _('View details'), str(e)) #TODO Must propagate the exception? raise
def get_schedule(device, config): current_image = device.config.get("general", "image_type") current_image_updated = device.config.get("last_update", current_image) testset = config.get(device.name, "testset") params = [current_image_updated, testset] result = types.SimpleNamespace() try: result = common.run_sh(common.CHECK_SCHEDULE_SCRIPT, params) flags_str = result.stdout.decode("UTF-8") except common.RunShError as e: common.error("Error in reading schedule for %s: %s" % \ (device.name, e.content.stderr.decode("UTF-8"))) result.allow_update = False result.upload_test_results = False return result flags = flags_str.strip().split(common.SCHEDULE_FLAG_SEPARATOR) if (len(flags) != 2): common.error("Schedule is errorneous for testset %s? Got a return value %s" % \ (testset, flags_str)) result.allow_update = False result.upload_test_results = False else: result.allow_update = flags[0] != "0" result.upload_test_results = flags[1] != "0" return result
def ArenaEnd(optId, UserId, ServerId, **para): '''战斗结束''' FightObj = mod.is_in_arena(UserId, ServerId) # 获取战斗对象 # 注意:由于返回的是弱引用,使用的时候应该加括号:FightObj() if not FightObj: return common.error(optId, -(optId * 1000 + 1)) #不在战斗中,无法结束战斗。 fight_result = FightObj().fight_over() if fight_result == False: #没有达到战斗结束的条件 return common.error(optId, -(optId * 1000 + 2)) #处理战斗结果 # + 发送消息给分服 RabbitMod.rm.send(optId, ServerId, copy.deepcopy(fight_result[(UserId, ServerId)])) # + 更新荣誉表 HonourMod.addHonour(UserId, ServerId, fight_result[(UserId, ServerId)]['gainHonour'], time.time()) #从竞技场中退出 stat = mod.leave_arena(UserId, ServerId) if stat: #返回战斗结果给玩家 return common.out(optId, body={'FightResult':fight_result[(UserId, ServerId)]}) #成功 return common.error(optId, -(optId * 1000 + 3)) #不在竞技场战斗中
def get(self, domain): url = 'http://%s/' % domain resp = common.requests_get(url) mf2 = mf2py.parse(resp.text, url=resp.url, img_with_alt=True) # logging.info('Parsed mf2 for %s: %s', resp.url, json.dumps(mf2, indent=2)) hcard = mf2util.representative_hcard(mf2, resp.url) logging.info('Representative h-card: %s', json.dumps(hcard, indent=2)) if not hcard: common.error( self, """\ Couldn't find a representative h-card (http://microformats.org/wiki/representative-hcard-parsing) on %s""" % resp.url) key = MagicKey.get_or_create(domain) obj = common.postprocess_as2(as2.from_as1( microformats2.json_to_object(hcard)), key=key) obj.update({ 'inbox': '%s/%s/inbox' % (appengine_config.HOST_URL, domain), 'outbox': '%s/%s/outbox' % (appengine_config.HOST_URL, domain), 'following': '%s/%s/following' % (appengine_config.HOST_URL, domain), 'followers': '%s/%s/followers' % (appengine_config.HOST_URL, domain), }) logging.info('Returning: %s', json.dumps(obj, indent=2)) self.response.headers.update({ 'Content-Type': common.CONTENT_TYPE_AS2, 'Access-Control-Allow-Origin': '*', }) self.response.write(json.dumps(obj, indent=2))
def MultiCastOpt(optId, UserId, ServerId, body, **para): '''广播战斗信息''' #参数检查 if isinstance(body, basestring): #如果是字符串,先尝试转成字典。 try: body = json.loads(body) except Exception: return common.error(optId, -(optId * 1000 + 1)) #不是jason字符串,失败。 if isinstance(body, dict): body['ServerTime'] = time.time() #加上服务器端时间戳 body['UserId'] = '%s.%s' % (ServerId, UserId) #加上UserId,ServerId else: return common.error(optId, -(optId * 1000 + 2)) #参数类型错误 FightObj = mod.is_in_arena(UserId, ServerId) # 获取战斗对象 # 注意:由于返回的是弱引用,使用的时候应该加括号:FightObj() if not FightObj: return common.error(optId, -(optId * 1000 + 3)) #不在战斗中,无法广播战斗信息。 #战斗过程验证放在此处 print '战斗是否结束', FightObj().is_fight_over() print '战斗是否超时', FightObj().is_time_out() print '战果是', FightObj().fight_over() print '当前损兵', FightObj().soldier_lose() print '1组与二组的级差', FightObj().user_level_diff() print '士兵和武将的平均等级', FightObj().army_level_avg() #开始广播 body = json.dumps({"body":body}) #广播之前,转成json。 stat = FightObj().zmq_muticast(body) if stat < 0: return common.error(optId, -(optId * 1000 - stat + 3)) # -1 发送内容不正确;-2 zmq发布失败 return common.out(optId) #广播成功
def __init__(self): common.debug('%s v%s has been started' % (common.AddonName(), common.AddonVersion())) try: if len(sys.argv) >= 2: params = dict(arg.split("=") for arg in sys.argv[1].split("&")) self._winid = params.get("window", "12006") else: self._winid = "12006" self.window = xbmcgui.Window(int(self._winid)) except Exception as ex: common.error('Unexpected error while parsing arguments: %s' % str(ex)) if self.addonrunning: common.debug( 'Script already running, no additional instance is needed') else: # addon setup self._configurations() self.__settings = MediaSlideshowSettings( updateSettingsMethod=self.setup) # self._nice() self._providers() if bool(self.PROVIDERS): self.execute() else: common.error("No data provider detected!") common.debug('%s v%s has been terminated' % (common.AddonName(), common.AddonVersion()))
def MultiCastOpt(optId, UserId, ServerId, body, **para): '''广播战斗信息''' #参数检查 if isinstance(body, basestring): #如果是字符串,先尝试转成字典。 try: body = json.loads(body) except Exception: return common.error(optId, -(optId * 1000 + 1)) #不是jason字符串,失败。 if isinstance(body, dict): body['ServerTime'] = time.time() #加上服务器端时间戳 body['UserId'] = '%s.%s' % (ServerId, UserId) #加上UserId,ServerId else: return common.error(optId, -(optId * 1000 + 2)) #参数类型错误 FightObj = mod.is_in_arena(UserId, ServerId) # 获取战斗对象 # 注意:由于返回的是弱引用,使用的时候应该加括号:FightObj() if not FightObj: return common.error(optId, -(optId * 1000 + 3)) #不在战斗中,无法广播战斗信息。 #战斗过程验证放在此处 print '战斗是否结束', FightObj().is_fight_over() print '战斗是否超时', FightObj().is_time_out() print '战果是', FightObj().fight_over() print '当前损兵', FightObj().soldier_lose() print '1组与二组的级差', FightObj().user_level_diff() print '士兵和武将的平均等级', FightObj().army_level_avg() #开始广播 body = json.dumps({"body": body}) #广播之前,转成json。 stat = FightObj().zmq_muticast(body) if stat < 0: return common.error(optId, -(optId * 1000 - stat + 3)) # -1 发送内容不正确;-2 zmq发布失败 return common.out(optId) #广播成功
def generate(self, data, element=None): NSMAP = { "d": "DAV:", "oc": "http://owncloud.org/ns", "nc": "http://nextcloud.org/ns" } try: # create the element itself xml = etree.Element(self._getXMLTag(data["root"], NSMAP), nsmap=NSMAP) if element is None else element # create any children recursively for k, v in (data["elements"].items() if element is None else data.items()): sub = etree.SubElement(xml, self._getXMLTag(k, NSMAP), nsmap=NSMAP) if type(v) is dict: self.generate(v, sub) elif type(v) is list: for value in v: lk = getValueByTagReference(value.keys()[0], self.data) lv = getValueByTagReference(value.values()[0], self.data) prop = etree.SubElement(sub, self._getXMLTag(lk, NSMAP), nsmap=NSMAP) prop.text = getValueByTagReference(lv, self.data) else: sub.text = getValueByTagReference(v, self.data) except Exception as e: error("XML generation failed: %s " % e, 1) return etree.tostring(xml).decode('utf-8')
def pro_manager(uid, sid, optId, para): '''协议管理''' try: if optId == 98001: #进入房间 return PvpUI.EnterRoom(optId, uid, sid, **para) elif optId == 98002: #离开房间 return PvpUI.LeaveRoom(optId, uid, sid, **para) elif optId == 98003: #离开竞技场 return PvpUI.LeaveArena(optId, uid, sid, **para) elif optId == 98004: #广播战斗信息 return PvpUI.MultiCastOpt(optId, uid, sid, **para) elif optId == 98005: #战斗结束 return PvpUI.ArenaEnd(optId, uid, sid, **para) elif optId == 98007: #获取本周所得荣誉 return PvpUI.GetWeekHonour(optId, uid, sid, **para) elif optId == 98997: #重载自定义模块 stat = Gcore.reload_userdefined_mod() if not stat: #重载自定义模块发生异常 return common.error(optId, -98997001) else: #成功重载自定义模块 return common.out(optId) elif optId == 98996: #开启竞技场 Gcore.arena_start() return common.out(optId) elif optId == 98995: #关闭竞技场 Gcore.arena_end() return common.out(optId) else: #未定义的协议号 return common.error(98998, -98998001) except Exception, e: #运行程序时,出现异常。 print e return common.error(98999, -98999001)
def checkGoodInput(self): goodInputFilePath = os.path.join(common.getTestsPath(), u"{}.good".format(self.path)) for line in self.iterFileLines(goodInputFilePath): if not self.passes(line): common.error(u"O corrector non aceptou «{}».".format(line)) details = self.analyze(line) common.details(details) self.errors += 1
def show_help(): try: query = args.arg[0] except IndexError: common.error( "Query name was not specified" ) return info, = client.query('_help', (query,)) print ' '.join(info).strip()
def makedir(path): """Build a directory if not existing, building possibly intermediate directories.""" path = str(path) if not os.path.isdir(path): try: os.makedirs(path) except os.error, e: common.error("cannot create '%s': %s" % (path, e))
def submit(self, session, module, artifact, no_argument=False): """ Run a single module against an artifact """ if no_argument: module_result = self.run(module, None) return module_result is_key, value = lookup_key(session, artifact) if is_key and value is None: error('Unable to find artifact key in session (%s)' % artifact) return elif is_key and value is not None: artifact = value else: pass artifact_type = detect_type(artifact) artifact = self.db.find(artifact_type, {'name': artifact}, one=True) if artifact is None: warning('Unable to find artifact in database (%s)' % artifact['name']) return None if module in self.modules[artifact['type']] or module in self.modules[artifact['subtype']]: pass else: warning('Artifact is not supported by module (%s)' % (artifact['name'])) return None result = self.run(module, artifact) if module in result['data'].keys(): if result['data'][module] is not None: if self.db.exists(artifact['type'], {'name': artifact['name']}): for child in result['children']: child_artifact = create_artifact(child['name'], parent=artifact['name'], _type=child['type'], source=child['source'], subtype=child['subtype']) if not self.db.exists(child['type'], {'name': child['name']}): self.db.insert_one(child['type'], child_artifact) self.db.update_one(artifact['type'], {'name': artifact['name']}, result) if len(result['children']) > 0: info('Created child artifacts: %d' % len(result['children'])) return result['data'][module] else: warning('No results found (%s)' % module) return None else: warning('Failed to get module results (%s)' % module)
def error(short_message, message, conf): """Error handling. Arguments: short_message: short description of the message message: message conf: configuration dictionary """ common.error('[Aozan] hiseq done: ' + short_message, message, conf[AOZAN_VAR_PATH_KEY] + '/hiseq.lasterr', conf)