Skip to contentSkip to conversation

rteval: Add multi stressor support

PATCH Superseded Sana Sharma 2 participants 3 messages Nov 11 – Nov 12

v5 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

PATCH v5 1/1 rteval: Add multi stressor support

Add the ability for rteval to take multiple stressors in one command to improve interface. The syntax works as follows:

--stressng-stressor cpu --stressng-stressor vm --stressng-workers 2 will use 2 workers for each stressor (in this case cpu and vm)

--stressng-stressors cpu,vm --stressng-workers 2 will use 2 workers for each stressor as in the above example

The second option exists to allow the user to access multiple stressors in an easier way.

Update the tests/test_stressng file to reflect these changes.

---
 rteval/modules/__init__.py       |  4 +-
 rteval/modules/loads/stressng.py | 79 +++++++++++++++++++++++++-------
 tests/test_stressng.py           |  4 +-
 3 files changed, 67 insertions(+), 20 deletions(-)
rteval/modules/__init__.py +2 -2
index 183efd8..abd88b6 100644
@@ -6,7 +6,6 @@
 import time
 from datetime import datetime
 import threading
-import argparse
 import libxml2
 from rteval.Log import Log
 from rteval.rtevalConfig import rtevalCfgSection
@@ -356,6 +355,7 @@ reference from the first import"""
             for (o, s) in list(opts.items()):
                 descr = 'descr' in s and s['descr'] or ""
                 metavar = 'metavar' in s and s['metavar'] or None
+                action = 'action' in s and s['action'] or 'store'
 
                 try:
                     default = cfg and getattr(cfg, o) or None
@@ -369,7 +369,7 @@ reference from the first import"""
 
                 grparser.add_argument(f'--{shortmod}-{o}',
                                          dest=f"{shortmod}___{o}",
-                                         action='store',
+                                         action=action,
                                          help='%s%s' % (descr,
                                                         default and ' (default: %s)' % default or ''),
                                          default=default,
rteval/modules/loads/stressng.py +63 -16

112 lines not on this page · raw message

tests/test_stressng.py +2 -2
index 6211fb3..9da3bcb 100644
@@ -41,14 +41,14 @@ class TestValidateStressor(unittest.TestCase):
            return_value=['cpu', 'vm'])
     def test_valid_passes(self, _):
         """Test that a valid stressor is accepted"""
-        stressng.validate_stressor('cpu')   # should not raise
+        stressng.validate_stressors('cpu, vm')   # should not raise
 
     @patch('rteval.modules.loads.stressng.get_valid_stressors',
            return_value=['cpu', 'vm'])
     def test_invalid_exits(self, _):
         """Test that an invalid stressor is rejected"""
         with self.assertRaises(SystemExit) as cm:
-            stressng.validate_stressor('bogus')
+            stressng.validate_stressors('bogus')
         self.assertEqual(cm.exception.code, 1)
 
 def main():
Signature · 1 line
2.56.0
#1 lore raw
Quoted 1 line · Sana Sharma

[PATCH v5] rteval: Add multi stressor support

Thanks for the v5, Sana. Moving validation into __init__ so sys.exit(1) runs on the main thread, the clean exit in validate_stressors(), and the subject fix all look good. Unfortunately the new 'workers' handling in __init__ introduces a regression that breaks the default run, so this needs another spin.

1) stressng now runs on every rteval invocation, even when no stressor was requested - and then crashes.

'workers' has a default of "0" in ModuleParameters(), and SetupModuleOptions() registers the option before argparse runs, so self.cfg.workers is "0" on every run whether or not the user asked for stress-ng. This block then unconditionally clears _donotrun:

rteval/modules/loads/stressng.py class Stressng(CommandLineLoad): · line 93

Quoted 9 lines
rteval/modules/loads/stressng.py +9 -0
+        if self.cfg.workers is not None:
+            try:
+                val = int(self.cfg.workers)
+                if val >= 0:
+                    workers = str(val)
+                    self._donotrun = False
+            except (ValueError, TypeError):
+                self._log(Log.WARN,"Stress-ng workers must be an int >= 0")
+                self._donotrun = True

So with no --stressng-stressor/--stressng-stressors, the stressor block above correctly sets _donotrun = True, and then this block immediately sets it back to False. Two consequences:

- stressng calls set_exclusive(), so once it is "will run", Start() calls set_donotrun() on the other loads - kcompile and hackbench get disabled.
- _WorkloadPrepare() then does for stressor in self.cfg.stressors with stressors=None -> TypeError: 'NoneType' object is not iterable, and the load thread dies.

The net effect is that a plain rteval -d ... (and make runit) with the default config no longer runs its normal loads. On main the no-stressor case leaves _donotrun = True and stressng simply opts out.

_donotrun should be decided only by whether a stressor was requested. The workers check should validate the value and, at most, set _donotrun = True on bad input - never clear it. Something like:

