const std = @import("std"); const config = @import("../config.zig"); const grpc_executor = @import("../protocol/grpc_executor.zig"); const http_executor = @import("../protocol/http_executor.zig"); const http_state = @import("../protocol/http_state.zig"); const request_dispatch = @import("../protocol/request_dispatch.zig"); const runner_context = @import("context.zig"); const runner_executor = @import("executor.zig"); const runner_log = @import("log.zig"); const runner_metrics = @import("metrics.zig"); const runner_progress = @import("progress.zig"); const template = @import("../template.zig"); const http = std.http; const CookieJar = http_state.CookieJar; const TlsContext = http_executor.TlsContext; const SimpleVu = struct { cookie_jar: CookieJar, fn deinit(self: *SimpleVu) void { self.cookie_jar.deinit(); self.* = undefined; } }; const SimpleExecutor = struct { allocator: std.mem.Allocator, client: *http.Client, grpc_client: *grpc_executor.Client, shared_store: *template.VarStore, tls_context: *TlsContext, scenario: *const config.ScenarioConfig, aggregator: *runner_metrics.MetricsAggregator, warmup_end: i128, request_error_logged: *std.atomic.Value(bool), logger: *runner_log.Logger, simple_vus: []SimpleVu, pub fn preConstantVus(self: *SimpleExecutor) bool { _ = self; return false; } pub fn constantVusSlots(self: *SimpleExecutor) usize { return self.simple_vus.len; } pub fn dispatchConstantVus(self: *SimpleExecutor, slot: usize) !bool { try executeIteration( self.allocator, self.client, self.grpc_client, self.shared_store, self.tls_context, &self.simple_vus[slot], self.scenario, self.aggregator, self.warmup_end, self.request_error_logged, self.logger, ); return false; } pub fn preArrivalDispatch(self: *SimpleExecutor) bool { _ = self; return false; } pub fn dispatchArrival(self: *SimpleExecutor, rr_index: *usize) !bool { const slot = rr_index.* % self.simple_vus.len; rr_index.* += 1; return try self.dispatchConstantVus(slot); } pub fn preRampingVus(self: *SimpleExecutor) bool { _ = self; return false; } pub fn dispatchRampingVus(self: *SimpleExecutor, slot: usize, active_vus: usize) !bool { _ = active_vus; return try self.dispatchConstantVus(slot); } }; const ParallelSimpleWorker = struct { scenario: *const config.ScenarioConfig, shared_store: *const template.VarStore, warmup_end: i128, measured_end: i128, stop_requested: *const std.atomic.Value(bool), abort_requested: *std.atomic.Value(bool), request_error_logged: *std.atomic.Value(bool), logger: *runner_log.Logger, slot_count: usize, gpa: std.heap.GeneralPurposeAllocator(.{}) = .{}, session: ?runner_context.Session = null, aggregator: ?runner_metrics.MetricsAggregator = null, simple_vus: []SimpleVu = &.{}, thread: ?std.Thread = null, run_error: ?anyerror = null, fn start(self: *ParallelSimpleWorker) !void { self.thread = try std.Thread.spawn(.{}, runThread, .{self}); } fn join(self: *ParallelSimpleWorker) void { if (self.thread) |thread| { thread.join(); self.thread = null; } } fn deinit(self: *ParallelSimpleWorker) void { for (self.simple_vus) |*vu| vu.deinit(); if (self.simple_vus.len != 0) { self.gpa.allocator().free(self.simple_vus); } if (self.aggregator) |*aggregator| aggregator.deinit(); if (self.session) |*session| session.deinit(); _ = self.gpa.deinit(); self.* = undefined; } fn runThread(self: *ParallelSimpleWorker) void { self.run_error = null; self.run() catch |err| { self.run_error = err; self.abort_requested.store(true, .monotonic); }; } fn run(self: *ParallelSimpleWorker) !void { const allocator = self.gpa.allocator(); self.session = try runner_context.Session.init(allocator, self.scenario); self.aggregator = .{ .allocator = allocator }; const session = &self.session.?; try session.shared_store.cloneFrom(self.shared_store); self.simple_vus = try allocator.alloc(SimpleVu, self.slot_count); errdefer allocator.free(self.simple_vus); var initialized: usize = 0; errdefer { for (self.simple_vus[0..initialized]) |*vu| vu.deinit(); } for (self.simple_vus) |*vu| { vu.* = .{ .cookie_jar = CookieJar.init(allocator) }; initialized += 1; } while (!self.stop_requested.load(.monotonic) and !self.abort_requested.load(.monotonic) and std.time.nanoTimestamp() < self.measured_end) { var slot: usize = 0; while (slot < self.simple_vus.len) : (slot += 1) { if (self.stop_requested.load(.monotonic) or self.abort_requested.load(.monotonic)) break; if (std.time.nanoTimestamp() >= self.measured_end) break; try executeIteration( allocator, &session.client, &session.grpc_client, &session.shared_store, &session.tls_context, &self.simple_vus[slot], self.scenario, &self.aggregator.?, self.warmup_end, self.request_error_logged, self.logger, ); } } } }; pub fn runSimpleMode( allocator: std.mem.Allocator, client: *http.Client, grpc_client: *grpc_executor.Client, shared_store: *template.VarStore, tls_context: *TlsContext, scenario: *const config.ScenarioConfig, aggregator: *runner_metrics.MetricsAggregator, warmup_end: i128, measured_end: i128, next_progress: *i128, stop_requested: *const std.atomic.Value(bool), abort_on_fail_enabled: bool, request_error_logged: *std.atomic.Value(bool), logger: *runner_log.Logger, ) !void { const simple_vu_count: usize = switch (scenario.execution.mode) { .constant_vus => scenario.execution.vus.?, .constant_arrival_rate => scenario.execution.pre_allocated_vus.?, .ramping_vus => scenario.execution.maxRampingVus(), }; if (scenario.execution.mode == .constant_vus) { const resolved_thread_count = scenario.execution.resolvedThreadCount(); if (resolved_thread_count > 1 and simple_vu_count > 1) { const worker_count = @min(resolved_thread_count, simple_vu_count); try logger.logf(.info, .{ .component = "runner", .source = .host, .event = "parallel_runner_enabled", }, "enabling multithreaded simple runner with {d} workers", .{worker_count}); return runSimpleModeParallel( allocator, shared_store, scenario, aggregator, warmup_end, measured_end, next_progress, stop_requested, request_error_logged, logger, simple_vu_count, worker_count, ); } } const simple_vus = try allocator.alloc(SimpleVu, simple_vu_count); defer allocator.free(simple_vus); for (simple_vus) |*vu| { vu.* = .{ .cookie_jar = CookieJar.init(allocator) }; } defer for (simple_vus) |*vu| vu.deinit(); var executor = SimpleExecutor{ .allocator = allocator, .client = client, .grpc_client = grpc_client, .shared_store = shared_store, .tls_context = tls_context, .scenario = scenario, .aggregator = aggregator, .warmup_end = warmup_end, .request_error_logged = request_error_logged, .logger = logger, .simple_vus = simple_vus, }; _ = try runner_executor.run(SimpleExecutor, &executor, .{ .scenario = scenario, .aggregator = aggregator, .warmup_end = warmup_end, .measured_end = measured_end, .next_progress = next_progress, .stop_requested = stop_requested, .abort_on_fail_enabled = abort_on_fail_enabled, .logger = logger, }); } fn runSimpleModeParallel( allocator: std.mem.Allocator, shared_store: *const template.VarStore, scenario: *const config.ScenarioConfig, aggregator: *runner_metrics.MetricsAggregator, warmup_end: i128, measured_end: i128, next_progress: *i128, stop_requested: *const std.atomic.Value(bool), request_error_logged: *std.atomic.Value(bool), logger: *runner_log.Logger, simple_vu_count: usize, worker_count: usize, ) !void { var abort_requested = std.atomic.Value(bool).init(false); const workers = try allocator.alloc(ParallelSimpleWorker, worker_count); defer allocator.free(workers); var started_count: usize = 0; errdefer { abort_requested.store(true, .monotonic); joinAndDeinitWorkers(workers[0..started_count]); } for (workers, 0..) |*worker, worker_index| { worker.* = .{ .scenario = scenario, .shared_store = shared_store, .warmup_end = warmup_end, .measured_end = measured_end, .stop_requested = stop_requested, .abort_requested = &abort_requested, .request_error_logged = request_error_logged, .logger = logger, .slot_count = slotCountForWorker(simple_vu_count, worker_index, worker_count), }; try worker.start(); started_count += 1; } while (!stop_requested.load(.monotonic) and !abort_requested.load(.monotonic) and std.time.nanoTimestamp() < measured_end) { const now = std.time.nanoTimestamp(); if (now < next_progress.*) { std.Thread.sleep(@intCast(next_progress.* - now)); continue; } var snapshot = runner_metrics.MetricsAggregator{ .allocator = allocator }; defer snapshot.deinit(); try mergeWorkerAggregators(&snapshot, workers[0..started_count]); try runner_progress.printProgress(logger, &snapshot, warmup_end); if (try snapshot.shouldAbortOnFail(scenario)) { try logger.log(.warn, "aborting run due to abort_on_fail threshold", .{ .component = "runner", .source = .host, .event = "threshold_abort", }); abort_requested.store(true, .monotonic); break; } next_progress.* += @as(i128, std.time.ns_per_s); } for (workers[0..started_count]) |*worker| worker.join(); defer deinitWorkers(workers[0..started_count]); for (workers[0..started_count]) |*worker| { if (worker.run_error) |err| return err; } try mergeWorkerAggregators(aggregator, workers[0..started_count]); } fn slotCountForWorker(total_slots: usize, worker_index: usize, worker_count: usize) usize { var count: usize = 0; var slot = worker_index; while (slot < total_slots) : (slot += worker_count) { count += 1; } return count; } fn mergeWorkerAggregators(destination: *runner_metrics.MetricsAggregator, workers: []ParallelSimpleWorker) !void { for (workers) |*worker| { if (worker.aggregator) |*aggregator| { try destination.mergeFrom(aggregator); } } } fn joinAndDeinitWorkers(workers: []ParallelSimpleWorker) void { for (workers) |*worker| worker.join(); deinitWorkers(workers); } fn deinitWorkers(workers: []ParallelSimpleWorker) void { for (workers) |*worker| worker.deinit(); } fn executeIteration( allocator: std.mem.Allocator, client: *http.Client, grpc_client: *grpc_executor.Client, store: *template.VarStore, tls_context: *TlsContext, vu: *SimpleVu, scenario: *const config.ScenarioConfig, aggregator: *runner_metrics.MetricsAggregator, warmup_end: i128, request_error_logged: *std.atomic.Value(bool), logger: *runner_log.Logger, ) !void { const request = &scenario.http.requests[0]; const start_nanos = std.time.nanoTimestamp(); if (scenario.http.defaults.cookie_jar and scenario.http.defaults.cookie_jar_scope == .iteration) { vu.cookie_jar.clear(); } var execution = request_dispatch.executeConfiguredRequest( allocator, scenario, client, grpc_client, store, tls_context, if (scenario.http.defaults.cookie_jar) &vu.cookie_jar else null, request.method, request.path, request.headers, request.body, null, request.connect_timeout_ms, request.timeout_ms, request.delay_before_ms, if (request.pass_response_body or request.capture_body_max_bytes != 0 or request.check_body_contains != null) http_executor.effectiveCaptureBodyMaxBytes(request) else 0, ) catch |err| { if (!request_error_logged.swap(true, .acq_rel)) { if (scenario.scenario.protocol == .http and scenario.http.transport_plugin == null) { const error_message = try http_executor.describeRequestError(allocator, err, &scenario.http); defer allocator.free(error_message); try logger.logf(.err, .{ .component = "runner", .source = .host, .event = "request_execution_error", }, "request execution error: {s}", .{error_message}); } else { try logger.logf(.err, .{ .component = "runner", .source = .host, .event = "request_execution_error", }, "request execution error: {s}", .{@errorName(err)}); } } const failed = http_executor.failedRequestExecution(start_nanos, request.body, err); try aggregator.recordRequest(start_nanos, warmup_end, .{ .duration_nanos = failed.duration_nanos, .bytes_sent = failed.bytes_sent, .bytes_received = failed.bytes_received, .success = failed.success, .checks_failed = http_executor.configuredCheckCount(request), .transport_code = failed.transport_code, .timeout_phase = failed.timeout_phase, .request_name = request.name, }); aggregator.recordIteration(start_nanos, warmup_end, false); return; }; defer execution.deinit(allocator); http_executor.evaluateBuiltInChecks(request, &execution); try aggregator.recordRequest(start_nanos, warmup_end, .{ .duration_nanos = execution.duration_nanos, .bytes_sent = execution.bytes_sent, .bytes_received = execution.bytes_received, .success = execution.success, .checks_passed = execution.checks_passed, .checks_failed = execution.checks_failed, .transport_code = execution.transport_code, .timeout_phase = execution.timeout_phase, .grpc_status = execution.grpc_status, .grpc_deadline_exceeded = execution.deadline_exceeded, .request_name = request.name, }); aggregator.recordIteration(start_nanos, warmup_end, execution.success); }