├── config_files
├── paths.yaml
├── config.yaml
└── models.yaml
├── tests
├── __init__.py
├── test_about.py
├── README.md
├── conftest.py
└── test_config_manager.py
├── assets
├── nh-00.gif
├── nh-01.gif
├── nh-10.gif
├── icon-dark.png
├── logo-bright.png
└── logo-dark.png
├── docs
├── assets
│ └── images
│ │ ├── models.png
│ │ ├── hardware.png
│ │ ├── overview.gif
│ │ ├── overview.png
│ │ ├── simulation.png
│ │ ├── add-new-path.png
│ │ ├── nethang-login.png
│ │ ├── traffic-charts.gif
│ │ ├── custom-settings.png
│ │ ├── logo-dark-trans.png
│ │ ├── nethang-starting.gif
│ │ ├── logo-bright-trans.png
│ │ └── nethang-dashboard.png
└── index.html
├── nethang
├── static
│ └── images
│ │ ├── favicon.png
│ │ ├── icon-bright.png
│ │ ├── icon-dark.png
│ │ ├── logo-bright.png
│ │ ├── logo-dark.png
│ │ ├── icon-dark-trans.png
│ │ ├── logo-dark-trans.png
│ │ ├── icon-bright-trans.png
│ │ └── logo-bright-trans.png
├── extensions.py
├── proc_lock.py
├── version.py
├── __init__.py
├── templates
│ ├── login.html
│ ├── base.html
│ ├── about.html
│ └── config.html
├── id_manager.py
├── routes.py
├── traffic_monitor.py
├── config_manager.py
└── simu_path.py
├── requirements-test.txt
├── run.py
├── pytest.ini
├── MANIFEST.in
├── .github
└── workflows
│ └── tests.yml
├── LICENSE
├── pyproject.toml
├── .gitignore
└── README.md
/config_files/paths.yaml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | # Tests package for NetHang
--------------------------------------------------------------------------------
/config_files/config.yaml:
--------------------------------------------------------------------------------
1 | lan_interface:
2 | wan_interface:
3 |
--------------------------------------------------------------------------------
/assets/nh-00.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/assets/nh-00.gif
--------------------------------------------------------------------------------
/assets/nh-01.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/assets/nh-01.gif
--------------------------------------------------------------------------------
/assets/nh-10.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/assets/nh-10.gif
--------------------------------------------------------------------------------
/assets/icon-dark.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/assets/icon-dark.png
--------------------------------------------------------------------------------
/assets/logo-bright.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/assets/logo-bright.png
--------------------------------------------------------------------------------
/assets/logo-dark.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/assets/logo-dark.png
--------------------------------------------------------------------------------
/docs/assets/images/models.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/models.png
--------------------------------------------------------------------------------
/docs/assets/images/hardware.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/hardware.png
--------------------------------------------------------------------------------
/docs/assets/images/overview.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/overview.gif
--------------------------------------------------------------------------------
/docs/assets/images/overview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/overview.png
--------------------------------------------------------------------------------
/docs/assets/images/simulation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/simulation.png
--------------------------------------------------------------------------------
/nethang/static/images/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/nethang/static/images/favicon.png
--------------------------------------------------------------------------------
/docs/assets/images/add-new-path.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/add-new-path.png
--------------------------------------------------------------------------------
/docs/assets/images/nethang-login.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/nethang-login.png
--------------------------------------------------------------------------------
/docs/assets/images/traffic-charts.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/traffic-charts.gif
--------------------------------------------------------------------------------
/nethang/static/images/icon-bright.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/nethang/static/images/icon-bright.png
--------------------------------------------------------------------------------
/nethang/static/images/icon-dark.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/nethang/static/images/icon-dark.png
--------------------------------------------------------------------------------
/nethang/static/images/logo-bright.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/nethang/static/images/logo-bright.png
--------------------------------------------------------------------------------
/nethang/static/images/logo-dark.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/nethang/static/images/logo-dark.png
--------------------------------------------------------------------------------
/docs/assets/images/custom-settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/custom-settings.png
--------------------------------------------------------------------------------
/docs/assets/images/logo-dark-trans.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/logo-dark-trans.png
--------------------------------------------------------------------------------
/docs/assets/images/nethang-starting.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/nethang-starting.gif
--------------------------------------------------------------------------------
/docs/assets/images/logo-bright-trans.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/logo-bright-trans.png
--------------------------------------------------------------------------------
/docs/assets/images/nethang-dashboard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/docs/assets/images/nethang-dashboard.png
--------------------------------------------------------------------------------
/nethang/static/images/icon-dark-trans.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/nethang/static/images/icon-dark-trans.png
--------------------------------------------------------------------------------
/nethang/static/images/logo-dark-trans.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/nethang/static/images/logo-dark-trans.png
--------------------------------------------------------------------------------
/nethang/static/images/icon-bright-trans.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/nethang/static/images/icon-bright-trans.png
--------------------------------------------------------------------------------
/nethang/static/images/logo-bright-trans.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stephenyin/NetHang/HEAD/nethang/static/images/logo-bright-trans.png
--------------------------------------------------------------------------------
/requirements-test.txt:
--------------------------------------------------------------------------------
1 | pytest>=7.0.0
2 | pytest-cov>=4.0.0
3 | pytest-mock>=3.10.0
4 | pytest-xdist>=3.0.0
5 | requests>=2.28.0
6 | PyYAML>=6.0
--------------------------------------------------------------------------------
/nethang/extensions.py:
--------------------------------------------------------------------------------
1 | """
2 | Extensions
3 |
4 | This module provides extensions for the Flask application.
5 |
6 | Author: Hang Yin
7 | Date: 2025-05-19
8 | """
9 |
10 | from flask_socketio import SocketIO
11 |
12 | socketio = SocketIO() # Initialize without app
--------------------------------------------------------------------------------
/run.py:
--------------------------------------------------------------------------------
1 | """
2 | Run
3 |
4 | This module provides a mechanism for running the application.
5 |
6 | Author: Hang Yin
7 | Date: 2025-05-19
8 | """
9 |
10 | from nethang import app
11 |
12 | def main():
13 | app.run(host='0.0.0.0', port=9527, debug=False)
14 |
15 | if __name__ == '__main__':
16 | main()
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [tool:pytest]
2 | testpaths = tests
3 | python_files = test_*.py
4 | python_classes = Test*
5 | python_functions = test_*
6 | addopts =
7 | -v
8 | --tb=short
9 | --strict-markers
10 | --disable-warnings
11 | markers =
12 | unit: Unit tests
13 | integration: Integration tests
14 | slow: Slow running tests
15 | network: Tests that require network access
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | # Include README and LICENSE
2 | include README.md
3 | include LICENSE
4 |
5 | # Include requirements
6 | include requirements.txt
7 |
8 | # Include Python package files
9 | include run.py
10 | recursive-include nethang *.py
11 | recursive-include nethang/static *
12 | recursive-include nethang/templates *
13 |
14 | # Include configuration files
15 | recursive-include config_files *
16 |
17 | # Include test files
18 | recursive-include tests *.py
19 |
20 | # Exclude cache files
21 | global-exclude __pycache__
22 | global-exclude *.py[cod]
23 | global-exclude *$py.class
24 |
25 | # Exclude development files
26 | exclude .git
27 | exclude .gitignore
28 | exclude .env
29 | exclude *.log
30 |
--------------------------------------------------------------------------------
/.github/workflows/tests.yml:
--------------------------------------------------------------------------------
1 | name: Python Tests
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | jobs:
10 | test:
11 | runs-on: ubuntu-latest
12 | strategy:
13 | matrix:
14 | python-version: [3.8, 3.9, "3.10"]
15 |
16 | steps:
17 | - uses: actions/checkout@v3
18 |
19 | - name: Set up Python ${{ matrix.python-version }}
20 | uses: actions/setup-python@v4
21 | with:
22 | python-version: ${{ matrix.python-version }}
23 |
24 | - name: Create config directory
25 | run: |
26 | mkdir -p ~/.nethang
27 | touch ~/.nethang/models.yaml
28 | echo "version: '1.0.0'" > ~/.nethang/models.yaml
29 |
30 | - name: Install dependencies
31 | run: |
32 | python -m pip install --upgrade pip
33 | pip install -e ".[dev]"
34 |
35 | - name: Run tests
36 | run: |
37 | pytest tests/ --cov=nethang
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2025 Hang Yin
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/nethang/proc_lock.py:
--------------------------------------------------------------------------------
1 | """
2 | Process Lock
3 |
4 | This module provides a process lock mechanism using file locking.
5 | It allows multiple processes to coordinate access to a shared resource
6 | by locking a file.
7 |
8 | The lock is acquired by calling the `acquire` method, and released by
9 | calling the `release` method.
10 |
11 | The lock is automatically released when the `ProcLock` object is deleted.
12 |
13 | The lock is also automatically released when the `ProcLock` object is used
14 | in a with statement.
15 |
16 | Author: Hang Yin
17 | Date: 2025-05-19
18 | """
19 |
20 | import fcntl
21 |
22 | class ProcLock:
23 | def __init__(self, filename):
24 | self.filename = filename
25 | self.handle = open(filename, 'wb')
26 |
27 | def acquire(self):
28 | """Acquire file lock"""
29 | fcntl.flock(self.handle.fileno(), fcntl.LOCK_EX)
30 |
31 | def release(self):
32 | """Release file lock"""
33 | fcntl.flock(self.handle.fileno(), fcntl.LOCK_UN)
34 |
35 | def __del__(self):
36 | self.handle.close()
37 |
38 | def __enter__(self):
39 | self.acquire()
40 | return self
41 |
42 | def __exit__(self, exc_type, exc_value, traceback):
43 | self.release()
44 |
--------------------------------------------------------------------------------
/nethang/version.py:
--------------------------------------------------------------------------------
1 | """
2 | nethang/version.py
3 |
4 | This module provides a mechanism for getting the version of the application.
5 |
6 | Author: Hang Yin
7 | Date: 2025-06-11
8 | """
9 |
10 | try:
11 | from importlib.metadata import version, PackageNotFoundError
12 | except ImportError:
13 | # Python < 3.8 的兼容性
14 | from importlib_metadata import version, PackageNotFoundError
15 |
16 | def get_version():
17 | """Get the version of the application"""
18 | try:
19 | return version('nethang')
20 | except PackageNotFoundError:
21 | # In development environment, the package may not be installed
22 | return "dev"
23 |
24 | def get_package_info():
25 | """Get the complete package information"""
26 | try:
27 | from importlib.metadata import metadata
28 | meta = metadata('nethang')
29 | return {
30 | 'name': meta['Name'],
31 | 'version': meta['Version'],
32 | 'summary': meta.get('Summary', ''),
33 | 'author': meta.get('Author', ''),
34 | 'homepage': meta.get('Home-page', ''),
35 | }
36 | except (PackageNotFoundError, ImportError):
37 | return {
38 | 'name': 'nethang',
39 | 'version': 'dev',
40 | 'summary': 'Development version',
41 | 'author': 'Unknown',
42 | 'homepage': '',
43 | }
44 |
45 | # Export the version information
46 | __version__ = get_version()
--------------------------------------------------------------------------------
/nethang/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | NetHang
3 |
4 | This is a Flask application for managing network quality simulation.
5 |
6 | Author: Hang Yin
7 | Date: 2025-05-19
8 | """
9 |
10 | import os
11 | import logging
12 | from flask import Flask
13 | from logging.handlers import RotatingFileHandler
14 |
15 | # Admin username
16 | ADMIN_USERNAME = 'admin'
17 |
18 | # Lock files
19 | IPT_LOCK_FILE : str = '/tmp/nethang_iptables_modi.lock'
20 | ID_LOCK_FILE : str = '/tmp/nethang_id.lock'
21 |
22 | # Config files
23 | CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.nethang')
24 | CONFIG_FILE = os.path.join(CONFIG_PATH, 'config.yaml')
25 | MODELS_FILE = os.path.join(CONFIG_PATH, 'models.yaml')
26 | PATHS_FILE = os.path.join(CONFIG_PATH, 'paths.yaml')
27 |
28 | # Log file
29 | LOG_FILE = os.path.join(CONFIG_PATH, 'nethang.log')
30 |
31 | # Create config directory if it doesn't exist
32 | os.makedirs(CONFIG_PATH, exist_ok=True)
33 |
34 | # Create Flask app
35 | app = Flask(__name__)
36 |
37 | # Configure logging
38 | try:
39 | file_handler = RotatingFileHandler(LOG_FILE, maxBytes=10000000, backupCount=5)
40 | file_handler.setFormatter(logging.Formatter(
41 | '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
42 | ))
43 | file_handler.setLevel(logging.INFO)
44 | app.logger.addHandler(file_handler)
45 | except (IOError, PermissionError) as e:
46 | # If we can't create the log file, just log to stderr
47 | app.logger.warning(f"Could not create log file: {e}")
48 | app.logger.warning("Logging to stderr instead")
49 |
50 | app.logger.setLevel(logging.INFO)
51 | app.logger.info('NetHang startup')
52 |
53 | # Import routes after app creation to avoid circular imports
54 | from . import routes
--------------------------------------------------------------------------------
/nethang/templates/login.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 |
3 | {% block title %}NetHang - Login{% endblock %}
4 |
5 | {% block content %}
6 |
7 |
8 |
9 |
10 |
11 |
12 |
14 |
15 |
16 |
17 | {% if error %}
18 |
19 | {{ error }}
20 |
21 |
22 | {% endif %}
23 |
24 |
35 |
36 |
37 |
38 |
39 | {% endblock %}
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=42", "wheel"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "nethang"
7 | version = "0.1.7"
8 | description = "A web-based tool for simulating network quality"
9 | readme = "README.md"
10 | authors = [
11 | {name = "Hang Yin", email = "stephen.yin.h@gmail.com"}
12 | ]
13 | license = {text = "MIT"}
14 | requires-python = ">=3.8"
15 | classifiers = [
16 | "Development Status :: 3 - Alpha",
17 | "Intended Audience :: Developers",
18 | "Programming Language :: Python :: 3",
19 | "Programming Language :: Python :: 3.8",
20 | "Programming Language :: Python :: 3.9",
21 | "Programming Language :: Python :: 3.10",
22 | "Programming Language :: Python :: 3.11",
23 | "Operating System :: POSIX :: Linux",
24 | ]
25 | dependencies = [
26 | "Flask>=2.0.0",
27 | "flask-socketio>=5.0.0",
28 | "python-dotenv>=0.10.0",
29 | "Werkzeug>=3.0.0",
30 | "pyyaml>=5.0.0",
31 | "netifaces>=0.10.0",
32 | "tomli>=2.0.0",
33 | "requests>=2.0.0",
34 | ]
35 |
36 | [project.scripts]
37 | nethang = "run:main"
38 |
39 | [project.optional-dependencies]
40 | dev = [
41 | "pytest>=7.0.0",
42 | "pytest-cov>=4.0.0",
43 | "mypy>=1.0.0",
44 | "types-PyYAML>=6.0.0",
45 | "black>=22.0.0",
46 | "flake8>=4.0.0",
47 | "isort>=5.0.0",
48 | ]
49 |
50 | [project.urls]
51 | Homepage = "https://stephenyin.github.io/NetHang/"
52 | Repository = "https://github.com/stephenyin/NetHang.git"
53 |
54 | [tool.setuptools]
55 | packages = ["nethang"]
56 | package-dir = {"" = "."}
57 | py-modules = ["run"]
58 | include-package-data = true
59 |
60 | [tool.setuptools.package-data]
61 | nethang = ["templates/*", "static/*", "static/**/*"]
62 |
63 | [tool.black]
64 | line-length = 88
65 | target-version = ["py38"]
66 | include = '\.pyi?$'
67 |
68 | [tool.isort]
69 | profile = "black"
70 | multi_line_output = 3
71 | line_length = 88
72 |
73 | [tool.mypy]
74 | python_version = "3.8"
75 | warn_return_any = true
76 | warn_unused_configs = true
77 | disallow_untyped_defs = true
78 | check_untyped_defs = true
79 |
80 | [tool.pytest.ini_options]
81 | testpaths = ["tests"]
82 | python_files = ["test_*.py"]
83 | addopts = "--cov=nethang --cov-report=term-missing"
--------------------------------------------------------------------------------
/tests/test_about.py:
--------------------------------------------------------------------------------
1 | import os
2 | import yaml
3 | import pytest
4 | from nethang import app
5 |
6 | @pytest.fixture
7 | def client():
8 | """Create a test client for the app."""
9 | app.config['TESTING'] = True
10 | with app.test_client() as client:
11 | # Create a test session
12 | with client.session_transaction() as session:
13 | session['logged_in'] = True
14 | yield client
15 |
16 | @pytest.fixture
17 | def mock_models_yaml(tmp_path):
18 | """Create a temporary models.yaml file for testing."""
19 | models_dir = tmp_path / ".nethang"
20 | models_dir.mkdir()
21 | models_file = models_dir / "models.yaml"
22 |
23 | # Create test models.yaml content
24 | models_content = {
25 | 'version': '1.0.0',
26 | 'models': [
27 | {'name': 'test_model', 'description': 'Test model'}
28 | ]
29 | }
30 |
31 | with open(models_file, 'w') as f:
32 | yaml.dump(models_content, f)
33 |
34 | # Store original HOME and set it to tmp_path
35 | original_home = os.environ.get('HOME')
36 | os.environ['HOME'] = str(tmp_path)
37 |
38 | yield models_file
39 |
40 | # Restore original HOME
41 | if original_home:
42 | os.environ['HOME'] = original_home
43 | else:
44 | del os.environ['HOME']
45 |
46 | def test_about_page_requires_login(client):
47 | """Test that about page requires login."""
48 | # Clear session
49 | with client.session_transaction() as session:
50 | session.clear()
51 |
52 | response = client.get('/about')
53 | assert response.status_code == 302 # Redirect to login
54 | assert '/login' in response.location
55 |
56 | def test_about_page_loads(client):
57 | """Test that about page loads successfully."""
58 | response = client.get('/about')
59 | assert response.status_code == 200
60 | assert b'About NetHang' in response.data
61 |
62 | def test_about_page_contains_links(client):
63 | """Test that about page contains all required links."""
64 | response = client.get('/about')
65 | assert b'github.com/stephenyin/NetHang' in response.data
66 | assert b'linkedin.com/in/hang-yin-stephen' in response.data
67 | assert b'mailto:stephen.yin.h@gmail.com' in response.data
--------------------------------------------------------------------------------
/nethang/id_manager.py:
--------------------------------------------------------------------------------
1 | """
2 | ID Manager
3 |
4 | This module provides a mechanism for managing unique IDs across processes
5 | using file locking.
6 |
7 | Author: Hang Yin
8 | Date: 2025-05-19
9 | """
10 |
11 | import os
12 | import yaml
13 | from typing import Optional
14 |
15 | class IDManager:
16 | """Manage unique IDs across processes using file locking"""
17 | _instance = None
18 |
19 | def __new__(cls, *args, **kwargs):
20 | if cls._instance is None:
21 | cls._instance = super().__new__(cls)
22 | return cls._instance
23 |
24 | def __init__(self,
25 | paths_file: str,
26 | id_range: tuple):
27 | self.paths_file = paths_file
28 | self.id_range = id_range
29 | self.current_id = None
30 | self._init_files()
31 |
32 | def _init_files(self):
33 | """Initialize lock file if it doesn't exist"""
34 |
35 | # Ensure the directory for paths.yaml exists
36 | os.makedirs(os.path.dirname(self.paths_file), exist_ok=True)
37 |
38 | def _read_paths(self) -> dict:
39 | """Read current paths from paths.yaml"""
40 | if os.path.exists(self.paths_file):
41 | try:
42 | with open(self.paths_file, 'r') as f:
43 | return yaml.safe_load(f) or[]
44 | except (yaml.YAMLError, IOError):
45 | return[]
46 | return[]
47 |
48 | def _get_used_ids(self) -> set:
49 | """Get the set of IDs currently in use from paths.yaml"""
50 | paths_data = self._read_paths()
51 | used_ids = set()
52 |
53 | for path in paths_data:
54 | if 'id' in path:
55 | used_ids.add(path['id'])
56 |
57 | return used_ids
58 |
59 | def acquire_id(self) -> Optional[int]:
60 | """Acquire a unique ID for the current process"""
61 | # Get currently used IDs from paths.yaml
62 | used_ids = self._get_used_ids()
63 |
64 | # Find first available ID in the range
65 | for potential_id in range(self.id_range[0], self.id_range[1] + 1):
66 | if potential_id not in used_ids:
67 | self.current_id = potential_id
68 | return potential_id
69 |
70 | return None # No available IDs
71 |
72 | def release_id(self):
73 | """Release the ID held by the current process"""
74 | # No need to do anything here as the ID is managed by paths.yaml
75 | # The ID will be released when the path is deleted from paths.yaml
76 | self.current_id = None
77 |
78 | def get_current_id(self) -> Optional[int]:
79 | """Get the current process's ID without acquiring a new one"""
80 | return self.current_id
81 |
82 | def __enter__(self):
83 | """Context manager support"""
84 | self.acquire_id()
85 | return self
86 |
87 | def __exit__(self, exc_type, exc_val, exc_tb):
88 | """Context manager support"""
89 | self.release_id()
90 |
--------------------------------------------------------------------------------
/tests/README.md:
--------------------------------------------------------------------------------
1 | # NetHang Tests
2 |
3 | This directory contains comprehensive tests for the NetHang application.
4 |
5 | ## Test Structure
6 |
7 | - `test_config_manager.py` - Tests for the ConfigManager class
8 | - `test_about.py` - Test for the About page
9 | - `conftest.py` - Shared fixtures and test configuration
10 | - `__init__.py` - Makes tests a Python package
11 |
12 | ## Running Tests
13 |
14 | ### Install Test Dependencies
15 |
16 | ```bash
17 | pip install -r requirements-test.txt
18 | ```
19 |
20 | ### Run All Tests
21 |
22 | ```bash
23 | pytest
24 | ```
25 |
26 | ### Run Specific Test File
27 |
28 | ```bash
29 | pytest tests/test_config_manager.py
30 | ```
31 |
32 | ### Run Tests with Coverage
33 |
34 | ```bash
35 | pytest --cov=nethang --cov-report=html
36 | ```
37 |
38 | ### Run Tests in Parallel
39 |
40 | ```bash
41 | pytest -n auto
42 | ```
43 |
44 | ### Run Tests with Verbose Output
45 |
46 | ```bash
47 | pytest -v
48 | ```
49 |
50 | ## Test Categories
51 |
52 | The tests are organized into the following categories:
53 |
54 | ### Unit Tests
55 | - Test individual methods and functions in isolation
56 | - Use mocking to isolate dependencies
57 | - Fast execution
58 |
59 | ### Integration Tests
60 | - Test interactions between components
61 | - May use real file system or network calls
62 | - Slower execution
63 |
64 | ### Network Tests
65 | - Tests that require network access
66 | - Marked with `@pytest.mark.network`
67 |
68 | ### Slow Tests
69 | - Tests that take longer to execute
70 | - Marked with `@pytest.mark.slow`
71 |
72 | ## Test Coverage
73 |
74 | The tests cover:
75 |
76 | ### ConfigManager Class
77 | - Initialization and configuration
78 | - GitHub config download functionality
79 | - Fallback config creation
80 | - Config file validation
81 | - Error handling for network issues
82 | - YAML parsing and validation
83 | - File operations (create, read, update)
84 | - Backup and restore functionality
85 |
86 | ### Key Test Scenarios
87 | - Successful config download from GitHub
88 | - Network failure handling
89 | - Invalid YAML content handling
90 | - File system errors
91 | - Config update logic
92 | - Fallback mechanism activation
93 |
94 | ## Mocking Strategy
95 |
96 | The tests use extensive mocking to:
97 |
98 | - Isolate the unit under test
99 | - Avoid real network calls
100 | - Control file system operations
101 | - Simulate error conditions
102 | - Test edge cases
103 |
104 | ## Fixtures
105 |
106 | Common fixtures are defined in `conftest.py`:
107 |
108 | - `temp_test_dir` - Temporary directory for test files
109 | - `mock_flask_app` - Mock Flask application
110 | - `mock_config_paths` - Mock configuration paths
111 | - `sample_yaml_config` - Sample YAML configuration
112 | - `mock_github_response_success` - Mock successful GitHub response
113 | - `mock_requests_get_success` - Mock successful HTTP requests
114 | - `mock_file_operations` - Mock file operations
115 |
116 | ## Best Practices
117 |
118 | 1. **Isolation**: Each test should be independent
119 | 2. **Mocking**: Use mocks to isolate dependencies
120 | 3. **Cleanup**: Clean up resources after tests
121 | 4. **Descriptive Names**: Use clear, descriptive test names
122 | 5. **Documentation**: Document complex test scenarios
123 | 6. **Edge Cases**: Test error conditions and edge cases
124 | 7. **Coverage**: Aim for high test coverage
125 |
126 | ## Adding New Tests
127 |
128 | When adding new tests:
129 |
130 | 1. Follow the existing naming convention
131 | 2. Use appropriate fixtures from `conftest.py`
132 | 3. Mock external dependencies
133 | 4. Test both success and failure scenarios
134 | 5. Add appropriate markers for test categorization
135 | 6. Update this README if adding new test categories
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # UV
98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | #uv.lock
102 |
103 | # poetry
104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105 | # This is especially recommended for binary packages to ensure reproducibility, and is more
106 | # commonly ignored for libraries.
107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108 | #poetry.lock
109 |
110 | # pdm
111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112 | #pdm.lock
113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114 | # in version control.
115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116 | .pdm.toml
117 | .pdm-python
118 | .pdm-build/
119 |
120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121 | __pypackages__/
122 |
123 | # Celery stuff
124 | celerybeat-schedule
125 | celerybeat.pid
126 |
127 | # SageMath parsed files
128 | *.sage.py
129 |
130 | # Environments
131 | .env
132 | .venv
133 | env/
134 | venv/
135 | ENV/
136 | env.bak/
137 | venv.bak/
138 |
139 | # Spyder project settings
140 | .spyderproject
141 | .spyproject
142 |
143 | # Rope project settings
144 | .ropeproject
145 |
146 | # mkdocs documentation
147 | /site
148 |
149 | # mypy
150 | .mypy_cache/
151 | .dmypy.json
152 | dmypy.json
153 |
154 | # Pyre type checker
155 | .pyre/
156 |
157 | # pytype static type analyzer
158 | .pytype/
159 |
160 | # Cython debug symbols
161 | cython_debug/
162 |
163 | # PyCharm
164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166 | # and can be added to the global gitignore or merged into this file. For a more nuclear
167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168 | #.idea/
169 |
170 | # Ruff stuff:
171 | .ruff_cache/
172 |
173 | # PyPI configuration file
174 | .pypirc
175 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 
6 |
7 | NetHang is a web-based tool designed to simulate network quality, focusing on the diversity of last-mile network conditions. For modern internet applications and services with high real-time requirements, NetHang offers a stable, reentrant, customizable, and easily extensible network quality simulation system, helping to achieve low-latency and high-quality internet services.
8 |
9 |
10 |
11 | Unlike traditional network impairment tools that target backbone network quality between servers and switches, NetHang is optimized for:
12 |
13 | - Simulating network quality from user equipment (UE) to servers, typically traversing:
14 | - UE <--> Lan (Wi-Fi or Wired) <--> Routers <--> ISP edge nodes <--> APP servers
15 | - UE <--> Cellular <--> ISP edge nodes <--> APP servers
16 | - UE <--> Air interface <--> Satellite <--> APP servers
17 |
18 |
19 |
20 | - The current network model is built and simplified based on existing network quality data modeling, while also supporting users to easily customize the network models they need for testing in YAML format.
21 |
22 | - NetHang clearly displays the differences in data traffic before and after simulation, as well as the state of the simulation conditions.
23 |
24 |
25 |
26 | ## Features
27 |
28 | - Traffic rate limiting and shaping
29 | - Network latency and latency variation simulation
30 | - Packet loss simulation
31 | - Support for both uplink and downlink traffic control
32 | - Configurable traffic rules and models
33 | - Real-time traffic statistics display
34 |
35 | ## Requirements
36 |
37 | - Python 3.8 or higher
38 | - Linux system with `tc` and `iptables` support
39 | - Root privileges for traffic control operations
40 |
41 | ## Installation
42 |
43 | ### From PyPI (Recommended)
44 |
45 | You can install NetHang from PyPI using the following command:
46 |
47 | ```pip install nethang```
48 |
49 | ### From Source (For Developers)
50 |
51 | You can also install NetHang from source by cloning the repository and running the following command:
52 |
53 | ```pip install .```
54 |
55 | ## License
56 |
57 | MIT License
58 |
59 | Copyright (c) 2025 NetHang Contributors
60 |
61 | Permission is hereby granted, free of charge, to any person obtaining a copy
62 | of this software and associated documentation files (the "Software"), to deal
63 | in the Software without restriction, including without limitation the rights
64 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
65 | copies of the Software, and to permit persons to whom the Software is
66 | furnished to do so, subject to the following conditions:
67 |
68 | The above copyright notice and this permission notice shall be included in all
69 | copies or substantial portions of the Software.
70 |
71 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
72 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
73 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
74 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
75 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
76 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
77 | SOFTWARE.
78 |
79 | ## Contributing
80 |
81 | 1. Fork the repository
82 | 2. Create a feature branch
83 | 3. Commit your changes
84 | 4. Push to the branch
85 | 5. Create a Pull Request
86 |
87 | Please make sure to update tests as appropriate and adhere to the existing coding style.
88 |
89 | ## Authors
90 |
91 | NetHang Contributors
92 |
93 | ## Acknowledgments
94 |
95 | - Thanks to all contributors who have helped with the project
96 | - Inspired by various network traffic control tools and utilities
97 |
--------------------------------------------------------------------------------
/nethang/templates/base.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | {% block title %}NetHang{% endblock %}
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
36 | {% block extra_css %}{% endblock %}
37 |
38 |
39 |
40 | {% if g.privileges and (not g.privileges.tc_access or not g.privileges.iptables_access) %}
41 |
NetHang is a web-based network quality simulation tool that allows you to create and manage
259 | network paths between LAN and WAN interfaces. Ideal for use
260 | with software routers on Linux platform. It focuses on simulating weak network (poor network)
261 | conditions, with built-in scenario models(Edge, 3G, 4G, Wi-Fi, Starlink, etc.) and combinations of
262 | parameters such as packet loss, delay, jitter, and bandwidth limitation, etc. It helps you
263 | simulate various network conditions and monitor their effects on traffic.
271 |
272 |
274 | How NetHang looks like
275 |
276 |
277 |
278 |
279 |
280 |
Preparation
281 |
In simple terms, NetHang needs to run on a Linux-based software router. If you already
282 | have such
283 | a software router device or are familiar with how to set up the environment, it will be very
284 | convenient.
285 |
If not, please follow the instructions below step-by-step to build one. Depending on your
286 | hardware and network environment, you may encounter different issues, which we can discuss and
287 | troubleshoot on GitHub.
288 |
Hardware
289 |
A Ubuntu 22.04 LTS server (or desktop) with at least TWO network interface cards (NICs) is
290 | required.
The application provides real-time monitoring of network conditions through three charts:
608 |
609 |
610 |
611 |
612 |
Throughput
613 |
Shows the bit rate for both uplink and downlink traffic.
614 |
615 |
616 |
617 |
618 |
619 |
620 |
621 |
Queuing
622 |
Displays the number of packets in the queue.
623 |
624 |
625 |
626 |
627 |
628 |
629 |
Loss
630 |
Shows the packet loss rate over time.
631 |
632 |
633 |
634 |
635 |
636 |
638 | Monitoring
639 |
640 |
641 |
642 |
643 |
644 |
645 |
Future Plans
646 |
647 |
648 |
649 |
650 |
Provide with more Models
651 |
More models to choose from.
652 |
653 |
654 |
655 |
656 |
657 |
658 |
Support more platforms
659 |
Debian, OpenWRT, etc.
660 |
661 |
662 |
663 |
664 |
665 |
666 |
Support recording statistics
667 |
Support recording statistics to a file or database.
668 |
669 |
670 |
671 |
672 |
673 |
674 |
Support more custom settings
675 |
Frame overhead size, Jitter distribution, Packet loss
676 | distribution, Rate limit burst size & ceil rate. etc.
677 |
678 |
679 |
680 |
681 |
682 |
683 |
684 |
FAQ
685 |
686 |
687 |
688 |
692 |
693 |
695 |
696 |
NetHang is a tool for simulating network conditions in a controlled environment.
697 | It allows you to test your network applications under various network
698 | conditions.
699 |
700 |
701 |
702 |
703 |
704 |
705 |
706 |
Repository and Author
707 |
708 |
709 |
710 |
711 |
Repository
712 |
NetHang is an open-source project hosted on GitHub. You can find the source code, report issues, and contribute to the project at: