validate_live_actions.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #!/usr/bin/env python3
  2. """At UEFI, verify idempotency, stale inputs, real directory I/O and missing EFI."""
  3. import argparse
  4. import asyncio
  5. import datetime
  6. import json
  7. from pathlib import Path
  8. import uuid
  9. import aiohttp
  10. class Client:
  11. def __init__(self, ws):
  12. self.ws, self.state = ws, None
  13. async def call(self, method, params):
  14. rid = uuid.uuid4().hex
  15. await self.ws.send_json({'v': 1, 'id': rid, 'method': method, 'params': params})
  16. async with asyncio.timeout(30):
  17. while True:
  18. frame = await self.ws.receive_json()
  19. if frame.get('event') == 'state':
  20. self.state = frame['result']
  21. if frame.get('id') == rid:
  22. if not frame.get('ok'):
  23. raise RuntimeError(str(frame.get('error')))
  24. return frame['result']
  25. async def command(self, payload):
  26. result = await self.call('StageAction', payload)
  27. async with asyncio.timeout(60):
  28. while result['state'] not in ('succeeded', 'failed', 'interrupted'):
  29. await asyncio.sleep(.2)
  30. result = await self.call('GetCommand', {'command_id': payload['command_id']})
  31. return result
  32. async def station(self):
  33. value = await self.call('GetState', {})
  34. return next(x for x in value['stations'] if x['station_id'] == 'S1')
  35. async def main():
  36. parser = argparse.ArgumentParser()
  37. parser.add_argument('--host', default='192.168.2.79:8080')
  38. parser.add_argument('--output', required=True)
  39. args = parser.parse_args()
  40. report = {'observed_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
  41. 'checks': [], 'passed': False, 'memory_verdict': 'NOT_TESTED'}
  42. def check(name, value, detail):
  43. report['checks'].append({'name': name, 'passed': bool(value), 'detail': detail})
  44. print(json.dumps({'name': name, 'passed': bool(value)}, ensure_ascii=False), flush=True)
  45. if not value:
  46. raise AssertionError(name)
  47. try:
  48. async with aiohttp.ClientSession() as session:
  49. async with session.ws_connect('http://' + args.host + '/ws') as full_ws, \
  50. session.ws_connect('http://' + args.host + '/ws?view=qt-clean') as clean_ws:
  51. full, clean = Client(full_ws), Client(clean_ws)
  52. info = await full.call('GetSystemInfo', {})
  53. report['system'] = info
  54. state = await clean.station()
  55. check('actual_uefi_ready', state['input']['ready'] and state['input']['stage'] == 'uefi',
  56. {'phase': state['phase'], 'boot_id': state['boot_id']})
  57. queue = await full.call('GetQueue', {'station_id': 'S1', 'limit': 100})
  58. started = next(x for x in queue['items'] if x['method'] == 'QtStartTest' and x['state'] == 'succeeded')
  59. boot = state['boot_id']
  60. duplicate = await clean.call('StartTest', {'station_id': 'S1', 'command_id': started['command_id']})
  61. check('duplicate_real_start_does_not_reboot', duplicate['state'] == 'succeeded'
  62. and duplicate['result']['boot_id'] == boot and (await clean.station())['boot_id'] == boot,
  63. duplicate)
  64. old = next(x for x in queue['items'] if x['method'] == 'QtStageAction'
  65. and x['arguments']['action'] == 'continue_uip')
  66. stale = await clean.command({'station_id': 'S1', 'command_id': 'stale-' + uuid.uuid4().hex,
  67. 'input_id': old['arguments']['input_id'], 'action': 'continue_uip'})
  68. check('stale_real_prompt_rejected', stale['state'] == 'failed'
  69. and stale['error']['code'] == 'FAILED_PRECONDITION', stale)
  70. state = await clean.station()
  71. listing = await clean.command({'station_id': 'S1', 'command_id': 'listing-' + uuid.uuid4().hex,
  72. 'input_id': state['input']['id'], 'action': 'list_uefi_files', 'path': 'FS0:\\EFI'})
  73. check('real_uefi_directory_read', listing['state'] == 'succeeded'
  74. and isinstance(listing['result'].get('files'), list), listing)
  75. state = await clean.station()
  76. missing = 'FS0:\\EFI\\__qt_missing_' + uuid.uuid4().hex + '.efi'
  77. mt = await clean.command({'station_id': 'S1', 'command_id': 'missing-' + uuid.uuid4().hex,
  78. 'input_id': state['input']['id'], 'action': 'start_mt', 'mt': {'efi_path': missing}})
  79. check('missing_efi_is_explicit_failure', mt['state'] == 'failed'
  80. and mt['error']['code'] == 'FAILED_PRECONDITION', mt)
  81. state = await clean.station()
  82. check('no_memory_pass_after_missing_efi', state['verdict'] != 'pass',
  83. {'verdict': state['verdict'], 'run_state': state['run_state']})
  84. # A harmless subsequent directory query proves that errors do not
  85. # corrupt the connection, while leaving the host at its Shell.
  86. listing2 = await clean.command({'station_id': 'S1', 'command_id': 'listing-' + uuid.uuid4().hex,
  87. 'input_id': state['input']['id'], 'action': 'list_uefi_files', 'path': 'FS0:\\EFI'})
  88. check('link_usable_after_rejected_efi', listing2['state'] == 'succeeded', listing2)
  89. report['passed'] = True
  90. except Exception as exc:
  91. report['error'] = type(exc).__name__ + ': ' + str(exc)
  92. print(report['error'], flush=True)
  93. finally:
  94. target = Path(args.output)
  95. target.parent.mkdir(parents=True, exist_ok=True)
  96. target.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
  97. return 0 if report['passed'] else 1
  98. if __name__ == '__main__':
  99. raise SystemExit(asyncio.run(main()))