-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathinterface.java
More file actions
216 lines (190 loc) · 6.23 KB
/
Copy pathinterface.java
File metadata and controls
216 lines (190 loc) · 6.23 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
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import org.zeromq.ZMsg;
import org.zeromq.ZThread;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Interface class for Chapter on Distributed Computing
* This implements an "interface" to our network of nodes
*/
public class Interface {
ZContext ctx; // Our context wrapper
ZMQ.Socket pipe;
public Interface() {
ctx = new ZContext();
pipe = ZThread.fork(ctx, new InterfaceAgent());
}
/**
* Here we wait for a message from the interface.
*
* @return Zmsg object or null if interrupted
*/
public ZMsg recv() {
return ZMsg.recvMsg(pipe);
}
public void destroy() {
this.ctx.destroy();
}
/**
* Asynchronous part, works in the background
*/
private static class InterfaceAgent implements ZThread.IAttachedRunnable {
private static final int PING_PORT_NUMBER = 9999;
private static final int PING_INTERVAL = 1000; // Once per second
private static final byte[] emptyUUID = new byte[16];
private Udplib udp; // UDP object
private UUID uuid; // Our UUID as binary blob
private Map<UUID, Peer> peers;
private ZMQ.Socket pipe; // Pipe back to application
private static ByteBuffer serializeUUID(UUID obj) {
ByteBuffer result = ByteBuffer.allocate(16);
result.putLong(obj.getMostSignificantBits());
result.putLong(obj.getLeastSignificantBits());
result.flip();
return result;
}
private static UUID deserializeUUID(ByteBuffer buffer) {
long msb = buffer.getLong(0);
long lsb = buffer.getLong(8);
return new UUID(msb, lsb);
}
private void init(ZMQ.Socket pipe) {
this.pipe = pipe;
try {
udp = new Udplib(PING_PORT_NUMBER);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
peers = new ConcurrentHashMap<>();
uuid = UUID.randomUUID();
System.out.println("I'm " + uuid);
}
private void destroy() throws IOException {
udp.destroy();
}
/**
* Here we handle the different control messages from the frontend.
*/
private void controlMsg() {
// Get the whole message off the pipe in one go
ZMsg msg = ZMsg.recvMsg(pipe);
String command = msg.popString();
// We don't actually implement any control commands yet
// but if we did, this would be where we did it…
// if("EXAMPLE".equals(command)) {
// }
msg.destroy();
}
/**
* This is how we handle a beacon coming into our UDP socket;
* this may be from other peers or an echo of our own broadcast
* beacon:
*/
private void handleBeacon() {
ByteBuffer uuidBuffer = ByteBuffer.allocate(16);
try {
udp.recv(uuidBuffer);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
if (Arrays.equals(uuidBuffer.array(), emptyUUID))
return; //nothing to read
UUID uuid = deserializeUUID(uuidBuffer);
// If we got a UUID and it's not our own beacon, we have a peer
if (!this.uuid.equals(uuid)) {
// Find or create peer via its UUID string
Peer peer = peers.get(uuid);
if (peer == null) {
peer = new Peer(uuid);
peers.put(uuid, peer);
// Report peer joined the network
pipe.sendMore("JOINED");
pipe.send(serializeUUID(uuid).array());
}
// Any activity from the peer means it's alive
peer.isAlive();
}
}
/**
* This method checks one peer peer for expiration; if the peer hasn't
* sent us anything by now, it's "dead" and we can delete it:
*/
private void reapPeer(Peer peer) {
if (System.currentTimeMillis() >= peer.expiresAt) {
// Report peer left the network
pipe.sendMore("LEFT");
pipe.send(serializeUUID(peer.uuid).array());
peers.remove(peer.uuid);
}
}
/**
* This is the main loop for the background agent. It uses zmq_poll
* to monitor the frontend pipe (commands from the API) and the
* backend UDP handle (beacons):
*/
@Override
public void run(Object[] args, ZContext ctx, ZMQ.Socket pipe) {
init(pipe);
// Send first beacon immediately
long pingAt = System.currentTimeMillis();
ZMQ.PollItem[] pollItems = new ZMQ.PollItem[]{
new ZMQ.PollItem(pipe, ZMQ.Poller.POLLIN),
new ZMQ.PollItem(udp.handle(), ZMQ.Poller.POLLIN)
};
while (!Thread.currentThread().isInterrupted()) {
long timeout = pingAt - System.currentTimeMillis();
if (timeout < 0)
timeout = 0;
if (ZMQ.poll(pollItems, 2, timeout) == -1)
break; // Interrupted
// If we had activity on the pipe, go handle the control
// message. Current code never sends control messages.
if (pollItems[0].isReadable())
this.controlMsg();
// If we had input on the UDP socket, go process that
if (pollItems[1].isReadable())
this.handleBeacon();
// If we passed the 1-second mark, broadcast our beacon
if (System.currentTimeMillis() >= pingAt) {
try {
udp.send(serializeUUID(this.uuid));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
pingAt = System.currentTimeMillis() + PING_INTERVAL;
}
// Delete and report any expired peers
for (Peer peer : peers.values())
reapPeer(peer);
}
try {
this.destroy();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
/**
* This class defines each peer that we discover and track:
*/
private static class Peer {
private static final int PEER_EXPIRY = 5000; // Five seconds and it's gone
private UUID uuid; // Peer's UUID as binary blob
private long expiresAt;
private Peer(UUID uuid) {
this.uuid = uuid;
}
private void isAlive() {
expiresAt = System.currentTimeMillis() + PEER_EXPIRY;
}
}
}