-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateCompose.py
More file actions
218 lines (205 loc) · 7.3 KB
/
generateCompose.py
File metadata and controls
218 lines (205 loc) · 7.3 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
212
213
214
215
216
217
218
#!/usr/bin/env python3
import yaml
from os import getenv as _
from dotenv import load_dotenv
from datetime import datetime
from sys import argv
imageVersion = (
argv[1] if len(argv) > 1 else "latest"
)
load_dotenv(dotenv_path="stanthonynovato.env")
# === CONFIGURATION ===
num_backends = 2 # Change this to add/remove backend instances
mysql_password = _("MYSQL_PASSWORD") # Replace with your real password or load from env
mysql_root_password = _("MYSQL_ROOT_PASSWORD")
mysql_db = _("MYSQL_DATABASE")
mysql_user = _("MYSQL_USER")
network_subnet = "172.20.0.0/16"
nginx_restricted_routes = [
"/stub_status",
"/metrics"
]
# === BASE SERVICES ===
compose = {
'version': '3.8',
'services': {
'mysql': {
'image': 'mysql:5.7',
'container_name': 'mysql',
'restart': 'unless-stopped',
'environment': {
'MYSQL_ROOT_PASSWORD': mysql_root_password,
'MYSQL_DATABASE': mysql_db,
'MYSQL_USER': mysql_user,
'MYSQL_PASSWORD': mysql_password
},
'volumes': ['mysql_data:/var/lib/mysql'],
'networks': ['backend']
},
'nginx': {
'image': 'nginx:latest',
'container_name': 'nginx',
'restart': 'unless-stopped',
'volumes': ['./nginx.conf:/etc/nginx/nginx.conf:ro'],
'ports': ['80:80'],
"depends_on": {},
'networks': ['backend']
},
"prometheus-nginx-exporter": {
"image": "nginx/nginx-prometheus-exporter:1.4",
"container_name": "prometheus-nginx-exporter",
"restart": "unless-stopped",
"ports": ["9113:9113"],
"environment": {
"NGINX_SCRAPE_URI": "http://nginx:80/stub_status"
},
"command": [
"--nginx.scrape-uri=http://nginx:80/stub_status"
],
"depends_on": ["nginx"],
'networks': ['backend']
}
},
'volumes': {
'mysql_data': {}
},
'networks': {
'backend': {
"ipam": {
"driver": "default",
"config": [
{
"subnet": network_subnet
}
]
}
}
}
}
# === DYNAMIC BACKEND SERVICES ===
for i in range(1, num_backends + 1):
name = f"say-backend-{i}"
compose['services'][name] = {
'image': f'alphagamedev/say-backend:{imageVersion}',
"hostname": name,
'container_name': name,
'restart': 'unless-stopped',
'environment': {
'MYSQL_HOST': 'mysql',
'MYSQL_USER': mysql_user,
'MYSQL_PASSWORD': mysql_password,
'MYSQL_DATABASE': mysql_db,
"DISCORD_WEBHOOK_URL": _("DISCORD_WEBHOOK_URL"),
"RECAPTCHA_SECRET_KEY": _("RECAPTCHA_SECRET_KEY"),
"PROMETHEUS_MULTIPROC_DIR": _("PROMETHEUS_MULTIPROC_DIR"),
"GOOGLE_APP_PASSWORD": _("GOOGLE_APP_PASSWORD"),
"SMTP_FROM_EMAIL": _("SMTP_FROM_EMAIL")
},
'depends_on': ['mysql'],
"healthcheck": {
'test': ['CMD', 'curl', "-A", f"HealthcheckChecker/1 (compatible; SAY-Backend/{imageVersion} +damien@alphagame.dev)", '-f', 'http://localhost:5000/healthcheck?reason=DockerAutomatedHealthcheck'],
'interval': '30s',
'timeout': '10s',
'retries': 5
},
'networks': ['backend']
}
# Add backend to nginx depends_on
compose['services']['nginx']['depends_on'].update({
f"say-backend-{i}": {
'condition': 'service_healthy'
} for i in range(1, num_backends + 1)
})
# === Prometheus ===
compose['services']['prometheus'] = {
'image': 'prom/prometheus:latest',
'container_name': 'prometheus',
'restart': 'unless-stopped',
'volumes': [
'./prometheus.yml:/etc/prometheus/prometheus.yml'
],
'ports': ['9090:9090'],
'networks': ['backend'],
'depends_on': {f"say-backend-{i}": {'condition': 'service_healthy'} for i in range(1, num_backends + 1)}
}
# === OUTPUT ===
with open('docker-compose.yml', 'w') as f:
f.write(f"# generated at: {datetime.now().isoformat()}\n")
yaml.dump(compose, f, default_flow_style=False)
with open("nginx.conf", "w") as f:
fc = ""
fc += f"# generated at {datetime.now()}\n"
fc += "user nginx;\n"
fc += "worker_processes auto;\n\n"
fc += "error_log /var/log/nginx/error.log notice;\n"
fc += "pid /run/nginx.pid;\n\n\n"
fc += "events {\n"
fc += " worker_connections 1024;\n"
fc += "}\n"
fc += "http {\n"
fc += " include /etc/nginx/mime.types;\n"
fc += " default_type application/octet-stream;\n\n"
fc += " log_format main '$remote_addr - $remote_user [$time_local] \"$request\" '\n"
fc += " '$status $body_bytes_sent \"$http_referer\" '\n"
fc += " '\"$http_user_agent\" \"$http_x_forwarded_for\"';\n\n"
fc += " access_log /var/log/nginx/access.log main;\n\n"
fc += " sendfile on;\n"
fc += " #tcp_nopush on;\n\n"
fc += " keepalive_timeout 65;\n\n"
fc += " #gzip on;\n\n"
# Define upstream block for load balancing
fc += " upstream app_backend {\n"
for i in range(1, num_backends + 1):
fc += f" server say-backend-{i}:5000;\n"
fc += " }\n\n"
# Configure server block to use the upstream
fc += " server {\n"
fc += " listen 80;\n\n"
fc += " location / {\n"
fc += " proxy_pass http://app_backend;\n"
fc += " proxy_set_header Host $host;\n"
fc += " proxy_set_header X-Real-IP $remote_addr;\n"
fc += " proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n"
fc += " proxy_set_header X-Forwarded-Proto $scheme;\n"
fc += " }\n"
for route in nginx_restricted_routes:
fc += f" location {route} {{\n"
fc += f" allow {network_subnet};\n"
fc += " deny all;\n"
fc += " }\n"
fc += " }\n"
fc += "}\n"
# build nginx.conf with all backend instances inside the http block
f.write(fc)
with open("prometheus.yml", "w") as f:
promConfig = {
'global': {
'scrape_interval': '15s',
'evaluation_interval': '15s',
'external_labels': {
'monitor': 'codelab'
}
},
'scrape_configs': [
{
'job_name': 'nginx',
'static_configs': [
{
'targets': ['prometheus-nginx-exporter:9113']
}
]
},
{
'job_name': 'backend',
'static_configs': [
{
'targets': [f'say-backend-{i}:5000' for i in range(1, num_backends + 1)]
}
]
}
]
}
with open('prometheus.yml', 'w') as f:
f.write(f"# generated at: {datetime.now().isoformat()}\n")
yaml.dump(promConfig, f, default_flow_style=False)
print(f"docker-compose.yml generated with {num_backends} backend instance(s).")