コード例 #1
0
 def test_find_nearest_neighbour(self):
     # 1
     temp = json_parser.JsonParser('', '', self.log_filename)
     self.assertEqual(temp.find_nearest_neighbour(),
                      "Brak danych użytkowników - źle pobrane dane.")
     # 2
     self.assertEqual(len(self.parser.find_nearest_neighbour()), 10)
コード例 #2
0
 def test_list_of_duplicates(self):
     # 1
     self.assertEqual(len(self.parser.list_of_duplicates()), 0)
     temp = json_parser.JsonParser('', '', self.log_filename)
     # 2
     self.assertEqual(temp.list_of_duplicates(),
                      "Brak danych o postach - źle pobrane dane.")
     # 3
     temp.posts_data = json_parser.json.loads(
         '[{"title": "sth"}, {"title": "sth"}]')
     duplicates = temp.list_of_duplicates()
     self.assertEqual(len(duplicates), 1)
     # 4
     self.assertEqual(duplicates[0], 'sth')
コード例 #3
0
    def test_init(self):
        file = open(self.log_filename, "r+")
        file.truncate(0)
        file.close()

        json_parser.JsonParser('', '', self.log_filename)
        with open(self.log_filename, 'r+') as logfile:
            log = logfile.readline()
            self.assertTrue("Nieznany typ URLa" in log)

            json_parser.JsonParser('https://jsonplaceholder.',
                                   'https://jsonplaceholder.',
                                   self.log_filename)
            next(logfile)
            log = logfile.readline()
            self.assertTrue("Błędny URL" in log)

            json_parser.JsonParser('https://jsonplaceholder.typicode.co',
                                   'https://jsonplaceholder.typicode.co',
                                   self.log_filename)
            next(logfile)
            log = logfile.readline()
            self.assertTrue("Błędny URL, powód: Forbidden" in log)
        logfile.close()
コード例 #4
0
def develop():
    """Функция чтения данных из сокета

    """
    # Создаём объекты классов
    attribute_functions = af.AttributeFunctions()
    influxdb_client = influxdb_producer.InfluxBDProducer(env_type=env_type,
                                                         logger=logger,
                                                         cfg=cfg,
                                                         root_path=root_path)
    email_notification = en.EmailNotification(env_type=env_type,
                                              logger=logger,
                                              cfg=cfg,
                                              influxdb_client=influxdb_client)
    mssql_producer_row_insert = mssql.MSSQLProducer(env_type=env_type,
                                                    logger=logger,
                                                    cfg=cfg,
                                                    influxdb_client=influxdb_client,
                                                    root_path=root_path,
                                                    email_notification=email_notification)
    kafka_producer = kp.KafkaProducer(logger=logger,
                                      cfg=cfg,
                                      influxdb_client=influxdb_client,
                                      email_notification=email_notification)
    kafka_consumer = kc.KafkaConsumer(logger=logger,
                                      cfg=cfg,
                                      influxdb_client=influxdb_client,
                                      email_notification=email_notification)
    file_producer = fs_producer.FSProducer(logger=logger,
                                           influxdb_client=influxdb_client,
                                           email_notification=email_notification)
    json_parser = jp.JsonParser(logger=logger,
                                cfg=cfg,
                                email_notification=email_notification,
                                influxdb_client=influxdb_client,
                                env_type=env_type,
                                attribute_functions=attribute_functions,
                                mode_type=mode_type,
                                file_producer=file_producer)

    error_message_list = deque(maxlen=9)

    for i in range(100000):
        # Читаем сообщение из очереди Kafka
        deal = kafka_consumer.receive_message()
        if deal:
            # Запоминаем партицию и оффсет
            message_partition = deal.partition()
            message_offset = deal.offset()

            key = str(message_partition) + '_' + str(message_offset)

            result_dict = json_parser.parse_deal(tables_metadata=tables_metadata, deal=deal)
            if result_dict:
                sql = result_dict['sql_query']
                table = result_dict['table_name'].lower()
                content = str(result_dict['content'])
                headers = {'table': table}
                if mssql_producer_row_insert.execute_row(table, sql):
                    kafka_consumer.consumer.commit(message=deal, asynchronous=True)
                else:
                    # Пытаемся обработать сообщение несколько раз, если не получается, выходим с ошибкой
                    error_message_list.append(key)
                    influxdb_client.write_error(module="UNACKNOWLEDGED_MESSAGE")
                    if error_message_list.count(key) == 3:
                        # Записываем ошибочное сообщение в Kafka в топик ошибок
                        if kafka_producer.write_message(topic=cfg['kafka_broker']['producer_topic_errors'],
                                                        key=key,
                                                        message=content,
                                                        headers=headers):
                            kafka_consumer.consumer.commit(message=deal, asynchronous=True)
                            email_notification.send_error_notification()
                            sys.exit(1)
                        else:
                            email_notification.send_error_notification()
                            sys.exit(1)
                    else:
                        kafka_consumer.seek_message(partition=message_partition, offset=message_offset)
                    sleep(1)

    kafka_consumer.consumer.close()
