lager-cli 0.62.0__tar.gz → 0.64.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. {lager_cli-0.62.0/lager_cli.egg-info → lager_cli-0.64.0}/PKG-INFO +1 -1
  2. {lager_cli-0.62.0 → lager_cli-0.64.0}/__init__.py +1 -1
  3. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/__init__.py +2 -0
  4. lager_cli-0.64.0/commands/utility/lease.py +228 -0
  5. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/login.py +23 -12
  6. {lager_cli-0.62.0 → lager_cli-0.64.0}/gateway_auth.py +84 -16
  7. {lager_cli-0.62.0 → lager_cli-0.64.0/lager_cli.egg-info}/PKG-INFO +1 -1
  8. {lager_cli-0.62.0 → lager_cli-0.64.0}/lager_cli.egg-info/SOURCES.txt +4 -0
  9. lager_cli-0.64.0/lease_client.py +282 -0
  10. {lager_cli-0.62.0 → lager_cli-0.64.0}/main.py +4 -2
  11. {lager_cli-0.62.0 → lager_cli-0.64.0}/LICENSE +0 -0
  12. {lager_cli-0.62.0 → lager_cli-0.64.0}/MANIFEST.in +0 -0
  13. {lager_cli-0.62.0 → lager_cli-0.64.0}/NOTICE +0 -0
  14. {lager_cli-0.62.0 → lager_cli-0.64.0}/README.md +0 -0
  15. {lager_cli-0.62.0 → lager_cli-0.64.0}/__main__.py +0 -0
  16. {lager_cli-0.62.0 → lager_cli-0.64.0}/address_utils.py +0 -0
  17. {lager_cli-0.62.0 → lager_cli-0.64.0}/battery/__init__.py +0 -0
  18. {lager_cli-0.62.0 → lager_cli-0.64.0}/battery/battery_tui.py +0 -0
  19. {lager_cli-0.62.0 → lager_cli-0.64.0}/battery/websocket_client.py +0 -0
  20. {lager_cli-0.62.0 → lager_cli-0.64.0}/box_storage.py +0 -0
  21. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/__init__.py +0 -0
  22. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/__init__.py +0 -0
  23. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/_device_identity.py +0 -0
  24. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/_gateway.py +0 -0
  25. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/_host_ops.py +0 -0
  26. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/_mount_prep.py +0 -0
  27. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/_net_preflight.py +0 -0
  28. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/_pip_validation.py +0 -0
  29. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/_shim_verbs.py +0 -0
  30. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/_ssh.py +0 -0
  31. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/bench.py +0 -0
  32. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/box_group.py +0 -0
  33. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/boxes.py +0 -0
  34. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/config.py +0 -0
  35. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/diagnose.py +0 -0
  36. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/drivers.py +0 -0
  37. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/dut.py +0 -0
  38. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/hello.py +0 -0
  39. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/instruments.py +0 -0
  40. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/labjack_pins.py +0 -0
  41. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/lock.py +0 -0
  42. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/net_tui.py +0 -0
  43. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/nets.py +0 -0
  44. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/ssh.py +0 -0
  45. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/box/ssh_setup.py +0 -0
  46. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/__init__.py +0 -0
  47. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/ble.py +0 -0
  48. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/blufi.py +0 -0
  49. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/i2c.py +0 -0
  50. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/router.py +0 -0
  51. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/spi.py +0 -0
  52. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/uart.py +0 -0
  53. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/usb.py +0 -0
  54. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/websocket_client.py +0 -0
  55. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/communication/wifi.py +0 -0
  56. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/custom.py +0 -0
  57. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/__init__.py +0 -0
  58. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/arm.py +0 -0
  59. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/debug/__init__.py +0 -0
  60. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/debug/commands.py +0 -0
  61. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/debug/net_cache.py +0 -0
  62. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/debug/rtt_websocket_client.py +0 -0
  63. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/debug/service_client.py +0 -0
  64. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/debug/service_helper.py +0 -0
  65. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/debug/tunnel.py +0 -0
  66. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/devenv.py +0 -0
  67. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/development/python.py +0 -0
  68. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/__init__.py +0 -0
  69. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/adc.py +0 -0
  70. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/dac.py +0 -0
  71. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/dmm.py +0 -0
  72. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/energy.py +0 -0
  73. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/gpi.py +0 -0
  74. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/gpo.py +0 -0
  75. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/logic.py +0 -0
  76. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/scope.py +0 -0
  77. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/thermocouple.py +0 -0
  78. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/measurement/watt.py +0 -0
  79. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/power/__init__.py +0 -0
  80. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/power/battery.py +0 -0
  81. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/power/battery_model_csv.py +0 -0
  82. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/power/eload.py +0 -0
  83. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/power/solar.py +0 -0
  84. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/power/supply.py +0 -0
  85. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/security/__init__.py +0 -0
  86. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/security/hsm.py +0 -0
  87. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/_host_cli.py +0 -0
  88. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/binaries.py +0 -0
  89. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/defaults.py +0 -0
  90. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/exec_.py +0 -0
  91. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/install.py +0 -0
  92. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/install_wheel.py +0 -0
  93. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/logs.py +0 -0
  94. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/uninstall.py +0 -0
  95. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/update.py +0 -0
  96. {lager_cli-0.62.0 → lager_cli-0.64.0}/commands/utility/webcam.py +0 -0
  97. {lager_cli-0.62.0 → lager_cli-0.64.0}/config.py +0 -0
  98. {lager_cli-0.62.0 → lager_cli-0.64.0}/context/__init__.py +0 -0
  99. {lager_cli-0.62.0 → lager_cli-0.64.0}/context/ci_detection.py +0 -0
  100. {lager_cli-0.62.0 → lager_cli-0.64.0}/context/constants.py +0 -0
  101. {lager_cli-0.62.0 → lager_cli-0.64.0}/context/core.py +0 -0
  102. {lager_cli-0.62.0 → lager_cli-0.64.0}/context/error_handlers.py +0 -0
  103. {lager_cli-0.62.0 → lager_cli-0.64.0}/context/session.py +0 -0
  104. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/__init__.py +0 -0
  105. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/custom_drivers.py +0 -0
  106. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/group_usage.py +0 -0
  107. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/matchers.py +0 -0
  108. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/net_group.py +0 -0
  109. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/net_helpers.py +0 -0
  110. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/net_storage.py +0 -0
  111. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/param_types.py +0 -0
  112. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/ssh_utils.py +0 -0
  113. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/tui_keys.py +0 -0
  114. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/tui_ws_bridge.py +0 -0
  115. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/utils.py +0 -0
  116. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/version_skew.py +0 -0
  117. {lager_cli-0.62.0 → lager_cli-0.64.0}/core/ws_diagnose.py +0 -0
  118. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/__init__.py +0 -0
  119. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/scripts/__init__.py +0 -0
  120. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/scripts/configure_docker_dns.py +0 -0
  121. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/scripts/configure_docker_dns.sh +0 -0
  122. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/scripts/convert_to_sparse_checkout.sh +0 -0
  123. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/scripts/setup_and_deploy_box.sh +0 -0
  124. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/scripts/setup_ssh_key.sh +0 -0
  125. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/security/__init__.py +0 -0
  126. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/security/etc_lager_perms.sh +0 -0
  127. {lager_cli-0.62.0 → lager_cli-0.64.0}/deployment/security/secure_box_firewall.sh +0 -0
  128. {lager_cli-0.62.0 → lager_cli-0.64.0}/errors.py +0 -0
  129. {lager_cli-0.62.0 → lager_cli-0.64.0}/exceptions.py +0 -0
  130. {lager_cli-0.62.0 → lager_cli-0.64.0}/gateway_tunnel.py +0 -0
  131. {lager_cli-0.62.0 → lager_cli-0.64.0}/impl/__init__.py +0 -0
  132. {lager_cli-0.62.0 → lager_cli-0.64.0}/impl/box_config.py +0 -0
  133. {lager_cli-0.62.0 → lager_cli-0.64.0}/impl/measurement/__init__.py +0 -0
  134. {lager_cli-0.62.0 → lager_cli-0.64.0}/impl/measurement/scope.py +0 -0
  135. {lager_cli-0.62.0 → lager_cli-0.64.0}/impl/measurement/scope_stream.py +0 -0
  136. {lager_cli-0.62.0 → lager_cli-0.64.0}/impl/power/__init__.py +0 -0
  137. {lager_cli-0.62.0 → lager_cli-0.64.0}/impl/power/enable_disable.py +0 -0
  138. {lager_cli-0.62.0 → lager_cli-0.64.0}/lager_cli.egg-info/dependency_links.txt +0 -0
  139. {lager_cli-0.62.0 → lager_cli-0.64.0}/lager_cli.egg-info/entry_points.txt +0 -0
  140. {lager_cli-0.62.0 → lager_cli-0.64.0}/lager_cli.egg-info/requires.txt +0 -0
  141. {lager_cli-0.62.0 → lager_cli-0.64.0}/lager_cli.egg-info/top_level.txt +0 -0
  142. {lager_cli-0.62.0 → lager_cli-0.64.0}/pyproject.toml +0 -0
  143. {lager_cli-0.62.0 → lager_cli-0.64.0}/run_record.py +0 -0
  144. {lager_cli-0.62.0 → lager_cli-0.64.0}/safe_unpickle.py +0 -0
  145. {lager_cli-0.62.0 → lager_cli-0.64.0}/setup.cfg +0 -0
  146. {lager_cli-0.62.0 → lager_cli-0.64.0}/setup.py +0 -0
  147. {lager_cli-0.62.0 → lager_cli-0.64.0}/simple_hdlc.py +0 -0
  148. {lager_cli-0.62.0 → lager_cli-0.64.0}/sort_utils.py +0 -0
  149. {lager_cli-0.62.0 → lager_cli-0.64.0}/status.py +0 -0
  150. {lager_cli-0.62.0 → lager_cli-0.64.0}/supply/__init__.py +0 -0
  151. {lager_cli-0.62.0 → lager_cli-0.64.0}/supply/supply_tui.py +0 -0
  152. {lager_cli-0.62.0 → lager_cli-0.64.0}/supply/websocket_client.py +0 -0
  153. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/__init__.py +0 -0
  154. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/core/__init__.py +0 -0
  155. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/core/executor.py +0 -0
  156. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/main.py +0 -0
  157. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/ui/__init__.py +0 -0
  158. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/ui/completer.py +0 -0
  159. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/ui/display.py +0 -0
  160. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/ui/logo.py +0 -0
  161. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/ui/repl.py +0 -0
  162. {lager_cli-0.62.0 → lager_cli-0.64.0}/terminal/ui/themes.py +0 -0
  163. {lager_cli-0.62.0 → lager_cli-0.64.0}/update_check.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lager-cli
