Merge remote-tracking branch 'refs/remotes/origin/fix-update'
This commit is contained in:
commit
835c908ca7
1
.gitignore
vendored
1
.gitignore
vendored
@ -17,3 +17,4 @@ src/tpre.cpython-311-x86_64-linux-gnu.so
|
||||
venv
|
||||
lib
|
||||
include
|
||||
/frontend/node_modules/
|
@ -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
|
@ -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
23
frontend/.gitignore
vendored
Normal 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
70
frontend/README.md
Normal 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
19780
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
39
frontend/package.json
Normal file
39
frontend/package.json
Normal 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
BIN
frontend/public/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.8 KiB |
13
frontend/public/index.html
Normal file
13
frontend/public/index.html
Normal 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>
|
25
frontend/public/manifest.json
Normal file
25
frontend/public/manifest.json
Normal 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"
|
||||
}
|
3
frontend/public/robots.txt
Normal file
3
frontend/public/robots.txt
Normal file
@ -0,0 +1,3 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
114
frontend/src/App.css
Normal file
114
frontend/src/App.css
Normal file
@ -0,0 +1,114 @@
|
||||
@keyframes glow-border {
|
||||
0% {
|
||||
box-shadow: inset 0 0 0 2px #00e6e6;
|
||||
}
|
||||
25% {
|
||||
box-shadow: inset 0 0 0 2px #00e6e6, 2px 0 0 0 #00e6e6;
|
||||
}
|
||||
50% {
|
||||
box-shadow: inset 0 0 0 2px #00e6e6, 2px 0 0 0 #00e6e6, 0 2px 0 0 #00e6e6;
|
||||
}
|
||||
75% {
|
||||
box-shadow: inset 0 0 0 2px #00e6e6, 2px 0 0 0 #00e6e6, 0 2px 0 0 #00e6e6, -2px 0 0 0 #00e6e6;
|
||||
}
|
||||
100% {
|
||||
box-shadow: inset 0 0 0 2px #00e6e6, 2px 0 0 0 #00e6e6, 0 2px 0 0 #00e6e6, -2px 0 0 0 #00e6e6, 0 -2px 0 0 #00e6e6;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: #1e1e1e;
|
||||
color: #ffffff;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
|
||||
.App-header {
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #eff4f0;
|
||||
font-size: 4em;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: #2196f3;
|
||||
font-size: 2em;
|
||||
margin-top: 20px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
color: #ff9800;
|
||||
font-size: 1.75em;
|
||||
margin-top: 15px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
h4 {
|
||||
color: #f44336;
|
||||
font-size: 1.5em;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
input, button {
|
||||
margin: 10px 0;
|
||||
padding: 10px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 80%;
|
||||
max-width: 300px;
|
||||
}
|
||||
|
||||
button {
|
||||
background-color: #2196f3;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: #1976d2;
|
||||
}
|
||||
|
||||
section {
|
||||
background-color: #333333;
|
||||
padding: 20px;
|
||||
margin: 20px 0;
|
||||
border-radius: 10px;
|
||||
animation: glow-border 4s infinite;
|
||||
}
|
||||
|
||||
.log-info {
|
||||
background-color: #444444;
|
||||
color: #ffffff;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
animation: glow-border 4s infinite;
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
li {
|
||||
background-color: #444444;
|
||||
margin: 5px 0;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.container {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.left-panel, .right-panel {
|
||||
width: 48%;
|
||||
}
|
118
frontend/src/App.js
Normal file
118
frontend/src/App.js
Normal file
@ -0,0 +1,118 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import WebSocketComponent from './WebSocketComponent';
|
||||
import './App.css';
|
||||
|
||||
function App() {
|
||||
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');
|
||||
setNodesList(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 className="glow">The server</h1>
|
||||
<div className="container">
|
||||
<div className="left-panel">
|
||||
<section>
|
||||
<h2 className="glow">get node</h2>
|
||||
<input
|
||||
type="text"
|
||||
value={ip}
|
||||
onChange={(e) => setIp(e.target.value)}
|
||||
placeholder="Enter node ip"
|
||||
/>
|
||||
<button onClick={handleFetchNode}>send</button>
|
||||
{node ? <p>{JSON.stringify(node)}</p> : <p>here is nothing!</p>}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 className="glow">heartbeat</h2>
|
||||
<button onClick={handleFetchHeartbeat}>Get heartbeat</button>
|
||||
{heartbeat ? <p>{JSON.stringify(heartbeat)}</p> : <p>here is nothing!</p>}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 className="glow">nodes list</h2>
|
||||
<input
|
||||
type="number"
|
||||
value={count}
|
||||
onChange={(e) => setCount(e.target.value)}
|
||||
placeholder="Enter the number of nodes"
|
||||
/>
|
||||
<button onClick={handleFetchNodesList}>Get node list</button>
|
||||
{nodesList.length > 0 ? (
|
||||
<ul>
|
||||
{nodesList.map((node, index) => (
|
||||
<li key={index}>{JSON.stringify(node)}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>here is nothing!</p>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
<div className="right-panel">
|
||||
<WebSocketComponent />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
66
frontend/src/WebSocketComponent.js
Normal file
66
frontend/src/WebSocketComponent.js
Normal file
@ -0,0 +1,66 @@
|
||||
import React, { useEffect, useState, useRef, useCallback } from 'react';
|
||||
|
||||
const WebSocketComponent = () => {
|
||||
const [logs, setLogs] = useState([]);
|
||||
const wsRef = 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 连接成功');
|
||||
};
|
||||
|
||||
wsRef.current.onmessage = (event) => {
|
||||
setLogs((prevLogs) => [...prevLogs, event.data]); // 直接加入收到的消息
|
||||
};
|
||||
|
||||
wsRef.current.onerror = (error) => {
|
||||
console.error('WebSocket 错误: ', error);
|
||||
};
|
||||
|
||||
wsRef.current.onclose = () => {
|
||||
console.log('WebSocket 连接关闭,尝试重新连接...');
|
||||
// 确保 WebSocket 连接在关闭后再进行重连
|
||||
setTimeout(() => {
|
||||
connectWebSocket();
|
||||
}, 5000); // 延迟 5 秒再重连
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
connectWebSocket();
|
||||
return () => {
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close();
|
||||
}
|
||||
};
|
||||
}, [connectWebSocket]);
|
||||
|
||||
useEffect(() => {
|
||||
const logContainer = document.querySelector('.log-info');
|
||||
if (logContainer) {
|
||||
logContainer.scrollTop = logContainer.scrollHeight;
|
||||
}
|
||||
}, [logs]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2>The logs</h2>
|
||||
<div
|
||||
className="log-info"
|
||||
style={{ height: '550px', overflowY: 'scroll', backgroundColor: 'rgb(32, 28, 28)', 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
11
frontend/src/index.css
Normal 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
13
frontend/src/index.js
Normal 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>
|
||||
);
|
10
frontend/src/setupProxy.js
Normal file
10
frontend/src/setupProxy.js
Normal 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,
|
||||
})
|
||||
);
|
||||
};
|
6
package-lock.json
generated
Normal file
6
package-lock.json
generated
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "tpre-python",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
19
src/node.py
19
src/node.py
@ -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")
|
||||
|
153
src/server.py
153
src/server.py
@ -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__":
|
||||
|
Loading…
x
Reference in New Issue
Block a user