Debian Codegraph @

hass_nabucasa/utils.py

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