-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
143 lines (125 loc) · 4.71 KB
/
app.py
File metadata and controls
143 lines (125 loc) · 4.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse, PlainTextResponse, HTMLResponse
from fastapi.templating import Jinja2Templates
import subprocess
import psutil
import re
from services import (
create_dns_record,
delete_dns_record,
deploy_nginx_site,
run_docker_container,
terminate_configuration,
list_docker_images,
list_docker_containers,
list_subdomains,
get_docker_container_logs
)
from dotenv import load_dotenv
import os
load_dotenv()
domain = os.getenv("DOMAIN")
ipaddress = os.getenv("IPADDRESS")
app = FastAPI(docs_url=None, redoc_url=None)
templates = Jinja2Templates(directory="templates")
@app.get("/")
def login():
template = templates.get_template("login.html")
html_content = template.render()
return HTMLResponse(content=html_content)
@app.get("/home")
async def home(uid: str, request: Request):
authorized_uids = os.getenv('AUTHORIZED_UIDS', '').split(',')
if uid not in authorized_uids:
raise HTTPException(status_code=400, detail="Wrong Creds")
images = list_docker_images()
containers = list_docker_containers()
subdomains = list_subdomains()
return templates.TemplateResponse("home.html", {
"request": request,
"images": images,
"containers": containers,
"subdomains": subdomains,
"running_containers": containers
})
@app.post("/deploy")
async def deploy(
port: int = Form(...),
subdomain: str = Form(...),
create_symlink: str = Form(...),
image_name: str = Form(...),
container_name: str = Form(...),
memory_limit: str = Form(...),
memory_limit_value: str = Form(None),
log_file_name: str = Form(None)
):
if memory_limit.lower() == 'yes':
if not memory_limit_value:
raise HTTPException(status_code=400, detail="Memory limit value is required.")
memory_limit_value = memory_limit_value.strip()
if not re.match(r'^\d+(b|k|m|g|B|K|M|G)$', memory_limit_value):
raise HTTPException(status_code=400, detail="Invalid memory limit format.")
else:
memory_limit_value = ''
try:
nginx_result = deploy_nginx_site(port, subdomain, create_symlink.lower() == 'yes')
dns_result = create_dns_record(
record_type="A",
name=f"{subdomain}.{domain}",
content={ipaddress},
ttl=3600,
proxied=True
)
docker_result = run_docker_container(
name=container_name,
image_name=image_name,
port=port,
memory_limit=memory_limit_value if memory_limit.lower() == 'yes' else None,
log_file_name=log_file_name
)
return RedirectResponse(url="/success?message=Deployment successful", status_code=303)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/success")
async def success(request: Request, message: str):
return templates.TemplateResponse("success.html", {"request": request, "message": message})
@app.post("/terminate")
async def terminate(
subdomain: str = Form(...),
container_name: str = Form(...)
):
if not subdomain or not container_name:
raise HTTPException(status_code=400, detail="Subdomain and container name are required.")
try:
print(f"Terminating subdomain: {subdomain}, container: {container_name}")
termination_result = terminate_configuration(subdomain, container_name)
return RedirectResponse(url="/success?message=Termination successful", status_code=303)
except Exception as e:
print(f"Error during termination: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/logs", response_class=PlainTextResponse)
async def get_logs(container_name: str):
containers = list_docker_containers()
if container_name not in containers:
raise HTTPException(status_code=404, detail="Container not found")
try:
result = subprocess.run(['docker', 'logs', container_name], capture_output=True, text=True)
logs = result.stdout
if not logs:
logs = "No logs available for this container."
except subprocess.CalledProcessError as e:
raise HTTPException(status_code=500, detail=f"Error fetching logs: {e.stderr}")
return PlainTextResponse(logs)
@app.get("/metrics")
async def get_metrics():
cpu_usage = psutil.cpu_percent(interval=1)
ram_usage = psutil.virtual_memory().percent
disk_usage = psutil.disk_usage('/').percent
return {
"cpu_usage": cpu_usage,
"ram_usage": ram_usage,
"disk_usage": disk_usage
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=5555)