lease.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. """ControlLease async context manager.
  2. gRPC keepalive is not a control heartbeat. This object renews the *lease*.
  3. It does not feed the FPGA watchdog; hthd does that by repeating continuous
  4. targets after startup_complete.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. from datetime import timedelta
  9. from typing import TYPE_CHECKING, Optional
  10. from hth_sdk.exceptions import LeaseError
  11. from hth_sdk.types import ActionBatch, ActionResult
  12. if TYPE_CHECKING:
  13. from hth_sdk.client import HthClient
  14. from hth_sdk.mock import MockClient
  15. class ControlLease:
  16. def __init__(
  17. self,
  18. *,
  19. client: "HthClient | MockClient",
  20. device_id: str,
  21. lease_id: str,
  22. lease_epoch: int,
  23. holder: str,
  24. ttl: timedelta,
  25. auto_renew: bool = True,
  26. ) -> None:
  27. self._client = client
  28. self.device_id = device_id
  29. self.lease_id = lease_id
  30. self.lease_epoch = lease_epoch
  31. self.holder = holder
  32. self.ttl = ttl
  33. self.auto_renew = auto_renew
  34. self._task: Optional[asyncio.Task] = None
  35. self._closed = False
  36. async def __aenter__(self) -> "ControlLease":
  37. if self.auto_renew:
  38. self._task = asyncio.create_task(self._renew_loop(), name="hth-lease-renew")
  39. return self
  40. async def __aexit__(self, *exc: object) -> None:
  41. await self.release()
  42. async def _renew_loop(self) -> None:
  43. # Renew at one-third of TTL so a missed tick still has margin.
  44. interval = max(self.ttl.total_seconds() / 3.0, 0.2)
  45. try:
  46. while not self._closed:
  47. await asyncio.sleep(interval)
  48. if self._closed:
  49. return
  50. await self._client.renew_lease(
  51. self.device_id, self.lease_id, self.lease_epoch, self.ttl
  52. )
  53. except asyncio.CancelledError:
  54. return
  55. def bind(self, batch: ActionBatch) -> ActionBatch:
  56. return batch.with_lease(self.lease_id, self.lease_epoch)
  57. async def validate(self, batch: ActionBatch) -> ActionResult:
  58. return await self._client.validate(self.bind(batch))
  59. async def apply(self, batch: ActionBatch) -> ActionResult:
  60. return await self._client.apply(self.bind(batch))
  61. async def enter_safe_mode(self, reason: str = "client-requested") -> ActionResult:
  62. result = await self._client.enter_safe_mode(
  63. self.device_id, self.lease_id, self.lease_epoch, reason
  64. )
  65. if result.accepted:
  66. # Host enterSafe() invalidates the control lease. ResumeFromSafe
  67. # requires a newly acquired lease (TestResumeFromSafeStateMachine).
  68. await self._abandon_invalidated_lease()
  69. return result
  70. async def resume_from_safe(self, batch: ActionBatch) -> ActionResult:
  71. if self._closed:
  72. raise LeaseError(
  73. "EnterSafeMode invalidates the control lease; "
  74. "acquire a new lease before ResumeFromSafe"
  75. )
  76. return await self._client.resume_from_safe(
  77. self.device_id, self.lease_id, self.lease_epoch, self.bind(batch)
  78. )
  79. async def _abandon_invalidated_lease(self) -> None:
  80. self._closed = True
  81. if self._task is not None:
  82. self._task.cancel()
  83. try:
  84. await self._task
  85. except (asyncio.CancelledError, Exception):
  86. pass
  87. self._task = None
  88. async def release(self) -> None:
  89. if self._closed:
  90. return
  91. self._closed = True
  92. if self._task is not None:
  93. self._task.cancel()
  94. try:
  95. await self._task
  96. except (asyncio.CancelledError, Exception):
  97. pass
  98. self._task = None
  99. await self._client.release_lease(self.device_id, self.lease_id, self.lease_epoch)