Compare commits
30 Commits
061bd5d2bf
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| e70cfdd857 | |||
| 5397a2bb90 | |||
| edab4a3950 | |||
| 043da6cb70 | |||
| c64ccd57e3 | |||
| 835c908ca7 | |||
| fffa6728bc | |||
| 7fa5bb460c | |||
| bf6e25b722 | |||
| 24a5e91382 | |||
| 2308b01cee | |||
| 04d44afac0 | |||
| ff9a763cec | |||
| 0bb058df6e | |||
| 983ac91f74 | |||
| 81e34965e0 | |||
| 90a173dfa1 | |||
| f69eecf58b | |||
| bba12099cd | |||
| a9a4e28d9a | |||
| d071296126 | |||
| 2839dd5500 | |||
| cb76380242 | |||
| f5493ed8a1 | |||
| 0830a6733f | |||
| ea8f17920a | |||
| e79b24f909 | |||
| 15e35405f0 | |||
| b26bd92328 | |||
| 5b85db2427 |
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/
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM python:3.11
|
||||
FROM python:3.12-slim
|
||||
|
||||
COPY requirements.txt /app/
|
||||
|
||||
@@ -8,9 +8,12 @@ COPY requirements.txt /app/
|
||||
# 根据目标平台复制相应架构的库文件
|
||||
#COPY lib/${TARGETPLATFORM}/* /lib/
|
||||
|
||||
COPY lib/* /lib/
|
||||
COPY lib/* /usr/local/lib/
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
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
|
||||
|
||||
31
docker-compose.yml
Normal file
31
docker-compose.yml
Normal file
@@ -0,0 +1,31 @@
|
||||
version: "3"
|
||||
services:
|
||||
server:
|
||||
image: git.mamahaha.work/sangge/tpre:base
|
||||
volumes:
|
||||
- ./src:/app
|
||||
environment:
|
||||
- server_address=http://server:8000
|
||||
entrypoint:
|
||||
- python
|
||||
- server.py
|
||||
|
||||
node:
|
||||
image: git.mamahaha.work/sangge/tpre:base
|
||||
volumes:
|
||||
- ./src:/app
|
||||
environment:
|
||||
- server_address=http://server:8000
|
||||
entrypoint:
|
||||
- python
|
||||
- node.py
|
||||
|
||||
client:
|
||||
image: git.mamahaha.work/sangge/tpre:base
|
||||
volumes:
|
||||
- ./src:/app
|
||||
environment:
|
||||
- server_address=http://server:8000
|
||||
entrypoint:
|
||||
- python
|
||||
- client.py
|
||||
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)
|
||||
19822
frontend/package-lock.json
generated
Normal file
19822
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
40
frontend/package.json
Normal file
40
frontend/package.json
Normal file
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"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-router-dom": "^6.27.0",
|
||||
"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:
|
||||
135
frontend/src/App.css
Normal file
135
frontend/src/App.css
Normal file
@@ -0,0 +1,135 @@
|
||||
/* App.css */
|
||||
body {
|
||||
background-color: #f0f8ff; /* AliceBlue */
|
||||
color: #2f6c99; /* Navy */
|
||||
font-family: Arial, sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh; /* Minimum height set to 100% of the viewport height */
|
||||
}
|
||||
|
||||
.App {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh; /* Ensure the App component takes the full height */
|
||||
}
|
||||
|
||||
.App-header {
|
||||
background-color: #4abbe1; /*背景颜色*/
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.App-content {
|
||||
flex: 1; /* This makes the main content take up the remaining space */
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 40px 20px;
|
||||
background: linear-gradient(135deg, #e0f7fa, #80deea); /* 渐变背景颜色 */
|
||||
border-radius: 0px; /* 圆角边框 */
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
|
||||
}
|
||||
|
||||
.App-footer {
|
||||
background-color: #4abbe1; /*背景颜色*/
|
||||
padding: 10px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.glow {
|
||||
color: #ffffff; /* White */
|
||||
text-shadow: 0 0 10px #00bfff, 0 0 20px #00bfff, 0 0 30px #00bfff, 0 0 40px #00bfff, 0 0 50px #00bfff, 0 0 60px #00bfff, 0 0 70px #00bfff;
|
||||
font-size: 2.5em; /* 调整字体大小 */
|
||||
}
|
||||
|
||||
input, button {
|
||||
margin: 20px 10px;
|
||||
padding: 10px;
|
||||
border: 1px solid #000080; /* Navy */
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
font-size: 1.2em; /* 调整字体大小 */
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: #104e8b; /* DodgerBlue Darker */
|
||||
}
|
||||
|
||||
nav ul {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
margin: 20px 0; /* 增加上下间距 */
|
||||
}
|
||||
|
||||
nav li {
|
||||
display: inline;
|
||||
margin: 0 10px;
|
||||
}
|
||||
|
||||
nav a {
|
||||
color: #ffffff; /* White */
|
||||
text-decoration: none;
|
||||
font-size: 1.5em; /* 调整字体大小 */
|
||||
padding: 5px 19px;
|
||||
border-radius: 5px;
|
||||
background-color: #2db5c391; /* DodgerBlue */
|
||||
transition: background-color 0.3s, transform 0.3s;
|
||||
}
|
||||
|
||||
nav a:hover {
|
||||
text-decoration: underline;
|
||||
background-color: #104e8b; /* DodgerBlue Darker */
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.log-info {
|
||||
height: 200px;
|
||||
overflow-y: scroll;
|
||||
background-color: #ffffff; /* White */
|
||||
padding: 10px;
|
||||
border: 1px solid #b3d9ff; /* Light Blue Border */
|
||||
border-radius: 5px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.log-entry {
|
||||
margin: 5px 0;
|
||||
padding: 5px;
|
||||
border-bottom: 1px solid #b3d9ff; /* Light Blue Border */
|
||||
}
|
||||
|
||||
.log-entry:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.log-timestamp {
|
||||
color: #007acc; /* Blue */
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.log-message {
|
||||
color: #333333; /* Dark Gray */
|
||||
}
|
||||
|
||||
.node-info, .heartbeat-info, .nodes-list {
|
||||
margin-top: 20px;
|
||||
background-color: #e6f7ff; /* Light Blue */
|
||||
padding: 10px;
|
||||
border: 1px solid #b3d9ff; /* Light Blue Border */
|
||||
border-radius: 5px;
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.info-item {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
pre {
|
||||
white-space: pre-wrap; /* Wrap long lines */
|
||||
word-wrap: break-word; /* Break long words */
|
||||
}
|
||||
38
frontend/src/App.js
Normal file
38
frontend/src/App.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import React from 'react';
|
||||
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
|
||||
import HomePage from './HomePage';
|
||||
import NodePage from './NodePage';
|
||||
import HeartbeatPage from './HeartbeatPage';
|
||||
import NodesListPage from './NodesListPage';
|
||||
import WebSocketComponent from './WebSocketComponent';
|
||||
import './App.css';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Router>
|
||||
<div className="App">
|
||||
{/* Header 部分仅放置导航或标题 */}
|
||||
<header className="App-header">
|
||||
</header>
|
||||
|
||||
{/* Main 部分用来渲染路由的内容 */}
|
||||
<main className="App-content">
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/node" element={<NodePage />} />
|
||||
<Route path="/heartbeat" element={<HeartbeatPage />} />
|
||||
<Route path="/nodes-list" element={<NodesListPage />} />
|
||||
<Route path="/logs" element={<WebSocketComponent />} />
|
||||
</Routes>
|
||||
</main>
|
||||
|
||||
{/* Footer 部分 */}
|
||||
<footer className="App-footer">
|
||||
<p>© 2024 Server Application</p>
|
||||
</footer>
|
||||
</div>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
55
frontend/src/HeartbeatPage.js
Normal file
55
frontend/src/HeartbeatPage.js
Normal file
@@ -0,0 +1,55 @@
|
||||
import React, { useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import { Link } from 'react-router-dom';
|
||||
import './App.css';
|
||||
|
||||
const HeartbeatPage = () => {
|
||||
const [ip, setIp] = useState('');
|
||||
const [heartbeat, setHeartbeat] = useState(null);
|
||||
|
||||
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 handleFetchHeartbeat = () => {
|
||||
fetchHeartbeat(ip);
|
||||
};
|
||||
|
||||
return (
|
||||
<section>
|
||||
<nav>
|
||||
<ul>
|
||||
<li><Link to="/">Home</Link></li>
|
||||
<li><Link to="/node">Get Node</Link></li>
|
||||
<li><Link to="/heartbeat">Heartbeat</Link></li>
|
||||
<li><Link to="/nodes-list">Nodes List</Link></li>
|
||||
<li><Link to="/logs">Logs</Link></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<h2 className="glow">Heartbeat</h2>
|
||||
<p>请输入节点 IP 地址以获取心跳状态信息:</p>
|
||||
<input
|
||||
type="text"
|
||||
value={ip}
|
||||
onChange={(e) => setIp(e.target.value)}
|
||||
placeholder="Enter node IP"
|
||||
/>
|
||||
<button onClick={handleFetchHeartbeat}>Get Heartbeat</button>
|
||||
{heartbeat ? (
|
||||
<div className="heartbeat-info">
|
||||
<h3>Heartbeat Information:</h3>
|
||||
<div className="info-item"><strong>Status:</strong> {heartbeat.status}</div>
|
||||
</div>
|
||||
) : (
|
||||
<p>这里没有任何信息!</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default HeartbeatPage;
|
||||
21
frontend/src/HomePage.js
Normal file
21
frontend/src/HomePage.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import './App.css';
|
||||
const HomePage = () => {
|
||||
return (
|
||||
<div>
|
||||
<h1 className="glow">The server</h1>
|
||||
<p>欢迎来到服务器管理页面。请选择一个操作:</p>
|
||||
<nav>
|
||||
<ul>
|
||||
<li><Link to="/node">Get Node</Link></li>
|
||||
<li><Link to="/heartbeat">Heartbeat</Link></li>
|
||||
<li><Link to="/nodes-list">Nodes List</Link></li>
|
||||
<li><Link to="/logs">Logs</Link></li>
|
||||
</ul>
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default HomePage;
|
||||
59
frontend/src/NodePage.js
Normal file
59
frontend/src/NodePage.js
Normal file
@@ -0,0 +1,59 @@
|
||||
import React, { useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import { Link } from 'react-router-dom';
|
||||
import './App.css';
|
||||
|
||||
const NodePage = () => {
|
||||
const [ip, setIp] = useState('');
|
||||
const [node, setNode] = useState(null);
|
||||
|
||||
const fetchNode = async (ip) => {
|
||||
try {
|
||||
const response = await axios.get('/server/get_node', { params: { ip } });
|
||||
const nodeData = response.data;
|
||||
const date = new Date(nodeData.current_time * 1000);
|
||||
nodeData.current_time = date.toLocaleString();
|
||||
setNode(nodeData);
|
||||
} catch (error) {
|
||||
console.error('Error fetching node:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFetchNode = () => {
|
||||
fetchNode(ip);
|
||||
};
|
||||
|
||||
return (
|
||||
<section>
|
||||
<nav>
|
||||
<ul>
|
||||
<li><Link to="/">Home</Link></li>
|
||||
<li><Link to="/node">Get Node</Link></li>
|
||||
<li><Link to="/heartbeat">Heartbeat</Link></li>
|
||||
<li><Link to="/nodes-list">Nodes List</Link></li>
|
||||
<li><Link to="/logs">Logs</Link></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<h2 className="glow">Get Node</h2>
|
||||
<p>请输入节点 IP 地址以获取节点信息:</p>
|
||||
<input
|
||||
type="text"
|
||||
value={ip}
|
||||
onChange={(e) => setIp(e.target.value)}
|
||||
placeholder="Enter node IP"
|
||||
/>
|
||||
<button onClick={handleFetchNode}>Send</button>
|
||||
{node ? (
|
||||
<div className="node-info">
|
||||
<h3>Node Information:</h3>
|
||||
<div className="info-item"><strong>ID:</strong> {node.id}</div>
|
||||
<div className="info-item"><strong>Current Time:</strong> {node.current_time}</div>
|
||||
</div>
|
||||
) : (
|
||||
<p>这里没有任何信息!</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default NodePage;
|
||||
61
frontend/src/NodesListPage.js
Normal file
61
frontend/src/NodesListPage.js
Normal file
@@ -0,0 +1,61 @@
|
||||
import React, { useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import { Link } from 'react-router-dom';
|
||||
import './App.css';
|
||||
|
||||
const NodesListPage = () => {
|
||||
const [count, setCount] = useState('');
|
||||
const [nodesList, setNodesList] = useState([]);
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFetchNodesList = () => {
|
||||
fetchNodesList(count);
|
||||
};
|
||||
|
||||
return (
|
||||
<section>
|
||||
<nav>
|
||||
<ul>
|
||||
<li><Link to="/">Home</Link></li>
|
||||
<li><Link to="/node">Get Node</Link></li>
|
||||
<li><Link to="/heartbeat">Heartbeat</Link></li>
|
||||
<li><Link to="/nodes-list">Nodes List</Link></li>
|
||||
<li><Link to="/logs">Logs</Link></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<h2 className="glow">Nodes List</h2>
|
||||
<p>请输入要获取的节点数量:</p>
|
||||
<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 ? (
|
||||
<div className="nodes-list">
|
||||
<h3>Nodes Information:</h3>
|
||||
<ul>
|
||||
{nodesList.map((node, index) => (
|
||||
<li key={index} className="info-item">
|
||||
{node}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : (
|
||||
<p>这里没有任何信息!</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default NodesListPage;
|
||||
71
frontend/src/WebSocketComponent.js
Normal file
71
frontend/src/WebSocketComponent.js
Normal file
@@ -0,0 +1,71 @@
|
||||
import React, { useEffect, useState, useRef, useCallback } from 'react';
|
||||
import './App.css'; // 确保引入了样式文件
|
||||
|
||||
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, JSON.parse(event.data)]); // 解析 JSON 数据
|
||||
};
|
||||
|
||||
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 className="glow">The logs</h2>
|
||||
<p>这里显示服务器的日志信息:</p>
|
||||
<div className="log-info">
|
||||
{logs.map((log, index) => {
|
||||
const [timestamp, message] = log.message.split(' - ', 2);
|
||||
return (
|
||||
<div key={index} className="log-entry">
|
||||
<span className="log-timestamp">{timestamp}</span>
|
||||
<span className="log-message"> - {message}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default WebSocketComponent;
|
||||
18
frontend/src/index.css
Normal file
18
frontend/src/index.css
Normal file
@@ -0,0 +1,18 @@
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%; /* Ensures the body takes the full height */
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
#root {
|
||||
height: 100%; /* Makes sure the root element takes the full height of the viewport */
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
|
||||
}
|
||||
11
frontend/src/index.js
Normal file
11
frontend/src/index.js
Normal file
@@ -0,0 +1,11 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
document.getElementById('root')
|
||||
);
|
||||
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,
|
||||
})
|
||||
);
|
||||
};
|
||||
5
install_gmssl.sh
Normal file → Executable file
5
install_gmssl.sh
Normal file → Executable file
@@ -8,4 +8,9 @@ cp -r gmssl/include include
|
||||
mkdir gmssl/build
|
||||
cd gmssl/build || exit
|
||||
cmake ..
|
||||
make
|
||||
cd bin || exit
|
||||
cp libgmssl.so libgmssl.so.3 libgmssl.so.3.1 ../../../lib
|
||||
cp libsdf_dummy.so libsdf_dummy.so.3 libsdf_dummy.so.3.1 ../../../lib
|
||||
cp libskf_dummy.so libskf_dummy.so.3 libskf_dummy.so.3.1 ../../../lib
|
||||
sudo make install
|
||||
|
||||
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": {}
|
||||
}
|
||||
@@ -2,3 +2,4 @@ gmssl-python>=2.2.2,<3.0.0
|
||||
fastapi
|
||||
uvicorn
|
||||
requests
|
||||
web3
|
||||
@@ -89,13 +89,8 @@ def init_db():
|
||||
|
||||
# load config from config file
|
||||
def init_config():
|
||||
import configparser
|
||||
|
||||
global server_address
|
||||
config = configparser.ConfigParser()
|
||||
config.read("client.ini")
|
||||
|
||||
server_address = config["settings"]["server_address"]
|
||||
server_address = os.environ.get("server_address")
|
||||
|
||||
|
||||
# execute on exit
|
||||
@@ -469,7 +464,7 @@ async def recieve_pk(pk: pk_model):
|
||||
|
||||
pk = (0, 0)
|
||||
sk = 0
|
||||
server_address = str
|
||||
server_address = os.environ.get("server_address")
|
||||
node_response = False
|
||||
message = bytes
|
||||
local_ip = get_own_ip()
|
||||
|
||||
30
src/node.py
30
src/node.py
@@ -25,7 +25,7 @@ async def lifespan(_: FastAPI):
|
||||
message_list = []
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
server_address = "http://60.204.236.38:8000/server"
|
||||
server_address = os.environ.get("server_address")
|
||||
id = 0
|
||||
ip = ""
|
||||
client_ip_src = "" # 发送信息用户的ip
|
||||
@@ -42,17 +42,21 @@ 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
|
||||
def get_local_ip():
|
||||
global ip
|
||||
def get_local_ip() -> str | None:
|
||||
ip = os.environ.get("HOST_IP")
|
||||
if not ip: # 如果环境变量中没有IP
|
||||
try:
|
||||
@@ -61,12 +65,16 @@ def get_local_ip():
|
||||
s.connect(("8.8.8.8", 80)) # 通过连接Google DNS获取IP
|
||||
ip = str(s.getsockname()[0])
|
||||
s.close()
|
||||
return ip
|
||||
except IndexError:
|
||||
raise ValueError("Unable to get IP")
|
||||
else:
|
||||
return ip
|
||||
|
||||
|
||||
def init():
|
||||
get_local_ip()
|
||||
global ip
|
||||
ip = get_local_ip()
|
||||
send_ip()
|
||||
asyncio.create_task(send_heartbeat_internal())
|
||||
print("Finish init")
|
||||
@@ -82,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:
|
||||
@@ -188,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")
|
||||
|
||||
154
src/server.py
154
src/server.py
@@ -1,12 +1,50 @@
|
||||
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 = os.path.expanduser("~/tpre-python-logs")
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
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 +55,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","build")
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.mount("/frontend", StaticFiles(directory=frontend_dir), name="frontend")
|
||||
|
||||
|
||||
def init():
|
||||
@@ -61,9 +106,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 +137,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 +154,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 +168,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 +184,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 +198,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 +219,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 +265,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 +273,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__":
|
||||
|
||||
@@ -9,7 +9,6 @@ import httpx
|
||||
import respx
|
||||
from fastapi.testclient import TestClient
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../src")))
|
||||
from node import (
|
||||
@@ -21,7 +20,6 @@ from node import (
|
||||
init,
|
||||
clear,
|
||||
send_user_des_message,
|
||||
ip,
|
||||
id,
|
||||
)
|
||||
|
||||
@@ -34,26 +32,23 @@ server_address = "http://60.204.236.38:8000/server"
|
||||
|
||||
class TestGetLocalIP(unittest.TestCase):
|
||||
|
||||
os.environ["HOST_IP"] = "60.204.193.58" # 模拟设置 HOST_IP 环境变量
|
||||
|
||||
def test_get_ip_from_env(self):
|
||||
global ip
|
||||
# 调用被测函数
|
||||
get_local_ip()
|
||||
os.environ["HOST_IP"] = "60.204.193.58" # 模拟设置 HOST_IP 环境变量
|
||||
ip = get_local_ip()
|
||||
# 检查函数是否正确获取到 HOST_IP
|
||||
self.assertEqual(ip, "60.204.193.58")
|
||||
|
||||
@patch("socket.socket") # Mock socket 连接行为
|
||||
@patch.dict("os.environ", {}) # 模拟没有 HOST_IP 环境变量
|
||||
def test_get_ip_from_socket(self, mock_socket):
|
||||
global ip
|
||||
os.environ.pop("HOST_IP", None)
|
||||
|
||||
# 模拟 socket 返回的 IP 地址
|
||||
mock_socket_instance = MagicMock()
|
||||
mock_socket.return_value = mock_socket_instance
|
||||
mock_socket_instance.getsockname.return_value = ("110.41.155.96", 0)
|
||||
|
||||
# 调用被测函数
|
||||
get_local_ip()
|
||||
ip = get_local_ip()
|
||||
|
||||
# 确认 socket 被调用过
|
||||
mock_socket_instance.connect.assert_called_with(("8.8.8.8", 80))
|
||||
|
||||
Reference in New Issue
Block a user