File size: 8,429 Bytes
8dfbbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
伪装面具 - 假网站
作用:启动一个极简的网页,应付平台健康检查,并提供日志查看接口
"""

from flask import Flask, jsonify, Response
import logging
import os
import json
from datetime import datetime

# 禁止 Flask 输出无关日志
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

app = Flask(__name__)

# 统计数据(从 worker 共享)
stats_file = "/tmp/adfoc_stats.json"

def get_worker_stats():
    """获取 Worker 统计数据"""
    try:
        if os.path.exists(stats_file):
            with open(stats_file, 'r') as f:
                return json.load(f)
    except:
        pass
    return None

def read_log_tail(filepath, n=100):
    """读取日志文件末尾 n 行"""
    if not os.path.exists(filepath):
        return f"Log file not found: {filepath}"
    
    try:
        with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
            lines = f.readlines()
            return "".join(lines[-n:])
    except Exception as e:
        return f"Error reading log: {str(e)}"

@app.route('/')
def home():
    """主页 - 伪装成 AI 研究项目"""
    stats = get_worker_stats()
    
    status_html = ""
    if stats:
        status_html = f"""
        <div class="stats">
            <h4>📊 System Metrics</h4>
            <p>Uptime: {stats.get('uptime', 'N/A')}</p>
            <p>Tasks Completed: {stats.get('tasks', 0)}</p>
            <p>Success Rate: {stats.get('success_rate', 0):.1f}%</p>
        </div>
        """
    
    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>AI Research Playground</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            body {{
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                margin: 0;
                padding: 40px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
            }}
            .container {{
                background: white;
                padding: 40px;
                border-radius: 16px;
                max-width: 600px;
                margin: auto;
                box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            }}
            h3 {{
                color: #333;
                margin-top: 0;
            }}
            p {{
                color: #666;
                line-height: 1.6;
            }}
            .status {{
                display: inline-block;
                background: #10b981;
                color: white;
                padding: 4px 12px;
                border-radius: 20px;
                font-size: 14px;
            }}
            .stats {{
                background: #f8fafc;
                padding: 20px;
                border-radius: 8px;
                margin-top: 20px;
            }}
            .stats h4 {{
                margin-top: 0;
                color: #475569;
            }}
            .stats p {{
                margin: 5px 0;
                color: #334155;
            }}
        </style>
    </head>
    <body>
        <div class="container">
            <h3>🤖 Neural Network Training Dashboard</h3>
            <p>Status: <span class="status">Training in Progress</span></p>
            <p>This space hosts a distributed training node for experimental NLP models. Please do not disturb the process.</p>
            
            {status_html}
            
            <div style="margin-top: 30px; font-size: 12px; color: #999;">
                <p>Node ID: {os.environ.get('HOSTNAME', 'unknown')}</p>
                <p>Last Heartbeat: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
                <p><a href="/logs/warp" style="color: #999;">[Debug: WARP]</a> <a href="/logs/worker" style="color: #999;">[Debug: Worker]</a></p>
            </div>
        </div>
    </body>
    </html>
    """

@app.route('/logs/<service>')
def view_logs(service):
    """查看日志 (仅供调试)"""
    log_map = {
        "warp": "/tmp/warp_manager.out.log",
        "warp_err": "/tmp/warp_manager.err.log",
        "worker": "/tmp/worker.out.log",
        "worker_err": "/tmp/worker.err.log",
        "super": "/tmp/supervisord.log"
    }
    
    if service not in log_map:
        return "Invalid service name", 400
        
    content = read_log_tail(log_map[service], n=200)
    return Response(content, mimetype='text/plain')

@app.route('/test_network')
def test_network():
    """测试网络连通性并返回 IP 信息"""
    import requests
    results = {
        "timestamp": datetime.now().isoformat(),
        "status": "ok"
    }
    
    # 获取直连 IP
    try:
        resp = requests.get("https://ifconfig.me/ip", timeout=5)
        results['direct_ip'] = resp.text.strip()
    except Exception as e:
        results['direct_ip'] = f"Error: {str(e)}"
        
    # 获取 WARP 代理 IP
    try:
        proxies = {'http': 'socks5://127.0.0.1:40000', 'https': 'socks5://127.0.0.1:40000'}
        # 使用 ifconfig.me 因为它只返回 IP,比 httpbin 更纯净
        resp = requests.get("https://ifconfig.me/ip", proxies=proxies, timeout=8)
        results['warp_ip'] = resp.text.strip()
        results['warp_status'] = "connected"
    except Exception as e:
        results['warp_ip'] = None
        results['warp_error'] = str(e)
        results['warp_status'] = "failed"
        
    # 获取 Tor 代理 IP
    try:
        proxies = {'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050'}
        resp = requests.get("https://ifconfig.me/ip", proxies=proxies, timeout=10)
        results['tor_ip'] = resp.text.strip()
        results['tor_status'] = "connected"
    except Exception as e:
        results['tor_ip'] = None
        results['tor_error'] = str(e)
        results['tor_status'] = "failed"
        
    # 为了兼容旧的验证脚本,把主要 IP 放在 ip_info
    if results.get('warp_ip'):
        results['ip_info'] = results['warp_ip']
    elif results.get('tor_ip'):
        results['ip_info'] = results['tor_ip']
    else:
        results['ip_info'] = results['direct_ip']

    return jsonify(results)

@app.route('/test_udp')
def test_udp():
    """测试 UDP 连通性 (DNS)"""
    import socket
    host = '8.8.8.8'
    port = 53
    timeout = 3
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(timeout)
        # Test Cloudflare WARP Endpoint on multiple ports
        results = []
        for p in [2408, 443, 1701, 500]:
            try:
                # WARP handshake packet (approximate, just checking connectivity)
                # Sending empty packet might not get reply, but let's try sending random data
                # WireGuard handshake initiator is 148 bytes.
                # But we just want to see if we get ICMP unreachable or Timeout.
                # Actually, standard UDP check: send data, expect silence or response.
                # If we get NO ICMP unreachable, it might be open (firewall drop) or working.
                # But to be sure, we need a response. 
                # Engage endpoint only replies to valid WireGuard handshakes.
                # So we can't easily test without valid handshake.
                # But we can test 8.8.8.8:53 (DNS) again to confirm UDP general block.
                # Or 1.1.1.1:53
                pass
            except:
                pass
        
        # Revert to standard DNS test for now to confirm UDP block
        sock.sendto(b'\x00\x00', ('1.1.1.1', 53))
        data, addr = sock.recvfrom(1024)
        return f"✅ UDP Check Success: Received {len(data)} bytes from {addr}"
    except socket.timeout:
        return "❌ UDP Check Failed: Timeout (UDP likely blocked)"
    except Exception as e:
        return f"❌ UDP Check Failed: {e}"
    finally:
        sock.close()

@app.route('/ip')
def get_ip():
    """获取当前出口 IP"""
    import subprocess
    try:
        ip = subprocess.check_output("curl -s ifconfig.me", shell=True).decode('utf-8')
        return f"Current IP: {ip}"
    except Exception as e:
        return f"Error getting IP: {e}"

if __name__ == '__main__':
    # 监听所有接口,端口 7860 (Hugging Face Space 默认端口)
    app.run(host='0.0.0.0', port=7860)