if requested is None:
self._donotrun = True
else:
self.cfg.stressors = validate_stressors(requested) self._donotrun = False

if self.cfg.workers is not None:
try:
if int(self.cfg.workers) < 0:
raise ValueError
except (ValueError, TypeError):
self._log(Log.WARN, "Stress-ng workers must be an int >= 0") self._donotrun = True

Note int() already rejects a negative only if you check it - the v5 if val >= 0: has no else, so --stressng-workers -1 passes silently and -1 is handed to stress-ng. The raise above closes that.

2) The 'workers is not None' guard I wrote out last time is still missing in _WorkloadPrepare():

rteval/modules/loads/stressng.py class Stressng(CommandLineLoad): · line 121

Quoted 4 lines
rteval/modules/loads/stressng.py +4 -0
+        stressors = self.cfg.stressors
+        workers = self.cfg.workers
+        for stressor in stressors:
+            self.args.extend([f'--{stressor}', workers])

If workers is ever None, self.args gets a None element, and the " ".join(self.args) in _WorkloadTask() raises TypeError (not caught by the except OSError there). The "0" default happens to mask this today, but it is fragile - please guard it as before:

workers = self.cfg.workers
for stressor in stressors:
self.args.append(f'--{stressor}')
if workers is not None:
self.args.append(workers)

Relatedly, the workers = str(val) computed in __init__ is dead - it is a local that is never read, since _WorkloadPrepare() goes back to self.cfg.workers. Either use the sanitized value or drop the assignment.

Minor:

- validate_stressors() docstring still says "Raises: ValueError", but it now prints and sys.exit(1)s. Please update it.

With (1) and (2) sorted this is close. Thanks again.

To make this easier to check against, I'm sending a test patch as a follow-up to this mail - it adds tests to tests/test_stressng.py that drive the Stressng class directly (not just the module functions), covering the _donotrun opt-out logic and the _WorkloadPrepare() arg building. Three of them fail on v5 as it stands and pin exactly (1) and (2) above; please fold them into your v6 and make them pass. The multi-stressor arg test already passes - it just keeps that behaviour from regressing later.

John

#2 lore raw

PATCH 1/1 rteval: Test stressng opt-out and arg building

In reply to Sana Sharma

The existing stressng tests only exercise the module-level functions get_valid_stressors() and validate_stressors(). Both the opt-out decision in Stressng.__init__() and the stress-ng command-line construction in _WorkloadPrepare() were untested, which is how recent regressions shipped green.

Add tests that drive the Stressng class itself, built from a real rtevalCfgSection (not a mock) so they follow the same path rteval-cmd uses. A make_stressng() helper disables logging and points build/report dirs at a temp dir so construction has no side effects, and the arg-building tests patch SysTopology for a deterministic topology.

Coverage:
- _donotrun must stay True when no stressor was requested, even though 'workers' always carries its "0" default from argparse;
- --stressng-stressors and repeated --stressng-stressor both opt in;
- negative and non-integer worker counts opt out rather than being passed to stress-ng;
- _WorkloadPrepare() must not place a None in self.args when no worker count is set (it would crash the " ".join() in _WorkloadTask());
- each stressor gets its own flag with the worker count.

These encode the intended behaviour and serve as acceptance criteria; three of them fail against the current multi-stressor series and pin the outstanding defects.

Assisted-by Claude:claude-opus-4-8
---
 tests/test_stressng.py | 128 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 128 insertions(+)
tests/test_stressng.py +128 -0
index 9da3bcb984e0..e9c0701569e5 100644
@@ -3,12 +3,54 @@
 # Copyright 2026 Sana Sharma <[email protected]>
 """ Unit tests for the new stressng input validation """
 
+import os
 import sys
+import shutil
+import tempfile
 import subprocess
 import unittest
 from unittest.mock import patch, MagicMock
 sys.path.insert(0,'.')
 from rteval.modules.loads import stressng
+from rteval.rtevalConfig import rtevalConfig
+from rteval.Log import Log
+
+
+_TEST_TMPDIRS = []
+
+
+def _cleanup_test_tmpdirs():
+    while _TEST_TMPDIRS:
+        shutil.rmtree(_TEST_TMPDIRS.pop(), ignore_errors=True)
+
+
+def make_stressng(**opts):
+    """Build a Stressng instance from a real rtevalCfgSection.
+
+    Mirrors how rteval-cmd wires up the module: a genuine config section
+    (not a mock), with logging disabled and build/report dirs pointed at a
+    temp dir so construction has no side effects on the tree.  'workers'
+    defaults to '0' here to match ModuleParameters()'s default, which
+    argparse applies on every real run.  Pass workers=None explicitly to
+    model a run where the value was never set.  Caller is responsible for
+    patching get_valid_stressors().
+    """
+    tmp = tempfile.mkdtemp(prefix="rteval-test-stressng-")
+    section = {
+        'stressor': None,
+        'stressors': None,
+        'workers': '0',
+        'timeout': None,
+        'logging': False,
+        'builddir': tmp,
+        'reportdir': tmp,
+        'cpulist': '0-1',
+    }
+    section.update(opts)
+    _TEST_TMPDIRS.append(tmp)
+    cfg = rtevalConfig(logger=Log())
+    cfg.AppendConfig('stressng', section)
+    return stressng.Stressng(cfg.GetSection('stressng'), Log())
 
 class TestGetValidStressors(unittest.TestCase):
     """Test suite for the function get_valid_stressors"""
