Skip to content

Commit

Permalink
Merge pull request aiokitchen#186 from aiokitchen/hotfix/rework-inter…
Browse files Browse the repository at this point in the history
…rupt-signal-handling

Rework interrupt signal beghaviour
  • Loading branch information
mosquito authored Jul 20, 2023
2 parents fd65e0c + 4cdb515 commit 34b5768
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions aiomisc/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,9 +384,13 @@ async def stop_services(
await self.post_stop.call(entrypoint=self, services=svc)

async def _cancel_background_tasks(self) -> None:
tasks = asyncio_all_tasks(self._loop)
current_task = asyncio_current_task(self.loop)
await cancel_tasks(task for task in tasks if task is not current_task)
await cancel_tasks(
filter(
lambda x: x is not current_task,
asyncio_all_tasks(self._loop),
),
)

async def graceful_shutdown(self, exception: Exception) -> None:
if self._closing:
Expand All @@ -407,22 +411,27 @@ def _on_interrupt_callback(self, _: Any) -> None:
def _on_interrupt(self, loop: asyncio.AbstractEventLoop) -> None:
async def shutdown() -> None:
log.warning("Interrupt signal received, shutting down...")
try:
await asyncio.wait_for(
self._stop(RuntimeError("Interrupt signal received")),
timeout=self.shutdown_timeout,
)
except asyncio.TimeoutError as e:
await self._stop(RuntimeError("Interrupt signal received"))

task = loop.create_task(shutdown())
handle = loop.call_later(self.shutdown_timeout, task.cancel)

def on_shutdown_finish(task: asyncio.Future) -> None:
nonlocal handle, loop

if task.cancelled():
log.warning(
"Shutdown did not happen in %s seconds, aborting.",
self.shutdown_timeout,
)
handle.cancel()
loop.stop()

if task.cancelled():
# 70 from sysexits.h means "internal software error"
raise SystemExit(70) from e
raise SystemExit(70)

self.loop.create_task(shutdown()).add_done_callback(
lambda _: loop.stop(),
)
task.add_done_callback(on_shutdown_finish)


CURRENT_ENTRYPOINT: StrictContextVar[Entrypoint] = StrictContextVar(
Expand Down

0 comments on commit 34b5768

Please sign in to comment.