Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

34 add notifications #41

Merged
merged 5 commits into from
Dec 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 41 additions & 21 deletions CommandAndControl/controller.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import logging
import sys
import traceback
import uuid
from fabric import Connection
from pyfiglet import figlet_format
Expand All @@ -13,6 +14,7 @@
from starter import startSession
import time
import mongo
import custom_discord as discord
class Client(Enum):
c1 = "c1 - Normal"
c2 = "c2 - Tor Normal"
Expand Down Expand Up @@ -177,17 +179,20 @@ def clientSession(client: Client, test_id: str, room_id: str) -> None:
command = f'python3 OnionRTC.py {name.replace(" ", "")} {test_id} {room_id} {timeout}'

logging.info("Starting the client " + name + " with the command: " + command )
mongo.log("COMMAND_START", test_id=test_id, room_id=room_id, client_username=name.replace(" ", ""))
mongo.log("COMMAND_SESSION_START", test_id=test_id, room_id=room_id, client_username=name.replace(" ", ""))
with connection.cd("OnionRTC-experiment/Selenium"):
try:
connection.run(command, hide=True)
logging.info(f"Session on the client {name} successfully ended")
except(UnexpectedExit) as e:
logging.error(f"Session on the client {name} exited with {e.result.exited}")
logging.error(f"Session failed on client {name}. Exited with {e.result.exited}")
logging.error(f"command: {e.result.command}")
logging.error(f"stdout:\n{e.result.stdout}")
logging.error(f"stderr:\n{e.result.stderr}")
mongo.log("COMMAND_END", test_id=test_id, room_id=room_id, client_username=str(name).replace(" ", ""))
discord.notify(header="Failed run!", message=f"Error in OnionRTC on client: {name}, Exit code: {e.result.exited}", errorMessage=f"Traceback: \n{e.result.stdout[max(-(len(e.result.stdout)),-1000):]}", test_id=test_id, room_id=room_id, client_id=name.replace(" ", ""))
mongo.log("COMMAND_SESSION_FAILED", test_id=test_id, room_id=room_id, client_username=str(name).replace(" ", ""))
return
mongo.log("COMMAND_SESSION_SUCCESS", test_id=test_id, room_id=room_id, client_username=str(name).replace(" ", ""))



Expand Down Expand Up @@ -260,25 +265,36 @@ def main():
[Client.c2, Client.d4],
[Client.c3, Client.d4],
]
test_id = str
room_id = str

logging.info("Waiting to start a new session.")
while(True):
if(startSession([0, 1, 0])):
test_id = str(uuid.uuid4())
mongo.log(loggingType="COMMAND_START_RUN", test_id=test_id)
logging.info("Starting a new run, test_id: " + test_id)
for testCase in testCases:
room_id = str(uuid.uuid4())
logging.info(f'Starting a test {test_id} in room {room_id} between [{str(testCase[0])}] and [{str(testCase[1])}]')
mongo.log(loggingType="COMMAND_START_TEST", test_id=test_id, room_id=room_id)
runSession(alice = testCase[0], bob = testCase[1], test_id=test_id, room_id=room_id)

logging.info("Run completed.")

# NOTE: Makes sure that the application doesn't run too fast
# and that the application is closeable with CTRL+C.
time.sleep(1)

try:
if(startSession([0, 1, 0])):
test_id = str(uuid.uuid4())
mongo.log(loggingType="COMMAND_START_RUN", test_id=test_id)
logging.info("Starting a new run, test_id: " + test_id)
for testCase in testCases:
room_id = str(uuid.uuid4())
logging.info(f'Starting a test {test_id} in room {room_id} between [{str(testCase[0])}] and [{str(testCase[1])}]')
mongo.log(loggingType="COMMAND_START_TEST", test_id=test_id, room_id=room_id)
runSession(alice = testCase[0], bob = testCase[1], test_id=test_id, room_id=room_id)

logging.info("Run completed, Waiting to start a new session")

