pythonlocust

Terminate cleanly after an exact number of Task executions have occurred across multiple processes


Following on from a previous question1, I want locust to terminate a run once I've performed an exact number of requests across multiple Users and processes. I can track the progress on a per-User basis, but I'm struggling to communicate that to locust in a clean manner where it doesn't try to spawn a bunch of extra Users in the dying throes of the run (which makes it complex for me to handle work assignment for each user).

Here's a sketch of what I have at the moment:

class MyUser:
    def __init__(self):
        self.id = next(distributors["user_id"])
        self.limit = ... # calculate limit based on user's id.
    @task
    def request(self):
        # perform request
        self.requests += 1
        ... epilogue of request():
        if self.requests == self.limit:
            runner = self.environment.runner
            if runner.user_count == 1:
                logging.info("Last user stopped, quitting runner")
                if isinstance(runner, WorkerRunner):
                    runner._send_stats()  # send a final report
                # need to trigger this in a separate greenlet, in case
                # test_stop handlers do something async
                gevent.spawn_later(0.1, runner.quit)
            raise StopUser()

This somewhat "works" (locust indeed does stop after the work is done), but in an unclean fashion, as locust sees that some of the specified number of Users no longer exits and attempts to start them again. This results in the Distributor being called more times than I expect (and StopIteration thrown on the master) - running with --users=5 and --processes=2, and modified log format to include process_id:

[2024-05-03 12:41:10,067] localhost/70327/INFO/root: Last user stopped, quitting runner
[2024-05-03 12:41:10,237] localhost/70327/INFO/locust.main: Shutting down (exit code 0)
[2024-05-03 12:41:10,237] localhost/70322/INFO/locust.runners: Sending spawn jobs of 5 users at 5.00 spawn rate to 1 ready workers
[2024-05-03 12:41:10,237] localhost/70322/DEBUG/locust.runners: Sending spawn messages for 5 total users to 1 worker(s)
[2024-05-03 12:41:10,237] localhost/70322/DEBUG/locust.runners: Currently spawned users: {"MyUser": 3} (3 total users)
[2024-05-03 12:41:10,237] localhost/70327/DEBUG/locust.main: Cleaning up runner...
[2024-05-03 12:41:10,267] localhost/70328/DEBUG/locust.runners: Spawning additional {"MyUser": 2} ({"MyUser": 3} already running)...
[2024-05-03 12:41:10,268] localhost/70328/DEBUG/locust.runners: Sending _user_id_request message to master
[2024-05-03 12:41:10,377] localhost/70328/INFO/root: Last user stopped, quitting runner
[2024-05-03 12:41:10,520] localhost/70328/DEBUG/locust.main: Running teardowns...
[2024-05-03 12:41:10,521] localhost/70328/INFO/locust.main: Shutting down (exit code 0)
[2024-05-03 12:41:10,521] localhost/70328/DEBUG/locust.main: Cleaning up runner...
[2024-05-03 12:41:11,238] localhost/70322/INFO/locust.runners: Spawning is complete and report waittime is expired, but not all reports received from workers: {"MyUser": 3} (3 total users)
[2024-05-03 12:41:11,239] localhost/70322/INFO/locust.runners: Worker 'localhost_fb58584ee115427f8fbe19907660dd26' (index 0) quit. 0 workers ready.
[2024-05-03 12:41:11,239] localhost/70322/DEBUG/locust.runners: Received _user_id_request message from worker localhost_c92c47b1ea284949b2baf21ef71ab265 (index 1)
[2024-05-03 12:41:11,240] localhost/70322/INFO/locust.runners: Worker 'localhost_c92c47b1ea284949b2baf21ef71ab265' (index 1) quit. 0 workers ready.
[2024-05-03 12:41:11,241] localhost/70322/INFO/locust.runners: The last worker quit, stopping test.
[2024-05-03 12:41:11,241] localhost/70322/DEBUG/locust.runners: Stopping...
[2024-05-03 12:41:11,241] localhost/70322/DEBUG/locust.runners: Quitting...
Traceback (most recent call last):
  File "src/gevent/greenlet.py", line 908, in gevent._gevent_cgreenlet.Greenlet.run
  File "/Users/dave/repos/pinecone-io/VSB/.venv/lib/python3.11/site-packages/locust_plugins/distributor.py", line 38, in _master_next_and_send
    item = next(self.iterator)
           ^^^^^^^^^^^^^^^^^^^
StopIteration
2024-05-03T11:41:11Z <Greenlet at 0x165afc360: <bound method Distributor._master_next_and_send of <locust_plugins.distributor.Distributor object at 0x1071aa050>>(0, 'localhost_c92c47b1ea284949b2baf21ef71ab2)> failed with StopIteration

The above is somewhat verbose (I wasn't sure exactly what's relavent), but the point of note is we see additional Users spawned by locust process 703222 after we have finished with all users and called quit on process 70327:

[2024-05-03 12:41:10,067] localhost/70327/INFO/root: Last user stopped, quitting runner
[2024-05-03 12:41:10,237] localhost/70327/INFO/locust.main: Shutting down (exit code 0)
[2024-05-03 12:41:10,237] localhost/70322/INFO/locust.runners: Sending spawn jobs of 5 users at 5.00 spawn rate to 1 ready workers
...
[2024-05-03 12:41:10,267] localhost/70328/DEBUG/locust.runners: Spawning additional {"MyUser": 2} ({"MyUser": 3} already running)...
...
[2024-05-03 12:41:10,519] localhost/70328/DEBUG/locust.runners: Stopping all users (called from .venv/lib/python3.11/site-packages/locust/runners.py:411)

Q: Is there a mechanism to tell locust to only spawn a given number of Users and not start any more after they finish, or perhaps a more explicit way to say "this user has successfully finished, don't respawn" other than raise StopUser()?


Solution

  • In short, I think that is not cleanly possible at the moment.

    Locust-plugins own CSVReader implementations catch the StopIteration exception and reuse the file, maybe that can work. https://github.com/SvenskaSpel/locust-plugins?tab=readme-ov-file#readers

    Another workaround that I've found useful at times is using time.sleep(99999) to "stop" a User without actually stopping it.