Repository navigation
Expand file tree
/
Copy pathcontrol_session.py
More file actions
822 lines (754 loc) · 41.9 KB
/
Copy pathcontrol_session.py
File metadata and controls
822 lines (754 loc) · 41.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
"""Cancellable owner-bound admission over an adapter's live byte channel.
The transport process belongs to this context. It never restores sessions,
replays actions, or carries owner authority in a public ID or environment value.
"""
from __future__ import annotations
import argparse
import json
import os
import queue
import subprocess
import sys
import threading
import time
import uuid
import machine_control as mc
SCHEMA = "machine-control-admission/v2"
CHANNEL_SCHEMA = "machine-control-admission-channel/v2"
def usable_browser_profiles(target, selector=None):
"""Enabled, connected profiles the person allowed, optionally one named."""
mc.require_selected_claim(target)
_, result, _ = mc.run_adapter(target, ["control", '{"operation":"browser.profiles"}'], accept_json_failure=True)
value = mc.validate_resident(result, target["platform"])
data = value.get("data") or {}
profiles = data.get("profiles", [])
approved = data.get("approvedProfiles", [])
return [profile["profileId"] for profile in profiles if profile.get("enabled") is True
and profile.get("connected") is True and profile.get("profileId") in approved
and (selector is None or selector in (profile.get("profileId"), profile.get("name")))]
def resolve_browser_profile(target, selector=None):
"""Resolve once before admission; the owner always names an exact profile."""
candidates = usable_browser_profiles(target, selector)
if len(candidates) != 1:
raise mc.ClientError("browser_profile_selection_required",
"Choose one enabled, connected profile allowed in Machine Control")
return candidates[0]
def _browser_needs_no_prompt(target):
"""Whether Browser access is on Automatic, from resident status.
None means an older resident that does not report its admission state.
"""
_, parsed, _ = mc.run_adapter(target, ["control", '{"operation":"status"}'], accept_json_failure=True)
data = mc.validate_resident(parsed, target["platform"]).get("data")
admission = data.get("admission") if isinstance(data, dict) else None
surfaces = admission.get("surfaces") if isinstance(admission, dict) else None
if not isinstance(surfaces, dict):
return None
browser = surfaces.get("browser") if isinstance(surfaces.get("browser"), dict) else {}
return browser.get("mode") == "automatic" and browser.get("expired") is not True
def quiet_browser_calls(target, build, *, reason, settle=3):
"""Run one background browser operation in every usable profile, or not at all.
Housekeeping never waits on a person or another owner: under Ask first,
pending approval, or while the profile is busy, it raises and the claim's
lease remains the backstop. build(profile) returns the
request, with no profile for the legacy direct route.
"""
first = build(None)
request = mc.with_browser_owner(target, first, mc.require_selected_claim(target))
_, parsed, _ = mc.run_adapter(target, ["control", json.dumps(request, separators=(",", ":"))],
accept_json_failure=True)
value = mc.validate_resident(parsed, target["platform"])
data = value.get("data")
if value.get("errorCode") != "control_session_required" or not isinstance(
data.get("controlSession") if isinstance(data, dict) else None, dict):
return [value]
if _browser_needs_no_prompt(target) is False:
raise mc.ClientError("approval_required", "Browser access asks first; housekeeping does not prompt")
profiles = usable_browser_profiles(target)
if not profiles:
raise mc.ClientError("browser_profile_unavailable", "No enabled, connected, allowed browser profile")
with ControlSession(target, reason=reason, surfaces=["browser"], profile_ids=profiles,
operations=[first["operation"]], wait=settle, duration=60, renew=False) as session:
deadline = time.monotonic() + settle
while True:
view = session.status()
if view["state"] in {"offered", "active"}:
break
if view["state"] in {"waiting_for_approval", "ended"} or time.monotonic() >= deadline:
code = ("approval_required" if view["state"] == "waiting_for_approval"
else view.get("terminalReason") or "control_ended" if view["state"] == "ended"
else "browser_owner_unavailable")
raise mc.ClientError(code, f"Browser housekeeping skipped while {view['state']}")
time.sleep(0.25)
session.wait()
return [mc.validate_resident(session.call(build(profile)), target["platform"]) for profile in profiles]
def release_claim_tabs(target, claim_id):
"""Release the tabs one ending claim attached, in every usable profile."""
return _release_summary(quiet_browser_calls(
target, lambda profile: {"operation": "browser.release", "ownerClaimId": claim_id,
**({"browserProfileId": profile} if profile else {})},
reason="Release browser tabs of an ending claim"))
def refresh_claim_tabs(target):
"""Carry a renewed claim's lease to its tabs with one owned observation."""
results = quiet_browser_calls(
target, lambda profile: {"operation": "browser.tabs", **({"browserProfileId": profile} if profile else {})},
reason="Extend browser tabs of a renewed claim")
summary = {"accepted": all(result.get("accepted") is True for result in results)}
errors = sorted({result["errorCode"] for result in results if result.get("errorCode")})
if errors:
summary["errorCode"] = errors[0]
return summary
def _release_summary(results):
summary = {"accepted": all(result.get("accepted") is True for result in results)}
errors = sorted({result["errorCode"] for result in results if result.get("errorCode")})
if errors:
summary["errorCode"] = errors[0]
datas = [result["data"] for result in results if isinstance(result.get("data"), dict)]
summary["released"] = summary["accepted"] and all(data.get("released") is True for data in datas)
for key in ("releasedTabs", "retainedTabs", "abandonedDialogs", "unconfirmedDetaches"):
tabs = [tab for data in datas for tab in data.get(key, []) if isinstance(tab, int)]
if tabs:
summary[key] = tabs
return summary
def complete_session_handoff(target, request, refusal):
"""Negotiate only an explicit, provably undispatched ownership refusal.
Never replay unknown delivery or fall back after channel failure. Legacy
providers without this declaration keep their existing command behavior.
"""
if refusal.get("accepted") is not False or refusal.get("errorCode") != "control_session_required":
return refusal, None
data = refusal.get("data")
requirement = data.get("controlSession") if isinstance(data, dict) else None
if requirement is None:
return refusal, None
if refusal.get("delivery") != "refused" or refusal.get("effect") != "refused" \
or refusal.get("uncertainty") != "none" or refusal.get("retrySafety") != "safe_not_dispatched":
return refusal, None
if not isinstance(requirement, dict) or requirement.get("schema") != SCHEMA \
or requirement.get("surface") not in {"desktop", "browser"}:
raise mc.ClientError("admission_unsupported", "Resident requires an unsupported control session")
if request.get("operation") == "browser.endpoint":
raise mc.ClientError("retained_owner_required",
"Request browser.endpoint through control stream or a retained ControlSession; "
"keep that owner open while using the target-loopback WebSocket")
started = time.monotonic()
profile_ids = None
if requirement["surface"] == "browser":
profile_ids = [resolve_browser_profile(target, request.get("browserProfileId"))]
request = {**request, "browserProfileId": profile_ids[0]}
with ControlSession(target, reason="CLI computer operation", surfaces=[requirement["surface"]],
profile_ids=profile_ids, operations=[request["operation"]]) as session:
session.wait()
value = mc.validate_resident(session.call(request), target["platform"])
return value, int((time.monotonic() - started) * 1000)
def validate_view(value, *, schema=SCHEMA):
if not isinstance(value, dict) or value.get("schema") != schema:
raise mc.ClientError("invalid_admission_status", "Invalid admission status")
states = {"waiting_for_approval", "waiting_for_resource", "paused", "announcing", "offered", "active", "ended"}
if value.get("state") not in states or not isinstance(value.get("intentId"), str) \
or not value["intentId"] or not isinstance(value.get("blockingReasons"), list) \
or any(not isinstance(reason, str) for reason in value["blockingReasons"]):
raise mc.ClientError("invalid_admission_status", "Invalid admission state")
for key in ("revision", "offerGeneration"):
if type(value.get(key)) is not int or value[key] < 0:
raise mc.ClientError("invalid_admission_status", "Invalid admission generation")
generations = value.get("resourceGenerations")
if not isinstance(generations, dict) or any(not isinstance(key, str) or type(number) is not int or number < 0 for key, number in generations.items()):
raise mc.ClientError("invalid_admission_status", "Invalid resource generations")
if value["state"] == "active" and (not isinstance(value.get("sessionId"), str) or not value["sessionId"] or not generations):
raise mc.ClientError("invalid_admission_status", "Active admission has no fence")
if value.get("requestSequencing") not in (None, "strict"):
raise mc.ClientError("admission_unsupported", "Unsupported admission request ordering")
if value.get("renewal") not in (None, "owner_connection/v1"):
raise mc.ClientError("admission_unsupported", "Unsupported admission renewal")
return value
class ControlSession:
_admission_schema = SCHEMA
def _validate_view(self, value):
return validate_view(value, schema=self._admission_schema)
def __init__(self, target, *, reason, surfaces=("desktop",), scopes=None,
profile_ids=None, operations=None, wait=300, duration=300, prepared_console=False, renew=None):
if type(prepared_console) is not bool or (renew is not None and type(renew) is not bool):
raise mc.ClientError("invalid_admission_request", "Invalid prepared console option")
if scopes is not None:
raise mc.ClientError("legacy_scope_contract_unsupported", "Admission v2 uses surfaces and an optional typed operation set")
if not reason or len(reason) > 240 or type(wait) is not int or not 1 <= wait <= 14400 \
or type(duration) is not int or not 1 <= duration <= 900:
raise mc.ClientError("invalid_admission_request", "Invalid control admission options")
if renew and duration < 15:
raise mc.ClientError("invalid_admission_request", "Automatic renewal requires an interval of at least 15 seconds")
mc.require_selected_claim(target)
if not isinstance(surfaces, (list, tuple)):
raise mc.ClientError("invalid_admission_request", "Choose Desktop and/or Browser")
selected = list(surfaces)
if not selected or len(set(selected)) != len(selected) or any(surface not in {"desktop", "browser"} for surface in selected):
raise mc.ClientError("invalid_admission_request", "Choose Desktop and/or Browser")
if prepared_console and selected != ["desktop"]:
raise mc.ClientError("invalid_admission_request", "Prepared console requires Desktop")
if "browser" in selected and profile_ids is None:
profile_ids = [resolve_browser_profile(target)]
profile_ids = list(profile_ids or [])
if len(profile_ids) > 64 or len(set(profile_ids)) != len(profile_ids) or any(not isinstance(profile, str) or not profile or len(profile) > 128 for profile in profile_ids):
raise mc.ClientError("invalid_admission_request", "Choose exact browser profiles")
if operations is not None and (not isinstance(operations, (list, tuple)) or not 1 <= len(operations) <= 64 or
any(not isinstance(operation, str) or not operation for operation in operations)):
raise mc.ClientError("invalid_admission_request", "Choose typed operations")
self.profile_ids = profile_ids
self.surfaces = selected
self._start_transport(target, "channel", CHANNEL_SCHEMA, "control.cancel")
try:
request = dict(operation="control.open", schema=SCHEMA, reason=reason, surfaces=selected, profileIds=profile_ids,
waitSeconds=wait, durationSeconds=duration)
if operations is not None:
request["operations"] = list(operations)
if prepared_console:
request["preparedConsole"] = True
if target.get("_claimId"):
request["claimId"] = target["_claimId"]
self.view = self._validate_view(self._rpc(request, timeout=10))
self.sequenced = self.view.get("requestSequencing") == "strict"
except BaseException:
self.close(cancel=False)
raise
self.deadline = time.monotonic() + wait
# Keep finite watchdog leases, but do not impose a task cutoff on a
# healthy retained owner. Explicit True requires provider support;
# the default negotiates it, and False requests finite ownership.
self.renew_required = renew is True
self.renew_duration = duration if renew is not False and duration >= 15 else None
self.heartbeat = threading.Thread(target=self._keepalive, daemon=True)
self.heartbeat.start()
def _start_transport(self, target, operation, response_schema, cancel_operation):
"""Shared bounded byte transport; subclasses retain their own authority."""
self.target = {**target}
self._profile_selection_checked = False
self.response_schema = response_schema
self.cancel_operation = cancel_operation
self.renew_duration = None
self.renew_required = False
self.sequenced = False
self.request_sequence = 0
command = mc.resolved_adapter_command(target)
if command is None:
raise mc.ClientError("adapter_unavailable", "Control adapter unavailable")
try:
self.process = subprocess.Popen([*command, operation], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, env={**os.environ, **target.get("environment", {})})
except OSError:
raise mc.ClientError("control_transport_unavailable", "Control transport unavailable")
self.pending = {}
self.lock = threading.Lock()
self.writes = threading.Lock()
self.stopped = threading.Event()
self.failure = None
self.view = None
self.parent = os.getppid()
self.reader = threading.Thread(target=self._read, daemon=True)
self.reader.start()
def _fail(self, error):
with self.lock:
if self.failure is None:
self.failure = error
entries = list(self.pending.values())
self.pending.clear()
for entry in entries:
entry.put(error)
def _read(self):
try:
while not self.stopped.is_set():
line = self.process.stdout.readline(4 * 1024 * 1024 + 1)
if not line or not line.endswith(b"\n") or len(line) > 4 * 1024 * 1024:
raise mc.ClientError("control_transport_closed", "Control transport closed or exceeded its frame limit")
value = json.loads(line)
if not isinstance(value, dict) or value.get("schema") != self.response_schema \
or type(value.get("accepted")) is not bool or not isinstance(value.get("requestId"), str):
raise mc.ClientError("admission_unsupported", "This route does not expose a compatible admission channel")
with self.lock:
entry = self.pending.pop(value["requestId"], None)
if entry is None:
raise mc.ClientError("invalid_control_response", "Unexpected control response")
entry.put(value)
except (OSError, ValueError, mc.ClientError) as error:
self._fail(error if isinstance(error, mc.ClientError) else mc.ClientError("invalid_control_response", "Invalid control response"))
def _rpc(self, request, *, timeout=5):
identifier = uuid.uuid4().hex
response = queue.Queue(maxsize=1)
with self.lock:
if self.failure:
raise self.failure
if self.stopped.is_set():
raise mc.ClientError("control_session_closed", "Control session is closed")
self.pending[identifier] = response
value = dict(request, requestId=identifier)
try:
with self.writes:
if self.sequenced:
value["requestSequence"] = self.request_sequence + 1
encoded = json.dumps(value, separators=(",", ":")).encode() + b"\n"
if len(encoded) > 65536:
with self.lock:
self.pending.pop(identifier, None)
raise mc.ClientError("invalid_control_request", "Control request exceeds 64 KiB")
if self.sequenced:
self.request_sequence += 1
self.process.stdin.write(encoded)
self.process.stdin.flush()
reply = response.get(timeout=timeout)
except (OSError, ValueError, queue.Empty):
error = mc.ClientError("control_transport_timeout", "Control response unavailable; action was not replayed")
self._fail(error)
raise error
if isinstance(reply, BaseException):
raise reply
if reply["accepted"] is not True:
# Typed refusal data, such as caller_not_verified's callerHost,
# stays visible to the caller; the request is never replayed.
data = reply.get("data")
raise mc.ClientError(reply.get("errorCode") or "control_refused", "Control request refused",
data=data if isinstance(data, dict) else None)
return reply.get("data")
def _keepalive(self):
while not self.stopped.wait(1):
if os.getppid() != self.parent:
self._fail(mc.ClientError("owner_disconnected", "Control owner exited"))
self.close(cancel=False)
return
try:
mc.require_selected_claim(self.target)
current = self._validate_view(self._rpc({"operation": "control.heartbeat"}))
self.view = current
if current['state'] == 'ended':
raise mc.ClientError(current.get('terminalReason') or 'control_ended', 'Control intent ended')
if self.renew_duration and current['state'] == 'active' \
and current.get('renewal') == 'owner_connection/v1' \
and current.get('activeRemainingSeconds', float('inf')) <= self.renew_duration / 3:
self.renew(self.renew_duration)
except mc.ClientError as error:
self._fail(error)
self.close(cancel=False)
return
def status(self):
current = self._validate_view(self._rpc({"operation": "control.status"}))
self.view = current
return current
def wait(self):
"""Accept only a currently offered activation; never replay old work."""
deadline = None
while True:
view = self.status()
if deadline is None:
# A resumed task has a fresh server-bounded waiting period.
# Pin it once per wait call so repeated polls cannot extend it.
budget = view.get("waitRemainingSeconds")
if type(budget) in (int, float) and 0 <= budget <= 14400:
deadline = time.monotonic() + budget
else:
deadline = self.deadline
if view["state"] == "ended":
raise mc.ClientError(view.get("terminalReason") or "control_ended", "Control intent ended")
if view["state"] == "active":
if self.renew_required and view.get('renewal') != 'owner_connection/v1':
raise mc.ClientError('control_renewal_unavailable', 'This provider does not support renewable owners')
return view
if view["state"] == "offered":
mc.require_selected_claim(self.target)
try:
accepted = self._validate_view(self._rpc({"operation":"control.accept", "offerGeneration":view["offerGeneration"]}))
self.view = accepted
if self.renew_required and accepted.get('renewal') != 'owner_connection/v1':
raise mc.ClientError('control_renewal_unavailable', 'This provider does not support renewable owners')
return accepted
except mc.ClientError as error:
if error.code not in {"stale_activation_offer", "admission_changed"}:
raise
remaining = deadline - time.monotonic()
if remaining <= 0:
raise mc.ClientError("wait_deadline_exceeded", "Control wait deadline exceeded")
self.stopped.wait(min(0.25, remaining))
def call(self, request):
"""Dispatch once with the current owner and resource fence."""
request = mc.with_browser_owner(self.target, request, mc.require_selected_claim(self.target))
view = self.status()
if view["state"] != "active":
raise mc.ClientError("control_interrupted", "Control is paused or ended; wait for a fresh session before issuing new work", data=view)
if request.get("operation", "").startswith("browser.") and request.get("operation") != "browser.profiles" and "browser" in getattr(self, "surfaces", []):
if "browserProfileId" not in request and len(self.profile_ids) == 1:
request = {**request, "browserProfileId": self.profile_ids[0]}
if "browserProfileId" in request and not self._profile_selection_checked:
capabilities = self._rpc({"operation":"control.dispatch", "sessionId":view["sessionId"],
"resourceGenerations":view["resourceGenerations"],
"request":{"operation":"capabilities"}}, timeout=10)
mc.require_browser_profile_selection(capabilities)
self._profile_selection_checked = True
result = self._rpc({"operation":"control.dispatch", "sessionId":view["sessionId"],
"resourceGenerations":view["resourceGenerations"], "request":request}, timeout=60)
if not isinstance(result, dict) or type(result.get("accepted")) is not bool:
raise mc.ClientError("invalid_control_response", "Invalid controlled operation result")
return result
def cancel(self):
return self._validate_view(self._rpc({"operation":"control.cancel"}))
def renew(self, duration=900):
"""Extend this live owner under remaining approval; never reopen it."""
if type(duration) is not int or not 1 <= duration <= 900:
raise mc.ClientError("invalid_renewal_duration", "Renewal must be 1-900 seconds")
mc.require_selected_claim(self.target)
view = self.status()
if view["state"] != "active" or view.get("renewal") != "owner_connection/v1":
raise mc.ClientError("control_renewal_unavailable", "This owner cannot renew")
try:
renewed = self._validate_view(self._rpc({"operation":"control.renew",
"sessionId":view["sessionId"], "resourceGenerations":view["resourceGenerations"],
"durationSeconds":duration}, timeout=10))
if renewed["state"] != "active":
raise mc.ClientError("control_renewal_failed", "Owner ended during renewal")
self.view = renewed
return renewed
except BaseException as error:
if isinstance(error, mc.ClientError):
self._fail(error)
self.close()
raise
def close(self, *, cancel=True):
if self.stopped.is_set():
return
if cancel and self.view is not None and self.failure is None:
try:
self._rpc({"operation":self.cancel_operation}, timeout=1)
except mc.ClientError:
pass
self.stopped.set()
self._fail(mc.ClientError("control_session_closed", "Control session closed"))
# Closing stdin releases the live adapter connection; bounded reaping
# prevents an abandoned local proxy from extending ownership.
try:
self.process.stdin.close()
except OSError:
pass
try:
self.process.wait(timeout=3)
except subprocess.TimeoutExpired:
self.process.terminate()
try:
self.process.wait(timeout=2)
except subprocess.TimeoutExpired:
self.process.kill(); self.process.wait()
self.process.stdout.close()
def __enter__(self):
return self
def __exit__(self, *exception):
self.close()
def raw_channel_frames(target, frames, *, reply_timeout=15.0):
"""Diagnostic parity probe: send frames unchanged, return raw replies.
Like `desktop raw`, nothing is validated, translated, renewed or retried;
conformance tooling inspects the resident's own framing. A closed channel
is reported as {"event": "closed"} after the frame that caused it.
"""
import queue
import threading
mc.require_selected_claim(target)
command = mc.resolved_adapter_command(target)
if command is None:
raise mc.ClientError("adapter_unavailable", "Control adapter unavailable")
process = subprocess.Popen([*command, "channel"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, env={**os.environ, **target.get("environment", {})})
replies, buffer, eof = [], b"", False
# select() accepts only sockets on Windows; a reader thread waits on the
# pipe portably and reports EOF as an empty chunk.
chunks = queue.Queue()
def pump():
try:
while True:
chunk = os.read(process.stdout.fileno(), 65536)
chunks.put(chunk)
if not chunk:
return
except OSError:
chunks.put(b"")
threading.Thread(target=pump, daemon=True).start()
def next_chunk(timeout):
nonlocal eof
if eof:
return b""
try:
chunk = chunks.get(timeout=max(0.0, timeout))
except queue.Empty:
return None
eof = not chunk
return chunk
def read_line(deadline):
nonlocal buffer
while b"\n" not in buffer:
remaining = deadline - time.monotonic()
if remaining <= 0:
return None
chunk = next_chunk(remaining)
if chunk is None:
return None
if not chunk:
return b""
buffer += chunk
line, buffer = buffer.split(b"\n", 1)
return line
try:
for frame in frames:
try:
process.stdin.write(json.dumps(frame, separators=(",", ":")).encode() + b"\n")
process.stdin.flush()
except (BrokenPipeError, OSError):
replies.append({"event": "closed"}); break
line = read_line(time.monotonic() + reply_timeout)
if line is None:
replies.append({"event": "timeout"}); continue
if line == b"":
replies.append({"event": "closed"}); break
try:
replies.append(json.loads(line))
except ValueError:
replies.append({"event": "invalid_frame"})
# A refusal that closes ownership must show up as EOF promptly.
if buffer == b"":
chunk = next_chunk(0.5)
if chunk == b"":
replies.append({"event": "closed"}); break
if chunk:
buffer += chunk
finally:
try:
process.stdin.close()
except OSError:
pass
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill(); process.wait()
return replies
# Refusals whose condition also ends the owner. Residents end it through
# their policy shortly after replying, so the view may still read active.
OWNER_ENDING_REFUSALS = frozenset({"audit_storage_unavailable", "locked_use_guard_failed"})
def ended_owner(session, error_code, *, settle=3.0):
"""Report whether a refused action also ended this owner; never retry it."""
deadline = time.monotonic() + (settle if error_code in OWNER_ENDING_REFUSALS else 0)
while True:
try:
view = session.status()
except mc.ClientError:
# The heartbeat records the ended view before it closes the owner.
view = session.view
if isinstance(view, dict) and view.get("state") == "ended":
return {"state": "ended", "terminalReason": view.get("terminalReason")}
if session.failure is not None or time.monotonic() >= deadline:
return None
time.sleep(0.25)
# A stream answers these from ordinary read-only status, not its owner channel.
STREAM_STATUS_OPERATIONS = frozenset({"status", "desktop.status"})
# Channel refusals raised before any provider dispatch; the owner stays live.
CHANNEL_UNDISPATCHED_REFUSALS = frozenset({"operation_not_permitted_by_control_channel"})
def stream_status(target, request):
if set(request) != {"operation"}:
return undispatched_refusal(request, mc.ClientError(
"invalid_control_request", "Stream status takes no other fields"))
_, parsed, _ = mc.run_adapter(target, ["control", '{"operation":"status"}'], accept_json_failure=True)
return mc.validate_resident(parsed, target["platform"])
def undispatched_refusal(request, error):
return {"accepted": False, "errorCode": error.code, "message": str(error),
"operation": str(request.get("operation", "")), "delivery": "refused", "effect": "refused",
"uncertainty": "none", "retrySafety": "safe_not_dispatched",
**({"data": error.data} if isinstance(error.data, dict) else {})}
def stream_continues(session, value):
"""Keep a live stream after a refusal that provably dispatched nothing.
Uncertain delivery, unknown or partial effects and any ended owner still
end the stream; nothing is ever replayed.
"""
if value.get("accepted") is not False:
return value.get("delivery") not in {"unknown", "refused"} and value.get("effect") not in {"unknown", "partial"}
if value.get("controlOwner") is not None or session.failure is not None:
return False
if value.get("uncertainty") != "none":
return False
# Refused before dispatch, or a read that never delivers anything, such
# as control_generation_changed when covered unlock replaces the desktop
# generation just after a prepared owner starts.
return (value.get("delivery") == "refused" and value.get("retrySafety") == "safe_not_dispatched") or \
(value.get("delivery") == "not_applicable" and value.get("effect") == "not_applicable")
KEEP_UNLOCKED_MAXIMUM = 14400
def keep_unlocked(target, arguments, *, clock=time.monotonic):
"""Hold a locked console unlocked behind covers for a bounded interval.
This composes the existing prepared-console Desktop owner; it adds no
authority. The owner renews itself, and it ends with an independent relock
on --for expiry, a signal, owner loss, Stop, Pause, deliberate physical
input, or claim expiry.
"""
import signal
parser = argparse.ArgumentParser(prog="machine-control control keep-unlocked")
parser.add_argument("--for", dest="hold", required=True, help="How long to hold, for example 30m or 2h (max 4h)")
parser.add_argument("--reason", required=True)
parser.add_argument("--wait", default="2m")
options = parser.parse_args(arguments)
hold = mc.parse_duration_seconds(options.hold)
if not 60 <= hold <= KEEP_UNLOCKED_MAXIMUM:
raise mc.ClientError("invalid_duration", "--for must be between 1m and 4h")
claim = mc.require_selected_claim(target)
remaining = None
if isinstance(claim, dict) and isinstance(claim.get("expiresAt"), str):
from datetime import datetime, timezone
expires = datetime.fromisoformat(claim["expiresAt"].replace("Z", "+00:00"))
remaining = (expires - datetime.now(timezone.utc)).total_seconds()
if type(remaining) in (int, float) and remaining < hold and not os.environ.get("MACHINE_CONTROL_SCOPE_FILE"):
raise mc.ClientError("claim_shorter_than_hold",
"The claim expires before --for ends; renew it, or run this inside `machine-control run`, which renews it",
data={"claimRemainingSeconds": int(remaining), "holdSeconds": hold})
state = stream_status(target, {"operation": "status"}).get("data") or {}
if state.get("desktopState") != "locked":
raise mc.ClientError("console_not_locked",
"keep-unlocked holds a locked console unlocked behind covers; this console is " +
str(state.get("desktopState", "unknown")))
stop = threading.Event()
ending = {"reason": None}
def requested(signum, _frame):
ending["reason"] = "signal_" + signal.Signals(signum).name.lower()
stop.set()
signals = (signal.SIGINT, signal.SIGTERM, getattr(signal, "SIGHUP", None))
previous = {number: signal.signal(number, requested) for number in signals if number is not None}
try:
with ControlSession(target, reason=options.reason, surfaces=["desktop"],
wait=mc.parse_duration_seconds(options.wait), duration=300,
prepared_console=True) as session:
session.wait()
# Activation replaces the desktop generation once; a read that
# races it is refused without delivery. Never retry an effect.
for _ in range(10):
value = session.call({"operation": "capabilities"})
if value.get("accepted") or value.get("errorCode") != "control_generation_changed":
break
time.sleep(0.5)
if not value.get("accepted"):
raise mc.ClientError(value.get("errorCode") or "prepared_console_unavailable",
"The prepared console did not become usable", data=value)
# Covers precede the native unlock observation by a moment.
settle = time.monotonic() + 15
while True:
observed = (stream_status(target, {"operation": "status"}).get("data") or {}).get("desktopState")
if observed == "unlocked" or time.monotonic() >= settle:
break
time.sleep(0.5)
deadline = clock() + hold
print(json.dumps({"event": "unlocked", "desktopState": observed, "holdSeconds": hold,
"controlSessionId": session.view.get("sessionId"),
"note": "The console relocks when this command exits"}), flush=True)
while not stop.wait(1):
if clock() >= deadline:
ending["reason"] = "duration_elapsed"
break
if session.failure is not None:
ending["reason"] = getattr(session.failure, "code", "owner_failed")
break
if isinstance(session.view, dict) and session.view.get("state") == "ended":
ending["reason"] = session.view.get("terminalReason") or "control_ended"
break
finally:
for number, handler in previous.items():
signal.signal(number, handler)
reason = ending["reason"] or "owner_failed"
print(json.dumps({"event": "ended", "reason": reason, "relock": "requested_by_owner_end"}), flush=True)
return 0 if reason == "duration_elapsed" or reason.startswith("signal_") else 1
def handle_control(alias, target, arguments):
if arguments[:1] == ["keep-unlocked"]:
return keep_unlocked(target, arguments[1:])
if arguments == ["status"]:
return mc.send_resident_request(alias, target, {"operation":"status"})
if arguments == ["frames"]:
frames = []
for line in sys.stdin.buffer.read(1024 * 1024 + 1).splitlines():
if line.strip():
try:
frames.append(json.loads(line))
except ValueError:
raise mc.ClientError("invalid_control_request", "Each frame must be one JSON object") from None
if len(frames) > 64:
raise mc.ClientError("invalid_control_request", "At most 64 diagnostic frames")
for reply in raw_channel_frames(target, frames):
print(json.dumps(reply, separators=(",", ":")), flush=True)
return 0
parser = argparse.ArgumentParser(prog="machine-control control")
parser.add_argument("command", choices=["call", "stream"])
parser.add_argument("json", nargs="?")
parser.add_argument("--reason", required=True)
parser.add_argument("--surface", action="append", choices=["desktop", "browser"])
parser.add_argument("--profile", action="append", help="Exact browser profile bound to this owner")
parser.add_argument("--wait", default="5m")
parser.add_argument("--duration", default="5m", help="Finite lease interval; supported live owners renew automatically")
parser.add_argument("--prepared-console", action="store_true")
renewal = parser.add_mutually_exclusive_group()
renewal.add_argument("--renew", action="store_true", default=None, help="Require automatic renewal support (negotiated by default)")
renewal.add_argument("--no-renew", action="store_false", dest="renew", help="End this owner after the finite --duration interval")
options = parser.parse_args(arguments)
if (options.command == "call") != (options.json is not None):
raise mc.ClientError("usage", "call requires JSON; stream reads JSON lines from stdin")
def parse(text):
try:
request = json.loads(text)
except ValueError:
raise mc.ClientError("invalid_control_request", "Control action must be valid JSON") from None
if not isinstance(request, dict) or not isinstance(request.get("operation"), str) or not request["operation"]:
raise mc.ClientError("invalid_control_request", "Control action must be an object with an operation")
return mc.translate_request(target["platform"], request)
def requests():
if options.command == "call":
yield parse(options.json)
return
while True:
line = sys.stdin.buffer.readline(65537)
if not line:
return
if len(line) > 65536:
raise mc.ClientError("invalid_control_request", "Control request exceeds 64 KiB")
yield parse(line)
try:
pending = iter(requests())
first = next(pending, None)
if first is None:
return 0
profiles = [resolve_browser_profile(target, profile) for profile in options.profile] if options.profile else None
with ControlSession(target, reason=options.reason,
surfaces=options.surface or ["desktop"], profile_ids=profiles,
operations=[first["operation"]] if options.command == "call" else None,
wait=mc.parse_duration_seconds(options.wait), duration=mc.parse_duration_seconds(options.duration),
prepared_console=options.prepared_console, renew=options.renew) as session:
session.wait()
request = first
while True:
stream = options.command == "stream"
if stream and request["operation"] in STREAM_STATUS_OPERATIONS:
# Read-only discovery needs no owner; the channel refuses it.
value = stream_status(target, request)
else:
try:
value = session.call(request)
except mc.ClientError as error:
if not stream or error.code not in CHANNEL_UNDISPATCHED_REFUSALS or session.failure is not None:
raise
value = undispatched_refusal(request, error)
if not value["accepted"]:
owner = ended_owner(session, value.get("errorCode"))
if owner is not None:
value = {**value, "controlOwner": owner}
# Stream replies are one JSON line each, available before the
# next input. Confirmed delivery with an unverifiable effect
# needs a follow-up observation under the same owner. Preserve
# that uncertainty; never mistake it for lost delivery.
if stream:
print(json.dumps(value, separators=(",", ":")), flush=True)
else:
mc.emit(value)
if stream and stream_continues(session, value):
request = next(pending, None)
if request is None:
return 0
continue
if not value["accepted"] or value.get("delivery") in {"unknown", "refused"} \
or value.get("effect") in {"unknown", "partial"}:
return 1
request = next(pending, None)
if request is None:
return 0
except KeyboardInterrupt:
raise mc.ClientError("cancelled", "Control request cancelled", exit_code=130)