### Complete Minimal Example for PasarGuard Node Bridge Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md A minimal example demonstrating how to create, start, interact with, and stop a PasarGuard Node Bridge instance. Ensure certificates and configuration files are correctly placed. ```python import asyncio import PasarGuardNodeBridge as Bridge from PasarGuardNodeBridge.common import service_pb2 as service async def main(): with open("certs/ssl_cert.pem", "r", encoding="utf-8") as f: server_ca = f.read() with open("config/xray.json", "r", encoding="utf-8") as f: config = f.read() node = Bridge.create_node( connection=Bridge.NodeType.grpc, address="127.0.0.1", port=2096, api_port=2097, server_ca=server_ca, api_key="d04d8680-942d-4365-992f-9f482275691d", name="example-node", ) await node.start(config=config, backend_type=service.BackendType.XRAY, users=[]) print(await node.get_system_stats()) await node.stop() asyncio.run(main()) ``` -------------------------------- ### Start and Stop Node Lifecycle Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Initialize the node service before accessing stats or logs. The `start` method requires configuration and optionally accepts initial users. Use `stop` to gracefully shut down the service. ```python await node.start( config=config_json_string, backend_type=service.BackendType.XRAY, # or service.BackendType.WIREGUARD users=[user], # optional initial user set keep_alive=30, # optional exclude_inbounds=[], # optional timeout=20, ) info = await node.info() print(info.node_version, info.core_version) await node.stop() ``` -------------------------------- ### Install pasarguard-node-bridge Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Install the package using pip. Ensure you have Python 3.12 or higher. ```bash pip install pasarguard-node-bridge ``` -------------------------------- ### Error Handling Example Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Demonstrates how to handle `Bridge.NodeAPIError` exceptions. ```APIDOC ## Error Handling All transport and API errors are surfaced as `Bridge.NodeAPIError`. ```python try: await node.get_backend_stats(timeout=5) except Bridge.NodeAPIError as e: print(e.code, e.detail) ``` ``` -------------------------------- ### Lifecycle Management Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Methods for starting, stopping, and retrieving information about the Node Bridge instance. ```APIDOC ## start ### Description Starts the Node Bridge with the provided configuration. ### Method `start(config, backend_type, users, keep_alive=0, exclude_inbounds=[], timeout=None)` ### Parameters - **config** (str) - Required - The configuration for the backend. - **backend_type** (service.BackendType) - Required - The type of backend to use. - **users** (list) - Required - A list of users. - **keep_alive** (int) - Optional - Duration to keep the connection alive. - **exclude_inbounds** (list) - Optional - List of inbounds to exclude. - **timeout** (int) - Optional - Timeout for the operation. ## stop ### Description Stops the Node Bridge instance. ### Method `stop(timeout=None)` ### Parameters - **timeout** (int) - Optional - Timeout for the operation. ## info ### Description Retrieves information about the Node Bridge instance. ### Method `info(timeout=None)` ### Parameters - **timeout** (int) - Optional - Timeout for the operation. ``` -------------------------------- ### Get Node Health and Version Information Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Check the health status of the node and retrieve version information for both the node and its core. Multiple methods are available for fetching this data. ```python health = await node.get_health() # Bridge.Health enum node_ver = await node.node_version() core_ver = await node.core_version() node_ver2, core_ver2 = await node.get_versions() meta = await node.get_extra() ``` -------------------------------- ### Create Protobuf User/Proxy Payloads Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Use helper functions to construct protobuf messages for user and proxy configurations. Ensure all required fields are populated. ```python user = Bridge.create_user( email="alice@example.com", proxies=Bridge.create_proxy( vmess_id="0d59268a-9847-4218-ae09-65308eb52e08", vless_id="0d59268a-9847-4218-ae09-65308eb52e08", vless_flow="", trojan_password="", shadowsocks_password="", shadowsocks_method="", wireguard_public_key="", wireguard_peer_ips=["10.10.0.2/32"], ), inbounds=["inbound-tag-1"], ) ``` -------------------------------- ### Create REST Node Client Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Instantiate a client for connecting to a PasarGuard node using REST. Provide connection details, certificates, and API key. Optional parameters include logger name, metadata, timeouts, and proxy settings. ```python node = Bridge.create_node( connection=Bridge.NodeType.rest, # Bridge.NodeType.grpc or Bridge.NodeType.rest address="127.0.0.1", port=2096, # gRPC or protobuf-REST port (based on connection) api_port=2097, # REST JSON API port (used internally for maintenance) server_ca=server_ca_pem_string, api_key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", name="node-1", # optional extra={"region": "eu-1"}, # optional default_timeout=10, # optional internal_timeout=15, # optional proxy="socks5://user:pass@127.0.0.1:1080", # optional ) ``` -------------------------------- ### Sync User Configuration (Direct) Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Directly synchronize a list of users with the node. Specify a timeout for the operation. ```python await node.sync_users([user1, user2], timeout=15) ``` -------------------------------- ### Import Protobuf Service Definitions in Python Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Import common service protobuf definitions for direct usage with the bridge. ```python from PasarGuardNodeBridge.common import service_pb2 as service ``` -------------------------------- ### Create gRPC Node Client Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Instantiate a client for connecting to a PasarGuard node using gRPC. Provide connection details, certificates, and API key. Optional parameters include logger name, metadata, timeouts, and proxy settings. ```python node = Bridge.create_node( connection=Bridge.NodeType.grpc, # Bridge.NodeType.grpc or Bridge.NodeType.rest address="127.0.0.1", port=2096, # gRPC or protobuf-REST port (based on connection) api_port=2097, # REST JSON API port (used internally for maintenance) server_ca=server_ca_pem_string, api_key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", name="node-1", # optional extra={"region": "eu-1"}, # optional default_timeout=10, # optional internal_timeout=15, # optional proxy="socks5://user:pass@127.0.0.1:1080", # optional ) ``` -------------------------------- ### Import PasarGuardNodeBridge Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Import the necessary modules for using the PasarGuard node bridge. ```python import PasarGuardNodeBridge as Bridge from PasarGuardNodeBridge.common import service_pb2 as service ``` -------------------------------- ### Sync User Configuration (Chunked) Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Synchronize large user lists by breaking them into chunks. This method returns a list of users that failed to sync. ```python failed_users = await node.sync_users_chunked( users=large_user_list, chunk_size=500, timeout=30, ) if failed_users: print(f"Failed users: {len(failed_users)}") ``` -------------------------------- ### Update User Configuration (Queue-Based) Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Enqueue user updates for background processing. `update_user` handles a single user, while `update_users` processes a list. ```python await node.update_user(user) more_users = [user1, user2, user3] await node.update_users(more_users) ``` -------------------------------- ### Logging Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Provides a method to stream logs from the Node Bridge. ```APIDOC ## stream_logs ### Description Asynchronously streams logs from the Node Bridge. Returns an `asyncio.Queue`. ### Method `stream_logs(max_queue_size=1000)` ### Parameters - **max_queue_size** (int) - Optional - The maximum size of the log queue. ``` -------------------------------- ### User Synchronization Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Methods for updating and synchronizing user information with the Node Bridge. ```APIDOC ## update_user ### Description Updates a single user's information. This operation is queued and processed in the background. ### Method `update_user(user)` ### Parameters - **user** (dict) - Required - The user object to update. ## update_users ### Description Updates multiple users' information. This operation is queued and processed in the background. ### Method `update_users(users)` ### Parameters - **users** (list) - Required - A list of user objects to update. ## sync_users ### Description Directly synchronizes user information. This is a direct call, not queued. ### Method `sync_users(users, flush_pending=False, timeout=None)` ### Parameters - **users** (list) - Required - A list of user objects to synchronize. - **flush_pending** (bool) - Optional - Whether to flush pending updates. - **timeout** (int) - Optional - Timeout for the operation. ## sync_users_chunked ### Description Synchronizes user information in chunks using a streaming approach. This is a direct call. ### Method `sync_users_chunked(users, chunk_size=100, flush_pending=False, timeout=None)` ### Parameters - **users** (list) - Required - A list of user objects to synchronize. - **chunk_size** (int) - Optional - The size of each chunk. - **flush_pending** (bool) - Optional - Whether to flush pending updates. - **timeout** (int) - Optional - Timeout for the operation. ``` -------------------------------- ### Retrieve Statistics Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Fetch various statistics from the node, including system, backend, and outbound latency. You can also retrieve specific user online statistics and IP lists. ```python system_stats = await node.get_system_stats() backend_stats = await node.get_backend_stats() latencies = await node.get_outbounds_latency() all_outbounds = await node.get_stats( stat_type=service.StatType.Outbounds, reset=False, ) single_user_online = await node.get_user_online_stats("alice@example.com") single_user_ips = await node.get_user_online_ip_list("alice@example.com") ``` -------------------------------- ### Health and Version Information Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Methods to check the health status and retrieve version information of the Node Bridge and its core components. ```APIDOC ## get_health ### Description Retrieves the health status of the Node Bridge. ### Method `get_health()` ## node_version ### Description Retrieves the version of the Node Bridge. ### Method `node_version()` ## core_version ### Description Retrieves the version of the Node Bridge core. ### Method `core_version()` ## get_versions ### Description Retrieves all version information for the Node Bridge and its components. ### Method `get_versions()` ## get_extra ### Description Retrieves extra information about the Node Bridge. ### Method `get_extra()` ``` -------------------------------- ### Statistics Retrieval Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Methods for fetching various statistics related to the system, backend, and user activity. ```APIDOC ## get_system_stats ### Description Retrieves system-wide statistics. ### Method `get_system_stats(timeout=None)` ### Parameters - **timeout** (int) - Optional - Timeout for the operation. ## get_backend_stats ### Description Retrieves statistics for the backend. ### Method `get_backend_stats(timeout=None)` ### Parameters - **timeout** (int) - Optional - Timeout for the operation. ## get_stats ### Description Retrieves general statistics of a specified type. ### Method `get_stats(stat_type, reset=True, name="", timeout=None)` ### Parameters - **stat_type** (str) - Required - The type of statistics to retrieve. - **reset** (bool) - Optional - Whether to reset stats after retrieval. - **name** (str) - Optional - The name of the stats to retrieve. - **timeout** (int) - Optional - Timeout for the operation. ## get_outbounds_latency ### Description Retrieves latency information for outbounds. ### Method `get_outbounds_latency(name="", timeout=None)` ### Parameters - **name** (str) - Optional - The name of the outbound. - **timeout** (int) - Optional - Timeout for the operation. ## get_user_online_stats ### Description Retrieves online statistics for a specific user. ### Method `get_user_online_stats(email, timeout=None)` ### Parameters - **email** (str) - Required - The email of the user. - **timeout** (int) - Optional - Timeout for the operation. ## get_user_online_ip_list ### Description Retrieves the list of online IPs for a specific user. ### Method `get_user_online_ip_list(email, timeout=None)` ### Parameters - **email** (str) - Required - The email of the user. - **timeout** (int) - Optional - Timeout for the operation. ``` -------------------------------- ### Maintenance Operations Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Methods for updating the Node Bridge software and its components. ```APIDOC ## update_node ### Description Updates the Node Bridge software. ### Method `update_node()` ## update_core ### Description Updates the core component of the Node Bridge with provided JSON data. ### Method `update_core(json)` ### Parameters - **json** (str) - Required - JSON data for the core update. ## update_geofiles ### Description Updates the geofiles with provided JSON data. ### Method `update_geofiles(json)` ### Parameters - **json** (str) - Required - JSON data for the geofile update. ``` -------------------------------- ### Stream Node Logs Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Asynchronously stream log lines from the node. The `stream_logs` method returns an asyncio queue that yields log strings or Bridge.NodeAPIError exceptions. Ensure proper error handling and timeout management. ```python import asyncio async with node.stream_logs(max_queue_size=200) as log_queue: for _ in range(20): item = await asyncio.wait_for(log_queue.get(), timeout=2) if isinstance(item, Bridge.NodeAPIError): raise item print(item) ``` -------------------------------- ### Handle Bridge Node API Errors in Python Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Catch Bridge.NodeAPIError to handle transport and API errors. Access error code and detail from the exception object. ```python try: await node.get_backend_stats(timeout=5) except Bridge.NodeAPIError as e: print(e.code, e.detail) ``` -------------------------------- ### Maintenance Operations Source: https://github.com/pasarguard/node_bridge_py/blob/main/README.md Perform maintenance tasks on the node using its REST JSON API. This includes updating the node configuration, core version, and geofiles. ```python await node.update_node() await node.update_core({"version": "latest"}) await node.update_geofiles({"remove_temp": True}) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.