prepare_logfiles.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import json
  2. import os
  3. import re
  4. from datetime import date, timedelta
  5. from config import DEBUG, DSN
  6. from logfiles.systeminfo_log import SysteminfoLog
  7. from model import StatusMeldung
  8. from sqlalchemy import create_engine, select
  9. from sqlalchemy.orm import Session
  10. class PrepareLogfiles:
  11. def prepare_logfiles(self):
  12. with Session(create_engine(DSN)) as db_session:
  13. if DEBUG:
  14. query = select(StatusMeldung).where(
  15. StatusMeldung.datum.between(date.today() - timedelta(days=3), date.today())
  16. )
  17. else:
  18. query = select(StatusMeldung).where(StatusMeldung.fehlerbericht.is_(None))
  19. for sm in db_session.scalars(query):
  20. self.convert_logfile(sm)
  21. db_session.commit()
  22. def convert_logfile(self, sm: StatusMeldung):
  23. whitelist_str = sm.kunde_ref.whitelist if sm.kunde_ref is not None else ""
  24. whitelist = self.get_whitelist(whitelist_str)
  25. fehlerbericht = dict([(f["Name"], f) for f in json.loads(sm.fehlerbericht_import)])
  26. for name, report in fehlerbericht.items():
  27. if ".bat" in name:
  28. e = report["Errors"][0]
  29. e = e.replace(
  30. "!! Bitte E-Mailadresse fuer Statusbericht angeben !!",
  31. "! Bitte E-Mailadresse fuer Statusbericht angeben !",
  32. )
  33. e = e.replace(
  34. "!! SMTP-Konfiguration bitte anpassen !!",
  35. "! SMTP-Konfiguration bitte anpassen !",
  36. )
  37. err_count = [0] * 15
  38. e, err_count[0] = re.subn(r"(!![^\n]*!!)", r"<b>\1</b>", e)
  39. e, err_count[1] = re.subn(
  40. r"\((\w{2}\d{4})\)( [^\r]*)",
  41. r"<b><a href='/wiki/\1' target='_blank'>(\1)</a>\2</b>",
  42. e,
  43. )
  44. e = re.sub(
  45. r"Error \= \[Micro.* NULL.*\.",
  46. "",
  47. e,
  48. )
  49. e, err_count[2] = re.subn(
  50. r"(Error \= \[Micro[^\r]*)",
  51. r"<b>\1</b>",
  52. e,
  53. )
  54. e, err_count[3] = re.subn(r"(Der Befehl \".*\" ist entweder falsch geschrieben)", r"<b>\1</b>", e)
  55. # e, err_count[9] = re.subn(r"(.* is not recognized as an internal or external command)", r"<b>\1</b>", e)
  56. # is not recognized as an internal or external command
  57. e, err_count[4] = re.subn(r"(FEHLER: .*: Source: Impromptu)", r"<b>\1</b>", e)
  58. e, err_count[5] = re.subn(r"(Traceback)", r"<b>\1</b>", e)
  59. e, err_count[6] = re.subn(r"(Fatal error: Uncaught exception)", r"<b>\1</b>", e)
  60. e, err_count[7] = re.subn(r"(Failed to create COM object)", r"<b>\1</b>", e)
  61. e, err_count[8] = re.subn(r"(0.0%)", r"<b>\1</b>", e)
  62. e = re.sub(r"<([^a-z/])", r"\1", e)
  63. e = re.sub(r"/\s+>", "/>", e)
  64. e = re.sub(r"([^a-z/])>", r"\1", e)
  65. report["Errors"][0] = e
  66. if sum(err_count) > 0:
  67. report["ErrorLevel"] = 2
  68. report["Errors"] = [e] + re.findall(r"<b>[^\n]*</b>", e)
  69. sm.anzahl += 1
  70. elif ".dtsx" in name:
  71. e = re.sub(r"\r\n", "\n", report["Errors"][0])
  72. e = re.sub(r"(\w*)ende\n", "§", e)
  73. e = re.sub(r"Copyright ", "§", e)
  74. loglevel_warn = [b for b in e.split("§") if "Status:" not in b]
  75. loglevel_error = [b for b in loglevel_warn if "Fehler:" in b]
  76. loglevel_combined = ["<b>" + b + "</b>" if "Fehler:" in b else b for b in loglevel_warn]
  77. loglevel_combined[-1] = loglevel_combined[-1].replace("DTSER_FAILURE", "<b>DTSER_FAILURE</b>")
  78. if len(loglevel_error) > 0 or "DTSER_SUCCESS" not in loglevel_combined[-1]:
  79. report["ErrorLevel"] = 2
  80. sm.anzahl += 1
  81. report["Errors"][0] = "\n".join(loglevel_combined)
  82. elif report["Type"] == "Modell":
  83. if len(report["Errors"]) > 0:
  84. report["ErrorLevel"] = str(min([int(e["Level"]) for e in report["Errors"]]))
  85. elif len(report["Errors"]) > 0 and report["Type"] in [
  86. "Portal",
  87. "Versand",
  88. ]:
  89. report["Errors2"] = [e for e in report["Errors"] if self.in_whitelist(e, whitelist)]
  90. report["Errors"] = [e for e in report["Errors"] if e not in report["Errors2"]]
  91. if len(report["Errors"]) == 0:
  92. report["ErrorLevel"] = 3
  93. sm.anzahl -= 1
  94. sm.anzahl = len([e for e in fehlerbericht.values() if int(e["ErrorLevel"]) <= 2])
  95. sm.fehlerbericht = json.dumps(list(fehlerbericht.values()), indent=2)
  96. # self.export_log_files(sm, fehlerbericht)
  97. # batch_log = [f for f in fehlerbericht if ".bat" in f["Name"]].pop(0)
  98. SysteminfoLog(fehlerbericht.get("system.info", {"Errors": [""]}))
  99. # if systeminfo_log.ip_address == "0.0.0.0":
  100. # print(sm.kunde)
  101. def in_whitelist(self, e, whitelist):
  102. return any(
  103. [
  104. e["Layer"] in whitelist["Layer"],
  105. e["Report"] in whitelist["Report"],
  106. e["Report"].lower().endswith("_graf"),
  107. e["User"] in whitelist["User"],
  108. ]
  109. )
  110. def export_log_files(self, status: StatusMeldung, fehlerbericht):
  111. kunde = status.kunde.replace(" ", "-").lower()
  112. path = f"fehlerbericht/temp/{status.datum}_{kunde}_{status.aufgabe}"
  113. os.makedirs(path, exist_ok=True)
  114. for file_name in os.listdir(path):
  115. file = path + file_name
  116. if os.path.isfile(file):
  117. os.remove(file)
  118. for name, f in fehlerbericht.items():
  119. if f["Type"] != "Workflow":
  120. continue
  121. f["Errors"][0] = f["Errors"][0].replace("\r\n", "\n")
  122. with open(f"{path}/{name}.log", "w", encoding="latin-1") as fwh:
  123. fwh.write(f["Errors"][0])
  124. def get_whitelist(self, whitelist2):
  125. whitelist = {"Layer": [], "Report": [], "User": []}
  126. if whitelist2 is not None and whitelist2 != "":
  127. whitelist.update(json.loads(whitelist2))
  128. return whitelist
  129. def prepare_logfiles():
  130. mi = PrepareLogfiles()
  131. mi.prepare_logfiles()
  132. if __name__ == "__main__":
  133. prepare_logfiles()
  134. # import cProfile
  135. # cProfile.run(
  136. # "main()",
  137. # "fehlerbericht/prepare_logfiles.prof",
  138. # )