test_hardware_review.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. """Regressions found in the first live handoff. No real device is contacted."""
  2. import asyncio
  3. import copy
  4. import json
  5. import os
  6. from pathlib import Path
  7. import sys
  8. import tempfile
  9. import unittest
  10. from unittest.mock import patch
  11. from stl_backend.config import load_settings
  12. from stl_backend.devices.hardware import HardwareDevice
  13. from stl_backend.engine import Bench
  14. from stl_backend.errors import BenchError
  15. from stl_backend.parsers import IncrementalSolParser
  16. ROOT = Path(__file__).resolve().parents[1]
  17. class HardwareReviewTests(unittest.IsolatedAsyncioTestCase):
  18. async def test_sdr_values_have_unknown_measurement_time_and_no_reading_is_not_empty_slot(self):
  19. class Device(HardwareDevice):
  20. async def _ipmi(self, *args):
  21. self.args = args
  22. return ('DIMM_CPU0_A_Temp | 98h | ok | 7.1 | 34 degrees C\n'
  23. 'DIMM_CPU0_B_Temp | 99h | ns | 7.1 | No Reading\n'
  24. 'CPU0_Temp | 9ah | ok | 7.1 | 52 degrees C\n')
  25. device = Device({"bmc": {"enabled": True, "host": "test-bmc"}})
  26. values = await device.read_bmc_dimms()
  27. self.assertEqual(device.args, ('sdr', 'type', 'Temperature'))
  28. self.assertEqual(len(values), 2)
  29. self.assertEqual(values[0]['value_c'], 34)
  30. self.assertEqual(values[0]['quality'], 'reported')
  31. self.assertGreater(values[0]['observed_unix_ms'], 0)
  32. self.assertEqual(values[1]['quality'], 'unavailable')
  33. self.assertNotIn('value_c', values[1])
  34. self.assertNotIn('present', values[1])
  35. async def test_idle_monitor_reads_only_and_start_without_thermal_is_rejected_before_run(self):
  36. class ReadOnlyDevice(HardwareDevice):
  37. async def bmc_read(self):
  38. return 'on'
  39. async def read_bmc_dimms(self):
  40. return [{'cpu': 0, 'channel': '0', 'slot': 'CPU0_A', 'source': 'bmc_sdr',
  41. 'value_c': 34, 'quality': 'unverified', 'observed_unix_ms': 0}]
  42. async def supply_set(self, on):
  43. raise AssertionError('A rejected run must not touch power')
  44. async def sol_start(self):
  45. raise AssertionError('Idle monitoring must never open SOL')
  46. with tempfile.TemporaryDirectory() as tmp:
  47. cfg = load_settings(ROOT / 'config/station0-live.json')
  48. cfg['data_dir'] = tmp
  49. with patch.dict(os.environ, {'STL_BMC_S1_PASSWORD': 'test-only'}), patch('stl_backend.engine.create_device', ReadOnlyDevice):
  50. bench = Bench(cfg)
  51. await bench.initialize()
  52. try:
  53. async with asyncio.timeout(1):
  54. while not bench.station('S1').snapshot['temperature']['dimms']:
  55. await asyncio.sleep(.01)
  56. snapshot = await bench.snapshot('S1')
  57. self.assertEqual(snapshot['bmc_state'], 'online')
  58. self.assertEqual(snapshot['server_power'], 'on')
  59. self.assertEqual(snapshot['temperature']['hood_air']['quality'], 'unknown')
  60. self.assertEqual(snapshot['sol_state'], 'offline')
  61. self.assertIn('温控板', snapshot['pending_instruction'])
  62. with self.assertRaisesRegex(BenchError, '温控板'):
  63. await bench.start_run({'command_id': 'incomplete-start', 'station_id': 'S1'})
  64. self.assertIsNone(bench.station('S1').run)
  65. self.assertEqual(await bench.store.unfinished_runs(), [])
  66. finally:
  67. await asyncio.wait_for(bench.close(), 2)
  68. async def test_sol_temperature_is_preserved_and_not_renewed_by_board_poll(self):
  69. with tempfile.TemporaryDirectory() as tmp:
  70. cfg = load_settings(ROOT / 'config/simulated.json')
  71. cfg['data_dir'] = tmp
  72. bench = Bench(cfg)
  73. await bench.initialize()
  74. try:
  75. rt = bench.station('S1')
  76. rt.run = {'run_id': 'R-test', 'dimms': [], 'tests': {}, 'verdict': 'pending', 'artifact_state': 'pending'}
  77. first = IncrementalSolParser().feed(b'[HD_RMTSensor]N0.C0.D0:42.5\r\n')[0]
  78. await bench._parsed_event(rt, first)
  79. before = copy.deepcopy(rt.snapshot['temperature']['dimms'][0])
  80. self.assertEqual(before['quality'], 'unavailable_in_phase')
  81. rt.uefi_ready = True
  82. bench._merge_sol_temperatures(rt)
  83. self.assertEqual(rt.snapshot['temperature']['dimms'][0]['quality'], 'unavailable_in_phase')
  84. rt.snapshot["sol_state"] = "online"
  85. for event in IncrementalSolParser().feed(b"UEFI Interactive Shell v2.2\nShell> \n"):
  86. await bench._parsed_event(rt, event)
  87. await bench._parsed_event(rt, first)
  88. valid = copy.deepcopy(rt.snapshot['temperature']['dimms'][0])
  89. self.assertEqual(valid['quality'], 'valid')
  90. rt.snapshot['temperature'].update(dimms=[], hood_air={'quality': 'read_error'})
  91. bench._merge_sol_temperatures(rt)
  92. self.assertEqual(rt.snapshot['temperature']['dimms'][0], valid)
  93. for item in rt.sol_temperatures.values():
  94. item['observed_unix_ms'] -= 60000
  95. bench._merge_sol_temperatures(rt)
  96. self.assertEqual(rt.snapshot['temperature']['dimms'][0]['quality'], 'stale')
  97. finally:
  98. rt.run = None
  99. await bench.close()
  100. async def test_live_profile_never_sends_unverified_commands(self):
  101. cfg = load_settings(ROOT / 'config/station0-live.json')
  102. profile = cfg['profiles']['cxmt-live-gnr']
  103. self.assertTrue(all(s.get('manual') for s in profile['steps']))
  104. self.assertTrue(all(not any(s.get(k) for k in ('send', 'use_stage1_commands', 'use_mt_command', 'append_enter')) for s in profile['steps']))
  105. self.assertEqual({s['test'] for s in profile['steps'] if 'test' in s}, {'rmt', 'amt', 'mt'})
  106. self.assertEqual(cfg['recipes'][0]['stage1_commands'], [])
  107. self.assertEqual(cfg['recipes'][0]['required_artifact_kinds'], ['memtest_html'])
  108. async def test_helper_requires_real_activation_and_password_is_not_in_argv(self):
  109. with tempfile.TemporaryDirectory() as tmp:
  110. stub = Path(tmp) / 'ipmitool'
  111. stub.write_text('#!/usr/bin/env python3\nimport os,sys,time\n'
  112. 'assert "-E" in sys.argv and "test-only-secret" not in sys.argv\n'
  113. 'assert os.environ["IPMI_PASSWORD"]=="test-only-secret"\n'
  114. 'time.sleep(.3)\n'
  115. 'os.write(1,b"[SOL Session operational. Use ~? for help]\\r\\nBIOS bytes")\n'
  116. 'os.write(1,os.read(0,8192))\n'
  117. 'time.sleep(30)\n')
  118. stub.chmod(0o755)
  119. env = dict(os.environ, PATH=tmp + os.pathsep + os.environ['PATH'],
  120. STL_SOL_HOST='example.invalid', STL_SOL_USER='test', STL_SOL_PASSWORD='test-only-secret')
  121. proc = await asyncio.create_subprocess_exec(sys.executable, str(ROOT / 'native/stl_sol_bridge.py'),
  122. stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env)
  123. try:
  124. self.assertEqual(json.loads(await proc.stderr.readline())['event'], 'connecting')
  125. with self.assertRaises(asyncio.TimeoutError):
  126. await asyncio.wait_for(proc.stderr.readline(), .1)
  127. self.assertEqual(json.loads(await asyncio.wait_for(proc.stderr.readline(), 2))['event'], 'ready')
  128. self.assertEqual(await asyncio.wait_for(proc.stdout.readexactly(10), 2), b'BIOS bytes')
  129. proc.stdin.write(b'help\r')
  130. await proc.stdin.drain()
  131. self.assertEqual(await asyncio.wait_for(proc.stdout.readexactly(5), 2), b'help\r')
  132. finally:
  133. proc.terminate()
  134. await asyncio.wait_for(proc.wait(), 4)
  135. async def test_helper_reports_busy_instead_of_ready_or_takeover(self):
  136. with tempfile.TemporaryDirectory() as tmp:
  137. stub = Path(tmp) / 'ipmitool'
  138. stub.write_text('#!/usr/bin/env python3\nimport os,time\nos.write(1,b"SOL payload already active on another session\\n")\ntime.sleep(30)\n')
  139. stub.chmod(0o755)
  140. env = dict(os.environ, PATH=tmp + os.pathsep + os.environ['PATH'],
  141. STL_SOL_HOST='example.invalid', STL_SOL_USER='test', STL_SOL_PASSWORD='test-only')
  142. proc = await asyncio.create_subprocess_exec(sys.executable, str(ROOT / 'native/stl_sol_bridge.py'),
  143. stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env)
  144. out, err = await asyncio.wait_for(proc.communicate(), 4)
  145. statuses = [json.loads(line) for line in err.splitlines()]
  146. self.assertEqual(out, b'')
  147. self.assertNotIn('ready', [s['event'] for s in statuses])
  148. self.assertEqual(statuses[-1], {'event': 'error', 'code': 1006})
  149. self.assertNotEqual(proc.returncode, 0)