# NOTE: Makes sure that the application doesn't run too fast
# and that the application is closeable with CTRL+C.
time.sleep(1)
except KeyboardInterrupt as e:
raise(e)
except Exception as e:
# Get string of exception

just_the_string = traceback.format_exc()
logging.error(f"An error occurred: \nException: {e}\nTraceback: \n{just_the_string}")
discord.notify(header="Crash!", message=f"Exception: {e}\nTraceback: \n{just_the_string}", test_id=test_id, room_id=room_id)
pass


# main method
Expand All @@ -301,9 +317,13 @@ def main():
logging.addLevelName( logging.WARNING, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
logging.addLevelName( logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))

discord.notify(header="Starting")

print(figlet_format("Command & Controller", font="slant"))

try:
main()
except KeyboardInterrupt as e:
print("KeyboardInterrupt")
except KeyboardInterrupt:
logging.info("Exiting the application")
exit(0)

Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"""


def notify(message: str, header: str = None, test_id = None, room_id = None, client_id = None, dict = None):
def notify(header: str = None, message: str = "", errorMessage: str = "" , test_id = None, room_id = None, client_id = None, dict = None):
"""
Sends a notification to the discord webhook

Expand Down Expand Up @@ -51,22 +51,26 @@ def notify(message: str, header: str = None, test_id = None, room_id = None, cli
return

if(header is not None):
message = f"**{header}**\n{message}"
header = f"**{header}**\n"

basicInfo = ""
if(test_id is not None or room_id is not None or client_id is not None):
message += "\n```shell\n"
basicInfo = "\n```shell\n"
if(test_id is not None):
message += f"Test ID: {test_id}\n"
basicInfo += f"Test ID: {test_id}\n"
if(room_id is not None):
message += f"Room ID: {room_id}\n"
basicInfo += f"Room ID: {room_id}\n"
if(client_id is not None):
message += f"Client ID: {client_id}\n"
message += "```\n"
basicInfo += f"Client ID: {client_id}\n"
basicInfo += "```\n"

dictText = ""
if(dict is not None):
message += "```json\n"
message += json.dumps(dict, indent=4)
message += "\n```"
dictText = "```json\n"
dictText += json.dumps(dict, indent=4)
dictText += "\n```"

message = f"{header}{message}{basicInfo}{errorMessage}{dictText}"

webhook = DiscordWebhook(url=discordHook, content=message)
response = webhook.execute()
Expand Down Expand Up @@ -95,4 +99,6 @@ def notify(message: str, header: str = None, test_id = None, room_id = None, cli
#notify("Testcase 4", test_id="test_id", room_id="room_id",client_id="client_id")
#notify("Testcase 5", test_id="test_id", room_id="room_id",client_id="client_id", dict={"test": "test", "test1": {"test2": "test2"}, "test3": [123, 321]})
#notify("Testcase 6", dict={"test": "test", "test1": {"test2": "test2"}, "test3": [123, 321]})
notify("Testcase 7", header="Error")
#notify("Testcase 7", header="Error")

notify(header="Testcase 4", message="message here :)", errorMessage="Stack trace", test_id="test_id", room_id="room_id",client_id="client_id")
3 changes: 2 additions & 1 deletion CommandAndControl/mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import logging
import sys
import os
import custom_discord as discord

def _getCollection():
"""
Expand Down Expand Up @@ -63,7 +64,7 @@ def log( loggingType: str, data = dict(), test_id = None, room_id = None, client
logging.error("Error while sending logging data, Key already exists?, data: {data}")
except errors.ServerSelectionTimeoutError as e:
logging.error(f"Connection to mongo server could not open")
#FIXME: SEND DISCORD MESSAGE!
discord.notify(header="MongoDB Connection Error", errorMessage=str(e))
except (KeyboardInterrupt, Exception) as e:
logging.error(f"Error while sending logging data {e}")

Expand Down
2 changes: 1 addition & 1 deletion Selenium/OnionRTC.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ def setup_session(self):
data["error"] = f"Exception: {e}"
create_client_report(data,logging)

raise Exception("geckodriver not found!")
raise e


return self.vars
Expand Down