Skip to content
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
36 changes: 24 additions & 12 deletions api/servers
Original file line number Diff line number Diff line change
@@ -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")
Expand All @@ -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()
Expand All @@ -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/<id>
elif extra_path.startswith("/") and extra_path[1:].isnumeric(): # /api/servers/<id>
# 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()

Expand All @@ -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")
print_status_405(extra_path, "GET")

if __name__ == "__main__":
main()
24 changes: 19 additions & 5 deletions create_server
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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:
Expand Down
18 changes: 12 additions & 6 deletions monitor_new_VM
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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

Expand All @@ -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;",
Expand All @@ -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()