コード例 #5
0
def batch(env_type, cfg, tables_metadata, mode_type, start_dt, table, root_path):
    """Запуск процесса чтения данных из файловой системы и запись сообщений в MSSQL

    Args:
        env_type (str): тип среды запуска программы
        cfg (dict): словарь параметров
        tables_metadata (dict): словарь метаданных по таблице
        mode_type (str): режим запуска программы
        start_dt (str): дата - нижняя граница чтения сообщений из файлов
        table (str): таблица для парсинга из файлов
        root_path (str): полный корневой путь к программе

    """
    start_time = time()
    # Создаём объекты классов
    attribute_functions = af.AttributeFunctions()
    logger = helpers.create_timed_rotating_log(mode_type=mode_type, cfg=cfg, root_path=root_path)
    influxdb_client = influxdb_producer.InfluxBDProducer(env_type=env_type,
                                                         logger=logger,
                                                         cfg=cfg,
                                                         root_path=root_path)
    email_notification = en.EmailNotification(env_type=env_type,
                                              logger=logger,
                                              cfg=cfg,
                                              influxdb_client=influxdb_client)
    mssql_producer = mssql.MSSQLProducer(env_type=env_type,
                                         logger=logger,
                                         cfg=cfg,
                                         influxdb_client=influxdb_client,
                                         root_path=root_path,
                                         email_notification=email_notification)
    file_consumer = fs_consumer.FSConsumer(logger=logger,
                                           cfg=cfg,
                                           influxdb_client=influxdb_client,
                                           start_dt=start_dt,
                                           table=table,
                                           email_notification=email_notification)
    json_parser = jp.JsonParser(logger=logger,
                                cfg=cfg,
                                email_notification=email_notification,
                                influxdb_client=influxdb_client,
                                env_type=env_type,
                                attribute_functions=attribute_functions,
                                mode_type=mode_type)

    # формируем список файлов для загрузки
    deals_files_list = file_consumer.prepare_messages_files_list()
    # удаляем сообщения из БД начиная с даты, указанной при запуске
    mssql_producer.delete_from_table_by_date(env_type=env_type,
                                             table=table,
                                             start_dt=start_dt,
                                             tables_metadata=tables_metadata)

    for deals_file in deals_files_list:
        # Читаем сообщение из плоского файла на сервере
        deals_file_result = file_consumer.read_messages_from_file(messages_file=deals_file)
        for deal in deals_file_result:
            result_dict = json_parser.parse_deal(tables_metadata=tables_metadata, deal=deal)
            if result_dict:
                sql = result_dict['sql_query']
                table = result_dict['table_name'].lower()
                if not mssql_producer.execute_row(table, sql):
                    influxdb_client.write_error(module="BATCH_UNPARSED_MESSAGE")

    logger.info("{0}: end parsing process of typology {1}. Elapsed time: ".format(mp.current_process().name, table) +
                str(round(time() - start_time, 2)) + " seconds")
コード例 #6
0
 def test_join_json_files(self):
     temp = json_parser.JsonParser('', '', self.log_filename)
     self.assertEqual(temp.join_json_files(),
                      "Brak danych użytkowników - źle pobrane dane.")
コード例 #7
0
 def setUp(self):
     self.log_filename = 'test_logs.log'
     self.parser = json_parser.JsonParser(
         "https://jsonplaceholder.typicode.com/posts",
         "https://jsonplaceholder.typicode.com/users", self.log_filename)