smokymath commited on
Commit
59a8725
·
verified ·
1 Parent(s): 2a9e960

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -41
app.py CHANGED
@@ -2,40 +2,55 @@ from flask import Flask
2
  import subprocess
3
  import time
4
  import json
5
- import os # Added for environment variables
 
6
 
7
  app = Flask(__name__)
 
8
 
9
- def start_ngrok(ngrok_auth):
10
- try:
11
- proc = subprocess.Popen(
12
- ["ngrok", "tcp", "25565", "--region=eu", "--log=stdout", "--authtoken", ngrok_auth],
13
- stdout=subprocess.PIPE,
14
- stderr=subprocess.STDOUT,
15
- text=True
16
- )
17
-
18
- tunnel_url = None
19
- for _ in range(30):
20
- try:
21
- result = subprocess.check_output(
22
- ["curl", "-s", "http://localhost:4040/api/tunnels"],
23
- timeout=5
24
- )
25
- data = json.loads(result)
26
- if data.get("tunnels"):
27
- tunnel_url = data["tunnels"][0]["public_url"]
28
- print(f"\n🔗 Tunnel Established: {tunnel_url}")
29
- return tunnel_url.replace("tcp://", "")
30
- except:
31
- time.sleep(1)
32
- continue
33
-
34
- raise Exception("Ngrok tunnel timeout after 30 seconds")
35
 
36
- except Exception as e:
37
- print(f"❌ Critical Error: {str(e)}")
38
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  def start_minecraft():
41
  subprocess.Popen(["/bin/bash", "start.sh"])
@@ -45,17 +60,16 @@ def status():
45
  return "🟢 Server Running - Check logs for connection URL"
46
 
47
  if __name__ == "__main__":
48
- # Get ngrok auth token from environment variables
49
  ngrok_auth = os.environ.get("NGROK_AUTH_TOKEN")
50
-
51
  if not ngrok_auth:
52
- print("❌ Error: Missing NGROK_AUTH_TOKEN environment variable")
53
  exit(1)
54
-
55
- url = start_ngrok(ngrok_auth)
56
- if not url:
57
- exit(1)
58
-
59
- start_minecraft()
60
- print(f"\n✅ Ready! Connect using: {url}")
61
- app.run(host='0.0.0.0', port=7860)
 
 
2
  import subprocess
3
  import time
4
  import json
5
+ import os
6
+ import logging
7
 
8
  app = Flask(__name__)
9
+ logging.basicConfig(level=logging.INFO)
10
 
11
+ def start_ngrok(ngrok_auth, max_retries=5, initial_delay=5):
12
+ """Start ngrok with exponential backoff retry strategy"""
13
+ attempt = 0
14
+ delay = initial_delay
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ while attempt < max_retries:
17
+ try:
18
+ logging.info(f"Starting ngrok attempt {attempt + 1}/{max_retries}")
19
+ proc = subprocess.Popen(
20
+ ["ngrok", "tcp", "25565", "--region=eu", "--log=stdout", "--authtoken", ngrok_auth],
21
+ stdout=subprocess.PIPE,
22
+ stderr=subprocess.STDOUT,
23
+ text=True
24
+ )
25
+
26
+ tunnel_url = None
27
+ for _ in range(40): # Increased timeout to 40 seconds per attempt
28
+ try:
29
+ result = subprocess.check_output(
30
+ ["curl", "-s", "http://localhost:4040/api/tunnels"],
31
+ timeout=8 # Increased individual request timeout
32
+ )
33
+ data = json.loads(result)
34
+ if data.get("tunnels"):
35
+ tunnel_url = data["tunnels"][0]["public_url"]
36
+ logging.info(f"🔗 Tunnel Established: {tunnel_url}")
37
+ return tunnel_url.replace("tcp://", "")
38
+ except (subprocess.CalledProcessError, json.JSONDecodeError):
39
+ time.sleep(1)
40
+ continue
41
+
42
+ # If we exit loop without returning, log and retry
43
+ logging.warning("Ngrok tunnel timeout, retrying...")
44
+
45
+ except Exception as e:
46
+ logging.error(f"Attempt {attempt + 1} failed: {str(e)}")
47
+
48
+ # Exponential backoff with jitter
49
+ time.sleep(delay + (random.random() * 2))
50
+ delay *= 2
51
+ attempt += 1
52
+
53
+ raise Exception(f"Failed to establish ngrok tunnel after {max_retries} attempts")
54
 
55
  def start_minecraft():
56
  subprocess.Popen(["/bin/bash", "start.sh"])
 
60
  return "🟢 Server Running - Check logs for connection URL"
61
 
62
  if __name__ == "__main__":
 
63
  ngrok_auth = os.environ.get("NGROK_AUTH_TOKEN")
 
64
  if not ngrok_auth:
65
+ logging.error("❌ Missing NGROK_AUTH_TOKEN environment variable")
66
  exit(1)
67
+
68
+ try:
69
+ url = start_ngrok(ngrok_auth)
70
+ start_minecraft()
71
+ logging.info(f"\n✅ Ready! Connect using: {url}")
72
+ app.run(host='0.0.0.0', port=7860)
73
+ except Exception as e:
74
+ logging.error(f"❌ Critical startup failure: {str(e)}")
75
+ exit(1)