-
-
Notifications
You must be signed in to change notification settings - Fork 31.3k
/
loader.py
1731 lines (1408 loc) · 58.8 KB
/
loader.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
"""The methods for loading Home Assistant integrations.
This module has quite some complex parts. I have tried to add as much
documentation as possible to keep it understandable.
"""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Iterable
from contextlib import suppress
from dataclasses import dataclass
import functools as ft
from functools import cached_property
import importlib
import logging
import os
import pathlib
import sys
import time
from types import ModuleType
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypedDict, cast
from awesomeversion import (
AwesomeVersion,
AwesomeVersionException,
AwesomeVersionStrategy,
)
import voluptuous as vol
from . import generated
from .const import Platform
from .core import HomeAssistant, callback
from .generated.application_credentials import APPLICATION_CREDENTIALS
from .generated.bluetooth import BLUETOOTH
from .generated.config_flows import FLOWS
from .generated.dhcp import DHCP
from .generated.mqtt import MQTT
from .generated.ssdp import SSDP
from .generated.usb import USB
from .generated.zeroconf import HOMEKIT, ZEROCONF
from .helpers.json import json_bytes, json_fragment
from .helpers.typing import UNDEFINED
from .util.hass_dict import HassKey
from .util.json import JSON_DECODE_EXCEPTIONS, json_loads
if TYPE_CHECKING:
# The relative imports below are guarded by TYPE_CHECKING
# because they would cause a circular import otherwise.
from .config_entries import ConfigEntry
from .helpers import device_registry as dr
from .helpers.typing import ConfigType
_LOGGER = logging.getLogger(__name__)
#
# Integration.get_component will check preload platforms and
# try to import the code to avoid a thundering heard of import
# executor jobs later in the startup process.
#
# default platforms are prepopulated in this list to ensure that
# by the time the component is loaded, we check if the platform is
# available.
#
# This list can be extended by calling async_register_preload_platform
#
BASE_PRELOAD_PLATFORMS = [
"config",
"config_flow",
"diagnostics",
"energy",
"group",
"logbook",
"hardware",
"intent",
"media_source",
"recorder",
"repairs",
"system_health",
"trigger",
]
@dataclass
class BlockedIntegration:
"""Blocked custom integration details."""
lowest_good_version: AwesomeVersion | None
reason: str
BLOCKED_CUSTOM_INTEGRATIONS: dict[str, BlockedIntegration] = {
# Added in 2024.3.0 because of https://github.com/home-assistant/core/issues/112464
"start_time": BlockedIntegration(AwesomeVersion("1.1.7"), "breaks Home Assistant"),
# Added in 2024.5.1 because of
# https://community.home-assistant.io/t/psa-2024-5-upgrade-failure-and-dreame-vacuum-custom-integration/724612
"dreame_vacuum": BlockedIntegration(
AwesomeVersion("1.0.4"), "crashes Home Assistant"
),
# Added in 2024.5.5 because of
# https://github.com/sh00t2kill/dolphin-robot/issues/185
"mydolphin_plus": BlockedIntegration(
AwesomeVersion("1.0.13"), "crashes Home Assistant"
),
}
DATA_COMPONENTS: HassKey[dict[str, ModuleType | ComponentProtocol]] = HassKey(
"components"
)
DATA_INTEGRATIONS: HassKey[dict[str, Integration | asyncio.Future[None]]] = HassKey(
"integrations"
)
DATA_MISSING_PLATFORMS: HassKey[dict[str, bool]] = HassKey("missing_platforms")
DATA_CUSTOM_COMPONENTS: HassKey[
dict[str, Integration] | asyncio.Future[dict[str, Integration]]
] = HassKey("custom_components")
DATA_PRELOAD_PLATFORMS: HassKey[list[str]] = HassKey("preload_platforms")
PACKAGE_CUSTOM_COMPONENTS = "custom_components"
PACKAGE_BUILTIN = "homeassistant.components"
CUSTOM_WARNING = (
"We found a custom integration %s which has not "
"been tested by Home Assistant. This component might "
"cause stability problems, be sure to disable it if you "
"experience issues with Home Assistant"
)
IMPORT_EVENT_LOOP_WARNING = (
"We found an integration %s which is configured to "
"to import its code in the event loop. This component might "
"cause stability problems, be sure to disable it if you "
"experience issues with Home Assistant"
)
MOVED_ZEROCONF_PROPS = ("macaddress", "model", "manufacturer")
class DHCPMatcherRequired(TypedDict, total=True):
"""Matcher for the dhcp integration for required fields."""
domain: str
class DHCPMatcherOptional(TypedDict, total=False):
"""Matcher for the dhcp integration for optional fields."""
macaddress: str
hostname: str
registered_devices: bool
class DHCPMatcher(DHCPMatcherRequired, DHCPMatcherOptional):
"""Matcher for the dhcp integration."""
class BluetoothMatcherRequired(TypedDict, total=True):
"""Matcher for the bluetooth integration for required fields."""
domain: str
class BluetoothMatcherOptional(TypedDict, total=False):
"""Matcher for the bluetooth integration for optional fields."""
local_name: str
service_uuid: str
service_data_uuid: str
manufacturer_id: int
manufacturer_data_start: list[int]
connectable: bool
class BluetoothMatcher(BluetoothMatcherRequired, BluetoothMatcherOptional):
"""Matcher for the bluetooth integration."""
class USBMatcherRequired(TypedDict, total=True):
"""Matcher for the usb integration for required fields."""
domain: str
class USBMatcherOptional(TypedDict, total=False):
"""Matcher for the usb integration for optional fields."""
vid: str
pid: str
serial_number: str
manufacturer: str
description: str
class USBMatcher(USBMatcherRequired, USBMatcherOptional):
"""Matcher for the bluetooth integration."""
@dataclass(slots=True)
class HomeKitDiscoveredIntegration:
"""HomeKit model."""
domain: str
always_discover: bool
class ZeroconfMatcher(TypedDict, total=False):
"""Matcher for zeroconf."""
domain: str
name: str
properties: dict[str, str]
class Manifest(TypedDict, total=False):
"""Integration manifest.
Note that none of the attributes are marked Optional here. However, some of
them may be optional in manifest.json in the sense that they can be omitted
altogether. But when present, they should not have null values in it.
"""
name: str
disabled: str
domain: str
integration_type: Literal[
"entity", "device", "hardware", "helper", "hub", "service", "system", "virtual"
]
dependencies: list[str]
after_dependencies: list[str]
requirements: list[str]
config_flow: bool
documentation: str
issue_tracker: str
quality_scale: str
iot_class: str
bluetooth: list[dict[str, int | str]]
mqtt: list[str]
ssdp: list[dict[str, str]]
zeroconf: list[str | dict[str, str]]
dhcp: list[dict[str, bool | str]]
usb: list[dict[str, str]]
homekit: dict[str, list[str]]
is_built_in: bool
version: str
codeowners: list[str]
loggers: list[str]
import_executor: bool
single_config_entry: bool
def async_setup(hass: HomeAssistant) -> None:
"""Set up the necessary data structures."""
_async_mount_config_dir(hass)
hass.data[DATA_COMPONENTS] = {}
hass.data[DATA_INTEGRATIONS] = {}
hass.data[DATA_MISSING_PLATFORMS] = {}
hass.data[DATA_PRELOAD_PLATFORMS] = BASE_PRELOAD_PLATFORMS.copy()
def manifest_from_legacy_module(domain: str, module: ModuleType) -> Manifest:
"""Generate a manifest from a legacy module."""
return {
"domain": domain,
"name": domain,
"requirements": getattr(module, "REQUIREMENTS", []),
"dependencies": getattr(module, "DEPENDENCIES", []),
"codeowners": [],
}
async def _async_get_custom_components(
hass: HomeAssistant,
) -> dict[str, Integration]:
"""Return list of custom integrations."""
if hass.config.recovery_mode or hass.config.safe_mode:
return {}
try:
import custom_components # pylint: disable=import-outside-toplevel
except ImportError:
return {}
def get_sub_directories(paths: list[str]) -> list[pathlib.Path]:
"""Return all sub directories in a set of paths."""
return [
entry
for path in paths
for entry in pathlib.Path(path).iterdir()
if entry.is_dir()
]
dirs = await hass.async_add_executor_job(
get_sub_directories, custom_components.__path__
)
integrations = await hass.async_add_executor_job(
_resolve_integrations_from_root,
hass,
custom_components,
[comp.name for comp in dirs],
)
return {
integration.domain: integration
for integration in integrations.values()
if integration is not None
}
async def async_get_custom_components(
hass: HomeAssistant,
) -> dict[str, Integration]:
"""Return cached list of custom integrations."""
comps_or_future = hass.data.get(DATA_CUSTOM_COMPONENTS)
if comps_or_future is None:
future = hass.data[DATA_CUSTOM_COMPONENTS] = hass.loop.create_future()
comps = await _async_get_custom_components(hass)
hass.data[DATA_CUSTOM_COMPONENTS] = comps
future.set_result(comps)
return comps
if isinstance(comps_or_future, asyncio.Future):
return await comps_or_future
return comps_or_future
async def async_get_config_flows(
hass: HomeAssistant,
type_filter: Literal["device", "helper", "hub", "service"] | None = None,
) -> set[str]:
"""Return cached list of config flows."""
integrations = await async_get_custom_components(hass)
flows: set[str] = set()
if type_filter is not None:
flows.update(FLOWS[type_filter])
else:
for type_flows in FLOWS.values():
flows.update(type_flows)
flows.update(
integration.domain
for integration in integrations.values()
if integration.config_flow
and (type_filter is None or integration.integration_type == type_filter)
)
return flows
class ComponentProtocol(Protocol):
"""Define the format of an integration."""
CONFIG_SCHEMA: vol.Schema
DOMAIN: str
async def async_setup_entry(
self, hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Set up a config entry."""
async def async_unload_entry(
self, hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Unload a config entry."""
async def async_migrate_entry(
self, hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Migrate an old config entry."""
async def async_remove_entry(
self, hass: HomeAssistant, config_entry: ConfigEntry
) -> None:
"""Remove a config entry."""
async def async_remove_config_entry_device(
self,
hass: HomeAssistant,
config_entry: ConfigEntry,
device_entry: dr.DeviceEntry,
) -> bool:
"""Remove a config entry device."""
async def async_reset_platform(
self, hass: HomeAssistant, integration_name: str
) -> None:
"""Release resources."""
async def async_setup(self, hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up integration."""
def setup(self, hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up integration."""
async def async_get_integration_descriptions(
hass: HomeAssistant,
) -> dict[str, Any]:
"""Return cached list of integrations."""
base = generated.__path__[0]
config_flow_path = pathlib.Path(base) / "integrations.json"
flow = await hass.async_add_executor_job(config_flow_path.read_text)
core_flows = cast(dict[str, Any], json_loads(flow))
custom_integrations = await async_get_custom_components(hass)
custom_flows: dict[str, Any] = {
"integration": {},
"helper": {},
}
for integration in custom_integrations.values():
# Remove core integration with same domain as the custom integration
if integration.integration_type in ("entity", "system"):
continue
for integration_type in ("integration", "helper"):
if integration.domain not in core_flows[integration_type]:
continue
del core_flows[integration_type][integration.domain]
if integration.domain in core_flows["translated_name"]:
core_flows["translated_name"].remove(integration.domain)
if integration.integration_type == "helper":
integration_key: str = integration.integration_type
else:
integration_key = "integration"
metadata = {
"config_flow": integration.config_flow,
"integration_type": integration.integration_type,
"iot_class": integration.iot_class,
"name": integration.name,
"single_config_entry": integration.manifest.get(
"single_config_entry", False
),
}
custom_flows[integration_key][integration.domain] = metadata
return {"core": core_flows, "custom": custom_flows}
async def async_get_application_credentials(hass: HomeAssistant) -> list[str]:
"""Return cached list of application credentials."""
integrations = await async_get_custom_components(hass)
return [
*APPLICATION_CREDENTIALS,
*[
integration.domain
for integration in integrations.values()
if "application_credentials" in integration.dependencies
],
]
def async_process_zeroconf_match_dict(entry: dict[str, Any]) -> ZeroconfMatcher:
"""Handle backwards compat with zeroconf matchers."""
entry_without_type: dict[str, Any] = entry.copy()
del entry_without_type["type"]
# These properties keys used to be at the top level, we relocate
# them for backwards compat
for moved_prop in MOVED_ZEROCONF_PROPS:
if value := entry_without_type.pop(moved_prop, None):
_LOGGER.warning(
(
'Matching the zeroconf property "%s" at top-level is deprecated and'
" should be moved into a properties dict; Check the developer"
" documentation"
),
moved_prop,
)
if "properties" not in entry_without_type:
prop_dict: dict[str, str] = {}
entry_without_type["properties"] = prop_dict
else:
prop_dict = entry_without_type["properties"]
prop_dict[moved_prop] = value.lower()
return cast(ZeroconfMatcher, entry_without_type)
async def async_get_zeroconf(
hass: HomeAssistant,
) -> dict[str, list[ZeroconfMatcher]]:
"""Return cached list of zeroconf types."""
zeroconf: dict[str, list[ZeroconfMatcher]] = ZEROCONF.copy() # type: ignore[assignment]
integrations = await async_get_custom_components(hass)
for integration in integrations.values():
if not integration.zeroconf:
continue
for entry in integration.zeroconf:
data: ZeroconfMatcher = {"domain": integration.domain}
if isinstance(entry, dict):
typ = entry["type"]
data.update(async_process_zeroconf_match_dict(entry))
else:
typ = entry
zeroconf.setdefault(typ, []).append(data)
return zeroconf
async def async_get_bluetooth(hass: HomeAssistant) -> list[BluetoothMatcher]:
"""Return cached list of bluetooth types."""
bluetooth = cast(list[BluetoothMatcher], BLUETOOTH.copy())
integrations = await async_get_custom_components(hass)
for integration in integrations.values():
if not integration.bluetooth:
continue
for entry in integration.bluetooth:
bluetooth.append(
cast(BluetoothMatcher, {"domain": integration.domain, **entry})
)
return bluetooth
async def async_get_dhcp(hass: HomeAssistant) -> list[DHCPMatcher]:
"""Return cached list of dhcp types."""
dhcp = cast(list[DHCPMatcher], DHCP.copy())
integrations = await async_get_custom_components(hass)
for integration in integrations.values():
if not integration.dhcp:
continue
for entry in integration.dhcp:
dhcp.append(cast(DHCPMatcher, {"domain": integration.domain, **entry}))
return dhcp
async def async_get_usb(hass: HomeAssistant) -> list[USBMatcher]:
"""Return cached list of usb types."""
usb = cast(list[USBMatcher], USB.copy())
integrations = await async_get_custom_components(hass)
for integration in integrations.values():
if not integration.usb:
continue
for entry in integration.usb:
usb.append(
cast(
USBMatcher,
{
"domain": integration.domain,
**{k: v for k, v in entry.items() if k != "known_devices"},
},
)
)
return usb
def homekit_always_discover(iot_class: str | None) -> bool:
"""Return if we should always offer HomeKit control for a device."""
#
# Since we prefer local control, if the integration that is being
# discovered is cloud AND the HomeKit device is UNPAIRED we still
# want to discovery it.
#
# Additionally if the integration is polling, HKC offers a local
# push experience for the user to control the device so we want
# to offer that as well.
#
return not iot_class or (iot_class.startswith("cloud") or "polling" in iot_class)
async def async_get_homekit(
hass: HomeAssistant,
) -> dict[str, HomeKitDiscoveredIntegration]:
"""Return cached list of homekit models."""
homekit: dict[str, HomeKitDiscoveredIntegration] = {
model: HomeKitDiscoveredIntegration(
cast(str, details["domain"]), cast(bool, details["always_discover"])
)
for model, details in HOMEKIT.items()
}
integrations = await async_get_custom_components(hass)
for integration in integrations.values():
if (
not integration.homekit
or "models" not in integration.homekit
or not integration.homekit["models"]
):
continue
for model in integration.homekit["models"]:
homekit[model] = HomeKitDiscoveredIntegration(
integration.domain,
homekit_always_discover(integration.iot_class),
)
return homekit
async def async_get_ssdp(hass: HomeAssistant) -> dict[str, list[dict[str, str]]]:
"""Return cached list of ssdp mappings."""
ssdp: dict[str, list[dict[str, str]]] = SSDP.copy()
integrations = await async_get_custom_components(hass)
for integration in integrations.values():
if not integration.ssdp:
continue
ssdp[integration.domain] = integration.ssdp
return ssdp
async def async_get_mqtt(hass: HomeAssistant) -> dict[str, list[str]]:
"""Return cached list of MQTT mappings."""
mqtt: dict[str, list[str]] = MQTT.copy()
integrations = await async_get_custom_components(hass)
for integration in integrations.values():
if not integration.mqtt:
continue
mqtt[integration.domain] = integration.mqtt
return mqtt
@callback
def async_register_preload_platform(hass: HomeAssistant, platform_name: str) -> None:
"""Register a platform to be preloaded."""
preload_platforms = hass.data[DATA_PRELOAD_PLATFORMS]
if platform_name not in preload_platforms:
preload_platforms.append(platform_name)
class Integration:
"""An integration in Home Assistant."""
@classmethod
def resolve_from_root(
cls, hass: HomeAssistant, root_module: ModuleType, domain: str
) -> Integration | None:
"""Resolve an integration from a root module."""
for base in root_module.__path__:
manifest_path = pathlib.Path(base) / domain / "manifest.json"
if not manifest_path.is_file():
continue
try:
manifest = cast(Manifest, json_loads(manifest_path.read_text()))
except JSON_DECODE_EXCEPTIONS as err:
_LOGGER.error(
"Error parsing manifest.json file at %s: %s", manifest_path, err
)
continue
file_path = manifest_path.parent
# Avoid the listdir for virtual integrations
# as they cannot have any platforms
is_virtual = manifest.get("integration_type") == "virtual"
integration = cls(
hass,
f"{root_module.__name__}.{domain}",
file_path,
manifest,
None if is_virtual else set(os.listdir(file_path)),
)
if not integration.import_executor:
_LOGGER.warning(IMPORT_EVENT_LOOP_WARNING, integration.domain)
if integration.is_built_in:
return integration
_LOGGER.warning(CUSTOM_WARNING, integration.domain)
if integration.version is None:
_LOGGER.error(
(
"The custom integration '%s' does not have a version key in the"
" manifest file and was blocked from loading. See"
" https://developers.home-assistant.io"
"/blog/2021/01/29/custom-integration-changes#versions"
" for more details"
),
integration.domain,
)
return None
try:
AwesomeVersion(
integration.version,
ensure_strategy=[
AwesomeVersionStrategy.CALVER,
AwesomeVersionStrategy.SEMVER,
AwesomeVersionStrategy.SIMPLEVER,
AwesomeVersionStrategy.BUILDVER,
AwesomeVersionStrategy.PEP440,
],
)
except AwesomeVersionException:
_LOGGER.error(
(
"The custom integration '%s' does not have a valid version key"
" (%s) in the manifest file and was blocked from loading. See"
" https://developers.home-assistant.io"
"/blog/2021/01/29/custom-integration-changes#versions"
" for more details"
),
integration.domain,
integration.version,
)
return None
if blocked := BLOCKED_CUSTOM_INTEGRATIONS.get(integration.domain):
if _version_blocked(integration.version, blocked):
_LOGGER.error(
(
"Version %s of custom integration '%s' %s and was blocked "
"from loading, please %s"
),
integration.version,
integration.domain,
blocked.reason,
async_suggest_report_issue(None, integration=integration),
)
return None
return integration
return None
def __init__(
self,
hass: HomeAssistant,
pkg_path: str,
file_path: pathlib.Path,
manifest: Manifest,
top_level_files: set[str] | None = None,
) -> None:
"""Initialize an integration."""
self.hass = hass
self.pkg_path = pkg_path
self.file_path = file_path
self.manifest = manifest
manifest["is_built_in"] = self.is_built_in
if self.dependencies:
self._all_dependencies_resolved: bool | None = None
self._all_dependencies: set[str] | None = None
else:
self._all_dependencies_resolved = True
self._all_dependencies = set()
self._platforms_to_preload = hass.data[DATA_PRELOAD_PLATFORMS]
self._component_future: asyncio.Future[ComponentProtocol] | None = None
self._import_futures: dict[str, asyncio.Future[ModuleType]] = {}
self._cache = hass.data[DATA_COMPONENTS]
self._missing_platforms_cache = hass.data[DATA_MISSING_PLATFORMS]
self._top_level_files = top_level_files or set()
_LOGGER.info("Loaded %s from %s", self.domain, pkg_path)
@cached_property
def manifest_json_fragment(self) -> json_fragment:
"""Return manifest as a JSON fragment."""
return json_fragment(json_bytes(self.manifest))
@cached_property
def name(self) -> str:
"""Return name."""
return self.manifest["name"]
@cached_property
def disabled(self) -> str | None:
"""Return reason integration is disabled."""
return self.manifest.get("disabled")
@cached_property
def domain(self) -> str:
"""Return domain."""
return self.manifest["domain"]
@cached_property
def dependencies(self) -> list[str]:
"""Return dependencies."""
return self.manifest.get("dependencies", [])
@cached_property
def after_dependencies(self) -> list[str]:
"""Return after_dependencies."""
return self.manifest.get("after_dependencies", [])
@cached_property
def requirements(self) -> list[str]:
"""Return requirements."""
return self.manifest.get("requirements", [])
@cached_property
def config_flow(self) -> bool:
"""Return config_flow."""
return self.manifest.get("config_flow") or False
@cached_property
def documentation(self) -> str | None:
"""Return documentation."""
return self.manifest.get("documentation")
@cached_property
def issue_tracker(self) -> str | None:
"""Return issue tracker link."""
return self.manifest.get("issue_tracker")
@cached_property
def loggers(self) -> list[str] | None:
"""Return list of loggers used by the integration."""
return self.manifest.get("loggers")
@cached_property
def quality_scale(self) -> str | None:
"""Return Integration Quality Scale."""
return self.manifest.get("quality_scale")
@cached_property
def iot_class(self) -> str | None:
"""Return the integration IoT Class."""
return self.manifest.get("iot_class")
@cached_property
def integration_type(
self,
) -> Literal[
"entity", "device", "hardware", "helper", "hub", "service", "system", "virtual"
]:
"""Return the integration type."""
return self.manifest.get("integration_type", "hub")
@cached_property
def import_executor(self) -> bool:
"""Import integration in the executor."""
# If the integration does not explicitly set import_executor, we default to
# True.
return self.manifest.get("import_executor", True)
@cached_property
def has_translations(self) -> bool:
"""Return if the integration has translations."""
return "translations" in self._top_level_files
@cached_property
def has_services(self) -> bool:
"""Return if the integration has services."""
return "services.yaml" in self._top_level_files
@property
def mqtt(self) -> list[str] | None:
"""Return Integration MQTT entries."""
return self.manifest.get("mqtt")
@property
def ssdp(self) -> list[dict[str, str]] | None:
"""Return Integration SSDP entries."""
return self.manifest.get("ssdp")
@property
def zeroconf(self) -> list[str | dict[str, str]] | None:
"""Return Integration zeroconf entries."""
return self.manifest.get("zeroconf")
@property
def bluetooth(self) -> list[dict[str, str | int]] | None:
"""Return Integration bluetooth entries."""
return self.manifest.get("bluetooth")
@property
def dhcp(self) -> list[dict[str, str | bool]] | None:
"""Return Integration dhcp entries."""
return self.manifest.get("dhcp")
@property
def usb(self) -> list[dict[str, str]] | None:
"""Return Integration usb entries."""
return self.manifest.get("usb")
@property
def homekit(self) -> dict[str, list[str]] | None:
"""Return Integration homekit entries."""
return self.manifest.get("homekit")
@property
def is_built_in(self) -> bool:
"""Test if package is a built-in integration."""
return self.pkg_path.startswith(PACKAGE_BUILTIN)
@property
def version(self) -> AwesomeVersion | None:
"""Return the version of the integration."""
if "version" not in self.manifest:
return None
return AwesomeVersion(self.manifest["version"])
@cached_property
def single_config_entry(self) -> bool:
"""Return if the integration supports a single config entry only."""
return self.manifest.get("single_config_entry", False)
@property
def all_dependencies(self) -> set[str]:
"""Return all dependencies including sub-dependencies."""
if self._all_dependencies is None:
raise RuntimeError("Dependencies not resolved!")
return self._all_dependencies
@property
def all_dependencies_resolved(self) -> bool:
"""Return if all dependencies have been resolved."""
return self._all_dependencies_resolved is not None
async def resolve_dependencies(self) -> bool:
"""Resolve all dependencies."""
if self._all_dependencies_resolved is not None:
return self._all_dependencies_resolved
self._all_dependencies_resolved = False
try:
dependencies = await _async_component_dependencies(self.hass, self)
except IntegrationNotFound as err:
_LOGGER.error(
(
"Unable to resolve dependencies for %s: we are unable to resolve"
" (sub)dependency %s"
),
self.domain,
err.domain,
)
except CircularDependency as err:
_LOGGER.error(
(
"Unable to resolve dependencies for %s: it contains a circular"
" dependency: %s -> %s"
),
self.domain,
err.from_domain,
err.to_domain,
)
else:
dependencies.discard(self.domain)
self._all_dependencies = dependencies
self._all_dependencies_resolved = True
return self._all_dependencies_resolved
async def async_get_component(self) -> ComponentProtocol:
"""Return the component.
This method will load the component if it's not already loaded
and will check if import_executor is set and load it in the executor,
otherwise it will load it in the event loop.
"""
domain = self.domain
if domain in (cache := self._cache):
return cache[domain]
if self._component_future:
return await self._component_future
if debug := _LOGGER.isEnabledFor(logging.DEBUG):
start = time.perf_counter()
# Some integrations fail on import because they call functions incorrectly.
# So we do it before validating config to catch these errors.
load_executor = self.import_executor and (
self.pkg_path not in sys.modules
or (self.config_flow and f"{self.pkg_path}.config_flow" not in sys.modules)
)
if not load_executor:
comp = self._get_component()
if debug:
_LOGGER.debug(
"Component %s import took %.3f seconds (loaded_executor=False)",
self.domain,
time.perf_counter() - start,
)
return comp
self._component_future = self.hass.loop.create_future()
try:
try:
comp = await self.hass.async_add_import_executor_job(
self._get_component, True
)
except ModuleNotFoundError:
raise
except ImportError as ex:
load_executor = False
_LOGGER.debug(
"Failed to import %s in executor", self.domain, exc_info=ex
)
# If importing in the executor deadlocks because there is a circular