summaryrefslogtreecommitdiffstats
path: root/src/main/java/derms/Replica4pkg/Replica4.java
blob: 91bc303a912ec7e9e75200095cc38d839c48dadc (plain) (blame)
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
package derms.Replica4pkg;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.*;

import javax.jws.WebMethod;

import derms.Replica;
import derms.ReplicaManager;
import derms.Request;
import derms.Response;
import derms.util.TestLogger;
import derms.util.ThreadPool;



public class Replica4 implements Replica {

    private ReplicaManager replicaManager;
    private boolean alive = true;
    private boolean byzFailure;

    private String serverName;
    private int udpPort;
    private Map<String, Map<String, Resource>> resourceMap; //resourceName -> (resourceID -> Resource)
    private Map<String, Set<String>> coordinatorResources; //coordinatorID -> Set<resourceID>
    private Map<String, Map<String, Integer>> coordinatorResourceDurations; //coordinatorID -> (resourceID -> allocatedDuration)
    private Map<String, Integer> serverUdpPorts; //serverName -> UDP port

    public Replica4(ReplicaManager replicaManager){
        this.replicaManager = replicaManager;
        this.resourceMap = new HashMap<>();
        this.coordinatorResources = new HashMap<>();
        this.coordinatorResourceDurations = new HashMap<>();
        startUDPListener();
    }

    @Override
    public boolean isAlive() {
        return alive;
    }

    @Override
    public void startProcess(int byzantine, int crash) {
        // [TEST] Detect crash
        if (crash == 1) {
            alive = false;
        } else {
            alive = true;
        }

        // [TEST] Detect byzantine failure
        if (byzantine == 1) {
            byzFailure = true;
        } else {
            byzFailure = false;
        }

        System.out.println("[Replica 4] Process started.");
    }

    @Override
	public void processRequest(Request request) {
		log(request.toString());

		// [TEST] Simulate byzantine failure (return incorrect value)
        if (byzFailure == true) {
            Response response = new Response(request, replicaManager.getReplicaId(), "BYZANTINE FAILURE", false);
            replicaManager.sendResponseToFE(response);
            return;
        }

		String status = "";
		try {
			switch (request.getFunction()) {
				case "addResource":
					status = addResource(request.getResourceID(), request.getResourceType(), request.getDuration());
					break;
				case "removeResource":
					status = removeResource(request.getResourceID(), request.getDuration());
					break;
				case "listResourceAvailability":
					status = listResourceAvailability(request.getResourceType());
					break;
				case "requestResource":
					status = requestResource(request.getClientID(), request.getResourceID(), request.getDuration());
					break;
				case "findResource":
					status = findResource(request.getClientID(), request.getResourceType());
					break;
				case "returnResource":
					status = returnResource(request.getClientID(), request.getResourceID());
					break;
				case "swapResource":
					status = swapResource(request.getClientID(), request.getOldResourceID(), request.getOldResourceType(), request.getResourceID(), request.getResourceType());
					break;
				default:
					status = "Failure: unknown function '" + request.getFunction() + "'";
			}
		} catch (Exception e) {
			log(e.getMessage());
			status = "Failure: " + request.getFunction() + ": " + e.getMessage();
		}

		Response response = new Response(request, replicaManager.getReplicaId(), status, false); // TODO: isSuccess flag
		log("Processed request " + request + "; response: " + response);
		replicaManager.sendResponseToFE(response);
	}

    @Override
	public void restart() {
		shutdown();

		// [TEST] Restart process without byzantine failure or crash
		TestLogger.log("REPLICA 2: {RESTARTED}");
		startProcess(0, 0);
	}

    public void shutdown() {
		log("Shutting down...");
		alive = false;
		log("Finished shutting down.");
	}

    @Override
    public int getId() {
        return 4;
    }

