-
Notifications
You must be signed in to change notification settings - Fork 5
/
DistributedVerticle.java
387 lines (319 loc) · 12.7 KB
/
DistributedVerticle.java
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
package org.genericsystem.watch.beta;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.genericsystem.common.Generic;
import org.genericsystem.cv.Classifier;
import org.genericsystem.cv.Ocr;
import org.genericsystem.cv.PdfToPngConverter;
import org.genericsystem.kernel.Cache;
import org.genericsystem.kernel.Engine;
import org.genericsystem.watch.ClassifierVerticle;
import org.genericsystem.watch.beta.Model.Message;
import org.genericsystem.watch.beta.Model.Task;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.eventbus.EventBusOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.core.spi.cluster.ClusterManager;
import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager;
public class DistributedVerticle extends AbstractVerticle {
public static final String PUBLIC_ADDRESS = "publicAddress";
public final String PRIVATE_ADDRESS = "privateAddress " + hashCode();
protected final Engine engine = new Engine(System.getenv("HOME") + "/genericsystem/cloud/", Task.class,
Message.class);
protected final Cache cache = engine.newCache();
protected final Generic messageType = engine.find(Message.class);
protected final Generic taskType = engine.find(Task.class);
private final RoundRobin roundrobin = new RoundRobin();
private static final DeliveryOptions TIMEOUT = new DeliveryOptions().setSendTimeout(2000);
private static final String IP_ADDRESS = "192.168.1.11";
private static final int ATTEMPTS = 5;
private static final long AVAILABILITY_PERIODICITY = 5000;
private static final long TASK_CREATION_PERIODICITY = 10000;
private static final long MESSAGE_SEND_PERIODICITY = 5000;
protected static final String TODO = "TODO";
private static final String INPROGRESS = "IN PROGRESS";
private static final String STARTED = "started";
private static final String FINISHED = "finished";
private static final String ABORTED = "aborted";
private static final String OK = "OK";
private static final String KO = "KO";
private static final String AbsoluteAddress = System.getenv("HOME") + "/genericsystem/cloud";
private static final String pdfDir = AbsoluteAddress + "/pdf";
private static final String pngDir = AbsoluteAddress + "/png";
private static final int port = 8084;
private int nb_executions;
public static void main(String[] args) {
ClusterManager mgr = new HazelcastClusterManager();
VertxOptions vertxOptions = new VertxOptions().setClustered(true).setClusterManager(mgr);
vertxOptions.setEventBusOptions(new EventBusOptions()).setClustered(true);
vertxOptions.setClusterHost(IP_ADDRESS);
vertxOptions.setMaxWorkerExecuteTime(Long.MAX_VALUE);
Vertx.clusteredVertx(vertxOptions, res -> {
if (res.succeeded()) {
Vertx vertx = res.result();
vertx.deployVerticle(new DistributedVerticle(), result -> {
System.out.println(result.result());
});
} else {
throw new IllegalStateException(res.cause());
}
});
}
@Override
public void start() throws Exception {
cache.safeConsum(nothing -> {
for (Generic task1 : taskType.getInstances()) {
if (STARTED.equals(new JsonObject((String) task1.getValue()).getString("state"))) {
addMessage(Paths.get(new JsonObject((String) task1.getValue()).getString("file")),
new JsonObject((String) task1.getValue()).getInteger("step"),
new JsonObject((String) task1.getValue()).getLong("task"), TODO,
new JsonObject((String) task1.getValue()).getInteger("max_parallel_executions"));
task1.remove();
}
}
for (Generic message1 : messageType.getInstances()) {
if (INPROGRESS.equals(new JsonObject((String) message1.getValue()).getString("state"))) {
addMessage(Paths.get(new JsonObject((String) message1.getValue()).getString("file")),
new JsonObject((String) message1.getValue()).getInteger("step"),
new JsonObject((String) message1.getValue()).getLong("task"), TODO,
new JsonObject((String) message1.getValue()).getInteger("max_parallel_executions"));
message1.remove();
}
}
cache.flush();
});
startServer();
// Periodic aknowledge of availability
vertx.setPeriodic(AVAILABILITY_PERIODICITY, h -> {
vertx.eventBus().publish(PUBLIC_ADDRESS, PRIVATE_ADDRESS);
});
vertx.eventBus().consumer(PUBLIC_ADDRESS, message -> {
roundrobin.Register((String) message.body());
});
// // Periodic : Task creation
// vertx.setPeriodic(TASK_CREATION_PERIODICITY, m -> {
// cache.safeConsum(n -> {
// messageType.addInstance(new JsonObject().put("task",
// System.currentTimeMillis()).put("state", TODO)
// .put("max_parallel_executions", 5).put("step", 1).put("file",
// "/image-0.png").encodePrettily());
// cache.flush();
// });
// });
// Periodic : Messages send
vertx.setPeriodic(MESSAGE_SEND_PERIODICITY, l -> {
cache.safeConsum(n -> {
System.out.println("========================================================================");
System.out.println(messageType.getInstances().toList().toString());
System.out.println("------------------------------------------------------------------------");
System.out.println(taskType.getInstances().toList().toString());
System.out.println("========================================================================");
for (Generic message : messageType.getInstances()) {
JsonObject json = new JsonObject((String) message.getValue());
if (TODO.equals(json.getString("state"))) {
String workerAddress = roundrobin.getNextAddress();
if (workerAddress != null) {
message.remove();
Generic inProgress = messageType.addInstance(new JsonObject()
.put("task", json.getLong("task")).put("state", INPROGRESS)
.put("max_parallel_executions", 5).put("step", json.getLong("step"))
.put("file", json.getString("file")).put("IP", IP_ADDRESS).encodePrettily());
cache.flush();
vertx.eventBus().send(workerAddress, inProgress.getValue(), TIMEOUT, reply -> {
cache.safeConsum(nothing -> {
inProgress.remove();
JsonObject js = new JsonObject((String) inProgress.getValue());
if (reply.failed()) {
System.out.println(reply.cause());
roundrobin.remove(workerAddress);
addMessage(Paths.get(js.getString("file")), js.getInteger("step"),
js.getLong("task"), TODO, js.getInteger("max_parallel_executions"));
} else {
if (KO.equals(reply.result().body()))
addMessage(Paths.get(js.getString("file")), js.getInteger("step"),
js.getLong("task"), TODO, js.getInteger("max_parallel_executions"));
}
cache.flush();
});
});
} else {
System.out.println("No worker Verticle available");
}
}
}
});
});
// Messages handling
vertx.eventBus().consumer(PRIVATE_ADDRESS, message -> {
cache.safeConsum(nothing -> {
nb_executions = 0;
for (Generic task : taskType.getInstances())
if (STARTED.equals(new JsonObject((String) task.getValue()).getString("state"))) {
nb_executions++;
}
if (new JsonObject((String) message.body()).getInteger("max_parallel_executions") <= nb_executions) {
message.reply(KO);
return;
}
JsonObject task = new JsonObject((String) message.body());
String ip_sender = task.getString("IP");
String messageTask = new JsonObject().put("task", task.getLong("task")).put("state", STARTED)
.put("step", task.getInteger("step")).put("file", task.getString("file")).encodePrettily();
taskType.addInstance(messageTask);
cache.flush();
vertx.executeBlocking(future -> {
// get the file to convert from sender and store it in the
// corresponding folder
String fileType = task.getString("file").substring(task.getString("file").length() - 3);
String remoteDirectory = "pdf".equals(fileType) ? pdfDir : pngDir;
boolean success = true;
BlockingQueue<byte[]> blockingQueue = new ArrayBlockingQueue<>(1);
vertx.createHttpClient().getNow(port, ip_sender, remoteDirectory + "/" + task.getString("file"),
resp -> resp.bodyHandler(body -> {
try {
blockingQueue.put(body.getBytes());
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}));
byte[] bytes;
try {
bytes = blockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
try {
FileOutputStream fos;
if ("png".equals(fileType)) {
fos = new FileOutputStream(new File(pngDir + "/" + task.getString("file")));
fos.write(bytes);
fos.close();
} else if ("pdf".equals(fileType)) {
fos = new FileOutputStream(new File(pdfDir + "/" + task.getString("file")));
fos.write(bytes);
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
switch (task.getInteger("step")) {
case 1:
System.out.println("Converting pdf to png");
convertPdfToPng(task);
break;
case 2:
System.out.println("Classification");
success = classify(task);
break;
case 3:
System.out.println("OCR");
ocr(task.getString("file"));
break;
}
if (success == false) {
future.fail("Impossible to classify image " + task.getString("file"));
} else {
future.complete();
}
}, false, res -> {
cache.safeConsum(nothing2 -> {
taskType.getInstance(messageTask).remove();
if (res.succeeded()) {
taskType.addInstance(new JsonObject().put("task", task.getLong("task"))
.put("state", FINISHED).put("step", task.getInteger("step"))
.put("file", task.getString("file")).encodePrettily());
} else {
taskType.addInstance(new JsonObject().put("task", task.getLong("task"))
.put("state", ABORTED).put("step", task.getInteger("step"))
.put("file", task.getString("file")).encodePrettily());
System.out.println(res.cause());
}
cache.flush();
});
});
message.reply(OK);
});
});
}
// public static <T> T synchronizeTask(Handler<Handler<AsyncResult<T>>>
// consumer) {
// BlockingQueue<AsyncResult<T>> blockingQueue = new
// ArrayBlockingQueue<>(1);
// consumer.handle(res -> {
// try {
// blockingQueue.put(res);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// });
// AsyncResult<T> res = null;
// try {
// res = blockingQueue.take();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// if (res.failed())
// throw new IllegalStateException(res.cause());
// return res.result();
// }
private void ocr(String string) {
System.out.println(">>>>> New image to OCR: " + string);
Ocr.ocrClassifiedImage(Paths.get(string));
}
private boolean classify(JsonObject task) {
Path newFile = Paths.get(task.getString("file"));
System.out.println(">>> New file to classify: " + newFile);
Path classesDirectory = Paths.get("classes");
classesDirectory.toFile().mkdirs();
Path savedFile;
synchronized (ClassifierVerticle.class) {
savedFile = Classifier.classify(classesDirectory, Paths.get(pngDir + "/" + newFile));
}
if (savedFile != null) {
System.gc();
System.runFinalization();
addMessage(savedFile, task.getInteger("step") + 1, task.getLong("task"), TODO,
task.getInteger("max_parallel_executions"));
return true;
} else
System.out.println("Impossible to classify image " + newFile);
return false;
}
private void convertPdfToPng(JsonObject task) {
Path newFile = Paths.get(pdfDir + "/" + task.getString("file"));
System.out.println(">> New PDF file: " + newFile);
List<Path> createdPngs = PdfToPngConverter.convertPdfToImages(newFile.toFile(), new File(pngDir));
for (Path path : createdPngs)
addMessage(path.getFileName(), task.getInteger("step") + 1, task.getLong("task"), TODO,
task.getInteger("max_parallel_executions"));
System.gc();
System.runFinalization();
}
protected void addMessage(Path file, int step, long timestamp, String state, int parallel_executions) {
cache.safeConsum(n -> {
messageType.addInstance(new JsonObject().put("task", timestamp).put("state", state)
.put("max_parallel_executions", parallel_executions).put("step", step).put("file", file.toString())
.encodePrettily());
cache.flush();
});
}
public void startServer() {
vertx.createHttpServer().requestHandler(req -> {
// String fileName = req.path().replace("/", "");
String fileName = req.path();
System.out.println("Will send :" + fileName);
req.response().sendFile(fileName);
}).listen(port);
}
}