authoravatarclover caruso<git@paperclover.net>2026-11-17 03:08:16-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-22 00:44:02-08:00
loge919bac8ce86abf4941d4e27ca5ec20527d82cbc
treee7dffc0c8719127b01f13b5bb71905212e416e2e
parentb30417da1ffc324c910e68dceba6a37585c3fb7c
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Distinguish guest agent rejection from an unavailable agent

Report missing guest files, denied access, full disks, unsupported commands and failed program starts without echoing guest diagnostics. Treat uncertain agent timeouts as timeouts and retain process-result lookup semantics. Assisted-by: gpt-6.1-sol

2 files changed, 69 insertions(+), 4 deletions(-)

tools/computer-test.py+44
...@@ -100,6 +100,46 @@ class GuestCancellation(unittest.TestCase):...@@ -100,6 +100,46 @@ class GuestCancellation(unittest.TestCase):
100 computer.write_file('fixture', 'owned-file', data)100 computer.write_file('fixture', 'owned-file', data)
101 self.assertEqual(b''.join(written), data)101 self.assertEqual(b''.join(written), data)
102102
103 def test_agent_rejections_report_causes_without_echoing_guest_diagnostics(self):
104 private = 'private-guest-diagnostic'
105 cases = [
106 ('guest-exec', 'GenericError', 'Failed to execute child process (Invalid argument)', 'program could not start'),
107 ('guest-file-open', 'GenericError', 'The system cannot find the file specified.', 'file was not found'),
108 ('guest-file-open', 'GenericError', 'No such file or directory', 'file was not found'),
109 ('guest-file-open', 'GenericError', 'Permission denied', 'guest denied access'),
110 ('guest-file-write', 'GenericError', 'No space left on device', 'disk is full'),
111 ('guest-info', 'CommandNotFound', 'Unknown command', 'does not support'),
112 ('guest-info', 'GenericError', 'Unknown failure', 'rejected the operation'),
113 ]
114 for operation, kind, diagnostic, expected in cases:
115 for structured in [False, True]:
116 reply = Mock(stdout=json.dumps({'error': {'class': kind, 'desc': private + ': ' + diagnostic}}) if structured else '',
117 stderr='' if structured else 'error: guest agent command failed: ' + private + ': ' + kind + ': ' + diagnostic)
118 with self.subTest(operation=operation, diagnostic=diagnostic, structured=structured), \
119 patch.object(computer.subprocess, 'run', return_value=reply), \
120 self.assertRaisesRegex(ValueError, expected) as failure:
121 computer.qga('fixture', operation)
122 self.assertNotIn(private, str(failure.exception))
123
124 def test_agent_timeouts_are_uncertain_and_do_not_repeat_the_command(self):
125 replies = [Mock(stdout='', stderr="error: guest agent command timed out: guest agent didn't respond to command within '10' seconds"),
126 Mock(stdout='', stderr='error: Timed out during operation: guest agent command'),
127 computer.subprocess.TimeoutExpired(['virsh'], 15)]
128 for reply in replies:
129 with self.subTest(reply=type(reply)), patch.object(computer.subprocess, 'run') as run:
130 if isinstance(reply, Exception):
131 run.side_effect = reply
132 else:
133 run.return_value = reply
134 with self.assertRaisesRegex(TimeoutError, 'Inspect the operation status'):
135 computer.qga('fixture', 'guest-exec', path='owned-program')
136 run.assert_called_once()
137
138 def test_agent_success_is_not_overridden_by_stderr(self):
139 reply = Mock(stdout='{"return":{"pid":123}}', stderr='guest agent command failed: stale warning')
140 with patch.object(computer.subprocess, 'run', return_value=reply):
141 self.assertEqual(computer.qga('fixture', 'guest-exec'), {'pid': 123})
142
103 def test_windows_powershell_reads_redirected_output_without_console_capture(self):143 def test_windows_powershell_reads_redirected_output_without_console_capture(self):
104 with patch.object(computer, 'write_file'), patch.object(computer, 'guest_exec', return_value=b''), patch.object(computer, 'read_file', return_value=b'file output'):144 with patch.object(computer, 'write_file'), patch.object(computer, 'guest_exec', return_value=b''), patch.object(computer, 'read_file', return_value=b'file output'):
105 self.assertEqual(computer.powershell('fixture', "Write-Output 'file output'"), b'file output')145 self.assertEqual(computer.powershell('fixture', "Write-Output 'file output'"), b'file output')
...@@ -211,6 +251,10 @@ class GuestCancellation(unittest.TestCase):...@@ -211,6 +251,10 @@ class GuestCancellation(unittest.TestCase):
211 status = computer.handle('fixture', {'action':'status'})251 status = computer.handle('fixture', {'action':'status'})
212 self.assertEqual(status['readiness'], 'worker_starting')252 self.assertEqual(status['readiness'], 'worker_starting')
213 self.assertIn('Sign in', status['worker_error'])253 self.assertIn('Sign in', status['worker_error'])
254 work.side_effect = TimeoutError('The guest agent timed out.')
255 status = computer.handle('fixture', {'action':'status'})
256 self.assertEqual(status['readiness'], 'worker_starting')
257 self.assertIn('timed out', status['worker_error'])
214 work.side_effect = None258 work.side_effect = None
215 work.return_value = {'runtimes':['bash']}259 work.return_value = {'runtimes':['bash']}
216 status = computer.handle('fixture', {'action':'status'})260 status = computer.handle('fixture', {'action':'status'})
tools/vm-computer.py+25-4
...@@ -42,17 +42,38 @@ def qga(name, operation, **arguments):...@@ -42,17 +42,38 @@ def qga(name, operation, **arguments):
42 payload = json.dumps({'execute': operation, 'arguments': arguments})42 payload = json.dumps({'execute': operation, 'arguments': arguments})
43 # Virsh reads stdin so guest scripts and file contents never enter host argv.43 # Virsh reads stdin so guest scripts and file contents never enter host argv.
44 command = 'qemu-agent-command ' + shlex.quote(name) + ' --timeout 10 ' + shlex.quote(payload) + '\n'44 command = 'qemu-agent-command ' + shlex.quote(name) + ' --timeout 10 ' + shlex.quote(payload) + '\n'
45 result = subprocess.run(['virsh', '--quiet', '--connect', 'qemu:///system'], input=command,45 try:
46 capture_output=True, text=True, timeout=remaining(15))46 result = subprocess.run(['virsh', '--quiet', '--connect', 'qemu:///system'], input=command,
47 capture_output=True, text=True, timeout=remaining(15))
48 except subprocess.TimeoutExpired:
49 raise TimeoutError('The guest agent timed out. Inspect the operation status before retrying.') from None
50 details = result.stderr.casefold()
51 rejected = False
47 for line in result.stdout.splitlines():52 for line in result.stdout.splitlines():
48 if line.startswith('{'):53 if line.startswith('{'):
49 value = json.loads(line)54 value = json.loads(line)
50 if 'return' in value:55 if 'return' in value:
51 return value['return']56 return value['return']
57 if 'error' in value:
58 details += json.dumps(value['error']).casefold()
59 rejected = True
52 if operation == 'guest-exec-status' and any(line.endswith((60 if operation == 'guest-exec-status' and any(line.endswith((
53 f"PID {arguments['pid']} does not exist", 'PID ld does not exist', 'PID lld does not exist', "Invalid parameter 'pid'"))61 f"PID {arguments['pid']} does not exist", 'PID ld does not exist', 'PID lld does not exist', "Invalid parameter 'pid'"))
54 for line in result.stderr.splitlines()):62 for line in result.stderr.splitlines()):
55 raise ProcessLookupError('The guest process result is unavailable. Check the VM before retrying.')63 raise ProcessLookupError('The guest process result is unavailable. Check the VM before retrying.')
64 if any(message in details for message in ('guest agent command timed out', 'timed out waiting', 'timed out during operation')):
65 raise TimeoutError('The guest agent timed out. Inspect the operation status before retrying.')
66 if rejected or 'guest agent command failed' in details or 'unable to execute qemu agent command' in details:
67 if operation == 'guest-exec' and 'failed to execute child process' in details:
68 raise ValueError('The program could not start. Check its path, arguments, permissions, and architecture.')
69 for fragments, message in [
70 (('no such file or directory', 'cannot find the file specified', 'cannot find the path specified'), 'The guest file was not found. Check its path.'),
71 (('permission denied', 'access is denied'), 'The guest denied access. Check the file permissions and security policy.'),
72 (('no space left on device', 'not enough space on the disk', 'disk is full'), 'The guest disk is full. Free space before retrying.'),
73 (('commandnotfound', 'has not been found', 'not supported'), 'The guest agent does not support this operation. Update the agent.')]:
74 if any(fragment in details for fragment in fragments):
75 raise ValueError(message)
76 raise ValueError('The guest agent rejected the operation. Check its arguments, permissions, and installed tools.')
56 raise ValueError('The guest agent did not answer. Wait for the VM to finish starting, then retry.')77 raise ValueError('The guest agent did not answer. Wait for the VM to finish starting, then retry.')
5778
5879
...@@ -595,7 +616,7 @@ def handle(name, request, *, active_snapshot=None):...@@ -595,7 +616,7 @@ def handle(name, request, *, active_snapshot=None):
595 try:616 try:
596 info = qga(name, 'guest-info')617 info = qga(name, 'guest-info')
597 native_text = any(command['name'] == 'guest-exec' and command['enabled'] for command in info['supported_commands'])618 native_text = any(command['name'] == 'guest-exec' and command['enabled'] for command in info['supported_commands'])
598 except (ValueError, subprocess.TimeoutExpired):619 except (ValueError, TimeoutError):
599 native_text = False620 native_text = False
600 if request['action'] == 'status':621 if request['action'] == 'status':
601 return {**status, 'readiness': 'agent_unavailable', 'text_encoding': 'ascii',622 return {**status, 'readiness': 'agent_unavailable', 'text_encoding': 'ascii',
...@@ -608,7 +629,7 @@ def handle(name, request, *, active_snapshot=None):...@@ -608,7 +629,7 @@ def handle(name, request, *, active_snapshot=None):
608 try:629 try:
609 status.update(worker(name,platform,request))630 status.update(worker(name,platform,request))
610 status['readiness'] = 'ready'631 status['readiness'] = 'ready'
611 except ValueError as error:632 except (ValueError, TimeoutError) as error:
612 status['worker_error'] = str(error)633 status['worker_error'] = str(error)
613 return status634 return status
614 if request['action'] == 'input':635 if request['action'] == 'input':