Compare commits

..

No commits in common. "main" and "2025.05.4" have entirely different histories.

182 changed files with 1489 additions and 4386 deletions

69
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,69 @@
---
name: Report a bug with the Supervisor on a supported System
about: Report an issue related to the Home Assistant Supervisor.
labels: bug
---
<!-- READ THIS FIRST:
- If you need additional help with this template please refer to https://www.home-assistant.io/help/reporting_issues/
- This is for bugs only. Feature and enhancement requests should go in our community forum: https://community.home-assistant.io/c/feature-requests
- Provide as many details as possible. Paste logs, configuration sample and code into the backticks. Do not delete any text from this template!
- If you have a problem with an add-on, make an issue in it's repository.
-->
<!--
Important: You can only fill a bug repport for an supported system! If you run an unsupported installation. This report would be closed without comment.
-->
### Describe the issue
<!-- Provide as many details as possible. -->
### Steps to reproduce
<!-- What do you do to encounter the issue. -->
1. ...
2. ...
3. ...
### Enviroment details
<!-- You can find these details in the system tab of the supervisor panel, or by using the `ha` CLI. -->
- **Operating System:**: xxx
- **Supervisor version:**: xxx
- **Home Assistant version**: xxx
### Supervisor logs
<details>
<summary>Supervisor logs</summary>
<!--
- Frontend -> Supervisor -> System
- Or use this command: ha supervisor logs
- Logs are more than just errors, even if you don't think it's important, it is.
-->
```
Paste supervisor logs here
```
</details>
### System Information
<details>
<summary>System Information</summary>
<!--
- Use this command: ha info
-->
```
Paste system info here
```
</details>

View File

@ -1,5 +1,6 @@
name: Report an issue with Home Assistant Supervisor
name: Bug Report Form
description: Report an issue related to the Home Assistant Supervisor.
labels: bug
body:
- type: markdown
attributes:
@ -8,7 +9,7 @@ body:
If you have a feature or enhancement request, please use the [feature request][fr] section of our [Community Forum][fr].
[fr]: https://github.com/orgs/home-assistant/discussions
[fr]: https://community.home-assistant.io/c/feature-requests
- type: textarea
validations:
required: true
@ -75,7 +76,7 @@ body:
description: >
The System information can be found in [Settings -> System -> Repairs -> (three dot menu) -> System Information](https://my.home-assistant.io/redirect/system_health/).
Click the copy button at the bottom of the pop-up and paste it here.
[![Open your Home Assistant instance and show health information about your system.](https://my.home-assistant.io/badges/system_health.svg)](https://my.home-assistant.io/redirect/system_health/)
- type: textarea
attributes:
@ -85,7 +86,7 @@ body:
Supervisor diagnostics can be found in [Settings -> Devices & services](https://my.home-assistant.io/redirect/integrations/).
Find the card that says `Home Assistant Supervisor`, open it, and select the three dot menu of the Supervisor integration entry
and select 'Download diagnostics'.
**Please drag-and-drop the downloaded file into the textbox below. Do not copy and paste its contents.**
- type: textarea
attributes:

View File

@ -13,7 +13,7 @@ contact_links:
about: Our documentation has its own issue tracker. Please report issues with the website there.
- name: Request a feature for the Supervisor
url: https://github.com/orgs/home-assistant/discussions
url: https://community.home-assistant.io/c/feature-requests
about: Request an new feature for the Supervisor.
- name: I have a question or need support

View File

@ -1,53 +0,0 @@
name: Task
description: For staff only - Create a task
type: Task
body:
- type: markdown
attributes:
value: |
## ⚠️ RESTRICTED ACCESS
**This form is restricted to Open Home Foundation staff and authorized contributors only.**
If you are a community member wanting to contribute, please:
- For bug reports: Use the [bug report form](https://github.com/home-assistant/supervisor/issues/new?template=bug_report.yml)
- For feature requests: Submit to [Feature Requests](https://github.com/orgs/home-assistant/discussions)
---
### For authorized contributors
Use this form to create tasks for development work, improvements, or other actionable items that need to be tracked.
- type: textarea
id: description
attributes:
label: Description
description: |
Provide a clear and detailed description of the task that needs to be accomplished.
Be specific about what needs to be done, why it's important, and any constraints or requirements.
placeholder: |
Describe the task, including:
- What needs to be done
- Why this task is needed
- Expected outcome
- Any constraints or requirements
validations:
required: true
- type: textarea
id: additional_context
attributes:
label: Additional context
description: |
Any additional information, links, research, or context that would be helpful.
Include links to related issues, research, prototypes, roadmap opportunities etc.
placeholder: |
- Roadmap opportunity: [link]
- Epic: [link]
- Feature request: [link]
- Technical design documents: [link]
- Prototype/mockup: [link]
- Dependencies: [links]
validations:
required: false

View File

@ -1,288 +0,0 @@
# GitHub Copilot & Claude Code Instructions
This repository contains the Home Assistant Supervisor, a Python 3 based container
orchestration and management system for Home Assistant.
## Supervisor Capabilities & Features
### Architecture Overview
Home Assistant Supervisor is a Python-based container orchestration system that
communicates with the Docker daemon to manage containerized components. It is tightly
integrated with the underlying Operating System and core Operating System components
through D-Bus.
**Managed Components:**
- **Home Assistant Core**: The main home automation application running in its own
container (also provides the web interface)
- **Add-ons**: Third-party applications and services (each add-on runs in its own
container)
- **Plugins**: Built-in system services like DNS, Audio, CLI, Multicast, and Observer
- **Host System Integration**: OS-level operations and hardware access via D-Bus
- **Container Networking**: Internal Docker network management and external
connectivity
- **Storage & Backup**: Data persistence and backup management across all containers
**Key Dependencies:**
- **Docker Engine**: Required for all container operations
- **D-Bus**: System-level communication with the host OS
- **systemd**: Service management for host system operations
- **NetworkManager**: Network configuration and management
### Add-on System
**Add-on Architecture**: Add-ons are containerized applications available through
add-on stores. Each store contains multiple add-ons, and each add-on includes metadata
that tells Supervisor the version, startup configuration (permissions), and available
user configurable options. Add-on metadata typically references a container image that
Supervisor fetches during installation. If not, the Supervisor builds the container
image from a Dockerfile.
**Built-in Stores**: Supervisor comes with several pre-configured stores:
- **Core Add-ons**: Official add-ons maintained by the Home Assistant team
- **Community Add-ons**: Popular third-party add-ons repository
- **ESPHome**: Add-ons for ESPHome ecosystem integration
- **Music Assistant**: Audio and music-related add-ons
- **Local Development**: Local folder for testing custom add-ons during development
**Store Management**: Stores are Git-based repositories that are periodically updated.
When updates are available, users receive notifications.
**Add-on Lifecycle**:
- **Installation**: Supervisor fetches or builds container images based on add-on
metadata
- **Configuration**: Schema-validated options with integrated UI management
- **Runtime**: Full container lifecycle management, health monitoring
- **Updates**: Automatic or manual version management
### Update System
**Core Components**: Supervisor, Home Assistant Core, HAOS, and built-in plugins
receive version information from a central JSON file fetched from
`https://version.home-assistant.io/{channel}.json`. The `Updater` class handles
fetching this data, validating signatures, and updating internal version tracking.
**Update Channels**: Three channels (`stable`/`beta`/`dev`) determine which version
JSON file is fetched, allowing users to opt into different release streams.
**Add-on Updates**: Add-on version information comes from store repository updates, not
the central JSON file. When repositories are refreshed via the store system, add-ons
compare their local versions against repository versions to determine update
availability.
### Backup & Recovery System
**Backup Capabilities**:
- **Full Backups**: Complete system state capture including all add-ons,
configuration, and data
- **Partial Backups**: Selective backup of specific components (Home Assistant,
add-ons, folders)
- **Encrypted Backups**: Optional backup encryption with user-provided passwords
- **Multiple Storage Locations**: Local storage and remote backup destinations
**Recovery Features**:
- **One-click Restore**: Simple restoration from backup files
- **Selective Restore**: Choose specific components to restore
- **Automatic Recovery**: Self-healing for common system issues
---
## Supervisor Development
### Python Requirements
- **Compatibility**: Python 3.13+
- **Language Features**: Use modern Python features:
- Type hints with `typing` module
- f-strings (preferred over `%` or `.format()`)
- Dataclasses and enum classes
- Async/await patterns
- Pattern matching where appropriate
### Code Quality Standards
- **Formatting**: Ruff
- **Linting**: PyLint and Ruff
- **Type Checking**: MyPy
- **Testing**: pytest with asyncio support
- **Language**: American English for all code, comments, and documentation
### Code Organization
**Core Structure**:
```
supervisor/
├── __init__.py # Package initialization
├── const.py # Constants and enums
├── coresys.py # Core system management
├── bootstrap.py # System initialization
├── exceptions.py # Custom exception classes
├── api/ # REST API endpoints
├── addons/ # Add-on management
├── backups/ # Backup system
├── docker/ # Docker integration
├── host/ # Host system interface
├── homeassistant/ # Home Assistant Core management
├── dbus/ # D-Bus system integration
├── hardware/ # Hardware detection and management
├── plugins/ # Plugin system
├── resolution/ # Issue detection and resolution
├── security/ # Security management
├── services/ # Service discovery and management
├── store/ # Add-on store management
└── utils/ # Utility functions
```
**Shared Constants**: Use constants from `supervisor/const.py` instead of hardcoding
values. Define new constants following existing patterns and group related constants
together.
### Supervisor Architecture Patterns
**CoreSysAttributes Inheritance Pattern**: Nearly all major classes in Supervisor
inherit from `CoreSysAttributes`, providing access to the centralized system state
via `self.coresys` and convenient `sys_*` properties.
```python
# Standard Supervisor class pattern
class MyManager(CoreSysAttributes):
"""Manage my functionality."""
def __init__(self, coresys: CoreSys):
"""Initialize manager."""
self.coresys: CoreSys = coresys
self._component: MyComponent = MyComponent(coresys)
@property
def component(self) -> MyComponent:
"""Return component handler."""
return self._component
# Access system components via inherited properties
async def do_something(self):
await self.sys_docker.containers.get("my_container")
self.sys_bus.fire_event(BusEvent.MY_EVENT, {"data": "value"})
```
**Key Inherited Properties from CoreSysAttributes**:
- `self.sys_docker` - Docker API access
- `self.sys_run_in_executor()` - Execute blocking operations
- `self.sys_create_task()` - Create async tasks
- `self.sys_bus` - Event bus for system events
- `self.sys_config` - System configuration
- `self.sys_homeassistant` - Home Assistant Core management
- `self.sys_addons` - Add-on management
- `self.sys_host` - Host system access
- `self.sys_dbus` - D-Bus system interface
**Load Pattern**: Many components implement a `load()` method which effectively
initialize the component from external sources (containers, files, D-Bus services).
### API Development
**REST API Structure**:
- **Base Path**: `/api/` for all endpoints
- **Authentication**: Bearer token authentication
- **Consistent Response Format**: `{"result": "ok", "data": {...}}` or
`{"result": "error", "message": "..."}`
- **Validation**: Use voluptuous schemas with `api_validate()`
**Use `@api_process` Decorator**: This decorator handles all standard error handling
and response formatting automatically. The decorator catches `APIError`, `HassioError`,
and other exceptions, returning appropriate HTTP responses.
```python
from ..api.utils import api_process, api_validate
@api_process
async def backup_full(self, request: web.Request) -> dict[str, Any]:
"""Create full backup."""
body = await api_validate(SCHEMA_BACKUP_FULL, request)
job = await self.sys_backups.do_backup_full(**body)
return {ATTR_JOB_ID: job.uuid}
```
### Docker Integration
- **Container Management**: Use Supervisor's Docker manager instead of direct
Docker API
- **Networking**: Supervisor manages internal Docker networks with predefined IP
ranges
- **Security**: AppArmor profiles, capability restrictions, and user namespace
isolation
- **Health Checks**: Implement health monitoring for all managed containers
### D-Bus Integration
- **Use dbus-fast**: Async D-Bus library for system integration
- **Service Management**: systemd, NetworkManager, hostname management
- **Error Handling**: Wrap D-Bus exceptions in Supervisor-specific exceptions
### Async Programming
- **All I/O operations must be async**: File operations, network calls, subprocess
execution
- **Use asyncio patterns**: Prefer `asyncio.gather()` over sequential awaits
- **Executor jobs**: Use `self.sys_run_in_executor()` for blocking operations
- **Two-phase initialization**: `__init__` for sync setup, `post_init()` for async
initialization
### Testing
- **Location**: `tests/` directory with module mirroring
- **Fixtures**: Extensive use of pytest fixtures for CoreSys setup
- **Mocking**: Mock external dependencies (Docker, D-Bus, network calls)
- **Coverage**: Minimum 90% test coverage, 100% for security-sensitive code
### Error Handling
- **Custom Exceptions**: Defined in `exceptions.py` with clear inheritance hierarchy
- **Error Propagation**: Use `from` clause for exception chaining
- **API Errors**: Use `APIError` with appropriate HTTP status codes
### Security Considerations
- **Container Security**: AppArmor profiles mandatory for add-ons, minimal
capabilities
- **Authentication**: Token-based API authentication with role-based access
- **Data Protection**: Backup encryption, secure secret management, comprehensive
input validation
### Development Commands
```bash
# Run tests, adjust paths as necessary
pytest -qsx tests/
# Linting and formatting
ruff check supervisor/
ruff format supervisor/
# Type checking
mypy --ignore-missing-imports supervisor/
# Pre-commit hooks
pre-commit run --all-files
```
Always run the pre-commit hooks at the end of code editing.
### Common Patterns to Follow
**✅ Use These Patterns**:
- Inherit from `CoreSysAttributes` for system access
- Use `@api_process` decorator for API endpoints
- Use `self.sys_run_in_executor()` for blocking operations
- Access Docker via `self.sys_docker` not direct Docker API
- Use constants from `const.py` instead of hardcoding
- Store types in (per-module) `const.py` (e.g. supervisor/store/const.py)
**❌ Avoid These Patterns**:
- Direct Docker API usage - use Supervisor's Docker manager
- Blocking operations in async context (use asyncio alternatives)
- Hardcoded values - use constants from `const.py`
- Manual error handling in API endpoints - let `@api_process` handle it
This guide provides the foundation for contributing to Home Assistant Supervisor.
Follow these patterns and guidelines to ensure code quality, security, and
maintainability.

View File

@ -131,9 +131,9 @@ jobs:
- name: Install Cosign
if: needs.init.outputs.publish == 'true'
uses: sigstore/cosign-installer@v3.9.2
uses: sigstore/cosign-installer@v3.8.2
with:
cosign-release: "v2.4.3"
cosign-release: "v2.4.0"
- name: Install dirhash and calc hash
if: needs.init.outputs.publish == 'true'

View File

@ -10,7 +10,6 @@ on:
env:
DEFAULT_PYTHON: "3.13"
PRE_COMMIT_CACHE: ~/.cache/pre-commit
MYPY_CACHE_VERSION: 1
concurrency:
group: "${{ github.workflow }}-${{ github.ref }}"
@ -287,52 +286,6 @@ jobs:
. venv/bin/activate
pylint supervisor tests
mypy:
name: Check mypy
runs-on: ubuntu-latest
needs: prepare
steps:
- name: Check out code from GitHub
uses: actions/checkout@v4.2.2
- name: Set up Python ${{ needs.prepare.outputs.python-version }}
uses: actions/setup-python@v5.6.0
id: python
with:
python-version: ${{ needs.prepare.outputs.python-version }}
- name: Generate partial mypy restore key
id: generate-mypy-key
run: |
mypy_version=$(cat requirements_test.txt | grep mypy | cut -d '=' -f 3)
echo "version=$mypy_version" >> $GITHUB_OUTPUT
echo "key=mypy-${{ env.MYPY_CACHE_VERSION }}-$mypy_version-$(date -u '+%Y-%m-%dT%H:%M:%s')" >> $GITHUB_OUTPUT
- name: Restore Python virtual environment
id: cache-venv
uses: actions/cache@v4.2.3
with:
path: venv
key: >-
${{ runner.os }}-venv-${{ needs.prepare.outputs.python-version }}-${{ hashFiles('requirements.txt') }}-${{ hashFiles('requirements_tests.txt') }}
- name: Fail job if Python cache restore failed
if: steps.cache-venv.outputs.cache-hit != 'true'
run: |
echo "Failed to restore Python virtual environment from cache"
exit 1
- name: Restore mypy cache
uses: actions/cache@v4.2.3
with:
path: .mypy_cache
key: >-
${{ runner.os }}-mypy-${{ needs.prepare.outputs.python-version }}-${{ steps.generate-mypy-key.outputs.key }}
restore-keys: >-
${{ runner.os }}-venv-${{ needs.prepare.outputs.python-version }}-mypy-${{ env.MYPY_CACHE_VERSION }}-${{ steps.generate-mypy-key.outputs.version }}
- name: Register mypy problem matcher
run: |
echo "::add-matcher::.github/workflows/matchers/mypy.json"
- name: Run mypy
run: |
. venv/bin/activate
mypy --ignore-missing-imports supervisor
pytest:
runs-on: ubuntu-latest
needs: prepare
@ -346,9 +299,9 @@ jobs:
with:
python-version: ${{ needs.prepare.outputs.python-version }}
- name: Install Cosign
uses: sigstore/cosign-installer@v3.9.2
uses: sigstore/cosign-installer@v3.8.2
with:
cosign-release: "v2.4.3"
cosign-release: "v2.4.0"
- name: Restore Python virtual environment
id: cache-venv
uses: actions/cache@v4.2.3

View File

@ -1,16 +0,0 @@
{
"problemMatcher": [
{
"owner": "mypy",
"pattern": [
{
"regexp": "^(.+):(\\d+):\\s(error|warning):\\s(.+)$",
"file": 1,
"line": 2,
"severity": 3,
"message": 4
}
]
}
]
}

View File

@ -1,58 +0,0 @@
name: Restrict task creation
# yamllint disable-line rule:truthy
on:
issues:
types: [opened]
jobs:
check-authorization:
runs-on: ubuntu-latest
# Only run if this is a Task issue type (from the issue form)
if: github.event.issue.issue_type == 'Task'
steps:
- name: Check if user is authorized
uses: actions/github-script@v7
with:
script: |
const issueAuthor = context.payload.issue.user.login;
// Check if user is an organization member
try {
await github.rest.orgs.checkMembershipForUser({
org: 'home-assistant',
username: issueAuthor
});
console.log(`✅ ${issueAuthor} is an organization member`);
return; // Authorized
} catch (error) {
console.log(`❌ ${issueAuthor} is not authorized to create Task issues`);
}
// Close the issue with a comment
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `Hi @${issueAuthor}, thank you for your contribution!\n\n` +
`Task issues are restricted to Open Home Foundation staff and authorized contributors.\n\n` +
`If you would like to:\n` +
`- Report a bug: Please use the [bug report form](https://github.com/home-assistant/supervisor/issues/new?template=bug_report.yml)\n` +
`- Request a feature: Please submit to [Feature Requests](https://github.com/orgs/home-assistant/discussions)\n\n` +
`If you believe you should have access to create Task issues, please contact the maintainers.`
});
await github.rest.issues.update({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
state: 'closed'
});
// Add a label to indicate this was auto-closed
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
labels: ['auto-closed']
});

View File

@ -12,7 +12,7 @@ jobs:
- name: Check out code from GitHub
uses: actions/checkout@v4.2.2
- name: Sentry Release
uses: getsentry/action-release@v3.2.0
uses: getsentry/action-release@v3.1.1
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}

View File

@ -13,15 +13,3 @@ repos:
- id: check-executables-have-shebangs
stages: [manual]
- id: check-json
- repo: local
hooks:
# Run mypy through our wrapper script in order to get the possible
# pyenv and/or virtualenv activated; it may not have been e.g. if
# committing from a GUI tool that was not launched from an activated
# shell.
- id: mypy
name: mypy
entry: script/run-in-env.sh mypy --ignore-missing-imports
language: script
types_or: [python, pyi]
files: ^supervisor/.+\.(py|pyi)$

View File

@ -1 +0,0 @@
.github/copilot-instructions.md

View File

@ -12,7 +12,7 @@ cosign:
base_identity: https://github.com/home-assistant/docker-base/.*
identity: https://github.com/home-assistant/supervisor/.*
args:
COSIGN_VERSION: 2.4.3
COSIGN_VERSION: 2.4.0
labels:
io.hass.type: supervisor
org.opencontainers.image.title: Home Assistant Supervisor

View File

@ -1,30 +1,30 @@
aiodns==3.5.0
aiohttp==3.12.15
aiodns==3.4.0
aiohttp==3.12.2
atomicwrites-homeassistant==1.4.1
attrs==25.3.0
awesomeversion==25.5.0
blockbuster==1.5.25
awesomeversion==24.6.0
blockbuster==1.5.24
brotli==1.1.0
ciso8601==2.3.2
colorlog==6.9.0
cpe==1.3.1
cryptography==45.0.5
debugpy==1.8.15
cryptography==45.0.3
debugpy==1.8.14
deepmerge==2.0
dirhash==0.5.0
docker==7.1.0
faust-cchardet==2.1.19
gitpython==3.1.45
gitpython==3.1.44
jinja2==3.1.6
log-rate-limit==1.4.2
orjson==3.11.1
orjson==3.10.18
pulsectl==24.12.0
pyudev==0.24.3
PyYAML==6.0.2
requests==2.32.4
requests==2.32.3
securetar==2025.2.1
sentry-sdk==2.34.0
sentry-sdk==2.29.1
setuptools==80.9.0
voluptuous==0.15.2
dbus-fast==2.44.2
dbus-fast==2.44.1
zlib-fast==0.2.1

View File

@ -1,16 +1,12 @@
astroid==3.3.11
coverage==7.10.1
mypy==1.17.0
astroid==3.3.10
coverage==7.8.2
pre-commit==4.2.0
pylint==3.3.7
pytest-aiohttp==1.1.0
pytest-asyncio==0.25.2
pytest-cov==6.2.1
pytest-cov==6.1.1
pytest-timeout==2.4.0
pytest==8.4.1
ruff==0.12.7
pytest==8.3.5
ruff==0.11.11
time-machine==2.16.0
types-docker==7.1.0.20250705
types-pyyaml==6.0.12.20250516
types-requests==2.32.4.20250611
urllib3==2.5.0
urllib3==2.4.0

View File

@ -1,30 +0,0 @@
#!/usr/bin/env sh
set -eu
# Used in venv activate script.
# Would be an error if undefined.
OSTYPE="${OSTYPE-}"
# Activate pyenv and virtualenv if present, then run the specified command
# pyenv, pyenv-virtualenv
if [ -s .python-version ]; then
PYENV_VERSION=$(head -n 1 .python-version)
export PYENV_VERSION
fi
if [ -n "${VIRTUAL_ENV-}" ] && [ -f "${VIRTUAL_ENV}/bin/activate" ]; then
. "${VIRTUAL_ENV}/bin/activate"
else
# other common virtualenvs
my_path=$(git rev-parse --show-toplevel)
for venv in venv .venv .; do
if [ -f "${my_path}/${venv}/bin/activate" ]; then
. "${my_path}/${venv}/bin/activate"
break
fi
done
fi
exec "$@"

View File

@ -66,15 +66,8 @@ if __name__ == "__main__":
_LOGGER.info("Setting up Supervisor")
loop.run_until_complete(coresys.core.setup())
bootstrap.register_signal_handlers(loop, coresys)
try:
loop.run_until_complete(coresys.core.start())
except Exception as err: # pylint: disable=broad-except
# Supervisor itself is running at this point, just something didn't
# start as expected. Log with traceback to get more insights for
# such cases.
_LOGGER.critical("Supervisor start failed: %s", err, exc_info=True)
loop.call_soon_threadsafe(loop.create_task, coresys.core.start())
loop.call_soon_threadsafe(bootstrap.reg_signal, loop, coresys)
try:
_LOGGER.info("Running Supervisor")

View File

@ -360,7 +360,7 @@ class Addon(AddonModel):
@property
def auto_update(self) -> bool:
"""Return if auto update is enable."""
return self.persist.get(ATTR_AUTO_UPDATE, False)
return self.persist.get(ATTR_AUTO_UPDATE, super().auto_update)
@auto_update.setter
def auto_update(self, value: bool) -> None:
@ -1335,6 +1335,13 @@ class Addon(AddonModel):
wait_for_start: asyncio.Task | None = None
# Refuse to backup if add-on is unknown (e.g. has been uninstalled by the user
# since the backup got started).
if self.state == AddonState.UNKNOWN:
raise AddonsError(
f"Add-on {self.slug} is not installed, cannot backup!", _LOGGER.error
)
data = {
ATTR_USER: self.persist,
ATTR_SYSTEM: self.data,

View File

@ -15,7 +15,6 @@ from ..const import (
ATTR_SQUASH,
FILE_SUFFIX_CONFIGURATION,
META_ADDON,
SOCKET_DOCKER,
)
from ..coresys import CoreSys, CoreSysAttributes
from ..docker.interface import MAP_ARCH
@ -122,64 +121,39 @@ class AddonBuild(FileConfiguration, CoreSysAttributes):
except HassioArchNotFound:
return False
def get_docker_args(
self, version: AwesomeVersion, image_tag: str
) -> dict[str, Any]:
"""Create a dict with Docker run args."""
dockerfile_path = self.get_dockerfile().relative_to(self.addon.path_location)
def get_docker_args(self, version: AwesomeVersion, image: str | None = None):
"""Create a dict with Docker build arguments.
build_cmd = [
"docker",
"buildx",
"build",
".",
"--tag",
image_tag,
"--file",
str(dockerfile_path),
"--platform",
MAP_ARCH[self.arch],
"--pull",
]
labels = {
"io.hass.version": version,
"io.hass.arch": self.arch,
"io.hass.type": META_ADDON,
"io.hass.name": self._fix_label("name"),
"io.hass.description": self._fix_label("description"),
**self.additional_labels,
Must be run in executor.
"""
args: dict[str, Any] = {
"path": str(self.addon.path_location),
"tag": f"{image or self.addon.image}:{version!s}",
"dockerfile": str(self.get_dockerfile()),
"pull": True,
"forcerm": not self.sys_dev,
"squash": self.squash,
"platform": MAP_ARCH[self.arch],
"labels": {
"io.hass.version": version,
"io.hass.arch": self.arch,
"io.hass.type": META_ADDON,
"io.hass.name": self._fix_label("name"),
"io.hass.description": self._fix_label("description"),
**self.additional_labels,
},
"buildargs": {
"BUILD_FROM": self.base_image,
"BUILD_VERSION": version,
"BUILD_ARCH": self.sys_arch.default,
**self.additional_args,
},
}
if self.addon.url:
labels["io.hass.url"] = self.addon.url
args["labels"]["io.hass.url"] = self.addon.url
for key, value in labels.items():
build_cmd.extend(["--label", f"{key}={value}"])
build_args = {
"BUILD_FROM": self.base_image,
"BUILD_VERSION": version,
"BUILD_ARCH": self.sys_arch.default,
**self.additional_args,
}
for key, value in build_args.items():
build_cmd.extend(["--build-arg", f"{key}={value}"])
# The addon path will be mounted from the host system
addon_extern_path = self.sys_config.local_to_extern_path(
self.addon.path_location
)
return {
"command": build_cmd,
"volumes": {
SOCKET_DOCKER: {"bind": "/var/run/docker.sock", "mode": "rw"},
addon_extern_path: {"bind": "/addon", "mode": "ro"},
},
"working_dir": "/addon",
}
return args
def _fix_label(self, label_name: str) -> str:
"""Remove characters they are not supported."""

View File

@ -67,10 +67,6 @@ class AddonManager(CoreSysAttributes):
return self.store.get(addon_slug)
return None
def get_local_only(self, addon_slug: str) -> Addon | None:
"""Return an installed add-on from slug."""
return self.local.get(addon_slug)
def from_token(self, token: str) -> Addon | None:
"""Return an add-on from Supervisor token."""
for addon in self.installed:
@ -266,7 +262,7 @@ class AddonManager(CoreSysAttributes):
],
on_condition=AddonsJobError,
)
async def rebuild(self, slug: str, *, force: bool = False) -> asyncio.Task | None:
async def rebuild(self, slug: str) -> asyncio.Task | None:
"""Perform a rebuild of local build add-on.
Returns a Task that completes when addon has state 'started' (see addon.start)
@ -289,7 +285,7 @@ class AddonManager(CoreSysAttributes):
raise AddonsError(
"Version changed, use Update instead Rebuild", _LOGGER.error
)
if not force and not addon.need_build:
if not addon.need_build:
raise AddonsNotSupportedError(
"Can't rebuild a image based add-on", _LOGGER.error
)

View File

@ -664,16 +664,12 @@ class AddonModel(JobGroup, ABC):
"""Validate if addon is available for current system."""
return self._validate_availability(self.data, logger=_LOGGER.error)
def __eq__(self, other: Any) -> bool:
"""Compare add-on objects."""
def __eq__(self, other):
"""Compaired add-on objects."""
if not isinstance(other, AddonModel):
return False
return self.slug == other.slug
def __hash__(self) -> int:
"""Hash for add-on objects."""
return hash(self.slug)
def _validate_availability(
self, config, *, logger: Callable[..., None] | None = None
) -> None:

View File

@ -8,7 +8,7 @@ from typing import Any
from aiohttp import hdrs, web
from ..const import SUPERVISOR_DOCKER_NAME, AddonState
from ..const import AddonState
from ..coresys import CoreSys, CoreSysAttributes
from ..exceptions import APIAddonNotInstalled, HostNotSupportedError
from ..utils.sentry import async_capture_exception
@ -426,7 +426,7 @@ class RestAPI(CoreSysAttributes):
async def get_supervisor_logs(*args, **kwargs):
try:
return await self._api_host.advanced_logs_handler(
*args, identifier=SUPERVISOR_DOCKER_NAME, **kwargs
*args, identifier="hassio_supervisor", **kwargs
)
except Exception as err: # pylint: disable=broad-exception-caught
# Supervisor logs are critical, so catch everything, log the exception
@ -789,7 +789,6 @@ class RestAPI(CoreSysAttributes):
self.webapp.add_routes(
[
web.get("/docker/info", api_docker.info),
web.post("/docker/options", api_docker.options),
web.get("/docker/registries", api_docker.registries),
web.post("/docker/registries", api_docker.create_registry),
web.delete("/docker/registries/{hostname}", api_docker.remove_registry),

View File

@ -36,7 +36,6 @@ from ..const import (
ATTR_DNS,
ATTR_DOCKER_API,
ATTR_DOCUMENTATION,
ATTR_FORCE,
ATTR_FULL_ACCESS,
ATTR_GPIO,
ATTR_HASSIO_API,
@ -140,8 +139,6 @@ SCHEMA_SECURITY = vol.Schema({vol.Optional(ATTR_PROTECTED): vol.Boolean()})
SCHEMA_UNINSTALL = vol.Schema(
{vol.Optional(ATTR_REMOVE_CONFIG, default=False): vol.Boolean()}
)
SCHEMA_REBUILD = vol.Schema({vol.Optional(ATTR_FORCE, default=False): vol.Boolean()})
# pylint: enable=no-value-for-parameter
@ -464,11 +461,7 @@ class APIAddons(CoreSysAttributes):
async def rebuild(self, request: web.Request) -> None:
"""Rebuild local build add-on."""
addon = self.get_addon_for_request(request)
body: dict[str, Any] = await api_validate(SCHEMA_REBUILD, request)
if start_task := await asyncio.shield(
self.sys_addons.rebuild(addon.slug, force=body[ATTR_FORCE])
):
if start_task := await asyncio.shield(self.sys_addons.rebuild(addon.slug)):
await start_task
@api_process

View File

@ -3,13 +3,11 @@
import asyncio
from collections.abc import Awaitable
import logging
from typing import Any, cast
from typing import Any
from aiohttp import BasicAuth, web
from aiohttp.hdrs import AUTHORIZATION, CONTENT_TYPE, WWW_AUTHENTICATE
from aiohttp.web import FileField
from aiohttp.web_exceptions import HTTPUnauthorized
from multidict import MultiDictProxy
import voluptuous as vol
from ..addons.addon import Addon
@ -53,10 +51,7 @@ class APIAuth(CoreSysAttributes):
return self.sys_auth.check_login(addon, auth.login, auth.password)
def _process_dict(
self,
request: web.Request,
addon: Addon,
data: dict[str, Any] | MultiDictProxy[str | bytes | FileField],
self, request: web.Request, addon: Addon, data: dict[str, str]
) -> Awaitable[bool]:
"""Process login with dict data.
@ -65,15 +60,7 @@ class APIAuth(CoreSysAttributes):
username = data.get("username") or data.get("user")
password = data.get("password")
# Test that we did receive strings and not something else, raise if so
try:
_ = username.encode and password.encode # type: ignore
except AttributeError:
raise HTTPUnauthorized(headers=REALM_HEADER) from None
return self.sys_auth.check_login(
addon, cast(str, username), cast(str, password)
)
return self.sys_auth.check_login(addon, username, password)
@api_process
async def auth(self, request: web.Request) -> bool:
@ -92,18 +79,13 @@ class APIAuth(CoreSysAttributes):
# Json
if request.headers.get(CONTENT_TYPE) == CONTENT_TYPE_JSON:
data = await request.json(loads=json_loads)
if not await self._process_dict(request, addon, data):
raise HTTPUnauthorized()
return True
return await self._process_dict(request, addon, data)
# URL encoded
if request.headers.get(CONTENT_TYPE) == CONTENT_TYPE_URL:
data = await request.post()
if not await self._process_dict(request, addon, data):
raise HTTPUnauthorized()
return True
return await self._process_dict(request, addon, data)
# Advertise Basic authentication by default
raise HTTPUnauthorized(headers=REALM_HEADER)
@api_process

