summaryrefslogtreecommitdiff
path: root/src/main/java/testing/HeadlessSimulationRunner.java
blob: ef50995ba5b0b2ad7b044f705c4a3858c6676195 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package testing;

import simulator.*;
import simulator.engine.*;
import simulator.messaging.*;
import core.*;
import prefs.*;
import events.*;
import serialize.VSSerialize;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.*;

/**
 * Runs DS-Sim simulations in headless mode without GUI dependencies.
 * Captures logs and provides verification capabilities for automated testing.
 */
public class HeadlessSimulationRunner {
    private final VSDefaultPrefs prefs;
    private VSSimulator simulator;
    private VSSimulatorVisualization viz;
    private LogCapture logCapture;
    private final ExecutorService executor;
    private boolean printLogs = false;
    
    public HeadlessSimulationRunner() {
        this.prefs = new VSDefaultPrefs();
        this.prefs.fillWithDefaults();
        VSRegisteredEvents.init(prefs);
        this.executor = Executors.newSingleThreadExecutor();
    }
    
    /**
     * Run a simulation from a saved file for a specified duration.
     * 
     * @param simulationFile Path to the saved simulation .dat file
     * @param maxTime Maximum simulation time in milliseconds
     * @return SimulationResult containing logs and metrics
     */
    public SimulationResult runSimulation(String simulationFile, long maxTime) 
            throws Exception {
        return runSimulation(simulationFile, maxTime, null);
    }
    
    /**
     * Run a simulation with an optional log listener.
     */
    public SimulationResult runSimulation(String simulationFile, long maxTime, LogListener listener) 
            throws Exception {
        System.out.println("Loading simulation: " + simulationFile);
        
        try {
            // Use HeadlessLoader to avoid any GUI initialization
            HeadlessLoader.LoadedSimulation loaded = HeadlessLoader.load(simulationFile, prefs);
            simulator = loaded.getSimulator();
            viz = loaded.getVisualization();
            
            if (simulator == null || viz == null) {
                throw new IllegalStateException("Failed to load simulation");
            }
            
            // Set up headless message handlers for all processes
            setupHeadlessMessageHandlers(viz);
            
            // Install log capture
            logCapture = new LogCapture();
            logCapture.setPrintLogs(printLogs);
            if (listener != null) {
                logCapture.addListener(listener);
            }
            installLogCapture();
            
            System.out.println("Running simulation for " + maxTime + "ms...");
            
            // Run simulation
            Future<Void> runFuture = executor.submit(() -> {
                try {
                    runSimulationSteps(maxTime);
                } catch (Exception e) {
                    System.err.println("Error during simulation: " + e.getMessage());
                    e.printStackTrace();
                }
                return null;
            });
            
            // Wait for completion or timeout
            try {
                runFuture.get(maxTime * 2, TimeUnit.MILLISECONDS);
            } catch (TimeoutException e) {
                System.out.println("Simulation timeout - stopping...");
                runFuture.cancel(true);
            }
            
            System.out.println("Simulation complete. Captured " + 
                             logCapture.getTotalLogCount() + " log entries.");
            
            return new SimulationResult(
                logCapture.getCapturedLogs(),
                logCapture.getProcessLogs(),
                getSimulationMetrics()
            );
        } catch (Exception e) {
            System.err.println("Failed to load simulation: " + e.getMessage());
            throw e;
        }
    }
    
    private void runSimulationSteps(long maxTime) throws Exception {
        VSTaskManager taskManager = viz.getTaskManager();
        
        // Get necessary fields via reflection
        Field timeField = VSSimulatorVisualization.class
            .getDeclaredField("time");
        timeField.setAccessible(true);
        
        // Find runTasks method with correct signature
        Method runTasksMethod = VSTaskManager.class
            .getDeclaredMethod("runTasks", long.class, long.class, long.class);
        runTasksMethod.setAccessible(true);
        
        long startTime = timeField.getLong(viz);
        long currentTime = startTime;
        
        while (currentTime - startTime < maxTime) {
            // Update time
            timeField.setLong(viz, currentTime);
            
            // Sync process times
            for (int i = 0; i < viz.getNumProcesses(); i++) {
                viz.getProcess(i).syncTime(currentTime);
            }
            
            // Run tasks (step, offset, lastGlobalTime)
            runTasksMethod.invoke(taskManager, currentTime, 0L, currentTime - 1);
            
            // Advance time by 1ms
            currentTime++;
            
            // Small delay to prevent CPU spinning
            Thread.sleep(1);
        }
    }
    
    private void installLogCapture() throws Exception {
        // Set simulatorVisualization reference in logCapture
        logCapture.setSimulatorCanvas(viz);
        
        // Install on visualization
        Field logingField = VSSimulatorVisualization.class
            .getDeclaredField("loging");
        logingField.setAccessible(true);
        logingField.set(viz, logCapture);
        
        // Install on all processes
        for (int i = 0; i < viz.getNumProcesses(); i++) {
            VSInternalProcess process = viz.getProcess(i);
            if (process != null) {
                Field processLogingField = VSAbstractProcess.class
                    .getDeclaredField("loging");
                processLogingField.setAccessible(true);
                processLogingField.set(process, logCapture);
            }
        }
    }
    
    private SimulationMetrics getSimulationMetrics() {
        return new SimulationMetrics(
            viz.getNumProcesses(),
            logCapture.getTotalLogCount(),
            logCapture.getProcessMessageCounts()
        );
    }
    
    public void setPrintLogs(boolean printLogs) {
        this.printLogs = printLogs;
        if (logCapture != null) {
            logCapture.setPrintLogs(printLogs);
        }
    }
    
    public void addLogListener(LogListener listener) {
        if (logCapture != null) {
            logCapture.addListener(listener);
        }
    }
    
    public void shutdown() {
        executor.shutdown();
        try {
            if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
    
    /**
     * Sets up headless message handlers for all processes to avoid GUI dependencies.
     */
    private void setupHeadlessMessageHandlers(VSSimulatorVisualization viz) {
        // Create a headless simulation engine
        HeadlessSimulationEngine engine = new HeadlessSimulationEngine(prefs, logCapture);
        
        // Copy processes to engine
        for (int i = 0; i < viz.getNumProcesses(); i++) {
            VSInternalProcess process = viz.getProcess(i);
            if (process != null) {
                engine.addProcess(process);
                
                // Create and set headless message handler
                MessageHandler handler = new HeadlessMessageHandler(engine);
                process.setMessageHandler(handler);
            }
        }
        
        // Note: Task manager state is not copied because:
        // - Global tasks are in VSTaskManager.globalTasks
        // - Local tasks are stored in each VSInternalProcess.tasks
        // - The engine already has references to the processes which contain their tasks
    }
}