3
- Version: 0.62.0
3
+ Version: 0.64.0
4
4
  Summary: Lager CLI - Box and Docker connectivity
5
5
  Home-page: https://github.com/lagerdata/lager
6
6
  Author: Lager Data
@@ -7,4 +7,4 @@ Lager CLI
7
7
  A Command Line Interface for Lager Data
8
8
  """
9
9
 
10
- __version__ = '0.62.0'
10
+ __version__ = '0.64.0'
@@ -27,6 +27,7 @@ from .install import install
27
27
  from .uninstall import uninstall
28
28
  from .install_wheel import install_wheel
29
29
  from .login import login, logout, whoami
30
+ from .lease import lease
30
31
 
31
32
  __all__ = [
32
33
  "defaults",
@@ -38,6 +39,7 @@ __all__ = [
38
39
  "install",
39
40
  "uninstall",
40
41
  "install_wheel",
42
+ "lease",
41
43
  "login",
42
44
  "logout",
43
45
  "whoami",
@@ -0,0 +1,228 @@
1
+ # Copyright 2024-2026 Lager Data
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """
5
+ `lager lease` -- lease any free box from a pool, run a command on it, give it back.
6
+ """
7
+ import os
8
+ import signal
9
+ import subprocess
10
+ import threading
11
+ import time
12
+
13
+ import click
14
+
15
+ from ...errors import LagerError
16
+ from ... import lease_client
17
+ from ...lease_client import (
18
+ DEFAULT_TTL_SECONDS,
19
+ EXIT_NO_LEASE,
20
+ MAX_TTL_SECONDS,
21
+ MIN_TTL_SECONDS,
22
+ LeaseClient,
23
+ LeaseEnded,
24
+ )
25
+
26
+ #: How long a command gets to exit after SIGTERM before it is killed, when
27
+ #: the lease ends under it.
28
+ TERMINATE_GRACE_SECONDS = 10
29
+
30
+
31
+ class LeaseHeartbeat(threading.Thread):
32
+ """Renews the lease every ``interval`` seconds until stopped.
33
+
34
+ A failed renewal is not fatal: the lease lives ``ttl`` seconds past the
35
+ last good one, so a short network outage costs nothing. A warning is
36
+ printed once half the TTL has passed without a good renewal. A renewal
37
+ the service refuses because the lease has ended sets ``ended`` and stops.
38
+ """
39
+
40
+ def __init__(self, client, lease_id, interval, ttl_seconds):
41
+ super().__init__(daemon=True, name='lager-lease-heartbeat')
42
+ self._client = client
43
+ self._lease_id = lease_id
44
+ self._interval = interval
45
+ self._ttl = ttl_seconds
46
+ self._stop_event = threading.Event()
47
+ self.ended = None
48
+ self._last_ok = time.monotonic()
49
+ self._warned = False
50
+
51
+ def stop(self):
52
+ self._stop_event.set()
53
+
54
+ def run(self):
55
+ while not self._stop_event.wait(self._interval):
56
+ try:
57
+ self._client.heartbeat(self._lease_id)
58
+ except LeaseEnded as exc:
59
+ self.ended = exc.end_reason
60
+ return
61
+ except LagerError as exc:
62
+ unrenewed = time.monotonic() - self._last_ok
63
+ if not self._warned and unrenewed >= self._ttl / 2:
64
+ self._warned = True
65
+ click.secho(
66
+ f'Warning: no renewal of the lease in the last {int(unrenewed)} s '
67
+ f'(it ends after {self._ttl} s): {exc.problem}',
68
+ fg='yellow', err=True,
69
+ )
70
+ continue
71
+ self._last_ok = time.monotonic()
72
+ self._warned = False
73
+
74
+
75
+ def _exit_status(returncode):
76
+ """A child's status as a shell reports it: 128+N for death by signal N."""
77
+ return 128 - returncode if returncode < 0 else returncode
78
+
79
+
80
+ def _forwarded_signals():
81
+ # SIGINT is not forwarded: Ctrl-C at a terminal already reaches the
82
+ # command, which is in the same process group; a second copy would make
83
+ # pytest and similar tools abort without cleaning up.
84
+ return [s for s in (getattr(signal, 'SIGTERM', None), getattr(signal, 'SIGHUP', None)) if s]
85
+
86
+
87
+ def run_under_lease(client, pool, command, *, ttl_seconds=DEFAULT_TTL_SECONDS,
88
+ context=None, popen=subprocess.Popen):
89
+ """Lease a box from ``pool``, run ``command`` on it, release. Returns the exit status."""
90
+ lease = client.acquire(pool, ttl_seconds=ttl_seconds, context=context)
91
+ box = lease.get('box') or {}
92
+ lease_id = lease['id']
93
+ box_label = box.get('name') or box.get('ipAddress')
94
+ click.secho(f'Leased box {box_label} ({box.get("ipAddress")}) from pool {pool!r}.',
95
+ fg='green', err=True)
96
+
97
+ env = dict(os.environ)
98
+ env['LAGER_BOX'] = box['ipAddress']
99
+ env['LAGER_LOCK_HOLDER'] = lease['holder']
100
+ env['LAGER_LEASE_ID'] = lease_id
101
+
102
+ interval = lease.get('heartbeatIntervalSeconds') or max(10, ttl_seconds // 3)
103
+ heartbeat = LeaseHeartbeat(client, lease_id, interval, lease.get('ttlSeconds') or ttl_seconds)
104
+
105
+ previous = {}
106
+ child = None
107
+ try:
108
+ try:
109
+ child = popen(list(command), env=env)
110
+ except OSError as exc:
111
+ raise LagerError(f'Cannot start {command[0]!r}.', cause=str(exc),
112
+ exit_code=127) from exc
113
+
114
+ def forward(signum, _frame):
115
+ if child.poll() is None:
116
+ child.send_signal(signum)
117
+
118
+ for signum in _forwarded_signals():
119
+ previous[signum] = signal.signal(signum, forward)
120
+ previous[signal.SIGINT] = signal.signal(signal.SIGINT, signal.SIG_IGN)
121
+
122
+ heartbeat.start()
123
+ while True:
124
+ try:
125
+ returncode = child.wait(timeout=0.5)
126
+ break
127
+ except subprocess.TimeoutExpired:
128
+ pass
129
+ if heartbeat.ended:
130
+ _stop_child(child)
131
+ raise LagerError(
132
+ f'The lease on box {box_label} ended before the command stopped.',
133
+ cause=f'Reason: {heartbeat.ended}. Another job can now use the box, '
134
+ 'so lager stopped the command.',
135
+ exit_code=EXIT_NO_LEASE,
136
+ )
137
+ if heartbeat.ended:
138
+ raise LagerError(
139
+ f'The lease on box {box_label} ended before the command finished.',
140
+ cause=f'Reason: {heartbeat.ended}.',
141
+ exit_code=EXIT_NO_LEASE,
142
+ )
143
+ return _exit_status(returncode)
144
+ finally:
145
+ heartbeat.stop()
146
+ for signum, handler in previous.items():
147
+ signal.signal(signum, handler)
148
+ if child is not None and child.poll() is None:
149
+ _stop_child(child)
150
+ _release(client, lease_id, box_label, lease.get('ttlSeconds') or ttl_seconds)
151
+
152
+
153
+ def _stop_child(child):
154
+ child.terminate()
155
+ try:
156
+ child.wait(timeout=TERMINATE_GRACE_SECONDS)
157
+ except subprocess.TimeoutExpired:
158
+ child.kill()
159
+ child.wait()
160
+
161
+
162
+ def _release(client, lease_id, box_label, ttl_seconds):
163
+ try:
164
+ client.release(lease_id)
165
+ except LagerError as exc:
166
+ click.secho(
167
+ f'Warning: lager did not release box {box_label}: {exc.problem} '
168
+ f'It is released automatically within {ttl_seconds} s.',
169
+ fg='yellow', err=True,
170
+ )
171
+ return
172
+ click.secho(f'Released box {box_label}.', err=True)
173
+
174
+
175
+ class _LeaseCommand(click.Command):
176
+ def format_usage(self, ctx, formatter):
177
+ formatter.write_usage(ctx.command_path, '[OPTIONS] -- COMMAND [ARGS]...')
178
+
179
+
180
+ def _make_client(server, org):
181
+ return LeaseClient(lease_client.resolve_server(server), org=org)
182
+
183
+
184
+ @click.command(
185
+ 'lease',
186
+ cls=_LeaseCommand,
187
+ context_settings={'ignore_unknown_options': True, 'allow_interspersed_args': False},
188
+ epilog=(
189
+ 'Exit status: the exit status of COMMAND. 75 if lager cannot lease a box '
190
+ '(COMMAND does not run), or if the lease ends while COMMAND runs.'
191
+ ),
192
+ )
193
+ @click.option('--pool', required=True, metavar='NAME',
194
+ help='Name of the pool. Get the name from the Pools page in Stout.')
195
+ @click.option('--ttl', 'ttl_seconds', type=click.IntRange(MIN_TTL_SECONDS, MAX_TTL_SECONDS),
196
+ default=DEFAULT_TTL_SECONDS, show_default=True, metavar='SECONDS',
197
+ help='Time that the lease stays active after the last renewal.')
198
+ @click.option('--context', 'context_pairs', multiple=True, metavar='KEY=VALUE',
199
+ help='Information that Stout shows with the lease, for example the '
200
+ 'URL of the CI run. Use up to 10 times.')
201
+ @click.option('--server', metavar='URL',
202
+ help='Lease server. Default: STOUT_URL, or the server of your one '
203
+ '`lager login` session.')
204
+ @click.option('--org', metavar='ORG',
205
+ help='Organization (id, slug or name), if your account is in more than one.')
206
+ @click.argument('command', nargs=-1, required=True, type=click.UNPROCESSED)
207
+ @click.pass_context
208
+ def lease(ctx, pool, ttl_seconds, context_pairs, server, org, command):
209
+ """Lease an available box from a pool, and run COMMAND on that box.
210
+
211
+ \b
212
+ Stout finds a box in the pool that is online and not in use, and locks
213
+ it for this run. COMMAND runs with LAGER_BOX set to that box, so every
214
+ lager command in it uses the leased box. Do not pass --box to them.
215
+ While COMMAND runs, lager renews the lease. When COMMAND stops, for any
216
+ reason, lager releases the box.
217
+
218
+ \b
219
+ Credentials: STOUT_TOKEN (for CI), or your `lager login` session.
220
+
221
+ \b
222
+ Examples:
223
+ lager lease --pool nrf52 -- lager python flash_and_test.py
224
+ lager lease --pool nrf52 --ttl 600 -- pytest tests/hardware
225
+ """
226
+ context = lease_client.parse_context(context_pairs)
227
+ client = _make_client(server, org)
228
+ ctx.exit(run_under_lease(client, pool, command, ttl_seconds=ttl_seconds, context=context))
@@ -77,6 +77,27 @@ def logout(auth_server_url):
77
77
  click.echo(f'Logged out of {target}.')
78
78
 
79
79
 
80
+ def _session_line(url, pinned):
81
+ """What the user can act on, not the access token's expiry.
82
+
83
+ The access token lapses every few minutes by design and renews silently,
84
+ so a lapsed one is only news if the renewal fails. A stored refresh
85
+ cookie does not prove the renewal works: the server can end the session
86
+ at any time. So an expired token is checked by renewing it, through the
87
+ same single-flight refresh every command uses.
88
+ """
89
+ if pinned:
90
+ return (f'not used: {gateway_auth.PINNED_TOKEN_ENV} is set, '
91
+ 'and commands send that token instead')
92
+ state = gateway_auth.check_session(url)
93
+ if state == gateway_auth.SESSION_ACTIVE:
94
+ return 'active'
95
+ if state == gateway_auth.SESSION_EXPIRED:
96
+ return f'expired. Run: lager login {url}'
97
+ return ('could not check: the auth server neither renewed it nor refused it. '
98
+ f'Try again later. If a box asks you to sign in, run: lager login {url}')
99
+
100
+
80
101
  @click.command(name='whoami')
81
102
  def whoami():
82
103
  """Show your access-gateway sign-in status.
@@ -93,19 +114,9 @@ def whoami():
93
114
  click.echo(f'Details: {ACCESS_DOCS_URL}')
94
115
  return
95
116
 
117
+ pinned = gateway_auth.pinned_token()
96
118
  for s in status:
97
119
  who = s['email'] or 'unknown user'
98
120
  click.secho(f'{s["url"]}', fg='cyan')
99
121
  click.echo(f' Signed in as: {who}')
100
- # Report what the user can act on, not the short-lived access token's
101
- # expiry (which lapses every few minutes by design and refreshes
102
- # silently). A stored refresh means you're good to go; without one, a
103
- # lapsed token can't renew and you must sign in again.
104
- exp = s['expires_in']
105
- if exp is not None and exp >= 0:
106
- state = 'active'
107
- elif s['refreshable']:
108
- state = 'active (renews automatically)'
109
- else:
110
- state = f'expired — run: lager login {s["url"]}'
111
- click.echo(f' Session: {state}')
122
+ click.echo(f' Session: {_session_line(s["url"], pinned)}')
@@ -128,7 +128,21 @@ _refresh_locks_guard = threading.Lock()
128
128
  # one. That also stops the memo outliving a test, which is the only way a
129
129
  # process here ever changes stores -- without it, one test's dead server
130
130
  # silently suppressed the next test's refresh.
131
- _refresh_failed = set()
131
+ #
132
+ # The value says why it failed, REFRESH_REJECTED or REFRESH_UNAVAILABLE, so
133
+ # `lager whoami` can tell a session the server refused from one it could not
134
+ # check. Every caller that only needs "did it fail" reads membership.
135
+ _refresh_failed = {}
136
+
137
+ # The auth server answered and refused the refresh cookie: the session is
138
+ # over, and only `lager login` starts a new one. The reference auth server
139
+ # answers 401 for every refusal (missing, expired, revoked, reused, past its
140
+ # maximum age); 403 is a CSRF or policy refusal of the same cookie.
141
+ REFRESH_REJECTED = 'rejected'
142
+ # No verdict on the session: the server did not answer, answered with an
143
+ # error of its own (5xx, rate limit), or answered 200 without a token.
144
+ REFRESH_UNAVAILABLE = 'unavailable'
145
+ _REJECTED_STATUSES = (401, 403)
132
146
 
133
147
 
134
148
  def _failed_key(url):
@@ -448,7 +462,11 @@ def clear_login(url=None):
448
462
 
449
463
 
450
464
  def _refresh_access_token(url, entry):
451
- """Ask the auth server for a fresh access token, or return None.
465
+ """Ask the auth server for a fresh access token.
466
+
467
+ Returns ``(token, None)`` on success, else ``(None, reason)`` with
468
+ reason REFRESH_REJECTED (the server refused the cookie) or
469
+ REFRESH_UNAVAILABLE (no verdict). Only a 401 or 403 is a refusal.
452
470
 
453
471
  Retries once, but ONLY when the request never reached the server and
454
472
  failed fast: the server rotates the refresh token on every successful
@@ -464,7 +482,8 @@ def _refresh_access_token(url, entry):
464
482
  """
465
483
  cookies = entry.get('cookies') or {}
466
484
  if not cookies:
467
- return None
485
+ # Nothing to renew with: as final as a refusal.
486
+ return None, REFRESH_REJECTED
468
487
  resp = None
469
488
  for _ in range(2):
470
489
  try:
@@ -475,23 +494,27 @@ def _refresh_access_token(url, entry):
475
494
  )
