Skip to content

Commit

Permalink
Simplify check_port by using asyncio.get_running_loop()
Browse files Browse the repository at this point in the history
  • Loading branch information
agners committed Nov 22, 2023
1 parent fe32cc2 commit dde9b06
Show file tree
Hide file tree
Showing 5 changed files with 6 additions and 11 deletions.
2 changes: 1 addition & 1 deletion supervisor/addons/addon.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ async def watchdog_application(self) -> bool:

# TCP monitoring
if s_prefix == "tcp":
return await check_port(self.coresys.loop, self.ip_address, port)
return await check_port(self.ip_address, port)

# lookup the correct protocol from config
if t_proto:
Expand Down
1 change: 0 additions & 1 deletion supervisor/homeassistant/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ async def get_api_state(self) -> str | None:

# Check if port is up
if not await check_port(
self.coresys.loop,
self.sys_homeassistant.ip_address,
self.sys_homeassistant.api_port,
):
Expand Down
4 changes: 1 addition & 3 deletions supervisor/ingress.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,7 @@ async def get_dynamic_port(self, addon_slug: str) -> int:
while (
port is None
or port in self.ports.values()
or await check_port(
self.coresys.loop, self.sys_docker.network.gateway, port
)
or await check_port(self.sys_docker.network.gateway, port)
):
port = random.randint(62000, 65500)

Expand Down
6 changes: 2 additions & 4 deletions supervisor/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,13 @@ async def wrap_api(api, *args, **kwargs):
return wrap_api


async def check_port(
loop: asyncio.AbstractEventLoop, address: IPv4Address, port: int
) -> bool:
async def check_port(address: IPv4Address, port: int) -> bool:
"""Check if port is mapped."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(False)
try:
async with asyncio.timeout(0.5):
await loop.sock_connect(sock, (str(address), port))
await asyncio.get_running_loop().sock_connect(sock, (str(address), port))
except (OSError, TimeoutError):
return False
finally:
Expand Down
4 changes: 2 additions & 2 deletions tests/utils/test_check_port.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@

async def test_exists_open_port(coresys: CoreSys):
"""Test a exists network port."""
assert await check_port(coresys.loop, ip_address("8.8.8.8"), 53)
assert await check_port(ip_address("8.8.8.8"), 53)


async def test_not_exists_port(coresys: CoreSys):
"""Test a not exists network service."""
assert not await check_port(coresys.loop, ip_address("192.0.2.1"), 53)
assert not await check_port(ip_address("192.0.2.1"), 53)

0 comments on commit dde9b06

Please sign in to comment.