summaryrefslogtreecommitdiffstats
path: root/gearman/controllerWorker/ControllerWorker/Boot.java
blob: 594f5de16b27ea199996b069333b4fdb61eb01cc (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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
package ControllerWorker;

import java.io.IOException;
import java.lang.Thread;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
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;

import org.apache.log4j.Logger;

public class Boot extends Thread {
	private static final Logger logger = ControllerWorkerMain.getLogger();

	private String eventName;
	private Boolean force;
	private Vector<Client> clients;
	private String bootOS;
	private final int updateRate;
	private long waitTime;
	private long scsavTime;
	private Vector<String> psWhitelist;
	private Vector<String> psBlacklist;

	private final GearmanJobServerConnection gearmanConnection;
	private GearmanClient gearmanClient;
	private Boolean finished;
	private Boolean error;

	public Boot(String eventName, Boolean force, Vector<Client> clients,
			String bootOS, int updateRate, long waitTime, long scsavTime,
			Vector<String> psWhitelist, Vector<String> psBlacklist,
			String gearmanServerAddress, int gearmanServerPort) {
		this.eventName = eventName;
		this.force = force;
		this.clients = clients;
		this.bootOS = bootOS;
		this.waitTime = waitTime * 1000;
		this.scsavTime = scsavTime * 1000;
		this.updateRate = updateRate; // updates per second
		this.psWhitelist = psWhitelist;
		this.psBlacklist = psBlacklist;
		gearmanConnection = new GearmanNIOJobServerConnection(
				gearmanServerAddress, gearmanServerPort);
		gearmanClient = new GearmanClientImpl();
		gearmanClient.addJobServer(this.gearmanConnection);
		finished = false;
		error = false;
	}

	public void run() {
		workerLoop();
	}

	private void workerLoop() {
		long beginTime;
		long timeTaken;
		long timeLeft;
		long updatePeriod = 1000000000L / updateRate; // nanoseconds
		Boolean run = true;
		while (run) {
			try {
				beginTime = System.nanoTime();
				run = update();
				timeTaken = System.nanoTime() - beginTime;
				timeLeft = (updatePeriod - timeTaken) / 1000000;
				if (timeLeft < 10)
					timeLeft = 10;
				sleep(timeLeft);
			} catch (Exception e) {
				logger.error(e.toString());
			}
		}
		finished = true;
		LinkedHashMap<String, Object> jsonData = new LinkedHashMap<String, Object>();
		jsonData.put("eventName", eventName);
		jsonData.put("type", "finishBootState");
		if (error) {
			logger.error("Booting of " + eventName + " failed");
			jsonData.put("error", true);
		} else {
			logger.info("Booting of " + eventName + " finished");
			jsonData.put("error", false);
		}
		String dataString = JSONValue.toJSONString(jsonData);
		GearmanJob job = GearmanJobImpl.createJob("status", dataString
				.getBytes(), "status" + eventName);
		gearmanClient.submit(job);
	}

	/*
	 * -------------- boot logik --------------
	 */

	private Boolean update() throws Exception {
		Date date;
		long timestamp;

		for (Client client : clients) {
			switch (client.getState()) {

			case CLIENT_UNKNOWN:
				ping(client);

				break;

			case CHECK_PING_PROGRESS:
				checkPingProgress(client);

				break;

			case CLIENT_IS_ALIVE:
				checkOS(client);

				break;

			case CLIENT_NOT_ALIVE:
				wakeOnLan(client);

				break;

			case CHECK_WAKE_ON_LAN_PROGRESS:
				checkWakeOnLanProgress(client);

				break;

			case MAGIC_PACKET_SENT:
				date = new Date();
				timestamp = date.getTime();
				client.addPingTime(ClientPingTime.WOL, timestamp);
				pingWakeOnLan(client);

				break;

			case PING_WOL_AGAIN:
				pingWakeOnLan(client);

				break;

			case CHECK_PING_WOL_PROGRESS:
				checkPingWolProgress(client);

				break;

			case CHECK_CHECKOS_PROGRESS:
				checkCheckosProgress(client);

				break;

			case WRONG_OS:
				who(client);

				break;

			case CHECK_WHO_PROGRESS:
				checkWhoProgress(client);

				break;

			case A_USER_IS_LOGGED_IN:
				if (force) {
					logger.info(client.getIp() + " force is enabled");
					// is not working
					client.setState(ClientState.RESTART_CLIENT, gearmanClient);
				} else {
					ps(client);
				}

				break;

			case CHECK_PS_PROGRESS:
				checkPsProgress(client);

				break;

			case USERPROCESSES_ARE_RUNNING:
				ls(client);

				break;

			case CHECK_LS_PROGRESS:
				checkLsProgress(client);

				break;

			case RESTART_CLIENT:
				restart(client);

				break;

			case CHECK_RESTART_PROGRESS:
				checkRestartProgress(client);

				break;

			case RESTART_COMMAND_SENT:
				date = new Date();
				timestamp = date.getTime();
				client.addPingTime(ClientPingTime.RESTARTSHUTDOWN, timestamp);
				pingRestartShutdown(client);

				break;

			case PING_RESTART_SHUTDOWN_AGAIN:
				pingRestartShutdown(client);

				break;

			case CHECK_PING_RESTART_SHUTDOWN_PROGRESS:
				checkPingRestartShutdownProgress(client);

				break;

			case USER_IS_WORKING:
				logger.error(client.getIp() + " User has been working");
				client.setError("The user has been working.");
				// user has been working, go in errorState
				client.setState(ClientState.BOOT_ERROR, gearmanClient);

				break;

			case CLIENT_IS_DOWN:
				date = new Date();
				timestamp = date.getTime();
				client.addPingTime(ClientPingTime.RESTARTBOOT, timestamp);
				pingRestartBoot(client);

				break;

			case PING_RESTART_BOOT_AGAIN:
				pingRestartBoot(client);

				break;

			case CHECK_PING_RESTART_BOOT_PROGRESS:
				checkPingRestartBootProgress(client);

				break;

			case BOOT_ERROR:
				if (!client.isFinished()) {
					logger.error(client.getIp() + " Booting failed"); // errorState
					client.finish();
					error = true;
				}

				break;

			case BOOT_SUCCESS:
				if (!client.isFinished()) {
					logger.info(client.getIp() + " Booting finished"); // successState
					client.finish();
				}

				break;
			}
		}

		boolean allFinished = false;
		for (Client client : clients) {
			if (client.isFinished()) {
				allFinished = true;
			} else {
				allFinished = false;
				break;
			}
		}

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

	/*
	 * ------------------------- function declarations -------------------------
	 */

	private void ping(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("ping", client.getIp()
				.getBytes(), "ping" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_PING_PROGRESS, gearmanClient);
		client.addJob(ClientJob.PINGJOB, job);
		logger.info("ping " + client.getIp());
	}

	private void checkPingProgress(Client client) throws Exception, IOException {
		GearmanJob pingJob = client.getJob(ClientJob.PINGJOB);

		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")) {
							logger.info(client.getIp() + " alive");
							client.setState(ClientState.CLIENT_IS_ALIVE,
									gearmanClient);
							client.removeJob(pingJob);
						} else if (alive.equals("false")) {
							logger.info(client.getIp() + " not alive");
							client.setState(ClientState.CLIENT_NOT_ALIVE,
									gearmanClient);
							client.removeJob(pingJob);
						}
					} else {
						logger.error(client.getIp()
								+ " Cannot send the ping message.");
						client
								.setError("Sending the ping message has been failed.");
						client.setState(ClientState.BOOT_ERROR, gearmanClient);
						client.removeJob(pingJob);
					}
				}
			}
		}
	}

	private void pingWakeOnLan(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("ping", client.getIp()
				.getBytes(), "ping" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_PING_WOL_PROGRESS, gearmanClient);
		client.addJob(ClientJob.PINGJOB, job);
		logger.info("ping " + client.getIp());
	}

	private void checkPingWolProgress(Client client) throws Exception,
			IOException {
		GearmanJob pingJobWoL = client.getJob(ClientJob.PINGJOB);

		if (pingJobWoL != null) {
			Date currentDate = new Date();
			Long currentTimestamp = currentDate.getTime();
			// wait 2 min until WoL - Failed
			Long expectedTimestamp = client.getPingTime(ClientPingTime.WOL)
					+ waitTime;
			if (expectedTimestamp >= currentTimestamp) {
				GearmanJobStatus jobStatus = gearmanClient
						.getJobStatus(pingJobWoL);
				if (!jobStatus.isKnown() && pingJobWoL.isDone()) {
					GearmanJobResult pingJobRes = pingJobWoL.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")) {
								logger.info(client.getIp()
										+ " is alive after WoL");
								// alive, go in successState
								client.setState(ClientState.BOOT_SUCCESS,
										gearmanClient);
								client.removeJob(pingJobWoL);
							} else if (alive.equals("false")) {
								logger.info("ping again " + client.getIp());
								client.setState(ClientState.PING_WOL_AGAIN,
										gearmanClient);
								client.removeJob(pingJobWoL);
							}
						} else {
							logger
									.error(client.getIp()
											+ " Cannot send the ping after wake on LAN message.");
							client
									.setError("Sending the ping after wake on LAN message has been failed.");
							/*
							 * sending the ping after wake on LAN message has
							 * been failed, go to errorState
							 */
							client.setState(ClientState.BOOT_ERROR,
									gearmanClient);
							client.removeJob(pingJobWoL);
						}
					}
				}
			} else {
				logger.error(client.getIp() + " is not alive after WoL");
				client.setError("The wake on LAN has been failed.");
				// not alive, go in errorState
				client.setState(ClientState.BOOT_ERROR, gearmanClient);
				client.removeJob(pingJobWoL);
			}
		}
	}

	private void pingRestartShutdown(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("ping", client.getIp()
				.getBytes(), "ping" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_PING_RESTART_SHUTDOWN_PROGRESS,
				gearmanClient);
		client.addJob(ClientJob.PINGJOB, job);
		logger.info("ping " + client.getIp());
	}

	private void checkPingRestartShutdownProgress(Client client)
			throws Exception, IOException {
		GearmanJob pingJobRestartShutdown = client.getJob(ClientJob.PINGJOB);
		if (pingJobRestartShutdown != null) {
			Date currentDate = new Date();
			Long currentTimestamp = currentDate.getTime();
			// wait 2 min until Restart - Failed
			Long expectedTimestamp = client
					.getPingTime(ClientPingTime.RESTARTSHUTDOWN)
					+ waitTime;
			if (expectedTimestamp >= currentTimestamp) {
				GearmanJobStatus jobStatus = gearmanClient
						.getJobStatus(pingJobRestartShutdown);
				if (!jobStatus.isKnown() && pingJobRestartShutdown.isDone()) {
					GearmanJobResult pingJobRestartRes = pingJobRestartShutdown
							.get();
					String result = ByteUtils.fromUTF8Bytes(pingJobRestartRes
							.getResults());
					if (!result.isEmpty()) {
						JSONObject resultObj = (JSONObject) JSONValue
								.parse(result);
						if (!resultObj.containsKey("err")) {
							String alive = resultObj.get("alive").toString();
							if (alive.equals("true")) {
								logger.info(client.getIp() + " is still alive");
								// still alive, ping again
								client
										.setState(
												ClientState.PING_RESTART_SHUTDOWN_AGAIN,
												gearmanClient);
								client.removeJob(pingJobRestartShutdown);
							} else if (alive.equals("false")) {
								logger.info(client.getIp() + " is down");
								// not alive, ping again
								client.setState(ClientState.CLIENT_IS_DOWN,
										gearmanClient);
								client.removeJob(pingJobRestartShutdown);
							}
						} else {
							logger
									.error(client.getIp()
											+ " Cannot send the ping after restart message.");
							client
									.setError("Sending the ping after restart message has been failed.");
							/*
							 * sending the ping after restart message has been
							 * failed
							 */
							client.setState(ClientState.BOOT_ERROR,
									gearmanClient);
							client.removeJob(pingJobRestartShutdown);
						}
					}
				}
			} else {
				logger.error(client.getIp() + " shutdown failed");
				client.setError("The shutdown has been failed.");
				// still alive, go in errorState
				client.setState(ClientState.BOOT_ERROR, gearmanClient);
				client.removeJob(pingJobRestartShutdown);
			}
		}
	}

	private void pingRestartBoot(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("ping", client.getIp()
				.getBytes(), "ping" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_PING_RESTART_BOOT_PROGRESS,
				gearmanClient);
		client.addJob(ClientJob.PINGJOB, job);
		logger.info("ping " + client.getIp());
	}

	private void checkPingRestartBootProgress(Client client) throws Exception,
			IOException {
		GearmanJob pingJobRestartBoot = client.getJob(ClientJob.PINGJOB);

		if (pingJobRestartBoot != null) {
			Date currentDate = new Date();
			Long currentTimestamp = currentDate.getTime();
			// wait 2 min until Restart - Failed
			Long expectedTimestamp = client
					.getPingTime(ClientPingTime.RESTARTBOOT)
					+ waitTime;
			if (expectedTimestamp >= currentTimestamp) {
				GearmanJobStatus jobStatus = gearmanClient
						.getJobStatus(pingJobRestartBoot);
				if (!jobStatus.isKnown() && pingJobRestartBoot.isDone()) {
					GearmanJobResult pingJobRestartRes = pingJobRestartBoot
							.get();
					String result = ByteUtils.fromUTF8Bytes(pingJobRestartRes
							.getResults());
					if (!result.isEmpty()) {
						JSONObject resultObj = (JSONObject) JSONValue
								.parse(result);
						if (!resultObj.containsKey("err")) {
							String alive = resultObj.get("alive").toString();
							if (alive.equals("true")) {
								logger.info(client.getIp()
										+ " is alive after restart");
								// alive, go to success state
								client.setState(ClientState.BOOT_SUCCESS,
										gearmanClient);
								client.removeJob(pingJobRestartBoot);
							} else if (alive.equals("false")) {
								logger.info("ping again " + client.getIp());
								// not alive, ping again
								client.setState(
										ClientState.PING_RESTART_BOOT_AGAIN,
										gearmanClient);
								client.removeJob(pingJobRestartBoot);
							}
						} else {
							logger
									.error(client.getIp()
											+ " Cannot send the ping after shutdown message.");
							client
									.setError("Sending the ping after shutdown message has been failed.");
							/*
							 * sending the ping after shutdown message has been
							 * failed
							 */
							client.setState(ClientState.BOOT_ERROR,
									gearmanClient);
						}
					}
				}
			} else {
				logger.error(client.getIp() + " is not alive after reboot");
				client.setError("The reboot has been failed.");
				// not alive, go in errorState
				client.setState(ClientState.BOOT_ERROR, gearmanClient);
				client.removeJob(pingJobRestartBoot);
			}
		}
	}

	private void wakeOnLan(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("wol", client.getMac()
				.getBytes(), "wol" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_WAKE_ON_LAN_PROGRESS, gearmanClient);
		client.addJob(ClientJob.WOLJOB, job);
		logger.info("wake on lan " + client.getMac());
	}

	private void checkWakeOnLanProgress(Client client) throws Exception,
			IOException {
		GearmanJob wolJob = client.getJob(ClientJob.WOLJOB);

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

			if (!jobStatus.isKnown() && wolJob.isDone()) {
				GearmanJobResult wolJobRes = wolJob.get();
				String result = ByteUtils.fromUTF8Bytes(wolJobRes.getResults());
				if (result.equals("Magic packet send.")) {
					logger.info(client.getMac() + " Magic packet sent.");
					client.setState(ClientState.MAGIC_PACKET_SENT,
							gearmanClient);
					client.removeJob(wolJob);
				} else {
					logger.error(client.getIp() + " Cannot send magic packet.");
					client
							.setError("Sending the magic packet has been failed.");
					// cannot send magic packet, go in errorState
					client.setState(ClientState.BOOT_ERROR, gearmanClient);
					client.removeJob(wolJob);
				}
			}
		}
	}

	private void checkOS(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("os", client.getIp()
				.getBytes(), "os" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_CHECKOS_PROGRESS, gearmanClient);
		client.addJob(ClientJob.OSJOB, job);
		logger.info("check OS " + client.getIp());
	}

	private void checkCheckosProgress(Client client) throws Exception,
			IOException {
		GearmanJob osJob = client.getJob(ClientJob.OSJOB);

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

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

				if (!result.isEmpty()) {
					JSONObject resultObj = (JSONObject) JSONValue.parse(result);
					if (!resultObj.containsKey("err")) {
						String clientBootOs = resultObj.get("Distributor ID")
								.toString()
								+ " " + resultObj.get("Release").toString();

						if (clientBootOs.equals(bootOS)) {
							logger.info(client.getIp() + " right OS");
							// right os, go to successState
							client.setState(ClientState.BOOT_SUCCESS,
									gearmanClient);
							client.removeJob(osJob);
						} else {
							logger.info(client.getIp() + " wrong OS");
							client
									.setState(ClientState.WRONG_OS,
											gearmanClient);
							client.removeJob(osJob);
						}
					} else {
						logger.error(client.getIp() + " Cannot check os");
						client
								.setError("The check for correct operating system has been failed.");
						// cannot check os, go in errorState
						client.setState(ClientState.BOOT_ERROR, gearmanClient);
						client.removeJob(osJob);
					}
				}
			}
		}
	}

	private void who(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("who", client.getIp()
				.getBytes(), "who" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_WHO_PROGRESS, gearmanClient);
		client.addJob(ClientJob.WHOJOB, job);
		logger.info("who " + client.getIp());
	}

	private void checkWhoProgress(Client client) throws Exception, IOException {
		GearmanJob whoJob = client.getJob(ClientJob.WHOJOB);

		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()) {
							logger.info(client.getIp()
									+ " no user is logged in -CHECK PS-");
							/*
							 * no user is logged in, doing restart ----- didn´t
							 * work in test-pool, check ps
							 */
							client.setState(ClientState.A_USER_IS_LOGGED_IN,
									gearmanClient);
							client.removeJob(whoJob);
						} else {
							logger
									.info(client.getIp()
											+ " a user is logged in");
							client.setState(ClientState.A_USER_IS_LOGGED_IN,
									gearmanClient);
							client.removeJob(whoJob);
						}
					} else {
						logger.error(client.getIp()
								+ " Cannot check if a user is logged in.");
						client
								.setError("The check if a user is logged in has been failed.");
						/*
						 * cannot check if a user is logged in, go in errorState
						 */
						// client
						client.setState(ClientState.BOOT_ERROR, gearmanClient);
						client.removeJob(whoJob);
					}
				}
			}
		}
	}

	private void ps(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("ps", client.getIp()
				.getBytes(), "ps" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_PS_PROGRESS, gearmanClient);
		client.addJob(ClientJob.PSJOB, job);
		logger.info("ps " + client.getIp());
	}

	private void checkPsProgress(Client client) throws Exception, IOException {
		GearmanJob psJob = client.getJob(ClientJob.PSJOB);

		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");
						HashMap<String, HashMap<String, Integer>> psMap = new HashMap<String, HashMap<String, Integer>>();

						for (Object obj : ps) {
							HashMap<String, Integer> psEntry = new HashMap<String, Integer>();
							JSONObject psLine = (JSONObject) obj;
							String cmd = psLine.get("cmd").toString();
							int pid = Integer.parseInt(psLine.get("pid")
									.toString());
							int ppid = Integer.parseInt(psLine.get("ppid")
									.toString());
							psEntry.put("pid", pid);
							psEntry.put("ppid", ppid);
							psMap.put(cmd, psEntry);
						}

						boolean whitelistFound = false;
						boolean blacklistFound = false;

						for (String blackEntry : psBlacklist) {
							if (psMap.containsKey(blackEntry)) {
								blacklistFound = true;
								break;
							}
						}

						for (String whiteEntry : psWhitelist) {
							if (psMap.containsKey(whiteEntry)) {
								HashMap<String, Integer> psEntry = psMap
										.get(whiteEntry);
								if (whiteEntry.equals("gnome-screensav")) {
									if (psEntry.get("ppid") != 1) {
										client.setScsavPID(psEntry.get("pid"));
										whitelistFound = true;
										break;
									}
								} else {
									client.setScsavPID(psEntry.get("pid"));
									whitelistFound = true;
									break;
								}
							}
						}

						if (blacklistFound) {
							if (whitelistFound) {
								logger.info(client.getIp()
										+ " processes are running");
								client.setState(
										ClientState.USERPROCESSES_ARE_RUNNING,
										gearmanClient);
							} else {
								logger.info(client.getIp() + " is working");
								client.setState(ClientState.USER_IS_WORKING,
										gearmanClient);
							}
							client.removeJob(psJob);
						} else {
							logger.info(client.getIp() + " is not working");
							// user is not working, doing restart
							client.setState(ClientState.RESTART_CLIENT,
									gearmanClient);
							client.removeJob(psJob);
						}
					} else {
						logger.error(client.getIp()
								+ " Cannot check if user is working.");
						client
								.setError("The check if a user is working has been failed.");
						/*
						 * cannot check if user is working, go in errorState
						 */
						client.setState(ClientState.BOOT_ERROR, gearmanClient);
						client.removeJob(psJob);
					}
				} else {
					logger.error(client.getIp()
							+ " Cannot check if user is working.");
					client
							.setError("The check if a user is working has been failed.");
					/*
					 * cannot check if user is working, go in errorState
					 */
					client.setState(ClientState.BOOT_ERROR, gearmanClient);
					client.removeJob(psJob);
				}
			}
		}
	}

	// screensaver check
	private void ls(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("ls", client.getIp()
				.getBytes(), "ls" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_LS_PROGRESS, gearmanClient);
		client.addJob(ClientJob.LSJOB, job);
		logger.info("ls " + client.getIp());
	}

	private void checkLsProgress(Client client) throws Exception, IOException {
		GearmanJob lsJob = client.getJob(ClientJob.LSJOB);

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

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

				if (!result.isEmpty()) {
					JSONObject resultObj = (JSONObject) JSONValue.parse(result);
					if (!resultObj.containsKey("err")) {
						JSONArray ls = (JSONArray) resultObj.get("ls");
						HashMap<String, Long> lsMap = new HashMap<String, Long>();

						for (Object obj : ls) {
							JSONObject lsLine = (JSONObject) obj;
							String name = lsLine.get("name").toString();
							SimpleDateFormat df = new SimpleDateFormat(
									"y-M-d H:m");
							Date date = df.parse(lsLine.get("date").toString()
									+ " " + lsLine.get("time").toString());
							long timestamp = date.getTime();
							lsMap.put(name, timestamp);
						}

						String scsavPID = Integer
								.toString(client.getScsavPID());
						long scsavTimestamp = lsMap.get(scsavPID);
						Date date = new Date();
						long currentTimestamp = date.getTime();
						long beetweenTimestamp = currentTimestamp
								- scsavTimestamp;

						if (beetweenTimestamp < scsavTime) {
							logger
									.info(client.getIp()
											+ " screensaver has been running shorter than "
											+ scsavTime / (1000 * 60)
											+ " minutes, user is working.");
							client.setState(ClientState.USER_IS_WORKING,
									gearmanClient);
							client.removeJob(lsJob);
						} else {
							logger
									.info(client.getIp()
											+ " screensaver has been running longer than "
											+ scsavTime / (1000 * 60)
											+ " minutes, user is not working.");
							client.setState(ClientState.RESTART_CLIENT,
									gearmanClient);
							client.removeJob(lsJob);
						}
					} else {
						logger.error(client.getIp()
								+ " Cannot check 'ls -al' of /proc/");
						client
								.setError("The check for screensaver has been failed.");
						// cannot check ls, go in errorState
						client.setState(ClientState.BOOT_ERROR, gearmanClient);
						client.removeJob(lsJob);
					}
				} else {
					logger.error(client.getIp()
							+ " Cannot check 'ls -al' of /proc/");
					client
							.setError("The check for screensaver has been failed.");
					// cannot check ls, go in errorState
					client.setState(ClientState.BOOT_ERROR, gearmanClient);
					client.removeJob(lsJob);
				}
			}
		}
	}

	// ------------------

	private void restart(Client client) {
		GearmanJob job = GearmanJobImpl.createJob("restart", client.getIp()
				.getBytes(), "restart" + client.getId());
		gearmanClient.submit(job);
		client.setState(ClientState.CHECK_RESTART_PROGRESS, gearmanClient);
		client.addJob(ClientJob.RESTARTJOB, job);
		logger.info("restart " + client.getIp());
	}

	private void checkRestartProgress(Client client) throws Exception,
			IOException {
		GearmanJob restartJob = client.getJob(ClientJob.RESTARTJOB);

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

			if (!jobStatus.isKnown() && restartJob.isDone()) {
				GearmanJobResult wolJobRes = restartJob.get();
				String result = ByteUtils.fromUTF8Bytes(wolJobRes.getResults());
				if (!result.isEmpty()) {
					JSONObject resultObj = (JSONObject) JSONValue.parse(result);
					if (!resultObj.containsKey("err")) {
						logger.info(client.getIp() + " Restart command sent");
						client.setState(ClientState.RESTART_COMMAND_SENT,
								gearmanClient);
						client.removeJob(restartJob);
					} else {
						logger.error(client.getIp()
								+ " Cannot send restart command");
						client
								.setError("Sending the restart command has been failed.");
						// cannot send restart command, go in errorState
						client.setState(ClientState.BOOT_ERROR, gearmanClient);
						client.removeJob(restartJob);
					}
				}
			}
		}
	}

	public Boolean isFinished() {
		return finished && !error;
	}

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

	public Vector<Client> getClients() {
		return clients;
	}

	public String getEventName() {
		return eventName;
	}
}