forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_entries.py
1553 lines (1264 loc) · 53.5 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.abc import Iterable, Mapping
from contextvars import ContextVar
from enum import Enum
import functools
import logging
from types import MappingProxyType, MethodType
from typing import Any, Callable, Optional, cast
import weakref
from homeassistant import data_entry_flow, loader
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import CALLBACK_TYPE, CoreState, HomeAssistant, callback
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
HomeAssistantError,
)
from homeassistant.helpers import device_registry, entity_registry
from homeassistant.helpers.event import Event
from homeassistant.helpers.typing import (
UNDEFINED,
ConfigType,
DiscoveryInfoType,
UndefinedType,
)
from homeassistant.setup import async_process_deps_reqs, async_setup_component
from homeassistant.util.decorator import Registry
import homeassistant.util.uuid as uuid_util
_LOGGER = logging.getLogger(__name__)
SOURCE_DISCOVERY = "discovery"
SOURCE_HASSIO = "hassio"
SOURCE_HOMEKIT = "homekit"
SOURCE_IMPORT = "import"
SOURCE_INTEGRATION_DISCOVERY = "integration_discovery"
SOURCE_MQTT = "mqtt"
SOURCE_SSDP = "ssdp"
SOURCE_USB = "usb"
SOURCE_USER = "user"
SOURCE_ZEROCONF = "zeroconf"
SOURCE_DHCP = "dhcp"
# 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 when a user uses the "Stop Ignoring" button in the UI (the
# config_entries/ignore_flow websocket command). It's triggered after the "ignore" config entry has
# been removed and unloaded.
SOURCE_UNIGNORE = "unignore"
# This is used to signal that re-authentication is required by the user.
SOURCE_REAUTH = "reauth"
HANDLERS = Registry()
STORAGE_KEY = "core.config_entries"
STORAGE_VERSION = 1
# Deprecated since 0.73
PATH_CONFIG = ".config_entries.json"
SAVE_DELAY = 1
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"""
_recoverable: bool
def __new__(cls: type[object], value: str, recoverable: bool) -> ConfigEntryState:
"""Create new ConfigEntryState."""
obj = object.__new__(cls)
obj._value_ = value
obj._recoverable = recoverable
return cast("ConfigEntryState", obj)
@property
def recoverable(self) -> bool:
"""Get if the state is recoverable."""
return self._recoverable
DEFAULT_DISCOVERY_UNIQUE_ID = "default_discovery_unique_id"
DISCOVERY_NOTIFICATION_ID = "config_entry_discovery"
DISCOVERY_SOURCES = (
SOURCE_SSDP,
SOURCE_USB,
SOURCE_DHCP,
SOURCE_HOMEKIT,
SOURCE_ZEROCONF,
SOURCE_HOMEKIT,
SOURCE_DHCP,
SOURCE_DISCOVERY,
SOURCE_IMPORT,
SOURCE_UNIGNORE,
)
RECONFIGURE_NOTIFICATION_ID = "config_entry_reconfigure"
EVENT_FLOW_DISCOVERED = "config_entry_discovered"
DISABLED_USER = "user"
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."""
UpdateListenerType = Callable[[HomeAssistant, "ConfigEntry"], Any]
class ConfigEntry:
"""Hold a configuration entry."""
__slots__ = (
"entry_id",
"version",
"domain",
"title",
"data",
"options",
"unique_id",
"supports_unload",
"pref_disable_new_entities",
"pref_disable_polling",
"source",
"state",
"disabled_by",
"_setup_lock",
"update_listeners",
"reason",
"_async_cancel_retry_setup",
"_on_unload",
)
def __init__(
self,
version: int,
domain: str,
title: str,
data: Mapping[str, Any],
source: str,
pref_disable_new_entities: bool | None = None,
pref_disable_polling: bool | None = None,
options: Mapping[str, Any] | None = None,
unique_id: str | None = None,
entry_id: str | None = None,
state: ConfigEntryState = ConfigEntryState.NOT_LOADED,
disabled_by: str | None = None,
) -> None:
"""Initialize a config entry."""
# Unique id of the config entry
self.entry_id = entry_id or uuid_util.random_uuid_hex()
# Version of the configuration.
self.version = version
# Domain the configuration belongs to
self.domain = domain
# Title of the configuration
self.title = title
# Config data
self.data = MappingProxyType(data)
# Entry options
self.options = MappingProxyType(options or {})
# Entry system options
if pref_disable_new_entities is None:
pref_disable_new_entities = False
self.pref_disable_new_entities = pref_disable_new_entities
if pref_disable_polling is None:
pref_disable_polling = False
self.pref_disable_polling = pref_disable_polling
# Source of the configuration (user, discovery, cloud)
self.source = source
# State of the entry (LOADED, NOT_LOADED)
self.state = state
# Unique ID of this entry.
self.unique_id = unique_id
# Config entry is disabled
self.disabled_by = disabled_by
# Supports unload
self.supports_unload = False
# Listeners to call on update
self.update_listeners: list[
weakref.ReferenceType[UpdateListenerType] | weakref.WeakMethod
] = []
# Reason why config entry is in a failed state
self.reason: str | None = None
# Function to cancel a scheduled retry
self._async_cancel_retry_setup: Callable[[], Any] | None = None
# Hold list for functions to call on unload.
self._on_unload: list[CALLBACK_TYPE] | None = None
async def async_setup(
self,
hass: HomeAssistant,
*,
integration: loader.Integration | None = None,
tries: int = 0,
) -> None:
"""Set up an entry."""
current_entry.set(self)
if self.source == SOURCE_IGNORE or self.disabled_by:
return
if integration is None:
integration = await loader.async_get_integration(hass, self.domain)
self.supports_unload = await support_entry_unload(hass, self.domain)
try:
component = integration.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 self.domain == integration.domain:
self.state = ConfigEntryState.SETUP_ERROR
self.reason = "Import error"
return
if self.domain == integration.domain:
try:
integration.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.state = ConfigEntryState.SETUP_ERROR
self.reason = "Import error"
return
# Perform migration
if not await self.async_migrate(hass):
self.state = ConfigEntryState.MIGRATION_ERROR
self.reason = None
return
error_reason = None
try:
result = await component.async_setup_entry(hass, self) # type: ignore
if not isinstance(result, bool):
_LOGGER.error(
"%s.async_setup_entry did not return boolean", integration.domain
)
result = False
except ConfigEntryAuthFailed as ex:
message = str(ex)
auth_base_message = "could not authenticate"
error_reason = message or auth_base_message
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,
)
self._async_process_on_unload()
self.async_start_reauth(hass)
result = False
except ConfigEntryNotReady as ex:
self.state = ConfigEntryState.SETUP_RETRY
self.reason = str(ex) or None
wait_time = 2 ** min(tries, 4) * 5
tries += 1
message = str(ex)
ready_message = f"ready yet: {message}" if message else "ready yet"
if tries == 1:
_LOGGER.warning(
"Config entry '%s' for %s integration not %s; Retrying in background",
self.title,
self.domain,
ready_message,
)
else:
_LOGGER.debug(
"Config entry '%s' for %s integration not %s; Retrying in %d seconds",
self.title,
self.domain,
ready_message,
wait_time,
)
async def setup_again(*_: Any) -> None:
"""Run setup again."""
self._async_cancel_retry_setup = None
await self.async_setup(hass, integration=integration, tries=tries)
if hass.state == CoreState.running:
self._async_cancel_retry_setup = hass.helpers.event.async_call_later(
wait_time, setup_again
)
else:
self._async_cancel_retry_setup = hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, setup_again
)
self._async_process_on_unload()
return
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error setting up entry %s for %s", self.title, integration.domain
)
result = False
# Only store setup result as state if it was not forwarded.
if self.domain != integration.domain:
return
if result:
self.state = ConfigEntryState.LOADED
self.reason = None
else:
self.state = ConfigEntryState.SETUP_ERROR
self.reason = error_reason
async 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.state = ConfigEntryState.NOT_LOADED
self.reason = None
return True
if self.state == ConfigEntryState.NOT_LOADED:
return True
if integration 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.state = ConfigEntryState.NOT_LOADED
self.reason = None
return True
component = integration.get_component()
if integration.domain == self.domain:
if not self.state.recoverable:
return False
if self.state is not ConfigEntryState.LOADED:
self.async_cancel_retry_setup()
self.state = ConfigEntryState.NOT_LOADED
self.reason = None
return True
supports_unload = hasattr(component, "async_unload_entry")
if not supports_unload:
if integration.domain == self.domain:
self.state = ConfigEntryState.FAILED_UNLOAD
self.reason = "Unload not supported"
return False
try:
result = await component.async_unload_entry(hass, self) # type: ignore
assert isinstance(result, bool)
# Only adjust state if we unloaded the component
if result and integration.domain == self.domain:
self.state = ConfigEntryState.NOT_LOADED
self.reason = None
self._async_process_on_unload()
return result
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error unloading entry %s for %s", self.title, integration.domain
)
if integration.domain == self.domain:
self.state = ConfigEntryState.FAILED_UNLOAD
self.reason = "Unknown error"
return False
async def async_remove(self, hass: HomeAssistant) -> None:
"""Invoke remove callback on component."""
if self.source == SOURCE_IGNORE:
return
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 = integration.get_component()
if not hasattr(component, "async_remove_entry"):
return
try:
await component.async_remove_entry(hass, self) # type: ignore
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error calling entry remove callback %s for %s",
self.title,
integration.domain,
)
async def async_migrate(self, hass: HomeAssistant) -> bool:
"""Migrate an entry.
Returns True if config entry is up-to-date or has been migrated.
"""
handler = HANDLERS.get(self.domain)
if handler is None:
_LOGGER.error(
"Flow handler not found for entry %s for %s", self.title, self.domain
)
return False
# Handler may be a partial
while isinstance(handler, functools.partial):
handler = handler.func
if self.version == handler.VERSION:
return True
integration = await loader.async_get_integration(hass, self.domain)
component = integration.get_component()
supports_migrate = hasattr(component, "async_migrate_entry")
if not supports_migrate:
_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) # type: ignore
if not isinstance(result, bool):
_LOGGER.error(
"%s.async_migrate_entry did not return boolean", self.domain
)
return False
if result:
# pylint: disable=protected-access
hass.config_entries._async_schedule_save()
return result
except Exception: # pylint: disable=broad-except
_LOGGER.exception(
"Error migrating entry %s for %s", self.title, self.domain
)
return False
def add_update_listener(self, listener: UpdateListenerType) -> CALLBACK_TYPE:
"""Listen for when entry is updated.
Returns function to unlisten.
"""
weak_listener: Any
# weakref.ref is not applicable to a bound method, e.g. method of a class instance, as reference will die immediately
if hasattr(listener, "__self__"):
weak_listener = weakref.WeakMethod(cast(MethodType, listener))
else:
weak_listener = weakref.ref(listener)
self.update_listeners.append(weak_listener)
return lambda: self.update_listeners.remove(weak_listener)
def as_dict(self) -> dict[str, Any]:
"""Return dictionary version of this entry."""
return {
"entry_id": self.entry_id,
"version": self.version,
"domain": self.domain,
"title": self.title,
"data": dict(self.data),
"options": dict(self.options),
"pref_disable_new_entities": self.pref_disable_new_entities,
"pref_disable_polling": self.pref_disable_polling,
"source": self.source,
"unique_id": self.unique_id,
"disabled_by": self.disabled_by,
}
@callback
def async_on_unload(self, func: CALLBACK_TYPE) -> None:
"""Add a function to call when config entry is unloaded."""
if self._on_unload is None:
self._on_unload = []
self._on_unload.append(func)
@callback
def _async_process_on_unload(self) -> None:
"""Process the on_unload callbacks."""
if self._on_unload is not None:
while self._on_unload:
self._on_unload.pop()()
@callback
def async_start_reauth(self, hass: HomeAssistant) -> None:
"""Start a reauth flow."""
flow_context = {
"source": SOURCE_REAUTH,
"entry_id": self.entry_id,
"unique_id": self.unique_id,
}
for flow in hass.config_entries.flow.async_progress():
if flow["context"] == flow_context:
return
hass.async_create_task(
hass.config_entries.flow.async_init(
self.domain,
context=flow_context,
data=self.data,
)
)
current_entry: ContextVar[ConfigEntry | None] = ContextVar(
"current_entry", default=None
)
class ConfigEntriesFlowManager(data_entry_flow.FlowManager):
"""Manage all the config entry flows that are in progress."""
def __init__(
self,
hass: HomeAssistant,
config_entries: ConfigEntries,
hass_config: ConfigType,
) -> None:
"""Initialize the config entry flow manager."""
super().__init__(hass)
self.config_entries = config_entries
self._hass_config = hass_config
async def async_finish_flow(
self, flow: data_entry_flow.FlowHandler, result: data_entry_flow.FlowResult
) -> data_entry_flow.FlowResult:
"""Finish a config flow and add an entry."""
flow = cast(ConfigFlow, flow)
# Remove notification if no other discovery config entries in progress
if not any(
ent["context"]["source"] in DISCOVERY_SOURCES
for ent in self.hass.config_entries.flow.async_progress()
if ent["flow_id"] != flow.flow_id
):
self.hass.components.persistent_notification.async_dismiss(
DISCOVERY_NOTIFICATION_ID
)
if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY:
return result
# Check if config entry exists with unique ID. Unload it.
existing_entry = None
# Abort all flows in progress with same unique ID
# or the default discovery ID
for progress_flow in self.async_progress():
progress_unique_id = progress_flow["context"].get("unique_id")
if (
progress_flow["handler"] == flow.handler
and progress_flow["flow_id"] != flow.flow_id
and (
(flow.unique_id and progress_unique_id == flow.unique_id)
or progress_unique_id == DEFAULT_DISCOVERY_UNIQUE_ID
)
):
self.async_abort(progress_flow["flow_id"])
if flow.unique_id is not None:
# Reset unique ID when the default discovery ID has been used
if flow.unique_id == DEFAULT_DISCOVERY_UNIQUE_ID:
await flow.async_set_unique_id(None)
# Find existing entry.
for check_entry in self.config_entries.async_entries(result["handler"]):
if check_entry.unique_id == flow.unique_id:
existing_entry = check_entry
break
# Unload the entry before setting up the new one.
# We will remove it only after the other one is set up,
# so that device customizations are not getting lost.
if existing_entry is not None and existing_entry.state.recoverable:
await self.config_entries.async_unload(existing_entry.entry_id)
entry = ConfigEntry(
version=result["version"],
domain=result["handler"],
title=result["title"],
data=result["data"],
options=result["options"],
source=flow.context["source"],
unique_id=flow.unique_id,
)
await self.config_entries.async_add(entry)
if existing_entry is not None:
await self.config_entries.async_remove(existing_entry.entry_id)
result["result"] = entry
return result
async def async_create_flow(
self, handler_key: Any, *, context: dict | None = None, data: Any = None
) -> ConfigFlow:
"""Create a flow for specified handler.
Handler key is the domain of the component that we want to set up.
"""
try:
integration = await loader.async_get_integration(self.hass, handler_key)
except loader.IntegrationNotFound as err:
_LOGGER.error("Cannot find integration %s", handler_key)
raise data_entry_flow.UnknownHandler from err
# Make sure requirements and dependencies of component are resolved
await async_process_deps_reqs(self.hass, self._hass_config, integration)
try:
integration.get_platform("config_flow")
except ImportError as err:
_LOGGER.error(
"Error occurred loading configuration flow for integration %s: %s",
handler_key,
err,
)
raise data_entry_flow.UnknownHandler
handler = HANDLERS.get(handler_key)
if handler is None:
raise data_entry_flow.UnknownHandler
if not context or "source" not in context:
raise KeyError("Context not set or doesn't have a source set")
flow = cast(ConfigFlow, handler())
flow.init_step = context["source"]
return flow
async def async_post_init(
self, flow: data_entry_flow.FlowHandler, result: data_entry_flow.FlowResult
) -> None:
"""After a flow is initialised trigger new flow notifications."""
source = flow.context["source"]
# Create notification.
if source in DISCOVERY_SOURCES:
self.hass.bus.async_fire(EVENT_FLOW_DISCOVERED)
self.hass.components.persistent_notification.async_create(
title="New devices discovered",
message=(
"We have discovered new devices on your network. "
"[Check it out](/config/integrations)."
),
notification_id=DISCOVERY_NOTIFICATION_ID,
)
elif source == SOURCE_REAUTH:
self.hass.components.persistent_notification.async_create(
title="Integration requires reconfiguration",
message=(
"At least one of your integrations requires reconfiguration to "
"continue functioning. [Check it out](/config/integrations)."
),
notification_id=RECONFIGURE_NOTIFICATION_ID,
)
class ConfigEntries:
"""Manage the configuration entries.
An instance of this object is available via `hass.config_entries`.
"""
def __init__(self, hass: HomeAssistant, hass_config: ConfigType) -> None:
"""Initialize the entry manager."""
self.hass = hass
self.flow = ConfigEntriesFlowManager(hass, self, hass_config)
self.options = OptionsFlowManager(hass)
self._hass_config = hass_config
self._entries: dict[str, ConfigEntry] = {}
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
EntityRegistryDisabledHandler(hass).async_setup()
@callback
def async_domains(
self, include_ignore: bool = False, include_disabled: bool = False
) -> list[str]:
"""Return domains for which we have entries."""
return list(
{
entry.domain: None
for entry in self._entries.values()
if (include_ignore or entry.source != SOURCE_IGNORE)
and (include_disabled or not entry.disabled_by)
}
)
@callback
def async_get_entry(self, entry_id: str) -> ConfigEntry | None:
"""Return entry with matching entry_id."""
return self._entries.get(entry_id)
@callback
def async_entries(self, domain: str | None = None) -> list[ConfigEntry]:
"""Return all entries or entries for a specific domain."""
if domain is None:
return list(self._entries.values())
return [entry for entry in self._entries.values() if entry.domain == domain]
async def async_add(self, entry: ConfigEntry) -> None:
"""Add and setup an entry."""
if entry.entry_id in self._entries:
raise HomeAssistantError(
f"An entry with the id {entry.entry_id} already exists."
)
self._entries[entry.entry_id] = entry
await self.async_setup(entry.entry_id)
self._async_schedule_save()
async def async_remove(self, entry_id: str) -> dict[str, Any]:
"""Remove an entry."""
entry = self.async_get_entry(entry_id)
if entry is None:
raise UnknownEntry
if not entry.state.recoverable:
unload_success = entry.state is not ConfigEntryState.FAILED_UNLOAD
else:
unload_success = await self.async_unload(entry_id)
await entry.async_remove(self.hass)
del self._entries[entry.entry_id]
self._async_schedule_save()
dev_reg, ent_reg = await asyncio.gather(
self.hass.helpers.device_registry.async_get_registry(),
self.hass.helpers.entity_registry.async_get_registry(),
)
dev_reg.async_clear_config_entry(entry_id)
ent_reg.async_clear_config_entry(entry_id)
# If the configuration entry is removed during reauth, it should
# abort any reauth flow that is active for the removed entry.
for progress_flow in self.hass.config_entries.flow.async_progress():
context = progress_flow.get("context")
if (
context
and context["source"] == SOURCE_REAUTH
and "entry_id" in context
and context["entry_id"] == entry_id
and "flow_id" in progress_flow
):
self.hass.config_entries.flow.async_abort(progress_flow["flow_id"])
# After we have fully removed an "ignore" config entry we can try and rediscover it so that a
# user is able to immediately start configuring it. We do this by starting a new flow with
# the 'unignore' step. If the integration doesn't implement async_step_unignore then
# this will be a no-op.
if entry.source == SOURCE_IGNORE:
self.hass.async_create_task(
self.hass.config_entries.flow.async_init(
entry.domain,
context={"source": SOURCE_UNIGNORE},
data={"unique_id": entry.unique_id},
)
)
return {"require_restart": not unload_success}
async def _async_shutdown(self, event: Event) -> None:
"""Call when Home Assistant is stopping."""
await asyncio.gather(
*(entry.async_shutdown() for entry in self._entries.values())
)
await self.flow.async_shutdown()
async def async_initialize(self) -> None:
"""Initialize config entry config."""
# Migrating for config entries stored before 0.73
config = await self.hass.helpers.storage.async_migrator(
self.hass.config.path(PATH_CONFIG),
self._store,
old_conf_migrate_func=_old_conf_migrator,
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._async_shutdown)
if config is None:
self._entries = {}
return
entries = {}
for entry in config["entries"]:
pref_disable_new_entities = entry.get("pref_disable_new_entities")
# Between 0.98 and 2021.6 we stored 'disable_new_entities' in a system options dictionary
if pref_disable_new_entities is None and "system_options" in entry:
pref_disable_new_entities = entry.get("system_options", {}).get(
"disable_new_entities"
)
entries[entry["entry_id"]] = ConfigEntry(
version=entry["version"],
domain=entry["domain"],
entry_id=entry["entry_id"],
data=entry["data"],
source=entry["source"],
title=entry["title"],
# New in 0.89
options=entry.get("options"),
# New in 0.104
unique_id=entry.get("unique_id"),
# New in 2021.3
disabled_by=entry.get("disabled_by"),
# New in 2021.6
pref_disable_new_entities=pref_disable_new_entities,
pref_disable_polling=entry.get("pref_disable_polling"),
)
self._entries = entries
async def async_setup(self, entry_id: str) -> bool:
"""Set up a config entry.
Return True if entry has been successfully loaded.
"""
entry = self.async_get_entry(entry_id)
if entry is None:
raise UnknownEntry
if entry.state is not ConfigEntryState.NOT_LOADED:
raise OperationNotAllowed
# Setup Component if not set up yet
if entry.domain in self.hass.config.components:
await entry.async_setup(self.hass)
else:
# Setting up the component will set up all its config entries
result = await async_setup_component(
self.hass, entry.domain, self._hass_config
)
if not result:
return result
return entry.state is ConfigEntryState.LOADED # type: ignore[comparison-overlap] # mypy bug?
async def async_unload(self, entry_id: str) -> bool:
"""Unload a config entry."""
entry = self.async_get_entry(entry_id)
if entry is None:
raise UnknownEntry
if not entry.state.recoverable:
raise OperationNotAllowed
return await entry.async_unload(self.hass)
async def async_reload(self, entry_id: str) -> bool:
"""Reload an entry.
If an entry was not loaded, will just load.
"""
entry = self.async_get_entry(entry_id)
if entry is None:
raise UnknownEntry
unload_result = await self.async_unload(entry_id)
if not unload_result or entry.disabled_by:
return unload_result
return await self.async_setup(entry_id)
async def async_set_disabled_by(
self, entry_id: str, disabled_by: str | None
) -> bool:
"""Disable an entry.
If disabled_by is changed, the config entry will be reloaded.
"""
entry = self.async_get_entry(entry_id)
if entry is None:
raise UnknownEntry
if entry.disabled_by == disabled_by:
return True
entry.disabled_by = disabled_by
self._async_schedule_save()
dev_reg = device_registry.async_get(self.hass)
ent_reg = entity_registry.async_get(self.hass)
if not entry.disabled_by:
# The config entry will no longer be disabled, enable devices and entities
device_registry.async_config_entry_disabled_by_changed(dev_reg, entry)
entity_registry.async_config_entry_disabled_by_changed(ent_reg, entry)
# Load or unload the config entry
reload_result = await self.async_reload(entry_id)