2018-02-03 20:40:17 +00:00
|
|
|
#!/usr/bin/env python3
|
2018-02-03 00:36:08 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2018-02-03 20:40:17 +00:00
|
|
|
# pylint: disable=C0111,C0326,C0103
|
|
|
|
|
2018-02-03 21:25:26 +00:00
|
|
|
"""Tools to manage dumps of API requests."""
|
|
|
|
|
2018-02-03 00:36:08 +00:00
|
|
|
import errno
|
|
|
|
import glob
|
|
|
|
import os
|
2018-02-05 15:52:06 +00:00
|
|
|
import random
|
|
|
|
import time
|
|
|
|
from math import floor
|
2018-02-03 20:24:36 +00:00
|
|
|
|
2018-02-03 00:36:08 +00:00
|
|
|
from . import ansi
|
|
|
|
|
2018-02-03 20:24:36 +00:00
|
|
|
|
2018-02-11 00:48:47 +00:00
|
|
|
def get_timestamp_random():
|
|
|
|
"""Generate timestamp + random part to avoid collisions."""
|
|
|
|
millis = floor(time.time() * 1000)
|
|
|
|
tail = "{:06d}".format(random.randint(0, 999999))
|
|
|
|
return "{}_{}".format(str(millis), tail)
|
|
|
|
|
2018-02-11 01:38:38 +00:00
|
|
|
|
2018-02-11 00:48:47 +00:00
|
|
|
def write_info_if_dumps_found():
|
|
|
|
"""Notify user to upload dumps if present."""
|
|
|
|
# To disable this info, uncomment the following line.
|
|
|
|
# return
|
|
|
|
files = glob.glob(os.path.normpath("logs/*.xml"))
|
|
|
|
if files:
|
|
|
|
print()
|
|
|
|
print("{}There are {} logs collected in the logs/ directory.{} Please consider uploading".format(ansi.YELLOW, len(files), ansi.RESET))
|
|
|
|
print("them to https://tclota.birth-online.de/ by running {}./upload_logs.py{}.".format(ansi.CYAN, ansi.RESET))
|
|
|
|
|
2018-02-11 01:38:38 +00:00
|
|
|
|
2018-02-11 00:48:47 +00:00
|
|
|
class DumpMgr:
|
|
|
|
"""A class for XML dump management."""
|
2018-02-06 18:27:36 +00:00
|
|
|
|
2018-02-03 01:37:55 +00:00
|
|
|
def __init__(self):
|
2018-02-03 21:25:26 +00:00
|
|
|
"""Populate dump file name."""
|
2018-02-03 01:37:55 +00:00
|
|
|
self.last_dump_filename = None
|
|
|
|
|
2018-02-03 00:36:08 +00:00
|
|
|
def write_dump(self, data):
|
2018-02-03 21:25:26 +00:00
|
|
|
"""Write dump to file."""
|
2018-02-11 00:48:47 +00:00
|
|
|
outfile = os.path.normpath("logs/{}.xml".format(get_timestamp_random()))
|
2018-02-03 00:36:08 +00:00
|
|
|
if not os.path.exists(os.path.dirname(outfile)):
|
|
|
|
try:
|
|
|
|
os.makedirs(os.path.dirname(outfile))
|
2018-02-03 20:24:36 +00:00
|
|
|
except OSError as err:
|
|
|
|
if err.errno != errno.EEXIST:
|
2018-02-03 00:36:08 +00:00
|
|
|
raise
|
2018-02-03 20:24:36 +00:00
|
|
|
with open(outfile, "w", encoding="utf-8") as fhandle:
|
|
|
|
fhandle.write(data)
|
2018-02-03 00:36:08 +00:00
|
|
|
self.last_dump_filename = outfile
|
|
|
|
|
|
|
|
def delete_last_dump(self):
|
2018-02-03 21:25:26 +00:00
|
|
|
"""Delete last dump."""
|
2018-02-03 00:36:08 +00:00
|
|
|
if self.last_dump_filename:
|
|
|
|
os.unlink(self.last_dump_filename)
|
|
|
|
self.last_dump_filename = None
|