-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
406 lines (343 loc) Β· 15.1 KB
/
Copy pathserver.py
File metadata and controls
406 lines (343 loc) Β· 15.1 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
"""
server.py β Web server for Render/Railway deployment.
Flask runs in a daemon thread.
Bot runs as a SUBPROCESS β stdout/stderr piped so all logs are visible.
SIGTERM from Render is caught and forwarded to the bot process.
Upgrades over previous version:
- /health β real bot-process liveness check (not always OK)
- /status β uptime + restart count + PID + version JSON
- /metrics β active grants count from MongoDB (lightweight)
- /oauth/callback β improved HTML with auto-select URL
- Exponential backoff on restart (5 β 10 β 20 β 40 β max 60s)
- threading.Event for thread-safe bot_running state
- stream_output label actually used in log prefix
- Startup banner with Python version + platform info
"""
import os
import sys
import platform
import subprocess
import threading
import logging
import signal
import time
from flask import Flask, jsonify
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# ββ Logging βββββββββββββββββββββββββββββββββββββββββββββββββββ
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
LOGGER = logging.getLogger(__name__)
# ββ Flask app βββββββββββββββββββββββββββββββββββββββββββββββββ
flask_app = Flask(__name__)
# ββ Shared state (thread-safe) ββββββββββββββββββββββββββββββββ
_bot_running = threading.Event() # set = running, clear = stopped
_shutdown = threading.Event() # set = shutdown requested
_state = {
"start_time": time.time(),
"restart_count": 0,
"bot_pid": None,
"last_exit_code": None,
}
bot_process: subprocess.Popen | None = None
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Flask Routes
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@flask_app.route("/")
@flask_app.route("/status")
def status():
"""
Returns JSON with runtime info.
Used by UptimeRobot / monitoring dashboards.
"""
uptime_secs = int(time.time() - _state["start_time"])
days, rem = divmod(uptime_secs, 86400)
hours, rem = divmod(rem, 3600)
mins = rem // 60
uptime_str = ""
if days: uptime_str += f"{days}d "
if hours: uptime_str += f"{hours}h "
uptime_str += f"{mins}m"
# Try to read version from config without importing the full stack
try:
import config
version = getattr(config, "VERSION", "unknown")
except Exception:
version = "unknown"
return jsonify({
"status": "running" if _bot_running.is_set() else "starting",
"uptime": uptime_str.strip(),
"uptime_secs": uptime_secs,
"restart_count": _state["restart_count"],
"bot_pid": _state["bot_pid"],
"last_exit_code": _state["last_exit_code"],
"version": version,
"python": platform.python_version(),
})
@flask_app.route("/health")
def health():
"""
Real liveness check β returns 200 only if bot subprocess is alive.
Render uses this to decide whether to restart the service.
Previously always returned 200 even when bot was dead.
"""
if bot_process is not None and bot_process.poll() is None:
return "OK", 200
# Bot not running β return 503 so Render/UptimeRobot knows
return "Bot not running", 503
@flask_app.route("/metrics")
def metrics():
"""
Lightweight operational metrics.
Queries MongoDB for active grant count β useful for monitoring dashboards.
Fails gracefully if DB is unreachable.
"""
try:
import asyncio
from services.database import db
loop = asyncio.new_event_loop()
grants = loop.run_until_complete(db.get_active_grants())
loop.close()
now = time.time()
expiring_soon = sum(
1 for g in grants
if 0 < g.get("expires_at", 0) - now < 86400
)
return jsonify({
"active_grants": len(grants),
"expiring_soon": expiring_soon,
"bot_running": _bot_running.is_set(),
"restart_count": _state["restart_count"],
})
except Exception as e:
return jsonify({"error": str(e), "bot_running": _bot_running.is_set()}), 500
@flask_app.route("/oauth/callback")
def oauth_callback():
"""
OAuth redirect landing page.
Improved: shows the full URL clearly with an auto-select button.
"""
return """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Google Drive Bot β OAuth</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #0f0f0f; color: #e0e0e0;
min-height: 100vh; display: flex;
align-items: center; justify-content: center; padding: 20px;
}
.card {
background: #1a1a2e; border: 1px solid #2d2d4e;
border-radius: 16px; padding: 36px 32px;
max-width: 540px; width: 100%; text-align: center;
}
.icon { font-size: 48px; margin-bottom: 16px; }
h1 { font-size: 22px; color: #4ade80; margin-bottom: 8px; }
p { color: #9ca3af; font-size: 14px; line-height: 1.6; margin-bottom: 20px; }
.url-box {
background: #0d0d1a; border: 1px solid #3b3b6b;
border-radius: 10px; padding: 12px 16px;
font-family: monospace; font-size: 12px;
color: #a78bfa; word-break: break-all;
text-align: left; margin-bottom: 16px;
max-height: 80px; overflow-y: auto;
}
button {
background: #4f46e5; color: white;
border: none; border-radius: 10px;
padding: 12px 28px; font-size: 15px;
cursor: pointer; width: 100%;
transition: background 0.2s;
}
button:hover { background: #4338ca; }
button:active { background: #3730a3; }
.copied { background: #16a34a !important; }
.step {
background: #111827; border-radius: 10px;
padding: 16px; text-align: left;
margin-bottom: 20px;
}
.step li { margin: 6px 0; font-size: 13px; color: #d1d5db; }
.step li span { color: #60a5fa; font-weight: 600; }
</style>
</head>
<body>
<div class="card">
<div class="icon">β
</div>
<h1>Authorization Received!</h1>
<p>Google has redirected you here. Now send this URL back to your bot.</p>
<div class="url-box" id="urlBox"></div>
<button id="copyBtn" onclick="copyUrl()">π Copy Full URL</button>
<br><br>
<div class="step">
<ol>
<li><span>Step 1:</span> Click "Copy Full URL" above</li>
<li><span>Step 2:</span> Go back to Telegram</li>
<li><span>Step 3:</span> Paste the URL and send it to the bot</li>
<li><span>Step 4:</span> Done! β
</li>
</ol>
</div>
<p style="font-size:12px; color:#6b7280;">
This page is safe to close after copying the URL.
</p>
</div>
<script>
const url = window.location.href;
document.getElementById("urlBox").textContent = url;
function copyUrl() {
navigator.clipboard.writeText(url).then(() => {
const btn = document.getElementById("copyBtn");
btn.textContent = "β
Copied!";
btn.classList.add("copied");
setTimeout(() => {
btn.textContent = "π Copy Full URL";
btn.classList.remove("copied");
}, 2500);
}).catch(() => {
// Fallback: select the text
const box = document.getElementById("urlBox");
const range = document.createRange();
range.selectNodeContents(box);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
});
}
// Auto-select URL text on page load for easy manual copy
window.onload = () => {
const box = document.getElementById("urlBox");
const range = document.createRange();
range.selectNodeContents(box);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
};
</script>
</body>
</html>
""", 200
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Flask thread
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_flask():
port = int(os.getenv("PORT", 10000))
LOGGER.info(f"π Flask listening on port {port}")
flask_app.run(host="0.0.0.0", port=port, use_reloader=False)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Signal handler
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def handle_shutdown_signal(signum, _frame):
sig_name = signal.Signals(signum).name
LOGGER.info(f"π Signal {sig_name} received β shutting down...")
_shutdown.set()
_bot_running.clear()
if bot_process and bot_process.poll() is None:
LOGGER.info("Terminating bot subprocess...")
bot_process.terminate()
try:
bot_process.wait(timeout=10)
except subprocess.TimeoutExpired:
LOGGER.warning("Bot did not stop in time β killing.")
bot_process.kill()
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Log streamer
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def stream_output(pipe, label: str = "BOT"):
"""Stream subprocess stdout/stderr to our logger so logs appear in Render dashboard."""
try:
for line in iter(pipe.readline, b""):
text = line.decode("utf-8", errors="replace").rstrip()
if text:
LOGGER.info(f"[{label}] {text}")
except Exception:
pass
finally:
pipe.close()
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Bot subprocess runner with exponential backoff
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
BACKOFF_MIN = 5 # seconds β first restart delay
BACKOFF_MAX = 60 # seconds β maximum restart delay
BACKOFF_FACTOR = 2 # multiply delay on each consecutive crash
BACKOFF_RESET = 300 # seconds β reset delay if bot ran this long
def run_bot_subprocess():
global bot_process
python = sys.executable
bot_dir = os.path.dirname(os.path.abspath(__file__))
delay = BACKOFF_MIN
while not _shutdown.is_set():
LOGGER.info(f"βΆοΈ Starting bot subprocess (bot.py) β attempt #{_state['restart_count'] + 1}")
launch_time = time.time()
try:
bot_process = subprocess.Popen(
[python, "-u", "bot.py"], # -u = unbuffered stdout
cwd=bot_dir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, # merge stderr into stdout
)
except Exception as e:
LOGGER.error(f"β Failed to start bot subprocess: {e}. Retrying in {delay}s...")
_shutdown.wait(timeout=delay)
delay = min(delay * BACKOFF_FACTOR, BACKOFF_MAX)
continue
_state["bot_pid"] = bot_process.pid
_bot_running.set()
LOGGER.info(f"β
Bot subprocess started (PID={bot_process.pid})")
# Stream logs in background thread
out_thread = threading.Thread(
target=stream_output,
args=(bot_process.stdout, "BOT"),
daemon=True,
)
out_thread.start()
bot_process.wait()
out_thread.join(timeout=2)
_bot_running.clear()
exit_code = bot_process.returncode
_state["last_exit_code"] = exit_code
_state["restart_count"] += 1
runtime = time.time() - launch_time
LOGGER.info(f"Bot subprocess exited (code={exit_code}, runtime={runtime:.0f}s)")
if _shutdown.is_set():
LOGGER.info("Shutdown requested β not restarting.")
break
# Exponential backoff β reset if bot ran long enough (healthy run)
if runtime >= BACKOFF_RESET:
delay = BACKOFF_MIN
LOGGER.info(f"Bot ran {runtime:.0f}s β resetting restart delay to {delay}s")
else:
LOGGER.warning(
f"β οΈ Bot exited after {runtime:.0f}s (code={exit_code}). "
f"Restarting in {delay}s... (restart #{_state['restart_count']})"
)
_shutdown.wait(timeout=delay)
delay = min(delay * BACKOFF_FACTOR, BACKOFF_MAX)
LOGGER.info("Bot runner loop finished.")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Entry point
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
# Startup banner
LOGGER.info("ββββββββββββββββββββββββββββββββββββββββ")
LOGGER.info(" Google Drive Access Manager Bot")
LOGGER.info(f" Python : {platform.python_version()}")
LOGGER.info(f" Platform: {platform.system()} {platform.release()}")
LOGGER.info(f" PID : {os.getpid()}")
LOGGER.info("ββββββββββββββββββββββββββββββββββββββββ")
signal.signal(signal.SIGTERM, handle_shutdown_signal)
signal.signal(signal.SIGINT, handle_shutdown_signal)
# Flask in daemon thread β dies when main thread exits
LOGGER.info("π Starting Flask thread...")
flask_thread = threading.Thread(target=run_flask, daemon=True)
flask_thread.start()
# Bot runner in non-daemon thread β keeps process alive
LOGGER.info("π€ Starting bot runner thread...")
bot_thread = threading.Thread(target=run_bot_subprocess, daemon=False)
bot_thread.start()
bot_thread.join()
LOGGER.info("server.py exiting.")