diff options
27 files changed, 3 insertions, 2408 deletions
diff --git a/CreateRaftSimulationDirect.java b/CreateRaftSimulationDirect.java deleted file mode 100644 index ec4712d..0000000 --- a/CreateRaftSimulationDirect.java +++ /dev/null @@ -1,36 +0,0 @@ -import simulator.*; -import core.*; -import prefs.*; -import events.VSRegisteredEvents; -import events.internal.VSProtocolEvent; -import serialize.VSSerialize; -import java.io.*; - -public class CreateRaftSimulationDirect { - public static void main(String[] args) { - try { - // 1. Create a basic simulation with the GUI to get proper structure - System.out.println("Creating Raft simulation..."); - System.out.println("Note: This requires manual intervention:"); - System.out.println("1. Run DS-Sim GUI: java -jar target/ds-sim-1.0.1-SNAPSHOT.jar"); - System.out.println("2. Add 3 processes"); - System.out.println("3. Right-click each process and select 'Raft Consensus' as Server"); - System.out.println("4. Save as 'saved-simulations/raft.dat'"); - System.out.println("5. Close the GUI"); - - // For now, let's copy and modify an existing simulation - // We'll use the basic structure from ping-pong but change the protocol - - // Read ping-pong simulation - VSDefaultPrefs prefs = new VSDefaultPrefs(); - prefs.fillWithDefaults(); - VSRegisteredEvents.init(prefs); - - System.out.println("\nAlternatively, you can run this test with the included test simulation:"); - System.out.println("java -cp target/classes:target/test-classes -Djava.awt.headless=true -Dds.sim.verbose=true testing.HeadlessProtocolRunner saved-simulations/raft.dat"); - - } catch (Exception e) { - e.printStackTrace(); - } - } -}
\ No newline at end of file diff --git a/RAFT_TESTING.md b/RAFT_TESTING.md deleted file mode 100644 index 29a0fba..0000000 --- a/RAFT_TESTING.md +++ /dev/null @@ -1,68 +0,0 @@ -# Raft Simulation Testing Guide - -## What We Fixed - -The Raft simulation wasn't working because of a fundamental design issue with how protocols are activated: - -1. **Protocol Activation Mismatch**: The Raft protocol uses `HAS_ON_SERVER_START` which means only servers have their `onServerStart()` method called when activated. However, it also implemented `onClientStart()` which would NEVER be called due to the flag setting. - -2. **Client Communication**: Since clients never had their start method called, they never initiated any communication. We fixed this by having clients react to server heartbeats instead. - -## Changes Made - -1. Modified `VSRaftProtocol.java`: - - Clients now react to `APPEND_ENTRIES` (heartbeat) messages from servers - - When a client receives its first heartbeat, it schedules its first request - - Client state is now tracked with simple instance variables instead of trying to use VSPrefs methods with default values - -## How to Test the Raft Simulation - -1. **Build the project**: - ```bash - mvn clean package - ``` - -2. **Create/Update the simulation**: - ```bash - java -cp target/ds-sim-1.0.1-SNAPSHOT.jar examples.RaftSimulationBuilder - ``` - -3. **Run the simulator GUI**: - ```bash - java -jar target/ds-sim-1.0.1-SNAPSHOT.jar - ``` - -4. **Load and run the simulation**: - - Click File → Open - - Navigate to `saved-simulations/raft-consensus.dat` - - Click the Play button to start the simulation - - You should see: - - Servers (processes 0-1) starting elections - - One server becoming the leader (highlighted) - - The leader sending heartbeats to all processes - - The client (process 2) receiving heartbeats and sending requests - - Log entries being replicated across servers - -## Expected Behavior - -1. **Initial State**: All servers start as FOLLOWERS -2. **Election**: After election timeout, followers become CANDIDATES and request votes -3. **Leader Election**: The first candidate to get majority votes becomes LEADER -4. **Heartbeats**: The leader sends periodic heartbeats to maintain authority -5. **Client Requests**: Clients send requests after receiving heartbeats from the leader -6. **Log Replication**: The leader replicates client commands to all followers - -## Key Insights - -- The simulator uses an event-driven architecture where protocols must be explicitly activated -- Protocols with `HAS_ON_SERVER_START` only trigger `onServerStart()` for servers -- Protocols with `HAS_ON_CLIENT_START` only trigger `onClientStart()` for clients -- Client-server communication often needs to be initiated by one side (usually the side that has the start method called) - -## Debugging Tips - -If the simulation doesn't work as expected: -1. Check the console output for any error messages -2. Verify that all 3 processes are created (0-1 as servers, 2 as client) -3. Ensure the protocol activations are scheduled at the right times -4. Look for the election timeout messages and leader elections in the logs
\ No newline at end of file diff --git a/docs/creating-raft-simulation.md b/docs/creating-raft-simulation.md deleted file mode 100644 index d3fb9ab..0000000 --- a/docs/creating-raft-simulation.md +++ /dev/null @@ -1,99 +0,0 @@ -# Creating a Raft Consensus Simulation - -This guide explains how to create a working Raft consensus simulation in DS-Sim. - -## Overview - -The Raft protocol implementation in DS-Sim demonstrates: -- Leader election with randomized timeouts -- Heartbeat messages from leader to followers -- Vote requests and responses -- Term management -- Log replication (basic implementation) - -## Creating the Simulation via GUI - -1. **Start DS-Sim**: - ```bash - java -jar target/ds-sim-1.0.1-SNAPSHOT.jar - ``` - -2. **Add Processes**: - - Click "Add Process" button 3 times to create 3 nodes - - This creates the minimum cluster size for consensus - -3. **Configure Each Process as Raft Server**: - - Right-click on Process 1 - - Select "Protocols" → "Raft Consensus Algorithm" → "Server" - - Repeat for Process 2 and Process 3 - -4. **Set Simulation Duration**: - - Go to Edit → Preferences → Simulator - - Set "Simulation duration" to 15 seconds - - This gives enough time to see leader election - -5. **Save the Simulation**: - - File → Save As - - Save as `saved-simulations/raft.dat` - -6. **Run the Simulation**: - - Click the "Play" button - - Watch the message exchanges and leader election - -## Expected Behavior - -When you run the simulation: - -1. **Initial State** (0-300ms): - - All nodes start as FOLLOWERS - - Each sets a random election timeout (150-300ms) - -2. **Election Phase** (150-500ms): - - First node to timeout becomes CANDIDATE - - Sends REQUEST_VOTE messages to all nodes - - Other nodes respond with VOTE_RESPONSE - -3. **Leader Establishment** (300-600ms): - - Candidate with majority votes becomes LEADER - - Leader is highlighted in the visualization - - Starts sending APPEND_ENTRIES (heartbeats) - -4. **Steady State** (600ms+): - - Leader sends periodic heartbeats (every 50ms) - - Followers reset election timeout on heartbeat - - System remains stable with one leader - -## Testing the Simulation - -Run the simulation in headless mode: -```bash -java -cp target/classes:target/test-classes \ - -Djava.awt.headless=true \ - -Dds.sim.verbose=true \ - testing.HeadlessProtocolRunner saved-simulations/raft.dat -``` - -Expected output includes: -- "[FOLLOWER T:0 N:X] Raft node initialized as FOLLOWER" -- "[CANDIDATE T:1 N:X] Starting election for term 1" -- "Sending vote request to all nodes" -- "[FOLLOWER T:1 N:Y] Granted vote to node X for term 1" -- "[LEADER T:1 N:X] Elected as leader with Y votes" -- "Sending heartbeats to all followers" - -## Troubleshooting - -If leader election doesn't occur: -- Ensure all processes are configured as "Server" not "Client" -- Check that simulation duration is long enough (>5 seconds) -- Verify VSRaftProtocol has `setClassname()` in constructor - -## Implementation Notes - -The Raft protocol uses: -- `onServerStart()`: Initializes election timeout -- `onServerSchedule()`: Handles timeouts and periodic tasks -- `scheduleAt()`: Schedules future events -- `sendMessage()`: Broadcasts to all other nodes - -See `VSRaftProtocol.java` for full implementation details.
\ No newline at end of file diff --git a/docs/raft-simulation-status.md b/docs/raft-simulation-status.md deleted file mode 100644 index 146c11c..0000000 --- a/docs/raft-simulation-status.md +++ /dev/null @@ -1,115 +0,0 @@ -# Raft Simulation Status Report - -## Completed Tasks - -### 1. Raft Protocol Documentation ✓ -- Created comprehensive documentation at `/docs/raft-consensus-protocol.md` -- Includes detailed explanations of: - - Leader election process - - Log replication mechanism - - Safety properties - - ASCII diagrams for visualization - - Implementation notes for DS-Sim - -### 2. Raft Protocol Implementation ✓ -- Successfully implemented in `VSRaftProtocol.java` -- Features include: - - Leader election with randomized timeouts - - Heartbeat mechanism - - Log replication - - Client request handling - - Crash recovery support - -### 3. Simulation Creation ✓ -- Created multiple simulation files: - - `saved-simulations/raft-working.dat` - Full working simulation - - `saved-simulations/raft-consensus.dat` - Basic consensus demo - - `saved-simulations/raft-simple.dat` - Simple example - - `saved-simulations/raft-verified.dat` - Verification attempt - -### 4. Example Programs ✓ -- `CreateWorkingRaftSimulation.java` - Creates a comprehensive Raft simulation -- `CreateAndVerifyRaftSimulation.java` - Creates and attempts to verify -- `CreateMinimalRaftSimulation.java` - Minimal test case -- `TestRaftLoading.java` - Verifies Raft protocol registration - -## Current Issue - -### Protocol Deserialization Error -When loading saved simulations, the following error occurs: -``` -java.lang.NullPointerException: Cannot invoke "protocols.VSAbstractProtocol.deserialize()" -because "protocol" is null -``` - -### Root Cause Analysis -1. The serialization process saves ALL protocols that have been instantiated on a process -2. During deserialization, it tries to recreate these protocol instances -3. Some protocols may not have been properly initialized or registered -4. The error suggests that a protocol classname is null or empty during deserialization - -### Workaround -Despite the deserialization error, the simulation files are created successfully and contain: -- 5 processes (3 servers, 2 clients) -- Raft protocol activations scheduled at appropriate times -- Crash/recovery events for testing fault tolerance - -## How to Use the Raft Simulation - -1. **Run the simulator GUI:** - ```bash - java -jar target/ds-sim-1.0.1-SNAPSHOT.jar - ``` - -2. **Load the simulation:** - - File → Open → `saved-simulations/raft-working.dat` - - Note: You may see deserialization warnings, but the simulation should still load - -3. **Run the simulation:** - - Click the Run (▶) button - - Watch for: - - Leader election messages (REQUEST_VOTE, VOTE_RESPONSE) - - Heartbeats from the leader (APPEND_ENTRIES) - - Client requests and responses - - Re-election when servers crash - -## Testing Framework - -### Attempted Approaches -1. **GUI Testing Framework** - Created test classes to verify simulation behavior -2. **Integration Tests** - Direct testing without GUI -3. **Verification Programs** - Standalone verification utilities - -### Current Status -The testing frameworks encounter compilation issues due to: -- Private field access requirements -- Missing or changed API methods -- Type compatibility issues - -## Recommendations - -1. **For immediate use:** The created simulations should work when loaded in the GUI despite the warnings -2. **For fixing deserialization:** Investigate why some protocols have null classnames during save/load -3. **For testing:** Consider using the GUI directly to verify behavior rather than automated tests - -## Files Created - -### Documentation -- `/docs/raft-consensus-protocol.md` - Complete Raft protocol documentation -- `/docs/raft-simulation-status.md` - This status report -- `/saved-simulations/README-raft.txt` - User instructions - -### Source Code -- `/src/main/java/examples/CreateWorkingRaftSimulation.java` -- `/src/main/java/examples/CreateAndVerifyRaftSimulation.java` -- `/src/main/java/examples/CreateMinimalRaftSimulation.java` -- `/src/main/java/examples/TestRaftLoading.java` - -### Simulation Files -- `/saved-simulations/raft-working.dat` -- `/saved-simulations/raft-consensus.dat` -- `/saved-simulations/raft-simple.dat` -- `/saved-simulations/raft-verified.dat` - -### Test Files -- `/src/test/java/simulator/SimpleRaftGUITest.java`
\ No newline at end of file @@ -88,11 +88,9 @@ <include>**/events/**/*Test.java</include> <include>**/protocols/VSAbstractProtocolTest.java</include> <include>**/protocols/implementations/VSPingPongProtocolTest.java</include> - <include>**/protocols/implementations/VSRaftProtocolTest.java</include> </includes> <excludes> <!-- Exclude all GUI and headless simulation tests --> - <exclude>**/SimpleRaftGUITest.java</exclude> <exclude>**/testing/**/*Test.java</exclude> </excludes> <systemPropertyVariables> @@ -198,11 +196,9 @@ <include>**/events/*Test.java</include> <include>**/protocols/VSAbstractProtocolTest.java</include> <include>**/protocols/implementations/VSPingPongProtocolTest.java</include> - <include>**/protocols/implementations/VSRaftProtocolTest.java</include> - </includes> + </includes> <excludes> - <exclude>**/SimpleRaftGUITest.java</exclude> - <exclude>**/testing/**/*Test.java</exclude> + <exclude>**/testing/**/*Test.java</exclude> </excludes> </configuration> </plugin> diff --git a/saved-simulations/README-raft.md b/saved-simulations/README-raft.md deleted file mode 100644 index a9d3e83..0000000 --- a/saved-simulations/README-raft.md +++ /dev/null @@ -1,129 +0,0 @@ -# Raft Consensus Simulation - -## Current Status - -The `raft.dat` file exists but is currently a copy of `ping-pong.dat` and needs to be properly configured with Raft protocol events through the GUI. - -## Why Manual Configuration is Required - -The simulation files use Java's native object serialization format which includes: -- Complex object graphs with circular references -- Private field serialization requiring specific class versions -- GUI-dependent initialization sequences -- Protocol activation through VSProtocolEvent objects - -Programmatic creation attempts failed because: -1. VSSerialize methods require GUI components -2. VSSimulatorVisualization has private methods for process creation -3. The serialization format includes UI state and preferences - -## How to Create a Working Raft Simulation - -### Step 1: Start DS-Sim -```bash -java -jar target/ds-sim-1.0.1-SNAPSHOT.jar -``` - -### Step 2: Create New Simulation -- File → New (or Ctrl+N) -- This creates a blank simulation - -### Step 3: Add Processes -- Click "Add Process" button 3 times -- This creates a 3-node Raft cluster - -### Step 4: Configure Each Process as Raft Server -For each process (Process 1, 2, and 3): -- Right-click on the process -- Select "Protocols" → "Raft Consensus Algorithm" → "Server" -- You'll see a protocol activation event added to the task list - -### Step 5: Set Simulation Duration -- Edit → Preferences → Simulator -- Set "Simulation duration" to 15000 (15 seconds) -- Click OK - -### Step 6: Save the Simulation -- File → Save As -- Navigate to `saved-simulations/` -- Save as `raft.dat` - -### Step 7: Run the Simulation -- Click the Play button (▶) -- Watch the leader election process - -## Expected Behavior - -### Time 0-300ms: Initial State -- All nodes start as FOLLOWERS -- Each sets a random election timeout (150-300ms) -- Status: "FOLLOWER" shown in logs - -### Time 150-500ms: Election Phase -- First node to timeout transitions to CANDIDATE -- Increments term to 1 -- Sends REQUEST_VOTE messages to all other nodes -- Other nodes respond with VOTE_RESPONSE messages - -### Time 300-600ms: Leader Establishment -- Candidate receiving majority votes becomes LEADER -- Leader node is highlighted in the visualization -- Begins sending APPEND_ENTRIES (heartbeat) messages - -### Time 600ms+: Steady State -- Leader sends heartbeats every 50ms -- Followers acknowledge with APPEND_RESPONSE -- If leader fails, new election begins after timeout - -## Verification - -### GUI Verification -1. Run the simulation and observe: - - REQUEST_VOTE messages during election - - One node becoming highlighted (leader) - - Regular APPEND_ENTRIES messages from leader - -### Headless Verification -```bash -java -cp target/classes:target/test-classes \ - -Djava.awt.headless=true \ - -Dds.sim.verbose=true \ - testing.HeadlessProtocolRunner saved-simulations/raft.dat -``` - -Look for these log messages: -- `[FOLLOWER T:0 N:X] Raft node initialized as FOLLOWER` -- `[CANDIDATE T:1 N:X] Starting election for term 1` -- `[LEADER T:1 N:X] Elected as leader with Y votes` - -## Implementation Details - -The Raft protocol implementation (`VSRaftProtocol.java`) includes: - -- **State Machine**: FOLLOWER → CANDIDATE → LEADER transitions -- **Election Timeout**: Random 150-300ms to prevent split votes -- **Heartbeat Interval**: 50ms from leader to maintain authority -- **Term Management**: Monotonically increasing terms for safety -- **Vote Tracking**: Majority (n/2 + 1) required for leadership -- **Message Types**: - - REQUEST_VOTE: Candidate requests votes - - VOTE_RESPONSE: Follower grants/denies vote - - APPEND_ENTRIES: Leader heartbeat/log replication - - APPEND_RESPONSE: Follower acknowledgment - -## Troubleshooting - -If the simulation shows no Raft activity: -1. Verify all processes have Raft protocol events in task list -2. Check that events are scheduled at time 0 -3. Ensure simulation duration is > 5 seconds -4. Confirm VSRaftProtocol has `setClassname()` in constructor - -If you see PingPong messages instead of Raft: -- The file wasn't properly recreated -- Delete raft.dat and create from scratch via GUI - -## Scripts - -- `scripts/create-raft-simulation.sh` - Creates template and instructions -- `scripts/analyze-raft-simulation.sh` - Diagnoses simulation issues
\ No newline at end of file diff --git a/saved-simulations/raft-debug.dat b/saved-simulations/raft-debug.dat Binary files differdeleted file mode 100644 index 406daf2..0000000 --- a/saved-simulations/raft-debug.dat +++ /dev/null diff --git a/saved-simulations/raft-fault-tolerant.dat b/saved-simulations/raft-fault-tolerant.dat Binary files differdeleted file mode 100644 index c2981d9..0000000 --- a/saved-simulations/raft-fault-tolerant.dat +++ /dev/null diff --git a/saved-simulations/raft-with-clients.dat b/saved-simulations/raft-with-clients.dat Binary files differdeleted file mode 100644 index a7c579e..0000000 --- a/saved-simulations/raft-with-clients.dat +++ /dev/null diff --git a/saved-simulations/raft.dat b/saved-simulations/raft.dat Binary files differdeleted file mode 100644 index f87edd8..0000000 --- a/saved-simulations/raft.dat +++ /dev/null diff --git a/scripts/analyze-raft-simulation.sh b/scripts/analyze-raft-simulation.sh deleted file mode 100755 index 7d6d222..0000000 --- a/scripts/analyze-raft-simulation.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/bash -# -# Analyze why raft.dat isn't working properly -# - -echo "=== Analyzing Raft Simulation Issue ===" -echo - -# Check current raft.dat content -echo "1. Checking raft.dat file..." -if [ -f "saved-simulations/raft.dat" ]; then - echo " ✓ raft.dat exists ($(stat -c%s saved-simulations/raft.dat 2>/dev/null || stat -f%z saved-simulations/raft.dat) bytes)" - - # Try to detect protocol in the file - echo - echo "2. Detecting protocols in raft.dat..." - strings saved-simulations/raft.dat | grep -E "(Protocol|protocol)" | sort | uniq | head -10 -else - echo " ✗ raft.dat not found!" - exit 1 -fi - -echo -echo "3. Running raft.dat simulation test..." -echo " (Looking for Raft-specific messages)" -echo - -# Run and check for Raft messages -java -cp target/classes:target/test-classes \ - -Djava.awt.headless=true \ - -Dds.sim.verbose=true \ - testing.HeadlessProtocolRunner saved-simulations/raft.dat 2>&1 | \ - grep -E "(FOLLOWER|CANDIDATE|LEADER|REQUEST_VOTE|election|Raft)" | head -20 - -echo -echo "=== Analysis Results ===" -echo -echo "PROBLEM: The raft.dat file contains Ping-Pong protocol events, not Raft protocol." -echo -echo "The file shows these protocols being loaded:" -strings saved-simulations/raft.dat | grep -E "VSPingPongProtocol|VSRaftProtocol" | head -5 - -echo -echo "=== Solution ===" -echo -echo "The raft.dat file needs to be recreated with Raft protocol events." -echo "Since the file uses Java serialization, it must be created via the GUI:" -echo -echo "1. Run: java -jar target/ds-sim-1.0.1-SNAPSHOT.jar" -echo "2. Create a new simulation (File → New)" -echo "3. Add 3 processes" -echo "4. For each process:" -echo " - Right-click → Protocols → Raft Consensus Algorithm → Server" -echo "5. Save as: saved-simulations/raft.dat" -echo -echo "The issue is that the current raft.dat is just a copy of ping-pong.dat" -echo "and still contains PingPong protocol activation events."
\ No newline at end of file diff --git a/scripts/create-raft-simulation.sh b/scripts/create-raft-simulation.sh deleted file mode 100755 index e133ce7..0000000 --- a/scripts/create-raft-simulation.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/bin/bash -# -# Create and verify a Raft consensus simulation for DS-Sim -# - -echo "=== DS-Sim Raft Simulation Creator ===" -echo - -# Check if we're in the right directory -if [ ! -f "pom.xml" ]; then - echo "Error: Must be run from the DS-Sim root directory" - exit 1 -fi - -# Check if the application is built -if [ ! -f "target/ds-sim-1.0.1-SNAPSHOT.jar" ]; then - echo "Error: Application not built. Run 'mvn clean package' first" - exit 1 -fi - -# Create the raft.dat file from template -if [ -f "saved-simulations/ping-pong.dat" ]; then - cp "saved-simulations/ping-pong.dat" "saved-simulations/raft.dat" - echo "✓ Created saved-simulations/raft.dat from template" -else - echo "✗ Error: Could not find ping-pong.dat template" - exit 1 -fi - -# Create a verification script -cat > verify-raft.sh << 'EOF' -#!/bin/bash -echo "Verifying Raft simulation..." -if [ -f "saved-simulations/raft.dat" ]; then - echo "✓ raft.dat exists" - ls -lh saved-simulations/raft.dat -else - echo "✗ raft.dat not found" -fi -EOF -chmod +x verify-raft.sh - -echo -echo "=== MANUAL STEPS REQUIRED ===" -echo -echo "The raft.dat file has been created but needs manual configuration." -echo "Please follow these steps:" -echo -echo "1. Start DS-Sim:" -echo " java -jar target/ds-sim-1.0.1-SNAPSHOT.jar" -echo -echo "2. Open the template:" -echo " File → Open → saved-simulations/raft.dat" -echo -echo "3. Configure for Raft (IMPORTANT - do all steps):" -echo " a) Delete existing protocol events in the task list" -echo " b) Right-click Process 1 → Protocols → Raft Consensus Algorithm → Server" -echo " c) Right-click Process 2 → Protocols → Raft Consensus Algorithm → Server" -echo " d) Right-click Process 3 → Protocols → Raft Consensus Algorithm → Server" -echo -echo "4. Save the file:" -echo " File → Save" -echo -echo "5. Test the simulation:" -echo " Click the Play button to see leader election" -echo -echo "=== EXPECTED BEHAVIOR ===" -echo "- All nodes start as FOLLOWERS" -echo "- First node to timeout (150-300ms) becomes CANDIDATE" -echo "- CANDIDATE requests votes from other nodes" -echo "- Node with majority votes becomes LEADER (highlighted)" -echo "- LEADER sends heartbeats every 50ms" -echo -echo "To verify after configuration: ./verify-raft.sh"
\ No newline at end of file diff --git a/src/main/java/events/VSRegisteredEvents.java b/src/main/java/events/VSRegisteredEvents.java index 91000bc..92deeb0 100644 --- a/src/main/java/events/VSRegisteredEvents.java +++ b/src/main/java/events/VSRegisteredEvents.java @@ -99,7 +99,6 @@ public final class VSRegisteredEvents { registerEvent("protocols.implementations.VSReliableMulticastProtocol"); registerEvent("protocols.implementations.VSTwoPhaseCommitProtocol"); registerEvent("protocols.implementations.VSTimestampDemoProtocol"); - registerEvent("protocols.implementations.VSRaftProtocol"); /* Make dummy objects of each protocol, to see if they contain VSPrefs values to edit */ diff --git a/src/main/java/examples/CreateAndVerifyRaftSimulation.java b/src/main/java/examples/CreateAndVerifyRaftSimulation.java deleted file mode 100644 index 126c37c..0000000 --- a/src/main/java/examples/CreateAndVerifyRaftSimulation.java +++ /dev/null @@ -1,142 +0,0 @@ -package examples; - -import simulator.*; -import core.*; -import prefs.*; -import events.*; -import events.internal.*; -import events.implementations.*; -import serialize.VSSerialize; -import java.io.*; - -/** - * Creates a Raft simulation and verifies it can be loaded properly. - */ -public class CreateAndVerifyRaftSimulation { - - private static final String RAFT_PROTOCOL = "protocols.implementations.VSRaftProtocol"; - - public static void main(String[] args) throws Exception { - System.out.println("=== Creating and Verifying Raft Simulation ===\n"); - - // Initialize - VSDefaultPrefs prefs = new VSDefaultPrefs(); - prefs.fillWithDefaults(); - VSRegisteredEvents.init(prefs); - - // Step 1: Create the simulation - System.out.println("Step 1: Creating Raft simulation..."); - - VSSimulatorFrame frame = new VSSimulatorFrame(prefs, null); - VSSimulator simulator = new VSSimulator(prefs, frame); - frame.addSimulator(simulator); - - // Access visualization - java.lang.reflect.Field vizField = VSSimulator.class.getDeclaredField("simulatorVisualization"); - vizField.setAccessible(true); - VSSimulatorVisualization viz = (VSSimulatorVisualization) vizField.get(simulator); - - // Add processes (5 total: 3 servers + 2 clients) - while (viz.getNumProcesses() < 5) { - java.lang.reflect.Method addProcessMethod = VSSimulatorVisualization.class.getDeclaredMethod("addProcess"); - addProcessMethod.setAccessible(true); - addProcessMethod.invoke(viz); - } - - VSTaskManager taskManager = viz.getTaskManager(); - - // Add Raft server activations - System.out.println(" - Adding 3 Raft servers"); - for (int i = 0; i < 3; i++) { - VSProtocolEvent serverEvent = new VSProtocolEvent(); - serverEvent.setProtocolClassname(RAFT_PROTOCOL); - serverEvent.isClientProtocol(false); - serverEvent.isProtocolActivation(true); - - VSTask task = new VSTask(0, viz.getProcess(i), serverEvent, false); - taskManager.addTask(task); - } - - // Add Raft client activations - System.out.println(" - Adding 2 Raft clients"); - for (int i = 3; i < 5; i++) { - VSProtocolEvent clientEvent = new VSProtocolEvent(); - clientEvent.setProtocolClassname(RAFT_PROTOCOL); - clientEvent.isClientProtocol(true); - clientEvent.isProtocolActivation(true); - - // Stagger client starts - VSTask task = new VSTask(200 + (i-3)*100, viz.getProcess(i), clientEvent, false); - taskManager.addTask(task); - } - - // Add some events - System.out.println(" - Adding crash/recovery events"); - - // Server 0 crashes at 1000, recovers at 1500 - VSProcessCrashEvent crash = new VSProcessCrashEvent(); - taskManager.addTask(new VSTask(1000, viz.getProcess(0), crash, false)); - - VSProcessRecoverEvent recover = new VSProcessRecoverEvent(); - taskManager.addTask(new VSTask(1500, viz.getProcess(0), recover, false)); - - // Save simulation - File outputFile = new File("saved-simulations/raft-verified.dat"); - outputFile.getParentFile().mkdirs(); - - VSSerialize serialize = new VSSerialize(); - serialize.saveSimulator(outputFile.getAbsolutePath(), simulator); - - frame.dispose(); - - System.out.println(" ✓ Simulation saved to: " + outputFile.getName()); - - // Step 2: Verify the simulation can be loaded - System.out.println("\nStep 2: Loading and verifying simulation..."); - - VSSimulatorFrame frame2 = new VSSimulatorFrame(prefs, null); - VSSimulator loadedSim = serialize.openSimulator(outputFile.getAbsolutePath(), frame2); - - if (loadedSim == null) { - System.err.println(" ✗ Failed to load simulation!"); - System.exit(1); - } - - // Verify contents - vizField = VSSimulator.class.getDeclaredField("simulatorVisualization"); - vizField.setAccessible(true); - VSSimulatorVisualization loadedViz = (VSSimulatorVisualization) vizField.get(loadedSim); - - System.out.println(" ✓ Simulation loaded successfully"); - System.out.println(" - Processes: " + loadedViz.getNumProcesses()); - - // Check tasks - VSTaskManager loadedTaskManager = loadedViz.getTaskManager(); - java.lang.reflect.Field tasksField = VSTaskManager.class.getDeclaredField("tasks"); - tasksField.setAccessible(true); - Object taskQueue = tasksField.get(loadedTaskManager); - java.lang.reflect.Method sizeMethod = taskQueue.getClass().getMethod("size"); - int taskCount = (Integer) sizeMethod.invoke(taskQueue); - - System.out.println(" - Sche |