View File

@ -87,4 +87,4 @@ class DetectBlockingIO(StrEnum):
OFF = "off"
ON = "on"
ON_AT_STARTUP = "on-at-startup"
ON_AT_STARTUP = "on_at_startup"

View File

@ -1,7 +1,7 @@
"""Init file for Supervisor network RESTful API."""
import logging
from typing import Any
from typing import Any, cast
from aiohttp import web
import voluptuous as vol
@ -56,8 +56,8 @@ class APIDiscovery(CoreSysAttributes):
}
for message in self.sys_discovery.list_messages
if (
discovered := self.sys_addons.get_local_only(
message.addon,
discovered := cast(
Addon, self.sys_addons.get(message.addon, local_only=True)
)
)
and discovered.state == AddonState.STARTED

View File

@ -6,10 +6,7 @@ from typing import Any
from aiohttp import web
import voluptuous as vol
from supervisor.resolution.const import ContextType, IssueType, SuggestionType
from ..const import (
ATTR_ENABLE_IPV6,
ATTR_HOSTNAME,
ATTR_LOGGING,
ATTR_PASSWORD,
@ -33,48 +30,10 @@ SCHEMA_DOCKER_REGISTRY = vol.Schema(
}
)
# pylint: disable=no-value-for-parameter
SCHEMA_OPTIONS = vol.Schema({vol.Optional(ATTR_ENABLE_IPV6): vol.Maybe(vol.Boolean())})
class APIDocker(CoreSysAttributes):
"""Handle RESTful API for Docker configuration."""
@api_process
async def info(self, request: web.Request):
"""Get docker info."""
data_registries = {}
for hostname, registry in self.sys_docker.config.registries.items():
data_registries[hostname] = {
ATTR_USERNAME: registry[ATTR_USERNAME],
}
return {
ATTR_VERSION: self.sys_docker.info.version,
ATTR_ENABLE_IPV6: self.sys_docker.config.enable_ipv6,
ATTR_STORAGE: self.sys_docker.info.storage,
ATTR_LOGGING: self.sys_docker.info.logging,
ATTR_REGISTRIES: data_registries,
}
@api_process
async def options(self, request: web.Request) -> None:
"""Set docker options."""
body = await api_validate(SCHEMA_OPTIONS, request)
if (
ATTR_ENABLE_IPV6 in body
and self.sys_docker.config.enable_ipv6 != body[ATTR_ENABLE_IPV6]
):
self.sys_docker.config.enable_ipv6 = body[ATTR_ENABLE_IPV6]
_LOGGER.info("Host system reboot required to apply new IPv6 configuration")
self.sys_resolution.create_issue(
IssueType.REBOOT_REQUIRED,
ContextType.SYSTEM,
suggestions=[SuggestionType.EXECUTE_REBOOT],
)
await self.sys_docker.config.save_data()
@api_process
async def registries(self, request) -> dict[str, Any]:
"""Return the list of registries."""
@ -105,3 +64,18 @@ class APIDocker(CoreSysAttributes):
del self.sys_docker.config.registries[hostname]
await self.sys_docker.config.save_data()
@api_process
async def info(self, request: web.Request):
"""Get docker info."""
data_registries = {}
for hostname, registry in self.sys_docker.config.registries.items():
data_registries[hostname] = {
ATTR_USERNAME: registry[ATTR_USERNAME],
}
return {
ATTR_VERSION: self.sys_docker.info.version,
ATTR_STORAGE: self.sys_docker.info.storage,
ATTR_LOGGING: self.sys_docker.info.logging,
ATTR_REGISTRIES: data_registries,
}

View File

@ -309,9 +309,9 @@ class APIIngress(CoreSysAttributes):
def _init_header(
request: web.Request, addon: Addon, session_data: IngressSessionData | None
) -> CIMultiDict[str]:
) -> CIMultiDict | dict[str, str]:
"""Create initial header."""
headers = CIMultiDict[str]()
headers = {}
if session_data is not None:
headers[HEADER_REMOTE_USER_ID] = session_data.user.id
@ -337,7 +337,7 @@ def _init_header(
istr(HEADER_REMOTE_USER_DISPLAY_NAME),
):
continue
headers.add(name, value)
headers[name] = value
# Update X-Forwarded-For
if request.transport:
@ -348,9 +348,9 @@ def _init_header(
return headers
def _response_header(response: aiohttp.ClientResponse) -> CIMultiDict[str]:
def _response_header(response: aiohttp.ClientResponse) -> dict[str, str]:
"""Create response header."""
headers = CIMultiDict[str]()
headers = {}
for name, value in response.headers.items():
if name in (
@ -360,7 +360,7 @@ def _response_header(response: aiohttp.ClientResponse) -> CIMultiDict[str]:
hdrs.CONTENT_ENCODING,
):
continue
headers.add(name, value)
headers[name] = value
return headers

View File

@ -40,8 +40,8 @@ from ..const import (
ATTR_TYPE,
ATTR_VLAN,
ATTR_WIFI,
DOCKER_IPV4_NETWORK_MASK,
DOCKER_NETWORK,
DOCKER_NETWORK_MASK,
)
from ..coresys import CoreSysAttributes
from ..exceptions import APIError, APINotFound, HostNetworkNotFound
@ -203,7 +203,7 @@ class APINetwork(CoreSysAttributes):
],
ATTR_DOCKER: {
ATTR_INTERFACE: DOCKER_NETWORK,
ATTR_ADDRESS: str(DOCKER_IPV4_NETWORK_MASK),
ATTR_ADDRESS: str(DOCKER_NETWORK_MASK),
ATTR_GATEWAY: str(self.sys_docker.network.gateway),
ATTR_DNS: str(self.sys_docker.network.dns),
},

View File