    public synchronized void log(String message) {
        String logMessage = new Date() + " - " + message;
        System.out.println(logMessage);

        try (FileWriter fw = new FileWriter("Replica4_log.txt", true);
             BufferedWriter bw = new BufferedWriter(fw);
             PrintWriter out = new PrintWriter(bw)) {
            out.println(logMessage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @WebMethod(exclude = true)
    public void initReplica4(String serverName, int udpPort, Map<String, Integer> serverUdpPorts) {
        this.serverName = serverName;
        this.udpPort = udpPort;
        this.serverUdpPorts = serverUdpPorts;
    }

    //Start UDP Listener
    private void startUDPListener() {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket(udpPort)) {
                byte[] buffer = new byte[4096];
                System.out.println(serverName + " UDP Server started on port " + udpPort);

                while (true) {
                    DatagramPacket request = new DatagramPacket(buffer, buffer.length);
                    socket.receive(request);
                    new Thread(() -> handleUDPRequest(request)).start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //Handle UDP Request
    private void handleUDPRequest(DatagramPacket requestPacket) {
        try {
            String requestData = new String(requestPacket.getData(), 0, requestPacket.getLength());
            String[] parts = requestData.split(":");
            String methodName = parts[0];
            String[] params = Arrays.copyOfRange(parts, 1, parts.length);

            String responseData = "";

            switch (methodName) {
                case "listResourceAvailability":
                    responseData = handleListResourceAvailability(params[0]);
                    break;
                case "requestResource":
                    responseData = handleLocalResourceRequest(params[0], params[1], Integer.parseInt(params[2]));
                    break;
                case "findResource":
                    responseData = handleFindResource(params[0], params[1]);
                    break;
                case "returnResource":
                    responseData = handleReturnResource(params[0], params[1]);
                    break;
                case "swapRequestResource":
                    responseData = handleSwapRequestResource(params[0], params[1], Integer.parseInt(params[2]));
                    break;    
                case "swapReturnResource":
                    responseData = handleSwapReturnResource(params[0], params[1]);
                    break;
                case "checkCoordinatorResource":
                    responseData = checkCoordinatorHasResource(params[0], params[1]);
                    break;
                case "getCoordinatorResourceDuration":
                    int duration = getCoordinatorResourceDuration(params[0], params[1]);
                    responseData = String.valueOf(duration);
                    break;
                default:
                    responseData = "Invalid method";
            }

            //Send response
            byte[] responseBytes = responseData.getBytes();
            DatagramPacket responsePacket = new DatagramPacket(responseBytes, responseBytes.length, requestPacket.getAddress(), requestPacket.getPort());
            DatagramSocket socket = new DatagramSocket();
            socket.send(responsePacket);
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //Operation Handlers
    private synchronized String handleListResourceAvailability(String resourceName) {
        StringBuilder result = new StringBuilder();
        resourceName = resourceName.toUpperCase();
        Map<String, Resource> resources = resourceMap.get(resourceName);

        if (resources != null) {
            for (Resource resource : resources.values()) {
            	if (resource.getDuration() > 0) {
                    result.append(resource.getResourceName()).append(" - ").append(serverName).append(" ").append(resource.getDuration()).append("\n");
            	}
            }
        }
        return result.toString();
    }

    private synchronized String handleLocalResourceRequest(String coordinatorID, String resourceID, int duration) {
        for (Map<String, Resource> resources : resourceMap.values()) {
            Resource resource = resources.get(resourceID);
            if (resource != null) {
                if (resource.getDuration() >= duration) {
                    resource.subDuration(duration);
                    coordinatorResources.computeIfAbsent(coordinatorID, k -> new HashSet<>()).add(resourceID);
                    coordinatorResourceDurations.computeIfAbsent(coordinatorID, k -> new HashMap<>()).put(resourceID, duration);

                    log("Resource " + resourceID + " allocated to " + coordinatorID + " for duration " + duration);
                    return "Resource " + resourceID + " allocated successfully.";
                } else {
                    return "Insufficient duration for resource " + resourceID;
                }
            }
        }
        return "Resource " + resourceID + " not found.";
    }

    private synchronized String handleFindResource(String coordinatorID, String resourceName) {
        StringBuilder result = new StringBuilder();
        resourceName = resourceName.toUpperCase();
        Set<String> resources = coordinatorResources.get(coordinatorID);
        if (resources != null) {
            Map<String, Integer> resourceDurations = coordinatorResourceDurations.get(coordinatorID);
            if (resourceDurations != null) {
                for (String resourceID : resources) {
                    Resource resource = getResourceByID(resourceID);
                    if (resource != null && resource.getResourceName().equals(resourceName)) {
                        Integer allocatedDuration = resourceDurations.get(resourceID);
                        if (allocatedDuration != null) {
                            result.append(resource.getResourceName()).append(" - ").append(resourceID).append(" ").append(allocatedDuration).append("\n");
                        }
                    }
                }
            }
        }
        return result.toString();
    }

    private synchronized String handleReturnResource(String coordinatorID, String resourceID) {
        Set<String> resources = coordinatorResources.get(coordinatorID);
        if (resources != null && resources.contains(resourceID)) {
            resources.remove(resourceID);
            if (resources.isEmpty()) {
                coordinatorResources.remove(coordinatorID);
            }
            Resource resource = getResourceByID(resourceID);
            if (resource != null) {
                Map<String, Integer> resourceDurations = coordinatorResourceDurations.get(coordinatorID);
                if (resourceDurations != null) {
                    Integer allocatedDuration = resourceDurations.remove(resourceID);
                    if (allocatedDuration != null) {
                        resource.addDuration(allocatedDuration);
                    }
                    if (resourceDurations.isEmpty()) {
                        coordinatorResourceDurations.remove(coordinatorID);
                    }
                }
                log("Coordinator " + coordinatorID + " returned resource " + resourceID);
                return "Resource " + resourceID + " returned successfully.";
            } else {
                return "Resource " + resourceID + " not found.";
            }
        } else {
            return "You do not occupy resource " + resourceID + ".";
        }
    }

    //Helper Methods
    private Resource getResourceByID(String resourceID) {
        for (Map<String, Resource> resources : resourceMap.values()) {
            if (resources.containsKey(resourceID)) {
                return resources.get(resourceID);
            }
        }
        return null;
    }
    
    private synchronized String handleSwapRequestResource(String coordinatorID, String resourceID, int duration) {
        //Attempt to allocate the resource to the coordinator
        for (Map<String, Resource> resources : resourceMap.values()) {
            Resource resource = resources.get(resourceID);
            if (resource != null) {
                if (resource.getDuration() >= duration) {
                    resource.subDuration(duration);
                    coordinatorResources.computeIfAbsent(coordinatorID, k -> new HashSet<>()).add(resourceID);
                    coordinatorResourceDurations.computeIfAbsent(coordinatorID, k -> new HashMap<>()).put(resourceID, duration);
                    log("Resource " + resourceID + " temporarily allocated to " + coordinatorID + " for swapping, duration " + duration);
                    return "Success";
                } else {
                    return "Insufficient duration for resource " + resourceID;
                }
            }
        }
        return "Resource " + resourceID + " not found.";
    }
    
    private synchronized String handleSwapReturnResource(String coordinatorID, String resourceID) {
        Set<String> resources = coordinatorResources.get(coordinatorID);
        if (resources != null && resources.contains(resourceID)) {
            resources.remove(resourceID);
            if (resources.isEmpty()) {
                coordinatorResources.remove(coordinatorID);
            }
            Resource resource = getResourceByID(resourceID);
            if (resource != null) {
                Map<String, Integer> resourceDurations = coordinatorResourceDurations.get(coordinatorID);
                if (resourceDurations != null) {
                    Integer allocatedDuration = resourceDurations.remove(resourceID);
                    if (allocatedDuration != null) {
                        resource.addDuration(allocatedDuration);
                    }
                    if (resourceDurations.isEmpty()) {
                        coordinatorResourceDurations.remove(coordinatorID);
                    }
                }
                log("Coordinator " + coordinatorID + " resource " + resourceID + " allocation undone during swap");
                return "Success";
            } else {
                return "Resource " + resourceID + " not found.";
            }
        } else {
            return "Coordinator did not acquire resource " + resourceID;
        }
    }

    private String sendUDPRequest(String serverName, String methodName, String... params) {
        String response = "";
        try {
            InetAddress host = InetAddress.getByName("localhost");
            int port = serverUdpPorts.get(serverName);
            String requestData = methodName + ":" + String.join(":", params);

            byte[] requestBytes = requestData.getBytes();
            DatagramPacket requestPacket = new DatagramPacket(requestBytes, requestBytes.length, host, port);

            DatagramSocket socket = new DatagramSocket();
            socket.send(requestPacket);

            byte[] buffer = new byte[4096];
            DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length);
            socket.receive(responsePacket);

            response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    //Implement ResponderInterface Methods
    public synchronized String addResource(String resourceID, String resourceName, int duration) {
        resourceName = resourceName.toUpperCase();
        Map<String, Resource> resources = resourceMap.computeIfAbsent(resourceName, k -> new HashMap<>());
        Resource resource = resources.get(resourceID);

        if (resource != null) {
            if (duration > resource.getDuration()) {
                resource.setDuration(duration);
                log("Updated duration of resource " + resourceID);
                return "Resource " + resourceID + " duration updated.";
            } else {
                log("Resource " + resourceID + " already exists with greater or equal duration.");
                return "Resource " + resourceID + " already exists with greater or equal duration.";
            }
        } else {
            resource = new Resource(resourceName, duration);
            resources.put(resourceID, resource);
            log("Added new resource " + resourceID);
            return "Resource " + resourceID + " added successfully.";
        }
    }

    public synchronized String removeResource(String resourceID, int duration) {
        for (Map<String, Resource> resources : resourceMap.values()) {
            Resource resource = resources.get(resourceID);
            if (resource != null) {
                if (duration >= resource.getDuration()) {
                    resources.remove(resourceID);
                    log("Resource " + resourceID + " completely removed.");
                    return "Resource " + resourceID + " completely removed.";
                } else {
                    resource.subDuration(duration);
                    log("Decreased duration of resource " + resourceID);
                    return "Resource " + resourceID + " duration decreased by " + duration + ".";
                }
            }
        }
        log("Resource " + resourceID + " not found.");
        return "Resource " + resourceID + " not found.";
    }

    public String listResourceAvailability(String resourceName) {
        resourceName = resourceName.toUpperCase();
        StringBuilder result = new StringBuilder();

        synchronized (this) {
            Map<String, Resource> resources = resourceMap.get(resourceName);
            if (resources != null) {
                for (Resource resource : resources.values()) {
                	if (resource.getDuration() > 0) {
	                    result.append(resource.getResourceName()).append(" - ").append(serverName).append(" ").append(resource.getDuration()).append("\n");
	                }
                }
            }
        }

        for (String otherServer : serverUdpPorts.keySet()) {
            if (!otherServer.equals(serverName)) {
                String response = sendUDPRequest(otherServer, "listResourceAvailability", resourceName);
                result.append(response);
            }
        }

        return result.toString();
    }

    public String requestResource(String coordinatorID, String resourceID, int duration) {
        String resourceServer = resourceID.substring(0, 3).toUpperCase();
        String response;

        if (resourceServer.equals(serverName)) {
            response = handleLocalResourceRequest(coordinatorID, resourceID, duration);
        } else {
            response = sendUDPRequest(resourceServer, "requestResource", coordinatorID, resourceID, String.valueOf(duration));
        }

        log("Coordinator " + coordinatorID + " requested resource " + resourceID + ": " + response);
        return response;
    }

    public String findResource(String coordinatorID, String resourceName) {
        resourceName = resourceName.toUpperCase();
        StringBuilder result = new StringBuilder();

        for (String otherServer : serverUdpPorts.keySet()) {
            String response;
            if (otherServer.equals(serverName)) {
                response = handleFindResource(coordinatorID, resourceName);
            } else {
                response = sendUDPRequest(otherServer, "findResource", coordinatorID, resourceName);
            }
            result.append(response);
        }

        return result.toString();
    }

    public String returnResource(String coordinatorID, String resourceID) {
        String resourceServer = resourceID.substring(0, 3).toUpperCase();
        String response;

        if (resourceServer.equals(serverName)) {
            response = handleReturnResource(coordinatorID, resourceID);
        } else {
            response = sendUDPRequest(resourceServer, "returnResource", coordinatorID, resourceID);
        }

        log("Coordinator " + coordinatorID + " returned resource " + resourceID + ": " + response);
        return response;
    }
    
    private synchronized int getCoordinatorResourceDuration(String coordinatorID, String resourceID) {
        Map<String, Integer> resourceDurations = coordinatorResourceDurations.get(coordinatorID);
        if (resourceDurations != null && resourceDurations.containsKey(resourceID)) {
            return resourceDurations.get(resourceID);
        }
        return 0;
    }
    
    private synchronized String checkCoordinatorHasResource(String coordinatorID, String resourceID) {
        Set<String> resources = coordinatorResources.get(coordinatorID);
        if (resources != null && resources.contains(resourceID)) {
            return "true";
        }
        return "false";
    }
    
    public String swapResource(String coordinatorID, String oldResourceID, String oldResourceType, String newResourceID, String newResourceType) {
        String oldResourceServer = oldResourceID.substring(0, 3).toUpperCase();
        String newResourceServer = newResourceID.substring(0, 3).toUpperCase();

        //Check if the coordinator has the old resource
        String checkOldResourceResponse;
        if (oldResourceServer.equals(serverName)) {
            checkOldResourceResponse = checkCoordinatorHasResource(coordinatorID, oldResourceID);
        } else {
            checkOldResourceResponse = sendUDPRequest(oldResourceServer, "checkCoordinatorResource", coordinatorID, oldResourceID);
        }

        if (!checkOldResourceResponse.equals("true")) {
            return "Coordinator has not acquired the old resource.";
        }

        //Get the duration allocated to the old resource
        int duration;
        if (oldResourceServer.equals(serverName)) {
            duration = getCoordinatorResourceDuration(coordinatorID, oldResourceID);
        } else {
            String durationStr = sendUDPRequest(oldResourceServer, "getCoordinatorResourceDuration", coordinatorID, oldResourceID);
            duration = Integer.parseInt(durationStr);
        }

        //Attempt to acquire the new resource
        String requestResponse;
        if (newResourceServer.equals(serverName)) {
            requestResponse = handleLocalResourceRequest(coordinatorID, newResourceID, duration);
        } else {
            requestResponse = sendUDPRequest(newResourceServer, "requestResource", coordinatorID, newResourceID, String.valueOf(duration));
        }

        if (!requestResponse.contains("allocated successfully")) {
            return "Failed to acquire new resource: " + requestResponse;
        }

        //Return the old resource
        String returnResponse;
        if (oldResourceServer.equals(serverName)) {
            returnResponse = handleReturnResource(coordinatorID, oldResourceID);
        } else {
            returnResponse = sendUDPRequest(oldResourceServer, "returnResource", coordinatorID, oldResourceID);
        }

        if (!returnResponse.contains("returned successfully")) {
            //Undo the allocation of the new resource
            if (newResourceServer.equals(serverName)) {
                handleReturnResource(coordinatorID, newResourceID);
            } else {
                sendUDPRequest(newResourceServer, "returnResource", coordinatorID, newResourceID);
            }
            return "Failed to return old resource: " + returnResponse;
        }

        log("Coordinator " + coordinatorID + " swapped resource " + oldResourceID + " with " + newResourceID);

        return "Resource swap successful.";
    }
}