Files
ukmesh/scripts/full-dev/qualification/test_resource_limits.py
T

209 lines
13 KiB
Python

"""Effective cgroup and native swap evidence, without Docker or host mutations."""
from pathlib import Path
from tempfile import TemporaryDirectory
import copy
import json
import subprocess
import unittest
from unittest.mock import patch
import resources
from test_qualification import resource_rows
class EffectiveMemoryEvidence(unittest.TestCase):
def files(self, directory):
group=Path(directory)
for name,value in {'memory.max':'1024','memory.swap.max':'0','memory.swap.current':'12',
'memory.swap.events':'high 0\nmax 2\nfail 1'}.items():
(group/name).write_text(value+'\n')
return group
def test_actual_limits_are_separate_from_docker_intent_and_existing_swap(self):
with TemporaryDirectory() as temporary:
group=self.files(temporary)
item=resources.memory_limit_evidence(group,{'Memory':1024,'MemorySwap':1024})
self.assertTrue(resources.memory_limits_match(item))
self.assertEqual(item['swap_current_bytes'],12)
self.assertEqual(item['swap_events'],{'high':0,'max':2,'fail':1})
for actual in ('max','1024'):
(group/'memory.swap.max').write_text(actual)
item=resources.memory_limit_evidence(group,{'Memory':1024,'MemorySwap':1024})
self.assertEqual(item['memory_swap_limit_bytes'],1024)
self.assertEqual(item['effective_swap_max'],'max' if actual=='max' else 1024)
self.assertFalse(resources.memory_limits_match(item))
(group/'memory.swap.max').write_text('0')
(group/'memory.max').write_text('max')
self.assertFalse(resources.memory_limits_match(resources.memory_limit_evidence(group,{'Memory':1024,'MemorySwap':1024})))
def test_missing_and_malformed_kernel_values_cannot_be_zero_or_unlimited(self):
for filename in ('memory.max','memory.swap.max','memory.swap.current','memory.swap.events'):
with self.subTest(filename=filename),TemporaryDirectory() as temporary:
group=self.files(temporary);(group/filename).unlink()
with self.assertRaises(FileNotFoundError):resources.memory_limit_evidence(group,{'Memory':1024,'MemorySwap':1024})
for filename,bad in [('memory.max','-1'),('memory.swap.max',''),('memory.swap.current','max'),
('memory.swap.current','-2'),('memory.swap.current','True'),
('memory.swap.events','max -1'),('memory.swap.events',''),
('memory.swap.events','max 1\nmax 2'),('memory.swap.events','max 1 extra')]:
with self.subTest(filename=filename,bad=bad),TemporaryDirectory() as temporary:
group=self.files(temporary);(group/filename).write_text(bad)
with self.assertRaises(ValueError):resources.memory_limit_evidence(group,{'Memory':1024,'MemorySwap':1024})
def test_requested_default_unlimited_or_extra_swap_is_not_no_swap(self):
with TemporaryDirectory() as temporary:
group=self.files(temporary)
for config in ({'Memory':1024,'MemorySwap':0},{'Memory':1024,'MemorySwap':-1},
{'Memory':1024,'MemorySwap':2048},{'Memory':0,'MemorySwap':0}):
with self.subTest(config=config):
self.assertFalse(resources.memory_limits_match(resources.memory_limit_evidence(group,config)))
for config in ({'Memory':True,'MemorySwap':1024},{'Memory':1024,'MemorySwap':-2}):
with self.assertRaises(ValueError):resources.memory_limit_evidence(group,config)
def test_cgroup_membership_cannot_escape_root_or_fallback_to_v1(self):
with TemporaryDirectory() as temporary:
root=Path(temporary);proc=root/'proc';(proc/'123').mkdir(parents=True)
groups=root/'cgroups';(groups/'owned').mkdir(parents=True)
file=proc/'123/cgroup';file.write_text('0::/owned\n')
self.assertEqual(resources.container_cgroup(123,proc_root=proc,cgroup_root=groups),groups/'owned')
(groups/'linked').symlink_to(root)
for text in ('0::/../../outside','0::/linked/outside','1:memory:/owned','0::owned','0::/owned\n0::/other'):
with self.subTest(text=text):
file.write_text(text)
with self.assertRaises((ValueError,RuntimeError)):resources.container_cgroup(123,proc_root=proc,cgroup_root=groups)
with self.assertRaises(ValueError):resources.container_cgroup(True,proc_root=proc,cgroup_root=groups)
def test_collector_reads_kernel_files_when_docker_claims_no_swap(self):
with TemporaryDirectory() as temporary:
group=self.files(temporary)
for name,value in {'memory.current':'100','memory.stat':'inactive_file 10\nanon 70\nfile 30',
'memory.events':'oom_kill 0','io.stat':'8:0 rbytes=1 wbytes=2 rios=3 wios=4',
'cpu.stat':'usage_usec 5'}.items():(group/name).write_text(value+'\n')
(group/'memory.swap.max').write_text('512')
item={'Name':'/api','Id':'id','RestartCount':0,'State':{'Pid':123,'OOMKilled':False,'StartedAt':'now'},
'HostConfig':{'Memory':1024,'MemorySwap':1024}}
def docker(args):
if args == ['ps', '-q']:
return type('Result', (), {'stdout': b'id\n'})()
self.assertEqual(args, ['inspect', '--type', 'container', '--format',
resources.CONTAINER_SAMPLE_TEMPLATE, 'id'])
return type('Result', (), {'stdout': (json.dumps(item) + '\n').encode()})()
with patch.object(resources,'docker',side_effect=docker),patch.object(resources,'container_cgroup',return_value=group):
row=resources.container_samples()[0]
self.assertEqual(row['working_bytes'],90)
self.assertEqual(row['effective_swap_max'],512)
self.assertFalse(resources.memory_limits_match(row))
def test_native_swap_pss_is_separate_and_missing_coverage_explicit(self):
with TemporaryDirectory() as temporary:
root=Path(temporary)
for pid,text in {1:'Pss: 10 kB\nSwapPss: 3 kB\n',2:'Pss: 20 kB\n',3:'Pss: 5 kB\nSwapPss: 2 kB\n'}.items():
(root/str(pid)).mkdir();(root/str(pid)/'smaps_rollup').write_text(text)
got=resources.process_memory({1,3,99},proc_root=root)
self.assertEqual(got['total_bytes'],15*1024)
self.assertEqual(got['swap_total_bytes'],5*1024)
self.assertTrue(got['swap_coverage_complete'])
got=resources.process_memory({1,2},proc_root=root)
self.assertEqual(got['total_bytes'],30*1024)
self.assertEqual(got['swap_total_bytes'],3*1024)
self.assertIsNone(got['swap_processes']['2'])
self.assertFalse(got['swap_coverage_complete'])
def test_mixed_verifier_reports_only_its_own_pss_and_swap(self):
with TemporaryDirectory() as temp:
root = Path(temp)
entry = root / 'soakDatabaseLookups.js'
harness = {'processes': {'10': 1300, '11': 90, '12': 300, '13': 55},
'swap_processes': {'10': 600, '11': 0, '12': 500, '13': None}}
argv = {'10': ['python', 'controller'], '11': ['node', '--optimize-for-size', str(entry)],
'12': ['node', 'different.js', str(entry)], '13': ['cat', str(entry)]}
for pid, args in argv.items():
(root / pid).mkdir()
(root / pid / 'cmdline').write_bytes(b'\0'.join(arg.encode() for arg in args))
self.assertEqual(resources.mixed_client_memory(harness, entry, proc_root=root),
{'pid': 11, 'pss_bytes': 90, 'swap_pss_bytes': 0})
(root / '11/cmdline').unlink()
self.assertIsNone(resources.mixed_client_memory(harness, entry, proc_root=root))
def test_process_family_survives_an_exiting_process(self):
with TemporaryDirectory() as temporary:
root = Path(temporary)
for pid in ('1', '2', '3'):
(root / pid).mkdir()
def status(path):
if path.parent.name == '2':
raise ProcessLookupError(3, 'No such process')
return {'PPid': int(path.parent.name == '3')}
with patch.object(resources, 'key_values', side_effect=status):
self.assertEqual(resources.process_family({1}, proc_root=root), {1, 3})
self.assertEqual(resources.process_family(set(), proc_root=root / 'absent'), set())
def test_host_pressure_reports_linux_averages_and_tolerates_unavailable_counters(self):
with TemporaryDirectory() as directory:
root = Path(directory)
self.assertEqual(resources.host_pressure(root), {})
(root/'io').write_text('some avg10=5.67 avg60=25.60 avg300=11.34 total=91234567890\n'
'full avg10=0.01 avg60=0.10 avg300=0.06 total=727\n')
(root/'memory').write_text('full avg10=bad total=0\n')
self.assertEqual(resources.host_pressure(root), {'io': {
'some': {'avg10': 5.67, 'avg60': 25.60, 'avg300': 11.34, 'total_us': 91234567890},
'full': {'avg10': 0.01, 'avg60': 0.10, 'avg300': 0.06, 'total_us': 727}}})
def test_resource_failures_name_the_probe_and_withhold_command_arguments(self):
private = 'synthetic-private-argument'
timeout = subprocess.TimeoutExpired([private], 120, output=private.encode())
with patch.object(resources, 'docker', side_effect=timeout), self.assertRaises(RuntimeError) as listing:
resources.container_samples()
self.assertEqual(str(listing.exception), 'Docker resident listing failed (subprocess exceeded 120s)')
ok = subprocess.CompletedProcess([], 0, stdout=b'first\nsecond\n')
failed = subprocess.CalledProcessError(17, [private], stderr=private.encode())
with patch.object(resources, 'docker', side_effect=[ok, failed]), self.assertRaises(RuntimeError) as inspecting:
resources.container_samples()
self.assertIn('Docker resident inspection failed', str(inspecting.exception))
self.assertIn('exit 17', str(inspecting.exception))
self.assertNotIn(private, str(inspecting.exception))
for label, replies in [('ukmesh', [timeout]), ('beacon', ['{}', timeout])]:
with self.subTest(label=label), patch.object(resources, 'sql', side_effect=replies):
with self.assertRaises(RuntimeError) as database:
resources.database_samples({'ukmesh': private, 'beacon': private})
self.assertEqual(str(database.exception), f'{label} database counters failed (subprocess exceeded 120s)')
def test_process_exit_still_fails_required_resident_coverage(self):
item = {'Name': '/api', 'State': {'Pid': 123}}
def docker(args):
output = b'id\n' if args == ['ps', '-q'] else (json.dumps(item) + '\n').encode()
return type('Result', (), {'stdout': output})()
with patch.object(resources, 'docker', side_effect=docker), patch.object(
resources, 'container_cgroup', side_effect=ProcessLookupError(3, 'No such process')):
missing = resources.container_samples()
self.assertEqual(missing, [])
rows = resource_rows()
rows[-1]['containers'] = missing
result = resources.evaluate(rows, duration=2400, warmup=120, required_containers={'api'})
self.assertFalse(result['passed'])
self.assertFalse(result['checks']['complete_resident_coverage'])
self.assertEqual(result['unstable_containers'], ['api'])
def test_acceptance_checks_effective_caps_and_keeps_host_swap_thresholds(self):
rows=resource_rows();self.assertTrue(resources.evaluate(rows,duration=2400,warmup=120)['passed'])
for key,value in [('effective_swap_max','max'),('effective_swap_max',1024),('effective_memory_max',1),
('memory_swap_limit_bytes',0),('swap_current_bytes',None),('swap_events',{})]:
bad=copy.deepcopy(rows);bad[-1]['containers'][0][key]=value
result=resources.evaluate(bad,duration=2400,warmup=120)
self.assertFalse(result['passed']);self.assertEqual(result['effective_limit_mismatches'],['api'])
bad=copy.deepcopy(rows);del bad[0]['containers'][0]['effective_swap_max']
self.assertFalse(resources.evaluate(bad,duration=2400,warmup=120)['passed'])
for current in (0,256*1024*1024):
bad=copy.deepcopy(rows);bad[-1]['host']['swap_used_bytes']+=129*resources.MIB
bad[-1]['containers'][0]['swap_current_bytes']=current
result=resources.evaluate(bad,duration=2400,warmup=120)
self.assertFalse(result['checks']['swap_growth'])
self.assertTrue(result['checks']['effective_container_memory_limits'])
if __name__=='__main__':unittest.main()