@ -17,7 +17,6 @@ from ..const import (
ATTR_ICON,
ATTR_LOGGING,
ATTR_MACHINE,
ATTR_MACHINE_ID,
ATTR_NAME,
ATTR_OPERATING_SYSTEM,
ATTR_STATE,
@ -49,7 +48,6 @@ class APIRoot(CoreSysAttributes):
ATTR_OPERATING_SYSTEM: self.sys_host.info.operating_system,
ATTR_FEATURES: self.sys_host.features,
ATTR_MACHINE: self.sys_machine,
ATTR_MACHINE_ID: self.sys_machine_id,
ATTR_ARCH: self.sys_arch.default,
ATTR_STATE: self.sys_core.state,
ATTR_SUPPORTED_ARCH: self.sys_arch.supported,

View File

@ -126,7 +126,9 @@ class APIStore(CoreSysAttributes):
"""Generate addon information."""
installed = (
self.sys_addons.get_local_only(addon.slug) if addon.is_installed else None
cast(Addon, self.sys_addons.get(addon.slug, local_only=True))
if addon.is_installed
else None
)
data = {

View File

@ -40,7 +40,7 @@ class CpuArch(CoreSysAttributes):
@property
def supervisor(self) -> str:
"""Return supervisor arch."""
return self.sys_supervisor.arch or self._default_arch
return self.sys_supervisor.arch
@property
def supported(self) -> list[str]:
@ -91,14 +91,4 @@ class CpuArch(CoreSysAttributes):
for check, value in MAP_CPU.items():
if cpu.startswith(check):
return value
if self.sys_supervisor.arch:
_LOGGER.warning(
"Unknown CPU architecture %s, falling back to Supervisor architecture.",
cpu,
)
return self.sys_supervisor.arch
_LOGGER.warning(
"Unknown CPU architecture %s, assuming CPU architecture equals Supervisor architecture.",
cpu,
)
return cpu
return self.sys_supervisor.arch

View File

@ -3,10 +3,10 @@
import asyncio
import hashlib
import logging
from typing import Any, TypedDict, cast
from typing import Any
from .addons.addon import Addon
from .const import ATTR_PASSWORD, ATTR_TYPE, ATTR_USERNAME, FILE_HASSIO_AUTH
from .const import ATTR_ADDON, ATTR_PASSWORD, ATTR_TYPE, ATTR_USERNAME, FILE_HASSIO_AUTH
from .coresys import CoreSys, CoreSysAttributes
from .exceptions import (
AuthError,
@ -21,17 +21,6 @@ from .validate import SCHEMA_AUTH_CONFIG
_LOGGER: logging.Logger = logging.getLogger(__name__)
class BackendAuthRequest(TypedDict):
"""Model for a backend auth request.
https://github.com/home-assistant/core/blob/ed9503324d9d255e6fb077f1614fb6d55800f389/homeassistant/components/hassio/auth.py#L66-L73
"""
username: str
password: str
addon: str
class Auth(FileConfiguration, CoreSysAttributes):
"""Manage SSO for Add-ons with Home Assistant user."""
@ -85,9 +74,6 @@ class Auth(FileConfiguration, CoreSysAttributes):
"""Check username login."""
if password is None:
raise AuthError("None as password is not supported!", _LOGGER.error)
if username is None:
raise AuthError("None as username is not supported!", _LOGGER.error)
_LOGGER.info("Auth request from '%s' for '%s'", addon.slug, username)
# Get from cache
@ -117,12 +103,11 @@ class Auth(FileConfiguration, CoreSysAttributes):
async with self.sys_homeassistant.api.make_request(
"post",
"api/hassio_auth",
json=cast(
dict[str, Any],
BackendAuthRequest(
username=username, password=password, addon=addon.slug
),
),
json={
ATTR_USERNAME: username,
ATTR_PASSWORD: password,
ATTR_ADDON: addon.slug,
},
) as req:
if req.status == 200:
_LOGGER.info("Successful login for '%s'", username)

View File

@ -18,6 +18,8 @@ import time
from typing import Any, Self, cast
from awesomeversion import AwesomeVersion, AwesomeVersionCompareException
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from securetar import AddFileError, SecureTarFile, atomic_contents_add, secure_path
import voluptuous as vol
from voluptuous.humanize import humanize_error
@ -60,11 +62,9 @@ from ..utils.dt import parse_datetime, utcnow
from ..utils.json import json_bytes
from ..utils.sentinel import DEFAULT
from .const import BUF_SIZE, LOCATION_CLOUD_BACKUP, BackupType
from .utils import password_to_key
from .utils import key_to_iv, password_to_key
from .validate import SCHEMA_BACKUP
IGNORED_COMPARISON_FIELDS = {ATTR_PROTECTED, ATTR_CRYPTO, ATTR_DOCKER}
_LOGGER: logging.Logger = logging.getLogger(__name__)
@ -102,6 +102,7 @@ class Backup(JobGroup):
self._tmp: TemporaryDirectory | None = None
self._outer_secure_tarfile: SecureTarFile | None = None
self._key: bytes | None = None
self._aes: Cipher | None = None
self._locations: dict[str | None, BackupLocation] = {
location: BackupLocation(
path=tar_file,
@ -267,7 +268,7 @@ class Backup(JobGroup):
# Compare all fields except ones about protection. Current encryption status does not affect equality
keys = self._data.keys() | other._data.keys()
for k in keys - IGNORED_COMPARISON_FIELDS:
for k in keys - {ATTR_PROTECTED, ATTR_CRYPTO, ATTR_DOCKER}:
if (
k not in self._data
or k not in other._data
@ -347,10 +348,16 @@ class Backup(JobGroup):
self._init_password(password)
else:
self._key = None
self._aes = None
def _init_password(self, password: str) -> None:
"""Create key from password."""
"""Set password + init aes cipher."""
self._key = password_to_key(password)
self._aes = Cipher(
algorithms.AES(self._key),
modes.CBC(key_to_iv(self._key)),
backend=default_backend(),
)
async def validate_backup(self, location: str | None) -> None:
"""Validate backup.
@ -579,21 +586,13 @@ class Backup(JobGroup):
@Job(name="backup_addon_save", cleanup=False)
async def _addon_save(self, addon: Addon) -> asyncio.Task | None:
"""Store an add-on into backup."""
self.sys_jobs.current.reference = slug = addon.slug
self.sys_jobs.current.reference = addon.slug
if not self._outer_secure_tarfile:
raise RuntimeError(
"Cannot backup components without initializing backup tar"
)
# Ensure it is still installed and get current data before proceeding
if not (curr_addon := self.sys_addons.get_local_only(slug)):
_LOGGER.warning(
"Skipping backup of add-on %s because it has been uninstalled",
slug,
)
return None
tar_name = f"{slug}.tar{'.gz' if self.compressed else ''}"
tar_name = f"{addon.slug}.tar{'.gz' if self.compressed else ''}"
addon_file = self._outer_secure_tarfile.create_inner_tar(
f"./{tar_name}",
@ -602,16 +601,16 @@ class Backup(JobGroup):
)
# Take backup
try:
start_task = await curr_addon.backup(addon_file)
start_task = await addon.backup(addon_file)
except AddonsError as err:
raise BackupError(str(err)) from err
# Store to config
self._data[ATTR_ADDONS].append(
{
ATTR_SLUG: slug,
ATTR_NAME: curr_addon.name,
ATTR_VERSION: curr_addon.version,
ATTR_SLUG: addon.slug,
ATTR_NAME: addon.name,
ATTR_VERSION: addon.version,
# Bug - addon_file.size used to give us this information
# It always returns 0 in current securetar. Skipping until fixed
ATTR_SIZE: 0,
@ -931,5 +930,5 @@ class Backup(JobGroup):
Return a coroutine.
"""
return self.sys_store.update_repositories(
set(self.repositories), issue_on_error=True, replace=replace
self.repositories, add_with_errors=True, replace=replace
)

View File

@ -1,7 +1,6 @@
"""Bootstrap Supervisor."""
# ruff: noqa: T100
import asyncio
from importlib import import_module
import logging
import os
@ -285,8 +284,8 @@ def check_environment() -> None:
_LOGGER.critical("Can't find Docker socket!")
def register_signal_handlers(loop: asyncio.AbstractEventLoop, coresys: CoreSys) -> None:
"""Register SIGTERM, SIGHUP and SIGKILL to stop the Supervisor."""
def reg_signal(loop, coresys: CoreSys) -> None:
"""Register SIGTERM and SIGKILL to stop system."""
try:
loop.add_signal_handler(
signal.SIGTERM, lambda: loop.create_task(coresys.core.stop())

View File

@ -2,7 +2,7 @@
from __future__ import annotations
from collections.abc import Callable, Coroutine
from collections.abc import Awaitable, Callable
import logging
from typing import Any
@ -19,7 +19,7 @@ class EventListener:
"""Event listener."""
event_type: BusEvent = attr.ib()
callback: Callable[[Any], Coroutine[Any, Any, None]] = attr.ib()
callback: Callable[[Any], Awaitable[None]] = attr.ib()
class Bus(CoreSysAttributes):
@ -31,7 +31,7 @@ class Bus(CoreSysAttributes):
self._listeners: dict[BusEvent, list[EventListener]] = {}
def register_event(
self, event: BusEvent, callback: Callable[[Any], Coroutine[Any, Any, None]]
self, event: BusEvent, callback: Callable[[Any], Awaitable[None]]
) -> EventListener:
"""Register callback for an event."""
listener = EventListener(event, callback)

View File

@ -66,7 +66,7 @@ _UTC = "UTC"
class CoreConfig(FileConfiguration):
"""Hold all core config data."""
def __init__(self) -> None:
def __init__(self):
"""Initialize config object."""
super().__init__(FILE_HASSIO_CONFIG, SCHEMA_SUPERVISOR_CONFIG)
self._timezone_tzinfo: tzinfo | None = None

View File

@ -2,20 +2,16 @@
from dataclasses import dataclass
from enum import StrEnum
from ipaddress import IPv4Network, IPv6Network
from ipaddress import IPv4Network
from pathlib import Path
from sys import version_info as systemversion
from typing import NotRequired, Self, TypedDict
from typing import Self
from aiohttp import __version__ as aiohttpversion
SUPERVISOR_VERSION = "9999.09.9.dev9999"
SERVER_SOFTWARE = f"HomeAssistantSupervisor/{SUPERVISOR_VERSION} aiohttp/{aiohttpversion} Python/{systemversion[0]}.{systemversion[1]}"
DOCKER_PREFIX: str = "hassio"
OBSERVER_DOCKER_NAME: str = f"{DOCKER_PREFIX}_observer"
SUPERVISOR_DOCKER_NAME: str = f"{DOCKER_PREFIX}_supervisor"
URL_HASSIO_ADDONS = "https://github.com/home-assistant/addons"
URL_HASSIO_APPARMOR = "https://version.home-assistant.io/apparmor_{channel}.txt"
URL_HASSIO_VERSION = "https://version.home-assistant.io/{channel}.json"
@ -45,10 +41,8 @@ SYSTEMD_JOURNAL_PERSISTENT = Path("/var/log/journal")
SYSTEMD_JOURNAL_VOLATILE = Path("/run/log/journal")
DOCKER_NETWORK = "hassio"
DOCKER_NETWORK_DRIVER = "bridge"
DOCKER_IPV6_NETWORK_MASK = IPv6Network("fd0c:ac1e:2100::/48")
DOCKER_IPV4_NETWORK_MASK = IPv4Network("172.30.32.0/23")
DOCKER_IPV4_NETWORK_RANGE = IPv4Network("172.30.33.0/24")
DOCKER_NETWORK_MASK = IPv4Network("172.30.32.0/23")
DOCKER_NETWORK_RANGE = IPv4Network("172.30.33.0/24")
# This needs to match the dockerd --cpu-rt-runtime= argument.
DOCKER_CPU_RUNTIME_TOTAL = 950_000
@ -178,7 +172,6 @@ ATTR_DOCKER_API = "docker_api"
ATTR_DOCUMENTATION = "documentation"
ATTR_DOMAINS = "domains"
ATTR_ENABLE = "enable"
ATTR_ENABLE_IPV6 = "enable_ipv6"
ATTR_ENABLED = "enabled"
ATTR_ENVIRONMENT = "environment"
ATTR_EVENT = "event"
@ -188,7 +181,6 @@ ATTR_FEATURES = "features"
ATTR_FILENAME = "filename"
ATTR_FLAGS = "flags"
ATTR_FOLDERS = "folders"
ATTR_FORCE = "force"
ATTR_FORCE_SECURITY = "force_security"
ATTR_FREQUENCY = "frequency"
ATTR_FULL_ACCESS = "full_access"
@ -247,7 +239,6 @@ ATTR_LOGO = "logo"
ATTR_LONG_DESCRIPTION = "long_description"
ATTR_MAC = "mac"
ATTR_MACHINE = "machine"
ATTR_MACHINE_ID = "machine_id"
ATTR_MAINTAINER = "maintainer"
ATTR_MAP = "map"
ATTR_MEMORY_LIMIT = "memory_limit"
@ -416,12 +407,10 @@ class AddonBoot(StrEnum):
MANUAL = "manual"
@classmethod
def _missing_(cls, value: object) -> Self | None:
def _missing_(cls, value: str) -> Self | None:
"""Convert 'forced' config values to their counterpart."""
if value == AddonBootConfig.MANUAL_ONLY:
for member in cls:
if member == AddonBoot.MANUAL:
return member
return AddonBoot.MANUAL
return None
@ -518,16 +507,6 @@ class CpuArch(StrEnum):
AMD64 = "amd64"
class IngressSessionDataUserDict(TypedDict):
"""Response object for ingress session user."""
id: str
username: NotRequired[str | None]
# Name is an alias for displayname, only one should be used
displayname: NotRequired[str | None]
name: NotRequired[str | None]
@dataclass
class IngressSessionDataUser:
"""Format of an IngressSessionDataUser object."""
@ -536,42 +515,38 @@ class IngressSessionDataUser:
display_name: str | None = None
username: str | None = None
def to_dict(self) -> IngressSessionDataUserDict:
def to_dict(self) -> dict[str, str | None]:
"""Get dictionary representation."""
return IngressSessionDataUserDict(
id=self.id, displayname=self.display_name, username=self.username
)
return {
ATTR_ID: self.id,
ATTR_DISPLAYNAME: self.display_name,
ATTR_USERNAME: self.username,
}
@classmethod
def from_dict(cls, data: IngressSessionDataUserDict) -> Self:
def from_dict(cls, data: dict[str, str | None]) -> Self:
"""Return object from dictionary representation."""
return cls(
id=data["id"],
display_name=data.get("displayname") or data.get("name"),
username=data.get("username"),
id=data[ATTR_ID],
display_name=data.get(ATTR_DISPLAYNAME),
username=data.get(ATTR_USERNAME),
)
class IngressSessionDataDict(TypedDict):
"""Response object for ingress session data."""
user: IngressSessionDataUserDict
@dataclass
class IngressSessionData:
"""Format of an IngressSessionData object."""
user: IngressSessionDataUser
def to_dict(self) -> IngressSessionDataDict:
def to_dict(self) -> dict[str, dict[str, str | None]]:
"""Get dictionary representation."""
return IngressSessionDataDict(user=self.user.to_dict())
return {ATTR_USER: self.user.to_dict()}
@classmethod
def from_dict(cls, data: IngressSessionDataDict) -> Self:
def from_dict(cls, data: dict[str, dict[str, str | None]]) -> Self:
"""Return object from dictionary representation."""
return cls(user=IngressSessionDataUser.from_dict(data["user"]))
return cls(user=IngressSessionDataUser.from_dict(data[ATTR_USER]))
STARTING_STATES = [

View File

@ -28,7 +28,7 @@ from .homeassistant.core import LANDINGPAGE
from .resolution.const import ContextType, IssueType, SuggestionType, UnhealthyReason
from .utils.dt import utcnow
from .utils.sentry import async_capture_exception
from .utils.whoami import retrieve_whoami
from .utils.whoami import WhoamiData, retrieve_whoami
_LOGGER: logging.Logger = logging.getLogger(__name__)
@ -36,7 +36,7 @@ _LOGGER: logging.Logger = logging.getLogger(__name__)
class Core(CoreSysAttributes):
"""Main object of Supervisor."""
def __init__(self, coresys: CoreSys) -> None:
def __init__(self, coresys: CoreSys):
"""Initialize Supervisor object."""
self.coresys: CoreSys = coresys
self._state: CoreState = CoreState.INITIALIZE
@ -91,7 +91,7 @@ class Core(CoreSysAttributes):
"info", {"state": self._state}
)
async def connect(self) -> None:
async def connect(self):
"""Connect Supervisor container."""
# Load information from container
await self.sys_supervisor.load()
@ -120,7 +120,7 @@ class Core(CoreSysAttributes):
self.sys_config.version = self.sys_supervisor.version
await self.sys_config.save_data()
async def setup(self) -> None:
async def setup(self):
"""Start setting up supervisor orchestration."""
await self.set_state(CoreState.SETUP)
@ -188,10 +188,7 @@ class Core(CoreSysAttributes):
await setup_task
except Exception as err: # pylint: disable=broad-except
_LOGGER.critical(
"Fatal error happening on load Task %s: %s",
setup_task,
err,
exc_info=True,
"Fatal error happening on load Task %s: %s", setup_task, err
)
self.sys_resolution.add_unhealthy_reason(UnhealthyReason.SETUP)
await async_capture_exception(err)
@ -216,7 +213,7 @@ class Core(CoreSysAttributes):
# Evaluate the system
await self.sys_resolution.evaluate.evaluate_system()
async def start(self) -> None:
async def start(self):
"""Start Supervisor orchestration."""
await self.set_state(CoreState.STARTUP)
@ -240,10 +237,10 @@ class Core(CoreSysAttributes):
await self.sys_supervisor.update()
return
try:
# Start addon mark as initialize
await self.sys_addons.boot(AddonStartup.INITIALIZE)
# Start addon mark as initialize
await self.sys_addons.boot(AddonStartup.INITIALIZE)
try:
# HomeAssistant is already running, only Supervisor restarted
if await self.sys_hardware.helper.last_boot() == self.sys_config.last_boot:
_LOGGER.info("Detected Supervisor restart")
@ -310,7 +307,7 @@ class Core(CoreSysAttributes):
)
_LOGGER.info("Supervisor is up and running")
async def stop(self) -> None:
async def stop(self):
"""Stop a running orchestration."""
# store new last boot / prevent time adjustments
if self.state in (CoreState.RUNNING, CoreState.SHUTDOWN):
@ -358,7 +355,7 @@ class Core(CoreSysAttributes):
_LOGGER.info("Supervisor is down - %d", self.exit_code)
self.sys_loop.stop()
async def shutdown(self, *, remove_homeassistant_container: bool = False) -> None:
async def shutdown(self, *, remove_homeassistant_container: bool = False):
"""Shutdown all running containers in correct order."""
# don't process scheduler anymore
if self.state == CoreState.RUNNING:
@ -382,15 +379,19 @@ class Core(CoreSysAttributes):
if self.state in (CoreState.STOPPING, CoreState.SHUTDOWN):
await self.sys_plugins.shutdown()
async def _update_last_boot(self) -> None:
async def _update_last_boot(self):
"""Update last boot time."""
if not (last_boot := await self.sys_hardware.helper.last_boot()):
_LOGGER.error("Could not update last boot information!")
return
self.sys_config.last_boot = last_boot
self.sys_config.last_boot = await self.sys_hardware.helper.last_boot()
await self.sys_config.save_data()
async def _adjust_system_datetime(self) -> None:
async def _retrieve_whoami(self, with_ssl: bool) -> WhoamiData | None:
try:
return await retrieve_whoami(self.sys_websession, with_ssl)
except WhoamiSSLError:
_LOGGER.info("Whoami service SSL error")
return None
async def _adjust_system_datetime(self):
"""Adjust system time/date on startup."""
# If no timezone is detect or set
# If we are not connected or time sync
@ -402,13 +403,11 @@ class Core(CoreSysAttributes):
# Get Timezone data
try:
try:
data = await retrieve_whoami(self.sys_websession, True)
except WhoamiSSLError:
# SSL Date Issue & possible time drift
_LOGGER.info("Whoami service SSL error")
data = await retrieve_whoami(self.sys_websession, False)
data = await self._retrieve_whoami(True)
# SSL Date Issue & possible time drift
if not data:
data = await self._retrieve_whoami(False)
except WhoamiError as err:
_LOGGER.warning("Can't adjust Time/Date settings: %s", err)
return
@ -424,7 +423,7 @@ class Core(CoreSysAttributes):
await self.sys_host.control.set_datetime(data.dt_utc)
await self.sys_supervisor.check_connectivity()
async def repair(self) -> None:
async def repair(self):
"""Repair system integrity."""
_LOGGER.info("Starting repair of Supervisor Environment")
await self.sys_run_in_executor(self.sys_docker.repair)

View File

@ -62,17 +62,17 @@ _LOGGER: logging.Logger = logging.getLogger(__name__)
class CoreSys:
"""Class that handle all shared data."""
def __init__(self) -> None:
def __init__(self):
"""Initialize coresys."""
# Static attributes protected
self._machine_id: str | None = None
self._machine: str | None = None
# External objects
self._loop = asyncio.get_running_loop()
self._loop: asyncio.BaseEventLoop = asyncio.get_running_loop()
# Global objects
self._config = CoreConfig()
self._config: CoreConfig = CoreConfig()
# Internal objects pointers
self._docker: DockerAPI | None = None
@ -122,12 +122,8 @@ class CoreSys:
if self._websession:
await self._websession.close()
resolver: aiohttp.abc.AbstractResolver
try:
# Use "unused" kwargs to force dedicated resolver instance. Otherwise
# aiodns won't reload /etc/resolv.conf which we need to make our connection
# check work in all cases.
resolver = aiohttp.AsyncResolver(loop=self.loop, timeout=None)
resolver = aiohttp.AsyncResolver(loop=self.loop)
# pylint: disable=protected-access
_LOGGER.debug(
"Initializing ClientSession with AsyncResolver. Using nameservers %s",
@ -148,7 +144,7 @@ class CoreSys:
self._websession = session
async def init_machine(self) -> None:
async def init_machine(self):
"""Initialize machine information."""
def _load_machine_id() -> str | None:
@ -192,7 +188,7 @@ class CoreSys:
return UTC
@property
def loop(self) -> asyncio.AbstractEventLoop:
def loop(self) -> asyncio.BaseEventLoop:
"""Return loop object."""
return self._loop
@ -590,7 +586,7 @@ class CoreSys:
return self._machine_id
@machine_id.setter
def machine_id(self, value: str | None) -> None:
def machine_id(self, value: str) -> None:
"""Set a machine-id type string."""
if self._machine_id:
raise RuntimeError("Machine-ID type already set!")
@ -612,8 +608,8 @@ class CoreSys:
self._set_task_context.append(callback)
def run_in_executor(
self, funct: Callable[..., T], *args, **kwargs
) -> asyncio.Future[T]:
self, funct: Callable[..., T], *args: tuple[Any], **kwargs: dict[str, Any]
) -> Coroutine[Any, Any, T]:
"""Add an job to the executor pool."""
if kwargs:
funct = partial(funct, **kwargs)
@ -634,9 +630,9 @@ class CoreSys:
def call_later(
self,
delay: float,
funct: Callable[..., Any],
*args,
**kwargs,
funct: Callable[..., Coroutine[Any, Any, T]],
*args: tuple[Any],
**kwargs: dict[str, Any],
) -> asyncio.TimerHandle:
"""Start a task after a delay."""
if kwargs:
@ -647,9 +643,9 @@ class CoreSys:
def call_at(
self,
when: datetime,
funct: Callable[..., Any],
*args,
**kwargs,
funct: Callable[..., Coroutine[Any, Any, T]],
*args: tuple[Any],
**kwargs: dict[str, Any],
) -> asyncio.TimerHandle:
"""Start a task at the specified datetime."""
if kwargs:
@ -677,7 +673,7 @@ class CoreSysAttributes:
@property
def sys_machine_id(self) -> str | None:
"""Return machine ID."""
"""Return machine id."""
return self.coresys.machine_id
@property
@ -686,7 +682,7 @@ class CoreSysAttributes:
return self.coresys.dev
@property
def sys_loop(self) -> asyncio.AbstractEventLoop:
def sys_loop(self) -> asyncio.BaseEventLoop:
"""Return loop object."""
return self.coresys.loop
@ -836,7 +832,7 @@ class CoreSysAttributes:
def sys_run_in_executor(
self, funct: Callable[..., T], *args, **kwargs
) -> asyncio.Future[T]:
) -> Coroutine[Any, Any, T]:
"""Add a job to the executor pool."""
return self.coresys.run_in_executor(funct, *args, **kwargs)
@ -847,7 +843,7 @@ class CoreSysAttributes:
def sys_call_later(
self,
delay: float,
funct: Callable[..., Any],
funct: Callable[..., Coroutine[Any, Any, T]],
*args,
**kwargs,
) -> asyncio.TimerHandle:
@ -857,7 +853,7 @@ class CoreSysAttributes:
def sys_call_at(
self,
when: datetime,
funct: Callable[..., Any],
funct: Callable[..., Coroutine[Any, Any, T]],
*args,
**kwargs,
) -> asyncio.TimerHandle:

View File

@ -135,7 +135,6 @@ DBUS_ATTR_LAST_ERROR = "LastError"
DBUS_ATTR_LLMNR = "LLMNR"
DBUS_ATTR_LLMNR_HOSTNAME = "LLMNRHostname"
DBUS_ATTR_LOADER_TIMESTAMP_MONOTONIC = "LoaderTimestampMonotonic"
DBUS_ATTR_LOCAL_RTC = "LocalRTC"
DBUS_ATTR_MANAGED = "Managed"
DBUS_ATTR_MODE = "Mode"
DBUS_ATTR_MODEL = "Model"

View File

@ -117,7 +117,7 @@ class DBusInterfaceProxy(DBusInterface, ABC):
"""Initialize object with already connected dbus object."""
await super().initialize(connected_dbus)
if not self.connected_dbus.supports_properties:
if not self.connected_dbus.properties:
self.disconnect()
raise DBusInterfaceError(
f"D-Bus object {self.object_path} is not usable, introspection is missing required properties interface"

View File

@ -8,7 +8,7 @@ from dbus_fast.aio.message_bus import MessageBus
from ..const import SOCKET_DBUS
from ..coresys import CoreSys, CoreSysAttributes
from ..exceptions import DBusFatalError, DBusNotConnectedError
from ..exceptions import DBusFatalError
from .agent import OSAgent
from .hostname import Hostname
from .interface import DBusInterface
@ -91,13 +91,6 @@ class DBusManager(CoreSysAttributes):
"""Return the message bus."""
return self._bus
@property
def connected_bus(self) -> MessageBus:
"""Return the message bus. Raise if not connected."""
if not self._bus:
raise DBusNotConnectedError()
return self._bus
@property
def all(self) -> list[DBusInterface]:
"""Return all managed dbus interfaces."""

View File

@ -259,7 +259,7 @@ class NetworkManager(DBusInterfaceProxy):
else:
interface.primary = False
interfaces[interface.interface_name] = interface
interfaces[interface.name] = interface
interfaces[interface.hw_address] = interface
# Disconnect removed devices

View File

@ -1,6 +1,5 @@
"""NetworkConnection objects for Network Manager."""
from abc import ABC
from dataclasses import dataclass
from ipaddress import IPv4Address, IPv6Address
@ -30,7 +29,7 @@ class ConnectionProperties:
class WirelessProperties:
"""Wireless Properties object for Network Manager."""
ssid: str
ssid: str | None
assigned_mac: str | None
mode: str | None
powersave: int | None
@ -56,7 +55,7 @@ class EthernetProperties:
class VlanProperties:
"""Ethernet properties object for Network Manager."""
id: int
id: int | None
parent: str | None
@ -68,20 +67,14 @@ class IpAddress:
prefix: int
@dataclass
class IpProperties(ABC):
@dataclass(slots=True)
class IpProperties:
"""IP properties object for Network Manager."""
method: str | None
address_data: list[IpAddress] | None
gateway: str | None
@dataclass(slots=True)
class Ip4Properties(IpProperties):
"""IPv4 properties object."""
dns: list[int] | None
dns: list[bytes | int] | None
@dataclass(slots=True)
@ -90,7 +83,6 @@ class Ip6Properties(IpProperties):
addr_gen_mode: int
ip6_privacy: int
dns: list[bytes] | None
@dataclass(slots=True)

View File

@ -96,7 +96,7 @@ class NetworkConnection(DBusInterfaceProxy):
@ipv4.setter
def ipv4(self, ipv4: IpConfiguration | None) -> None:
"""Set IPv4 configuration."""
"""Set ipv4 configuration."""
if self._ipv4 and self._ipv4 is not ipv4:
self._ipv4.shutdown()
@ -109,7 +109,7 @@ class NetworkConnection(DBusInterfaceProxy):
@ipv6.setter
def ipv6(self, ipv6: IpConfiguration | None) -> None:
"""Set IPv6 configuration."""
"""Set ipv6 configuration."""
if self._ipv6 and self._ipv6 is not ipv6:
self._ipv6.shutdown()

View File

@ -49,7 +49,7 @@ class NetworkInterface(DBusInterfaceProxy):
@property
@dbus_property
def interface_name(self) -> str:
def name(self) -> str:
"""Return interface name."""
return self.properties[DBUS_ATTR_DEVICE_INTERFACE]

View File

@ -12,9 +12,9 @@ from ...utils import dbus_connected
from ..configuration import (
ConnectionProperties,
EthernetProperties,
Ip4Properties,
Ip6Properties,
IpAddress,
IpProperties,
MatchProperties,
VlanProperties,
WirelessProperties,
@ -115,7 +115,7 @@ class NetworkSetting(DBusInterface):
self._wireless_security: WirelessSecurityProperties | None = None
self._ethernet: EthernetProperties | None = None
self._vlan: VlanProperties | None = None
self._ipv4: Ip4Properties | None = None
self._ipv4: IpProperties | None = None
self._ipv6: Ip6Properties | None = None
self._match: MatchProperties | None = None
super().__init__()
@ -151,13 +151,13 @@ class NetworkSetting(DBusInterface):
return self._vlan
@property
def ipv4(self) -> Ip4Properties | None:
"""Return IPv4 properties if any."""
def ipv4(self) -> IpProperties | None:
"""Return ipv4 properties if any."""
return self._ipv4
@property
def ipv6(self) -> Ip6Properties | None:
"""Return IPv6 properties if any."""
"""Return ipv6 properties if any."""
return self._ipv6
@property
@ -271,23 +271,16 @@ class NetworkSetting(DBusInterface):
)
if CONF_ATTR_VLAN in data:
if CONF_ATTR_VLAN_ID in data[CONF_ATTR_VLAN]:
self._vlan = VlanProperties(
data[CONF_ATTR_VLAN][CONF_ATTR_VLAN_ID],
data[CONF_ATTR_VLAN].get(CONF_ATTR_VLAN_PARENT),
)
else:
self._vlan = None
_LOGGER.warning(
"Network settings for vlan connection %s missing required vlan id, cannot process it",
self.connection.interface_name,
)
self._vlan = VlanProperties(
id=data[CONF_ATTR_VLAN].get(CONF_ATTR_VLAN_ID),
parent=data[CONF_ATTR_VLAN].get(CONF_ATTR_VLAN_PARENT),
)
if CONF_ATTR_IPV4 in data:
address_data = None
if ips := data[CONF_ATTR_IPV4].get(CONF_ATTR_IPV4_ADDRESS_DATA):
address_data = [IpAddress(ip["address"], ip["prefix"]) for ip in ips]
self._ipv4 = Ip4Properties(
self._ipv4 = IpProperties(
method=data[CONF_ATTR_IPV4].get(CONF_ATTR_IPV4_METHOD),
address_data=address_data,
gateway=data[CONF_ATTR_IPV4].get(CONF_ATTR_IPV4_GATEWAY),

View File

@ -222,10 +222,8 @@ def get_connection_from_interface(
}
elif interface.type == "vlan":
parent = cast(VlanConfig, interface.vlan).interface
if (
parent
and parent in network_manager
and (parent_connection := network_manager.get(parent).connection)
if parent in network_manager and (
parent_connection := network_manager.get(parent).connection
):
parent = parent_connection.uuid

View File

@ -10,7 +10,6 @@ from dbus_fast.aio.message_bus import MessageBus
from ..exceptions import DBusError, DBusInterfaceError, DBusServiceUnkownError
from ..utils.dt import get_time_zone, utc_from_timestamp
from .const import (
DBUS_ATTR_LOCAL_RTC,
DBUS_ATTR_NTP,
DBUS_ATTR_NTPSYNCHRONIZED,
DBUS_ATTR_TIMEUSEC,
@ -47,12 +46,6 @@ class TimeDate(DBusInterfaceProxy):
"""Return host timezone."""
return self.properties[DBUS_ATTR_TIMEZONE]
@property
@dbus_property
def local_rtc(self) -> bool:
"""Return whether rtc is local time or utc."""
return self.properties[DBUS_ATTR_LOCAL_RTC]
@property
@dbus_property
def ntp(self) -> bool:

View File

@ -28,8 +28,6 @@ class DeviceSpecificationDataType(TypedDict, total=False):
path: str
label: str
uuid: str
partuuid: str
partlabel: str
@dataclass(slots=True)
@ -42,8 +40,6 @@ class DeviceSpecification:
path: Path | None = None
label: str | None = None
uuid: str | None = None
partuuid: str | None = None
partlabel: str | None = None
@staticmethod
def from_dict(data: DeviceSpecificationDataType) -> "DeviceSpecification":
@ -52,8 +48,6 @@ class DeviceSpecification:
path=Path(data["path"]) if "path" in data else None,
label=data.get("label"),
uuid=data.get("uuid"),
partuuid=data.get("partuuid"),
partlabel=data.get("partlabel"),
)
def to_dict(self) -> dict[str, Variant]:
@ -62,8 +56,6 @@ class DeviceSpecification:
"path": Variant("s", self.path.as_posix()) if self.path else None,
"label": _optional_variant("s", self.label),
"uuid": _optional_variant("s", self.uuid),
"partuuid": _optional_variant("s", self.partuuid),
"partlabel": _optional_variant("s", self.partlabel),
}
return {k: v for k, v in data.items() if v}

View File

@ -12,7 +12,6 @@ from typing import TYPE_CHECKING, cast
from attr import evolve
from awesomeversion import AwesomeVersion
import docker
import docker.errors
from docker.types import Mount
import requests
@ -44,7 +43,6 @@ from ..jobs.decorator import Job
from ..resolution.const import CGROUP_V2_VERSION, ContextType, IssueType, SuggestionType
from ..utils.sentry import async_capture_exception
from .const import (
ADDON_BUILDER_IMAGE,
ENV_TIME,
ENV_TOKEN,
ENV_TOKEN_OLD,
@ -346,7 +344,7 @@ class DockerAddon(DockerInterface):
mounts = [
MOUNT_DEV,
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.addon.path_extern_data.as_posix(),
target=target_data_path or PATH_PRIVATE_DATA.as_posix(),
read_only=False,
@ -357,7 +355,7 @@ class DockerAddon(DockerInterface):
if MappingType.CONFIG in addon_mapping:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_homeassistant.as_posix(),
target=addon_mapping[MappingType.CONFIG].path
or PATH_HOMEASSISTANT_CONFIG_LEGACY.as_posix(),
@ -370,7 +368,7 @@ class DockerAddon(DockerInterface):
if self.addon.addon_config_used:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.addon.path_extern_config.as_posix(),
target=addon_mapping[MappingType.ADDON_CONFIG].path
or PATH_PUBLIC_CONFIG.as_posix(),
@ -382,7 +380,7 @@ class DockerAddon(DockerInterface):
if MappingType.HOMEASSISTANT_CONFIG in addon_mapping:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_homeassistant.as_posix(),
target=addon_mapping[MappingType.HOMEASSISTANT_CONFIG].path
or PATH_HOMEASSISTANT_CONFIG.as_posix(),
@ -395,7 +393,7 @@ class DockerAddon(DockerInterface):
if MappingType.ALL_ADDON_CONFIGS in addon_mapping:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_addon_configs.as_posix(),
target=addon_mapping[MappingType.ALL_ADDON_CONFIGS].path
or PATH_ALL_ADDON_CONFIGS.as_posix(),
@ -406,7 +404,7 @@ class DockerAddon(DockerInterface):
if MappingType.SSL in addon_mapping:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_ssl.as_posix(),
target=addon_mapping[MappingType.SSL].path or PATH_SSL.as_posix(),
read_only=addon_mapping[MappingType.SSL].read_only,
@ -416,7 +414,7 @@ class DockerAddon(DockerInterface):
if MappingType.ADDONS in addon_mapping:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_addons_local.as_posix(),
target=addon_mapping[MappingType.ADDONS].path
or PATH_LOCAL_ADDONS.as_posix(),
@ -427,7 +425,7 @@ class DockerAddon(DockerInterface):
if MappingType.BACKUP in addon_mapping:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_backup.as_posix(),
target=addon_mapping[MappingType.BACKUP].path
or PATH_BACKUP.as_posix(),
@ -438,7 +436,7 @@ class DockerAddon(DockerInterface):
if MappingType.SHARE in addon_mapping:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_share.as_posix(),
target=addon_mapping[MappingType.SHARE].path
or PATH_SHARE.as_posix(),
@ -450,7 +448,7 @@ class DockerAddon(DockerInterface):
if MappingType.MEDIA in addon_mapping:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_media.as_posix(),
target=addon_mapping[MappingType.MEDIA].path
or PATH_MEDIA.as_posix(),
@ -468,7 +466,7 @@ class DockerAddon(DockerInterface):
continue
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=gpio_path,
target=gpio_path,
read_only=False,
@ -479,7 +477,7 @@ class DockerAddon(DockerInterface):
if self.addon.with_devicetree:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source="/sys/firmware/devicetree/base",
target="/device-tree",
read_only=True,
@ -494,7 +492,7 @@ class DockerAddon(DockerInterface):
if self.addon.with_kernel_modules:
mounts.append(
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source="/lib/modules",
target="/lib/modules",
read_only=True,
@ -513,19 +511,19 @@ class DockerAddon(DockerInterface):
if self.addon.with_audio:
mounts += [
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.addon.path_extern_pulse.as_posix(),
target="/etc/pulse/client.conf",
read_only=True,
),
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_plugins.audio.path_extern_pulse.as_posix(),
target="/run/audio",
read_only=True,
),
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_plugins.audio.path_extern_asound.as_posix(),
target="/etc/asound.conf",
read_only=True,
@ -536,13 +534,13 @@ class DockerAddon(DockerInterface):
if self.addon.with_journald:
mounts += [
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=SYSTEMD_JOURNAL_PERSISTENT.as_posix(),
target=SYSTEMD_JOURNAL_PERSISTENT.as_posix(),
read_only=True,
),
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=SYSTEMD_JOURNAL_VOLATILE.as_posix(),
target=SYSTEMD_JOURNAL_VOLATILE.as_posix(),
read_only=True,
@ -675,41 +673,10 @@ class DockerAddon(DockerInterface):
_LOGGER.info("Starting build for %s:%s", self.image, version)
def build_image():
if build_env.squash:
_LOGGER.warning(
"Ignoring squash build option for %s as Docker BuildKit does not support it.",
self.addon.slug,
)
addon_image_tag = f"{image or self.addon.image}:{version!s}"
docker_version = self.sys_docker.info.version
builder_version_tag = f"{docker_version.major}.{docker_version.minor}.{docker_version.micro}-cli"
builder_name = f"addon_builder_{self.addon.slug}"
# Remove dangling builder container if it exists by any chance
# E.g. because of an abrupt host shutdown/reboot during a build
with suppress(docker.errors.NotFound):
self.sys_docker.containers.get(builder_name).remove(force=True, v=True)
result = self.sys_docker.run_command(
ADDON_BUILDER_IMAGE,
version=builder_version_tag,
name=builder_name,
**build_env.get_docker_args(version, addon_image_tag),
return self.sys_docker.images.build(
use_config_proxy=False, **build_env.get_docker_args(version, image)
)
logs = result.output.decode("utf-8")
if result.exit_code != 0:
error_message = f"Docker build failed for {addon_image_tag} (exit code {result.exit_code}). Build output:\n{logs}"
raise docker.errors.DockerException(error_message)
addon_image = self.sys_docker.images.get(addon_image_tag)
return addon_image, logs
try:
docker_image, log = await self.sys_run_in_executor(build_image)
@ -720,6 +687,15 @@ class DockerAddon(DockerInterface):
except (docker.errors.DockerException, requests.RequestException) as err:
_LOGGER.error("Can't build %s:%s: %s", self.image, version, err)
if hasattr(err, "build_log"):
log = "\n".join(
[
x["stream"]
for x in err.build_log # pylint: disable=no-member
if isinstance(x, dict) and "stream" in x
]
)
_LOGGER.error("Build log: \n%s", log)
raise DockerError() from err
_LOGGER.info("Build %s:%s done", self.image, version)

View File

@ -47,7 +47,7 @@ class DockerAudio(DockerInterface, CoreSysAttributes):
mounts = [
MOUNT_DEV,
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_audio.as_posix(),
target=PATH_PRIVATE_DATA.as_posix(),
read_only=False,

View File

@ -74,26 +74,24 @@ ENV_TOKEN_OLD = "HASSIO_TOKEN"
LABEL_MANAGED = "supervisor_managed"
MOUNT_DBUS = Mount(
type=MountType.BIND.value, source="/run/dbus", target="/run/dbus", read_only=True
)
MOUNT_DEV = Mount(
type=MountType.BIND.value, source="/dev", target="/dev", read_only=True
type=MountType.BIND, source="/run/dbus", target="/run/dbus", read_only=True
)
MOUNT_DEV = Mount(type=MountType.BIND, source="/dev", target="/dev", read_only=True)
MOUNT_DEV.setdefault("BindOptions", {})["ReadOnlyNonRecursive"] = True
MOUNT_DOCKER = Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source="/run/docker.sock",
target="/run/docker.sock",
read_only=True,
)
MOUNT_MACHINE_ID = Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=MACHINE_ID.as_posix(),
target=MACHINE_ID.as_posix(),
read_only=True,
)
MOUNT_UDEV = Mount(
type=MountType.BIND.value, source="/run/udev", target="/run/udev", read_only=True
type=MountType.BIND, source="/run/udev", target="/run/udev", read_only=True
)
PATH_PRIVATE_DATA = PurePath("/data")
@ -107,6 +105,3 @@ PATH_BACKUP = PurePath("/backup")
PATH_SHARE = PurePath("/share")
PATH_MEDIA = PurePath("/media")
PATH_CLOUD_BACKUP = PurePath("/cloud_backup")
# https://hub.docker.com/_/docker
ADDON_BUILDER_IMAGE = "docker.io/library/docker"

View File

@ -48,7 +48,7 @@ class DockerDNS(DockerInterface, CoreSysAttributes):
environment={ENV_TIME: self.sys_timezone},
mounts=[
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_dns.as_posix(),
target="/config",
read_only=False,

View File

@ -99,7 +99,7 @@ class DockerHomeAssistant(DockerInterface):
MOUNT_UDEV,
# HA config folder
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_homeassistant.as_posix(),
target=PATH_PUBLIC_CONFIG.as_posix(),
read_only=False,
@ -112,20 +112,20 @@ class DockerHomeAssistant(DockerInterface):
[
# All other folders
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_ssl.as_posix(),
target=PATH_SSL.as_posix(),
read_only=True,
),
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_share.as_posix(),
target=PATH_SHARE.as_posix(),
read_only=False,
propagation=PropagationMode.RSLAVE.value,
),
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_media.as_posix(),
target=PATH_MEDIA.as_posix(),
read_only=False,
@ -133,19 +133,19 @@ class DockerHomeAssistant(DockerInterface):
),
# Configuration audio
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_homeassistant.path_extern_pulse.as_posix(),
target="/etc/pulse/client.conf",
read_only=True,
),
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_plugins.audio.path_extern_pulse.as_posix(),
target="/run/audio",
read_only=True,
),
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_plugins.audio.path_extern_asound.as_posix(),
target="/etc/asound.conf",
read_only=True,
@ -213,21 +213,24 @@ class DockerHomeAssistant(DockerInterface):
privileged=True,
init=True,
entrypoint=[],
detach=True,
stdout=True,
stderr=True,
mounts=[
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_homeassistant.as_posix(),
target="/config",
read_only=False,
),
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_ssl.as_posix(),
target="/ssl",
read_only=True,
),
Mount(
type=MountType.BIND.value,
type=MountType.BIND,
source=self.sys_config.path_extern_share.as_posix(),
target="/share",
read_only=False,

View File

@ -22,7 +22,6 @@ from docker.types.daemon import CancellableStream
import requests
from ..const import (
ATTR_ENABLE_IPV6,
ATTR_REGISTRIES,
DNS_SUFFIX,
DOCKER_NETWORK,
@ -94,16 +93,6 @@ class DockerConfig(FileConfiguration):
"""Initialize the JSON configuration."""
super().__init__(FILE_HASSIO_DOCKER, SCHEMA_DOCKER_CONFIG)
@property
def enable_ipv6(self) -> bool | None:
"""Return IPv6 configuration for docker network."""
return self._data.get(ATTR_ENABLE_IPV6, None)
@enable_ipv6.setter
def enable_ipv6(self, value: bool | None) -> None:
"""Set IPv6 configuration for docker network."""
self._data[ATTR_ENABLE_IPV6] = value
@property
def registries(self) -> dict[str, Any]:
"""Return credentials for docker registries."""
@ -135,11 +124,9 @@ class DockerAPI:
timeout=900,
),
)
self._network = DockerNetwork(self._docker)
self._info = DockerInfo.new(self.docker.info())
await self.config.read_data()
self._network = await DockerNetwork(self.docker).post_init(
self.config.enable_ipv6
)
return self
@property
@ -294,8 +281,8 @@ class DockerAPI:
def run_command(
self,
image: str,
version: str = "latest",
command: str | list[str] | None = None,
tag: str = "latest",
command: str | None = None,
**kwargs: Any,
) -> CommandReturn:
"""Create a temporary container and run command.
@ -305,15 +292,12 @@ class DockerAPI:
stdout = kwargs.get("stdout", True)
stderr = kwargs.get("stderr", True)
image_with_tag = f"{image}:{version}"
_LOGGER.info("Runing command '%s' on %s", command, image_with_tag)
_LOGGER.info("Runing command '%s' on %s", command, image)
container = None
try:
container = self.docker.containers.run(
image_with_tag,
f"{image}:{tag}",
command=command,
detach=True,
network=self.network.name,
use_config_proxy=False,
**kwargs,
@ -330,9 +314,9 @@ class DockerAPI:
# cleanup container
if container:
with suppress(docker_errors.DockerException, requests.RequestException):
container.remove(force=True, v=True)
container.remove(force=True)
return CommandReturn(result["StatusCode"], output)
return CommandReturn(result.get("StatusCode"), output)
def repair(self) -> None:
"""Repair local docker overlayfs2 issues."""
@ -445,7 +429,7 @@ class DockerAPI:
if remove_container:
with suppress(DockerException, requests.RequestException):
_LOGGER.info("Cleaning %s application", name)
docker_container.remove(force=True, v=True)
docker_container.remove(force=True)
def start_container(self, name: str) -> None:
"""Start Docker container."""

View File

@ -1,54 +1,17 @@
"""Internal network manager for Supervisor."""
import asyncio
from contextlib import suppress
from ipaddress import IPv4Address
import logging
from typing import Self
import docker
import requests
from ..const import (
ATTR_AUDIO,
ATTR_CLI,
ATTR_DNS,
ATTR_ENABLE_IPV6,
ATTR_OBSERVER,
ATTR_SUPERVISOR,
DOCKER_IPV4_NETWORK_MASK,
DOCKER_IPV4_NETWORK_RANGE,
DOCKER_IPV6_NETWORK_MASK,
DOCKER_NETWORK,
DOCKER_NETWORK_DRIVER,
DOCKER_PREFIX,
OBSERVER_DOCKER_NAME,
SUPERVISOR_DOCKER_NAME,
)
from ..const import DOCKER_NETWORK, DOCKER_NETWORK_MASK, DOCKER_NETWORK_RANGE
from ..exceptions import DockerError
_LOGGER: logging.Logger = logging.getLogger(__name__)
DOCKER_ENABLEIPV6 = "EnableIPv6"
DOCKER_NETWORK_PARAMS = {
"name": DOCKER_NETWORK,
"driver": DOCKER_NETWORK_DRIVER,
"ipam": docker.types.IPAMConfig(
pool_configs=[
docker.types.IPAMPool(subnet=str(DOCKER_IPV6_NETWORK_MASK)),
docker.types.IPAMPool(
subnet=str(DOCKER_IPV4_NETWORK_MASK),
gateway=str(DOCKER_IPV4_NETWORK_MASK[1]),
iprange=str(DOCKER_IPV4_NETWORK_RANGE),
),
]
),
ATTR_ENABLE_IPV6: True,
"options": {"com.docker.network.bridge.name": DOCKER_NETWORK},
}
DOCKER_ENABLE_IPV6_DEFAULT = True
class DockerNetwork:
"""Internal Supervisor Network.
@ -59,14 +22,7 @@ class DockerNetwork:
def __init__(self, docker_client: docker.DockerClient):
"""Initialize internal Supervisor network."""
self.docker: docker.DockerClient = docker_client
self._network: docker.models.networks.Network
async def post_init(self, enable_ipv6: bool | None = None) -> Self:
"""Post init actions that must be done in event loop."""
self._network = await asyncio.get_running_loop().run_in_executor(
None, self._get_network, enable_ipv6
)
return self
self._network: docker.models.networks.Network = self._get_network()
@property
def name(self) -> str:
@ -86,112 +42,55 @@ class DockerNetwork:
@property
def gateway(self) -> IPv4Address:
"""Return gateway of the network."""
return DOCKER_IPV4_NETWORK_MASK[1]
return DOCKER_NETWORK_MASK[1]
@property
def supervisor(self) -> IPv4Address:
"""Return supervisor of the network."""
return DOCKER_IPV4_NETWORK_MASK[2]
return DOCKER_NETWORK_MASK[2]
@property
def dns(self) -> IPv4Address:
"""Return dns of the network."""
return DOCKER_IPV4_NETWORK_MASK[3]
return DOCKER_NETWORK_MASK[3]
@property
def audio(self) -> IPv4Address:
"""Return audio of the network."""
return DOCKER_IPV4_NETWORK_MASK[4]
return DOCKER_NETWORK_MASK[4]
@property
def cli(self) -> IPv4Address:
"""Return cli of the network."""
return DOCKER_IPV4_NETWORK_MASK[5]
return DOCKER_NETWORK_MASK[5]
@property
def observer(self) -> IPv4Address:
"""Return observer of the network."""
return DOCKER_IPV4_NETWORK_MASK[6]
return DOCKER_NETWORK_MASK[6]
def _get_network(
self, enable_ipv6: bool | None = None
) -> docker.models.networks.Network:
def _get_network(self) -> docker.models.networks.Network:
"""Get supervisor network."""
try:
if network := self.docker.networks.get(DOCKER_NETWORK):
current_ipv6 = network.attrs.get(DOCKER_ENABLEIPV6, False)
# If the network exists and we don't have an explicit setting,
# simply stick with what we have.
if enable_ipv6 is None or current_ipv6 == enable_ipv6:
return network
# We have an explicit setting which differs from the current state.
_LOGGER.info(
"Migrating Supervisor network to %s",
"IPv4/IPv6 Dual-Stack" if enable_ipv6 else "IPv4-Only",
)
if (containers := network.containers) and (
containers_all := all(
container.name in (OBSERVER_DOCKER_NAME, SUPERVISOR_DOCKER_NAME)
for container in containers
)
):
for container in containers:
with suppress(
docker.errors.APIError,
docker.errors.DockerException,
requests.RequestException,
):
network.disconnect(container, force=True)
if not containers or containers_all:
try:
network.remove()
except docker.errors.APIError:
_LOGGER.warning("Failed to remove existing Supervisor network")
return network
else:
_LOGGER.warning(
"System appears to be running, "
"not applying Supervisor network change. "
"Reboot your system to apply the change."
)
return network
return self.docker.networks.get(DOCKER_NETWORK)
except docker.errors.NotFound:
_LOGGER.info("Can't find Supervisor network, creating a new network")
network_params = DOCKER_NETWORK_PARAMS.copy()
network_params[ATTR_ENABLE_IPV6] = (
DOCKER_ENABLE_IPV6_DEFAULT if enable_ipv6 is None else enable_ipv6
ipam_pool = docker.types.IPAMPool(
subnet=str(DOCKER_NETWORK_MASK),
gateway=str(self.gateway),
iprange=str(DOCKER_NETWORK_RANGE),
)
try:
self._network = self.docker.networks.create(**network_params) # type: ignore
except docker.errors.APIError as err:
raise DockerError(
f"Can't create Supervisor network: {err}", _LOGGER.error
) from err
ipam_config = docker.types.IPAMConfig(pool_configs=[ipam_pool])
with suppress(DockerError):
self.attach_container_by_name(
SUPERVISOR_DOCKER_NAME, [ATTR_SUPERVISOR], self.supervisor
)
with suppress(DockerError):
self.attach_container_by_name(
OBSERVER_DOCKER_NAME, [ATTR_OBSERVER], self.observer
)
for name, ip in (
(ATTR_CLI, self.cli),
(ATTR_DNS, self.dns),
(ATTR_AUDIO, self.audio),
):
with suppress(DockerError):
self.attach_container_by_name(f"{DOCKER_PREFIX}_{name}", [name], ip)
return self._network
return self.docker.networks.create(
DOCKER_NETWORK,
driver="bridge",
ipam=ipam_config,
enable_ipv6=False,
options={"com.docker.network.bridge.name": DOCKER_NETWORK},
)
def attach_container(
self,
@ -203,6 +102,8 @@ class DockerNetwork:
Need run inside executor.
"""
ipv4_address = str(ipv4) if ipv4 else None
# Reload Network information
with suppress(docker.errors.DockerException, requests.RequestException):
self.network.reload()
@ -215,43 +116,12 @@ class DockerNetwork:
# Attach Network
try:
self.network.connect(
container, aliases=alias, ipv4_address=str(ipv4) if ipv4 else None
)
except (
docker.errors.NotFound,
docker.errors.APIError,
docker.errors.DockerException,
requests.RequestException,
) as err:
self.network.connect(container, aliases=alias, ipv4_address=ipv4_address)
except docker.errors.APIError as err:
raise DockerError(
f"Can't connect {container.name} to Supervisor network: {err}",
_LOGGER.error,
f"Can't link container to hassio-net: {err}", _LOGGER.error
) from err
def attach_container_by_name(
self,
name: str,
alias: list[str] | None = None,
ipv4: IPv4Address | None = None,
) -> None:
"""Attach container to Supervisor network.
Need run inside executor.
"""
try:
container = self.docker.containers.get(name)
except (
docker.errors.NotFound,
docker.errors.APIError,
docker.errors.DockerException,
requests.RequestException,
) as err:
raise DockerError(f"Can't find {name}: {err}", _LOGGER.error) from err
if container.id not in self.containers:
self.attach_container(container, alias, ipv4)
def detach_default_bridge(
self, container: docker.models.containers.Container
) -> None:
@ -260,33 +130,25 @@ class DockerNetwork:
Need run inside executor.
"""
try:
default_network = self.docker.networks.get(DOCKER_NETWORK_DRIVER)
default_network = self.docker.networks.get("bridge")
default_network.disconnect(container)
except docker.errors.NotFound:
pass
except (
docker.errors.APIError,
docker.errors.DockerException,
requests.RequestException,
) as err:
return
except docker.errors.APIError as err:
raise DockerError(
f"Can't disconnect {container.name} from default network: {err}",
_LOGGER.warning,
f"Can't disconnect container from default: {err}", _LOGGER.warning
) from err
def stale_cleanup(self, name: str) -> None:
"""Force remove a container from Network.
def stale_cleanup(self, container_name: str):
"""Remove force a container from Network.
Fix: https://github.com/moby/moby/issues/23302
"""
try:
self.network.disconnect(name, force=True)
except (
docker.errors.APIError,
docker.errors.DockerException,
requests.RequestException,
) as err:
raise DockerError(
f"Can't disconnect {name} from Supervisor network: {err}",
_LOGGER.warning,
) from err
self.network.disconnect(container_name, force=True)
except docker.errors.NotFound:
pass
except (docker.errors.DockerException, requests.RequestException) as err:
raise DockerError() from err

View File

@ -2,7 +2,7 @@
import logging
from ..const import DOCKER_IPV4_NETWORK_MASK, OBSERVER_DOCKER_NAME
from ..const import DOCKER_NETWORK_MASK
from ..coresys import CoreSysAttributes
from ..exceptions import DockerJobError
from ..jobs.const import JobExecutionLimit
@ -12,6 +12,7 @@ from .interface import DockerInterface
_LOGGER: logging.Logger = logging.getLogger(__name__)
OBSERVER_DOCKER_NAME: str = "hassio_observer"
ENV_NETWORK_MASK: str = "NETWORK_MASK"
@ -48,7 +49,7 @@ class DockerObserver(DockerInterface, CoreSysAttributes):
environment={
ENV_TIME: self.sys_timezone,
ENV_TOKEN: self.sys_plugins.observer.supervisor_token,
ENV_NETWORK_MASK: DOCKER_IPV4_NETWORK_MASK,
ENV_NETWORK_MASK: DOCKER_NETWORK_MASK,
},
mounts=[MOUNT_DOCKER],
ports={"80/tcp": 4357},

View File

@ -87,19 +87,19 @@ class HomeAssistantCore(JobGroup):
try:
# Evaluate Version if we lost this information
if self.sys_homeassistant.version:
version = self.sys_homeassistant.version
else:
if not self.sys_homeassistant.version:
self.sys_homeassistant.version = (
version
) = await self.instance.get_latest_version()
await self.instance.get_latest_version()
)
await self.instance.attach(version=version, skip_state_event_if_down=True)
await self.instance.attach(
version=self.sys_homeassistant.version, skip_state_event_if_down=True
)
# Ensure we are using correct image for this system (unless user has overridden it)
if not self.sys_homeassistant.override_image:
await self.instance.check_image(
version, self.sys_homeassistant.default_image
self.sys_homeassistant.version, self.sys_homeassistant.default_image
)
self.sys_homeassistant.set_image(self.sys_homeassistant.default_image)
except DockerError:
@ -108,7 +108,7 @@ class HomeAssistantCore(JobGroup):
)
await self.install_landingpage()
else:
self.sys_homeassistant.version = self.instance.version or version
self.sys_homeassistant.version = self.instance.version
self.sys_homeassistant.set_image(self.instance.image)
await self.sys_homeassistant.save_data()
@ -182,13 +182,12 @@ class HomeAssistantCore(JobGroup):
if not self.sys_homeassistant.latest_version:
await self.sys_updater.reload()
if to_version := self.sys_homeassistant.latest_version:
if self.sys_homeassistant.latest_version:
try:
await self.instance.update(
to_version,
self.sys_homeassistant.latest_version,
image=self.sys_updater.image_homeassistant,
)
self.sys_homeassistant.version = self.instance.version or to_version
break
except (DockerError, JobException):
pass
@ -199,6 +198,7 @@ class HomeAssistantCore(JobGroup):
await asyncio.sleep(30)
_LOGGER.info("Home Assistant docker now installed")
self.sys_homeassistant.version = self.instance.version
self.sys_homeassistant.set_image(self.sys_updater.image_homeassistant)
await self.sys_homeassistant.save_data()
@ -231,8 +231,8 @@ class HomeAssistantCore(JobGroup):
backup: bool | None = False,
) -> None:
"""Update HomeAssistant version."""
to_version = version or self.sys_homeassistant.latest_version
if not to_version:
version = version or self.sys_homeassistant.latest_version
if not version:
raise HomeAssistantUpdateError(
"Cannot determine latest version of Home Assistant for update",
_LOGGER.error,
@ -243,9 +243,9 @@ class HomeAssistantCore(JobGroup):
running = await self.instance.is_running()
exists = await self.instance.exists()
if exists and to_version == self.instance.version:
if exists and version == self.instance.version:
raise HomeAssistantUpdateError(
f"Version {to_version!s} is already installed", _LOGGER.warning
f"Version {version!s} is already installed", _LOGGER.warning
)
if backup:
@ -268,7 +268,7 @@ class HomeAssistantCore(JobGroup):
"Updating Home Assistant image failed", _LOGGER.warning
) from err
self.sys_homeassistant.version = self.instance.version or to_version
self.sys_homeassistant.version = self.instance.version
self.sys_homeassistant.set_image(self.sys_updater.image_homeassistant)
if running:
@ -282,7 +282,7 @@ class HomeAssistantCore(JobGroup):
# Update Home Assistant
with suppress(HomeAssistantError):
await _update(to_version)
await _update(version)
if not self.error_state and rollback:
try:

View File

@ -35,7 +35,6 @@ from ..const import (
FILE_HASSIO_HOMEASSISTANT,
BusEvent,
IngressSessionDataUser,
IngressSessionDataUserDict,
)
from ..coresys import CoreSys, CoreSysAttributes
from ..exceptions import (
@ -558,11 +557,18 @@ class HomeAssistant(FileConfiguration, CoreSysAttributes):
async def get_users(self) -> list[IngressSessionDataUser]:
"""Get list of all configured users."""
list_of_users: (
list[IngressSessionDataUserDict] | None
list[dict[str, Any]] | None
) = await self.sys_homeassistant.websocket.async_send_command(
{ATTR_TYPE: "config/auth/list"}
)
if list_of_users:
return [IngressSessionDataUser.from_dict(data) for data in list_of_users]
return [
IngressSessionDataUser(
id=data["id"],
username=data.get("username"),
display_name=data.get("name"),
)
for data in list_of_users
]
return []

View File

@ -2,7 +2,6 @@
from dataclasses import dataclass
from ipaddress import IPv4Address, IPv4Interface, IPv6Address, IPv6Interface
import logging
import socket
from ..dbus.const import (
@ -24,8 +23,6 @@ from .const import (
WifiMode,
)
_LOGGER: logging.Logger = logging.getLogger(__name__)
@dataclass(slots=True)
class AccessPoint:
@ -82,7 +79,7 @@ class VlanConfig:
"""Represent a vlan configuration."""
id: int
interface: str | None
interface: str
@dataclass(slots=True)
@ -111,10 +108,7 @@ class Interface:
if inet.settings.match and inet.settings.match.path:
return inet.settings.match.path == [self.path]
return (
inet.settings.connection is not None
and inet.settings.connection.interface_name == self.name
)
return inet.settings.connection.interface_name == self.name
@staticmethod
def from_dbus_interface(inet: NetworkInterface) -> "Interface":
@ -166,23 +160,23 @@ class Interface:
ipv6_setting = Ip6Setting(InterfaceMethod.DISABLED, [], None, [])
ipv4_ready = (
inet.connection is not None
bool(inet.connection)
and ConnectionStateFlags.IP4_READY in inet.connection.state_flags
)
ipv6_ready = (
inet.connection is not None
bool(inet.connection)
and ConnectionStateFlags.IP6_READY in inet.connection.state_flags
)
return Interface(
name=inet.interface_name,
mac=inet.hw_address,
path=inet.path,
enabled=inet.settings is not None,
connected=Interface._map_nm_connected(inet.connection),
primary=inet.primary,
type=Interface._map_nm_type(inet.type),
ipv4=IpConfig(
inet.name,
inet.hw_address,
inet.path,
inet.settings is not None,
Interface._map_nm_connected(inet.connection),
inet.primary,
Interface._map_nm_type(inet.type),
IpConfig(
address=inet.connection.ipv4.address
if inet.connection.ipv4.address
else [],
@ -194,8 +188,8 @@ class Interface:
)
if inet.connection and inet.connection.ipv4
else IpConfig([], None, [], ipv4_ready),
ipv4setting=ipv4_setting,
ipv6=IpConfig(
ipv4_setting,
IpConfig(
address=inet.connection.ipv6.address
if inet.connection.ipv6.address
else [],
@ -207,28 +201,30 @@ class Interface:
)
if inet.connection and inet.connection.ipv6
else IpConfig([], None, [], ipv6_ready),
ipv6setting=ipv6_setting,
wifi=Interface._map_nm_wifi(inet),
vlan=Interface._map_nm_vlan(inet),
ipv6_setting,
Interface._map_nm_wifi(inet),
Interface._map_nm_vlan(inet),
)
@staticmethod
def _map_nm_method(method: str | None) -> InterfaceMethod:
def _map_nm_method(method: str) -> InterfaceMethod:
"""Map IP interface method."""
match method:
case NMInterfaceMethod.AUTO.value:
return InterfaceMethod.AUTO
case NMInterfaceMethod.MANUAL:
return InterfaceMethod.STATIC
return InterfaceMethod.DISABLED
mapping = {
NMInterfaceMethod.AUTO: InterfaceMethod.AUTO,
NMInterfaceMethod.DISABLED: InterfaceMethod.DISABLED,
NMInterfaceMethod.MANUAL: InterfaceMethod.STATIC,
NMInterfaceMethod.LINK_LOCAL: InterfaceMethod.DISABLED,
}
return mapping.get(method, InterfaceMethod.DISABLED)
@staticmethod
def _map_nm_addr_gen_mode(addr_gen_mode: int) -> InterfaceAddrGenMode:
"""Map IPv6 interface addr_gen_mode."""
mapping = {
NMInterfaceAddrGenMode.EUI64.value: InterfaceAddrGenMode.EUI64,
NMInterfaceAddrGenMode.STABLE_PRIVACY.value: InterfaceAddrGenMode.STABLE_PRIVACY,
NMInterfaceAddrGenMode.DEFAULT_OR_EUI64.value: InterfaceAddrGenMode.DEFAULT_OR_EUI64,
NMInterfaceAddrGenMode.EUI64: InterfaceAddrGenMode.EUI64,
NMInterfaceAddrGenMode.STABLE_PRIVACY: InterfaceAddrGenMode.STABLE_PRIVACY,
NMInterfaceAddrGenMode.DEFAULT_OR_EUI64: InterfaceAddrGenMode.DEFAULT_OR_EUI64,
}
return mapping.get(addr_gen_mode, InterfaceAddrGenMode.DEFAULT)
@ -237,9 +233,9 @@ class Interface:
def _map_nm_ip6_privacy(ip6_privacy: int) -> InterfaceIp6Privacy:
"""Map IPv6 interface ip6_privacy."""
mapping = {
NMInterfaceIp6Privacy.DISABLED.value: InterfaceIp6Privacy.DISABLED,
NMInterfaceIp6Privacy.ENABLED_PREFER_PUBLIC.value: InterfaceIp6Privacy.ENABLED_PREFER_PUBLIC,
NMInterfaceIp6Privacy.ENABLED.value: InterfaceIp6Privacy.ENABLED,
NMInterfaceIp6Privacy.DISABLED: InterfaceIp6Privacy.DISABLED,
NMInterfaceIp6Privacy.ENABLED_PREFER_PUBLIC: InterfaceIp6Privacy.ENABLED_PREFER_PUBLIC,
NMInterfaceIp6Privacy.ENABLED: InterfaceIp6Privacy.ENABLED,
}
return mapping.get(ip6_privacy, InterfaceIp6Privacy.DEFAULT)
@ -257,14 +253,12 @@ class Interface:
@staticmethod
def _map_nm_type(device_type: int) -> InterfaceType:
match device_type:
case DeviceType.ETHERNET.value:
return InterfaceType.ETHERNET
case DeviceType.WIRELESS.value:
return InterfaceType.WIRELESS
case DeviceType.VLAN.value:
return InterfaceType.VLAN
raise ValueError(f"Invalid device type: {device_type}")
mapping = {
DeviceType.ETHERNET: InterfaceType.ETHERNET,
DeviceType.WIRELESS: InterfaceType.WIRELESS,
DeviceType.VLAN: InterfaceType.VLAN,
}
return mapping[device_type]
@staticmethod
def _map_nm_wifi(inet: NetworkInterface) -> WifiConfig | None:
@ -273,22 +267,15 @@ class Interface:
return None
# Authentication and PSK
auth = AuthMethod.OPEN
auth = None
psk = None
if inet.settings.wireless_security:
match inet.settings.wireless_security.key_mgmt:
case "none":
auth = AuthMethod.WEP
case "wpa-psk":
auth = AuthMethod.WPA_PSK
psk = inet.settings.wireless_security.psk
case _:
_LOGGER.warning(
"Auth method %s for network interface %s unsupported, skipping",
inet.settings.wireless_security.key_mgmt,
inet.interface_name,
)
return None
if not inet.settings.wireless_security:
auth = AuthMethod.OPEN
elif inet.settings.wireless_security.key_mgmt == "none":
auth = AuthMethod.WEP
elif inet.settings.wireless_security.key_mgmt == "wpa-psk":
auth = AuthMethod.WPA_PSK
psk = inet.settings.wireless_security.psk
# WifiMode
mode = WifiMode.INFRASTRUCTURE
@ -302,17 +289,17 @@ class Interface:
signal = None
return WifiConfig(
mode=mode,
ssid=inet.settings.wireless.ssid if inet.settings.wireless else "",
auth=auth,
psk=psk,
signal=signal,
mode,
inet.settings.wireless.ssid,
auth,
psk,
signal,
)
@staticmethod
def _map_nm_vlan(inet: NetworkInterface) -> VlanConfig | None:
def _map_nm_vlan(inet: NetworkInterface) -> WifiConfig | None:
"""Create mapping to nm vlan property."""
if inet.type != DeviceType.VLAN or not inet.settings or not inet.settings.vlan:
if inet.type != DeviceType.VLAN or not inet.settings:
return None
return VlanConfig(inet.settings.vlan.id, inet.settings.vlan.parent)

View File

@ -80,7 +80,6 @@ class LogFormat(StrEnum):
JOURNAL = "application/vnd.fdo.journal"
JSON = "application/json"
JSON_SEQ = "application/json-seq"
TEXT = "text/plain"

View File

@ -2,7 +2,7 @@
from __future__ import annotations
from collections.abc import AsyncGenerator, Mapping
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
import json
import logging
@ -25,7 +25,6 @@ from ..exceptions import (
HostServiceError,
)
from ..utils.json import read_json_file
from ..utils.systemd_journal import journal_boots_reader
from .const import PARAM_BOOT_ID, PARAM_SYSLOG_IDENTIFIER, LogFormat
_LOGGER: logging.Logger = logging.getLogger(__name__)
@ -109,8 +108,12 @@ class LogsControl(CoreSysAttributes):
return boot_ids[offset]
async def _get_boot_ids_legacy(self) -> list[str]:
"""Get boots IDs using suboptimal method where /boots is not available."""
async def get_boot_ids(self) -> list[str]:
"""Get boot IDs from oldest to newest."""
if self._boot_ids:
# Doesn't change without a reboot, no reason to query again once cached
return self._boot_ids
try:
async with self.journald_logs(
params=BOOT_IDS_QUERY,
@ -139,51 +142,13 @@ class LogsControl(CoreSysAttributes):
_LOGGER.error,
) from err
_boot_ids = []
self._boot_ids = []
for entry in text.split("\n"):
if entry and (boot_id := json.loads(entry)[PARAM_BOOT_ID]) not in _boot_ids:
_boot_ids.append(boot_id)
return _boot_ids
async def _get_boot_ids_native(self):
"""Get boot IDs using /boots endpoint."""
try:
async with self.journald_logs(
path="/boots",
accept=LogFormat.JSON_SEQ,
timeout=ClientTimeout(total=20),
) as resp:
if resp.status != 200:
raise HostLogError(
f"Got HTTP {resp.status} from /boots.",
_LOGGER.debug,
)
# Don't rely solely on the order of boots in the response,
# sort the boots by index returned in the response.
boot_id_tuples = [boot async for boot in journal_boots_reader(resp)]
return [
boot_id for _, boot_id in sorted(boot_id_tuples, key=lambda x: x[0])
]
except (ClientError, TimeoutError) as err:
raise HostLogError(
"Could not get a list of boot IDs from systemd-journal-gatewayd",
_LOGGER.error,
) from err
async def get_boot_ids(self) -> list[str]:
"""Get boot IDs from oldest to newest."""
if self._boot_ids:
# Doesn't change without a reboot, no reason to query again once cached
return self._boot_ids
try:
self._boot_ids = await self._get_boot_ids_native()
except HostLogError:
_LOGGER.info(
"Could not get /boots from systemd-journal-gatewayd, using fallback."
)
self._boot_ids = await self._get_boot_ids_legacy()
if (
entry
and (boot_id := json.loads(entry)[PARAM_BOOT_ID]) not in self._boot_ids
):
self._boot_ids.append(boot_id)
return self._boot_ids
@ -205,7 +170,7 @@ class LogsControl(CoreSysAttributes):
async def journald_logs(
self,
path: str = "/entries",
params: Mapping[str, str | list[str]] | None = None,
params: dict[str, str | list[str]] | None = None,
range_header: str | None = None,
accept: LogFormat = LogFormat.TEXT,
timeout: ClientTimeout | None = None,
@ -226,7 +191,7 @@ class LogsControl(CoreSysAttributes):
base_url = "http://localhost/"
connector = UnixConnector(path=str(SYSTEMD_JOURNAL_GATEWAYD_SOCKET))
async with ClientSession(base_url=base_url, connector=connector) as session:
headers = {ACCEPT: accept.value}
headers = {ACCEPT: accept}
if range_header:
if range_header.endswith(":"):
# Make sure that num_entries is always set - before Systemd v256 it was

View File

@ -8,11 +8,11 @@ from typing import Any
from ..const import ATTR_HOST_INTERNET
from ..coresys import CoreSys, CoreSysAttributes
from ..dbus.const import (
DBUS_ATTR_CONFIGURATION,
DBUS_ATTR_CONNECTION_ENABLED,
DBUS_ATTR_CONNECTIVITY,
DBUS_IFACE_DNS,
DBUS_ATTR_PRIMARY_CONNECTION,
DBUS_IFACE_NM,
DBUS_OBJECT_BASE,
DBUS_SIGNAL_NM_CONNECTION_ACTIVE_CHANGED,
ConnectionStateType,
ConnectivityState,
@ -46,8 +46,6 @@ class NetworkManager(CoreSysAttributes):
"""Initialize system center handling."""
self.coresys: CoreSys = coresys
self._connectivity: bool | None = None
# No event need on initial change (NetworkManager initializes with empty list)
self._dns_configuration: list = []
@property
def connectivity(self) -> bool | None:
@ -89,7 +87,7 @@ class NetworkManager(CoreSysAttributes):
for config in self.sys_dbus.network.dns.configuration:
if config.vpn or not config.nameservers:
continue
servers.extend([str(ns) for ns in config.nameservers])
servers.extend(config.nameservers)
return list(dict.fromkeys(servers))
@ -140,12 +138,8 @@ class NetworkManager(CoreSysAttributes):
]
)
self.sys_dbus.network.dbus.properties.on(
"properties_changed", self._check_connectivity_changed
)
self.sys_dbus.network.dns.dbus.properties.on(
"properties_changed", self._check_dns_changed
self.sys_dbus.network.dbus.properties.on_properties_changed(
self._check_connectivity_changed
)
async def _check_connectivity_changed(
@ -158,6 +152,15 @@ class NetworkManager(CoreSysAttributes):
connectivity_check: bool | None = changed.get(DBUS_ATTR_CONNECTION_ENABLED)
connectivity: int | None = changed.get(DBUS_ATTR_CONNECTIVITY)
# This potentially updated the DNS configuration. Make sure the DNS plug-in
# picks up the latest settings.
if (
DBUS_ATTR_PRIMARY_CONNECTION in changed
and changed[DBUS_ATTR_PRIMARY_CONNECTION]
and changed[DBUS_ATTR_PRIMARY_CONNECTION] != DBUS_OBJECT_BASE
):
await self.sys_plugins.dns.restart()
if (
connectivity_check is True
or DBUS_ATTR_CONNECTION_ENABLED in invalidated
@ -171,20 +174,6 @@ class NetworkManager(CoreSysAttributes):
elif connectivity is not None:
self.connectivity = connectivity == ConnectivityState.CONNECTIVITY_FULL
async def _check_dns_changed(
self, interface: str, changed: dict[str, Any], invalidated: list[str]
):
"""Check if DNS properties have changed."""
if interface != DBUS_IFACE_DNS:
return
if (
DBUS_ATTR_CONFIGURATION in changed
and self._dns_configuration != changed[DBUS_ATTR_CONFIGURATION]
):
self._dns_configuration = changed[DBUS_ATTR_CONFIGURATION]
self.sys_plugins.dns.notify_locals_changed()
async def update(self, *, force_connectivity_check: bool = False):
"""Update properties over dbus."""
_LOGGER.info("Updating local network information")
@ -207,16 +196,10 @@ class NetworkManager(CoreSysAttributes):
with suppress(NetworkInterfaceNotFound):
inet = self.sys_dbus.network.get(interface.name)
con: NetworkConnection | None = None
con: NetworkConnection = None
# Update exist configuration
if (
inet
and inet.settings
and inet.settings.connection
and interface.equals_dbus_interface(inet)
and interface.enabled
):
if inet and interface.equals_dbus_interface(inet) and interface.enabled:
_LOGGER.debug("Updating existing configuration for %s", interface.name)
settings = get_connection_from_interface(
interface,
@ -227,12 +210,12 @@ class NetworkManager(CoreSysAttributes):
try:
await inet.settings.update(settings)
con = activated = await self.sys_dbus.network.activate_connection(
con = await self.sys_dbus.network.activate_connection(
inet.settings.object_path, inet.object_path
)
_LOGGER.debug(
"activate_connection returns %s",
activated.object_path,
con.object_path,
)
except DBusError as err:
raise HostNetworkError(
@ -252,16 +235,12 @@ class NetworkManager(CoreSysAttributes):
settings = get_connection_from_interface(interface, self.sys_dbus.network)
try:
(
settings,
activated,
) = await self.sys_dbus.network.add_and_activate_connection(
settings, con = await self.sys_dbus.network.add_and_activate_connection(
settings, inet.object_path
)
con = activated
_LOGGER.debug(
"add_and_activate_connection returns %s",
activated.object_path,
con.object_path,
)
except DBusError as err:
raise HostNetworkError(
@ -297,7 +276,7 @@ class NetworkManager(CoreSysAttributes):
)
if con:
async with con.connected_dbus.signal(
async with con.dbus.signal(
DBUS_SIGNAL_NM_CONNECTION_ACTIVE_CHANGED
) as signal:
# From this point we monitor signals. However, it might be that
@ -323,7 +302,7 @@ class NetworkManager(CoreSysAttributes):
"""Scan on Interface for AccessPoint."""
inet = self.sys_dbus.network.get(interface.name)
if inet.type != DeviceType.WIRELESS or not inet.wireless:
if inet.type != DeviceType.WIRELESS:
raise HostNotSupportedError(
f"Can only scan with wireless card - {interface.name}", _LOGGER.error
)

View File

@ -12,7 +12,6 @@ from .const import (
ATTR_SESSION_DATA,
FILE_HASSIO_INGRESS,
IngressSessionData,
IngressSessionDataDict,
)
from .coresys import CoreSys, CoreSysAttributes
from .utils import check_port
@ -36,7 +35,7 @@ class Ingress(FileConfiguration, CoreSysAttributes):
"""Return addon they have this ingress token."""
if token not in self.tokens:
return None
return self.sys_addons.get_local_only(self.tokens[token])
return self.sys_addons.get(self.tokens[token], local_only=True)
def get_session_data(self, session_id: str) -> IngressSessionData | None:
"""Return complementary data of current session or None."""
@ -50,7 +49,7 @@ class Ingress(FileConfiguration, CoreSysAttributes):
return self._data[ATTR_SESSION]
@property
def sessions_data(self) -> dict[str, IngressSessionDataDict]:
def sessions_data(self) -> dict[str, dict[str, str | None]]:
"""Return sessions_data."""
return self._data[ATTR_SESSION_DATA]
@ -90,7 +89,7 @@ class Ingress(FileConfiguration, CoreSysAttributes):
now = utcnow()
sessions = {}
sessions_data: dict[str, IngressSessionDataDict] = {}
sessions_data: dict[str, dict[str, str | None]] = {}
for session, valid in self.sessions.items():
# check if timestamp valid, to avoid crash on malformed timestamp
try:
@ -119,8 +118,7 @@ class Ingress(FileConfiguration, CoreSysAttributes):
# Read all ingress token and build a map
for addon in self.addons:
if addon.ingress_token:
self.tokens[addon.ingress_token] = addon.slug
self.tokens[addon.ingress_token] = addon.slug
def create_session(self, data: IngressSessionData | None = None) -> str:
"""Create new session."""
@ -143,7 +141,7 @@ class Ingress(FileConfiguration, CoreSysAttributes):
try:
valid_until = utc_from_timestamp(self.sessions[session])
except OverflowError:
self.sessions[session] = (utcnow() + timedelta(minutes=15)).timestamp()
self.sessions[session] = utcnow() + timedelta(minutes=15)
return True
# Is still valid?

View File

@ -1,13 +1,13 @@
"""Supervisor job manager."""
import asyncio
from collections.abc import Callable, Coroutine, Generator
from contextlib import contextmanager, suppress
from collections.abc import Awaitable, Callable
from contextlib import contextmanager
from contextvars import Context, ContextVar, Token
from dataclasses import dataclass
from datetime import datetime
import logging
from typing import Any, Self
from typing import Any
from uuid import uuid4
from attrs import Attribute, define, field
@ -27,7 +27,7 @@ from .validate import SCHEMA_JOBS_CONFIG
# When a new asyncio task is started the current context is copied over.
# Modifications to it in one task are not visible to others though.
# This allows us to track what job is currently in progress in each task.
_CURRENT_JOB: ContextVar[str | None] = ContextVar("current_job", default=None)
_CURRENT_JOB: ContextVar[str] = ContextVar("current_job")
_LOGGER: logging.Logger = logging.getLogger(__name__)
@ -75,7 +75,7 @@ class SupervisorJobError:
message: str = "Unknown error, see supervisor logs"
stage: str | None = None
def as_dict(self) -> dict[str, str | None]:
def as_dict(self) -> dict[str, str]:
"""Return dictionary representation."""
return {
"type": self.type_.__name__,
@ -101,7 +101,9 @@ class SupervisorJob:
stage: str | None = field(
default=None, validator=[_invalid_if_done], on_setattr=_on_change
)
parent_id: str | None = field(factory=_CURRENT_JOB.get, on_setattr=frozen)
parent_id: str | None = field(
factory=lambda: _CURRENT_JOB.get(None), on_setattr=frozen
)
done: bool | None = field(init=False, default=None, on_setattr=_on_change)
on_change: Callable[["SupervisorJob", Attribute, Any], None] | None = field(
default=None, on_setattr=frozen
@ -135,7 +137,7 @@ class SupervisorJob:
self.errors += [new_error]
@contextmanager
def start(self) -> Generator[Self]:
def start(self):
"""Start the job in the current task.
This can only be called if the parent ID matches the job running in the current task.
@ -144,11 +146,11 @@ class SupervisorJob:
"""
if self.done is not None:
raise JobStartException("Job has already been started")
if _CURRENT_JOB.get() != self.parent_id:
if _CURRENT_JOB.get(None) != self.parent_id:
raise JobStartException("Job has a different parent from current job")
self.done = False
token: Token[str | None] | None = None
token: Token[str] | None = None
try:
token = _CURRENT_JOB.set(self.uuid)
yield self
@ -191,15 +193,17 @@ class JobManager(FileConfiguration, CoreSysAttributes):
Must be called from within a job. Raises RuntimeError if there is no current job.
"""
if job_id := _CURRENT_JOB.get():
with suppress(JobNotFound):
return self.get_job(job_id)
raise RuntimeError("No job for the current asyncio task!", _LOGGER.critical)
try:
return self.get_job(_CURRENT_JOB.get())
except (LookupError, JobNotFound):
raise RuntimeError(
"No job for the current asyncio task!", _LOGGER.critical
) from None
@property
def is_job(self) -> bool:
"""Return true if there is an active job for the current asyncio task."""
return _CURRENT_JOB.get() is not None
return bool(_CURRENT_JOB.get(None))
def _notify_on_job_change(
self, job: SupervisorJob, attribute: Attribute, value: Any
@ -261,7 +265,7 @@ class JobManager(FileConfiguration, CoreSysAttributes):
def schedule_job(
self,
job_method: Callable[..., Coroutine],
job_method: Callable[..., Awaitable[Any]],
options: JobSchedulerOptions,
*args,
**kwargs,

View File

@ -34,60 +34,8 @@ class JobCondition(StrEnum):
SUPERVISOR_UPDATED = "supervisor_updated"
class JobConcurrency(StrEnum):
"""Job concurrency control.
Controls how many instances of a job can run simultaneously.
Individual Concurrency (applies to each method separately):
- REJECT: Fail immediately if another instance is already running
- QUEUE: Wait for the current instance to finish, then run
Group Concurrency (applies across all methods on a JobGroup):
- GROUP_REJECT: Fail if ANY job is running on the JobGroup
- GROUP_QUEUE: Wait for ANY running job on the JobGroup to finish
JobGroup Behavior:
- All methods on the same JobGroup instance share a single lock
- Methods can call other methods on the same group without deadlock
- Uses the JobGroup.group_name for coordination
- Requires the class to inherit from JobGroup
"""
REJECT = "reject" # Fail if already running (was ONCE)
QUEUE = "queue" # Wait if already running (was SINGLE_WAIT)
GROUP_REJECT = "group_reject" # Was GROUP_ONCE
GROUP_QUEUE = "group_queue" # Was GROUP_WAIT
class JobThrottle(StrEnum):
"""Job throttling control.
Controls how frequently jobs can be executed.
Individual Throttling (each method has its own throttle state):
- THROTTLE: Skip execution if called within throttle_period
- RATE_LIMIT: Allow up to throttle_max_calls within throttle_period, then fail
Group Throttling (all methods on a JobGroup share throttle state):
- GROUP_THROTTLE: Skip if ANY method was called within throttle_period
- GROUP_RATE_LIMIT: Allow up to throttle_max_calls total across ALL methods
JobGroup Behavior:
- All methods on the same JobGroup instance share throttle counters/timers
- Uses the JobGroup.group_name as the key for tracking state
- If one method is throttled, other methods may also be throttled
- Requires the class to inherit from JobGroup
"""
THROTTLE = "throttle" # Skip if called too frequently
RATE_LIMIT = "rate_limit" # Rate limiting with max calls per period
GROUP_THROTTLE = "group_throttle" # Group version of THROTTLE
GROUP_RATE_LIMIT = "group_rate_limit" # Group version of RATE_LIMIT
class JobExecutionLimit(StrEnum):
"""Job Execution limits - DEPRECATED: Use JobConcurrency and JobThrottle instead."""
"""Job Execution limits."""
ONCE = "once"
SINGLE_WAIT = "single_wait"

View File

@ -1,12 +1,12 @@
"""Job decorator."""
import asyncio
from collections.abc import Awaitable, Callable
from collections.abc import Callable
from contextlib import suppress
from datetime import datetime, timedelta
from functools import wraps
import logging
from typing import Any, cast
from typing import Any
from ..const import CoreState
from ..coresys import CoreSys, CoreSysAttributes
@ -20,7 +20,7 @@ from ..host.const import HostFeature
from ..resolution.const import MINIMUM_FREE_SPACE_THRESHOLD, ContextType, IssueType
from ..utils.sentry import async_capture_exception
from . import SupervisorJob
from .const import JobConcurrency, JobCondition, JobExecutionLimit, JobThrottle
from .const import JobCondition, JobExecutionLimit
from .job_group import JobGroup
_LOGGER: logging.Logger = logging.getLogger(__package__)
@ -36,34 +36,14 @@ class Job(CoreSysAttributes):
conditions: list[JobCondition] | None = None,
cleanup: bool = True,
on_condition: type[JobException] | None = None,
concurrency: JobConcurrency | None = None,
throttle: JobThrottle | None = None,
limit: JobExecutionLimit | None = None,
throttle_period: timedelta
| Callable[[CoreSys, datetime, list[datetime] | None], timedelta]
| None = None,
throttle_max_calls: int | None = None,
internal: bool = False,
# Backward compatibility - DEPRECATED
limit: JobExecutionLimit | None = None,
): # pylint: disable=too-many-positional-arguments
"""Initialize the Job decorator.
Args:
name (str): Unique name for the job. Must not be duplicated.
conditions (list[JobCondition] | None): List of conditions that must be met before the job runs.
cleanup (bool): Whether to clean up the job after execution. Defaults to True. If set to False, the job will remain accessible through the Supervisor API until the next restart.
on_condition (type[JobException] | None): Exception type to raise if a job condition fails. If None, logs the failure.
concurrency (JobConcurrency | None): Concurrency control policy (e.g., reject, queue, group-based).
throttle (JobThrottle | None): Throttling policy (e.g., throttle, rate_limit, group-based).
throttle_period (timedelta | Callable | None): Throttle period as a timedelta or a callable returning a timedelta (for throttled jobs).
throttle_max_calls (int | None): Maximum number of calls allowed within the throttle period (for rate-limited jobs).
internal (bool): Whether the job is internal (not exposed through the Supervisor API). Defaults to False.
limit (JobExecutionLimit | None): DEPRECATED - Use concurrency and throttle instead.
Raises:
RuntimeError: If job name is not unique, or required throttle parameters are missing for the selected throttle policy.
"""
):
"""Initialize the Job class."""
if name in _JOB_NAMES:
raise RuntimeError(f"A job already exists with name {name}!")
@ -72,114 +52,43 @@ class Job(CoreSysAttributes):
self.conditions = conditions
self.cleanup = cleanup
self.on_condition = on_condition
self.limit = limit
self._throttle_period = throttle_period
self._throttle_max_calls = throttle_max_calls
self.throttle_max_calls = throttle_max_calls
self._lock: asyncio.Semaphore | None = None
self._method = None
self._last_call: dict[str | None, datetime] = {}
self._rate_limited_calls: dict[str | None, list[datetime]] | None = None
self._rate_limited_calls: dict[str, list[datetime]] | None = None
self._internal = internal
# Handle backward compatibility with limit parameter
if limit is not None:
if concurrency is not None or throttle is not None:
raise RuntimeError(
f"Job {name} cannot specify both 'limit' (deprecated) and 'concurrency'/'throttle' parameters!"
)
# Map old limit values to new parameters
concurrency, throttle = self._map_limit_to_new_params(limit)
self.concurrency = concurrency
self.throttle = throttle
# Validate Options
self._validate_parameters()
def _map_limit_to_new_params(
self, limit: JobExecutionLimit
) -> tuple[JobConcurrency | None, JobThrottle | None]:
"""Map old limit parameter to new concurrency and throttle parameters."""
mapping = {
JobExecutionLimit.ONCE: (JobConcurrency.REJECT, None),
JobExecutionLimit.SINGLE_WAIT: (JobConcurrency.QUEUE, None),
JobExecutionLimit.THROTTLE: (None, JobThrottle.THROTTLE),
JobExecutionLimit.THROTTLE_WAIT: (
JobConcurrency.QUEUE,
JobThrottle.THROTTLE,
),
JobExecutionLimit.THROTTLE_RATE_LIMIT: (None, JobThrottle.RATE_LIMIT),
JobExecutionLimit.GROUP_ONCE: (JobConcurrency.GROUP_REJECT, None),
JobExecutionLimit.GROUP_WAIT: (JobConcurrency.GROUP_QUEUE, None),
JobExecutionLimit.GROUP_THROTTLE: (None, JobThrottle.GROUP_THROTTLE),
JobExecutionLimit.GROUP_THROTTLE_WAIT: (
# Seems a bit counter intuitive, but GROUP_QUEUE deadlocks
# tests/jobs/test_job_decorator.py::test_execution_limit_group_throttle_wait
# The reason this deadlocks is because when using GROUP_QUEUE and the
# throttle limit is hit, the group lock is trying to be unlocked outside
# of the job context. The current implementation doesn't allow to unlock
# the group lock when the job is not running.
JobConcurrency.QUEUE,
JobThrottle.GROUP_THROTTLE,
),
JobExecutionLimit.GROUP_THROTTLE_RATE_LIMIT: (
None,
JobThrottle.GROUP_RATE_LIMIT,
),
}
return mapping.get(limit, (None, None))
def _validate_parameters(self) -> None:
"""Validate job parameters."""
# Validate throttle parameters
if (
self.throttle
self.limit
in (
JobThrottle.THROTTLE,
JobThrottle.GROUP_THROTTLE,
JobThrottle.RATE_LIMIT,
JobThrottle.GROUP_RATE_LIMIT,
JobExecutionLimit.THROTTLE,
JobExecutionLimit.THROTTLE_WAIT,
JobExecutionLimit.THROTTLE_RATE_LIMIT,
JobExecutionLimit.GROUP_THROTTLE,
JobExecutionLimit.GROUP_THROTTLE_WAIT,
JobExecutionLimit.GROUP_THROTTLE_RATE_LIMIT,
)
and self._throttle_period is None
):
raise RuntimeError(
f"Job {self.name} is using throttle {self.throttle} without a throttle period!"
f"Job {name} is using execution limit {limit} without a throttle period!"
)
if self.throttle in (
JobThrottle.RATE_LIMIT,
JobThrottle.GROUP_RATE_LIMIT,
if self.limit in (
JobExecutionLimit.THROTTLE_RATE_LIMIT,
JobExecutionLimit.GROUP_THROTTLE_RATE_LIMIT,
):
if self._throttle_max_calls is None:
if self.throttle_max_calls is None:
raise RuntimeError(
f"Job {self.name} is using throttle {self.throttle} without throttle max calls!"
f"Job {name} is using execution limit {limit} without throttle max calls!"
)
self._rate_limited_calls = {}
if self.throttle is not None and self.concurrency in (
JobConcurrency.GROUP_REJECT,
JobConcurrency.GROUP_QUEUE,
):
# We cannot release group locks when Job is not running (e.g. throttled)
# which makes these combinations impossible to use currently.
raise RuntimeError(
f"Job {self.name} is using throttling ({self.throttle}) with group concurrency ({self.concurrency}), which is not allowed!"
)
@property
def throttle_max_calls(self) -> int:
"""Return max calls for throttle."""
if self._throttle_max_calls is None:
raise RuntimeError("No throttle max calls set for job!")
return self._throttle_max_calls
@property
def lock(self) -> asyncio.Semaphore:
"""Return lock for limits."""
# asyncio.Semaphore objects must be created in event loop
# Since this is sync code it is not safe to create if missing here
if not self._lock:
raise RuntimeError("Lock has not been created yet!")
return self._lock
def last_call(self, group_name: str | None = None) -> datetime:
"""Return last call datetime."""
return self._last_call.get(group_name, datetime.min)
@ -188,12 +97,12 @@ class Job(CoreSysAttributes):
"""Set last call datetime."""
self._last_call[group_name] = value
def rate_limited_calls(self, group_name: str | None = None) -> list[datetime]:
def rate_limited_calls(
self, group_name: str | None = None
) -> list[datetime] | None:
"""Return rate limited calls if used."""
if self._rate_limited_calls is None:
raise RuntimeError(
"Rate limited calls not available for this throttle type"
)
return None
return self._rate_limited_calls.get(group_name, [])
@ -203,7 +112,7 @@ class Job(CoreSysAttributes):
"""Add a rate limited call to list if used."""
if self._rate_limited_calls is None:
raise RuntimeError(
"Rate limited calls not available for this throttle type"
f"Rate limited calls not available for limit type {self.limit}"
)
if group_name in self._rate_limited_calls:
@ -217,15 +126,15 @@ class Job(CoreSysAttributes):
"""Set rate limited calls if used."""
if self._rate_limited_calls is None:
raise RuntimeError(
"Rate limited calls not available for this throttle type"
f"Rate limited calls not available for limit type {self.limit}"
)
self._rate_limited_calls[group_name] = value
def throttle_period(self, group_name: str | None = None) -> timedelta:
def throttle_period(self, group_name: str | None = None) -> timedelta | None:
"""Return throttle period."""
if self._throttle_period is None:
raise RuntimeError("No throttle period set for Job!")
return None
if isinstance(self._throttle_period, timedelta):
return self._throttle_period
@ -233,7 +142,7 @@ class Job(CoreSysAttributes):
return self._throttle_period(
self.coresys,
self.last_call(group_name),
self.rate_limited_calls(group_name) if self._rate_limited_calls else None,
self.rate_limited_calls(group_name),
)
def _post_init(self, obj: JobGroup | CoreSysAttributes) -> JobGroup | None:
@ -249,31 +158,23 @@ class Job(CoreSysAttributes):
self._lock = asyncio.Semaphore()
# Job groups
job_group: JobGroup | None = None
with suppress(AttributeError):
if obj.acquire and obj.release: # type: ignore
job_group = cast(JobGroup, obj)
try:
is_job_group = obj.acquire and obj.release
except AttributeError:
is_job_group = False
# Check for group-based parameters
if not job_group:
if self.concurrency in (
JobConcurrency.GROUP_REJECT,
JobConcurrency.GROUP_QUEUE,
):
raise RuntimeError(
f"Job {self.name} uses group concurrency ({self.concurrency}) but is not on a JobGroup! "
f"The class must inherit from JobGroup to use GROUP_REJECT or GROUP_QUEUE."
) from None
if self.throttle in (
JobThrottle.GROUP_THROTTLE,
JobThrottle.GROUP_RATE_LIMIT,
):
raise RuntimeError(
f"Job {self.name} uses group throttling ({self.throttle}) but is not on a JobGroup! "
f"The class must inherit from JobGroup to use GROUP_THROTTLE or GROUP_RATE_LIMIT."
) from None
if not is_job_group and self.limit in (
JobExecutionLimit.GROUP_ONCE,
JobExecutionLimit.GROUP_WAIT,
JobExecutionLimit.GROUP_THROTTLE,
JobExecutionLimit.GROUP_THROTTLE_WAIT,
JobExecutionLimit.GROUP_THROTTLE_RATE_LIMIT,
):
raise RuntimeError(
f"Job on {self.name} need to be a JobGroup to use group based limits!"
) from None
return job_group
return obj if is_job_group else None
def _handle_job_condition_exception(self, err: JobConditionException) -> None:
"""Handle a job condition failure."""
@ -283,8 +184,9 @@ class Job(CoreSysAttributes):
return
raise self.on_condition(error_msg, _LOGGER.warning) from None
def __call__(self, method: Callable[..., Awaitable]):
def __call__(self, method):
"""Call the wrapper logic."""
self._method = method
@wraps(method)
async def wrapper(
@ -319,31 +221,87 @@ class Job(CoreSysAttributes):
if self.conditions:
try:
await Job.check_conditions(
self, set(self.conditions), method.__qualname__
self, set(self.conditions), self._method.__qualname__
)
except JobConditionException as err:
return self._handle_job_condition_exception(err)
# Handle execution limits
await self._handle_concurrency_control(job_group, job)
try:
if not await self._handle_throttling(group_name):
self._release_concurrency_control(job_group)
return # Job was throttled, exit early
except Exception:
self._release_concurrency_control(job_group)
raise
# Handle exection limits
if self.limit in (
JobExecutionLimit.SINGLE_WAIT,
JobExecutionLimit.ONCE,
):
await self._acquire_exection_limit()
elif self.limit in (
JobExecutionLimit.GROUP_ONCE,
JobExecutionLimit.GROUP_WAIT,
):
try:
await obj.acquire(
job, self.limit == JobExecutionLimit.GROUP_WAIT
)
except JobGroupExecutionLimitExceeded as err:
if self.on_condition:
raise self.on_condition(str(err)) from err
raise err
elif self.limit in (
JobExecutionLimit.THROTTLE,
JobExecutionLimit.GROUP_THROTTLE,
):
time_since_last_call = datetime.now() - self.last_call(group_name)
if time_since_last_call < self.throttle_period(group_name):
return
elif self.limit in (
JobExecutionLimit.THROTTLE_WAIT,
JobExecutionLimit.GROUP_THROTTLE_WAIT,
):
await self._acquire_exection_limit()
time_since_last_call = datetime.now() - self.last_call(group_name)
if time_since_last_call < self.throttle_period(group_name):
self._release_exception_limits()
return
elif self.limit in (
JobExecutionLimit.THROTTLE_RATE_LIMIT,
JobExecutionLimit.GROUP_THROTTLE_RATE_LIMIT,
):
# Only reprocess array when necessary (at limit)
if (
len(self.rate_limited_calls(group_name))
>= self.throttle_max_calls
):
self.set_rate_limited_calls(
[
call
for call in self.rate_limited_calls(group_name)
if call
> datetime.now() - self.throttle_period(group_name)
],
group_name,
)
if (
len(self.rate_limited_calls(group_name))
>= self.throttle_max_calls
):
on_condition = (
JobException
if self.on_condition is None
else self.on_condition
)
raise on_condition(
f"Rate limit exceeded, more than {self.throttle_max_calls} calls in {self.throttle_period(group_name)}",
)
# Execute Job
with job.start():
try:
self.set_last_call(datetime.now(), group_name)
if self._rate_limited_calls is not None:
if self.rate_limited_calls(group_name) is not None:
self.add_rate_limited_call(
self.last_call(group_name), group_name
)
return await method(obj, *args, **kwargs)
return await self._method(obj, *args, **kwargs)
# If a method has a conditional JobCondition, they must check it in the method
# These should be handled like normal JobConditions as much as possible
@ -358,7 +316,12 @@ class Job(CoreSysAttributes):
await async_capture_exception(err)
raise JobException() from err
finally:
self._release_concurrency_control(job_group)
self._release_exception_limits()
if self.limit in (
JobExecutionLimit.GROUP_ONCE,
JobExecutionLimit.GROUP_WAIT,
):
obj.release()
# Jobs that weren't started are always cleaned up. Also clean up done jobs if required
finally:
@ -500,75 +463,31 @@ class Job(CoreSysAttributes):
f"'{method_name}' blocked from execution, mounting not supported on system"
)
def _release_concurrency_control(self, job_group: JobGroup | None) -> None:
"""Release concurrency control locks."""
if self.concurrency == JobConcurrency.REJECT:
if self.lock.locked():
self.lock.release()
elif self.concurrency == JobConcurrency.QUEUE:
if self.lock.locked():
self.lock.release()
elif self.concurrency in (
JobConcurrency.GROUP_REJECT,
JobConcurrency.GROUP_QUEUE,
async def _acquire_exection_limit(self) -> None:
"""Process exection limits."""
if self.limit not in (
JobExecutionLimit.SINGLE_WAIT,
JobExecutionLimit.ONCE,
JobExecutionLimit.THROTTLE_WAIT,
JobExecutionLimit.GROUP_THROTTLE_WAIT,
):
if job_group and job_group.has_lock:
job_group.release()
return
async def _handle_concurrency_control(
self, job_group: JobGroup | None, job: SupervisorJob
) -> None:
"""Handle concurrency control limits."""
if self.concurrency == JobConcurrency.REJECT:
if self.lock.locked():
on_condition = (
JobException if self.on_condition is None else self.on_condition
)
raise on_condition("Another job is running")
await self.lock.acquire()
elif self.concurrency == JobConcurrency.QUEUE:
await self.lock.acquire()
elif self.concurrency == JobConcurrency.GROUP_REJECT:
try:
await cast(JobGroup, job_group).acquire(job, wait=False)
except JobGroupExecutionLimitExceeded as err:
if self.on_condition:
raise self.on_condition(str(err)) from err
raise err
elif self.concurrency == JobConcurrency.GROUP_QUEUE:
try:
await cast(JobGroup, job_group).acquire(job, wait=True)
except JobGroupExecutionLimitExceeded as err:
if self.on_condition:
raise self.on_condition(str(err)) from err
raise err
if self.limit == JobExecutionLimit.ONCE and self._lock.locked():
on_condition = (
JobException if self.on_condition is None else self.on_condition
)
raise on_condition("Another job is running")
async def _handle_throttling(self, group_name: str | None) -> bool:
"""Handle throttling limits. Returns True if job should continue, False if throttled."""
if self.throttle in (JobThrottle.THROTTLE, JobThrottle.GROUP_THROTTLE):
time_since_last_call = datetime.now() - self.last_call(group_name)
throttle_period = self.throttle_period(group_name)
if time_since_last_call < throttle_period:
# Always return False when throttled (skip execution)
return False
elif self.throttle in (JobThrottle.RATE_LIMIT, JobThrottle.GROUP_RATE_LIMIT):
# Only reprocess array when necessary (at limit)
if len(self.rate_limited_calls(group_name)) >= self.throttle_max_calls:
self.set_rate_limited_calls(
[
call
for call in self.rate_limited_calls(group_name)
if call > datetime.now() - self.throttle_period(group_name)
],
group_name,
)
await self._lock.acquire()
if len(self.rate_limited_calls(group_name)) >= self.throttle_max_calls:
on_condition = (
JobException if self.on_condition is None else self.on_condition
)
raise on_condition(
f"Rate limit exceeded, more than {self.throttle_max_calls} calls in {self.throttle_period(group_name)}",
)
return True
def _release_exception_limits(self) -> None:
"""Release possible exception limits."""
if self.limit not in (
JobExecutionLimit.SINGLE_WAIT,
JobExecutionLimit.ONCE,
JobExecutionLimit.THROTTLE_WAIT,
JobExecutionLimit.GROUP_THROTTLE_WAIT,
):
return
self._lock.release()

View File

@ -41,7 +41,7 @@ class JobGroup(CoreSysAttributes):
def has_lock(self) -> bool:
"""Return true if current task has the lock on this job group."""
return (
self.active_job is not None
self.active_job
and self.sys_jobs.is_job
and self.active_job == self.sys_jobs.current
)

View File

@ -9,7 +9,7 @@ from aiohttp import hdrs
import attr
from sentry_sdk.types import Event, Hint
from ..const import DOCKER_IPV4_NETWORK_MASK, HEADER_TOKEN, HEADER_TOKEN_OLD, CoreState
from ..const import DOCKER_NETWORK_MASK, HEADER_TOKEN, HEADER_TOKEN_OLD, CoreState
from ..coresys import CoreSys
from ..exceptions import AddonConfigurationError
@ -21,7 +21,7 @@ def sanitize_host(host: str) -> str:
try:
# Allow internal URLs
ip = ipaddress.ip_address(host)
if ip in ipaddress.ip_network(DOCKER_IPV4_NETWORK_MASK):
if ip in ipaddress.ip_network(DOCKER_NETWORK_MASK):
return host
except ValueError:
pass

View File

@ -2,10 +2,9 @@
from datetime import datetime, timedelta
import logging
from typing import cast
from ..addons.const import ADDON_UPDATE_CONDITIONS
from ..backups.const import LOCATION_CLOUD_BACKUP, LOCATION_TYPE
from ..backups.const import LOCATION_CLOUD_BACKUP
from ..const import ATTR_TYPE, AddonState
from ..coresys import CoreSysAttributes
from ..exceptions import (
@ -379,8 +378,6 @@ class Tasks(CoreSysAttributes):
]
for backup in old_backups:
try:
await self.sys_backups.remove(
backup, [cast(LOCATION_TYPE, LOCATION_CLOUD_BACKUP)]
)
await self.sys_backups.remove(backup, [LOCATION_CLOUD_BACKUP])
except BackupFileNotFoundError as err:
_LOGGER.debug("Can't remove backup %s: %s", backup.slug, err)

View File

@ -56,7 +56,7 @@ class MountManager(FileConfiguration, CoreSysAttributes):
async def load_config(self) -> Self:
"""Load config in executor."""
await super().load_config()
self._mounts = {
self._mounts: dict[str, Mount] = {
mount[ATTR_NAME]: Mount.from_dict(self.coresys, mount)
for mount in self._data[ATTR_MOUNTS]
}
@ -172,12 +172,12 @@ class MountManager(FileConfiguration, CoreSysAttributes):
errors = await asyncio.gather(*mount_tasks, return_exceptions=True)
for i in range(len(errors)): # pylint: disable=consider-using-enumerate
if not (err := errors[i]):
if not errors[i]:
continue
if mounts[i].failed_issue in self.sys_resolution.issues:
continue
if not isinstance(err, MountError):
await async_capture_exception(err)
if not isinstance(errors[i], MountError):
await async_capture_exception(errors[i])
self.sys_resolution.add_issue(
evolve(mounts[i].failed_issue),
@ -219,7 +219,7 @@ class MountManager(FileConfiguration, CoreSysAttributes):
conditions=[JobCondition.MOUNT_AVAILABLE],
on_condition=MountJobError,
)
async def remove_mount(self, name: str, *, retain_entry: bool = False) -> Mount:
async def remove_mount(self, name: str, *, retain_entry: bool = False) -> None:
"""Remove a mount."""
# Add mount name to job
self.sys_jobs.current.reference = name

View File

@ -2,7 +2,6 @@
from abc import ABC, abstractmethod
import asyncio
from collections.abc import Callable
from functools import cached_property
import logging
from pathlib import Path, PurePath
@ -10,6 +9,14 @@ from pathlib import Path, PurePath
from dbus_fast import Variant
from voluptuous import Coerce
from ..const import (
ATTR_NAME,
ATTR_PASSWORD,
ATTR_PORT,
ATTR_TYPE,
ATTR_USERNAME,
ATTR_VERSION,
)
from ..coresys import CoreSys, CoreSysAttributes
from ..dbus.const import (
DBUS_ATTR_ACTIVE_STATE,
@ -34,13 +41,22 @@ from ..exceptions import (
from ..resolution.const import ContextType, IssueType
from ..resolution.data import Issue
from ..utils.sentry import async_capture_exception
from .const import MountCifsVersion, MountType, MountUsage
from .const import (
ATTR_PATH,
ATTR_READ_ONLY,
ATTR_SERVER,
ATTR_SHARE,
ATTR_USAGE,
MountCifsVersion,
MountType,
MountUsage,
)
from .validate import MountData
_LOGGER: logging.Logger = logging.getLogger(__name__)
COERCE_MOUNT_TYPE: Callable[[str], MountType] = Coerce(MountType)
COERCE_MOUNT_USAGE: Callable[[str], MountUsage] = Coerce(MountUsage)
COERCE_MOUNT_TYPE = Coerce(MountType)
COERCE_MOUNT_USAGE = Coerce(MountUsage)
class Mount(CoreSysAttributes, ABC):
@ -64,7 +80,7 @@ class Mount(CoreSysAttributes, ABC):
if cls not in [Mount, NetworkMount]:
return cls(coresys, data)
type_ = COERCE_MOUNT_TYPE(data["type"])
type_ = COERCE_MOUNT_TYPE(data[ATTR_TYPE])
if type_ == MountType.CIFS:
return CIFSMount(coresys, data)
if type_ == MountType.NFS:
@ -74,33 +90,32 @@ class Mount(CoreSysAttributes, ABC):
def to_dict(self, *, skip_secrets: bool = True) -> MountData:
"""Return dictionary representation."""
return MountData(
name=self.name,
type=self.type,
usage=self.usage and self.usage.value,
read_only=self.read_only,
name=self.name, type=self.type, usage=self.usage, read_only=self.read_only
)
@property
def name(self) -> str:
"""Get name."""
return self._data["name"]
return self._data[ATTR_NAME]
@property
def type(self) -> MountType:
"""Get mount type."""
return COERCE_MOUNT_TYPE(self._data["type"])
return COERCE_MOUNT_TYPE(self._data[ATTR_TYPE])
@property
def usage(self) -> MountUsage | None:
"""Get mount usage."""
if self._data["usage"] is None:
return None
return COERCE_MOUNT_USAGE(self._data["usage"])
return (
COERCE_MOUNT_USAGE(self._data[ATTR_USAGE])
if ATTR_USAGE in self._data
else None
)
@property
def read_only(self) -> bool:
"""Is mount read-only."""
return self._data.get("read_only", False)
return self._data.get(ATTR_READ_ONLY, False)
@property
@abstractmethod
@ -171,20 +186,20 @@ class Mount(CoreSysAttributes, ABC):
async def load(self) -> None:
"""Initialize object."""
# If there's no mount unit, mount it to make one
if not (unit := await self._update_unit()):
if not await self._update_unit():
await self.mount()
return
await self._update_state_await(unit, not_state=UnitActiveState.ACTIVATING)
await self._update_state_await(not_state=UnitActiveState.ACTIVATING)
# If mount is not available, try to reload it
if not await self.is_mounted():
await self.reload()
async def _update_state(self, unit: SystemdUnit) -> None:
async def _update_state(self) -> UnitActiveState | None:
"""Update mount unit state."""
try:
self._state = await unit.get_active_state()
self._state = await self.unit.get_active_state()
except DBusError as err:
await async_capture_exception(err)
raise MountError(
@ -205,10 +220,10 @@ class Mount(CoreSysAttributes, ABC):
async def update(self) -> bool:
"""Update info about mount from dbus. Return true if it is mounted and available."""
if not (unit := await self._update_unit()):
if not await self._update_unit():
return False
await self._update_state(unit)
await self._update_state()
# If active, dismiss corresponding failed mount issue if found
if (
@ -220,14 +235,16 @@ class Mount(CoreSysAttributes, ABC):
async def _update_state_await(
self,
unit: SystemdUnit,
expected_states: list[UnitActiveState] | None = None,
not_state: UnitActiveState = UnitActiveState.ACTIVATING,
) -> None:
"""Update state info about mount from dbus. Wait for one of expected_states to appear or state to change from not_state."""
if not self.unit:
return
try:
async with asyncio.timeout(30), unit.properties_changed() as signal:
await self._update_state(unit)
async with asyncio.timeout(30), self.unit.properties_changed() as signal:
await self._update_state()
while (
expected_states
and self.state not in expected_states
@ -295,8 +312,8 @@ class Mount(CoreSysAttributes, ABC):
f"Could not mount {self.name} due to: {err!s}", _LOGGER.error
) from err
if unit := await self._update_unit():
await self._update_state_await(unit, not_state=UnitActiveState.ACTIVATING)
if await self._update_unit():
await self._update_state_await(not_state=UnitActiveState.ACTIVATING)
if not await self.is_mounted():
raise MountActivationError(
@ -306,17 +323,17 @@ class Mount(CoreSysAttributes, ABC):
async def unmount(self) -> None:
"""Unmount using systemd."""
if not (unit := await self._update_unit()):
if not await self._update_unit():
_LOGGER.info("Mount %s is not mounted, skipping unmount", self.name)
return
await self._update_state(unit)
await self._update_state()
try:
if self.state != UnitActiveState.FAILED:
await self.sys_dbus.systemd.stop_unit(self.unit_name, StopUnitMode.FAIL)
await self._update_state_await(
unit, [UnitActiveState.INACTIVE, UnitActiveState.FAILED]
[UnitActiveState.INACTIVE, UnitActiveState.FAILED]
)
if self.state == UnitActiveState.FAILED:
@ -343,10 +360,8 @@ class Mount(CoreSysAttributes, ABC):
f"Could not reload mount {self.name} due to: {err!s}", _LOGGER.error
) from err
else:
if unit := await self._update_unit():
await self._update_state_await(
unit, not_state=UnitActiveState.ACTIVATING
)
if await self._update_unit():
await self._update_state_await(not_state=UnitActiveState.ACTIVATING)
if not await self.is_mounted():
raise MountActivationError(
@ -366,18 +381,18 @@ class NetworkMount(Mount, ABC):
"""Return dictionary representation."""
out = MountData(server=self.server, **super().to_dict())
if self.port is not None:
out["port"] = self.port
out[ATTR_PORT] = self.port
return out
@property
def server(self) -> str:
"""Get server."""
return self._data["server"]
return self._data[ATTR_SERVER]
@property
def port(self) -> int | None:
"""Get port, returns none if using the protocol default."""
return self._data.get("port")
return self._data.get(ATTR_PORT)
@property
def where(self) -> PurePath:
@ -405,31 +420,31 @@ class CIFSMount(NetworkMount):
def to_dict(self, *, skip_secrets: bool = True) -> MountData:
"""Return dictionary representation."""
out = MountData(share=self.share, **super().to_dict())
if not skip_secrets and self.username is not None and self.password is not None:
out["username"] = self.username
out["password"] = self.password
out["version"] = self.version
if not skip_secrets and self.username is not None:
out[ATTR_USERNAME] = self.username
out[ATTR_PASSWORD] = self.password
out[ATTR_VERSION] = self.version
return out
@property
def share(self) -> str:
"""Get share."""
return self._data["share"]
return self._data[ATTR_SHARE]
@property
def username(self) -> str | None:
"""Get username, returns none if auth is not used."""
return self._data.get("username")
return self._data.get(ATTR_USERNAME)
@property
def password(self) -> str | None:
"""Get password, returns none if auth is not used."""
return self._data.get("password")
return self._data.get(ATTR_PASSWORD)
@property
def version(self) -> str | None:
"""Get cifs version, returns none if using default."""
version = self._data.get("version")
"""Get password, returns none if auth is not used."""
version = self._data.get(ATTR_VERSION)
if version == MountCifsVersion.LEGACY_1_0:
return "1.0"
if version == MountCifsVersion.LEGACY_2_0:
@ -498,7 +513,7 @@ class NFSMount(NetworkMount):
@property
def path(self) -> PurePath:
"""Get path."""
return PurePath(self._data["path"])
return PurePath(self._data[ATTR_PATH])
@property
def what(self) -> str:
@ -528,7 +543,7 @@ class BindMount(Mount):
def create(
coresys: CoreSys,
name: str,
path: PurePath,
path: Path,
usage: MountUsage | None = None,
where: PurePath | None = None,
read_only: bool = False,
@ -553,7 +568,7 @@ class BindMount(Mount):
@property
def path(self) -> PurePath:
"""Get path."""
return PurePath(self._data["path"])
return PurePath(self._data[ATTR_PATH])
@property
def what(self) -> str:

View File

@ -103,7 +103,7 @@ class MountData(TypedDict):
name: str
type: str
read_only: bool
usage: str | None
usage: NotRequired[str]
# CIFS and NFS fields
server: NotRequired[str]
@ -113,7 +113,6 @@ class MountData(TypedDict):
share: NotRequired[str]
username: NotRequired[str]
password: NotRequired[str]
version: NotRequired[str | None]
# NFS and Bind fields
path: NotRequired[str]

View File

@ -5,7 +5,7 @@ from contextlib import suppress
from dataclasses import dataclass
import logging
from pathlib import Path
from typing import Any, Final, cast
from typing import Any, Final
from awesomeversion import AwesomeVersion
@ -24,7 +24,6 @@ from ..exceptions import (
)
from ..jobs.const import JobCondition, JobExecutionLimit
from ..jobs.decorator import Job
from ..resolution.checks.base import CheckBase
from ..resolution.checks.disabled_data_disk import CheckDisabledDataDisk
from ..resolution.checks.multiple_data_disks import CheckMultipleDataDisks
from ..utils.sentry import async_capture_exception
@ -150,7 +149,7 @@ class DataDisk(CoreSysAttributes):
Available disks are drives where nothing on it has been mounted
and it can be formatted.
"""
available: list[Disk] = []
available: list[UDisks2Drive] = []
for drive in self.sys_dbus.udisks2.drives:
block_devices = self._get_block_devices_for_drive(drive)
primary = _get_primary_block_device(block_devices)
@ -167,16 +166,12 @@ class DataDisk(CoreSysAttributes):
@property
def check_multiple_data_disks(self) -> CheckMultipleDataDisks:
"""Resolution center check for multiple data disks."""
return cast(
CheckMultipleDataDisks, self.sys_resolution.check.get("multiple_data_disks")
)
return self.sys_resolution.check.get("multiple_data_disks")
@property
def check_disabled_data_disk(self) -> CheckDisabledDataDisk:
"""Resolution center check for disabled data disk."""
return cast(
CheckDisabledDataDisk, self.sys_resolution.check.get("disabled_data_disk")
)
return self.sys_resolution.check.get("disabled_data_disk")
def _get_block_devices_for_drive(self, drive: UDisks2Drive) -> list[UDisks2Block]:
"""Get block devices for a drive."""
@ -366,7 +361,7 @@ class DataDisk(CoreSysAttributes):
try:
partition_block = await UDisks2Block.new(
partition, self.sys_dbus.connected_bus, sync_properties=False
partition, self.sys_dbus.bus, sync_properties=False
)
except DBusError as err:
raise HassOSDataDiskError(
@ -393,7 +388,7 @@ class DataDisk(CoreSysAttributes):
properties[DBUS_IFACE_BLOCK][DBUS_ATTR_ID_LABEL]
== FILESYSTEM_LABEL_DATA_DISK
):
check: CheckBase = self.check_multiple_data_disks
check = self.check_multiple_data_disks
elif (
properties[DBUS_IFACE_BLOCK][DBUS_ATTR_ID_LABEL]
== FILESYSTEM_LABEL_DISABLED_DATA_DISK
@ -416,7 +411,7 @@ class DataDisk(CoreSysAttributes):
and issue.context == self.check_multiple_data_disks.context
for issue in self.sys_resolution.issues
):
check: CheckBase = self.check_multiple_data_disks
check = self.check_multiple_data_disks
elif any(
issue.type == self.check_disabled_data_disk.issue
and issue.context == self.check_disabled_data_disk.context

View File

@ -1,11 +1,11 @@
"""OS support on supervisor."""
from collections.abc import Awaitable
from dataclasses import dataclass
from datetime import datetime
import errno
import logging
from pathlib import Path, PurePath
from typing import cast
import aiohttp
from awesomeversion import AwesomeVersion, AwesomeVersionException
@ -61,8 +61,8 @@ class SlotStatus:
device=PurePath(data["device"]),
bundle_compatible=data.get("bundle.compatible"),
sha256=data.get("sha256"),
size=cast(int | None, data.get("size")),
installed_count=cast(int | None, data.get("installed.count")),
size=data.get("size"),
installed_count=data.get("installed.count"),
bundle_version=AwesomeVersion(data["bundle.version"])
if "bundle.version" in data
else None,
@ -70,17 +70,51 @@ class SlotStatus:
if "installed.timestamp" in data
else None,
status=data.get("status"),
activated_count=cast(int | None, data.get("activated.count")),
activated_count=data.get("activated.count"),
activated_timestamp=datetime.fromisoformat(data["activated.timestamp"])
if "activated.timestamp" in data
else None,
boot_status=RaucState(data["boot-status"])
if "boot-status" in data
else None,
boot_status=data.get("boot-status"),
bootname=data.get("bootname"),
parent=data.get("parent"),
)
def to_dict(self) -> SlotStatusDataType:
"""Get dictionary representation."""
out: SlotStatusDataType = {
"class": self.class_,
"type": self.type_,
"state": self.state,
"device": self.device.as_posix(),
}
if self.bundle_compatible is not None:
out["bundle.compatible"] = self.bundle_compatible
if self.sha256 is not None:
out["sha256"] = self.sha256
if self.size is not None:
out["size"] = self.size
if self.installed_count is not None:
out["installed.count"] = self.installed_count
if self.bundle_version is not None:
out["bundle.version"] = str(self.bundle_version)
if self.installed_timestamp is not None:
out["installed.timestamp"] = str(self.installed_timestamp)
if self.status is not None:
out["status"] = self.status
if self.activated_count is not None:
out["activated.count"] = self.activated_count
if self.activated_timestamp:
out["activated.timestamp"] = str(self.activated_timestamp)
if self.boot_status:
out["boot-status"] = self.boot_status
if self.bootname is not None:
out["bootname"] = self.bootname
if self.parent is not None:
out["parent"] = self.parent
return out
class OSManager(CoreSysAttributes):
"""OS interface inside supervisor."""
@ -114,11 +148,7 @@ class OSManager(CoreSysAttributes):
def need_update(self) -> bool:
"""Return true if a HassOS update is available."""
try:
return (
self.version is not None
and self.latest_version is not None
and self.version < self.latest_version
)
return self.version < self.latest_version
except (AwesomeVersionException, TypeError):
return False
@ -146,9 +176,6 @@ class OSManager(CoreSysAttributes):
def get_slot_name(self, boot_name: str) -> str:
"""Get slot name from boot name."""
if not self._slots:
raise HassOSSlotNotFound()
for name, status in self._slots.items():
if status.bootname == boot_name:
return name
@ -261,8 +288,11 @@ class OSManager(CoreSysAttributes):
conditions=[JobCondition.HAOS],
on_condition=HassOSJobError,
)
async def config_sync(self) -> None:
"""Trigger a host config reload from usb."""
async def config_sync(self) -> Awaitable[None]:
"""Trigger a host config reload from usb.
Return a coroutine.
"""
_LOGGER.info(
"Synchronizing configuration from USB with Home Assistant Operating System."
)
@ -284,10 +314,6 @@ class OSManager(CoreSysAttributes):
version = version or self.latest_version
# Check installed version
if not version:
raise HassOSUpdateError(
"No version information available, cannot update", _LOGGER.error
)
if version == self.version:
raise HassOSUpdateError(
f"Version {version!s} is already installed", _LOGGER.warning

View File

@ -22,7 +22,6 @@ from ..exceptions import (
AudioUpdateError,
ConfigurationFileError,
DockerError,
PluginError,
)
from ..jobs.const import JobExecutionLimit
from ..jobs.decorator import Job
@ -128,7 +127,7 @@ class PluginAudio(PluginBase):
"""Update Audio plugin."""
try:
await super().update(version)
except (DockerError, PluginError) as err:
except DockerError as err:
raise AudioUpdateError("Audio update failed", _LOGGER.error) from err
async def restart(self) -> None:

View File

@ -63,11 +63,7 @@ class PluginBase(ABC, FileConfiguration, CoreSysAttributes):
def need_update(self) -> bool:
"""Return True if an update is available."""
try:
return (
self.version is not None
and self.latest_version is not None
and self.version < self.latest_version
)
return self.version < self.latest_version
except (AwesomeVersionException, TypeError):
return False
@ -157,10 +153,6 @@ class PluginBase(ABC, FileConfiguration, CoreSysAttributes):
async def start(self) -> None:
"""Start system plugin."""
@abstractmethod
async def stop(self) -> None:
"""Stop system plugin."""
async def load(self) -> None:
"""Load system plugin."""
self.start_watchdog()
@ -168,14 +160,14 @@ class PluginBase(ABC, FileConfiguration, CoreSysAttributes):
# Check plugin state
try:
# Evaluate Version if we lost this information
if self.version:
version = self.version
else:
self.version = version = await self.instance.get_latest_version()
if not self.version:
self.version = await self.instance.get_latest_version()
await self.instance.attach(version=version, skip_state_event_if_down=True)
await self.instance.attach(
version=self.version, skip_state_event_if_down=True
)
await self.instance.check_image(version, self.default_image)
await self.instance.check_image(self.version, self.default_image)
except DockerError:
_LOGGER.info(
"No %s plugin Docker image %s found.", self.slug, self.instance.image
@ -185,7 +177,7 @@ class PluginBase(ABC, FileConfiguration, CoreSysAttributes):
with suppress(PluginError):
await self.install()
else:
self.version = self.instance.version or version
self.version = self.instance.version
self.image = self.default_image
await self.save_data()
@ -202,10 +194,11 @@ class PluginBase(ABC, FileConfiguration, CoreSysAttributes):
if not self.latest_version:
await self.sys_updater.reload()
if to_version := self.latest_version:
if self.latest_version:
with suppress(DockerError):
await self.instance.install(to_version, image=self.default_image)
self.version = self.instance.version or to_version
await self.instance.install(
self.latest_version, image=self.default_image
)
break
_LOGGER.warning(
"Error on installing %s plugin, retrying in 30sec", self.slug
@ -213,28 +206,23 @@ class PluginBase(ABC, FileConfiguration, CoreSysAttributes):
await asyncio.sleep(30)
_LOGGER.info("%s plugin now installed", self.slug)
self.version = self.instance.version
self.image = self.default_image
await self.save_data()
async def update(self, version: str | None = None) -> None:
"""Update system plugin."""
to_version = AwesomeVersion(version) if version else self.latest_version
if not to_version:
raise PluginError(
f"Cannot determine latest version of plugin {self.slug} for update",
_LOGGER.error,
)
version = version or self.latest_version
old_image = self.image
if to_version == self.version:
if version == self.version:
_LOGGER.warning(
"Version %s is already installed for %s", to_version, self.slug
"Version %s is already installed for %s", version, self.slug
)
return
await self.instance.update(to_version, image=self.default_image)
self.version = self.instance.version or to_version
await self.instance.update(version, image=self.default_image)
self.version = self.instance.version
self.image = self.default_image
await self.save_data()

View File

@ -14,7 +14,7 @@ from ..coresys import CoreSys
from ..docker.cli import DockerCli
from ..docker.const import ContainerState
from ..docker.stats import DockerStats
from ..exceptions import CliError, CliJobError, CliUpdateError, DockerError, PluginError
from ..exceptions import CliError, CliJobError, CliUpdateError, DockerError
from ..jobs.const import JobExecutionLimit
from ..jobs.decorator import Job
from ..utils.sentry import async_capture_exception
@ -53,7 +53,7 @@ class PluginCli(PluginBase):
return self.sys_updater.version_cli
@property
def supervisor_token(self) -> str | None:
def supervisor_token(self) -> str:
"""Return an access token for the Supervisor API."""
return self._data.get(ATTR_ACCESS_TOKEN)
@ -66,7 +66,7 @@ class PluginCli(PluginBase):
"""Update local HA cli."""
try:
await super().update(version)
except (DockerError, PluginError) as err:
except DockerError as err:
raise CliUpdateError("CLI update failed", _LOGGER.error) from err
async def start(self) -> None:

View File

@ -15,8 +15,7 @@ from awesomeversion import AwesomeVersion
import jinja2
import voluptuous as vol
from ..bus import EventListener
from ..const import ATTR_SERVERS, DNS_SUFFIX, BusEvent, LogLevel
from ..const import ATTR_SERVERS, DNS_SUFFIX, LogLevel
from ..coresys import CoreSys
from ..dbus.const import MulticastProtocolEnabled
from ..docker.const import ContainerState
@ -29,7 +28,6 @@ from ..exceptions import (
CoreDNSJobError,
CoreDNSUpdateError,
DockerError,
PluginError,
)
from ..jobs.const import JobExecutionLimit
from ..jobs.decorator import Job
@ -73,17 +71,11 @@ class PluginDns(PluginBase):
self.slug = "dns"
self.coresys: CoreSys = coresys
self.instance: DockerDNS = DockerDNS(coresys)
self._resolv_template: jinja2.Template | None = None
self._hosts_template: jinja2.Template | None = None
self.resolv_template: jinja2.Template | None = None
self.hosts_template: jinja2.Template | None = None
self._hosts: list[HostEntry] = []
self._loop: bool = False
self._cached_locals: list[str] | None = None
# Debouncing system for rapid local changes
self._locals_changed_handle: asyncio.TimerHandle | None = None
self._restart_after_locals_change_handle: asyncio.Task | None = None
self._connectivity_check_listener: EventListener | None = None
@property
def hosts(self) -> Path:
@ -98,12 +90,6 @@ class PluginDns(PluginBase):
@property
def locals(self) -> list[str]:
"""Return list of local system DNS servers."""
if self._cached_locals is None:
self._cached_locals = self._compute_locals()
return self._cached_locals
def _compute_locals(self) -> list[str]:
"""Compute list of local system DNS servers."""
servers: list[str] = []
for server in [
f"dns://{server!s}" for server in self.sys_host.network.dns_servers
@ -113,52 +99,6 @@ class PluginDns(PluginBase):
return servers
async def _on_dns_container_running(self, event: DockerContainerStateEvent) -> None:
"""Handle DNS container state change to running and trigger connectivity check."""
if event.name == self.instance.name and event.state == ContainerState.RUNNING:
# Wait before CoreDNS actually becomes available
await asyncio.sleep(5)
_LOGGER.debug("CoreDNS started, checking connectivity")
await self.sys_supervisor.check_connectivity()
async def _restart_dns_after_locals_change(self) -> None:
"""Restart DNS after a debounced delay for local changes."""
old_locals = self._cached_locals
new_locals = self._compute_locals()
if old_locals == new_locals:
return
_LOGGER.debug("DNS locals changed from %s to %s", old_locals, new_locals)
self._cached_locals = new_locals
if not await self.instance.is_running():
return
await self.restart()
self._restart_after_locals_change_handle = None
def _trigger_restart_dns_after_locals_change(self) -> None:
"""Trigger a restart of DNS after local changes."""
# Cancel existing restart task if any
if self._restart_after_locals_change_handle:
self._restart_after_locals_change_handle.cancel()
self._restart_after_locals_change_handle = self.sys_create_task(
self._restart_dns_after_locals_change()
)
self._locals_changed_handle = None
def notify_locals_changed(self) -> None:
"""Schedule a debounced DNS restart for local changes."""
# Cancel existing timer if any
if self._locals_changed_handle:
self._locals_changed_handle.cancel()
# Schedule new timer with 1 second delay
self._locals_changed_handle = self.sys_call_later(
1.0, self._trigger_restart_dns_after_locals_change
)
@property
def servers(self) -> list[str]:
"""Return list of DNS servers."""
@ -207,25 +147,11 @@ class PluginDns(PluginBase):
"""Set fallback DNS enabled."""
self._data[ATTR_FALLBACK] = value
@property
def hosts_template(self) -> jinja2.Template:
"""Get hosts jinja template."""
if not self._hosts_template:
raise RuntimeError("Hosts template not set!")
return self._hosts_template
@property
def resolv_template(self) -> jinja2.Template:
"""Get resolv jinja template."""
if not self._resolv_template:
raise RuntimeError("Resolv template not set!")
return self._resolv_template
async def load(self) -> None:
"""Load DNS setup."""
# Initialize CoreDNS Template
try:
self._resolv_template = jinja2.Template(
self.resolv_template = jinja2.Template(
await self.sys_run_in_executor(RESOLV_TMPL.read_text, encoding="utf-8")
)
except OSError as err:
@ -236,7 +162,7 @@ class PluginDns(PluginBase):
_LOGGER.error("Can't read resolve.tmpl: %s", err)
try:
self._hosts_template = jinja2.Template(
self.hosts_template = jinja2.Template(
await self.sys_run_in_executor(HOSTS_TMPL.read_text, encoding="utf-8")
)
except OSError as err:
@ -247,19 +173,10 @@ class PluginDns(PluginBase):
_LOGGER.error("Can't read hosts.tmpl: %s", err)
await self._init_hosts()
# Register Docker event listener for connectivity checks
if not self._connectivity_check_listener:
self._connectivity_check_listener = self.sys_bus.register_event(
BusEvent.DOCKER_CONTAINER_STATE_CHANGE, self._on_dns_container_running
)
await super().load()
# Update supervisor
# Resolv template should always be set but just in case don't fail load
if self._resolv_template:
await self._write_resolv(HOST_RESOLV)
await self._write_resolv(HOST_RESOLV)
# Reinitializing aiohttp.ClientSession after DNS setup makes sure that
# aiodns is using the right DNS servers (see #5857).
@ -284,7 +201,7 @@ class PluginDns(PluginBase):
"""Update CoreDNS plugin."""
try:
await super().update(version)
except (DockerError, PluginError) as err:
except DockerError as err:
raise CoreDNSUpdateError("CoreDNS update failed", _LOGGER.error) from err
async def restart(self) -> None:
@ -294,7 +211,7 @@ class PluginDns(PluginBase):
try:
await self.instance.restart()
except DockerError as err:
raise CoreDNSError("Can't restart CoreDNS plugin", _LOGGER.error) from err
raise CoreDNSError("Can't start CoreDNS plugin", _LOGGER.error) from err
async def start(self) -> None:
"""Run CoreDNS."""
@ -309,16 +226,6 @@ class PluginDns(PluginBase):
async def stop(self) -> None:
"""Stop CoreDNS."""
# Cancel any pending locals change timer
if self._locals_changed_handle:
self._locals_changed_handle.cancel()
self._locals_changed_handle = None
# Wait for any pending restart before stopping
if self._restart_after_locals_change_handle:
self._restart_after_locals_change_handle.cancel()
self._restart_after_locals_change_handle = None
_LOGGER.info("Stopping CoreDNS plugin")
try:
await self.instance.stop()
@ -521,6 +428,12 @@ class PluginDns(PluginBase):
async def _write_resolv(self, resolv_conf: Path) -> None:
"""Update/Write resolv.conf file."""
if not self.resolv_template:
_LOGGER.warning(
"Resolv template is missing, cannot write/update %s", resolv_conf
)
return
nameservers = [str(self.sys_docker.network.dns), "127.0.0.11"]
# Read resolv config

View File

@ -16,7 +16,6 @@ from ..exceptions import (
MulticastError,
MulticastJobError,
MulticastUpdateError,
PluginError,
)
from ..jobs.const import JobExecutionLimit
from ..jobs.decorator import Job
@ -64,7 +63,7 @@ class PluginMulticast(PluginBase):
"""Update Multicast plugin."""
try:
await super().update(version)
except (DockerError, PluginError) as err:
except DockerError as err:
raise MulticastUpdateError(
"Multicast update failed", _LOGGER.error
) from err

View File

@ -19,7 +19,6 @@ from ..exceptions import (
ObserverError,
ObserverJobError,
ObserverUpdateError,
PluginError,
)
from ..jobs.const import JobExecutionLimit
from ..jobs.decorator import Job
@ -59,7 +58,7 @@ class PluginObserver(PluginBase):
return self.sys_updater.version_observer
@property
def supervisor_token(self) -> str | None:
def supervisor_token(self) -> str:
"""Return an access token for the Observer API."""
return self._data.get(ATTR_ACCESS_TOKEN)
@ -72,7 +71,7 @@ class PluginObserver(PluginBase):
"""Update local HA observer."""
try:
await super().update(version)
except (DockerError, PluginError) as err:
except DockerError as err:
raise ObserverUpdateError(
"HA observer update failed", _LOGGER.error
) from err
@ -91,10 +90,6 @@ class PluginObserver(PluginBase):
_LOGGER.error("Can't start observer plugin")
raise ObserverError() from err
async def stop(self) -> None:
"""Raise. Supervisor should not stop observer."""
raise RuntimeError("Stopping observer without a restart is not supported!")
async def stats(self) -> DockerStats:
"""Return stats of observer."""
try:

View File

@ -67,11 +67,10 @@ class CheckAddonPwned(CheckBase):
@Job(name="check_addon_pwned_approve", conditions=[JobCondition.INTERNET_SYSTEM])
async def approve_check(self, reference: str | None = None) -> bool:
"""Approve check if it is affected by issue."""
if not reference:
return False
addon = self.sys_addons.get(reference)
# Uninstalled
if not (addon := self.sys_addons.get_local_only(reference)):
if not addon or not addon.is_installed:
return False
# Not in use anymore

View File

@ -29,11 +29,9 @@ class CheckDetachedAddonMissing(CheckBase):
async def approve_check(self, reference: str | None = None) -> bool:
"""Approve check if it is affected by issue."""
if not reference:
return False
addon = self.sys_addons.get_local_only(reference)
return addon is not None and addon.is_detached
return (
addon := self.sys_addons.get(reference, local_only=True)
) and addon.is_detached
@property
def issue(self) -> IssueType:

View File

@ -27,11 +27,9 @@ class CheckDetachedAddonRemoved(CheckBase):
async def approve_check(self, reference: str | None = None) -> bool:
"""Approve check if it is affected by issue."""
if not reference:
return False
addon = self.sys_addons.get_local_only(reference)
return addon is not None and addon.is_detached
return (
addon := self.sys_addons.get(reference, local_only=True)
) and addon.is_detached
@property
def issue(self) -> IssueType:

View File

@ -35,9 +35,6 @@ class CheckDisabledDataDisk(CheckBase):
async def approve_check(self, reference: str | None = None) -> bool:
"""Approve check if it is affected by issue."""
if not reference:
return False
resolved = await self.sys_dbus.udisks2.resolve_device(
DeviceSpecification(path=Path(reference))
)
@ -46,7 +43,7 @@ class CheckDisabledDataDisk(CheckBase):
def _is_disabled_data_disk(self, block_device: UDisks2Block) -> bool:
"""Return true if filesystem block device has name indicating it was disabled by OS."""
return (
block_device.filesystem is not None
block_device.filesystem
and block_device.id_label == FILESYSTEM_LABEL_DISABLED_DATA_DISK
)

View File

@ -2,7 +2,6 @@
import asyncio
from datetime import timedelta
from typing import Literal
from aiodns import DNSResolver
from aiodns.error import DNSError
@ -16,15 +15,6 @@ from ..const import DNS_CHECK_HOST, ContextType, IssueType
from .base import CheckBase
async def check_server(
loop: asyncio.AbstractEventLoop, server: str, qtype: Literal["A"] | Literal["AAAA"]
) -> None:
"""Check a DNS server and report issues."""
ip_addr = server[6:] if server.startswith("dns://") else server
async with DNSResolver(loop=loop, nameservers=[ip_addr]) as resolver:
await resolver.query(DNS_CHECK_HOST, qtype)
def setup(coresys: CoreSys) -> CheckBase:
"""Check setup function."""
return CheckDNSServer(coresys)
@ -43,18 +33,16 @@ class CheckDNSServer(CheckBase):
"""Run check if not affected by issue."""
dns_servers = self.dns_servers
results = await asyncio.gather(
*[check_server(self.sys_loop, server, "A") for server in dns_servers],
*[self._check_server(server) for server in dns_servers],
return_exceptions=True,
)
# pylint: disable-next=consider-using-enumerate
for i in range(len(results)):
if isinstance(result := results[i], DNSError):
self.sys_resolution.create_issue(
IssueType.DNS_SERVER_FAILED,
ContextType.DNS_SERVER,
reference=dns_servers[i],
)
await async_capture_exception(result)
for i in (r for r in range(len(results)) if isinstance(results[r], DNSError)):
self.sys_resolution.create_issue(
IssueType.DNS_SERVER_FAILED,
ContextType.DNS_SERVER,
reference=dns_servers[i],
)
await async_capture_exception(results[i])
@Job(name="check_dns_server_approve", conditions=[JobCondition.INTERNET_SYSTEM])
async def approve_check(self, reference: str | None = None) -> bool:
@ -63,12 +51,18 @@ class CheckDNSServer(CheckBase):
return False
try:
await check_server(self.sys_loop, reference, "A")
await self._check_server(reference)
except DNSError:
return True
return False
async def _check_server(self, server: str):
"""Check a DNS server and report issues."""
ip_addr = server[6:] if server.startswith("dns://") else server
resolver = DNSResolver(nameservers=[ip_addr])
await resolver.query(DNS_CHECK_HOST, "A")
@property
def dns_servers(self) -> list[str]:
"""All user and system provided dns servers."""

View File

@ -3,6 +3,7 @@
import asyncio
from datetime import timedelta
from aiodns import DNSResolver
from aiodns.error import DNSError
from ...const import CoreState
@ -10,9 +11,8 @@ from ...coresys import CoreSys
from ...jobs.const import JobCondition, JobExecutionLimit
from ...jobs.decorator import Job
from ...utils.sentry import async_capture_exception
from ..const import DNS_ERROR_NO_DATA, ContextType, IssueType
from ..const import DNS_CHECK_HOST, DNS_ERROR_NO_DATA, ContextType, IssueType
from .base import CheckBase
from .dns_server import check_server
def setup(coresys: CoreSys) -> CheckBase:
@ -33,21 +33,21 @@ class CheckDNSServerIPv6(CheckBase):
"""Run check if not affected by issue."""
dns_servers = self.dns_servers
results = await asyncio.gather(
*[check_server(self.sys_loop, server, "AAAA") for server in dns_servers],
*[self._check_server(server) for server in dns_servers],
return_exceptions=True,
)
# pylint: disable-next=consider-using-enumerate
for i in range(len(results)):
if (
isinstance(result := results[i], DNSError)
and result.args[0] != DNS_ERROR_NO_DATA
):
self.sys_resolution.create_issue(
IssueType.DNS_SERVER_IPV6_ERROR,
ContextType.DNS_SERVER,
reference=dns_servers[i],
)
await async_capture_exception(result)
for i in (
r
for r in range(len(results))
if isinstance(results[r], DNSError)
and results[r].args[0] != DNS_ERROR_NO_DATA
):
self.sys_resolution.create_issue(
IssueType.DNS_SERVER_IPV6_ERROR,
ContextType.DNS_SERVER,
reference=dns_servers[i],
)
await async_capture_exception(results[i])
@Job(
name="check_dns_server_ipv6_approve", conditions=[JobCondition.INTERNET_SYSTEM]
@ -58,13 +58,19 @@ class CheckDNSServerIPv6(CheckBase):
return False
try:
await check_server(self.sys_loop, reference, "AAAA")
await self._check_server(reference)
except DNSError as dns_error:
if dns_error.args[0] != DNS_ERROR_NO_DATA:
return True
return False
async def _check_server(self, server: str):
"""Check a DNS server and report issues."""
ip_addr = server[6:] if server.startswith("dns://") else server
resolver = DNSResolver(nameservers=[ip_addr])
await resolver.query(DNS_CHECK_HOST, "AAAA")
@property
def dns_servers(self) -> list[str]:
"""All user and system provided dns servers."""

View File

@ -1,108 +0,0 @@
"""Helpers to check for duplicate OS installations."""
import logging
from ...const import CoreState
from ...coresys import CoreSys
from ...dbus.udisks2.data import DeviceSpecification
from ..const import ContextType, IssueType, UnhealthyReason
from .base import CheckBase
_LOGGER: logging.Logger = logging.getLogger(__name__)
# Partition labels to check for duplicates (GPT-based installations)
HAOS_PARTITIONS = [
"hassos-boot",
"hassos-kernel0",
"hassos-kernel1",
"hassos-system0",
"hassos-system1",
]
# Partition UUIDs to check for duplicates (MBR-based installations)
HAOS_PARTITION_UUIDS = [
"48617373-01", # hassos-boot
"48617373-05", # hassos-kernel0
"48617373-06", # hassos-system0
"48617373-07", # hassos-kernel1
"48617373-08", # hassos-system1
]
def _get_device_specifications():
"""Generate DeviceSpecification objects for both GPT and MBR partitions."""
# GPT-based installations (partition labels)
for partition_label in HAOS_PARTITIONS:
yield (
DeviceSpecification(partlabel=partition_label),
"partition",
partition_label,
)
# MBR-based installations (partition UUIDs)
for partition_uuid in HAOS_PARTITION_UUIDS:
yield (
DeviceSpecification(partuuid=partition_uuid),
"partition UUID",
partition_uuid,
)
def setup(coresys: CoreSys) -> CheckBase:
"""Check setup function."""
return CheckDuplicateOSInstallation(coresys)
class CheckDuplicateOSInstallation(CheckBase):
"""CheckDuplicateOSInstallation class for check."""
async def run_check(self) -> None:
"""Run check if not affected by issue."""
if not self.sys_os.available:
_LOGGER.debug(
"Skipping duplicate OS installation check, OS is not available"
)
return
for device_spec, spec_type, identifier in _get_device_specifications():
resolved = await self.sys_dbus.udisks2.resolve_device(device_spec)
if resolved and len(resolved) > 1:
_LOGGER.warning(
"Found duplicate OS installation: %s %s exists on %d devices (%s)",
identifier,
spec_type,
len(resolved),
", ".join(str(device.device) for device in resolved),
)
self.sys_resolution.add_unhealthy_reason(
UnhealthyReason.DUPLICATE_OS_INSTALLATION
)
self.sys_resolution.create_issue(
IssueType.DUPLICATE_OS_INSTALLATION,
ContextType.SYSTEM,
)
return
async def approve_check(self, reference: str | None = None) -> bool:
"""Approve check if it is affected by issue."""
# Check all partitions for duplicates since issue is created without reference
for device_spec, _, _ in _get_device_specifications():
resolved = await self.sys_dbus.udisks2.resolve_device(device_spec)
if resolved and len(resolved) > 1:
return True
return False
@property
def issue(self) -> IssueType:
"""Return a IssueType enum."""
return IssueType.DUPLICATE_OS_INSTALLATION
@property
def context(self) -> ContextType:
"""Return a ContextType enum."""
return ContextType.SYSTEM
@property
def states(self) -> list[CoreState]:
"""Return a list of valid states when this check can run."""
return [CoreState.SETUP]

View File

@ -21,9 +21,6 @@ class CheckMultipleDataDisks(CheckBase):
async def run_check(self) -> None:
"""Run check if not affected by issue."""
if not self.sys_os.available:
return
for block_device in self.sys_dbus.udisks2.block_devices:
if self._block_device_has_name_issue(block_device):
self.sys_resolution.create_issue(
@ -38,9 +35,6 @@ class CheckMultipleDataDisks(CheckBase):
async def approve_check(self, reference: str | None = None) -> bool:
"""Approve check if it is affected by issue."""
if not reference:
return False
resolved = await self.sys_dbus.udisks2.resolve_device(
DeviceSpecification(path=Path(reference))
)
@ -49,7 +43,7 @@ class CheckMultipleDataDisks(CheckBase):
def _block_device_has_name_issue(self, block_device: UDisks2Block) -> bool:
"""Return true if filesystem block device incorrectly has data disk name."""
return (
block_device.filesystem is not None
block_device.filesystem
and block_device.id_label == FILESYSTEM_LABEL_DATA_DISK
and block_device.device != self.sys_dbus.agent.datadisk.current_device
)

View File

@ -19,12 +19,12 @@ class CheckNetworkInterfaceIPV4(CheckBase):
async def run_check(self) -> None:
"""Run check if not affected by issue."""
for inet in self.sys_dbus.network.interfaces:
if CheckNetworkInterfaceIPV4.check_interface(inet):
for interface in self.sys_dbus.network.interfaces:
if CheckNetworkInterfaceIPV4.check_interface(interface):
self.sys_resolution.create_issue(
IssueType.IPV4_CONNECTION_PROBLEM,
ContextType.SYSTEM,
inet.interface_name,
interface.name,
)
async def approve_check(self, reference: str | None = None) -> bool:

View File

@ -64,11 +64,10 @@ class UnhealthyReason(StrEnum):
"""Reasons for unsupported status."""
DOCKER = "docker"
DUPLICATE_OS_INSTALLATION = "duplicate_os_installation"
OSERROR_BAD_MESSAGE = "oserror_bad_message"
PRIVILEGED = "privileged"
SETUP = "setup"
SUPERVISOR = "supervisor"
SETUP = "setup"
UNTRUSTED = "untrusted"
@ -84,7 +83,6 @@ class IssueType(StrEnum):
DEVICE_ACCESS_MISSING = "device_access_missing"
DISABLED_DATA_DISK = "disabled_data_disk"
DNS_LOOP = "dns_loop"
DUPLICATE_OS_INSTALLATION = "duplicate_os_installation"
DNS_SERVER_FAILED = "dns_server_failed"
DNS_SERVER_IPV6_ERROR = "dns_server_ipv6_error"
DOCKER_CONFIG = "docker_config"

View File

@ -1,6 +1,6 @@
"""Data objects."""
from uuid import uuid4
from uuid import UUID, uuid4
import attr
@ -20,7 +20,7 @@ class Issue:
type: IssueType = attr.ib()
context: ContextType = attr.ib()
reference: str | None = attr.ib(default=None)
uuid: str = attr.ib(factory=lambda: uuid4().hex, eq=False, init=False)
uuid: UUID = attr.ib(factory=lambda: uuid4().hex, eq=False, init=False)
@attr.s(frozen=True, slots=True)
@ -30,7 +30,7 @@ class Suggestion:
type: SuggestionType = attr.ib()
context: ContextType = attr.ib()
reference: str | None = attr.ib(default=None)
uuid: str = attr.ib(factory=lambda: uuid4().hex, eq=False, init=False)
uuid: UUID = attr.ib(factory=lambda: uuid4().hex, eq=False, init=False)
@attr.s(frozen=True, slots=True)

View File

@ -33,7 +33,7 @@ class EvaluateAppArmor(EvaluateBase):
"""Return a list of valid states when this evaluation can run."""
return [CoreState.INITIALIZE]
async def evaluate(self) -> bool:
async def evaluate(self) -> None:
"""Run evaluation."""
try:
apparmor = await self.sys_run_in_executor(

View File

@ -5,8 +5,6 @@ import logging
from docker.errors import DockerException
from requests import RequestException
from supervisor.docker.const import ADDON_BUILDER_IMAGE
from ...const import CoreState
from ...coresys import CoreSys
from ..const import (
@ -40,7 +38,7 @@ class EvaluateContainer(EvaluateBase):
"""Initialize the evaluation class."""
super().__init__(coresys)
self.coresys = coresys
self._images: set[str] = set()
self._images = set()
@property
def reason(self) -> UnsupportedReason:
@ -62,10 +60,9 @@ class EvaluateContainer(EvaluateBase):
"""Return a set of all known images."""
return {
self.sys_homeassistant.image,
self.sys_supervisor.image or self.sys_supervisor.default_image,
*(plugin.image for plugin in self.sys_plugins.all_plugins if plugin.image),
*(addon.image for addon in self.sys_addons.installed if addon.image),
ADDON_BUILDER_IMAGE,
self.sys_supervisor.image,
*(plugin.image for plugin in self.sys_plugins.all_plugins),
*(addon.image for addon in self.sys_addons.installed),
}
async def evaluate(self) -> bool:

View File

@ -29,6 +29,6 @@ class EvaluateContentTrust(EvaluateBase):
"""Return a list of valid states when this evaluation can run."""
return [CoreState.INITIALIZE, CoreState.SETUP, CoreState.RUNNING]
async def evaluate(self) -> bool:
async def evaluate(self) -> None:
"""Run evaluation."""
return not self.sys_security.content_trust

View File

@ -29,6 +29,6 @@ class EvaluateDbus(EvaluateBase):
"""Return a list of valid states when this evaluation can run."""
return [CoreState.INITIALIZE]
async def evaluate(self) -> bool:
async def evaluate(self) -> None:
"""Run evaluation."""
return not await self.sys_run_in_executor(SOCKET_DBUS.exists)
return not SOCKET_DBUS.exists()

View File

@ -29,7 +29,7 @@ class EvaluateDNSServer(EvaluateBase):
"""Return a list of valid states when this evaluation can run."""
return [CoreState.RUNNING]
async def evaluate(self) -> bool:
async def evaluate(self) -> None:
"""Run evaluation."""
return (
not self.sys_plugins.dns.fallback

View File

@ -36,7 +36,7 @@ class EvaluateDockerConfiguration(EvaluateBase):
"""Return a list of valid states when this evaluation can run."""
return [CoreState.INITIALIZE]
async def evaluate(self) -> bool:
async def evaluate(self):
"""Run evaluation."""
storage_driver = self.sys_docker.info.storage
logging_driver = self.sys_docker.info.logging

Some files were not shown because too many files have changed in this diff Show More