476
495
  break
477
496
  except requests.ConnectTimeout:
478
- return None
497
+ return None, REFRESH_UNAVAILABLE
479
498
  except requests.ConnectionError:
480
499
  continue
481
500
  except requests.RequestException:
482
- return None
483
- if resp is None or resp.status_code != 200:
484
- return None
501
+ return None, REFRESH_UNAVAILABLE
502
+ if resp is None:
503
+ return None, REFRESH_UNAVAILABLE
504
+ if resp.status_code in _REJECTED_STATUSES:
505
+ return None, REFRESH_REJECTED
506
+ if resp.status_code != 200:
507
+ return None, REFRESH_UNAVAILABLE
485
508
  try:
486
509
  access_token = resp.json().get('accessToken')
487
- except ValueError:
488
- return None
510
+ except (ValueError, AttributeError):
511
+ return None, REFRESH_UNAVAILABLE
489
512
  if not access_token:
490
- return None
513
+ return None, REFRESH_UNAVAILABLE
491
514
  # Replay-safe: merge any rotated cookies the server handed back.
492
515
  rotated = {**cookies, **requests.utils.dict_from_cookiejar(resp.cookies)}
493
516
  save_login(url, access_token, rotated)
494
- return access_token
517
+ return access_token, None
495
518
 
