forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.py
1352 lines (1132 loc) · 45.5 KB
/
config.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
"""Module to help with parsing and generating configuration files."""
from __future__ import annotations
import asyncio
from collections import OrderedDict
from collections.abc import Callable, Hashable, Iterable, Sequence
from contextlib import suppress
from dataclasses import dataclass
from enum import StrEnum
from functools import partial, reduce
import logging
import operator
import os
from pathlib import Path
import re
import shutil
from types import ModuleType
from typing import TYPE_CHECKING, Any
from awesomeversion import AwesomeVersion
import voluptuous as vol
from voluptuous.humanize import MAX_VALIDATION_ERROR_ITEM_LENGTH
from yaml.error import MarkedYAMLError
from .const import CONF_PACKAGES, CONF_PLATFORM, __version__
from .core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback
from .core_config import _PACKAGE_DEFINITION_SCHEMA, _PACKAGES_CONFIG_SCHEMA
from .exceptions import ConfigValidationError, HomeAssistantError
from .helpers import config_validation as cv
from .helpers.translation import async_get_exception_message
from .helpers.typing import ConfigType
from .loader import ComponentProtocol, Integration, IntegrationNotFound
from .requirements import RequirementsNotFound, async_get_integration_with_requirements
from .util.async_ import create_eager_task
from .util.package import is_docker_env
from .util.yaml import SECRET_YAML, Secrets, YamlTypeError, load_yaml_dict
from .util.yaml.objects import NodeStrClass
_LOGGER = logging.getLogger(__name__)
RE_YAML_ERROR = re.compile(r"homeassistant\.util\.yaml")
RE_ASCII = re.compile(r"\033\[[^m]*m")
YAML_CONFIG_FILE = "configuration.yaml"
VERSION_FILE = ".HA_VERSION"
CONFIG_DIR_NAME = ".homeassistant"
AUTOMATION_CONFIG_PATH = "automations.yaml"
SCRIPT_CONFIG_PATH = "scripts.yaml"
SCENE_CONFIG_PATH = "scenes.yaml"
LOAD_EXCEPTIONS = (ImportError, FileNotFoundError)
INTEGRATION_LOAD_EXCEPTIONS = (IntegrationNotFound, RequirementsNotFound)
SAFE_MODE_FILENAME = "safe-mode"
DEFAULT_CONFIG = f"""
# Loads default set of integrations. Do not remove.
default_config:
# Load frontend themes from the themes folder
frontend:
themes: !include_dir_merge_named themes
automation: !include {AUTOMATION_CONFIG_PATH}
script: !include {SCRIPT_CONFIG_PATH}
scene: !include {SCENE_CONFIG_PATH}
"""
DEFAULT_SECRETS = """
# Use this file to store secrets like usernames and passwords.
# Learn more at https://www.home-assistant.io/docs/configuration/secrets/
some_password: welcome
"""
TTS_PRE_92 = """
tts:
- platform: google
"""
TTS_92 = """
tts:
- platform: google_translate
service_name: google_say
"""
class ConfigErrorTranslationKey(StrEnum):
"""Config error translation keys for config errors."""
# translation keys with a generated config related message text
CONFIG_VALIDATION_ERR = "config_validation_err"
PLATFORM_CONFIG_VALIDATION_ERR = "platform_config_validation_err"
# translation keys with a general static message text
COMPONENT_IMPORT_ERR = "component_import_err"
CONFIG_PLATFORM_IMPORT_ERR = "config_platform_import_err"
CONFIG_VALIDATOR_UNKNOWN_ERR = "config_validator_unknown_err"
CONFIG_SCHEMA_UNKNOWN_ERR = "config_schema_unknown_err"
PLATFORM_COMPONENT_LOAD_ERR = "platform_component_load_err"
PLATFORM_COMPONENT_LOAD_EXC = "platform_component_load_exc"
PLATFORM_SCHEMA_VALIDATOR_ERR = "platform_schema_validator_err"
# translation key in case multiple errors occurred
MULTIPLE_INTEGRATION_CONFIG_ERRORS = "multiple_integration_config_errors"
_CONFIG_LOG_SHOW_STACK_TRACE: dict[ConfigErrorTranslationKey, bool] = {
ConfigErrorTranslationKey.COMPONENT_IMPORT_ERR: False,
ConfigErrorTranslationKey.CONFIG_PLATFORM_IMPORT_ERR: False,
ConfigErrorTranslationKey.CONFIG_VALIDATOR_UNKNOWN_ERR: True,
ConfigErrorTranslationKey.CONFIG_SCHEMA_UNKNOWN_ERR: True,
ConfigErrorTranslationKey.PLATFORM_COMPONENT_LOAD_ERR: False,
ConfigErrorTranslationKey.PLATFORM_COMPONENT_LOAD_EXC: True,
ConfigErrorTranslationKey.PLATFORM_SCHEMA_VALIDATOR_ERR: True,
}
@dataclass
class ConfigExceptionInfo:
"""Configuration exception info class."""
exception: Exception
translation_key: ConfigErrorTranslationKey
platform_path: str
config: ConfigType
integration_link: str | None
@dataclass
class IntegrationConfigInfo:
"""Configuration for an integration and exception information."""
config: ConfigType | None
exception_info_list: list[ConfigExceptionInfo]
def get_default_config_dir() -> str:
"""Put together the default configuration directory based on the OS."""
data_dir = os.path.expanduser("~")
return os.path.join(data_dir, CONFIG_DIR_NAME)
async def async_ensure_config_exists(hass: HomeAssistant) -> bool:
"""Ensure a configuration file exists in given configuration directory.
Creating a default one if needed.
Return boolean if configuration dir is ready to go.
"""
config_path = hass.config.path(YAML_CONFIG_FILE)
if os.path.isfile(config_path):
return True
print( # noqa: T201
"Unable to find configuration. Creating default one in", hass.config.config_dir
)
return await async_create_default_config(hass)
async def async_create_default_config(hass: HomeAssistant) -> bool:
"""Create a default configuration file in given configuration directory.
Return if creation was successful.
"""
return await hass.async_add_executor_job(
_write_default_config, hass.config.config_dir
)
def _write_default_config(config_dir: str) -> bool:
"""Write the default config."""
config_path = os.path.join(config_dir, YAML_CONFIG_FILE)
secret_path = os.path.join(config_dir, SECRET_YAML)
version_path = os.path.join(config_dir, VERSION_FILE)
automation_yaml_path = os.path.join(config_dir, AUTOMATION_CONFIG_PATH)
script_yaml_path = os.path.join(config_dir, SCRIPT_CONFIG_PATH)
scene_yaml_path = os.path.join(config_dir, SCENE_CONFIG_PATH)
# Writing files with YAML does not create the most human readable results
# So we're hard coding a YAML template.
try:
with open(config_path, "w", encoding="utf8") as config_file:
config_file.write(DEFAULT_CONFIG)
if not os.path.isfile(secret_path):
with open(secret_path, "w", encoding="utf8") as secret_file:
secret_file.write(DEFAULT_SECRETS)
with open(version_path, "w", encoding="utf8") as version_file:
version_file.write(__version__)
if not os.path.isfile(automation_yaml_path):
with open(automation_yaml_path, "w", encoding="utf8") as automation_file:
automation_file.write("[]")
if not os.path.isfile(script_yaml_path):
with open(script_yaml_path, "w", encoding="utf8"):
pass
if not os.path.isfile(scene_yaml_path):
with open(scene_yaml_path, "w", encoding="utf8"):
pass
except OSError:
print( # noqa: T201
f"Unable to create default configuration file {config_path}"
)
return False
return True
async def async_hass_config_yaml(hass: HomeAssistant) -> dict:
"""Load YAML from a Home Assistant configuration file.
This function allows a component inside the asyncio loop to reload its
configuration by itself. Include package merge.
"""
secrets = Secrets(Path(hass.config.config_dir))
# Not using async_add_executor_job because this is an internal method.
try:
config = await hass.loop.run_in_executor(
None,
load_yaml_config_file,
hass.config.path(YAML_CONFIG_FILE),
secrets,
)
except HomeAssistantError as exc:
if not (base_exc := exc.__cause__) or not isinstance(base_exc, MarkedYAMLError):
raise
# Rewrite path to offending YAML file to be relative the hass config dir
if base_exc.context_mark and base_exc.context_mark.name:
base_exc.context_mark.name = _relpath(hass, base_exc.context_mark.name)
if base_exc.problem_mark and base_exc.problem_mark.name:
base_exc.problem_mark.name = _relpath(hass, base_exc.problem_mark.name)
raise
invalid_domains = []
for key in config:
try:
cv.domain_key(key)
except vol.Invalid as exc:
suffix = ""
if annotation := find_annotation(config, exc.path):
suffix = f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
_LOGGER.error("Invalid domain '%s'%s", key, suffix)
invalid_domains.append(key)
for invalid_domain in invalid_domains:
config.pop(invalid_domain)
core_config = config.get(HOMEASSISTANT_DOMAIN, {})
try:
await merge_packages_config(hass, config, core_config.get(CONF_PACKAGES, {}))
except vol.Invalid as exc:
suffix = ""
if annotation := find_annotation(
config, [HOMEASSISTANT_DOMAIN, CONF_PACKAGES, *exc.path]
):
suffix = f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
_LOGGER.error(
"Invalid package configuration '%s'%s: %s", CONF_PACKAGES, suffix, exc
)
core_config[CONF_PACKAGES] = {}
return config
def load_yaml_config_file(
config_path: str, secrets: Secrets | None = None
) -> dict[Any, Any]:
"""Parse a YAML configuration file.
Raises FileNotFoundError or HomeAssistantError.
This method needs to run in an executor.
"""
try:
conf_dict = load_yaml_dict(config_path, secrets)
except YamlTypeError as exc:
msg = (
f"The configuration file {os.path.basename(config_path)} "
"does not contain a dictionary"
)
_LOGGER.error(msg)
raise HomeAssistantError(msg) from exc
# Convert values to dictionaries if they are None
for key, value in conf_dict.items():
conf_dict[key] = value or {}
return conf_dict
def process_ha_config_upgrade(hass: HomeAssistant) -> None:
"""Upgrade configuration if necessary.
This method needs to run in an executor.
"""
version_path = hass.config.path(VERSION_FILE)
try:
with open(version_path, encoding="utf8") as inp:
conf_version = inp.readline().strip()
except FileNotFoundError:
# Last version to not have this file
conf_version = "0.7.7"
if conf_version == __version__:
return
_LOGGER.info(
"Upgrading configuration directory from %s to %s", conf_version, __version__
)
version_obj = AwesomeVersion(conf_version)
if version_obj < AwesomeVersion("0.50"):
# 0.50 introduced persistent deps dir.
lib_path = hass.config.path("deps")
if os.path.isdir(lib_path):
shutil.rmtree(lib_path)
if version_obj < AwesomeVersion("0.92"):
# 0.92 moved google/tts.py to google_translate/tts.py
config_path = hass.config.path(YAML_CONFIG_FILE)
with open(config_path, encoding="utf-8") as config_file:
config_raw = config_file.read()
if TTS_PRE_92 in config_raw:
_LOGGER.info("Migrating google tts to google_translate tts")
config_raw = config_raw.replace(TTS_PRE_92, TTS_92)
try:
with open(config_path, "w", encoding="utf-8") as config_file:
config_file.write(config_raw)
except OSError:
_LOGGER.exception("Migrating to google_translate tts failed")
if version_obj < AwesomeVersion("0.94") and is_docker_env():
# In 0.94 we no longer install packages inside the deps folder when
# running inside a Docker container.
lib_path = hass.config.path("deps")
if os.path.isdir(lib_path):
shutil.rmtree(lib_path)
with open(version_path, "w", encoding="utf8") as outp:
outp.write(__version__)
@callback
def async_log_schema_error(
exc: vol.Invalid,
domain: str,
config: dict,
hass: HomeAssistant,
link: str | None = None,
) -> None:
"""Log a schema validation error."""
message = format_schema_error(hass, exc, domain, config, link)
_LOGGER.error(message)
@callback
def async_log_config_validator_error(
exc: vol.Invalid | HomeAssistantError,
domain: str,
config: dict,
hass: HomeAssistant,
link: str | None = None,
) -> None:
"""Log an error from a custom config validator."""
if isinstance(exc, vol.Invalid):
async_log_schema_error(exc, domain, config, hass, link)
return
message = format_homeassistant_error(hass, exc, domain, config, link)
_LOGGER.error(message, exc_info=exc)
def _get_annotation(item: Any) -> tuple[str, int | str] | None:
if not hasattr(item, "__config_file__"):
return None
return (getattr(item, "__config_file__"), getattr(item, "__line__", "?"))
def _get_by_path(data: dict | list, items: list[Hashable]) -> Any:
"""Access a nested object in root by item sequence.
Returns None in case of error.
"""
try:
return reduce(operator.getitem, items, data) # type: ignore[arg-type]
except (KeyError, IndexError, TypeError):
return None
def find_annotation(
config: dict | list, path: list[Hashable]
) -> tuple[str, int | str] | None:
"""Find file/line annotation for a node in config pointed to by path.
If the node pointed to is a dict or list, prefer the annotation for the key in
the key/value pair defining the dict or list.
If the node is not annotated, try the parent node.
"""
def find_annotation_for_key(
item: dict, path: list[Hashable], tail: Hashable
) -> tuple[str, int | str] | None:
for key in item:
if key == tail:
if annotation := _get_annotation(key):
return annotation
break
return None
def find_annotation_rec(
config: dict | list, path: list[Hashable], tail: Hashable | None
) -> tuple[str, int | str] | None:
item = _get_by_path(config, path)
if isinstance(item, dict) and tail is not None:
if tail_annotation := find_annotation_for_key(item, path, tail):
return tail_annotation
if (
isinstance(item, (dict, list))
and path
and (
key_annotation := find_annotation_for_key(
_get_by_path(config, path[:-1]), path[:-1], path[-1]
)
)
):
return key_annotation
if annotation := _get_annotation(item):
return annotation
if not path:
return None
tail = path.pop()
if annotation := find_annotation_rec(config, path, tail):
return annotation
return _get_annotation(item)
return find_annotation_rec(config, list(path), None)
def _relpath(hass: HomeAssistant, path: str) -> str:
"""Return path relative to the Home Assistant config dir."""
return os.path.relpath(path, hass.config.config_dir)
def stringify_invalid(
hass: HomeAssistant,
exc: vol.Invalid,
domain: str,
config: dict,
link: str | None,
max_sub_error_length: int,
) -> str:
"""Stringify voluptuous.Invalid.
This is an alternative to the custom __str__ implemented in
voluptuous.error.Invalid. The modifications are:
- Format the path delimited by -> instead of @data[]
- Prefix with domain, file and line of the error
- Suffix with a link to the documentation
- Give a more user friendly output for unknown options
- Give a more user friendly output for missing options
"""
if "." in domain:
integration_domain, _, platform_domain = domain.partition(".")
message_prefix = (
f"Invalid config for '{platform_domain}' from integration "
f"'{integration_domain}'"
)
else:
message_prefix = f"Invalid config for '{domain}'"
if domain != HOMEASSISTANT_DOMAIN and link:
message_suffix = f", please check the docs at {link}"
else:
message_suffix = ""
if annotation := find_annotation(config, exc.path):
message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
path = "->".join(str(m) for m in exc.path)
if exc.error_message == "extra keys not allowed":
return (
f"{message_prefix}: '{exc.path[-1]}' is an invalid option for '{domain}', "
f"check: {path}{message_suffix}"
)
if exc.error_message == "required key not provided":
return (
f"{message_prefix}: required key '{exc.path[-1]}' not provided"
f"{message_suffix}"
)
# This function is an alternative to the stringification done by
# vol.Invalid.__str__, so we need to call Exception.__str__ here
# instead of str(exc)
output = Exception.__str__(exc)
if error_type := exc.error_type:
output += " for " + error_type
offending_item_summary = repr(_get_by_path(config, exc.path))
if len(offending_item_summary) > max_sub_error_length:
offending_item_summary = (
f"{offending_item_summary[: max_sub_error_length - 3]}..."
)
return (
f"{message_prefix}: {output} '{path}', got {offending_item_summary}"
f"{message_suffix}"
)
def humanize_error(
hass: HomeAssistant,
validation_error: vol.Invalid,
domain: str,
config: dict,
link: str | None,
max_sub_error_length: int = MAX_VALIDATION_ERROR_ITEM_LENGTH,
) -> str:
"""Provide a more helpful + complete validation error message.
This is a modified version of voluptuous.error.Invalid.__str__,
the modifications make some minor changes to the formatting.
"""
if isinstance(validation_error, vol.MultipleInvalid):
return "\n".join(
sorted(
humanize_error(
hass, sub_error, domain, config, link, max_sub_error_length
)
for sub_error in validation_error.errors
)
)
return stringify_invalid(
hass, validation_error, domain, config, link, max_sub_error_length
)
@callback
def format_homeassistant_error(
hass: HomeAssistant,
exc: HomeAssistantError,
domain: str,
config: dict,
link: str | None = None,
) -> str:
"""Format HomeAssistantError thrown by a custom config validator."""
if "." in domain:
integration_domain, _, platform_domain = domain.partition(".")
message_prefix = (
f"Invalid config for '{platform_domain}' from integration "
f"'{integration_domain}'"
)
else:
message_prefix = f"Invalid config for '{domain}'"
# HomeAssistantError raised by custom config validator has no path to the
# offending configuration key, use the domain key as path instead.
if annotation := find_annotation(config, [domain]):
message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
message = f"{message_prefix}: {str(exc) or repr(exc)}"
if domain != HOMEASSISTANT_DOMAIN and link:
message += f", please check the docs at {link}"
return message
@callback
def format_schema_error(
hass: HomeAssistant,
exc: vol.Invalid,
domain: str,
config: dict,
link: str | None = None,
) -> str:
"""Format configuration validation error."""
return humanize_error(hass, exc, domain, config, link)
def _log_pkg_error(
hass: HomeAssistant, package: str, component: str | None, config: dict, message: str
) -> None:
"""Log an error while merging packages."""
message_prefix = f"Setup of package '{package}'"
if annotation := find_annotation(
config, [HOMEASSISTANT_DOMAIN, CONF_PACKAGES, package]
):
message_prefix += f" at {_relpath(hass, annotation[0])}, line {annotation[1]}"
_LOGGER.error("%s failed: %s", message_prefix, message)
def _identify_config_schema(module: ComponentProtocol) -> str | None:
"""Extract the schema and identify list or dict based."""
if not isinstance(module.CONFIG_SCHEMA, vol.Schema):
return None # type: ignore[unreachable]
schema = module.CONFIG_SCHEMA.schema
if isinstance(schema, vol.All):
for subschema in schema.validators:
if isinstance(subschema, dict):
schema = subschema
break
else:
return None
try:
key = next(k for k in schema if k == module.DOMAIN)
except (TypeError, AttributeError, StopIteration):
return None
except Exception:
_LOGGER.exception("Unexpected error identifying config schema")
return None
if hasattr(key, "default") and not isinstance(
key.default, vol.schema_builder.Undefined
):
default_value = module.CONFIG_SCHEMA({module.DOMAIN: key.default()})[
module.DOMAIN
]
if isinstance(default_value, dict):
return "dict"
if isinstance(default_value, list):
return "list"
return None
domain_schema = schema[key]
t_schema = str(domain_schema)
if t_schema.startswith("{") or "schema_with_slug_keys" in t_schema:
return "dict"
if t_schema.startswith(("[", "All(<function ensure_list")):
return "list"
return None
def _validate_package_definition(name: str, conf: Any) -> None:
"""Validate basic package definition properties."""
cv.slug(name)
_PACKAGE_DEFINITION_SCHEMA(conf)
def _recursive_merge(conf: dict[str, Any], package: dict[str, Any]) -> str | None:
"""Merge package into conf, recursively."""
duplicate_key: str | None = None
for key, pack_conf in package.items():
if isinstance(pack_conf, dict):
if not pack_conf:
continue
conf[key] = conf.get(key, OrderedDict())
duplicate_key = _recursive_merge(conf=conf[key], package=pack_conf)
elif isinstance(pack_conf, list):
conf[key] = cv.remove_falsy(
cv.ensure_list(conf.get(key)) + cv.ensure_list(pack_conf)
)
else:
if conf.get(key) is not None:
return key
conf[key] = pack_conf
return duplicate_key
async def merge_packages_config(
hass: HomeAssistant,
config: dict,
packages: dict[str, Any],
_log_pkg_error: Callable[
[HomeAssistant, str, str | None, dict, str], None
] = _log_pkg_error,
) -> dict:
"""Merge packages into the top-level configuration.
Ignores packages that cannot be setup. Mutates config. Raises
vol.Invalid if whole package config is invalid.
"""
_PACKAGES_CONFIG_SCHEMA(packages)
invalid_packages = []
for pack_name, pack_conf in packages.items():
try:
_validate_package_definition(pack_name, pack_conf)
except vol.Invalid as exc:
_log_pkg_error(
hass,
pack_name,
None,
config,
f"Invalid package definition '{pack_name}': {exc!s}. Package "
f"will not be initialized",
)
invalid_packages.append(pack_name)
continue
for comp_name, comp_conf in pack_conf.items():
if comp_name == HOMEASSISTANT_DOMAIN:
continue
try:
domain = cv.domain_key(comp_name)
except vol.Invalid:
_log_pkg_error(
hass, pack_name, comp_name, config, f"Invalid domain '{comp_name}'"
)
continue
try:
integration = await async_get_integration_with_requirements(
hass, domain
)
component = await integration.async_get_component()
except LOAD_EXCEPTIONS as exc:
_log_pkg_error(
hass,
pack_name,
comp_name,
config,
f"Integration {comp_name} caused error: {exc!s}",
)
continue
except INTEGRATION_LOAD_EXCEPTIONS as exc:
_log_pkg_error(hass, pack_name, comp_name, config, str(exc))
continue
try:
config_platform: (
ModuleType | None
) = await integration.async_get_platform("config")
# Test if config platform has a config validator
if not hasattr(config_platform, "async_validate_config"):
config_platform = None
except ImportError:
config_platform = None
merge_list = False
# If integration has a custom config validator, it needs to provide a hint.
if config_platform is not None:
merge_list = config_platform.PACKAGE_MERGE_HINT == "list"
if not merge_list:
merge_list = hasattr(component, "PLATFORM_SCHEMA")
if not merge_list and hasattr(component, "CONFIG_SCHEMA"):
merge_list = _identify_config_schema(component) == "list"
if merge_list:
config[comp_name] = cv.remove_falsy(
cv.ensure_list(config.get(comp_name)) + cv.ensure_list(comp_conf)
)
continue
if comp_conf is None:
comp_conf = OrderedDict()
if not isinstance(comp_conf, dict):
_log_pkg_error(
hass,
pack_name,
comp_name,
config,
f"integration '{comp_name}' cannot be merged, expected a dict",
)
continue
if comp_name not in config or config[comp_name] is None:
config[comp_name] = OrderedDict()
if not isinstance(config[comp_name], dict):
_log_pkg_error(
hass,
pack_name,
comp_name,
config,
(
f"integration '{comp_name}' cannot be merged, dict expected in "
"main config"
),
)
continue
duplicate_key = _recursive_merge(conf=config[comp_name], package=comp_conf)
if duplicate_key:
_log_pkg_error(
hass,
pack_name,
comp_name,
config,
f"integration '{comp_name}' has duplicate key '{duplicate_key}'",
)
for pack_name in invalid_packages:
packages.pop(pack_name, {})
return config
@callback
def _get_log_message_and_stack_print_pref(
hass: HomeAssistant, domain: str, platform_exception: ConfigExceptionInfo
) -> tuple[str | None, bool, dict[str, str]]:
"""Get message to log and print stack trace preference."""
exception = platform_exception.exception
platform_path = platform_exception.platform_path
platform_config = platform_exception.config
link = platform_exception.integration_link
placeholders: dict[str, str] = {
"domain": domain,
"error": str(exception),
"p_name": platform_path,
"config_file": "?",
"line": "?",
}
show_stack_trace: bool | None = _CONFIG_LOG_SHOW_STACK_TRACE.get(
platform_exception.translation_key
)
if show_stack_trace is None:
# If no pre defined log_message is set, we generate an enriched error
# message, so we can notify about it during setup
show_stack_trace = False
if isinstance(exception, vol.Invalid):
log_message = format_schema_error(
hass, exception, platform_path, platform_config, link
)
if annotation := find_annotation(platform_config, exception.path):
placeholders["config_file"], line = annotation
placeholders["line"] = str(line)
else:
if TYPE_CHECKING:
assert isinstance(exception, HomeAssistantError)
log_message = format_homeassistant_error(
hass, exception, platform_path, platform_config, link
)
if annotation := find_annotation(platform_config, [platform_path]):
placeholders["config_file"], line = annotation
placeholders["line"] = str(line)
show_stack_trace = True
return (log_message, show_stack_trace, placeholders)
# Generate the log message from the English translations
log_message = async_get_exception_message(
HOMEASSISTANT_DOMAIN,
platform_exception.translation_key,
translation_placeholders=placeholders,
)
return (log_message, show_stack_trace, placeholders)
async def async_process_component_and_handle_errors(
hass: HomeAssistant,
config: ConfigType,
integration: Integration,
raise_on_failure: bool = False,
) -> ConfigType | None:
"""Process and component configuration and handle errors.
In case of errors:
- Print the error messages to the log.
- Raise a ConfigValidationError if raise_on_failure is set.
Returns the integration config or `None`.
"""
integration_config_info = await async_process_component_config(
hass, config, integration
)
async_handle_component_errors(
hass, integration_config_info, integration, raise_on_failure
)
return async_drop_config_annotations(integration_config_info, integration)
@callback
def async_drop_config_annotations(
integration_config_info: IntegrationConfigInfo,
integration: Integration,
) -> ConfigType | None:
"""Remove file and line annotations from str items in component configuration."""
if (config := integration_config_info.config) is None:
return None
def drop_config_annotations_rec(node: Any) -> Any:
if isinstance(node, dict):
# Some integrations store metadata in custom dict classes, preserve those
tmp = dict(node)
node.clear()
node.update(
(drop_config_annotations_rec(k), drop_config_annotations_rec(v))
for k, v in tmp.items()
)
return node
if isinstance(node, list):
return [drop_config_annotations_rec(v) for v in node]
if isinstance(node, NodeStrClass):
return str(node)
return node
# Don't drop annotations from the homeassistant integration because it may
# have configuration for other integrations as packages.
if integration.domain in config and integration.domain != HOMEASSISTANT_DOMAIN:
drop_config_annotations_rec(config[integration.domain])
return config
@callback
def async_handle_component_errors(
hass: HomeAssistant,
integration_config_info: IntegrationConfigInfo,
integration: Integration,
raise_on_failure: bool = False,
) -> None:
"""Handle component configuration errors from async_process_component_config.
In case of errors:
- Print the error messages to the log.
- Raise a ConfigValidationError if raise_on_failure is set.
"""
if not (config_exception_info := integration_config_info.exception_info_list):
return
platform_exception: ConfigExceptionInfo
domain = integration.domain
placeholders: dict[str, str]
for platform_exception in config_exception_info:
exception = platform_exception.exception
(
log_message,
show_stack_trace,
placeholders,
) = _get_log_message_and_stack_print_pref(hass, domain, platform_exception)
_LOGGER.error(
log_message,
exc_info=exception if show_stack_trace else None,
)
if not raise_on_failure:
return
if len(config_exception_info) == 1:
translation_key = platform_exception.translation_key
else:
translation_key = ConfigErrorTranslationKey.MULTIPLE_INTEGRATION_CONFIG_ERRORS
errors = str(len(config_exception_info))
placeholders = {
"domain": domain,
"errors": errors,
}
raise ConfigValidationError(
translation_key,
[platform_exception.exception for platform_exception in config_exception_info],
translation_domain=HOMEASSISTANT_DOMAIN,
translation_placeholders=placeholders,
)
def config_per_platform(
config: ConfigType, domain: str
) -> Iterable[tuple[str | None, ConfigType]]:
"""Break a component config into different platforms.
For example, will find 'switch', 'switch 2', 'switch 3', .. etc
Async friendly.
"""
for config_key in extract_domain_configs(config, domain):
if not (platform_config := config[config_key]):
continue
if not isinstance(platform_config, list):
platform_config = [platform_config]
item: ConfigType
platform: str | None
for item in platform_config:
try:
platform = item.get(CONF_PLATFORM)
except AttributeError:
platform = None
yield platform, item
def extract_platform_integrations(
config: ConfigType, domains: set[str]
) -> dict[str, set[str]]:
"""Find all the platforms in a configuration.
Returns a dictionary with domain as key and a set of platforms as value.
"""
platform_integrations: dict[str, set[str]] = {}