diff options
| author | Andrew <saintruler@gmail.com> | 2019-04-17 15:01:38 +0400 |
|---|---|---|
| committer | Andrew <saintruler@gmail.com> | 2019-04-17 15:01:38 +0400 |
| commit | ce17eacde37c124abe07288ae1453b5b658f8ff2 (patch) | |
| tree | 04e0f8590ba1ca112a580914ed510f5bbfa75e45 /day4/task3 | |
| parent | 402d0d2b9ebd76b8e99eddceeb85c4a66030b51b (diff) | |
Четвертый день, задача номер 3
Diffstat (limited to 'day4/task3')
| -rw-r--r-- | day4/task3/client.py | 72 | ||||
| -rw-r--r-- | day4/task3/db.py | 57 | ||||
| -rw-r--r-- | day4/task3/server.py | 82 |
3 files changed, 211 insertions, 0 deletions
diff --git a/day4/task3/client.py b/day4/task3/client.py new file mode 100644 index 0000000..7f5c298 --- /dev/null +++ b/day4/task3/client.py @@ -0,0 +1,72 @@ +import socket +from time import sleep +import struct +import json + + +def pack_data(data): + encoded = data.encode() + return struct.pack('I', len(encoded)) + encoded + + +def get_data(connection): + buffer = b'' + while len(buffer) < 4: + data = connection.recv(4 - len(buffer)) + if not data: + raise ConnectionError('Connection was closed') + + buffer += data + + size_packed, buffer = buffer[:4], buffer[4:] + if not size_packed: + raise ConnectionError('Connection was closed') + + (size,) = struct.unpack('I', size_packed) + data = connection.recv(size - len(buffer)) + return buffer + data + + +def parse_data(data): + data = json.loads(data.decode()) + arr = [f'Найдено {len(data)} совпадений:'] + for error in data: + arr.append(f"[{error['date']}][{error['type']}][{error['module']}][{error['id']}] {error['text']}") + return '\n'.join(arr) + + +HOST, PORT = ADDR = 'localhost', 6001 + +cnt = 0 +sock = socket.socket() +while cnt < 10: + try: + cnt += 1 + sock.connect(ADDR) + + except ConnectionRefusedError: + print('Не удалось подключиться к серверу. Следующая попытка через 3 секунды...') + sleep(3) + + else: + del cnt + break +else: + print('Не удалось подключиться к серверу через 10 попыток.\nОстанавливаемся...') + sock.close() + quit() + + +while True: + try: + data = input('Введите модуль для поиска:\n') + + except KeyboardInterrupt: + break + + else: + sock.sendall(pack_data(data)) + response = get_data(sock) + print(parse_data(response)) + +sock.close() diff --git a/day4/task3/db.py b/day4/task3/db.py new file mode 100644 index 0000000..15eba02 --- /dev/null +++ b/day4/task3/db.py @@ -0,0 +1,57 @@ +import re +from datetime import datetime + +f = open('otrs_error.log') + +matcher = re.compile(r'\[(?P<date>.*?)\]\[(?P<type>.*?)\]\[(?P<module>.*?)\]\[(?P<id>.*?)\] (?P<text>.*)') + +db = [] + +lines = f.readlines() +f.close() +for line in lines: + line = line.strip() + match = re.match(matcher, line) + + if match: + date = datetime.strptime(match.group('date'), '%c') + module = match.group('module') + + db.append({ + 'date': date, + 'type': match.group('type'), + 'module': module, + 'id': match.group('id'), + 'text': match.group('text') + }) + + else: + print(f'Ошибка при разборе строки:\n{line}') + + +def search_by_date(hour, minute=None, second=None, data=None): + arr = [] + print(f'filtering by h={hour}, m={minute}, s={second}, data="{data}"') + for err in db: + if err['date'].hour == int(hour): + if minute is not None: + if second is not None: + if err['date'].minute == int(minute) and err['date'].second == int(second): + if data in err['module']: + _ = err.copy() + _['date'] = _['date'].ctime() + arr.append(_) + else: + if err['date'].minute == int(minute): + if data in err['module']: + _ = err.copy() + _['date'] = _['date'].ctime() + arr.append(_) + + else: + if data in err['module']: + _ = err.copy() + _['date'] = _['date'].ctime() + arr.append(_) + + return arr diff --git a/day4/task3/server.py b/day4/task3/server.py new file mode 100644 index 0000000..b3cb619 --- /dev/null +++ b/day4/task3/server.py @@ -0,0 +1,82 @@ +import socket +import struct +from db import search_by_date +import re +import json + + +def pack_data(data): + encoded = data.encode() + return struct.pack('I', len(encoded)) + encoded + + +def handle_request(data): + match = re.match(r'(\d+):?(\d+)?:?(\d+)?-(.*)', data) + if match: + *date, msg = match.groups() + return pack_data(json.dumps(search_by_date(*date, msg))) + + else: + print('String not matched.') + return pack_data(json.dumps([])) + + +def get_data(connection): + buffer = b'' + while len(buffer) < 4: + data = connection.recv(4 - len(buffer)) + if not data: + raise ConnectionError('Connection was closed') + + buffer += data + + size_packed, buffer = buffer[:4], buffer[4:] + if not size_packed: + raise ConnectionError('Connection was closed') + + (size,) = struct.unpack('I', size_packed) + data = connection.recv(size - len(buffer)) + return buffer + data + + +def handle_connection(connection, address): + while True: + try: + data = get_data(connection) + + except ConnectionResetError: + print(f'Connection with {address[0]} was unexpectedly closed') + break + + except ConnectionError: + print(f'Connection with {address[0]} was ended') + break + + except KeyboardInterrupt: + raise KeyboardInterrupt() + + else: + if not data: + print(f'Connection with {address[0]} was ended') + break + response = handle_request(data.decode()) + connection.sendall(response) + + +HOST, PORT = ADDR = '0.0.0.0', 6001 +sock = socket.socket() +sock.bind(ADDR) +sock.listen(5) + +while True: + print('Listening for new connections...') + try: + connection, address = sock.accept() + print(f'Got a connection from {address[0]}') + handle_connection(connection, address) + + except KeyboardInterrupt: + print('Stopping server...') + sock.close() + print('Server stopped') + break |