Debian Codegraph @

hass_nabucasa/utils.py

raw ◀ ▶
1 Debian patch touch this file
1 """Helper methods to handle the time in Home Assistant."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from collections.abc import Awaitable, Callable, Mapping
7 import datetime as dt
8 import logging
9 from logging import Logger
10 import random
11 import ssl
12 from typing import Any, TypedDict, TypeVar
13
14 import ciso8601
15 from icmplib import Host, ICMPLibError, SocketPermissionError, async_multiping
16 import jwt
17
18 from .exceptions import NabuCasaBaseError
19
20 CALLABLE_T = TypeVar("CALLABLE_T", bound=Callable) # pylint: disable=invalid-name
21 UTC = dt.UTC
•22 UNIX_EPOCH = dt.datetime(1970, 1, 1, tzinfo=UTC)
23
24 _LOGGER = logging.getLogger(__name__)
25
26
27 class CheckLatencyError(NabuCasaBaseError):
28 """Error to indicate a ping failure."""
29
30
31 class CheckLatencyInsufficientPrivileges(CheckLatencyError):
32 """Error to indicate insufficient privileges for pinging."""
33
34
35 class CheckLatencyHostResult(TypedDict):
36 """Result of a latency check for a single host."""
37
38 address: str
39 avg_rtt: float
40 is_alive: bool
41 max_rtt: float
42 min_rtt: float
43
44
45 def utcnow() -> dt.datetime:
46 """Get now in UTC time."""
47 return dt.datetime.now(UTC)
48
49
50 def utc_from_timestamp(timestamp: float) -> dt.datetime:
51 """Return a UTC time from a timestamp."""
•52 return UNIX_EPOCH + dt.timedelta(seconds=timestamp)
53
54
55 def parse_date(dt_str: str) -> dt.date | None:
56 """Convert a date string to a date object."""
57 try:
58 return ciso8601.parse_datetime(dt_str).date()
59 except ValueError: # If dt_str did not match our format
60 return None
61
62
63 def seconds_as_dhms(seconds: float) -> str:
64 """Convert seconds to a DDd:HHh:MMm:SSs string."""
65 days, seconds = divmod(int(seconds), 86400)
66 hours, seconds = divmod(seconds, 3600)
67 minutes, seconds = divmod(seconds, 60)
68
69 parts = []
70 if days > 0:
71 parts.append(f"{days}d")
72 if hours > 0 or (parts and (minutes > 0 or seconds > 0)):
73 parts.append(f"{hours}h")
74 if minutes > 0 or (parts and seconds > 0):
75 parts.append(f"{minutes}m")
76 if seconds > 0 or not parts:
77 parts.append(f"{seconds}s")
78 return ":".join(parts)
79
80
81 def expiration_from_token(token: str | None) -> int | None:
82 """Return the expiration time from a token."""
83 if not token:
84 return None
85
86 try:
87 decoded_token: Mapping[str, Any] = jwt.decode(
88 token,
89 options={"verify_signature": False},
90 )
91 return int(decoded_token["exp"])
92 except jwt.DecodeError, KeyError:
93 return None
94
95
96 def server_context_modern() -> ssl.SSLContext:
97 """
98 Return an SSL context following the Mozilla recommendations.
99
100 TLS configuration follows the best-practice guidelines specified here:
101 https://wiki.mozilla.org/Security/Server_Side_TLS
102 Modern guidelines are followed.
103 """
104 context = ssl.SSLContext(ssl.PROTOCOL_TLS) # pylint: disable=no-member
105
106 context.options |= (
107 ssl.OP_NO_SSLv2
108 | ssl.OP_NO_SSLv3
109 | ssl.OP_NO_TLSv1
110 | ssl.OP_NO_TLSv1_1
111 | ssl.OP_CIPHER_SERVER_PREFERENCE
112 )
113 if hasattr(ssl, "OP_NO_COMPRESSION"):
114 context.options |= ssl.OP_NO_COMPRESSION
115
116 context.set_ciphers(
117 "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
118 "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:"
119 "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
120 "ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:"
121 "ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256",
122 )
123
124 return context
125
126
127 def next_midnight() -> float:
128 """Return the seconds till next local midnight."""
129 midnight = dt.datetime.now().replace(
130 hour=0,
131 minute=0,
132 second=0,
133 microsecond=0,
134 ) + dt.timedelta(days=1)
135 return (midnight - dt.datetime.now()).total_seconds()
136
137
138 async def async_check_latency(
139 addresses: list[str],
140 *,
141 count: int = 1,
142 ping_timeout: float = 5,
143 privileged: bool = True,
144 ) -> list[CheckLatencyHostResult]:
145 """Check latency to a list of IP addresses and return them.
146
147 Args:
148 addresses: List of IP addresses to ping.
149 count: Number of ping packets to send to each address.
150 ping_timeout: Timeout in seconds for each ping.
151 privileged: Whether to use privileged (raw socket) mode.
152
153 Returns:
154 List of CheckLatencyHostResult dicts.
155
156 """
157 if not addresses:
158 raise CheckLatencyError("No addresses provided")
159
160 hosts: list[Host]
161 try:
162 hosts = await async_multiping(
163 addresses=addresses,
164 count=count,
165 timeout=ping_timeout,
166 privileged=privileged,
167 )
168 except SocketPermissionError as err:
169 if not privileged:
170 raise CheckLatencyInsufficientPrivileges(
171 "Insufficient privileges to perform ICMP ping."
172 ) from err
173 _LOGGER.info(
174 "Ping failed due to insufficient privileges, "
175 "retrying without privileged mode"
176 )
177 return await async_check_latency(
178 addresses,
179 count=count,
180 ping_timeout=ping_timeout,
181 privileged=False,
182 )
183 except ICMPLibError as err:
184 raise CheckLatencyError("ICMP ping failed") from err
185
186 return [
187 CheckLatencyHostResult(
188 address=host.address,
189 is_alive=host.is_alive,
190 avg_rtt=host.avg_rtt,
191 max_rtt=host.max_rtt,
192 min_rtt=host.min_rtt,
193 )
194 for host in hosts
195 ]
196
197
198 def jitter(minimum: float, maximum: float) -> float:
199 """Return a random float between minimum and maximum for backoff jitter."""
200 return random.uniform(minimum, maximum)
201
202
203 async def gather_callbacks(
204 logger: Logger,
205 name: str,
206 callbacks: list[Callable[[], Awaitable[None]]],
207 ) -> None:
208 """Gather callbacks and log exceptions."""
209 results = await asyncio.gather(*[cb() for cb in callbacks], return_exceptions=True)
210 for result, callback in zip(results, callbacks, strict=False):
211 if not isinstance(result, Exception):
212 continue
213 logger.error(
214 "Unexpected error in %s callback %s", name, callback, exc_info=result
215 )
216
217
218 class Registry(dict):
219 """Registry of items."""
220
221 def register(self, name: str) -> Callable[[CALLABLE_T], CALLABLE_T]:
222 """Return decorator to register item with a specific name."""
223
224 def decorator(func: CALLABLE_T) -> CALLABLE_T:
225 """Register decorated function."""
226 self[name] = func
227 return func
228
229 return decorator