monkey/envs/monkey_zoo/blackbox/log_handlers/monkey_log.py

39 lines
1.1 KiB
Python
Raw Normal View History

import logging
2019-09-13 21:12:58 +08:00
import os
from bson import ObjectId
2019-10-01 21:11:53 +08:00
LOGGER = logging.getLogger(__name__)
2019-09-13 21:12:58 +08:00
class MonkeyLog(object):
def __init__(self, monkey, log_dir_path):
self.monkey = monkey
self.log_dir_path = log_dir_path
def download_log(self, island_client):
2021-04-06 21:19:27 +08:00
log = island_client.find_log_in_db({"monkey_id": ObjectId(self.monkey["id"])})
2019-09-13 21:12:58 +08:00
if not log:
2021-04-06 21:19:27 +08:00
LOGGER.error("Log for monkey {} not found".format(self.monkey["ip_addresses"][0]))
return False
2019-09-13 21:12:58 +08:00
else:
self.write_log_to_file(log)
return True
2019-09-13 21:12:58 +08:00
def write_log_to_file(self, log):
2021-04-06 21:19:27 +08:00
with open(self.get_log_path_for_monkey(self.monkey), "w") as log_file:
2019-09-13 21:12:58 +08:00
log_file.write(MonkeyLog.parse_log(log))
@staticmethod
def parse_log(log):
log = log.strip('"')
log = log.replace("\\n", "\n ")
return log
@staticmethod
def get_filename_for_monkey_log(monkey):
2021-04-06 21:19:27 +08:00
return "{}.txt".format(monkey["ip_addresses"][0])
2019-09-13 21:12:58 +08:00
def get_log_path_for_monkey(self, monkey):
return os.path.join(self.log_dir_path, MonkeyLog.get_filename_for_monkey_log(monkey))