class TExportHumanFiles: @staticmethod def parse_args(arg_list): parser = argparse.ArgumentParser() parser.add_argument("--table", dest='table', default="declarations_documentfile") parser.add_argument("--document-file-id", dest='document_file_id', required=False) parser.add_argument("--tmp-folder", dest='tmp_folder', default=None) parser.add_argument("--dlrobot-human-json", dest='dlrobot_human_json', default="human_files.json") parser.add_argument("--start-from-an-empty-file", dest='start_from_empty', action="store_true", default=False) parser.add_argument("--max-files-count", dest='max_files_count', type=int) parser.add_argument("--mysql-port", dest='mysql_port', type=int, default=None) parser.add_argument("--pdf-conversion-timeout", dest='pdf_conversion_timeout', default=1*60*60, type=int, help="pdf conversion timeout") parser.add_argument("--pdf-conversion-queue-limit", dest='pdf_conversion_queue_limit', type=int, default=100 * 2 ** 20, help="max sum size of al pdf files that are in pdf conversion queue", required=False) return parser.parse_args(arg_list) def __init__(self, args): self.logger = setup_logging(log_file_name="export_human_files.log") self.args = args if self.args.tmp_folder is None: self.args.tmp_folder = tempfile.mkdtemp("export_human") self.logger.debug("create folder {}".format(self.args.tmp_folder)) else: self.logger.debug("rm folder {}".format(self.args.tmp_folder)) shutil.rmtree(self.args.tmp_folder, ignore_errors=True) os.mkdir(self.args.tmp_folder) self.source_doc_client = TSourceDocClient(TSourceDocClient.parse_args([]), self.logger) self.pdf_conversion_client = TDocConversionClient(TDocConversionClient.parse_args([]), self.logger) self.smart_parser_server_client = TSmartParserCacheClient(TSmartParserCacheClient.parse_args([]), self.logger) self.new_pdfs = set() def __enter__(self): self.pdf_conversion_client.start_conversion_thread() return self def __exit__(self, exc_type, exc_value, traceback): self.pdf_conversion_client.stop_conversion_thread() shutil.rmtree(self.args.tmp_folder, ignore_errors=True) def unarchive(self, input_file): base_name, file_extension = os.path.splitext(os.path.basename(input_file)) output_folder = os.path.dirname(input_file) dearchiver = TDearchiver(self.logger, output_folder) for _, _, filename in dearchiver.dearchive_one_archive(file_extension, input_file, base_name): yield filename def download_file_and_unzip(self, file_url, filename): file_without_extension, extension = os.path.splitext(filename) if not os.path.isfile(filename): self.logger.debug("download {0} to {1}".format(file_url, filename)) result = requests.get(file_url) with open(filename, 'wb') as fd: fd.write(result.content) if extension == '.zip': try: for archive_filename in self.unarchive(filename): yield archive_filename except Exception as e: self.logger.error("cannot unzip {}, exception={}".format(filename, e)) else: yield filename else: if extension == '.zip': for archive_filename in glob.glob("{}_*".format(file_without_extension)): yield archive_filename else: yield filename def get_all_file_sql_records(self): if self.args.mysql_port is None: db = pymysql.connect(db="declarator", user="******", password="******", unix_socket="/var/run/mysqld/mysqld.sock" ) else: db = pymysql.connect(db="declarator", user="******", password="******", port=self.args.mysql_port) cursor = db.cursor() if self.args.document_file_id is not None: where_clause = "where f.id = {}\n".format(self.args.document_file_id) else: where_clause = "" query = (""" select f.id, d.id, f.file, f.link, d.office_id, d.income_year from {} f join declarations_document d on f.document_id=d.id {} """.format(self.args.table, where_clause)) self.logger.debug(query.replace("\n", " ")) cursor.execute(query) for (document_file_id, document_id, filename, link, office_id, income_year) in cursor: if filename is not None and len(filename) > 0: yield document_file_id, document_id, filename, link, office_id, income_year cursor.close() db.close() def download_unzip_and_send_file_source_doc_server(self, declarator_url_path, document_file_id): path, declarator_filename = os.path.split(declarator_url_path) _, ext = os.path.splitext(declarator_filename) ext = ext.lower() temp_file = os.path.join(self.args.tmp_folder, "{}{}".format(document_file_id, ext)) declarator_url = os.path.join(DECLARATOR_DOMAIN, "media", urllib.parse.quote(declarator_url_path)) declarator_url = declarator_url.replace('\\', '/') for file_name in self.download_file_and_unzip(declarator_url, temp_file): self.source_doc_client.send_file(file_name) if file_name.lower().endswith('.pdf'): _, extension = os.path.splitext(file_name) self.pdf_conversion_client.start_conversion_task_if_needed(file_name, extension) self.new_pdfs.add(build_dislosures_sha256(file_name)) else: self.smart_parser_server_client.send_file(file_name) yield file_name, declarator_url self.pdf_conversion_client.wait_all_tasks_to_be_sent() for f in os.listdir(self.args.tmp_folder): os.unlink(os.path.join(self.args.tmp_folder, f)) def fix_list(self, sha256, office_id): fixed_office_id = FIX_LIST.get(sha256) if fixed_office_id is not None: return fixed_office_id else: return office_id def export_files(self): human_files_db = TDlrobotHumanFileDBM(self.args.dlrobot_human_json) if self.args.start_from_empty: human_files_db.create_db() else: human_files_db.open_write_mode() document_file_ids = set() for sha256, doc in human_files_db.get_all_documents(): for ref in doc.decl_references: if ref.document_file_id is not None: document_file_ids.add(ref.document_file_id) files_count = 0 for document_file_id, document_id, file_path, link, office_id, income_year in self.get_all_file_sql_records(): if document_file_id in document_file_ids: continue while self.pdf_conversion_client.server_is_too_busy(): self.logger.error("wait pdf conversion_server for 5 minutes, last_pdf_conversion_queue_length={}".format( self.pdf_conversion_client.last_pdf_conversion_queue_length )) time.sleep(5*60) web_site = urlsplit_pro(link).netloc if web_site.startswith('www.'): web_site = web_site[len('www.'):] if self.args.max_files_count is not None and files_count >= self.args.max_files_count: break self.logger.debug("export document_file_id={}".format(document_file_id)) for local_file_path, declarator_url in self.download_unzip_and_send_file_source_doc_server(file_path, document_file_id): sha256 = build_dislosures_sha256(local_file_path) self.logger.debug("add {}, sha256={}".format(local_file_path, sha256)) source_document = TSourceDocument(os.path.splitext(local_file_path)[1]) ref = TDeclaratorReference() ref.document_id = document_id ref.document_file_id = document_file_id ref._site_url = web_site ref.office_id = self.fix_list(sha256, office_id) ref.income_year = income_year ref.document_file_url = declarator_url source_document.add_decl_reference(ref) human_files_db.update_source_document(sha256, source_document) files_count += 1 self.logger.debug('added files count: {}'.format(files_count)) human_files_db.close_db() self.send_new_pdfs_to_smart_parser() def send_new_pdfs_to_smart_parser(self): self.logger.debug("wait pdf conversion for {} seconds".format(self.args.pdf_conversion_timeout)) self.pdf_conversion_client.wait_doc_conversion_finished(self.args.pdf_conversion_timeout) missed_pdf_count = 0 received_pdf_count = 0 for sha256 in self.new_pdfs: self.logger.debug("try to converted file for {}".format(sha256)) handle, temp_filename = tempfile.mkstemp(suffix=".docx") os.close(handle) if self.pdf_conversion_client.retrieve_document(sha256, temp_filename): received_pdf_count += 1 self.logger.debug("send the converted file to smart parser") self.smart_parser_server_client.send_file(temp_filename) else: self.logger.error("converted file is not received") missed_pdf_count += 1 os.unlink(temp_filename) if missed_pdf_count > 0: self.logger.error('received_pdf_count = {}, missed_pdf_count={}'.format(received_pdf_count, missed_pdf_count))
class TDlrobotHTTPServer(http.server.HTTPServer): max_continuous_failures_count = 7 PITSTOP_FILE = ".dlrobot_pit_stop" @staticmethod def parse_args(arg_list): parser = argparse.ArgumentParser() parser.add_argument( "--server-address", dest='server_address', default=None, help= "by default read it from environment variable DLROBOT_CENTRAL_SERVER_ADDRESS" ) parser.add_argument("--dlrobot-config-type", dest='dlrobot_config_type', required=False, default="prod", help="can be prod, preliminary or test") parser.add_argument("--custom-offices-file", dest='offices_file', required=False) parser.add_argument("--log-file-name", dest='log_file_name', required=False, default="dlrobot_central.log") parser.add_argument("--remote-calls-file", dest='remote_calls_file', default=None) parser.add_argument("--result-folder", dest='result_folder', required=True) parser.add_argument("--tries-count", dest='tries_count', required=False, default=2, type=int) parser.add_argument("--central-heart-rate", dest='central_heart_rate', required=False, default='60s') parser.add_argument( "--check-yandex-cloud", dest='check_yandex_cloud', default=False, action='store_true', required=False, help="check yandex cloud health and restart workstations") parser.add_argument( "--skip-worker-check", dest='skip_worker_check', default=False, action='store_true', required=False, help="skip checking that this task was given to this worker") parser.add_argument("--enable-ip-checking", dest='enable_ip_checking', default=False, action='store_true', required=False) parser.add_argument("--disable-smart-parser-server", dest="enable_smart_parser", default=True, action="store_false", required=False) parser.add_argument("--disable-source-doc-server", dest="enable_source_doc_server", default=True, action="store_false", required=False) parser.add_argument("--disable-search-engines", dest="enable_search_engines", default=True, action="store_false", required=False) parser.add_argument("--disable-telegram", dest="enable_telegram", default=True, required=False, action="store_false") parser.add_argument("--disable-pdf-conversion-server-checking", dest="pdf_conversion_server_checking", default=True, required=False, action="store_false") parser.add_argument("--web-site-regexp", dest="web_site_regexp", required=False) parser.add_argument("--office-source-id", dest="office_source_id", required=False) parser.add_argument( "--round-file", dest="round_file", default=TDeclarationRounds.default_dlrobot_round_path) args = parser.parse_args(arg_list) args.central_heart_rate = convert_timeout_to_seconds( args.central_heart_rate) if args.server_address is None: args.server_address = os.environ['DLROBOT_CENTRAL_SERVER_ADDRESS'] if args.check_yandex_cloud: assert TYandexCloud.get_yc() is not None return args def __init__(self, args): self.register_task_result_error_count = 0 self.logger = setup_logging(log_file_name=args.log_file_name, append_mode=True) self.conversion_client = TDocConversionClient( TDocConversionClient.parse_args([]), self.logger) self.args = args rounds = TDeclarationRounds(args.round_file) self.dlrobot_remote_calls = TRemoteDlrobotCallList( logger=self.logger, file_name=args.remote_calls_file, min_start_time_stamp=rounds.start_time_stamp) self.worker_2_running_tasks = defaultdict(list) self.worker_2_continuous_failures_count = defaultdict(int) offices = TOfficeTableInMemory() offices.read_from_local_file(self.args.offices_file) self.web_sites_db = TDeclarationWebSiteList(self.logger, offices=offices) if not os.path.exists(self.args.result_folder): os.makedirs(self.args.result_folder) self.web_sites_to_process = self.find_projects_to_process() self.cloud_id_to_worker_ip = dict() self.config = TRobotConfig.read_by_config_type( self.args.dlrobot_config_type) self.last_remote_call = None # for testing host, port = self.args.server_address.split(":") self.logger.debug("start server on {}:{}".format(host, port)) super().__init__((host, int(port)), TDlrobotRequestHandler) self.last_service_action_time_stamp = time.time() self.service_action_count = 0 self.decl_sender = TDeclarationSender( self.logger, self.args.enable_smart_parser, self.args.enable_source_doc_server) self.stop_process = False if self.args.enable_ip_checking: self.permitted_hosts = set( str(x) for x in ipaddress.ip_network('192.168.100.0/24').hosts()) self.permitted_hosts.add('127.0.0.1') self.permitted_hosts.add('95.165.96.61') # disclosures.ru self.logger.debug("init complete") self.send_to_telegram("start dlrobot central with {} tasks".format( len(self.web_sites_to_process))) def send_to_telegram(self, message): if self.args.enable_telegram: self.logger.debug("send to telegram: {}".format(message)) telegram_send.send(messages=[message]) def stop_server(self): self.server_close() self.shutdown() def verify_request(self, request, client_address): if self.args.enable_ip_checking: (ip, dummy) = client_address if ip not in self.permitted_hosts: return False return True def log_process_result(self, process_result): s = process_result.stdout.strip("\n\r ") if len(s) > 0: for line in s.split("\n"): self.logger.error("task stderr: {}".format(line)) s = process_result.stderr.strip("\n\r ") if len(s) > 0: for line in s.split("\n"): self.logger.error("task stderr: {}".format(line)) def have_tasks(self): return len(self.web_sites_to_process) > 0 and not self.stop_process def project_is_to_process(self, project_file): interactions = self.dlrobot_remote_calls.get_interactions(project_file) if sum(1 for i in interactions if i.task_was_successful()) > 0: return False tries_count = self.args.tries_count if sum(1 for i in interactions if not i.task_ended()) > 0: # if the last result was not obtained, may be, # worker is down, so the problem is not in the task but in the worker # so give this task one more chance tries_count += 1 self.logger.debug("increase max_tries_count for {} to {}".format( project_file, tries_count)) return len(interactions) < tries_count def save_dlrobot_remote_call(self, remote_call: TRemoteDlrobotCall): self.dlrobot_remote_calls.add_dlrobot_remote_call(remote_call) if not remote_call.task_was_successful(): if self.project_is_to_process(remote_call.project_file): self.web_sites_to_process.append(remote_call.web_site) self.logger.debug("register retry for {}".format( remote_call.web_site)) def find_projects_to_process(self): web_sites_to_process = list() self.logger.info("filter web sites") web_site_info: TDeclarationWebSite for web_site, web_site_info in self.web_sites_db.web_sites.items(): if self.args.web_site_regexp is not None: if re.match(self.args.web_site_regexp, web_site) is None: continue if self.args.office_source_id is not None: if web_site_info.get_parent_source_id( ) != self.args.office_source_id: continue if TWebSiteReachStatus.can_communicate(web_site_info.reach_status): project_file = TRemoteDlrobotCall.web_site_to_project_file( web_site) if self.project_is_to_process(project_file): web_sites_to_process.append(web_site) self.logger.info("there are {} sites in the input queue".format( len(web_sites_to_process))) web_sites_to_process.sort( key=(lambda x: self.dlrobot_remote_calls.last_interaction[x])) with open("web_sites_to_process_debug.txt", "w") as out: for w in web_sites_to_process: out.write(w + "\n") return web_sites_to_process def get_running_jobs_count(self): return sum(len(w) for w in self.worker_2_running_tasks.values()) def get_processed_jobs_count(self): return len(list(self.dlrobot_remote_calls.get_all_calls())) def get_new_project_to_process(self, worker_host_name, worker_ip): site_url = self.web_sites_to_process.pop(0) project_file = TRemoteDlrobotCall.web_site_to_project_file(site_url) self.logger.info( "start job: {} on {} (host name={}), left jobs: {}, running jobs: {}" .format(project_file, worker_ip, worker_host_name, len(self.web_sites_to_process), self.get_running_jobs_count())) remote_call = TRemoteDlrobotCall(worker_ip=worker_ip, project_file=project_file, web_site=site_url) remote_call.worker_host_name = worker_host_name web_site_passport = self.web_sites_db.get_web_site(site_url) regional_main_pages = list() if web_site_passport is None: self.logger.error( "{} is not registered in the web site db, no office information is available for the site" ) project_content_str = TRobotProject.create_project_str( site_url, regional_main_pages, disable_search_engine=not self.args.enable_search_engines) self.worker_2_running_tasks[worker_ip].append(remote_call) return remote_call, project_content_str.encode("utf8") def untar_file(self, project_file, result_archive): base_folder, _ = os.path.splitext(project_file) output_folder = os.path.join(self.args.result_folder, base_folder) + ".{}".format( int(time.time())) compressed_file = io.BytesIO(result_archive) decompressed_file = gzip.GzipFile(fileobj=compressed_file) tar = tarfile.open(fileobj=decompressed_file) tar.extractall(output_folder) return output_folder def pop_project_from_running_tasks(self, worker_ip, project_file): if worker_ip not in self.worker_2_running_tasks: raise Exception( "{} is missing in the worker table".format(worker_ip)) worker_running_tasks = self.worker_2_running_tasks[worker_ip] for i in range(len(worker_running_tasks)): if worker_running_tasks[i].project_file == project_file: return worker_running_tasks.pop(i) raise Exception("{} is missing in the worker {} task table".format( project_file, worker_ip)) def worker_is_banned(self, worker_ip, host_name): return self.worker_2_continuous_failures_count[(worker_ip, host_name)] > \ TDlrobotHTTPServer.max_continuous_failures_count def update_worker_info(self, worker_host_name, worker_ip, exit_code): key = (worker_ip, worker_host_name) if exit_code == 0: self.worker_2_continuous_failures_count[key] = 0 else: self.worker_2_continuous_failures_count[key] += 1 if self.worker_is_banned(worker_ip, worker_host_name): self.send_to_telegram( "too many dlrobot errors from ip {}, hostname={}, the host is banned, " "you have to restart dlrobot_central to unban it".format( worker_ip, worker_host_name)) def register_task_result(self, worker_host_name, worker_ip, project_file, exit_code, result_archive): if self.args.skip_worker_check: remote_call = TRemoteDlrobotCall(worker_ip, project_file) else: try: remote_call = self.pop_project_from_running_tasks( worker_ip, project_file) except: if ipaddress.ip_address(worker_ip).is_private: self.logger.debug( "try to get a result {} from a local ip {}, though this task was not dispatched" .format(project_file, worker_ip)) remote_call = TRemoteDlrobotCall(worker_ip, project_file) else: raise self.update_worker_info(worker_host_name, worker_ip, exit_code) remote_call.worker_host_name = worker_host_name remote_call.exit_code = exit_code remote_call.end_time = int(time.time()) project_folder = self.untar_file(project_file, result_archive) remote_call.calc_project_stats(self.logger, self.web_sites_db, project_folder, self.config) if not TWebSiteReachStatus.can_communicate(remote_call.reach_status): remote_call.exit_code = -1 self.decl_sender.send_declaraion_files_to_other_servers(project_folder) self.save_dlrobot_remote_call(remote_call) self.last_remote_call = remote_call self.logger.debug( "got exitcode {} for task result {} from worker {} (host_name = {})" .format(exit_code, project_file, worker_ip, worker_host_name)) def forget_old_remote_processes(self, current_time): for running_procs in self.worker_2_running_tasks.values(): for i in range(len(running_procs) - 1, -1, -1): remote_call = running_procs[i] elapsed_seconds = current_time - remote_call.start_time if elapsed_seconds > self.config.get_kill_timeout_in_central(): self.logger.debug( "task {} on worker {}(host={}) takes {} seconds, probably it failed, stop waiting for a result" .format(remote_call.web_site, remote_call.worker_ip, remote_call.worker_host_name, elapsed_seconds)) running_procs.pop(i) remote_call.exit_code = 126 self.save_dlrobot_remote_call(remote_call) def forget_remote_processes_for_yandex_worker(self, cloud_id): worker_ip = self.cloud_id_to_worker_ip.get(cloud_id) if worker_ip is None and len(self.cloud_id_to_worker_ip) > 0: self.logger.info( "I do not remember ip for cloud_id {}, cannot delete processes" .format(cloud_id)) return running_procs = self.worker_2_running_tasks.get(worker_ip, list()) for i in range(len(running_procs) - 1, -1, -1): rc = running_procs[i] self.logger.debug( "forget task {} on worker {} since the workstation was stopped" .format(rc.project_file, rc.worker_ip)) running_procs.pop(i) rc.exit_code = 125 self.save_dlrobot_remote_call(rc) if cloud_id in self.cloud_id_to_worker_ip: del self.cloud_id_to_worker_ip[cloud_id] def check_yandex_cloud(self): if not self.args.check_yandex_cloud: return None try: if not check_internet(): self.logger.error( "cannot connect to google dns, probably internet is down") return None for m in TYandexCloud.list_instances(): cloud_id = m['id'] if m['status'] == 'STOPPED': self.forget_remote_processes_for_yandex_worker(cloud_id) self.logger.info( "start yandex cloud worker {}".format(cloud_id)) TYandexCloud.start_yandex_cloud_worker(cloud_id) elif m['status'] == "RUNNING": worker_ip = TYandexCloud.get_worker_ip(m) if self.args.enable_ip_checking: self.permitted_hosts.add(worker_ip) self.cloud_id_to_worker_ip[cloud_id] = worker_ip except Exception as exp: self.logger.error(exp) def check_pdf_conversion_server(self): if not self.args.pdf_conversion_server_checking: return True return not self.conversion_client.server_is_too_busy() def service_actions(self): current_time = time.time() if current_time - self.last_service_action_time_stamp >= self.args.central_heart_rate: self.service_action_count += 1 if self.service_action_count % 10 == 0: self.logger.debug('alive') self.last_service_action_time_stamp = current_time if os.path.exists(self.PITSTOP_FILE): self.stop_process = True self.logger.debug( "stop sending tasks, exit for a pit stop after all tasks complete" ) os.unlink(self.PITSTOP_FILE) if self.stop_process and self.get_running_jobs_count() == 0: self.logger.debug("exit via exception") raise Exception("exit for pit stop") try: self.forget_old_remote_processes(current_time) except Exception as exp: self.logger.error(exp) self.check_yandex_cloud() if not self.check_pdf_conversion_server(): self.logger.debug( "stop sending tasks, because conversion pdf queue length is {}" .format(self.conversion_client. last_pdf_conversion_queue_length)) def get_stats(self): workers = dict((k, list(r.write_to_json() for r in v)) for (k, v) in self.worker_2_running_tasks.items()) stats = { 'running_count': self.get_running_jobs_count(), 'input_tasks': len(self.web_sites_to_process), 'processed_tasks': self.get_processed_jobs_count(), 'worker_2_running_tasks': workers, 'last_service_action_time_stamp': self.last_service_action_time_stamp, 'central_heart_rate': self.args.central_heart_rate, 'register_task_result_error_count': self.register_task_result_error_count } if self.stop_process: stats['stop_process'] = True return stats