diff --git a/api/servers b/api/servers index 91cd9e1..71c755c 100644 --- a/api/servers +++ b/api/servers @@ -1,10 +1,17 @@ #! /usr/bin/python3 -import os +import os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import MySQLdb import config import json +def print_json_200(data): + # respond with json data + print("Status: 200 OK") + print("Content-Type: application/json\n") + print(json.dumps(data)) + def print_status_400(body: str): print("Status: 400 Bad Request") print("Content-Type: text/plain\n") @@ -26,24 +33,26 @@ def get_db_connection(): db = MySQLdb.connect( host=config.DB_HOST, user=config.DB_USER, - passwd=config.DB_PASS, - db=config.DB_NAME + passwd=config.DB_PASSWORD, + db=config.DB_NAME, + port=config.DB_PORT, + ssl={"ssl": {}} ) return db except MySQLdb.Error as e: print_status_500(str(e)) + exit(1) def main(): # extract basic request info request_method = os.environ["REQUEST_METHOD"] extra_path = os.environ.get("PATH_INFO", "") path_component = extra_path.split("/") - resp = None if request_method == "GET": db = get_db_connection() cursor = db.cursor() - if extra_path == "/api/servers": + if extra_path == "" or extra_path == "/": # return all instances in database cursor.execute("SELECT * FROM servers;") rows = cursor.fetchall() @@ -59,10 +68,11 @@ def main(): "ready": row[5] } ) + print_json_200(resp) - if len(path_component) == 4 and path_component[3].isnumeric(): # /api/servers/ + elif extra_path.startswith("/") and extra_path[1:].isnumeric(): # /api/servers/ # return a single instance in db - primary_key = int(path_component[3]) + primary_key = int(extra_path[1:]) cursor.execute("SELECT * FROM servers WHERE id = %s;", (primary_key,)) row = cursor.fetchone() @@ -79,10 +89,12 @@ def main(): "ready": row[5] } - # respond with json data - print("Status: 200 OK") - print("Content-Type: application/json\n") - print(json.dumps(resp)) + print_json_200(resp) + else: + print_status_400("Page not found: " + extra_path) else: - print_status_405(extra_path, "GET") \ No newline at end of file + print_status_405(extra_path, "GET") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/create_server b/create_server index fd05605..dcd3b1e 100644 --- a/create_server +++ b/create_server @@ -6,7 +6,17 @@ import MySQLdb import config from pydo import Client -root_url = "" +config_commands = """#cloud-config + runcmd: + - apt update + - apt install apache2 -y + - systemctl enable apache2 + - mkdir -p /etc/systemd/system/apache2.service.d/ + - bash -c 'echo -e "[Unit]\nAfter=network-online.target\nWants=network-online.target" > /etc/systemd/system/apache2.service.d/override.conf' + - systemctl daemon-reload + - systemctl restart apache2 + - echo "hello, world" > /root/dummy.txt +""" def print_status_400(body: str): print("Status: 400 Bad Request") @@ -29,13 +39,16 @@ def get_db_connection(): db = MySQLdb.connect( host=config.DB_HOST, user=config.DB_USER, - passwd=config.DB_PASS, - db=config.DB_NAME + passwd=config.DB_PASSWORD, + db=config.DB_NAME, + port=config.DB_PORT, + ssl={"ssl": {}} ) return db except MySQLdb.Error as e: print_status_500(str(e)) + exit(1) def create_server(user: str, desc: str) -> int: try: @@ -56,6 +69,7 @@ def create_server(user: str, desc: str) -> int: "backups": False, "ipv6": True, "monitoring": True, + "user_data": config_commands } resp = client.droplets.create(body=req) @@ -81,10 +95,10 @@ def add_server_to_db(user: str, desc: str, instance_id: int, ready: bool): db.close() # run background script - os.system(f"/monitor_new_VM {instance_id} {new_server_id} 1>/dev/null 2>/dev/null &") + os.system(f"./monitor_new_VM {instance_id} {new_server_id} 1>/dev/null 2>/dev/null &") print("Status: 303 See Other") - print(f"Location: {root_url}/api/servers/{new_server_id}") + print(f"Location: {config.ROOT_URL}/api/servers/{new_server_id}") print() except Exception as e: diff --git a/monitor_new_VM b/monitor_new_VM index e78f24a..e8b8f31 100644 --- a/monitor_new_VM +++ b/monitor_new_VM @@ -11,14 +11,16 @@ def get_db_connection(): db = MySQLdb.connect( host=config.DB_HOST, user=config.DB_USER, - passwd=config.DB_PASS, - db=config.DB_NAME + passwd=config.DB_PASSWORD, + db=config.DB_NAME, + port=config.DB_PORT, + ssl={"ssl": {}} ) return db except MySQLdb.Error as e: print(str(e)) - raise + exit(1) def main(): try: @@ -40,9 +42,8 @@ def main(): # Connect to Digital Ocean API to track new VM creation resp = client.droplets.get(droplet_id=int(instance_id)) limit -= 1 - if "droplet" not in resp: # error status - # report error, sleep for 5 seconds and retry - print(resp["message"]) + if not resp or "droplet" not in resp: + print("Error fetching droplet info:", resp) time.sleep(5) continue @@ -64,6 +65,9 @@ def main(): db = get_db_connection() cursor = db.cursor() # Insert into servers table + if public_ip is None: + print("Failed to retrieve public IP address.") + exit(1) cursor.execute("UPDATE servers \ SET ready = %s, public_ip = %s \ WHERE id = %s;", @@ -74,7 +78,9 @@ def main(): except ValueError as e: print(str(e)) + exit(1) except Exception as e: print(str(e)) + exit(1) main() \ No newline at end of file