Skip to content

Commit 6ea274c

Browse files
committed
Refactor: Refactor function in topologymanager and add code descriptions
- Refactored a function in topologymanager to improve efficiency and readability. - Added descriptions to the code in env.py, functionts.py, mobility.py, reporter.py, and topologymanager.py for better understanding of functionality.
1 parent ef0bdbb commit 6ea274c

File tree

6 files changed

+838
-98
lines changed

6 files changed

+838
-98
lines changed

nebula/addons/__init__.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
This package consists of several modules that handle different aspects of the network simulation:
3+
4+
1. `env.py`:
5+
- Manages the environment configuration and settings.
6+
- It initializes the system environment, loads configuration parameters, and ensures correct operation of other components based on the simulation's settings.
7+
8+
2. `functions.py`:
9+
- Contains utility functions that are used across different parts of the simulation.
10+
- It provides helper methods for common operations like data processing, mathematical calculations, and other reusable functionalities.
11+
12+
3. `mobility.py`:
13+
- Models and simulates the mobility of nodes within the network.
14+
- It handles dynamic aspects of the simulation, such as node movement and position updates, based on mobility models and the simulation's configuration.
15+
16+
4. `reporter.py`:
17+
- Responsible for collecting and reporting data during the simulation.
18+
- It tracks various system metrics, including node status and network performance, and periodically sends updates to a controller or dashboard for analysis and monitoring.
19+
20+
5. `topologymanager.py`:
21+
- Manages the topology of the network.
22+
- It handles the creation and maintenance of the network's structure (e.g., nodes and their connections), including generating different types of topologies like ring, random, or fully connected based on simulation parameters.
23+
24+
Each of these modules plays a critical role in simulating a network environment, enabling real-time tracking, topology management, mobility simulation, and efficient reporting of results.
25+
"""

nebula/addons/env.py

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,29 @@
1010

1111

1212
def check_version():
13-
# Check version of NEBULA (__version__ is defined in __init__.py) and compare with __version__ in https://raw.githubusercontent.com/CyberDataLab/nebula/main/nebula/__init__.py
13+
"""
14+
Checks the current version of NEBULA and compares it with the latest version available in the repository.
15+
16+
This function retrieves the latest NEBULA version from the specified GitHub repository and compares
17+
it with the version defined in the local NEBULA package. If the versions do not match, it logs a message
18+
prompting the user to update to the latest version.
19+
20+
Returns:
21+
None
22+
23+
Raises:
24+
SystemExit: If the version check fails or an exception occurs during the request.
25+
26+
Notes:
27+
- The version information is expected to be defined in the `__init__.py` file of the NEBULA package
28+
using the `__version__` variable.
29+
- If the latest version is not the same as the local version, the program will exit after logging
30+
the necessary information.
31+
- An exception during the request will be logged, and the program will also exit.
32+
"""
1433
logging.info("Checking NEBULA version...")
1534
try:
16-
r = requests.get("https://raw.githubusercontent.com/CyberDataLab/nebula/main/nebula/__init__.py")
35+
r = requests.get("https://raw.githubusercontent.com/CyberDataLab/nebula/main/nebula/__init__.py", timeout=5)
1736
if r.status_code == 200:
1837
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', r.text, re.MULTILINE).group(1)
1938
if version != __version__:
@@ -26,12 +45,30 @@ def check_version():
2645
sys.exit(0)
2746
else:
2847
logging.info(f"Your NEBULA version is {__version__} and it is the latest version.")
29-
except Exception as e:
30-
logging.exception(f"Error while checking NEBULA version: {e}")
48+
except Exception:
49+
logging.exception("Error while checking NEBULA version")
3150
sys.exit(0)
3251

3352

3453
def check_environment():
54+
"""
55+
Logs the current environment configuration for the NEBULA platform.
56+
57+
This function gathers and logs information about the operating system, hardware, Python version,
58+
PyTorch version (if installed), CPU configuration, and GPU configuration (if applicable). It provides
59+
insights into the system's capabilities and current usage statistics.
60+
61+
Returns:
62+
None
63+
64+
Notes:
65+
- The function logs the NEBULA platform version using the `__version__` variable.
66+
- It checks the system's CPU load, available memory, and detailed GPU statistics using the `pynvml`
67+
library if running on Windows or Linux.
68+
- If any of the libraries required for gathering information (like `torch`, `psutil`, or `pynvml`)
69+
are not installed, appropriate log messages will be generated indicating the absence of that information.
70+
- If any unexpected error occurs during execution, it will be logged as an exception.
71+
"""
3572
logging.info(f"NEBULA Platform version: {__version__}")
3673
# check_version()
3774

@@ -46,7 +83,7 @@ def check_environment():
4683
logging.info("PyTorch version: " + torch.__version__)
4784
except ImportError:
4885
logging.info("PyTorch is not installed properly")
49-
except Exception:
86+
except Exception: # noqa: S110
5087
pass
5188

5289
logging.info("======== CPU Configuration ========")
@@ -62,7 +99,7 @@ def check_environment():
6299
)
63100
except ImportError:
64101
logging.info("No CPU information available")
65-
except Exception:
102+
except Exception: # noqa: S110
66103
pass
67104

68105
if sys.platform == "win32" or sys.platform == "linux":
@@ -93,7 +130,7 @@ def check_environment():
93130
logging.info(f"GPU{i} fan speed: {gpu_fan_speed}")
94131
except ImportError:
95132
logging.info("pynvml module not found, GPU information unavailable")
96-
except Exception:
133+
except Exception: # noqa: S110
97134
pass
98135
else:
99136
logging.info("GPU information unavailable")

nebula/addons/functions.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,36 @@
22

33

44
def print_msg_box(msg, indent=1, width=None, title=None, logger_name=None):
5-
"""Print message-box with optional title."""
6-
if logger_name:
7-
logger = logging.getLogger(logger_name)
8-
else:
9-
logger = logging.getLogger()
5+
"""
6+
Prints a formatted message box to the logger with an optional title.
7+
8+
This function creates a visually appealing message box format for logging messages.
9+
It allows for indentation, custom width, and inclusion of a title. If the message is
10+
multiline, each line will be included in the box.
11+
12+
Args:
13+
msg (str): The message to be displayed inside the box. Must be a string.
14+
indent (int, optional): The number of spaces to indent the message box. Default is 1.
15+
width (int, optional): The width of the message box. If not provided, it will be calculated
16+
based on the longest line of the message and the title (if provided).
17+
title (str, optional): An optional title for the message box. Must be a string if provided.
18+
logger_name (str, optional): The name of the logger to use. If not provided, the root logger
19+
will be used.
20+
21+
Raises:
22+
TypeError: If `msg` or `title` is not a string.
23+
24+
Returns:
25+
None
26+
27+
Notes:
28+
- The message box is bordered with decorative characters to enhance visibility in the logs.
29+
- If the `width` is not provided, it will automatically adjust to fit the content.
30+
"""
31+
logger = logging.getLogger(logger_name) if logger_name else logging.getLogger()
1032

1133
if not isinstance(msg, str):
12-
raise TypeError("msg parameter must be a string")
34+
raise TypeError("msg parameter must be a string") # noqa: TRY003
1335

1436
lines = msg.split("\n")
1537
space = " " * indent
@@ -20,7 +42,7 @@ def print_msg_box(msg, indent=1, width=None, title=None, logger_name=None):
2042
box = f"\n{'═' * (width + indent * 2)}\n" # upper_border
2143
if title:
2244
if not isinstance(title, str):
23-
raise TypeError("title parameter must be a string")
45+
raise TypeError("title parameter must be a string") # noqa: TRY003
2446
box += f"║{space}{title:<{width}}{space}\n" # title
2547
box += f"║{space}{'-' * len(title):<{width}}{space}\n" # underscore
2648
box += "".join([f"║{space}{line:<{width}}{space}\n" for line in lines])

0 commit comments

Comments
 (0)