Add front-end functionality and improved server.py and node.py
All checks were successful
Test CI / test speed (push) Successful in 17s

This commit is contained in:
muzhi 2024-10-15 17:05:39 +08:00
parent 24a5e91382
commit bf6e25b722
21 changed files with 20491 additions and 29 deletions

View File

@ -8,7 +8,7 @@ COPY requirements.txt /app/
# 根据目标平台复制相应架构的库文件
#COPY lib/${TARGETPLATFORM}/* /lib/
COPY lib/* /lib/
COPY lib/* /usr/local/lib/
WORKDIR /app
@ -16,3 +16,4 @@ RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
RUN pip install --index-url https://git.mamahaha.work/api/packages/sangge/pypi/simple/ ecc-rs
RUN ldconfig

View File

@ -3,9 +3,9 @@
## Run docker
```bash
docker run -it -p 8000-8002:8000-8002 -v ~/mimajingsai/src:/app -e HOST_IP=60.204.193.58 git.mamahaha.work/sangge/tpre:base bash
docker run -it -p 8000-8002:8000-8002 -v ~/mimajingsai/src:/app -e HOST_IP=119.3.125.234 git.mamahaha.work/sangge/tpre:base bash
docker run -it -p 8000-8002:8000-8002 -v ~/mimajingsai/src:/app -e HOST_IP=124.70.165.73 git.mamahaha.work/sangge/tpre:base bash
docker run -it -p 8000-8002:8000-8002 -v ~/tpre-python/src:/app -e HOST_IP=192.168.8.57 -e server_address=192.168.8.57:8000 git.mamahaha.work/sangge/tpre:base bash
docker run -it -p 8000-8002:8000-8002 -v ~/tpre-python/src:/app -e HOST_IP=119.3.125.234 git.mamahaha.work/sangge/tpre:base bash
docker run -it -p 8000-8002:8000-8002 -v ~/tpre-python/src:/app -e HOST_IP=124.70.165.73 git.mamahaha.work/sangge/tpre:base bash
```
```bash

23
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

70
frontend/README.md Normal file
View File

@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

19780
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
frontend/package.json Normal file
View File

@ -0,0 +1,39 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>中央服务器路由</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div id="root"></div>
<script src="/frontend/static/js/bundle.js"></script> <!-- 通过构建工具引入打包后的JS文件 -->
</body>
</html>

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

29
frontend/src/App.css Normal file
View File

@ -0,0 +1,29 @@
.App-header {
background-color: #282c34;
padding: 20px;
color: white;
}
.App {
text-align: center;
margin: 20px;
}
table {
margin: 20px auto;
border-collapse: collapse;
}
table, th, td {
border: 1px solid #ccc;
padding: 10px;
}
th {
background-color: #f0f0f0;
}
.log-info {
width: 80%;
margin: 20px auto;
}

118
frontend/src/App.js Normal file
View File

@ -0,0 +1,118 @@
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import WebSocketComponent from './WebSocketComponent';
function App() {
const [nodes, setNodes] = useState([]);
const [node, setNode] = useState(null);
const [heartbeat, setHeartbeat] = useState(null);
const [nodesList, setNodesList] = useState([]);
const [ip, setIp] = useState('');
const [count, setCount] = useState('');
const fetchNodes = async () => {
try {
const response = await axios.get('/server/show_nodes');
setNodes(response.data);
} catch (error) {
console.error('Error fetching nodes:', error);
}
};
const fetchNode = async (ip) => {
try {
const response = await axios.get('/server/get_node', { params: { ip } });
setNode(response.data);
} catch (error) {
console.error('Error fetching node:', error);
}
};
const fetchHeartbeat = async (ip) => {
try {
const response = await axios.get('/server/heartbeat', { params: { ip } });
setHeartbeat(response.data);
} catch (error) {
console.error('Error fetching heartbeat:', error);
}
};
const fetchNodesList = async (count) => {
try {
const response = await axios.get('/server/send_nodes_list', { params: { count } });
setNodesList(response.data);
} catch (error) {
console.error('Error fetching nodes list:', error);
}
};
useEffect(() => {
fetchNodes(); // 获取所有节点
}, []);
const handleFetchNode = () => {
fetchNode(ip); // 根据输入的 IP 获取单个节点
};
const handleFetchHeartbeat = () => {
fetchHeartbeat(ip); // 根据输入的 IP 获取心跳信息
};
const handleFetchNodesList = () => {
fetchNodesList(count); // 根据输入的数量获取节点列表
};
return (
<div className="App">
<header className="App-header">
<h1>中央服务器路由</h1>
<h2>所有节点</h2>
{nodes.length > 0 ? (
<ul>
{nodes.map((node, index) => (
<li key={index}>{JSON.stringify(node)}</li>
))}
</ul>
) : (
<p>没有节点数据</p>
)}
<h2>单个节点</h2>
<input
type="text"
value={ip}
onChange={(e) => setIp(e.target.value)}
placeholder="输入节点 IP"
/>
<button onClick={handleFetchNode}>获取节点</button>
{node ? <p>{JSON.stringify(node)}</p> : <p></p>}
<h2>心跳信息</h2>
<button onClick={handleFetchHeartbeat}>获取心跳信息</button>
{heartbeat ? <p>{JSON.stringify(heartbeat)}</p> : <p></p>}
<h2>节点列表</h2>
<input
type="number"
value={count}
onChange={(e) => setCount(e.target.value)}
placeholder="输入节点数量"
/>
<button onClick={handleFetchNodesList}>获取节点列表</button>
{nodesList.length > 0 ? (
<ul>
{nodesList.map((node, index) => (
<li key={index}>{JSON.stringify(node)}</li>
))}
</ul>
) : (
<p>没有节点列表数据</p>
)}
</header>
<WebSocketComponent/>
</div>
);
}
export default App;

View File

@ -0,0 +1,115 @@
import React, { useEffect, useState, useRef, useCallback } from 'react';
const WebSocketComponent = () => {
const [logs, setLogs] = useState([]);
const [nodes, setNodes] = useState([]);
const wsRef = useRef(null);
const heartbeatIntervalRef = useRef(null);
const connectWebSocket = useCallback(() => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
return; // 如果连接已经打开,不再重新连接
}
wsRef.current = new WebSocket('ws://localhost:8000/ws/logs');
wsRef.current.onopen = () => {
console.log('WebSocket 连接成功');
heartbeatIntervalRef.current = setInterval(() => {
if (wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: 'heartbeat' }));
}
}, 10000); // 心跳包间隔调整为 10 秒
};
wsRef.current.onmessage = (event) => {
setLogs((prevLogs) => [...prevLogs, event.data]); // 直接加入收到的消息
};
wsRef.current.onerror = (error) => {
console.error('WebSocket 错误: ', error);
};
wsRef.current.onclose = () => {
console.log('WebSocket 连接关闭,尝试重新连接...');
clearInterval(heartbeatIntervalRef.current);
// 确保 WebSocket 连接在关闭后再进行重连
setTimeout(() => {
connectWebSocket();
}, 5000); // 延迟 5 秒再重连
};
}, []);
useEffect(() => {
connectWebSocket();
return () => {
if (wsRef.current) {
wsRef.current.close();
}
clearInterval(heartbeatIntervalRef.current);
};
}, [connectWebSocket]);
// 获取节点信息
const fetchNodes = useCallback(async () => {
try {
const response = await fetch('/server/show_nodes');
const data = await response.json();
setNodes(data);
} catch (error) {
console.error('Error fetching nodes:', error);
}
}, []);
useEffect(() => {
connectWebSocket();
fetchNodes(); // 组件加载时获取节点信息
return () => {
if (wsRef.current) {
wsRef.current.close();
}
clearInterval(heartbeatIntervalRef.current);
};
}, [connectWebSocket, fetchNodes]);
useEffect(() => {
const logContainer = document.querySelector('.log-info');
if (logContainer) {
logContainer.scrollTop = logContainer.scrollHeight;
}
}, [logs]);
return (
<div>
<h1>节点记录信息</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>IP</th>
<th>Last Heartbeat</th>
</tr>
</thead>
<tbody>
{nodes.map((node) => (
<tr key={node[0]}>
<td>{node[0]}</td>
<td>{node[1]}</td>
<td>{new Date(node[2] * 1000).toLocaleString()}</td>
</tr>
))}
</tbody>
</table>
<h2>日志信息</h2>
<div
className="log-info"
style={{ height: '300px', overflowY: 'scroll', background: '#fff', padding: '10px' }}
>
{logs.map((log, index) => (
<p key={index} style={{ margin: '5px 0' }}>{log}</p>
))}
</div>
</div>
);
};
export default WebSocketComponent;

11
frontend/src/index.css Normal file
View File

@ -0,0 +1,11 @@
/* src/index.css */
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
}

13
frontend/src/index.js Normal file
View File

@ -0,0 +1,13 @@
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import './index.css';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

View File

@ -0,0 +1,10 @@
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
createProxyMiddleware('/server', {
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};

84
logs/server_logs.log Normal file
View File

@ -0,0 +1,84 @@
2024-10-14 22:50:49,964 - server - INFO - 节点信息已成功获取
2024-10-14 22:50:58,662 - server - INFO - 节点信息已成功获取
2024-10-14 22:51:03,979 - server - INFO - 节点信息已成功获取
2024-10-14 22:51:05,667 - server - INFO - 节点信息已成功获取
2024-10-14 22:51:13,103 - server - INFO - 节点信息已成功获取
2024-10-14 22:51:13,117 - server - INFO - 节点信息已成功获取
2024-10-14 22:51:13,119 - server - INFO - 节点信息已成功获取
2024-10-14 22:53:44,044 - server - INFO - 数据库已清空
2024-10-14 22:55:08,488 - server - INFO - 节点信息已成功获取
2024-10-14 22:55:08,494 - server - INFO - 节点信息已成功获取
2024-10-14 22:55:08,497 - server - INFO - 节点信息已成功获取
2024-10-14 22:56:22,602 - server - INFO - 数据库已清空
2024-10-14 22:56:44,348 - server - INFO - 节点信息已成功获取
2024-10-14 22:56:44,353 - server - INFO - 节点信息已成功获取
2024-10-14 22:56:44,356 - server - INFO - 节点信息已成功获取
2024-10-14 22:57:25,960 - server - INFO - 节点信息已成功获取
2024-10-14 22:57:25,964 - server - INFO - 节点信息已成功获取
2024-10-14 22:57:25,966 - server - INFO - 节点信息已成功获取
2024-10-14 22:57:27,676 - server - INFO - 节点信息已成功获取
2024-10-14 22:57:30,534 - server - INFO - 节点信息已成功获取
2024-10-14 22:57:30,537 - server - INFO - 节点信息已成功获取
2024-10-14 22:57:30,540 - server - INFO - 节点信息已成功获取
2024-10-14 23:05:37,396 - server - INFO - 节点信息已成功获取
2024-10-14 23:05:37,405 - server - INFO - 节点信息已成功获取
2024-10-14 23:05:45,897 - server - INFO - 节点信息已成功获取
2024-10-14 23:05:45,906 - server - INFO - 节点信息已成功获取
2024-10-14 23:05:50,598 - server - INFO - 已成功发送 2 个节点信息
2024-10-14 23:05:55,495 - server - INFO - 已成功发送 2 个节点信息
2024-10-14 23:06:34,923 - server - INFO - 已成功发送 2 个节点信息
2024-10-14 23:06:58,479 - server - WARNING - 收到无效 IP 格式的心跳包:
2024-10-14 23:11:47,671 - server - INFO - 节点信息已成功获取
2024-10-14 23:13:06,672 - server - INFO - 节点信息已成功获取
2024-10-14 23:13:19,665 - server - INFO - 节点信息已成功获取
2024-10-14 23:13:19,976 - server - INFO - 节点信息已成功获取
2024-10-14 23:13:20,286 - server - INFO - 节点信息已成功获取
2024-10-14 23:15:27,409 - server - INFO - 节点信息已成功获取
2024-10-14 23:15:27,558 - server - INFO - 节点信息已成功获取
2024-10-14 23:15:27,621 - server - INFO - 节点信息已成功获取
2024-10-14 23:15:27,631 - server - INFO - 节点信息已成功获取
2024-10-14 23:16:40,476 - server - INFO - 节点信息已成功获取
2024-10-14 23:16:40,487 - server - INFO - 节点信息已成功获取
2024-10-14 23:16:40,540 - server - INFO - 节点信息已成功获取
2024-10-14 23:16:40,798 - server - INFO - 节点信息已成功获取
2024-10-14 23:17:25,417 - server - INFO - 节点信息已成功获取
2024-10-14 23:18:35,867 - server - INFO - IP 119.3.125.234 对应的ID为 1996717546
2024-10-14 23:18:35,867 - server - INFO - 当前时间: 1728919115
2024-10-14 23:18:35,874 - server - INFO - 节点 119.3.125.234 已成功添加到数据库
2024-10-14 23:18:56,376 - server - WARNING - 节点 127.0.0.1 未找到
2024-10-14 23:19:22,373 - server - INFO - 已成功发送 1 个节点信息
2024-10-14 23:19:22,630 - server - INFO - 已成功发送 1 个节点信息
2024-10-14 23:19:27,170 - server - WARNING - 收到无效 IP 格式的心跳包:
2024-10-14 23:19:49,887 - server - INFO - 收到来自 119.3.125.234 的心跳包
2024-10-14 23:19:49,895 - server - INFO - 成功更新节点 119.3.125.234 的心跳时间
2024-10-14 23:19:54,186 - server - WARNING - 收到无效 IP 格式的心跳包:
2024-10-15 13:05:13,546 - server - INFO - 节点信息已成功获取
2024-10-15 13:05:13,556 - server - INFO - 节点信息已成功获取
2024-10-15 13:05:13,569 - server - INFO - 节点信息已成功获取
2024-10-15 13:05:13,584 - server - INFO - 节点信息已成功获取
2024-10-15 13:06:27,487 - server - INFO - 节点信息已成功获取
2024-10-15 13:08:25,875 - server - WARNING - 节点 127.0.0.1 未找到
2024-10-15 13:08:41,176 - server - INFO - IP 127.0.0.0 对应的ID为 2130706432
2024-10-15 13:08:41,176 - server - INFO - 当前时间: 1728968921
2024-10-15 13:08:41,183 - server - INFO - 节点 127.0.0.0 已成功添加到数据库
2024-10-15 13:08:42,347 - server - INFO - IP 127.0.0.0 对应的ID为 2130706432
2024-10-15 13:08:42,347 - server - INFO - 当前时间: 1728968922
2024-10-15 13:09:42,114 - asyncio - ERROR - Task exception was never retrieved
future: <Task finished name='Task-3' coro=<receive_heartbeat_internal() done, defined at /home/muzhi/tpre-python/src/server.py:232> exception=OperationalError('no such table: nodes')>
Traceback (most recent call last):
File "/home/muzhi/tpre-python/src/server.py", line 237, in receive_heartbeat_internal
db.execute(
sqlite3.OperationalError: no such table: nodes
2024-10-15 13:11:26,824 - server - INFO - IP 192.168.8.57 对应的ID为 3232237625
2024-10-15 13:11:26,824 - server - INFO - 当前时间: 1728969086
2024-10-15 13:11:26,831 - server - INFO - 节点 192.168.8.57 已成功添加到数据库
2024-10-15 13:11:28,244 - server - INFO - IP 192.168.8.57 对应的ID为 3232237625
2024-10-15 13:11:28,244 - server - INFO - 当前时间: 1728969088
2024-10-15 13:11:46,205 - server - INFO - IP 192.168.8.57 对应的ID为 3232237625
2024-10-15 13:11:46,205 - server - INFO - 当前时间: 1728969106
2024-10-15 13:12:28,014 - server - INFO - IP 192.168.8.58 对应的ID为 3232237626
2024-10-15 13:12:28,014 - server - INFO - 当前时间: 1728969148
2024-10-15 13:12:28,020 - server - INFO - 节点 192.168.8.58 已成功添加到数据库
2024-10-15 13:12:34,416 - server - INFO - 收到来自 192.168.8.58 的心跳包
2024-10-15 13:12:34,422 - server - INFO - 成功更新节点 192.168.8.58 的心跳时间
2024-10-15 13:12:42,439 - server - INFO - 已成功发送 1 个节点信息

6
package-lock.json generated Normal file
View File

@ -0,0 +1,6 @@
{
"name": "tpre-python",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

BIN
server.db

Binary file not shown.

View File

@ -42,12 +42,17 @@ logger = logging.getLogger("uvicorn")
# 向中心服务器发送自己的IP地址,并获取自己的id
def send_ip():
url = server_address + "/get_node?ip=" + ip # type: ignore
url = f"http://{server_address}/server/get_node?ip={ip}" # 添加 http:// 协议
# ip = get_local_ip() # type: ignore
global id
id = requests.get(url, timeout=3)
logger.info(f"中心服务器返回节点ID为: {id}")
print("中心服务器返回节点ID为: ", id)
try:
response = requests.get(url, timeout=3)
response.raise_for_status() # 检查请求是否成功
data = response.json() # 将响应内容解析为 JSON 格式
global id
id = data.get("id") # 假设返回的 JSON 包含 id 字段
logger.info(f"中心服务器返回节点ID为: {id}")
except requests.exceptions.RequestException as e:
logger.error(f"请求中心服务器失败: {e}")
# 用环境变量获取本机ip
@ -85,7 +90,7 @@ def clear():
async def send_heartbeat_internal() -> None:
timeout = 30
global ip
url = server_address + "/heartbeat?ip=" + ip # type: ignore
url = f"http://{server_address}/server/heartbeat?ip={ip}" # 添加 http:// 协议
while True:
# print('successful send my_heart')
try:
@ -191,6 +196,6 @@ wallet_pk = "ae66ae3711a69079efd3d3e9b55f599ce7514eb29dfe4f9551404d3f361438c6"
if __name__ == "__main__":
import uvicorn
threading.Thread(target=log_message).start()
# threading.Thread(target=log_message).start()
uvicorn.run("node:app", host="0.0.0.0", port=8001, reload=True, log_level="debug")

View File

@ -1,12 +1,49 @@
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from fastapi.websockets import WebSocketState
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import sqlite3
import asyncio
import time
import ipaddress
import logging
import os
import queue
app = FastAPI()
origins = [
"http://localhost:3000",
]
# 配置 CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"], # 允许所有方法
allow_headers=["*"], # 允许所有头
)
# 配置日志文件路径
log_dir = "logs"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = os.path.join(log_dir, "server_logs.log")
# 全局日志配置
logging.basicConfig(
level=logging.INFO, # 设置全局日志级别
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", # 日志格式
handlers=[
logging.FileHandler(log_file, encoding="utf-8"), # 输出到日志文件
logging.StreamHandler(), # 输出到控制台
],
)
# 获取日志记录器
logger = logging.getLogger(__name__)
@ -17,7 +54,14 @@ async def lifespan(_: FastAPI):
clean_env()
# 获取当前文件所在的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 定义 frontend 的绝对路径
frontend_dir = os.path.join(current_dir, "..", "frontend")
app = FastAPI(lifespan=lifespan)
app.mount("/frontend", StaticFiles(directory="frontend/build"), name="frontend")
def init():
@ -61,9 +105,16 @@ async def show_nodes() -> list:
for row in rows:
nodes_list.append(row)
# TODO: use JSONResponse
logger.info("节点信息已成功获取")
return nodes_list
@app.get("/nodes", response_class=HTMLResponse)
async def get_nodes_page():
with open("frontend/public/index.html") as f:
return HTMLResponse(content=f.read(), status_code=200)
def validate_ip(ip: str) -> bool:
"""
Validate an IP address.
@ -85,7 +136,7 @@ def validate_ip(ip: str) -> bool:
@app.get("/server/get_node")
async def get_node(ip: str) -> int:
async def get_node(ip: str) -> JSONResponse:
"""
中心服务器与节点交互, 节点发送ip, 中心服务器接收ip存入数据库并将ip转换为int作为节点id返回给节点
params:
@ -102,13 +153,11 @@ async def get_node(ip: str) -> int:
for i in range(4):
ip_int += int(ip_parts[i]) << (24 - (8 * i))
# TODO: replace print with logger
print("IP", ip, "对应的ID为", ip_int)
logger.info(f"IP {ip} 对应的ID为 {ip_int}")
# 获取当前时间
current_time = int(time.time())
# TODO: replace print with logger
print("当前时间: ", current_time)
logger.info(f"当前时间: {current_time}")
with sqlite3.connect("server.db") as db:
# 插入数据
@ -118,8 +167,10 @@ async def get_node(ip: str) -> int:
)
db.commit()
# TODO: use JSONResponse
return ip_int
# 使用 JSONResponse 返回节点ID和当前时间
logger.info(f"节点 {ip} 已成功添加到数据库")
content = {"id": ip_int, "current_time": current_time}
return JSONResponse(content, status_code=200)
# TODO: try to use @app.delete("/node")
@ -132,6 +183,9 @@ async def delete_node(ip: str):
ip (str): The ip of the node to be deleted.
"""
if not validate_ip(ip):
logger.warning(f"收到无效 IP 格式的删除请求: {ip}")
raise HTTPException(status_code=400, detail="Invalid IP format")
with sqlite3.connect("server.db") as db:
# 查询要删除的节点
@ -143,11 +197,10 @@ async def delete_node(ip: str):
db.execute("DELETE FROM nodes WHERE ip=?", (ip,))
db.commit()
# TODO: replace print with logger
print(f"Node with IP {ip} deleted successfully.")
return {"message", f"Node with IP {ip} deleted successfully."}
logger.info(f"节点 {ip} 已成功删除")
return {"message": f"Node with IP {ip} deleted successfully."}
else:
print(f"Node with IP {ip} not found.")
logger.warning(f"节点 {ip} 未找到")
raise HTTPException(status_code=404, detail=f"Node with IP {ip} not found.")
@ -165,14 +218,15 @@ async def receive_heartbeat(ip: str):
"""
if not validate_ip(ip):
content = {"message": "invalid ip format"}
logger.warning(f"收到无效 IP 格式的心跳包: {ip}")
return JSONResponse(content, status_code=400)
print("收到来自", ip, "的心跳包")
logger.info("收到来自", ip, "的心跳包")
logger.info(f"收到来自 {ip} 的心跳包")
with sqlite3.connect("server.db") as db:
db.execute(
"UPDATE nodes SET last_heartbeat = ? WHERE ip = ?", (time.time(), ip)
)
logger.info(f"成功更新节点 {ip} 的心跳时间")
content = {"status": "received"}
return JSONResponse(content, status_code=200)
@ -210,9 +264,7 @@ async def send_nodes_list(count: int) -> list:
_, ip, _ = row
nodes_list.append(ip)
print("收到来自客户端的节点列表请求...")
print(nodes_list)
# TODO: use JSONResponse
logger.info(f"已成功发送 {count} 个节点信息")
return nodes_list
@ -220,6 +272,71 @@ def clear_database() -> None:
with sqlite3.connect("server.db") as db:
db.execute("DELETE FROM nodes")
db.commit()
logger.info("数据库已清空")
# WebSocket连接池
connected_clients = []
log_queue = queue.Queue() # 用于存储日志的队列
@app.websocket("/ws/logs")
async def websocket_logs(websocket: WebSocket):
await websocket.accept()
connected_clients.append(websocket) # 添加 WebSocket 客户端
try:
# 发送历史日志
while not log_queue.empty():
log_message = log_queue.get()
await websocket.send_json({"type": "log", "message": log_message})
# 实时日志发送
while True:
await asyncio.sleep(5) # 保证 WebSocket 持续连接
except Exception as e:
print(f"WebSocket connection closed with error: {e}")
finally:
if websocket in connected_clients:
connected_clients.remove(websocket)
await websocket.close()
class WebSocketLogHandler(logging.Handler):
def emit(self, record):
log_entry = self.format(record)
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(record.created))
log_message = f"{timestamp} - {log_entry}"
log_queue.put(log_message) # 将日志消息放入队列
for client in connected_clients:
if client.application_state == WebSocketState.CONNECTED:
# 改为异步线程安全地发送日志
asyncio.run_coroutine_threadsafe(
self.safe_send_log(client, log_message), asyncio.get_event_loop()
)
async def safe_send_log(self, client, log_message):
try:
await client.send_json({"type": "log", "message": log_message})
except RuntimeError as e:
print(f"Error while sending log to {client.application_state}: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
if client in connected_clients:
connected_clients.remove(client)
# 捕获 FastAPI 和 Uvicorn 的日志
uvicorn_logger = logging.getLogger("uvicorn")
uvicorn_logger.setLevel(logging.INFO)
# 捕获 FastAPI 的日志
fastapi_logger = logging.getLogger("fastapi")
fastapi_logger.setLevel(logging.INFO)
# 将日志输出到 WebSocket
uvicorn_logger.addHandler(WebSocketLogHandler())
fastapi_logger.addHandler(WebSocketLogHandler())
if __name__ == "__main__":