Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 24 additions & 18 deletions homeassistant/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,19 @@
)


def attempt_use_uvloop() -> None:
def set_loop() -> None:
"""Attempt to use uvloop."""
import asyncio
try:
import uvloop
except ImportError:
pass

if sys.platform == 'win32':
asyncio.set_event_loop(asyncio.ProactorEventLoop())
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
try:
import uvloop
except ImportError:
pass
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
Copy link
Copy Markdown
Member

@pvizeli pvizeli Sep 20, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be simple:

try:
   import uvloop
   asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ..:
   pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it's simpler, but the part that's supposed to raise an ImportError is the actual import. I don't want to guard the policy call because if uvloop has an internal problem which happens to raise an ImportError the system may be left in an inconsistent state and the error won't be reported.

All of this is probably not relevant in this particular case, but I got into the habit of following this pattern as a matter of principle because it's good coding practice and I did hit that set of circumstances often enough to be wary of it.



def validate_python() -> None:
Expand Down Expand Up @@ -244,17 +248,6 @@ async def setup_and_run_hass(config_dir: str,
"""Set up HASS and run."""
from homeassistant import bootstrap, core

# Run a simple daemon runner process on Windows to handle restarts
if os.name == 'nt' and '--runner' not in sys.argv:
nt_args = cmdline() + ['--runner']
while True:
try:
subprocess.check_call(nt_args)
sys.exit(0)
except subprocess.CalledProcessError as exc:
if exc.returncode != RESTART_EXIT_CODE:
sys.exit(exc.returncode)

hass = core.HomeAssistant()

if args.demo_mode:
Expand Down Expand Up @@ -345,7 +338,20 @@ def main() -> int:
monkey_patch.disable_c_asyncio()
monkey_patch.patch_weakref_tasks()

attempt_use_uvloop()
set_loop()

# Run a simple daemon runner process on Windows to handle restarts
if os.name == 'nt' and '--runner' not in sys.argv:
nt_args = cmdline() + ['--runner']
while True:
try:
subprocess.check_call(nt_args)
sys.exit(0)
except KeyboardInterrupt:
sys.exit(0)
except subprocess.CalledProcessError as exc:
if exc.returncode != RESTART_EXIT_CODE:
sys.exit(exc.returncode)

args = get_arguments()

Expand Down
5 changes: 1 addition & 4 deletions homeassistant/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,7 @@ def __init__(
self,
loop: Optional[asyncio.events.AbstractEventLoop] = None) -> None:
"""Initialize new Home Assistant object."""
if sys.platform == 'win32':
self.loop = loop or asyncio.ProactorEventLoop()
else:
self.loop = loop or asyncio.get_event_loop()
self.loop = loop or asyncio.get_event_loop()

executor_opts = {'max_workers': None} # type: Dict[str, Any]
if sys.version_info[:2] >= (3, 6):
Expand Down
25 changes: 25 additions & 0 deletions homeassistant/helpers/signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,28 @@ def async_signal_handle(exit_code):
signal.SIGHUP, async_signal_handle, RESTART_EXIT_CODE)
except ValueError:
_LOGGER.warning("Could not bind to SIGHUP")

else:
old_sigterm = None
old_sigint = None

@callback
def async_signal_handle(exit_code, frame):
"""Wrap signal handling.

* queue call to shutdown task
* re-instate default handler
"""
signal.signal(signal.SIGTERM, old_sigterm)
signal.signal(signal.SIGINT, old_sigint)
hass.async_create_task(hass.async_stop(exit_code))

try:
old_sigterm = signal.signal(signal.SIGTERM, async_signal_handle)
except ValueError:
_LOGGER.warning("Could not bind to SIGTERM")

try:
old_sigint = signal.signal(signal.SIGINT, async_signal_handle)
except ValueError:
_LOGGER.warning("Could not bind to SIGINT")