init home-assistant
This commit is contained in:
80
home-assistant/homeassistant/scripts/__init__.py
Normal file
80
home-assistant/homeassistant/scripts/__init__.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""Home Assistant command line scripts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from collections.abc import Sequence
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
from homeassistant import runner
|
||||
from homeassistant.bootstrap import async_mount_local_lib_path
|
||||
from homeassistant.config import get_default_config_dir
|
||||
from homeassistant.requirements import pip_kwargs
|
||||
from homeassistant.util.package import install_package, is_installed, is_virtual_env
|
||||
|
||||
# mypy: allow-untyped-defs, disallow-any-generics, no-warn-return-any
|
||||
|
||||
|
||||
def run(args: list[str]) -> int:
|
||||
"""Run a script."""
|
||||
scripts = []
|
||||
path = os.path.dirname(__file__)
|
||||
for fil in os.listdir(path):
|
||||
if fil == "__pycache__":
|
||||
continue
|
||||
|
||||
if os.path.isdir(os.path.join(path, fil)):
|
||||
scripts.append(fil)
|
||||
elif fil != "__init__.py" and fil.endswith(".py"):
|
||||
scripts.append(fil[:-3])
|
||||
|
||||
if not args:
|
||||
print("Please specify a script to run.")
|
||||
print("Available scripts:", ", ".join(scripts))
|
||||
return 1
|
||||
|
||||
if args[0] not in scripts:
|
||||
print("Invalid script specified.")
|
||||
print("Available scripts:", ", ".join(scripts))
|
||||
return 1
|
||||
|
||||
script = importlib.import_module(f"homeassistant.scripts.{args[0]}")
|
||||
|
||||
config_dir = extract_config_dir()
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
if not is_virtual_env():
|
||||
loop.run_until_complete(async_mount_local_lib_path(config_dir))
|
||||
|
||||
_pip_kwargs = pip_kwargs(config_dir)
|
||||
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
|
||||
|
||||
for req in getattr(script, "REQUIREMENTS", []):
|
||||
if is_installed(req):
|
||||
continue
|
||||
|
||||
if not install_package(req, **_pip_kwargs):
|
||||
print("Aborting script, could not install dependency", req)
|
||||
return 1
|
||||
|
||||
asyncio.set_event_loop_policy(runner.HassEventLoopPolicy(False))
|
||||
|
||||
return script.run(args[1:])
|
||||
|
||||
|
||||
def extract_config_dir(args: Sequence[str] | None = None) -> str:
|
||||
"""Extract the config dir from the arguments or get the default."""
|
||||
parser = argparse.ArgumentParser(add_help=False)
|
||||
parser.add_argument("-c", "--config", default=None)
|
||||
parsed_args = parser.parse_known_args(args)[0]
|
||||
return (
|
||||
os.path.join(os.getcwd(), parsed_args.config)
|
||||
if parsed_args.config
|
||||
else get_default_config_dir()
|
||||
)
|
||||
126
home-assistant/homeassistant/scripts/auth.py
Normal file
126
home-assistant/homeassistant/scripts/auth.py
Normal file
@@ -0,0 +1,126 @@
|
||||
"""Script to manage users for the Home Assistant auth provider."""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from collections.abc import Sequence
|
||||
import logging
|
||||
import os
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from homeassistant import runner
|
||||
from homeassistant.auth import auth_manager_from_config
|
||||
from homeassistant.auth.providers import homeassistant as hass_auth
|
||||
from homeassistant.config import get_default_config_dir
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
|
||||
# mypy: allow-untyped-calls, allow-untyped-defs
|
||||
|
||||
|
||||
def run(args: Sequence[str] | None) -> None:
|
||||
"""Handle Home Assistant auth provider script."""
|
||||
parser = argparse.ArgumentParser(description="Manage Home Assistant users")
|
||||
parser.add_argument("--script", choices=["auth"])
|
||||
parser.add_argument(
|
||||
"-c",
|
||||
"--config",
|
||||
default=get_default_config_dir(),
|
||||
help="Directory that contains the Home Assistant configuration",
|
||||
)
|
||||
|
||||
subparsers = parser.add_subparsers(dest="func")
|
||||
subparsers.required = True
|
||||
parser_list = subparsers.add_parser("list")
|
||||
parser_list.set_defaults(func=list_users)
|
||||
|
||||
parser_add = subparsers.add_parser("add")
|
||||
parser_add.add_argument("username", type=str)
|
||||
parser_add.add_argument("password", type=str)
|
||||
parser_add.set_defaults(func=add_user)
|
||||
|
||||
parser_validate_login = subparsers.add_parser("validate")
|
||||
parser_validate_login.add_argument("username", type=str)
|
||||
parser_validate_login.add_argument("password", type=str)
|
||||
parser_validate_login.set_defaults(func=validate_login)
|
||||
|
||||
parser_change_pw = subparsers.add_parser("change_password")
|
||||
parser_change_pw.add_argument("username", type=str)
|
||||
parser_change_pw.add_argument("new_password", type=str)
|
||||
parser_change_pw.set_defaults(func=change_password)
|
||||
|
||||
asyncio.set_event_loop_policy(runner.HassEventLoopPolicy(False))
|
||||
asyncio.run(run_command(parser.parse_args(args)))
|
||||
|
||||
|
||||
async def run_command(args: argparse.Namespace) -> None:
|
||||
"""Run the command."""
|
||||
hass = HomeAssistant(os.path.join(os.getcwd(), args.config))
|
||||
await asyncio.gather(dr.async_load(hass), er.async_load(hass))
|
||||
hass.auth = await auth_manager_from_config(hass, [{"type": "homeassistant"}], [])
|
||||
provider = hass.auth.auth_providers[0]
|
||||
await provider.async_initialize()
|
||||
await args.func(hass, provider, args)
|
||||
|
||||
# Triggers save on used storage helpers with delay (core auth)
|
||||
logging.getLogger("homeassistant.core").setLevel(logging.WARNING)
|
||||
|
||||
await hass.async_stop()
|
||||
|
||||
|
||||
async def list_users(
|
||||
hass: HomeAssistant, provider: hass_auth.HassAuthProvider, args: argparse.Namespace
|
||||
) -> None:
|
||||
"""List the users."""
|
||||
count = 0
|
||||
if TYPE_CHECKING:
|
||||
assert provider.data
|
||||
for user in provider.data.users:
|
||||
count += 1
|
||||
print(user["username"])
|
||||
|
||||
print()
|
||||
print("Total users:", count)
|
||||
|
||||
|
||||
async def add_user(
|
||||
hass: HomeAssistant, provider: hass_auth.HassAuthProvider, args: argparse.Namespace
|
||||
) -> None:
|
||||
"""Create a user."""
|
||||
if TYPE_CHECKING:
|
||||
assert provider.data
|
||||
try:
|
||||
provider.data.add_auth(args.username, args.password)
|
||||
except hass_auth.InvalidUser:
|
||||
print("Username already exists!")
|
||||
return
|
||||
|
||||
# Save username/password
|
||||
await provider.data.async_save()
|
||||
print("Auth created")
|
||||
|
||||
|
||||
async def validate_login(
|
||||
hass: HomeAssistant, provider: hass_auth.HassAuthProvider, args: argparse.Namespace
|
||||
) -> None:
|
||||
"""Validate a login."""
|
||||
if TYPE_CHECKING:
|
||||
assert provider.data
|
||||
try:
|
||||
provider.data.validate_login(args.username, args.password)
|
||||
print("Auth valid")
|
||||
except hass_auth.InvalidAuth:
|
||||
print("Auth invalid")
|
||||
|
||||
|
||||
async def change_password(
|
||||
hass: HomeAssistant, provider: hass_auth.HassAuthProvider, args: argparse.Namespace
|
||||
) -> None:
|
||||
"""Change password."""
|
||||
if TYPE_CHECKING:
|
||||
assert provider.data
|
||||
try:
|
||||
provider.data.change_password(args.username, args.new_password)
|
||||
await provider.data.async_save()
|
||||
print("Password changed")
|
||||
except hass_auth.InvalidUser:
|
||||
print("User not found")
|
||||
310
home-assistant/homeassistant/scripts/benchmark/__init__.py
Normal file
310
home-assistant/homeassistant/scripts/benchmark/__init__.py
Normal file
@@ -0,0 +1,310 @@
|
||||
"""Script to run benchmarks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
import logging
|
||||
from timeit import default_timer as timer
|
||||
|
||||
from homeassistant import core
|
||||
from homeassistant.const import EVENT_STATE_CHANGED
|
||||
from homeassistant.helpers.entityfilter import convert_include_exclude_filter
|
||||
from homeassistant.helpers.event import (
|
||||
async_track_state_change,
|
||||
async_track_state_change_event,
|
||||
)
|
||||
from homeassistant.helpers.json import JSON_DUMP
|
||||
|
||||
# mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs
|
||||
# mypy: no-warn-return-any
|
||||
|
||||
BENCHMARKS: dict[str, Callable] = {}
|
||||
|
||||
|
||||
def run(args):
|
||||
"""Handle benchmark commandline script."""
|
||||
# Disable logging
|
||||
logging.getLogger("homeassistant.core").setLevel(logging.CRITICAL)
|
||||
|
||||
parser = argparse.ArgumentParser(description="Run a Home Assistant benchmark.")
|
||||
parser.add_argument("name", choices=BENCHMARKS)
|
||||
parser.add_argument("--script", choices=["benchmark"])
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
bench = BENCHMARKS[args.name]
|
||||
print("Using event loop:", asyncio.get_event_loop_policy().loop_name)
|
||||
|
||||
with suppress(KeyboardInterrupt):
|
||||
while True:
|
||||
asyncio.run(run_benchmark(bench))
|
||||
|
||||
|
||||
async def run_benchmark(bench):
|
||||
"""Run a benchmark."""
|
||||
hass = core.HomeAssistant("")
|
||||
runtime = await bench(hass)
|
||||
print(f"Benchmark {bench.__name__} done in {runtime}s")
|
||||
await hass.async_stop()
|
||||
|
||||
|
||||
def benchmark[_CallableT: Callable](func: _CallableT) -> _CallableT:
|
||||
"""Decorate to mark a benchmark."""
|
||||
BENCHMARKS[func.__name__] = func
|
||||
return func
|
||||
|
||||
|
||||
@benchmark
|
||||
async def fire_events(hass):
|
||||
"""Fire a million events."""
|
||||
count = 0
|
||||
event_name = "benchmark_event"
|
||||
events_to_fire = 10**6
|
||||
|
||||
@core.callback
|
||||
def listener(_):
|
||||
"""Handle event."""
|
||||
nonlocal count
|
||||
count += 1
|
||||
|
||||
hass.bus.async_listen(event_name, listener)
|
||||
|
||||
for _ in range(events_to_fire):
|
||||
hass.bus.async_fire(event_name)
|
||||
|
||||
start = timer()
|
||||
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert count == events_to_fire
|
||||
|
||||
return timer() - start
|
||||
|
||||
|
||||
@benchmark
|
||||
async def fire_events_with_filter(hass):
|
||||
"""Fire a million events with a filter that rejects them."""
|
||||
count = 0
|
||||
event_name = "benchmark_event"
|
||||
events_to_fire = 10**6
|
||||
|
||||
@core.callback
|
||||
def event_filter(event_data):
|
||||
"""Filter event."""
|
||||
return False
|
||||
|
||||
@core.callback
|
||||
def listener(_):
|
||||
"""Handle event."""
|
||||
nonlocal count
|
||||
count += 1
|
||||
|
||||
hass.bus.async_listen(event_name, listener, event_filter=event_filter)
|
||||
|
||||
for _ in range(events_to_fire):
|
||||
hass.bus.async_fire(event_name)
|
||||
|
||||
start = timer()
|
||||
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert count == 0
|
||||
|
||||
return timer() - start
|
||||
|
||||
|
||||
@benchmark
|
||||
async def state_changed_helper(hass):
|
||||
"""Run a million events through state changed helper with 1000 entities."""
|
||||
count = 0
|
||||
entity_id = "light.kitchen"
|
||||
event = asyncio.Event()
|
||||
|
||||
@core.callback
|
||||
def listener(*args):
|
||||
"""Handle event."""
|
||||
nonlocal count
|
||||
count += 1
|
||||
|
||||
if count == 10**6:
|
||||
event.set()
|
||||
|
||||
for idx in range(1000):
|
||||
async_track_state_change(hass, f"{entity_id}{idx}", listener, "off", "on")
|
||||
event_data = {
|
||||
"entity_id": f"{entity_id}0",
|
||||
"old_state": core.State(entity_id, "off"),
|
||||
"new_state": core.State(entity_id, "on"),
|
||||
}
|
||||
|
||||
for _ in range(10**6):
|
||||
hass.bus.async_fire(EVENT_STATE_CHANGED, event_data)
|
||||
|
||||
start = timer()
|
||||
|
||||
await event.wait()
|
||||
|
||||
return timer() - start
|
||||
|
||||
|
||||
@benchmark
|
||||
async def state_changed_event_helper(hass):
|
||||
"""Run a million events through state changed event helper with 1000 entities."""
|
||||
count = 0
|
||||
entity_id = "light.kitchen"
|
||||
events_to_fire = 10**6
|
||||
|
||||
@core.callback
|
||||
def listener(*args):
|
||||
"""Handle event."""
|
||||
nonlocal count
|
||||
count += 1
|
||||
|
||||
async_track_state_change_event(
|
||||
hass, [f"{entity_id}{idx}" for idx in range(1000)], listener
|
||||
)
|
||||
|
||||
event_data = {
|
||||
"entity_id": f"{entity_id}0",
|
||||
"old_state": core.State(entity_id, "off"),
|
||||
"new_state": core.State(entity_id, "on"),
|
||||
}
|
||||
|
||||
for _ in range(events_to_fire):
|
||||
hass.bus.async_fire(EVENT_STATE_CHANGED, event_data)
|
||||
|
||||
start = timer()
|
||||
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert count == events_to_fire
|
||||
|
||||
return timer() - start
|
||||
|
||||
|
||||
@benchmark
|
||||
async def state_changed_event_filter_helper(hass):
|
||||
"""Run a million events through state changed event helper.
|
||||
|
||||
With 1000 entities that all get filtered.
|
||||
"""
|
||||
count = 0
|
||||
entity_id = "light.kitchen"
|
||||
events_to_fire = 10**6
|
||||
|
||||
@core.callback
|
||||
def listener(*args):
|
||||
"""Handle event."""
|
||||
nonlocal count
|
||||
count += 1
|
||||
|
||||
async_track_state_change_event(
|
||||
hass, [f"{entity_id}{idx}" for idx in range(1000)], listener
|
||||
)
|
||||
|
||||
event_data = {
|
||||
"entity_id": "switch.no_listeners",
|
||||
"old_state": core.State(entity_id, "off"),
|
||||
"new_state": core.State(entity_id, "on"),
|
||||
}
|
||||
|
||||
for _ in range(events_to_fire):
|
||||
hass.bus.async_fire(EVENT_STATE_CHANGED, event_data)
|
||||
|
||||
start = timer()
|
||||
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert count == 0
|
||||
|
||||
return timer() - start
|
||||
|
||||
|
||||
@benchmark
|
||||
async def filtering_entity_id(hass):
|
||||
"""Run a 100k state changes through entity filter."""
|
||||
config = {
|
||||
"include": {
|
||||
"domains": [
|
||||
"automation",
|
||||
"script",
|
||||
"group",
|
||||
"media_player",
|
||||
"custom_component",
|
||||
],
|
||||
"entity_globs": [
|
||||
"binary_sensor.*_contact",
|
||||
"binary_sensor.*_occupancy",
|
||||
"binary_sensor.*_detected",
|
||||
"binary_sensor.*_active",
|
||||
"input_*",
|
||||
"device_tracker.*_phone",
|
||||
"switch.*_light",
|
||||
"binary_sensor.*_charging",
|
||||
"binary_sensor.*_lock",
|
||||
"binary_sensor.*_connected",
|
||||
],
|
||||
"entities": [
|
||||
"test.entity_1",
|
||||
"test.entity_2",
|
||||
"binary_sensor.garage_door_open",
|
||||
"test.entity_3",
|
||||
"test.entity_4",
|
||||
],
|
||||
},
|
||||
"exclude": {
|
||||
"domains": ["input_number"],
|
||||
"entity_globs": ["media_player.google_*", "group.all_*"],
|
||||
"entities": [],
|
||||
},
|
||||
}
|
||||
|
||||
entity_ids = [
|
||||
"automation.home_arrival",
|
||||
"script.shut_off_house",
|
||||
"binary_sensor.garage_door_open",
|
||||
"binary_sensor.front_door_lock",
|
||||
"binary_sensor.kitchen_motion_sensor_occupancy",
|
||||
"switch.desk_lamp",
|
||||
"light.dining_room",
|
||||
"input_boolean.guest_staying_over",
|
||||
"person.eleanor_fant",
|
||||
"alert.issue_at_home",
|
||||
"calendar.eleanor_fant_s_calendar",
|
||||
"sun.sun",
|
||||
]
|
||||
|
||||
entities_filter = convert_include_exclude_filter(config)
|
||||
size = len(entity_ids)
|
||||
|
||||
start = timer()
|
||||
|
||||
for i in range(10**5):
|
||||
entities_filter(entity_ids[i % size])
|
||||
|
||||
return timer() - start
|
||||
|
||||
|
||||
@benchmark
|
||||
async def valid_entity_id(hass):
|
||||
"""Run valid entity ID a million times."""
|
||||
start = timer()
|
||||
for _ in range(10**6):
|
||||
core.valid_entity_id("light.kitchen")
|
||||
return timer() - start
|
||||
|
||||
|
||||
@benchmark
|
||||
async def json_serialize_states(hass):
|
||||
"""Serialize million states with websocket default encoder."""
|
||||
states = [
|
||||
core.State("light.kitchen", "on", {"friendly_name": "Kitchen Lights"})
|
||||
for _ in range(10**6)
|
||||
]
|
||||
|
||||
start = timer()
|
||||
JSON_DUMP(states)
|
||||
return timer() - start
|
||||
303
home-assistant/homeassistant/scripts/check_config.py
Normal file
303
home-assistant/homeassistant/scripts/check_config.py
Normal file
@@ -0,0 +1,303 @@
|
||||
"""Script to check the configuration file."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Callable, Mapping, Sequence
|
||||
from glob import glob
|
||||
import logging
|
||||
import os
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from homeassistant import core, loader
|
||||
from homeassistant.config import get_default_config_dir
|
||||
from homeassistant.config_entries import ConfigEntries
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers import (
|
||||
area_registry as ar,
|
||||
device_registry as dr,
|
||||
entity_registry as er,
|
||||
issue_registry as ir,
|
||||
)
|
||||
from homeassistant.helpers.check_config import async_check_ha_config_file
|
||||
from homeassistant.util.yaml import Secrets
|
||||
import homeassistant.util.yaml.loader as yaml_loader
|
||||
|
||||
# mypy: allow-untyped-calls, allow-untyped-defs
|
||||
|
||||
REQUIREMENTS = ("colorlog==6.8.2",)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
MOCKS: dict[str, tuple[str, Callable]] = {
|
||||
"load": ("homeassistant.util.yaml.loader.load_yaml", yaml_loader.load_yaml),
|
||||
"load*": ("homeassistant.config.load_yaml_dict", yaml_loader.load_yaml_dict),
|
||||
"secrets": ("homeassistant.util.yaml.loader.secret_yaml", yaml_loader.secret_yaml),
|
||||
}
|
||||
|
||||
PATCHES: dict[str, Any] = {}
|
||||
|
||||
C_HEAD = "bold"
|
||||
ERROR_STR = "General Errors"
|
||||
WARNING_STR = "General Warnings"
|
||||
|
||||
|
||||
def color(the_color, *args, reset=None):
|
||||
"""Color helper."""
|
||||
# pylint: disable-next=import-outside-toplevel
|
||||
from colorlog.escape_codes import escape_codes, parse_colors
|
||||
|
||||
try:
|
||||
if not args:
|
||||
assert reset is None, "You cannot reset if nothing being printed"
|
||||
return parse_colors(the_color)
|
||||
return parse_colors(the_color) + " ".join(args) + escape_codes[reset or "reset"]
|
||||
except KeyError as k:
|
||||
raise ValueError(f"Invalid color {k!s} in {the_color}") from k
|
||||
|
||||
|
||||
def run(script_args: list) -> int:
|
||||
"""Handle check config commandline script."""
|
||||
parser = argparse.ArgumentParser(description="Check Home Assistant configuration.")
|
||||
parser.add_argument("--script", choices=["check_config"])
|
||||
parser.add_argument(
|
||||
"-c",
|
||||
"--config",
|
||||
default=get_default_config_dir(),
|
||||
help="Directory that contains the Home Assistant configuration",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-i",
|
||||
"--info",
|
||||
nargs="?",
|
||||
default=None,
|
||||
const="all",
|
||||
help="Show a portion of the config",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-f", "--files", action="store_true", help="Show used configuration files"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s", "--secrets", action="store_true", help="Show secret information"
|
||||
)
|
||||
|
||||
args, unknown = parser.parse_known_args()
|
||||
if unknown:
|
||||
print(color("red", "Unknown arguments:", ", ".join(unknown)))
|
||||
|
||||
config_dir = os.path.join(os.getcwd(), args.config)
|
||||
|
||||
print(color("bold", "Testing configuration at", config_dir))
|
||||
|
||||
res = check(config_dir, args.secrets)
|
||||
|
||||
domain_info: list[str] = []
|
||||
if args.info:
|
||||
domain_info = args.info.split(",")
|
||||
|
||||
if args.files:
|
||||
print(color(C_HEAD, "yaml files"), "(used /", color("red", "not used") + ")")
|
||||
deps = os.path.join(config_dir, "deps")
|
||||
yaml_files = [
|
||||
f
|
||||
for f in glob(os.path.join(config_dir, "**/*.yaml"), recursive=True)
|
||||
if not f.startswith(deps)
|
||||
]
|
||||
|
||||
for yfn in sorted(yaml_files):
|
||||
the_color = "" if yfn in res["yaml_files"] else "red"
|
||||
print(color(the_color, "-", yfn))
|
||||
|
||||
if res["except"]:
|
||||
print(color("bold_white", "Failed config"))
|
||||
for domain, config in res["except"].items():
|
||||
domain_info.append(domain)
|
||||
print(" ", color("bold_red", domain + ":"), color("red", "", reset="red"))
|
||||
dump_dict(config, reset="red")
|
||||
print(color("reset"))
|
||||
|
||||
if res["warn"]:
|
||||
print(color("bold_white", "Incorrect config"))
|
||||
for domain, config in res["warn"].items():
|
||||
domain_info.append(domain)
|
||||
print(
|
||||
" ",
|
||||
color("bold_yellow", domain + ":"),
|
||||
color("yellow", "", reset="yellow"),
|
||||
)
|
||||
dump_dict(config, reset="yellow")
|
||||
print(color("reset"))
|
||||
|
||||
if domain_info:
|
||||
if "all" in domain_info:
|
||||
print(color("bold_white", "Successful config (all)"))
|
||||
for domain, config in res["components"].items():
|
||||
print(" ", color(C_HEAD, domain + ":"))
|
||||
dump_dict(config)
|
||||
else:
|
||||
print(color("bold_white", "Successful config (partial)"))
|
||||
for domain in domain_info:
|
||||
if domain == ERROR_STR:
|
||||
continue
|
||||
print(" ", color(C_HEAD, domain + ":"))
|
||||
dump_dict(res["components"].get(domain))
|
||||
|
||||
if args.secrets:
|
||||
flatsecret: dict[str, str] = {}
|
||||
|
||||
for sfn, sdict in res["secret_cache"].items():
|
||||
sss = []
|
||||
for skey in sdict:
|
||||
if skey in flatsecret:
|
||||
_LOGGER.error(
|
||||
"Duplicated secrets in files %s and %s", flatsecret[skey], sfn
|
||||
)
|
||||
flatsecret[skey] = sfn
|
||||
sss.append(color("green", skey) if skey in res["secrets"] else skey)
|
||||
print(color(C_HEAD, "Secrets from", sfn + ":"), ", ".join(sss))
|
||||
|
||||
print(color(C_HEAD, "Used Secrets:"))
|
||||
for skey, sval in res["secrets"].items():
|
||||
if sval is None:
|
||||
print(" -", skey + ":", color("red", "not found"))
|
||||
continue
|
||||
print(" -", skey + ":", sval)
|
||||
|
||||
return len(res["except"])
|
||||
|
||||
|
||||
def check(config_dir, secrets=False):
|
||||
"""Perform a check by mocking hass load functions."""
|
||||
logging.getLogger("homeassistant.loader").setLevel(logging.CRITICAL)
|
||||
res: dict[str, Any] = {
|
||||
"yaml_files": OrderedDict(), # yaml_files loaded
|
||||
"secrets": OrderedDict(), # secret cache and secrets loaded
|
||||
"except": OrderedDict(), # critical exceptions raised (with config)
|
||||
"warn": OrderedDict(), # non critical exceptions raised (with config)
|
||||
#'components' is a HomeAssistantConfig
|
||||
"secret_cache": {},
|
||||
}
|
||||
|
||||
# pylint: disable-next=possibly-unused-variable
|
||||
def mock_load(filename, secrets=None):
|
||||
"""Mock hass.util.load_yaml to save config file names."""
|
||||
res["yaml_files"][filename] = True
|
||||
return MOCKS["load"][1](filename, secrets)
|
||||
|
||||
# pylint: disable-next=possibly-unused-variable
|
||||
def mock_secrets(ldr, node):
|
||||
"""Mock _get_secrets."""
|
||||
try:
|
||||
val = MOCKS["secrets"][1](ldr, node)
|
||||
except HomeAssistantError:
|
||||
val = None
|
||||
res["secrets"][node.value] = val
|
||||
return val
|
||||
|
||||
# Patches with local mock functions
|
||||
for key, val in MOCKS.items():
|
||||
if not secrets and key == "secrets":
|
||||
continue
|
||||
# The * in the key is removed to find the mock_function (side_effect)
|
||||
# This allows us to use one side_effect to patch multiple locations
|
||||
mock_function = locals()[f"mock_{key.replace('*', '')}"]
|
||||
PATCHES[key] = patch(val[0], side_effect=mock_function)
|
||||
|
||||
# Start all patches
|
||||
for pat in PATCHES.values():
|
||||
pat.start()
|
||||
|
||||
if secrets:
|
||||
# Ensure !secrets point to the patched function
|
||||
yaml_loader.add_constructor("!secret", yaml_loader.secret_yaml)
|
||||
|
||||
def secrets_proxy(*args):
|
||||
secrets = Secrets(*args)
|
||||
res["secret_cache"] = secrets._cache # noqa: SLF001
|
||||
return secrets
|
||||
|
||||
try:
|
||||
with patch.object(yaml_loader, "Secrets", secrets_proxy):
|
||||
res["components"] = asyncio.run(async_check_config(config_dir))
|
||||
res["secret_cache"] = {
|
||||
str(key): val for key, val in res["secret_cache"].items()
|
||||
}
|
||||
for err in res["components"].errors:
|
||||
domain = err.domain or ERROR_STR
|
||||
res["except"].setdefault(domain, []).append(err.message)
|
||||
if err.config:
|
||||
res["except"].setdefault(domain, []).append(err.config)
|
||||
|
||||
for err in res["components"].warnings:
|
||||
domain = err.domain or WARNING_STR
|
||||
res["warn"].setdefault(domain, []).append(err.message)
|
||||
if err.config:
|
||||
res["warn"].setdefault(domain, []).append(err.config)
|
||||
|
||||
except Exception as err: # noqa: BLE001
|
||||
print(color("red", "Fatal error while loading config:"), str(err))
|
||||
res["except"].setdefault(ERROR_STR, []).append(str(err))
|
||||
finally:
|
||||
# Stop all patches
|
||||
for pat in PATCHES.values():
|
||||
pat.stop()
|
||||
if secrets:
|
||||
# Ensure !secrets point to the original function
|
||||
yaml_loader.add_constructor("!secret", yaml_loader.secret_yaml)
|
||||
|
||||
return res
|
||||
|
||||
|
||||
async def async_check_config(config_dir):
|
||||
"""Check the HA config."""
|
||||
hass = core.HomeAssistant(config_dir)
|
||||
loader.async_setup(hass)
|
||||
hass.config_entries = ConfigEntries(hass, {})
|
||||
await ar.async_load(hass)
|
||||
await dr.async_load(hass)
|
||||
await er.async_load(hass)
|
||||
await ir.async_load(hass, read_only=True)
|
||||
components = await async_check_ha_config_file(hass)
|
||||
await hass.async_stop(force=True)
|
||||
return components
|
||||
|
||||
|
||||
def line_info(obj, **kwargs):
|
||||
"""Display line config source."""
|
||||
if hasattr(obj, "__config_file__"):
|
||||
return color(
|
||||
"cyan", f"[source {obj.__config_file__}:{obj.__line__ or '?'}]", **kwargs
|
||||
)
|
||||
return "?"
|
||||
|
||||
|
||||
def dump_dict(layer, indent_count=3, listi=False, **kwargs):
|
||||
"""Display a dict.
|
||||
|
||||
A friendly version of print yaml_loader.yaml.dump(config).
|
||||
"""
|
||||
|
||||
def sort_dict_key(val):
|
||||
"""Return the dict key for sorting."""
|
||||
key = str(val[0]).lower()
|
||||
return "0" if key == "platform" else key
|
||||
|
||||
indent_str = indent_count * " "
|
||||
if listi or isinstance(layer, list):
|
||||
indent_str = indent_str[:-1] + "-"
|
||||
if isinstance(layer, Mapping):
|
||||
for key, value in sorted(layer.items(), key=sort_dict_key):
|
||||
if isinstance(value, (dict, list)):
|
||||
print(indent_str, str(key) + ":", line_info(value, **kwargs))
|
||||
dump_dict(value, indent_count + 2, **kwargs)
|
||||
else:
|
||||
print(indent_str, str(key) + ":", value, line_info(key, **kwargs))
|
||||
indent_str = indent_count * " "
|
||||
if isinstance(layer, Sequence):
|
||||
for i in layer:
|
||||
if isinstance(i, dict):
|
||||
dump_dict(i, indent_count + 2, True, **kwargs)
|
||||
else:
|
||||
print(" ", indent_str, i)
|
||||
46
home-assistant/homeassistant/scripts/ensure_config.py
Normal file
46
home-assistant/homeassistant/scripts/ensure_config.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""Script to ensure a configuration file exists."""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import homeassistant.config as config_util
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
# mypy: allow-untyped-calls, allow-untyped-defs
|
||||
|
||||
|
||||
def run(args):
|
||||
"""Handle ensure config commandline script."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Ensure a Home Assistant config exists, creates one if necessary."
|
||||
)
|
||||
parser.add_argument(
|
||||
"-c",
|
||||
"--config",
|
||||
metavar="path_to_config_dir",
|
||||
default=config_util.get_default_config_dir(),
|
||||
help="Directory that contains the Home Assistant configuration",
|
||||
)
|
||||
parser.add_argument("--script", choices=["ensure_config"])
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
config_dir = os.path.join(os.getcwd(), args.config)
|
||||
|
||||
# Test if configuration directory exists
|
||||
if not os.path.isdir(config_dir):
|
||||
print("Creating directory", config_dir)
|
||||
os.makedirs(config_dir, exist_ok=True)
|
||||
|
||||
config_path = asyncio.run(async_run(config_dir))
|
||||
print("Configuration file:", config_path)
|
||||
return 0
|
||||
|
||||
|
||||
async def async_run(config_dir):
|
||||
"""Make sure config exists."""
|
||||
hass = HomeAssistant(config_dir)
|
||||
path = await config_util.async_ensure_config_exists(hass)
|
||||
await hass.async_stop(force=True)
|
||||
return path
|
||||
67
home-assistant/homeassistant/scripts/macos/__init__.py
Normal file
67
home-assistant/homeassistant/scripts/macos/__init__.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""Script to install/uninstall HA into OS X."""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
# mypy: allow-untyped-calls, allow-untyped-defs
|
||||
|
||||
|
||||
def install_osx():
|
||||
"""Set up to run via launchd on OS X."""
|
||||
with os.popen("which hass") as inp:
|
||||
hass_path = inp.read().strip()
|
||||
|
||||
with os.popen("whoami") as inp:
|
||||
user = inp.read().strip()
|
||||
|
||||
template_path = os.path.join(os.path.dirname(__file__), "launchd.plist")
|
||||
|
||||
with open(template_path, encoding="utf-8") as tinp:
|
||||
plist = tinp.read()
|
||||
|
||||
plist = plist.replace("$HASS_PATH$", hass_path)
|
||||
plist = plist.replace("$USER$", user)
|
||||
|
||||
path = os.path.expanduser("~/Library/LaunchAgents/org.homeassistant.plist")
|
||||
|
||||
try:
|
||||
with open(path, "w", encoding="utf-8") as outp:
|
||||
outp.write(plist)
|
||||
except OSError as err:
|
||||
print(f"Unable to write to {path}", err)
|
||||
return
|
||||
|
||||
os.popen(f"launchctl load -w -F {path}")
|
||||
|
||||
print("Home Assistant has been installed. Open it here: http://localhost:8123")
|
||||
|
||||
|
||||
def uninstall_osx():
|
||||
"""Unload from launchd on OS X."""
|
||||
path = os.path.expanduser("~/Library/LaunchAgents/org.homeassistant.plist")
|
||||
os.popen(f"launchctl unload {path}")
|
||||
|
||||
print("Home Assistant has been uninstalled.")
|
||||
|
||||
|
||||
def run(args: list[str]) -> int:
|
||||
"""Handle OSX commandline script."""
|
||||
commands = "install", "uninstall", "restart"
|
||||
if not args or args[0] not in commands:
|
||||
print("Invalid command. Available commands:", ", ".join(commands))
|
||||
return 1
|
||||
|
||||
if args[0] == "install":
|
||||
install_osx()
|
||||
return 0
|
||||
if args[0] == "uninstall":
|
||||
uninstall_osx()
|
||||
return 0
|
||||
if args[0] == "restart":
|
||||
uninstall_osx()
|
||||
# A small delay is needed on some systems to let the unload finish.
|
||||
time.sleep(0.5)
|
||||
install_osx()
|
||||
return 0
|
||||
|
||||
raise ValueError(f"Invalid command {args[0]}")
|
||||
38
home-assistant/homeassistant/scripts/macos/launchd.plist
Normal file
38
home-assistant/homeassistant/scripts/macos/launchd.plist
Normal file
@@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>org.homeassistant</string>
|
||||
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>PATH</key>
|
||||
<string>/usr/local/bin/:/usr/bin:/usr/sbin:/sbin:$PATH</string>
|
||||
<key>LC_CTYPE</key>
|
||||
<string>UTF-8</string>
|
||||
</dict>
|
||||
|
||||
<key>Program</key>
|
||||
<string>$HASS_PATH$</string>
|
||||
|
||||
<key>AbandonProcessGroup</key>
|
||||
<false/>
|
||||
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
|
||||
<key>KeepAlive</key>
|
||||
<dict>
|
||||
<key>SuccessfulExit</key>
|
||||
<false/>
|
||||
</dict>
|
||||
|
||||
<key>StandardErrorPath</key>
|
||||
<string>/Users/$USER$/Library/Logs/homeassistant.log</string>
|
||||
|
||||
<key>StandardOutPath</key>
|
||||
<string>/Users/$USER$/Library/Logs/homeassistant.log</string>
|
||||
|
||||
</dict>
|
||||
</plist>
|
||||
Reference in New Issue
Block a user