496
519
 
497
520
  def access_token_for(url, *, allow_refresh=True, min_remaining_fraction=None):
@@ -569,10 +592,10 @@ def access_token_for(url, *, allow_refresh=True, min_remaining_fraction=None):
569
592
  return fresh
570
593
  if _failed_key(url) in _refresh_failed:
571
594
  return _usable(entry, margin=False)
572
- refreshed = _refresh_access_token(url, entry)
595
+ refreshed, reason = _refresh_access_token(url, entry)
573
596
  if refreshed:
574
597
  return refreshed
575
- _refresh_failed.add(_failed_key(url))
598
+ _refresh_failed[_failed_key(url)] = reason
576
599
  return _usable(entry, margin=False)
577
600
 
578
601
 
@@ -673,6 +696,43 @@ def auth_status():
673
696
  return out
674
697
 
675
698
 
699
+ SESSION_ACTIVE = 'active'
700
+ SESSION_EXPIRED = 'expired'
701
+ SESSION_UNCHECKED = 'unchecked'
702
+
703
+
704
+ def check_session(url):
705
+ """Whether the stored session for `url` can still get a token.
706
+
707
+ Returns SESSION_ACTIVE, SESSION_EXPIRED (the server refused the refresh,
708
+ or there is nothing to refresh with: only `lager login` helps), or
709
+ SESSION_UNCHECKED (the server gave no verdict). Contacts the server only
710
+ when the stored access token has expired, and then only through
711
+ `access_token_for`, so the refresh stays single-flight and its rotation
712
+ is saved: a second refresh path would spend the cookie on its own.
713
+
714
+ A stored refresh cookie alone proves nothing. The server can end the
715
+ session at any time, and the cookie carries no expiry the CLI can read,
716
+ so `auth_status`'s ``refreshable`` cannot answer this.
717
+
718
+ With a pinned token every command sends that instead of the stored
719
+ session, and `access_token_for` returns it without looking at the
720
+ store, so the answer is SESSION_UNCHECKED.
721
+ """
722
+ if pinned_token():
723
+ return SESSION_UNCHECKED
724
+ entry = _load_store().get('authServers', {}).get(url)
725
+ token = (entry or {}).get('accessToken')
726
+ if token and _token_expires_at(token) > time.time():
727
+ return SESSION_ACTIVE
728
+ if not (entry or {}).get('cookies'):
729
+ return SESSION_EXPIRED
730
+ if access_token_for(url):
731
+ return SESSION_ACTIVE
732
+ reason = _refresh_failed.get(_failed_key(url))
733
+ return SESSION_EXPIRED if reason == REFRESH_REJECTED else SESSION_UNCHECKED
734
+
735
+
676
736
  # ---------------------------------------------------------------------------
