ruff: apply automatic fixes

This commit is contained in:
Jörg Thalheim
2025-08-20 13:52:45 +02:00
parent 798d445f3e
commit ea2d6aab65
217 changed files with 2283 additions and 1739 deletions

View File

@@ -16,9 +16,11 @@ class ConnectionOptions:
@API.register
def check_machine_ssh_login(
remote: Remote, opts: ConnectionOptions | None = None
remote: Remote,
opts: ConnectionOptions | None = None,
) -> None:
"""Checks if a remote machine is reachable via SSH by attempting to run a simple command.
Args:
remote (Remote): The remote host to check for SSH login.
opts (ConnectionOptions, optional): Connection options such as timeout.
@@ -29,8 +31,10 @@ def check_machine_ssh_login(
print("SSH login successful")
else:
print(f"SSH login failed: {result.reason}")
Raises:
ClanError: If the SSH login fails.
"""
if opts is None:
opts = ConnectionOptions()
@@ -54,15 +58,17 @@ def check_machine_ssh_login(
@API.register
def check_machine_ssh_reachable(
remote: Remote, opts: ConnectionOptions | None = None
remote: Remote,
opts: ConnectionOptions | None = None,
) -> None:
"""
Checks if a remote machine is reachable via SSH by attempting to open a TCP connection
"""Checks if a remote machine is reachable via SSH by attempting to open a TCP connection
to the specified address and port.
Args:
remote (Remote): The remote host to check for SSH reachability.
opts (ConnectionOptions, optional): Connection options such as timeout.
If not provided, default values are used.
Returns:
CheckResult: An object indicating whether the SSH port is reachable (`ok=True`) or not (`ok=False`),
and a reason if the check failed.
@@ -71,6 +77,7 @@ def check_machine_ssh_reachable(
if result.ok:
print("SSH port is reachable")
print(f"SSH port is not reachable: {result.reason}")
"""
if opts is None:
opts = ConnectionOptions()
@@ -90,7 +97,7 @@ def check_machine_ssh_reachable(
[
"-o",
f"ProxyCommand=nc -X 5 -x localhost:{remote.socks_port} %h %p",
]
],
)
cmd.extend(
@@ -109,7 +116,7 @@ def check_machine_ssh_reachable(
str(remote.port or 22),
f"dummy@{remote.address.strip()}",
"true",
]
],
)
try:

View File

@@ -108,7 +108,7 @@ def networks_from_flake(flake: Flake) -> dict[str, Network]:
flake.precache(
[
"clan.?exports.instances.*.networking",
]
],
)
networks: dict[str, Network] = {}
networks_ = flake.select("clan.?exports.instances.*.networking")
@@ -123,7 +123,9 @@ def networks_from_flake(flake: Flake) -> dict[str, Network]:
peers: dict[str, Peer] = {}
for _peer in network["peers"].values():
peers[_peer["name"]] = Peer(
name=_peer["name"], _host=_peer["host"], flake=flake
name=_peer["name"],
_host=_peer["host"],
flake=flake,
)
networks[network_name] = Network(
peers=peers,
@@ -135,8 +137,7 @@ def networks_from_flake(flake: Flake) -> dict[str, Network]:
@contextmanager
def get_best_remote(machine: "Machine") -> Iterator["Remote"]:
"""
Context manager that yields the best remote connection for a machine following this priority:
"""Context manager that yields the best remote connection for a machine following this priority:
1. If machine has targetHost in inventory, return a direct connection
2. Return the highest priority network where machine is reachable
3. If no network works, try to get targetHost from machine nixos config
@@ -149,8 +150,8 @@ def get_best_remote(machine: "Machine") -> Iterator["Remote"]:
Raises:
ClanError: If no connection method works
"""
"""
# Step 1: Check if targetHost is set in inventory
inv_machine = machine.get_inv_machine()
target_host = inv_machine.get("deploy", {}).get("targetHost")
@@ -182,7 +183,7 @@ def get_best_remote(machine: "Machine") -> Iterator["Remote"]:
ping_time = network.ping(machine.name)
if ping_time is not None:
log.info(
f"Machine {machine.name} reachable via {network_name} network"
f"Machine {machine.name} reachable via {network_name} network",
)
yield network.remote(machine.name)
return
@@ -195,13 +196,13 @@ def get_best_remote(machine: "Machine") -> Iterator["Remote"]:
ping_time = connected_network.ping(machine.name)
if ping_time is not None:
log.info(
f"Machine {machine.name} reachable via {network_name} network after connection"
f"Machine {machine.name} reachable via {network_name} network after connection",
)
yield connected_network.remote(machine.name)
return
except Exception as e:
log.debug(
f"Failed to establish connection to {machine.name} via {network_name}: {e}"
f"Failed to establish connection to {machine.name} via {network_name}: {e}",
)
except Exception as e:
log.debug(f"Failed to use networking modules to determine machines remote: {e}")
@@ -211,18 +212,19 @@ def get_best_remote(machine: "Machine") -> Iterator["Remote"]:
target_host = machine.select('config.clan.core.networking."targetHost"')
if target_host:
log.debug(
f"Using targetHost from machine config for {machine.name}: {target_host}"
f"Using targetHost from machine config for {machine.name}: {target_host}",
)
# Check if reachable
try:
remote = Remote.from_ssh_uri(
machine_name=machine.name, address=target_host
machine_name=machine.name,
address=target_host,
)
yield remote
return
except Exception as e:
log.debug(
f"Machine config targetHost not reachable for {machine.name}: {e}"
f"Machine config targetHost not reachable for {machine.name}: {e}",
)
except Exception as e:
log.debug(f"Could not get targetHost from machine config: {e}")
@@ -247,10 +249,10 @@ def get_network_overview(networks: dict[str, Network]) -> dict:
for peer_name in network.peers:
try:
result[network_name]["peers"][peer_name] = network.ping(
peer_name
peer_name,
)
except ClanError:
log.warning(
f"getting host for machine: {peer_name} in network: {network_name} failed"
f"getting host for machine: {peer_name} in network: {network_name} failed",
)
return result

View File

@@ -37,7 +37,7 @@ def test_networks_from_flake(mock_get_machine_var: MagicMock) -> None:
"machine": "machine1",
"generator": "wireguard",
"file": "address",
}
},
},
},
"machine2": {
@@ -47,7 +47,7 @@ def test_networks_from_flake(mock_get_machine_var: MagicMock) -> None:
"machine": "machine2",
"generator": "wireguard",
"file": "address",
}
},
},
},
},
@@ -68,7 +68,7 @@ def test_networks_from_flake(mock_get_machine_var: MagicMock) -> None:
"module": "clan_lib.network.direct",
"priority": 500,
},
}
},
}
# Mock the select method

View File

@@ -33,7 +33,7 @@ class QRCodeData:
try:
log.debug(f"Establishing connection via {address}")
with address.network.module.connection(
address.network
address.network,
) as connected_network:
ping_time = connected_network.module.ping(address.remote)
if ping_time is not None:
@@ -44,8 +44,7 @@ class QRCodeData:
def read_qr_json(qr_data: dict[str, Any], flake: Flake) -> QRCodeData:
"""
Parse QR code JSON contents and output a dict of networks with remotes.
"""Parse QR code JSON contents and output a dict of networks with remotes.
Args:
qr_data: JSON data from QR code containing network information
@@ -72,6 +71,7 @@ def read_qr_json(qr_data: dict[str, Any], flake: Flake) -> QRCodeData:
"remote": Remote(...)
}
}
"""
addresses: list[RemoteWithNetwork] = []
@@ -123,8 +123,7 @@ def read_qr_json(qr_data: dict[str, Any], flake: Flake) -> QRCodeData:
def read_qr_image(image_path: Path) -> dict[str, Any]:
"""
Parse a QR code image and extract the JSON data.
"""Parse a QR code image and extract the JSON data.
Args:
image_path: Path to the QR code image file
@@ -134,6 +133,7 @@ def read_qr_image(image_path: Path) -> dict[str, Any]:
Raises:
ClanError: If the QR code cannot be read or contains invalid JSON
"""
if not image_path.exists():
msg = f"QR code image file not found: {image_path}"

View File

@@ -3,7 +3,6 @@ import time
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING
from clan_lib.errors import ClanError
from clan_lib.network import Network, NetworkTechnologyBase, Peer

View File

@@ -35,10 +35,7 @@ def is_tor_running(proxy_port: int | None = None) -> bool:
# TODO: Move this to network technology tor module
@contextmanager
def spawn_tor() -> Iterator[None]:
"""
Spawns a Tor process using `nix-shell` if Tor is not already running.
"""
"""Spawns a Tor process using `nix-shell` if Tor is not already running."""
# Check if Tor is already running
if is_tor_running():
log.info("Tor is running")
@@ -68,9 +65,7 @@ class TorCheck:
def tor_online_test(proxy_port: int) -> None:
"""
Tests if Tor is online by checking if we can establish a SOCKS5 connection.
"""
"""Tests if Tor is online by checking if we can establish a SOCKS5 connection."""
import socket
# Try to establish a SOCKS5 handshake with the Tor proxy