-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathrest_service.py
273 lines (218 loc) · 8.42 KB
/
rest_service.py
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
import asyncio
import json
import time
from uuid import UUID, uuid4
from fastapi import (APIRouter, Body, FastAPI, HTTPException, Request,
WebSocket, status)
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.websockets import WebSocketDisconnect
from config import XRAY_ASSETS_PATH, XRAY_EXECUTABLE_PATH
from logger import logger
from xray import XRayConfig, XRayCore
app = FastAPI()
@app.exception_handler(RequestValidationError)
def validation_exception_handler(request: Request, exc: RequestValidationError):
details = {}
for error in exc.errors():
details[error["loc"][-1]] = error.get("msg")
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=jsonable_encoder({"detail": details}),
)
class Service(object):
def __init__(self):
self.router = APIRouter()
self.connected = False
self.client_ip = None
self.session_id = None
self.core = XRayCore(
executable_path=XRAY_EXECUTABLE_PATH,
assets_path=XRAY_ASSETS_PATH
)
self.core_version = self.core.get_version()
self.config = None
self.router.add_api_route("/", self.base, methods=["POST"])
self.router.add_api_route("/ping", self.ping, methods=["POST"])
self.router.add_api_route("/connect", self.connect, methods=["POST"])
self.router.add_api_route("/disconnect", self.disconnect, methods=["POST"])
self.router.add_api_route("/start", self.start, methods=["POST"])
self.router.add_api_route("/stop", self.stop, methods=["POST"])
self.router.add_api_route("/restart", self.restart, methods=["POST"])
self.router.add_websocket_route("/logs", self.logs)
def match_session_id(self, session_id: UUID):
if session_id != self.session_id:
raise HTTPException(
status_code=403,
detail="Session ID mismatch."
)
return True
def response(self, **kwargs):
return {
"connected": self.connected,
"started": self.core.started,
"core_version": self.core_version,
**kwargs
}
def base(self):
return self.response()
def connect(self, request: Request):
self.session_id = uuid4()
self.client_ip = request.client.host
if self.connected:
logger.warning(
f'New connection from {self.client_ip}, Core control access was taken away from previous client.')
if self.core.started:
try:
self.core.stop()
except RuntimeError:
pass
self.connected = True
logger.info(f'{self.client_ip} connected, Session ID = "{self.session_id}".')
return self.response(
session_id=self.session_id
)
def disconnect(self):
if self.connected:
logger.info(f'{self.client_ip} disconnected, Session ID = "{self.session_id}".')
self.session_id = None
self.client_ip = None
self.connected = False
if self.core.started:
try:
self.core.stop()
except RuntimeError:
pass
return self.response()
def ping(self, session_id: UUID = Body(embed=True)):
self.match_session_id(session_id)
return {}
def start(self, session_id: UUID = Body(embed=True), config: str = Body(embed=True)):
self.match_session_id(session_id)
try:
config = XRayConfig(config, self.client_ip)
except json.decoder.JSONDecodeError as exc:
raise HTTPException(
status_code=422,
detail={
"config": f'Failed to decode config: {exc}'
}
)
with self.core.get_logs() as logs:
try:
self.core.start(config)
start_time = time.time()
end_time = start_time + 3
last_log = ''
while time.time() < end_time:
while logs:
log = logs.popleft()
if log:
last_log = log
if f'Xray {self.core_version} started' in log:
break
time.sleep(0.1)
except Exception as exc:
logger.error(f"Failed to start core: {exc}")
raise HTTPException(
status_code=503,
detail=str(exc)
)
if not self.core.started:
raise HTTPException(
status_code=503,
detail=last_log
)
return self.response()
def stop(self, session_id: UUID = Body(embed=True)):
self.match_session_id(session_id)
try:
self.core.stop()
except RuntimeError:
pass
return self.response()
def restart(self, session_id: UUID = Body(embed=True), config: str = Body(embed=True)):
self.match_session_id(session_id)
try:
config = XRayConfig(config, self.client_ip)
except json.decoder.JSONDecodeError as exc:
raise HTTPException(
status_code=422,
detail={
"config": f'Failed to decode config: {exc}'
}
)
try:
with self.core.get_logs() as logs:
self.core.restart(config)
start_time = time.time()
end_time = start_time + 3
last_log = ''
while time.time() < end_time:
while logs:
log = logs.popleft()
if log:
last_log = log
if f'Xray {self.core_version} started' in log:
break
time.sleep(0.1)
except Exception as exc:
logger.error(f"Failed to restart core: {exc}")
raise HTTPException(
status_code=503,
detail=str(exc)
)
if not self.core.started:
raise HTTPException(
status_code=503,
detail=last_log
)
return self.response()
async def logs(self, websocket: WebSocket):
session_id = websocket.query_params.get('session_id')
interval = websocket.query_params.get('interval')
try:
session_id = UUID(session_id)
if session_id != self.session_id:
return await websocket.close(reason="Session ID mismatch.", code=4403)
except ValueError:
return await websocket.close(reason="session_id should be a valid UUID.", code=4400)
if interval:
try:
interval = float(interval)
except ValueError:
return await websocket.close(reason="Invalid interval value.", code=4400)
if interval > 10:
return await websocket.close(reason="Interval must be more than 0 and at most 10 seconds.", code=4400)
await websocket.accept()
cache = ''
last_sent_ts = 0
with self.core.get_logs() as logs:
while session_id == self.session_id:
if interval and time.time() - last_sent_ts >= interval and cache:
try:
await websocket.send_text(cache)
except (WebSocketDisconnect, RuntimeError):
break
cache = ''
last_sent_ts = time.time()
if not logs:
try:
await asyncio.wait_for(websocket.receive(), timeout=0.2)
continue
except asyncio.TimeoutError:
continue
except (WebSocketDisconnect, RuntimeError):
break
log = logs.popleft()
if interval:
cache += f'{log}\n'
continue
try:
await websocket.send_text(log)
except (WebSocketDisconnect, RuntimeError):
break
await websocket.close()
service = Service()
app.include_router(service.router)