forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.py
2675 lines (2224 loc) · 90.1 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Core components of Home Assistant.
Home Assistant is a Home Automation framework for observing the state
of entities and react to changes.
"""
from __future__ import annotations
import asyncio
from collections import UserDict, defaultdict
from collections.abc import (
Callable,
Collection,
Coroutine,
Iterable,
KeysView,
Mapping,
ValuesView,
)
import concurrent.futures
from contextlib import suppress
from dataclasses import dataclass
import datetime
import enum
import functools
import logging
import os
import pathlib
import re
import threading
import time
from time import monotonic
from typing import (
TYPE_CHECKING,
Any,
Generic,
Literal,
ParamSpec,
Self,
TypeVar,
cast,
overload,
)
from urllib.parse import urlparse
import voluptuous as vol
import yarl
from . import block_async_io, util
from .const import (
ATTR_DOMAIN,
ATTR_FRIENDLY_NAME,
ATTR_SERVICE,
ATTR_SERVICE_DATA,
COMPRESSED_STATE_ATTRIBUTES,
COMPRESSED_STATE_CONTEXT,
COMPRESSED_STATE_LAST_CHANGED,
COMPRESSED_STATE_LAST_UPDATED,
COMPRESSED_STATE_STATE,
EVENT_CALL_SERVICE,
EVENT_CORE_CONFIG_UPDATE,
EVENT_HOMEASSISTANT_CLOSE,
EVENT_HOMEASSISTANT_FINAL_WRITE,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STARTED,
EVENT_HOMEASSISTANT_STOP,
EVENT_SERVICE_REGISTERED,
EVENT_SERVICE_REMOVED,
EVENT_STATE_CHANGED,
MATCH_ALL,
MAX_LENGTH_EVENT_EVENT_TYPE,
MAX_LENGTH_STATE_STATE,
UnitOfLength,
__version__,
)
from .exceptions import (
HomeAssistantError,
InvalidEntityFormatError,
InvalidStateError,
MaxLengthExceeded,
ServiceNotFound,
Unauthorized,
)
from .helpers.deprecation import (
DeprecatedConstantEnum,
all_with_deprecated_constants,
check_if_deprecated_constant,
dir_with_deprecated_constants,
)
from .helpers.json import json_bytes, json_fragment
from .util import dt as dt_util, location
from .util.async_ import (
cancelling,
run_callback_threadsafe,
shutdown_run_callback_threadsafe,
)
from .util.json import JsonObjectType
from .util.read_only_dict import ReadOnlyDict
from .util.timeout import TimeoutManager
from .util.ulid import ulid_at_time, ulid_now
from .util.unit_system import (
_CONF_UNIT_SYSTEM_IMPERIAL,
_CONF_UNIT_SYSTEM_US_CUSTOMARY,
METRIC_SYSTEM,
UnitSystem,
get_unit_system,
)
# Typing imports that create a circular dependency
if TYPE_CHECKING:
from functools import cached_property
from .auth import AuthManager
from .components.http import ApiConfig, HomeAssistantHTTP
from .config_entries import ConfigEntries
from .helpers.entity import StateInfo
else:
from .backports.functools import cached_property
STOPPING_STAGE_SHUTDOWN_TIMEOUT = 20
STOP_STAGE_SHUTDOWN_TIMEOUT = 100
FINAL_WRITE_STAGE_SHUTDOWN_TIMEOUT = 60
CLOSE_STAGE_SHUTDOWN_TIMEOUT = 30
block_async_io.enable()
_T = TypeVar("_T")
_R = TypeVar("_R")
_R_co = TypeVar("_R_co", covariant=True)
_P = ParamSpec("_P")
# Internal; not helpers.typing.UNDEFINED due to circular dependency
_UNDEF: dict[Any, Any] = {}
_CallableT = TypeVar("_CallableT", bound=Callable[..., Any])
CALLBACK_TYPE = Callable[[], None]
CORE_STORAGE_KEY = "core.config"
CORE_STORAGE_VERSION = 1
CORE_STORAGE_MINOR_VERSION = 3
DOMAIN = "homeassistant"
# How long to wait to log tasks that are blocking
BLOCK_LOG_TIMEOUT = 60
ServiceResponse = JsonObjectType | None
EntityServiceResponse = dict[str, ServiceResponse]
class ConfigSource(enum.StrEnum):
"""Source of core configuration."""
DEFAULT = "default"
DISCOVERED = "discovered"
STORAGE = "storage"
YAML = "yaml"
# SOURCE_* are deprecated as of Home Assistant 2022.2, use ConfigSource instead
_DEPRECATED_SOURCE_DISCOVERED = DeprecatedConstantEnum(
ConfigSource.DISCOVERED, "2025.1"
)
_DEPRECATED_SOURCE_STORAGE = DeprecatedConstantEnum(ConfigSource.STORAGE, "2025.1")
_DEPRECATED_SOURCE_YAML = DeprecatedConstantEnum(ConfigSource.YAML, "2025.1")
# How long to wait until things that run on startup have to finish.
TIMEOUT_EVENT_START = 15
MAX_EXPECTED_ENTITY_IDS = 16384
_LOGGER = logging.getLogger(__name__)
@functools.lru_cache(MAX_EXPECTED_ENTITY_IDS)
def split_entity_id(entity_id: str) -> tuple[str, str]:
"""Split a state entity ID into domain and object ID."""
domain, _, object_id = entity_id.partition(".")
if not domain or not object_id:
raise ValueError(f"Invalid entity ID {entity_id}")
return domain, object_id
_OBJECT_ID = r"(?!_)[\da-z_]+(?<!_)"
_DOMAIN = r"(?!.+__)" + _OBJECT_ID
VALID_DOMAIN = re.compile(r"^" + _DOMAIN + r"$")
VALID_ENTITY_ID = re.compile(r"^" + _DOMAIN + r"\." + _OBJECT_ID + r"$")
@functools.lru_cache(64)
def valid_domain(domain: str) -> bool:
"""Test if a domain a valid format."""
return VALID_DOMAIN.match(domain) is not None
@functools.lru_cache(512)
def valid_entity_id(entity_id: str) -> bool:
"""Test if an entity ID is a valid format.
Format: <domain>.<entity> where both are slugs.
"""
return VALID_ENTITY_ID.match(entity_id) is not None
def validate_state(state: str) -> str:
"""Validate a state, raise if it not valid."""
if len(state) > MAX_LENGTH_STATE_STATE:
raise InvalidStateError(
f"Invalid state with length {len(state)}. "
"State max length is 255 characters."
)
return state
def callback(func: _CallableT) -> _CallableT:
"""Annotation to mark method as safe to call from within the event loop."""
setattr(func, "_hass_callback", True)
return func
def is_callback(func: Callable[..., Any]) -> bool:
"""Check if function is safe to be called in the event loop."""
return getattr(func, "_hass_callback", False) is True
def is_callback_check_partial(target: Callable[..., Any]) -> bool:
"""Check if function is safe to be called in the event loop.
This version of is_callback will also check if the target is a partial
and walk the chain of partials to find the original function.
"""
check_target = target
while isinstance(check_target, functools.partial):
check_target = check_target.func
return is_callback(check_target)
class _Hass(threading.local):
"""Container which makes a HomeAssistant instance available to the event loop."""
hass: HomeAssistant | None = None
_hass = _Hass()
@callback
def async_get_hass() -> HomeAssistant:
"""Return the HomeAssistant instance.
Raises HomeAssistantError when called from the wrong thread.
This should be used where it's very cumbersome or downright impossible to pass
hass to the code which needs it.
"""
if not _hass.hass:
raise HomeAssistantError("async_get_hass called from the wrong thread")
return _hass.hass
@callback
def get_release_channel() -> Literal["beta", "dev", "nightly", "stable"]:
"""Find release channel based on version number."""
version = __version__
if "dev0" in version:
return "dev"
if "dev" in version:
return "nightly"
if "b" in version:
return "beta"
return "stable"
@enum.unique
class HassJobType(enum.Enum):
"""Represent a job type."""
Coroutinefunction = 1
Callback = 2
Executor = 3
class HassJob(Generic[_P, _R_co]):
"""Represent a job to be run later.
We check the callable type in advance
so we can avoid checking it every time
we run the job.
"""
__slots__ = ("job_type", "target", "name", "_cancel_on_shutdown")
def __init__(
self,
target: Callable[_P, _R_co],
name: str | None = None,
*,
cancel_on_shutdown: bool | None = None,
job_type: HassJobType | None = None,
) -> None:
"""Create a job object."""
self.target = target
self.name = name
self.job_type = job_type or _get_hassjob_callable_job_type(target)
self._cancel_on_shutdown = cancel_on_shutdown
@property
def cancel_on_shutdown(self) -> bool | None:
"""Return if the job should be cancelled on shutdown."""
return self._cancel_on_shutdown
def __repr__(self) -> str:
"""Return the job."""
return f"<Job {self.name} {self.job_type} {self.target}>"
@dataclass(frozen=True)
class HassJobWithArgs:
"""Container for a HassJob and arguments."""
job: HassJob[..., Coroutine[Any, Any, Any] | Any]
args: Iterable[Any]
def _get_hassjob_callable_job_type(target: Callable[..., Any]) -> HassJobType:
"""Determine the job type from the callable."""
# Check for partials to properly determine if coroutine function
check_target = target
while isinstance(check_target, functools.partial):
check_target = check_target.func
if asyncio.iscoroutinefunction(check_target):
return HassJobType.Coroutinefunction
if is_callback(check_target):
return HassJobType.Callback
if asyncio.iscoroutine(check_target):
raise ValueError("Coroutine not allowed to be passed to HassJob")
return HassJobType.Executor
class CoreState(enum.Enum):
"""Represent the current state of Home Assistant."""
not_running = "NOT_RUNNING"
starting = "STARTING"
running = "RUNNING"
stopping = "STOPPING"
final_write = "FINAL_WRITE"
stopped = "STOPPED"
def __str__(self) -> str:
"""Return the event."""
return self.value
class HomeAssistant:
"""Root object of the Home Assistant home automation."""
auth: AuthManager
http: HomeAssistantHTTP = None # type: ignore[assignment]
config_entries: ConfigEntries = None # type: ignore[assignment]
def __new__(cls, config_dir: str) -> HomeAssistant:
"""Set the _hass thread local data."""
hass = super().__new__(cls)
_hass.hass = hass
return hass
def __repr__(self) -> str:
"""Return the representation."""
return f"<HomeAssistant {self.state}>"
def __init__(self, config_dir: str) -> None:
"""Initialize new Home Assistant object."""
# pylint: disable-next=import-outside-toplevel
from . import loader
self.loop = asyncio.get_running_loop()
self._tasks: set[asyncio.Future[Any]] = set()
self._background_tasks: set[asyncio.Future[Any]] = set()
self.bus = EventBus(self)
self.services = ServiceRegistry(self)
self.states = StateMachine(self.bus, self.loop)
self.config = Config(self, config_dir)
self.components = loader.Components(self)
self.helpers = loader.Helpers(self)
# This is a dictionary that any component can store any data on.
self.data: dict[str, Any] = {}
self.state: CoreState = CoreState.not_running
self.exit_code: int = 0
# If not None, use to signal end-of-loop
self._stopped: asyncio.Event | None = None
# Timeout handler for Core/Helper namespace
self.timeout: TimeoutManager = TimeoutManager()
self._stop_future: concurrent.futures.Future[None] | None = None
self._shutdown_jobs: list[HassJobWithArgs] = []
@cached_property
def is_running(self) -> bool:
"""Return if Home Assistant is running."""
return self.state in (CoreState.starting, CoreState.running)
@cached_property
def is_stopping(self) -> bool:
"""Return if Home Assistant is stopping."""
return self.state in (CoreState.stopping, CoreState.final_write)
def set_state(self, state: CoreState) -> None:
"""Set the current state."""
self.state = state
for prop in ("is_running", "is_stopping"):
with suppress(AttributeError):
delattr(self, prop)
def start(self) -> int:
"""Start Home Assistant.
Note: This function is only used for testing.
For regular use, use "await hass.run()".
"""
# Register the async start
_future = asyncio.run_coroutine_threadsafe(self.async_start(), self.loop)
# Run forever
# Block until stopped
_LOGGER.info("Starting Home Assistant core loop")
self.loop.run_forever()
# The future is never retrieved but we still hold a reference to it
# to prevent the task from being garbage collected prematurely.
del _future
return self.exit_code
async def async_run(self, *, attach_signals: bool = True) -> int:
"""Home Assistant main entry point.
Start Home Assistant and block until stopped.
This method is a coroutine.
"""
if self.state is not CoreState.not_running:
raise RuntimeError("Home Assistant is already running")
# _async_stop will set this instead of stopping the loop
self._stopped = asyncio.Event()
await self.async_start()
if attach_signals:
# pylint: disable-next=import-outside-toplevel
from .helpers.signal import async_register_signal_handling
async_register_signal_handling(self)
await self._stopped.wait()
return self.exit_code
async def async_start(self) -> None:
"""Finalize startup from inside the event loop.
This method is a coroutine.
"""
_LOGGER.info("Starting Home Assistant")
setattr(self.loop, "_thread_ident", threading.get_ident())
self.set_state(CoreState.starting)
self.bus.async_fire(EVENT_CORE_CONFIG_UPDATE)
self.bus.async_fire(EVENT_HOMEASSISTANT_START)
if not self._tasks:
pending: set[asyncio.Future[Any]] | None = None
else:
_done, pending = await asyncio.wait(
self._tasks, timeout=TIMEOUT_EVENT_START
)
if pending:
_LOGGER.warning(
(
"Something is blocking Home Assistant from wrapping up the start up"
" phase. We're going to continue anyway. Please report the"
" following info at"
" https://github.com/home-assistant/core/issues: %s"
),
", ".join(self.config.components),
)
# Allow automations to set up the start triggers before changing state
await asyncio.sleep(0)
if self.state is not CoreState.starting:
_LOGGER.warning(
"Home Assistant startup has been interrupted. "
"Its state may be inconsistent"
)
return
self.set_state(CoreState.running)
self.bus.async_fire(EVENT_CORE_CONFIG_UPDATE)
self.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
def add_job(
self, target: Callable[..., Any] | Coroutine[Any, Any, Any], *args: Any
) -> None:
"""Add a job to be executed by the event loop or by an executor.
If the job is either a coroutine or decorated with @callback, it will be
run by the event loop, if not it will be run by an executor.
target: target to call.
args: parameters for method to call.
"""
if target is None:
raise ValueError("Don't call add_job with None")
self.loop.call_soon_threadsafe(self.async_add_job, target, *args)
@overload
@callback
def async_add_job(
self, target: Callable[..., Coroutine[Any, Any, _R]], *args: Any
) -> asyncio.Future[_R] | None:
...
@overload
@callback
def async_add_job(
self, target: Callable[..., Coroutine[Any, Any, _R] | _R], *args: Any
) -> asyncio.Future[_R] | None:
...
@overload
@callback
def async_add_job(
self, target: Coroutine[Any, Any, _R], *args: Any
) -> asyncio.Future[_R] | None:
...
@callback
def async_add_job(
self,
target: Callable[..., Coroutine[Any, Any, _R] | _R] | Coroutine[Any, Any, _R],
*args: Any,
) -> asyncio.Future[_R] | None:
"""Add a job to be executed by the event loop or by an executor.
If the job is either a coroutine or decorated with @callback, it will be
run by the event loop, if not it will be run by an executor.
This method must be run in the event loop.
target: target to call.
args: parameters for method to call.
"""
if target is None:
raise ValueError("Don't call async_add_job with None")
if asyncio.iscoroutine(target):
return self.async_create_task(target)
# This code path is performance sensitive and uses
# if TYPE_CHECKING to avoid the overhead of constructing
# the type used for the cast. For history see:
# https://github.com/home-assistant/core/pull/71960
if TYPE_CHECKING:
target = cast(Callable[..., Coroutine[Any, Any, _R] | _R], target)
return self.async_add_hass_job(HassJob(target), *args)
@overload
@callback
def async_add_hass_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, _R]], *args: Any
) -> asyncio.Future[_R] | None:
...
@overload
@callback
def async_add_hass_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R], *args: Any
) -> asyncio.Future[_R] | None:
...
@callback
def async_add_hass_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R], *args: Any
) -> asyncio.Future[_R] | None:
"""Add a HassJob from within the event loop.
This method must be run in the event loop.
hassjob: HassJob to call.
args: parameters for method to call.
"""
task: asyncio.Future[_R]
# This code path is performance sensitive and uses
# if TYPE_CHECKING to avoid the overhead of constructing
# the type used for the cast. For history see:
# https://github.com/home-assistant/core/pull/71960
if hassjob.job_type is HassJobType.Coroutinefunction:
if TYPE_CHECKING:
hassjob.target = cast(
Callable[..., Coroutine[Any, Any, _R]], hassjob.target
)
task = self.loop.create_task(hassjob.target(*args), name=hassjob.name)
elif hassjob.job_type is HassJobType.Callback:
if TYPE_CHECKING:
hassjob.target = cast(Callable[..., _R], hassjob.target)
self.loop.call_soon(hassjob.target, *args)
return None
else:
if TYPE_CHECKING:
hassjob.target = cast(Callable[..., _R], hassjob.target)
task = self.loop.run_in_executor(None, hassjob.target, *args)
self._tasks.add(task)
task.add_done_callback(self._tasks.remove)
return task
def create_task(
self, target: Coroutine[Any, Any, Any], name: str | None = None
) -> None:
"""Add task to the executor pool.
target: target to call.
"""
self.loop.call_soon_threadsafe(self.async_create_task, target, name)
@callback
def async_create_task(
self, target: Coroutine[Any, Any, _R], name: str | None = None
) -> asyncio.Task[_R]:
"""Create a task from within the event loop.
This method must be run in the event loop. If you are using this in your
integration, use the create task methods on the config entry instead.
target: target to call.
"""
task = self.loop.create_task(target, name=name)
self._tasks.add(task)
task.add_done_callback(self._tasks.remove)
return task
@callback
def async_create_background_task(
self,
target: Coroutine[Any, Any, _R],
name: str,
) -> asyncio.Task[_R]:
"""Create a task from within the event loop.
This is a background task which will not block startup and will be
automatically cancelled on shutdown. If you are using this in your
integration, use the create task methods on the config entry instead.
This method must be run in the event loop.
"""
task = self.loop.create_task(target, name=name)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.remove)
return task
@callback
def async_add_executor_job(
self, target: Callable[..., _T], *args: Any
) -> asyncio.Future[_T]:
"""Add an executor job from within the event loop."""
task = self.loop.run_in_executor(None, target, *args)
self._tasks.add(task)
task.add_done_callback(self._tasks.remove)
return task
@overload
@callback
def async_run_hass_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, _R]], *args: Any
) -> asyncio.Future[_R] | None:
...
@overload
@callback
def async_run_hass_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R], *args: Any
) -> asyncio.Future[_R] | None:
...
@callback
def async_run_hass_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R], *args: Any
) -> asyncio.Future[_R] | None:
"""Run a HassJob from within the event loop.
This method must be run in the event loop.
hassjob: HassJob
args: parameters for method to call.
"""
# This code path is performance sensitive and uses
# if TYPE_CHECKING to avoid the overhead of constructing
# the type used for the cast. For history see:
# https://github.com/home-assistant/core/pull/71960
if hassjob.job_type is HassJobType.Callback:
if TYPE_CHECKING:
hassjob.target = cast(Callable[..., _R], hassjob.target)
hassjob.target(*args)
return None
return self.async_add_hass_job(hassjob, *args)
@overload
@callback
def async_run_job(
self, target: Callable[..., Coroutine[Any, Any, _R]], *args: Any
) -> asyncio.Future[_R] | None:
...
@overload
@callback
def async_run_job(
self, target: Callable[..., Coroutine[Any, Any, _R] | _R], *args: Any
) -> asyncio.Future[_R] | None:
...
@overload
@callback
def async_run_job(
self, target: Coroutine[Any, Any, _R], *args: Any
) -> asyncio.Future[_R] | None:
...
@callback
def async_run_job(
self,
target: Callable[..., Coroutine[Any, Any, _R] | _R] | Coroutine[Any, Any, _R],
*args: Any,
) -> asyncio.Future[_R] | None:
"""Run a job from within the event loop.
This method must be run in the event loop.
target: target to call.
args: parameters for method to call.
"""
if asyncio.iscoroutine(target):
return self.async_create_task(target)
# This code path is performance sensitive and uses
# if TYPE_CHECKING to avoid the overhead of constructing
# the type used for the cast. For history see:
# https://github.com/home-assistant/core/pull/71960
if TYPE_CHECKING:
target = cast(Callable[..., Coroutine[Any, Any, _R] | _R], target)
return self.async_run_hass_job(HassJob(target), *args)
def block_till_done(self) -> None:
"""Block until all pending work is done."""
asyncio.run_coroutine_threadsafe(
self.async_block_till_done(), self.loop
).result()
async def async_block_till_done(self) -> None:
"""Block until all pending work is done."""
# To flush out any call_soon_threadsafe
await asyncio.sleep(0)
start_time: float | None = None
current_task = asyncio.current_task()
while tasks := [
task
for task in self._tasks
if task is not current_task and not cancelling(task)
]:
await self._await_and_log_pending(tasks)
if start_time is None:
# Avoid calling monotonic() until we know
# we may need to start logging blocked tasks.
start_time = 0
elif start_time == 0:
# If we have waited twice then we set the start
# time
start_time = monotonic()
elif monotonic() - start_time > BLOCK_LOG_TIMEOUT:
# We have waited at least three loops and new tasks
# continue to block. At this point we start
# logging all waiting tasks.
for task in tasks:
_LOGGER.debug("Waiting for task: %s", task)
async def _await_and_log_pending(
self, pending: Collection[asyncio.Future[Any]]
) -> None:
"""Await and log tasks that take a long time."""
wait_time = 0
while pending:
_, pending = await asyncio.wait(pending, timeout=BLOCK_LOG_TIMEOUT)
if not pending:
return
wait_time += BLOCK_LOG_TIMEOUT
for task in pending:
_LOGGER.debug("Waited %s seconds for task: %s", wait_time, task)
@overload
@callback
def async_add_shutdown_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, Any]], *args: Any
) -> CALLBACK_TYPE:
...
@overload
@callback
def async_add_shutdown_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, Any] | Any], *args: Any
) -> CALLBACK_TYPE:
...
@callback
def async_add_shutdown_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, Any] | Any], *args: Any
) -> CALLBACK_TYPE:
"""Add a HassJob which will be executed on shutdown.
This method must be run in the event loop.
hassjob: HassJob
args: parameters for method to call.
Returns function to remove the job.
"""
job_with_args = HassJobWithArgs(hassjob, args)
self._shutdown_jobs.append(job_with_args)
@callback
def remove_job() -> None:
self._shutdown_jobs.remove(job_with_args)
return remove_job
def stop(self) -> None:
"""Stop Home Assistant and shuts down all threads."""
if self.state is CoreState.not_running: # just ignore
return
# The future is never retrieved, and we only hold a reference
# to it to prevent it from being garbage collected.
self._stop_future = asyncio.run_coroutine_threadsafe(
self.async_stop(), self.loop
)
async def async_stop(self, exit_code: int = 0, *, force: bool = False) -> None:
"""Stop Home Assistant and shuts down all threads.
The "force" flag commands async_stop to proceed regardless of
Home Assistant's current state. You should not set this flag
unless you're testing.
This method is a coroutine.
"""
if not force:
# Some tests require async_stop to run,
# regardless of the state of the loop.
if self.state is CoreState.not_running: # just ignore
return
if self.state in [CoreState.stopping, CoreState.final_write]:
_LOGGER.info("Additional call to async_stop was ignored")
return
if self.state is CoreState.starting:
# This may not work
_LOGGER.warning(
"Stopping Home Assistant before startup has completed may fail"
)
# Stage 1 - Run shutdown jobs
try:
async with self.timeout.async_timeout(STOPPING_STAGE_SHUTDOWN_TIMEOUT):
tasks: list[asyncio.Future[Any]] = []
for job in self._shutdown_jobs:
task_or_none = self.async_run_hass_job(job.job, *job.args)
if not task_or_none:
continue
tasks.append(task_or_none)
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
except TimeoutError:
_LOGGER.warning(
"Timed out waiting for shutdown jobs to complete, the shutdown will"
" continue"
)
self._async_log_running_tasks("run shutdown jobs")
# Stage 2 - Stop integrations
# Keep holding the reference to the tasks but do not allow them
# to block shutdown. Only tasks created after this point will
# be waited for.
running_tasks = self._tasks
# Avoid clearing here since we want the remove callbacks to fire
# and remove the tasks from the original set which is now running_tasks
self._tasks = set()
# Cancel all background tasks
for task in self._background_tasks:
self._tasks.add(task)
task.add_done_callback(self._tasks.remove)
task.cancel("Home Assistant is stopping")
self._cancel_cancellable_timers()
self.exit_code = exit_code
self.set_state(CoreState.stopping)
self.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
try:
async with self.timeout.async_timeout(STOP_STAGE_SHUTDOWN_TIMEOUT):
await self.async_block_till_done()
except TimeoutError:
_LOGGER.warning(
"Timed out waiting for integrations to stop, the shutdown will"
" continue"
)
self._async_log_running_tasks("stop integrations")
# Stage 3 - Final write
self.set_state(CoreState.final_write)
self.bus.async_fire(EVENT_HOMEASSISTANT_FINAL_WRITE)
try:
async with self.timeout.async_timeout(FINAL_WRITE_STAGE_SHUTDOWN_TIMEOUT):
await self.async_block_till_done()
except TimeoutError:
_LOGGER.warning(
"Timed out waiting for final writes to complete, the shutdown will"
" continue"
)
self._async_log_running_tasks("final write")
# Stage 4 - Close
self.set_state(CoreState.not_running)
self.bus.async_fire(EVENT_HOMEASSISTANT_CLOSE)
# Make a copy of running_tasks since a task can finish
# while we are awaiting canceled tasks to get their result
# which will result in the set size changing during iteration
for task in list(running_tasks):
if task.done() or cancelling(task):
# Since we made a copy we need to check
# to see if the task finished while we
# were awaiting another task
continue
_LOGGER.warning(
"Task %s was still running after final writes shutdown stage; "
"Integrations should cancel non-critical tasks when receiving "
"the stop event to prevent delaying shutdown",
task,
)
task.cancel("Home Assistant final writes shutdown stage")
try:
async with asyncio.timeout(0.1):
await task
except asyncio.CancelledError:
pass
except TimeoutError:
# Task may be shielded from cancellation.
_LOGGER.exception(
"Task %s could not be canceled during final shutdown stage", task
)
except Exception as exc: # pylint: disable=broad-except
_LOGGER.exception(
"Task %s error during final shutdown stage: %s", task, exc
)
# Prevent run_callback_threadsafe from scheduling any additional
# callbacks in the event loop as callbacks created on the futures
# it returns will never run after the final `self.async_block_till_done`
# which will cause the futures to block forever when waiting for
# the `result()` which will cause a deadlock when shutting down the executor.
shutdown_run_callback_threadsafe(self.loop)
try:
async with self.timeout.async_timeout(CLOSE_STAGE_SHUTDOWN_TIMEOUT):
await self.async_block_till_done()
except TimeoutError:
_LOGGER.warning(
"Timed out waiting for close event to be processed, the shutdown will"
" continue"
)
self._async_log_running_tasks("close")
self.set_state(CoreState.stopped)
if self._stopped is not None:
self._stopped.set()
def _cancel_cancellable_timers(self) -> None:
"""Cancel timer handles marked as cancellable."""
# pylint: disable-next=protected-access
handles: Iterable[asyncio.TimerHandle] = self.loop._scheduled # type: ignore[attr-defined]
for handle in handles:
if (
not handle.cancelled()
and (args := handle._args) # pylint: disable=protected-access
and type(job := args[0]) is HassJob # noqa: E721
and job.cancel_on_shutdown
):
handle.cancel()
def _async_log_running_tasks(self, stage: str) -> None:
"""Log all running tasks."""