summaryrefslogtreecommitdiffstats
path: root/gearman/controllerWorker/ControllerWorker/Shutdown.java
blob: 15ec6230660894565bd4674dd5eee236be332d2d (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
package ControllerWorker;

import java.io.IOException;
import java.lang.Thread;
import java.util.concurrent.ExecutionException;
import java.util.Date;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Vector;

import org.gearman.client.GearmanClient;
import org.gearman.client.GearmanClientImpl;
import org.gearman.client.GearmanJob;
import org.gearman.client.GearmanJobImpl;
import org.gearman.client.GearmanJobResult;
import org.gearman.client.GearmanJobStatus;
import org.gearman.common.GearmanJobServerConnection;
import org.gearman.common.GearmanNIOJobServerConnection;
import org.gearman.util.ByteUtils;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class Shutdown extends Thread {
	private long beginTime;
	private long timeTaken;
	private long timeLeft;
	private Boolean finished;
	private Boolean error;
	private final int updateRate;
	private final long updatePeriod;
	private long waitTime;
	private String[] statusText;

	private HashMap<Integer, GearmanJob> pingJobs;
	private HashMap<Integer, GearmanJob> whoJobs;
	private HashMap<Integer, GearmanJob> doShutdownJobs;
	private HashMap<Integer, GearmanJob> pingShutdownJobs;
	private HashMap<Integer, GearmanJob> psJobs;
	private HashMap<Integer, Integer> status;
	private HashMap<Integer, String> errors;
	private HashMap<Integer, Long> pingShutdownTime;

	private Vector<HashMap<String, String>> clients;

	private final GearmanJobServerConnection gearmanConnection;
	private GearmanClient gearmanClient;

	public Shutdown(String serverAddress, int port,
			Vector<HashMap<String, String>> clients, int updateRate,
			long waitTime) {
		this.pingJobs = new HashMap<Integer, GearmanJob>();
		this.whoJobs = new HashMap<Integer, GearmanJob>();
		this.doShutdownJobs = new HashMap<Integer, GearmanJob>();
		this.pingShutdownJobs = new HashMap<Integer, GearmanJob>();
		this.psJobs = new HashMap<Integer, GearmanJob>();
		this.status = new HashMap<Integer, Integer>();
		this.errors = new HashMap<Integer, String>();
		this.pingShutdownTime = new HashMap<Integer, Long>();
		this.updateRate = updateRate; // updates per second
		this.updatePeriod = 1000000000L / this.updateRate; // nanoseconds
		this.gearmanConnection = new GearmanNIOJobServerConnection(
				serverAddress, port);
		this.gearmanClient = new GearmanClientImpl();
		gearmanClient.addJobServer(this.gearmanConnection);
		this.waitTime = waitTime * 1000;
		this.clients = clients;
		for (HashMap<String, String> client : clients) {
			int clientID = Integer.parseInt(client.get("id"));
			status.put(clientID, 0); // no work
		}
		this.finished = false;
		this.error = false;
		this.statusText = new String[14];
		this.statusText[0] = "The shutdown process of the client has been started.";
		this.statusText[1] = "The ping has been started.";
		this.statusText[2] = "The client is alive.";
		this.statusText[3] = "The check if a user is logged in has been started.";
		this.statusText[4] = "No user is logged in.";
		this.statusText[5] = "A shutdown of the client has been triggered.";
		this.statusText[6] = "The shutdown command has been sent.";
		this.statusText[7] = "The ping after shutdown has been started.";
		this.statusText[8] = "Doing ping after shutdown again and again, until client is not alive or two minutes has been elapsed";
		this.statusText[9] = "A user is logged in.";
		this.statusText[10] = "The check if the user is working has been started.";
		this.statusText[11] = "The user is working.";
		this.statusText[12] = "Shutdown of the client has not been finished, due to an error.";
		this.statusText[13] = "Shutdown of the client has been finished.";
	}

	public void run() {
		workerLoop();
	}

	private void workerLoop() {
		Boolean run = true;
		while (run) {
			try {
				beginTime = System.nanoTime();
				run = update();
				timeTaken = System.nanoTime() - beginTime;
				timeLeft = (updatePeriod - timeTaken) / 1000000;
				if (timeLeft < 10)
					timeLeft = 10;
				Thread.sleep(timeLeft);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		this.finished = true;
	}

	private Boolean update() throws IllegalStateException, IOException,
			InterruptedException, ExecutionException {
		Boolean allFinished = false;

		for (HashMap<String, String> client : clients) {
			String ipAddress = client.get("ip");
			int clientID = Integer.parseInt(client.get("id"));
			int clientStatus = status.get(clientID);

			switch (clientStatus) {

			case 0:
				ping(client);

				break;

			case 1:
				GearmanJob pingJob = pingJobs.get(clientID);

				if (pingJob != null) {
					GearmanJobStatus jobStatus = gearmanClient
							.getJobStatus(pingJob);

					if (!jobStatus.isKnown() && pingJob.isDone()) {
						GearmanJobResult pingJobRes = pingJob.get();
						String result = ByteUtils.fromUTF8Bytes(pingJobRes
								.getResults());

						if (!result.isEmpty()) {
							JSONObject resultObj = (JSONObject) JSONValue
									.parse(result);
							if (!resultObj.containsKey("err")) {
								String alive = resultObj.get("alive")
										.toString();

								if (alive.equals("true")) {
									System.out.println(ipAddress + " alive");
									status.put(clientID, 2); // alive, check
									// Users
									pingJobs.remove(clientID);
								} else if (alive.equals("false")) {
									System.out
											.println(ipAddress + " not alive");
									// not alive, go in successState
									status.put(clientID, 13);
									pingJobs.remove(clientID);
								}
							} else {
								System.out.println(ipAddress
										+ " Cannot send the ping message.");
								this.errors
										.put(clientID,
												"Sending the ping message has been failed.");
								// sending the ping message has been failed
								status.put(clientID, 12);
								pingJobs.remove(clientID);
							}
						}
					}
				}

				break;

			case 2:
				who(client);

				break;

			case 3:
				GearmanJob whoJob = whoJobs.get(clientID);

				if (whoJob != null) {
					GearmanJobStatus jobStatus = gearmanClient
							.getJobStatus(whoJob);

					if (!jobStatus.isKnown() && whoJob.isDone()) {
						GearmanJobResult whoJobRes = whoJob.get();
						String result = ByteUtils.fromUTF8Bytes(whoJobRes
								.getResults());

						if (!result.isEmpty()) {
							JSONObject resultObj = (JSONObject) JSONValue
									.parse(result);
							if (!resultObj.containsKey("err")) {
								String rawoutput = resultObj.get("rawoutput")
										.toString();
								StringTokenizer str = new StringTokenizer(
										rawoutput, " ");
								String user = "";
								if (str.hasMoreTokens()) {
									user = str.nextToken();
								}

								if (user.isEmpty()) {
									System.out.println(ipAddress
											+ " no user is logged in");
									// no user is logged in
									status.put(clientID, 4);
									whoJobs.remove(clientID);
								} else {
									System.out.println(ipAddress
											+ " a user is logged in");
									// a user is logged in
									status.put(clientID, 9);
									whoJobs.remove(clientID);
								}
							} else {
								System.out
										.println(ipAddress
												+ " Cannot check if a user is logged in.");
								this.errors
										.put(clientID,
												"The check if a user is logged in has been failed.");
								/*
								 * cannot check if a user is logged in, go in
								 * errorState
								 */
								status.put(clientID, 12);
								whoJobs.remove(clientID);
							}
						}
					}
				}

				break;

			case 4:
				doShutdown(client);

				break;

			case 5:
				GearmanJob doShutdownJob = doShutdownJobs.get(clientID);
				if (doShutdownJob != null) {
					GearmanJobStatus jobStatus = gearmanClient
							.getJobStatus(doShutdownJob);

					if (!jobStatus.isKnown() && doShutdownJob.isDone()) {
						GearmanJobResult wolJobRes = doShutdownJob.get();
						String result = ByteUtils.fromUTF8Bytes(wolJobRes
								.getResults());
						if (!result.isEmpty()) {
							JSONObject resultObj = (JSONObject) JSONValue
									.parse(result);
							if (!resultObj.containsKey("err")) {
								System.out.println(ipAddress
										+ " Shutdown command send");
								status.put(clientID, 6); // shutdown command
								// send
								doShutdownJobs.remove(clientID);
							} else {
								System.out.println(ipAddress
										+ " Cannot send shutdown command");
								this.errors
										.put(clientID,
												"Sending the shutdown command has been failed.");
								/*
								 * cannot send shutdown command, go in /
								 * errorState
								 */
								status.put(clientID, 12);
								doShutdownJobs.remove(clientID);
							}
						}
					}
				}

				break;

			case 6:
				Date date = new Date();
				Long timestamp = date.getTime();
				pingShutdownTime.put(clientID, timestamp);
				status.put(clientID, 7); // ping after shutdown

				break;

			case 7:
				pingShutdown(client);

				break;

			case 8:
				GearmanJob pingJobShutdown = pingShutdownJobs.get(clientID);
				if (pingJobShutdown != null) {
					Date currentDate = new Date();
					Long currentTimestamp = currentDate.getTime();
					// wait 2 min until shutdown
					Long expectedTimestamp = this.pingShutdownTime
							.get(clientID)
							+ waitTime;
					if (expectedTimestamp >= currentTimestamp) {
						GearmanJobStatus jobStatus = gearmanClient
								.getJobStatus(pingJobShutdown);
						if (!jobStatus.isKnown() && pingJobShutdown.isDone()) {
							GearmanJobResult pingJobRes = pingJobShutdown.get();
							String result = ByteUtils.fromUTF8Bytes(pingJobRes
									.getResults());
							if (!result.isEmpty()) {
								JSONObject resultObj = (JSONObject) JSONValue
										.parse(result);
								if (!resultObj.containsKey("err")) {
									String alive = resultObj.get("alive")
											.toString();
									if (alive.equals("false")) {
										System.out
												.println(ipAddress
														+ " is not alive after shutdown");
										// not alive, go in successState
										status.put(clientID, 13);
										pingShutdownJobs.remove(clientID);
									} else if (alive.equals("true")) {
										System.out
												.println(ipAddress
														+ " is still alive after shutdown");
										// still alive, ping again
										status.put(clientID, 7);
									}
								} else {
									System.out
											.println(ipAddress
													+ " Cannot send the ping after shutdown message.");
									this.errors
											.put(clientID,
													"Sending the ping after shutdown message has been failed.");
									/*
									 * sending the ping after shutdown message
									 * has been failed
									 */
									status.put(clientID, 12);
									pingJobs.remove(clientID);
								}
							}
						}
					} else {
						System.out.println(ipAddress
								+ " is alive after shutdown");
						this.errors.put(clientID,
								"Client is still alive after shutdown.");
						// still alive, go in errorState
						status.put(clientID, 12);
						pingShutdownJobs.remove(clientID);
					}
				}

				break;

			case 9:
				ps(client);

				break;

			case 10:
				GearmanJob psJob = psJobs.get(clientID);

				if (psJob != null) {
					GearmanJobStatus jobStatus = gearmanClient
							.getJobStatus(psJob);

					if (!jobStatus.isKnown() && psJob.isDone()) {
						GearmanJobResult whoJobRes = psJob.get();
						String result = ByteUtils.fromUTF8Bytes(whoJobRes
								.getResults());

						if (!result.isEmpty()) {
							JSONObject resultObj = (JSONObject) JSONValue
									.parse(result);
							if (!resultObj.containsKey("err")) {
								JSONArray ps = (JSONArray) resultObj
										.get("ps");
								boolean isWorking = true;
								
								//LOGIC_TESTS
								/*System.out.println("######");
								System.out.println("######");
								System.out.println("firefox: " + ps.toString().contains("firefox-bin")); // browser firefox
								System.out.println("chromium: " + ps.toString().contains("chromium-browse")); // browser chromium
								System.out.println("email: " + ps.toString().contains("thunderbird-bi")); // email
								System.out.println("pdf-viewer: " + ps.toString().contains("evince")); // pdf-viewer
								System.out.println("office: " + ps.toString().contains("soffice.bin")); // office
								System.out.println("eclipse: " + ps.toString().contains("eclipse")); // eclipse
								System.out.println("######");
								System.out.println("gnome screensaver: " + ps.toString().contains("gnome-screensav")); // gnome screensaver
								System.out.println("kde screensaver: " + ps.toString().contains("Kscreensaver")); // kde screensaver
								System.out.println("######");*/
								
								if (ps.toString().contains("firefox.bin") || ps.toString().contains("chromium-browse") || ps.toString().contains("thunderbird-bi") || ps.toString().contains("evince") || ps.toString().contains("soffice.bin") || ps.toString().contains("eclipse")) {
									System.out.println(ipAddress
											+ " is working");
									status.put(clientID, 11); // is working
									psJobs.remove(clientID);
								} else if (ps.toString().contains("gnome-screensav") || ps.toString().contains("Kscreensaver")) {
									System.out.println(ipAddress
											+ " is not working");
									status.put(clientID, 4); // is not working
									psJobs.remove(clientID);
								}
							} else {
								System.out.println(ipAddress
										+ " Cannot check if user is working.");
								this.errors
										.put(clientID,
												"The check if a user is working has been failed.");
								/*
								 * cannot check if user is working, go in
								 * errorState
								 */
								status.put(clientID, 12);
								psJobs.remove(clientID);
							}
						}
					}
				}

				break;

			case 11:
				this.errors.put(clientID, "The user is working.");
				// user is working, go in errorState
				status.put(clientID, 12);

				break;

			case 12:
				System.out.println("Shutdown failed"); // errorState

				break;

			case 13:
				System.out.println("Shutdown finished"); // successState

				break;

			}
			if (clientStatus == 12) {
				allFinished = true;
			} else if (clientStatus == 13) {
				allFinished = true;
				this.error = true;
			} else {
				allFinished = false;
			}
		}

		if (allFinished) {
			return false;
		} else {
			return true;
		}
	}

	private void ping(HashMap<String, String> client) {
		String ipAddress = client.get("ip");
		int clientID = Integer.parseInt(client.get("id"));

		GearmanJob job = GearmanJobImpl.createJob("ping", ipAddress.getBytes(),
				"ping" + clientID);
		gearmanClient.submit(job);

		status.put(clientID, 1); // ping started
		pingJobs.put(clientID, job);

		System.out.println("ping " + ipAddress);
	}

	private void who(HashMap<String, String> client) {
		String ipAddress = client.get("ip");
		int clientID = Integer.parseInt(client.get("id"));

		GearmanJob job = GearmanJobImpl.createJob("who", ipAddress.getBytes(),
				"who" + clientID);
		gearmanClient.submit(job);

		status.put(clientID, 3); // who started
		whoJobs.put(clientID, job);

		System.out.println("who " + ipAddress);
	}

	private void doShutdown(HashMap<String, String> client) {
		String ipAddress = client.get("ip");
		int clientID = Integer.parseInt(client.get("id"));

		GearmanJob job = GearmanJobImpl.createJob("doShutdown", ipAddress
				.getBytes(), "doShutdown" + clientID);
		gearmanClient.submit(job);

		status.put(clientID, 5); // shutdown started
		doShutdownJobs.put(clientID, job);

		System.out.println("doShutdown " + ipAddress);
	}

	private void pingShutdown(HashMap<String, String> client) {
		String ipAddress = client.get("ip");
		int clientID = Integer.parseInt(client.get("id"));

		GearmanJob job = GearmanJobImpl.createJob("ping", ipAddress.getBytes(),
				"ping" + clientID);
		gearmanClient.submit(job);

		status.put(clientID, 8); // pingShutdown started
		pingShutdownJobs.put(clientID, job);

		System.out.println("ping " + ipAddress);
	}

	private void ps(HashMap<String, String> client) {
		String ipAddress = client.get("ip");
		int clientID = Integer.parseInt(client.get("id"));

		GearmanJob job = GearmanJobImpl.createJob("ps", ipAddress.getBytes(),
				"ps" + clientID);
		gearmanClient.submit(job);

		status.put(clientID, 10); // ps started
		psJobs.put(clientID, job);

		System.out.println("ps " + ipAddress);
	}

	public String getStatusText(HashMap<String, String> client) {
		int clientID = Integer.parseInt(client.get("id"));
		int clientStatus = this.status.get(clientID);
		return this.statusText[clientStatus];
	}

	public String getError(HashMap<String, String> client) {
		int clientID = Integer.parseInt(client.get("id"));
		String clientError = this.errors.get(clientID);
		return clientError;
	}

	public Boolean isFinished() {
		return finished;
	}

	public Boolean isFinishedWithErrors() {
		return finished && error;
	}

	public Vector<HashMap<String, String>> getClients() {
		return clients;
	}
}