@@ -51,6 +93,92 @@ class TestValidateStressor(unittest.TestCase):
             stressng.validate_stressors('bogus')
         self.assertEqual(cm.exception.code, 1)
 
+class TestDonotrun(unittest.TestCase):
+    """Whether the module opts in/out of running via _donotrun.
+
+    stressng is listed in the default [loads] config and is exclusive, so a
+    wrong _donotrun does not just misfire stressng - it disables kcompile
+    and hackbench too.  It must opt out whenever no stressor was requested,
+    regardless of the always-present 'workers' default.
+    """
+
+    @patch('rteval.modules.loads.stressng.get_valid_stressors',
+           return_value=['cpu', 'vm'])
+    def test_no_stressor_opts_out_despite_workers_default(self, _):
+        """No stressor + default workers='0' must leave _donotrun True"""
+        mod = make_stressng(stressor=None, stressors=None, workers='0')
+        self.assertTrue(mod._donotrun)
+
+    @patch('rteval.modules.loads.stressng.get_valid_stressors',
+           return_value=['cpu', 'vm'])
+    def test_stressors_string_opts_in_and_validates(self, _):
+        """--stressng-stressors cpu,vm runs and is validated to a list"""
+        mod = make_stressng(stressors='cpu,vm', workers='0')
+        self.assertFalse(mod._donotrun)
+        self.assertEqual(mod.cfg.stressors, ['cpu', 'vm'])
+
+    @patch('rteval.modules.loads.stressng.get_valid_stressors',
+           return_value=['cpu', 'vm'])
+    def test_stressor_append_opts_in(self, _):
+        """Repeated --stressng-stressor (action='append') runs"""
+        mod = make_stressng(stressor=['cpu', 'vm'], workers='0')
+        self.assertFalse(mod._donotrun)
+
+    @patch('rteval.modules.loads.stressng.get_valid_stressors',
+           return_value=['cpu', 'vm'])
+    def test_negative_workers_rejected(self, _):
+        """A negative worker count must opt out, not be passed to stress-ng"""
+        mod = make_stressng(stressor=['cpu'], workers='-1')
+        self.assertTrue(mod._donotrun)
+
+    @patch('rteval.modules.loads.stressng.get_valid_stressors',
+           return_value=['cpu', 'vm'])
+    def test_noninteger_workers_rejected(self, _):
+        """A non-integer worker count must opt out"""
+        mod = make_stressng(stressor=['cpu'], workers='abc')
+        self.assertTrue(mod._donotrun)
+
+    def tearDown(self):
+        _cleanup_test_tmpdirs()
+
+
+class TestArgBuilding(unittest.TestCase):
+    """_WorkloadPrepare() builds the stress-ng command line correctly."""
+
+    def _prepare(self, mod):
+        """Run _WorkloadPrepare() with a deterministic, fake topology."""
+        with patch('rteval.modules.loads.stressng.SysTopology') as systop:
+            systop.return_value.getnodes.return_value = ['0']
+            systop.return_value.getcpus.return_value = [0, 1]
+            mod._WorkloadPrepare()
+        return mod.args
+
+    @patch('rteval.modules.loads.stressng.get_valid_stressors',
+           return_value=['cpu', 'vm'])
+    def test_multi_stressor_with_workers(self, _):
+        """Each stressor gets its own flag with the worker count"""
+        mod = make_stressng(stressor=['cpu', 'vm'], workers='2')
+        args = self._prepare(mod)
+        self.assertIn('--cpu', args)
+        self.assertIn('--vm', args)
+        # worker count follows each stressor flag
+        self.assertEqual(args[args.index('--cpu') + 1], '2')
+        self.assertEqual(args[args.index('--vm') + 1], '2')
+
+    @patch('rteval.modules.loads.stressng.get_valid_stressors',
+           return_value=['cpu', 'vm'])
+    def test_no_workers_leaves_no_none_in_args(self, _):
+        """workers=None must not inject a None into argv (crashes join/Popen)"""
+        mod = make_stressng(stressor=['cpu'], workers=None)
+        args = self._prepare(mod)
+        self.assertNotIn(None, args)
+        # _WorkloadTask does " ".join(self.args); it must not raise
+        " ".join(args)
+
+    def tearDown(self):
+        _cleanup_test_tmpdirs()
+
+
 def main():
     """Run the test suite"""
     unittest.main(verbosity=2)
Signature · 1 line
2.56.0