-
-
Notifications
You must be signed in to change notification settings - Fork 32.1k
/
Copy pathconfig_entries.py
3332 lines (2842 loc) · 122 KB
/
config_entries.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
"""Manage config entries in Home Assistant."""
from __future__ import annotations
import asyncio
from collections import UserDict, defaultdict
from collections.abc import (
Callable,
Coroutine,
Generator,
Hashable,
Iterable,
Mapping,
ValuesView,
)
from contextvars import ContextVar
from copy import deepcopy
from datetime import datetime
from enum import Enum, StrEnum
import functools
from functools import cache
import logging
from random import randint
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Self, cast
from async_interrupt import interrupt
from propcache.api import cached_property
import voluptuous as vol
from . import data_entry_flow, loader
from .components import persistent_notification
from .const import (
CONF_NAME,
EVENT_HOMEASSISTANT_STARTED,
EVENT_HOMEASSISTANT_STOP,
Platform,
)
from .core import (
CALLBACK_TYPE,
DOMAIN as HOMEASSISTANT_DOMAIN,
CoreState,
Event,
HassJob,
HassJobType,
HomeAssistant,
callback,
)
from .data_entry_flow import FLOW_NOT_COMPLETE_STEPS, FlowContext, FlowResult
from .exceptions import (
ConfigEntryAuthFailed,
ConfigEntryError,
ConfigEntryNotReady,
HomeAssistantError,
)
from .helpers import (
device_registry as dr,
entity_registry as er,
issue_registry as ir,
storage,
)
from .helpers.debounce import Debouncer
from .helpers.discovery_flow import DiscoveryKey
from .helpers.dispatcher import SignalType, async_dispatcher_send_internal
from .helpers.event import (
RANDOM_MICROSECOND_MAX,
RANDOM_MICROSECOND_MIN,
async_call_later,
)
from .helpers.frame import ReportBehavior, report_usage
from .helpers.json import json_bytes, json_bytes_sorted, json_fragment
from .helpers.typing import UNDEFINED, ConfigType, DiscoveryInfoType, UndefinedType
from .loader import async_suggest_report_issue
from .setup import (
DATA_SETUP_DONE,
SetupPhases,
async_pause_setup,
async_process_deps_reqs,
async_setup_component,
async_start_setup,
)
from .util import ulid as ulid_util
from .util.async_ import create_eager_task
from .util.decorator import Registry
from .util.dt import utc_from_timestamp, utcnow
from .util.enum import try_parse_enum
if TYPE_CHECKING:
from .components.bluetooth import BluetoothServiceInfoBleak
from .helpers.service_info.dhcp import DhcpServiceInfo
from .helpers.service_info.hassio import HassioServiceInfo
from .helpers.service_info.mqtt import MqttServiceInfo
from .helpers.service_info.ssdp import SsdpServiceInfo
from .helpers.service_info.usb import UsbServiceInfo
from .helpers.service_info.zeroconf import ZeroconfServiceInfo
_LOGGER = logging.getLogger(__name__)
SOURCE_BLUETOOTH = "bluetooth"
SOURCE_DHCP = "dhcp"
SOURCE_DISCOVERY = "discovery"
SOURCE_HARDWARE = "hardware"
SOURCE_HASSIO = "hassio"
SOURCE_HOMEKIT = "homekit"
SOURCE_IMPORT = "import"
SOURCE_INTEGRATION_DISCOVERY = "integration_discovery"
SOURCE_MQTT = "mqtt"
SOURCE_SSDP = "ssdp"
SOURCE_SYSTEM = "system"
SOURCE_USB = "usb"
SOURCE_USER = "user"
SOURCE_ZEROCONF = "zeroconf"
# If a user wants to hide a discovery from the UI they can "Ignore" it. The
# config_entries/ignore_flow websocket command creates a config entry with this
# source and while it exists normal discoveries with the same unique id are ignored.
SOURCE_IGNORE = "ignore"
# This is used to signal that re-authentication is required by the user.
SOURCE_REAUTH = "reauth"
# This is used to initiate a reconfigure flow by the user.
SOURCE_RECONFIGURE = "reconfigure"
HANDLERS: Registry[str, type[ConfigFlow]] = Registry()
STORAGE_KEY = "core.config_entries"
STORAGE_VERSION = 1
STORAGE_VERSION_MINOR = 4
SAVE_DELAY = 1
DISCOVERY_COOLDOWN = 1
ISSUE_UNIQUE_ID_COLLISION = "config_entry_unique_id_collision"
UNIQUE_ID_COLLISION_TITLE_LIMIT = 5
class ConfigEntryState(Enum):
"""Config entry state."""
LOADED = "loaded", True
"""The config entry has been set up successfully"""
SETUP_ERROR = "setup_error", True
"""There was an error while trying to set up this config entry"""
MIGRATION_ERROR = "migration_error", False
"""There was an error while trying to migrate the config entry to a new version"""
SETUP_RETRY = "setup_retry", True
"""The config entry was not ready to be set up yet, but might be later"""
NOT_LOADED = "not_loaded", True
"""The config entry has not been loaded"""
FAILED_UNLOAD = "failed_unload", False
"""An error occurred when trying to unload the entry"""
SETUP_IN_PROGRESS = "setup_in_progress", False
"""The config entry is setting up."""
_recoverable: bool
def __new__(cls, value: str, recoverable: bool) -> Self:
"""Create new ConfigEntryState."""
obj = object.__new__(cls)
obj._value_ = value
obj._recoverable = recoverable # noqa: SLF001
return obj
@property
def recoverable(self) -> bool:
"""Get if the state is recoverable.
If the entry state is recoverable, unloads
and reloads are allowed.
"""
return self._recoverable
DEFAULT_DISCOVERY_UNIQUE_ID = "default_discovery_unique_id"
DISCOVERY_NOTIFICATION_ID = "config_entry_discovery"
DISCOVERY_SOURCES = {
SOURCE_BLUETOOTH,
SOURCE_DHCP,
SOURCE_DISCOVERY,
SOURCE_HARDWARE,
SOURCE_HASSIO,
SOURCE_HOMEKIT,
SOURCE_IMPORT,
SOURCE_INTEGRATION_DISCOVERY,
SOURCE_MQTT,
SOURCE_SSDP,
SOURCE_SYSTEM,
SOURCE_USB,
SOURCE_ZEROCONF,
}
RECONFIGURE_NOTIFICATION_ID = "config_entry_reconfigure"
EVENT_FLOW_DISCOVERED = "config_entry_discovered"
SIGNAL_CONFIG_ENTRY_CHANGED = SignalType["ConfigEntryChange", "ConfigEntry"](
"config_entry_changed"
)
@cache
def signal_discovered_config_entry_removed(
discovery_domain: str,
) -> SignalType[ConfigEntry]:
"""Format signal."""
return SignalType(f"{discovery_domain}_discovered_config_entry_removed")
NO_RESET_TRIES_STATES = {
ConfigEntryState.SETUP_RETRY,
ConfigEntryState.SETUP_IN_PROGRESS,
}
class ConfigEntryChange(StrEnum):
"""What was changed in a config entry."""
ADDED = "added"
REMOVED = "removed"
UPDATED = "updated"
class ConfigEntryDisabler(StrEnum):
"""What disabled a config entry."""
USER = "user"
# DISABLED_* is deprecated, to be removed in 2022.3
DISABLED_USER = ConfigEntryDisabler.USER.value
RELOAD_AFTER_UPDATE_DELAY = 30
# Deprecated: Connection classes
# These aren't used anymore since 2021.6.0
# Mainly here not to break custom integrations.
CONN_CLASS_CLOUD_PUSH = "cloud_push"
CONN_CLASS_CLOUD_POLL = "cloud_poll"
CONN_CLASS_LOCAL_PUSH = "local_push"
CONN_CLASS_LOCAL_POLL = "local_poll"
CONN_CLASS_ASSUMED = "assumed"
CONN_CLASS_UNKNOWN = "unknown"
class ConfigError(HomeAssistantError):
"""Error while configuring an account."""
class UnknownEntry(ConfigError):
"""Unknown entry specified."""
class OperationNotAllowed(ConfigError):
"""Raised when a config entry operation is not allowed."""
type UpdateListenerType = Callable[
[HomeAssistant, ConfigEntry], Coroutine[Any, Any, None]
]
STATE_KEYS = {
"state",
"reason",
"error_reason_translation_key",
"error_reason_translation_placeholders",
}
FROZEN_CONFIG_ENTRY_ATTRS = {"entry_id", "domain", *STATE_KEYS}
UPDATE_ENTRY_CONFIG_ENTRY_ATTRS = {
"unique_id",
"title",
"data",
"options",
"pref_disable_new_entities",
"pref_disable_polling",
"minor_version",
"version",
}
class ConfigFlowContext(FlowContext, total=False):
"""Typed context dict for config flow."""
alternative_domain: str
configuration_url: str
confirm_only: bool
discovery_key: DiscoveryKey
entry_id: str
title_placeholders: Mapping[str, str]
unique_id: str | None
class ConfigFlowResult(FlowResult[ConfigFlowContext, str], total=False):
"""Typed result dict for config flow."""
minor_version: int
options: Mapping[str, Any]
version: int
def _validate_item(*, disabled_by: ConfigEntryDisabler | Any | None = None) -> None:
"""Validate config entry item."""
# Deprecated in 2022.1, stopped working in 2024.10
if disabled_by is not None and not isinstance(disabled_by, ConfigEntryDisabler):
raise TypeError(
f"disabled_by must be a ConfigEntryDisabler value, got {disabled_by}"
)
class ConfigEntry[_DataT = Any]:
"""Hold a configuration entry."""
entry_id: str
domain: str
title: str
data: MappingProxyType[str, Any]
runtime_data: _DataT
options: MappingProxyType[str, Any]
unique_id: str | None
state: ConfigEntryState
reason: str | None
error_reason_translation_key: str | None
error_reason_translation_placeholders: dict[str, Any] | None
pref_disable_new_entities: bool
pref_disable_polling: bool
version: int
source: str
minor_version: int
disabled_by: ConfigEntryDisabler | None
supports_unload: bool | None
supports_remove_device: bool | None
_supports_options: bool | None
_supports_reconfigure: bool | None
update_listeners: list[UpdateListenerType]
_async_cancel_retry_setup: Callable[[], Any] | None
_on_unload: list[Callable[[], Coroutine[Any, Any, None] | None]] | None
setup_lock: asyncio.Lock
_reauth_lock: asyncio.Lock
_tasks: set[asyncio.Future[Any]]
_background_tasks: set[asyncio.Future[Any]]
_integration_for_domain: loader.Integration | None
_tries: int
created_at: datetime
modified_at: datetime
discovery_keys: MappingProxyType[str, tuple[DiscoveryKey, ...]]
def __init__(
self,
*,
created_at: datetime | None = None,
data: Mapping[str, Any],
disabled_by: ConfigEntryDisabler | None = None,
discovery_keys: MappingProxyType[str, tuple[DiscoveryKey, ...]],
domain: str,
entry_id: str | None = None,
minor_version: int,
modified_at: datetime | None = None,
options: Mapping[str, Any] | None,
pref_disable_new_entities: bool | None = None,
pref_disable_polling: bool | None = None,
source: str,
state: ConfigEntryState = ConfigEntryState.NOT_LOADED,
title: str,
unique_id: str | None,
version: int,
) -> None:
"""Initialize a config entry."""
_setter = object.__setattr__
# Unique id of the config entry
_setter(self, "entry_id", entry_id or ulid_util.ulid_now())
# Version of the configuration.
_setter(self, "version", version)
_setter(self, "minor_version", minor_version)
# Domain the configuration belongs to
_setter(self, "domain", domain)
# Title of the configuration
_setter(self, "title", title)
# Config data
_setter(self, "data", MappingProxyType(data))
# Entry options
_setter(self, "options", MappingProxyType(options or {}))
# Entry system options
if pref_disable_new_entities is None:
pref_disable_new_entities = False
_setter(self, "pref_disable_new_entities", pref_disable_new_entities)
if pref_disable_polling is None:
pref_disable_polling = False
_setter(self, "pref_disable_polling", pref_disable_polling)
# Source of the configuration (user, discovery, cloud)
_setter(self, "source", source)
# State of the entry (LOADED, NOT_LOADED)
_setter(self, "state", state)
# Unique ID of this entry.
_setter(self, "unique_id", unique_id)
# Config entry is disabled
_validate_item(disabled_by=disabled_by)
_setter(self, "disabled_by", disabled_by)
# Supports unload
_setter(self, "supports_unload", None)
# Supports remove device
_setter(self, "supports_remove_device", None)
# Supports options
_setter(self, "_supports_options", None)
# Supports reconfigure
_setter(self, "_supports_reconfigure", None)
# Listeners to call on update
_setter(self, "update_listeners", [])
# Reason why config entry is in a failed state
_setter(self, "reason", None)
_setter(self, "error_reason_translation_key", None)
_setter(self, "error_reason_translation_placeholders", None)
# Function to cancel a scheduled retry
_setter(self, "_async_cancel_retry_setup", None)
# Hold list for actions to call on unload.
_setter(self, "_on_unload", None)
# Reload lock to prevent conflicting reloads
_setter(self, "setup_lock", asyncio.Lock())
# Reauth lock to prevent concurrent reauth flows
_setter(self, "_reauth_lock", asyncio.Lock())
_setter(self, "_tasks", set())
_setter(self, "_background_tasks", set())
_setter(self, "_integration_for_domain", None)
_setter(self, "_tries", 0)
_setter(self, "created_at", created_at or utcnow())
_setter(self, "modified_at", modified_at or utcnow())
_setter(self, "discovery_keys", discovery_keys)
def __repr__(self) -> str:
"""Representation of ConfigEntry."""
return (
f"<ConfigEntry entry_id={self.entry_id} version={self.version} domain={self.domain} "
f"title={self.title} state={self.state} unique_id={self.unique_id}>"
)
def __setattr__(self, key: str, value: Any) -> None:
"""Set an attribute."""
if key in UPDATE_ENTRY_CONFIG_ENTRY_ATTRS:
raise AttributeError(
f"{key} cannot be changed directly, use async_update_entry instead"
)
if key in FROZEN_CONFIG_ENTRY_ATTRS:
raise AttributeError(f"{key} cannot be changed")
super().__setattr__(key, value)
self.clear_state_cache()
self.clear_storage_cache()
@property
def supports_options(self) -> bool:
"""Return if entry supports config options."""
if self._supports_options is None and (handler := HANDLERS.get(self.domain)):
# work out if handler has support for options flow
object.__setattr__(
self, "_supports_options", handler.async_supports_options_flow(self)
)
return self._supports_options or False
@property
def supports_reconfigure(self) -> bool:
"""Return if entry supports reconfigure step."""
if self._supports_reconfigure is None and (
handler := HANDLERS.get(self.domain)
):
# work out if handler has support for reconfigure step
object.__setattr__(
self,
"_supports_reconfigure",
hasattr(handler, "async_step_reconfigure"),
)
return self._supports_reconfigure or False
def clear_state_cache(self) -> None:
"""Clear cached properties that are included in as_json_fragment."""
self.__dict__.pop("as_json_fragment", None)
@cached_property
def as_json_fragment(self) -> json_fragment:
"""Return JSON fragment of a config entry that is used for the API."""
json_repr = {
"created_at": self.created_at.timestamp(),
"entry_id": self.entry_id,
"domain": self.domain,
"modified_at": self.modified_at.timestamp(),
"title": self.title,
"source": self.source,
"state": self.state.value,
"supports_options": self.supports_options,
"supports_remove_device": self.supports_remove_device or False,
"supports_unload": self.supports_unload or False,
"supports_reconfigure": self.supports_reconfigure,
"pref_disable_new_entities": self.pref_disable_new_entities,
"pref_disable_polling": self.pref_disable_polling,
"disabled_by": self.disabled_by,
"reason": self.reason,
"error_reason_translation_key": self.error_reason_translation_key,
"error_reason_translation_placeholders": self.error_reason_translation_placeholders,
}
return json_fragment(json_bytes(json_repr))
def clear_storage_cache(self) -> None:
"""Clear cached properties that are included in as_storage_fragment."""
self.__dict__.pop("as_storage_fragment", None)
@cached_property
def as_storage_fragment(self) -> json_fragment:
"""Return a storage fragment for this entry."""
return json_fragment(json_bytes_sorted(self.as_dict()))
async def async_setup(
self,
hass: HomeAssistant,
*,
integration: loader.Integration | None = None,
) -> None:
"""Set up an entry."""
if self.source == SOURCE_IGNORE or self.disabled_by:
return
current_entry.set(self)
try:
await self.__async_setup_with_context(hass, integration)
finally:
current_entry.set(None)
async def __async_setup_with_context(
self,
hass: HomeAssistant,
integration: loader.Integration | None,
) -> None:
"""Set up an entry, with current_entry set."""
if integration is None and not (integration := self._integration_for_domain):
integration = await loader.async_get_integration(hass, self.domain)
self._integration_for_domain = integration
# Only store setup result as state if it was not forwarded.
if domain_is_integration := self.domain == integration.domain:
if self.state in (
ConfigEntryState.LOADED,
ConfigEntryState.SETUP_IN_PROGRESS,
):
raise OperationNotAllowed(
f"The config entry {self.title} ({self.domain}) with entry_id"
f" {self.entry_id} cannot be set up because it is already loaded "
f"in the {self.state} state"
)
if not self.setup_lock.locked():
raise OperationNotAllowed(
f"The config entry {self.title} ({self.domain}) with entry_id"
f" {self.entry_id} cannot be set up because it does not hold "
"the setup lock"
)
self._async_set_state(hass, ConfigEntryState.SETUP_IN_PROGRESS, None)
if self.supports_unload is None:
self.supports_unload = await support_entry_unload(hass, self.domain)
if self.supports_remove_device is None:
self.supports_remove_device = await support_remove_from_device(
hass, self.domain
)
try:
component = await integration.async_get_component()
except ImportError as err:
_LOGGER.error(
"Error importing integration %s to set up %s configuration entry: %s",
integration.domain,
self.domain,
err,
)
if domain_is_integration:
self._async_set_state(
hass, ConfigEntryState.SETUP_ERROR, "Import error"
)
return
if domain_is_integration:
try:
await integration.async_get_platform("config_flow")
except ImportError as err:
_LOGGER.error(
(
"Error importing platform config_flow from integration %s to"
" set up %s configuration entry: %s"
),
integration.domain,
self.domain,
err,
)
self._async_set_state(
hass, ConfigEntryState.SETUP_ERROR, "Import error"
)
return
# Perform migration
if not await self.async_migrate(hass):
self._async_set_state(hass, ConfigEntryState.MIGRATION_ERROR, None)
return
setup_phase = SetupPhases.CONFIG_ENTRY_SETUP
else:
setup_phase = SetupPhases.CONFIG_ENTRY_PLATFORM_SETUP
error_reason = None
error_reason_translation_key = None
error_reason_translation_placeholders = None
try:
with async_start_setup(
hass, integration=self.domain, group=self.entry_id, phase=setup_phase
):
result = await component.async_setup_entry(hass, self)
if not isinstance(result, bool):
_LOGGER.error( # type: ignore[unreachable]
"%s.async_setup_entry did not return boolean", integration.domain
)
result = False
except ConfigEntryError as exc:
error_reason = str(exc) or "Unknown fatal config entry error"
error_reason_translation_key = exc.translation_key
error_reason_translation_placeholders = exc.translation_placeholders
_LOGGER.exception(
"Error setting up entry %s for %s: %s",
self.title,
self.domain,
error_reason,
)
await self._async_process_on_unload(hass)
result = False
except ConfigEntryAuthFailed as exc:
message = str(exc)
auth_base_message = "could not authenticate"
error_reason = message or auth_base_message
error_reason_translation_key = exc.translation_key
error_reason_translation_placeholders = exc.translation_placeholders
auth_message = (
f"{auth_base_message}: {message}" if message else auth_base_message
)
_LOGGER.warning(
"Config entry '%s' for %s integration %s",
self.title,
self.domain,
auth_message,
)
await self._async_process_on_unload(hass)
self.async_start_reauth(hass)
result = False
except ConfigEntryNotReady as exc:
message = str(exc)
error_reason_translation_key = exc.translation_key
error_reason_translation_placeholders = exc.translation_placeholders
self._async_set_state(
hass,
ConfigEntryState.SETUP_RETRY,
message or None,
error_reason_translation_key,
error_reason_translation_placeholders,
)
wait_time = 2 ** min(self._tries, 4) * 5 + (
randint(RANDOM_MICROSECOND_MIN, RANDOM_MICROSECOND_MAX) / 1000000
)
self._tries += 1
ready_message = f"ready yet: {message}" if message else "ready yet"
_LOGGER.debug(
"Config entry '%s' for %s integration not %s; Retrying in %d seconds",
self.title,
self.domain,
ready_message,
wait_time,
)
if hass.state is CoreState.running:
self._async_cancel_retry_setup = async_call_later(
hass,
wait_time,
HassJob(
functools.partial(self._async_setup_again, hass),
job_type=HassJobType.Callback,
cancel_on_shutdown=True,
),
)
else:
self._async_cancel_retry_setup = hass.bus.async_listen(
EVENT_HOMEASSISTANT_STARTED,
functools.partial(self._async_setup_again, hass),
)
await self._async_process_on_unload(hass)
return
# pylint: disable-next=broad-except
except (asyncio.CancelledError, SystemExit, Exception):
_LOGGER.exception(
"Error setting up entry %s for %s", self.title, integration.domain
)
result = False
#
# After successfully calling async_setup_entry, it is important that this function
# does not yield to the event loop by using `await` or `async with` or
# similar until after the state has been set by calling self._async_set_state.
#
# Otherwise we risk that any `call_soon`s
# created by an integration will be executed before the state is set.
#
# Only store setup result as state if it was not forwarded.
if not domain_is_integration:
return
self.async_cancel_retry_setup()
if result:
self._async_set_state(hass, ConfigEntryState.LOADED, None)
else:
self._async_set_state(
hass,
ConfigEntryState.SETUP_ERROR,
error_reason,
error_reason_translation_key,
error_reason_translation_placeholders,
)
@callback
def _async_setup_again(self, hass: HomeAssistant, *_: Any) -> None:
"""Schedule setup again.
This method is a callback to ensure that _async_cancel_retry_setup
is unset as soon as its callback is called.
"""
self._async_cancel_retry_setup = None
# Check again when we fire in case shutdown
# has started so we do not block shutdown
if not hass.is_stopping:
hass.async_create_background_task(
self.async_setup_locked(hass),
f"config entry retry {self.domain} {self.title}",
eager_start=True,
)
async def async_setup_locked(
self, hass: HomeAssistant, integration: loader.Integration | None = None
) -> None:
"""Set up while holding the setup lock."""
async with self.setup_lock:
if self.state is ConfigEntryState.LOADED:
# If something loaded the config entry while
# we were waiting for the lock, we should not
# set it up again.
_LOGGER.debug(
"Not setting up %s (%s %s) again, already loaded",
self.title,
self.domain,
self.entry_id,
)
return
await self.async_setup(hass, integration=integration)
@callback
def async_shutdown(self) -> None:
"""Call when Home Assistant is stopping."""
self.async_cancel_retry_setup()
@callback
def async_cancel_retry_setup(self) -> None:
"""Cancel retry setup."""
if self._async_cancel_retry_setup is not None:
self._async_cancel_retry_setup()
self._async_cancel_retry_setup = None
async def async_unload(
self, hass: HomeAssistant, *, integration: loader.Integration | None = None
) -> bool:
"""Unload an entry.
Returns if unload is possible and was successful.
"""
if self.source == SOURCE_IGNORE:
self._async_set_state(hass, ConfigEntryState.NOT_LOADED, None)
return True
if self.state == ConfigEntryState.NOT_LOADED:
return True
if not integration and (integration := self._integration_for_domain) is None:
try:
integration = await loader.async_get_integration(hass, self.domain)
except loader.IntegrationNotFound:
# The integration was likely a custom_component
# that was uninstalled, or an integration
# that has been renamed without removing the config
# entry.
self._async_set_state(hass, ConfigEntryState.NOT_LOADED, None)
return True
component = await integration.async_get_component()
if domain_is_integration := self.domain == integration.domain:
if not self.setup_lock.locked():
raise OperationNotAllowed(
f"The config entry {self.title} ({self.domain}) with entry_id"
f" {self.entry_id} cannot be unloaded because it does not hold "
"the setup lock"
)
if not self.state.recoverable:
return False
if self.state is not ConfigEntryState.LOADED:
self.async_cancel_retry_setup()
self._async_set_state(hass, ConfigEntryState.NOT_LOADED, None)
return True
supports_unload = hasattr(component, "async_unload_entry")
if not supports_unload:
if domain_is_integration:
self._async_set_state(
hass, ConfigEntryState.FAILED_UNLOAD, "Unload not supported"
)
return False
try:
result = await component.async_unload_entry(hass, self)
assert isinstance(result, bool)
# Only adjust state if we unloaded the component
if domain_is_integration and result:
await self._async_process_on_unload(hass)
if hasattr(self, "runtime_data"):
object.__delattr__(self, "runtime_data")
self._async_set_state(hass, ConfigEntryState.NOT_LOADED, None)
except Exception as exc:
_LOGGER.exception(
"Error unloading entry %s for %s", self.title, integration.domain
)
if domain_is_integration:
self._async_set_state(
hass, ConfigEntryState.FAILED_UNLOAD, str(exc) or "Unknown error"
)
return False
return result
async def async_remove(self, hass: HomeAssistant) -> None:
"""Invoke remove callback on component."""
old_modified_at = self.modified_at
object.__setattr__(self, "modified_at", utcnow())
self.clear_state_cache()
self.clear_storage_cache()
if self.source == SOURCE_IGNORE:
return
if not self.setup_lock.locked():
raise OperationNotAllowed(
f"The config entry {self.title} ({self.domain}) with entry_id"
f" {self.entry_id} cannot be removed because it does not hold "
"the setup lock"
)
if not (integration := self._integration_for_domain):
try:
integration = await loader.async_get_integration(hass, self.domain)
except loader.IntegrationNotFound:
# The integration was likely a custom_component
# that was uninstalled, or an integration
# that has been renamed without removing the config
# entry.
return
component = await integration.async_get_component()
if not hasattr(component, "async_remove_entry"):
return
try:
await component.async_remove_entry(hass, self)
except Exception:
_LOGGER.exception(
"Error calling entry remove callback %s for %s",
self.title,
integration.domain,
)
# Restore modified_at
object.__setattr__(self, "modified_at", old_modified_at)
@callback
def _async_set_state(
self,
hass: HomeAssistant,
state: ConfigEntryState,
reason: str | None,
error_reason_translation_key: str | None = None,
error_reason_translation_placeholders: dict[str, str] | None = None,
) -> None:
"""Set the state of the config entry."""
if state not in NO_RESET_TRIES_STATES:
self._tries = 0
_setter = object.__setattr__
_setter(self, "state", state)
_setter(self, "reason", reason)
_setter(self, "error_reason_translation_key", error_reason_translation_key)
_setter(
self,
"error_reason_translation_placeholders",
error_reason_translation_placeholders,
)
self.clear_state_cache()
# Storage cache is not cleared here because the state is not stored
# in storage and we do not want to clear the cache on every state change
# since state changes are frequent.
async_dispatcher_send_internal(
hass, SIGNAL_CONFIG_ENTRY_CHANGED, ConfigEntryChange.UPDATED, self
)
async def async_migrate(self, hass: HomeAssistant) -> bool:
"""Migrate an entry.
Returns True if config entry is up-to-date or has been migrated.
"""
if (handler := HANDLERS.get(self.domain)) is None:
_LOGGER.error(
"Flow handler not found for entry %s for %s", self.title, self.domain
)
return False
# Handler may be a partial
# Keep for backwards compatibility
# https://github.com/home-assistant/core/pull/67087#discussion_r812559950
while isinstance(handler, functools.partial):
handler = handler.func # type: ignore[unreachable]
same_major_version = self.version == handler.VERSION
if same_major_version and self.minor_version == handler.MINOR_VERSION:
return True
if not (integration := self._integration_for_domain):
integration = await loader.async_get_integration(hass, self.domain)
component = await integration.async_get_component()
supports_migrate = hasattr(component, "async_migrate_entry")
if not supports_migrate:
if same_major_version:
return True
_LOGGER.error(
"Migration handler not found for entry %s for %s",
self.title,
self.domain,
)
return False
try:
result = await component.async_migrate_entry(hass, self)
if not isinstance(result, bool):
_LOGGER.error( # type: ignore[unreachable]
"%s.async_migrate_entry did not return boolean", self.domain
)
return False
if result:
hass.config_entries._async_schedule_save() # noqa: SLF001
except Exception:
_LOGGER.exception(
"Error migrating entry %s for %s", self.title, self.domain
)
return False
return result
def add_update_listener(self, listener: UpdateListenerType) -> CALLBACK_TYPE:
"""Listen for when entry is updated.
Returns function to unlisten.
"""
self.update_listeners.append(listener)
return lambda: self.update_listeners.remove(listener)
def as_dict(self) -> dict[str, Any]: