-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain5.py
More file actions
211 lines (172 loc) · 6.21 KB
/
Copy pathmain5.py
File metadata and controls
211 lines (172 loc) · 6.21 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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import os
import subprocess
import docker
from pathlib import Path
import argparse
import re
import fcntl
client = docker.from_env()
nginx_container_name = "nginx"
conf_dir = Path("/home/dockeruser/reverse_proxy/nginx/conf.d")
conf_dir.mkdir(parents=True, exist_ok=True)
config_file = str(conf_dir / "auto_config.conf")
parser = argparse.ArgumentParser()
parser.add_argument(
"operation", choices=["add", "delete"], help="Add or delete operation"
)
parser.add_argument("http", choices=["true", "false"], help="Enable or disable HTTP")
parser.add_argument("port", help="Port exposed by the container ")
parser.add_argument("subdomain", help="Subdomain to access the service")
parser.add_argument("manager_ip", help="IP of the manager server")
parser.add_argument(
"domain", nargs="?", default="saggitarius.world", help="Domain name"
)
args = parser.parse_args()
domain_suffix = (
".localtest.me" if os.getenv("ENVIRONMENT") == "development" else args.domain
)
if not domain_suffix.startswith("."):
domain_suffix = "." + domain_suffix
# Check certificate
"""def check_letsencrypt_cert(fqdn: str) -> bool:
certbot_path = Path(f"/home/dockeruser/reverse_proxy/certbot/conf/live/saggitarius.world")
print(fqdn)
cert_path = certbot_path / "fullchain.pem"
key_path = certbot_path / "privkey.pem"
return cert_path.exists() and key_path.exists()"""
# Add config
def update_nginx_config(
subdomain: str,
port: str,
manager_ip: str,
allow_http: bool = False,
domain: str = "saggitarius.world",
):
fqdn = f"{subdomain}{domain_suffix}"
"""if not check_letsencrypt_cert(fqdn):
print(check_letsencrypt_cert(fqdn))
print(f"Certificate not found for {fqdn}")
return"""
http_config: str = ""
if allow_http:
http_port: int = int(port) + 2000
http_config = f"""
server {{
listen {http_port};
server_name {domain};
location / {{
proxy_pass http://{subdomain}_service:{port};
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 1h;
proxy_send_timeout 1h;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}}
}}
"""
config_block = f"""
{http_config}
server {{
server_name {subdomain}.{domain};
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/{subdomain}.{domain}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/{subdomain}.{domain}/privkey.pem;
location ^~ /.well-known/acme-challenge/ {{
root /var/www/certbot;
try_files $uri =404;
}}
location / {{
resolver 127.0.0.11 valid=24000s;
set $upstream "{subdomain}_service:{port}";
proxy_pass http://{subdomain}_service:{port};
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}}
}}
"""
# Check if block already exists
if os.path.exists(config_file):
with open(config_file, "r") as f:
old_config = f.read()
if config_block in old_config:
print("This subdomain is already configured")
return
# Append new config
with open(config_file, "a") as f:
f.write(config_block)
print(f"Block added for {fqdn} -> port {port}")
# Reload nginx
try:
nginx = client.containers.get(nginx_container_name)
result = nginx.exec_run("nginx -s reload")
if result.exit_code == 0:
print("Nginx reloaded")
else:
print(f"Error while reloading Nginx: {result.output.decode()}")
except docker.errors.NotFound:
print(f"Nginx container '{nginx_container_name}' not found")
# Delete config
def delete_nginx_config(subdomain: str):
fqdn = f"{subdomain}{domain_suffix}"
if not os.path.exists(config_file):
print("Configuration file does not exist")
return
with open(config_file, "r") as f:
content = f.read()
server_block_pattern = re.compile(
r"server\s*\{[^{}]*\{[^{}]*\}[^{}]*\}|server\s*\{[^{}]*\}", re.DOTALL
)
block_found = False
for match in server_block_pattern.finditer(content):
block = match.group()
if f"server_name {fqdn};" in block:
content = content.replace(block, "")
block_found = True
break
if not block_found:
print(f"No configuration found for {fqdn}")
return
cleaned = "\n".join(line for line in content.splitlines() if line.strip())
with open(config_file, "w") as f:
f.write(cleaned + "\n")
print(f"Configuration for {fqdn} removed")
# Reload nginx
try:
nginx = client.containers.get(nginx_container_name)
result = nginx.exec_run("nginx -s reload")
if result.exit_code == 0:
print("Nginx reloaded")
else:
print(f"Error while reloading Nginx: {result.output.decode()}")
except docker.errors.NotFound:
print(f"Nginx container '{nginx_container_name}' not found")
# Entry point
op = args.operation
def startop():
if op == "add":
port = args.port
subdomain = args.subdomain
manager_ip = args.manager_ip
domain = args.domain
allow_http = args.http.lower() == "true"
update_nginx_config(
subdomain=subdomain,
port=port,
manager_ip=manager_ip,
allow_http=allow_http,
domain=domain,
)
elif op == "delete":
subdomain = args.subdomain
delete_nginx_config(subdomain=subdomain)
if __name__ == "__main__":
startop()