-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.java
More file actions
290 lines (265 loc) · 9.22 KB
/
Server.java
File metadata and controls
290 lines (265 loc) · 9.22 KB
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
/**
*
*/
package com.ashishp.dc.assignment.cl.main;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ashishp.dc.assignment.cl.config.Configuration;
import com.ashishp.dc.assignment.cl.entity.Node;
import com.ashishp.dc.assignment.cl.handler.InputHandler;
import com.ashishp.dc.assignment.cl.handler.NetworkHandler;
import com.ashishp.dc.assignment.cl.handler.RemoteHandler;
import com.ashishp.dc.assignment.cl.handler.StorageHandler;
import com.ashishp.dc.assignment.cl.remote.NodeRemote;
/**
* @author <a href="http://www.linkedin.com/in/aashishpanchal">Aashish</a>
*
*/
public class Server {
private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);
private Configuration configuration;
@Nullable
private static Node node;
private static NodeState nodeState = NodeState.DISCONNECTED;
/**
* Thread pool scheduler of N threads for money transfer and snapshot taking
*/
private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
public Server() {
super();
configuration = Configuration.getInstance();
LOGGER.debug("========System Configuration====\n {}", configuration);
}
public static void main(String args[]) {
LOGGER.debug("Starting Server...");
new Server();
if (BankTransfer.MIN_AMOUNT >= BankTransfer.MAX_AMOUNT
|| BankTransfer.MAX_AMOUNT >= BankTransfer.INITIAL_BALANCE) {
LOGGER.warn(
"Bank transfer properties must maintain formula [ MIN_AMOUNT < MAX_AMOUNT < INITIAL_BALANCE ] !");
return;
}
StorageHandler.init();
try {
create("localhost", 10);
join("localhost", 15, "localhost", 10);
join("localhost", 20, "localhost", 15);
join("localhost", 25, "localhost", 20);
join("localhost", 30, "localhost", 25);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NetworkHandler.printMachineIPv4();
LOGGER.info("In oredr to view Branch details type 'view'");
LOGGER.info("In order to create snapshot type 'snapshot'");
LOGGER.info("\n");
LOGGER.info("Bank is ready for request >");
InputHandler.readInput(Server.class.getName());
}
/**
* Signals current node to create the graph
*
* @param nodeHost
* host for new current node
* @param nodeId
* id for new current node
*/
public static void create(@NotNull String nodeHost, int nodeId) throws Exception {
if (nodeState != NodeState.DISCONNECTED) {
LOGGER.warn("Must be DISCONNECTED to create! Current nodeState=" + nodeState);
return;
}
if (nodeId <= 0) {
LOGGER.warn("Node id must be positive integer [ nodeID > 0 ] !");
return;
}
startRMIRegistry();
LOGGER.info("NodeId=" + nodeId + " is the first bank in the graph");
node = register(nodeId, nodeHost);
LOGGER.info("NodeId=" + nodeId + " is connected as first node=" + node);
nodeState = NodeState.CONNECTED;
startMoneyTransferring();
LOGGER.debug("Node State after Create: {}", nodeState);
}
/**
* Signals current node to join the graph: - accumulate the graph structure of
* all available banks from the existing node - start randomly sending/accepting
* money transfers
* <p>
* Existing node MUST be operational!
*
* @param nodeHost
* host for new current node
* @param nodeId
* id for new current node
* @param existingNodeHost
* of node in the graph to fetch data from
* @param existingNodeId
* of node in the graph to fetch data from
*/
public static void join(@NotNull String nodeHost, int nodeId, @NotNull String existingNodeHost, int existingNodeId)
throws Exception {
LOGGER.debug("Node state at time of joining : {}", nodeState);
if (nodeState == NodeState.DISCONNECTED) {
LOGGER.warn("Must be CONNECTED to join! Current nodeState=" + nodeState);
return;
}
if (nodeId <= 0) {
LOGGER.warn("Node id must be positive integer [ nodeID > 0 ] !");
return;
}
startRMIRegistry();
LOGGER.info("NodeId=" + nodeId + " connects to existing nodeId=" + existingNodeId);
Node existingNode = RemoteHandler.getRemoteNode(existingNodeId, existingNodeHost).getNode();
if (existingNode.getNodes().isEmpty()) {
LOGGER.warn("Existing node must be operational!");
return;
}
if (existingNode.getNodes().containsKey(nodeId)) {
LOGGER.warn("Cannot join as nodeId=" + nodeId + " already taken!");
return;
}
node = register(nodeId, nodeHost);
node.putNodes(existingNode.getNodes());
announceJoin();
LOGGER.info("NodeId=" + nodeId + " connected as node=" + node + " from existingNode=" + existingNode);
nodeState = NodeState.CONNECTED;
startMoneyTransferring();
}
/**
* View the graph topology aka all the banks in connected component
*/
public static void view() throws RemoteException {
if (nodeState != NodeState.CONNECTED) {
LOGGER.warn("Must be CONNECTED to view topology! Current nodeState=" + nodeState);
return;
}
LOGGER.info("Viewing topology from node=" + node);
node.getNodes().entrySet().forEach(n -> {
try {
RemoteHandler.getRemoteNode(n.getKey(), n.getValue()).getNode();
} catch (RemoteException e) {
throw new RuntimeException(e);
}
});
}
/**
* Initiate distributed snapshot to all known nodes (all nodes are
* interconnected as a digraph)
*/
public static void snapshot() throws RemoteException {
if (nodeState != NodeState.CONNECTED) {
LOGGER.warn("Must be CONNECTED to initiate the distributed snapshot! Current nodeState=" + nodeState);
return;
}
LOGGER.info("Starting distributed snapshot from node=" + node);
RemoteHandler.getRemoteNode(node).receiveMarker(node.getId());
}
/**
* Registers RMI for new node, initializes node object
*
* @param id
* of the new node
* @param host
* of the new node
*/
@NotNull
private static Node register(int id, @NotNull String host) throws Exception {
System.setProperty("java.rmi.server.hostname", host);
Node node = new Node(id, host);
Naming.bind("rmi://" + node.getHost() + "/NodeRemote" + node.getId(), new NodeRemote(node));
String bindedNodes[] = Naming.list("rmi://" + node.getHost());
for (String n : bindedNodes) {
LOGGER.info("Node {} bounded.", n);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
LOGGER.info("Auto-leaving process initiated...");
try {
if (nodeState == NodeState.CONNECTED) {
leave();
}
} catch (Exception e) {
//LOGGER.error("Failed to leave node", e);
}
}
});
return node;
}
/**
* Signals current node to leave the graph
*/
private static void leave() throws Exception {
LOGGER.info("NodeId=" + node.getId() + " is disconnecting from the graph...");
Naming.unbind("rmi://" + node.getHost() + "/NodeRemote" + node.getId());
StorageHandler.removeFile(node.getId());
LOGGER.info("NodeId=" + node.getId() + " disconnected");
node = null;
nodeState = NodeState.DISCONNECTED;
}
/**
* Announce JOIN operation to the nodes in the graph
*/
private static void announceJoin() throws RemoteException {
LOGGER.debug("Announcing join to nodes=" + Arrays.toString(node.getNodes().entrySet().toArray()));
node.getNodes().entrySet().parallelStream().filter(n -> n.getKey() != node.getId()).forEach(n -> {
try {
RemoteHandler.getRemoteNode(n.getKey(), n.getValue()).addNode(node.getId(), node.getHost());
LOGGER.trace("Announced join to nodeId=" + n.getKey());
} catch (RemoteException e) {
throw new RuntimeException(e);
}
});
}
private static void startMoneyTransferring() {
// LOGGER.debug("--------- Starting money transferring ------------");
// LOGGER.debug("\n");
executor.scheduleAtFixedRate((Runnable) () -> {
try {
if (node != null && node.getNodes().size() > 1) {
Node randomNode = getRandomNode();
int randomAmount = new Random().nextInt(BankTransfer.MAX_AMOUNT + 1) + BankTransfer.MIN_AMOUNT;
// LOGGER.debug("Trasnferring {} funds to node {} ", randomAmount,
// randomNode.getId());
RemoteHandler.getRemoteNode(node).transferMoney(randomNode.getId(), randomAmount);
}
} catch (RemoteException e) {
LOGGER.error("Failed to transfer to random node!", e);
}
}, 0, BankTransfer.TIMEOUT_FREQUENCY, TimeUnit.valueOf(BankTransfer.TIMEOUT_UNIT));
LOGGER.debug("\n");
}
/**
* Gets node given nodeId
*
* @return currentNode if nodeId is the same, remote node otherwise
*/
private static Node getRandomNode() {
int index = new Random().nextInt(node.getNodes().size() - 1);
int nodeId = node.getNodes().keySet().parallelStream().filter(n -> n != node.getId())
.collect(Collectors.toList()).get(index);
return new Node(nodeId, node.getNodes().get(nodeId));
}
/**
* Starts RMI registry on default port if not started already
*/
private static void startRMIRegistry() {
try {
LocateRegistry.createRegistry(Configuration.getInstance().getRmiPort());
} catch (RemoteException e) {
// already started
}
}
}