677
737
  # Login
678
738
  # ---------------------------------------------------------------------------
@@ -1039,11 +1099,19 @@ def handle_gateway_upstream_error(response, box_ip):
1039
1099
  if headers.get(UPSTREAM_ERROR_HEADER) != UPSTREAM_UNAVAILABLE:
1040
1100
  return
1041
1101
  upstream = headers.get(UPSTREAM_HEADER) or 'the lager container'
1102
+ # Retry comes first because the common cause is brief. A box service
1103
+ # exits on purpose to recover a wedged USB device, and its supervisor has
1104
+ # it listening again within seconds (lager.util.self_restart). Leading
1105
+ # with "update or reinstall" sent people to rebuild a box that would
1106
+ # have answered the next request.
1042
1107
  raise GatewayUpstreamUnavailable(
1043
1108
  f'The lager service behind box {box_ip}\'s gateway does not answer.',
1044
- cause=f'The gateway is up, but {upstream} did not accept its connection: '
1045
- 'the lager container is stopped, still starting, or failed to start.',
1046
- fixes=[f'Update the box: lager update --box {box_ip}',
1109
+ cause=f'The gateway is up, but {upstream} did not accept its connection. '
1110
+ 'Usually the service restarts itself to recover a USB device and '
1111
+ 'answers again in a few seconds. Otherwise, the lager container '
1112
+ 'is stopped or failed to start.',
1113
+ fixes=['Retry in a few seconds.',
1114
+ f'If it keeps failing, update the box: lager update --box {box_ip}',
1047
1115
  f'If it has no lager container at all, reinstall: lager install --ip {box_ip}',
1048
1116
  'Or update Lager from the control plane that manages the box.'],
1049
1117
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lager-cli
3
- Version: 0.62.0
3
+ Version: 0.64.0
4
4
  Summary: Lager CLI - Box and Docker connectivity
5
5
  Home-page: https://github.com/lagerdata/lager
6
6
  Author: Lager Data
@@ -11,6 +11,7 @@ errors.py
11
11
  exceptions.py
12
12
  gateway_auth.py
13
13
  gateway_tunnel.py
14
+ lease_client.py
14
15
  main.py
15
16
  pyproject.toml
16
17
  run_record.py
@@ -29,6 +30,7 @@ update_check.py
29
30
  ./exceptions.py
30
31
  ./gateway_auth.py
31
32
  ./gateway_tunnel.py
33
+ ./lease_client.py
32
34
  ./main.py
33
35
  ./run_record.py
34
36
  ./safe_unpickle.py
@@ -113,6 +115,7 @@ update_check.py
113
115
  ./commands/utility/exec_.py
114
116
  ./commands/utility/install.py
115
117
  ./commands/utility/install_wheel.py
118
+ ./commands/utility/lease.py
116
119
  ./commands/utility/login.py
117
120
  ./commands/utility/logs.py
118
121
  ./commands/utility/uninstall.py
@@ -244,6 +247,7 @@ commands/utility/defaults.py
244
247
  commands/utility/exec_.py
245
248
  commands/utility/install.py
246
249
  commands/utility/install_wheel.py
250
+ commands/utility/lease.py
247
251
  commands/utility/login.py
248
252
  commands/utility/logs.py
249
253
  commands/utility/uninstall.py