summaryrefslogblamecommitdiffstats
path: root/gearman/controllerWorker/ControllerWorker/Boot.java
blob: 4a3f8a4a7d6098d2b0b7133f7cee1caba2be3ca1 (plain) (tree)
1
2
3
4
5
6
7
8
9



                           
                      
                                               
                         
                                 
                        





                                            
                                           



                                                        


                                  
                                  


                               
                                 


                                        
                              
                                    
 

                                                      
                                                         
                                                    


                                                             
                                                             
                                                 
                                                
                                                   
                                                       




                                                                   

                                                   

                                                                                
                                                                   
                                                                      
                                                                  
                                                                 
                                                                  

                                                                          
                                                                          
                                                              
                                                             
                                                                
                                                                    

                                                                                 






                                                                           
                                                           
                 
                                      
                                   
                                     
                                                 






                                                                                           
                                                                                                                                           
                                                                                                    
                                                                              




                                                                                           
                                                                                 

                                                                                                                                        

                                                                                                      






                                   

                                   

                                                              
                                               
                                                                          
                                                                                






                                                       
                                     
                                                       

         
                                                                           
                                                                  
                                            
 



                                                                          
                                                                
 
                                               
 

                                             
 
                                      
 
                               
                                                                            
 
                                                      

                                                                                  
 



                                                                                                  
 



                                                                                                         
 
                                                                                   
                                                                                                         

                                                                                                 

                                                                                                             

                                                                                                     


                                                         
                                 
 
                                      
 
                               
                                                
 
                                      
 

                                                  
 
                                      
 
                               
                                                                          
                                                     

                                                                                  
 



                                                                                                 

                                                                                            

                                                                                                 

                                                                                                     

                                                                                    
                                                                                                        


                                                                                                                                     

                                                                                                     
                                                                                 

                                                 
                                 
 
                                      
 
                               



                                                                                  
 
                                      
 
                               
                                                      




                                                                                  


                                                                                      

                                                                                                          














                                                                                                                 

                                                                                                    
                                                                                                     
                                                                      

                                                                                                        

                                                                                                      




                                                                                             

                                                                                                    
                                                                                                        


                                                                             
 
                                      
 
                               













                                                                                                     





                                                                                                      



                                                                                                         
                                                                                                            
                                                                                                     
                                                                                        

                                                                                                            
                                                                                                    
                                                                                        
                                                         






                                                                                                                                                   
                                                                                


                                                 
 
                                      
 
                               
                                            
 
                                      
 
                                













                                                                                                     







                                                                                                     
 
                                                                             
                                                                                                              
                                                                                                       
                                                                                         

                                                                                                              
                                                                                                       
                                                                                         
                                                         










                                                                                                                                             
                                                                                 


                                                 
 
                                      
 

                                                    
 
                                      
 
                                





































                                                                                                                                           
 
                                      
 

                                                
 
                                      
 
                                



                                                                               
 

                                      
                                



























                                                                                                                     
                                                                                                         



                                                                                                               
                                                                                                         








                                                                                                        
                                                                                 





                                         



                                                                            
                                
                                                                                
 



                                                                                      
 

                                      
                         
 
                                                 
                                                   
                                                        
                                                   
                                                  
                                
                                                    


                         
                                  


                                     





                                                                  
 

                                                                                       
                                          
 

                                                        
 


                                                        
                                                                    






                                                                                       
                                                           




                                                        













                                                                                       


                                                                  
 

                                                                                       
                                          
 

                                                               
 
                                                  

         
                                                              

                                                                  
 

                                                                                     
                                          
 




                                                            
 








                                                                                      
                                           
 
                                                       
         
 



                                                                  

                                                                                  


                                                                
                                                   
 
                                                               
         
 



                                                                  

                                                                              


                                                            
                                               
 
                                                           
         
 





                                                                     





                                                                  







                                               


                                                             
 
package ControllerWorker;

import java.io.IOException;
import java.lang.Thread;
import java.util.Date;
import java.util.concurrent.ExecutionException;
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.JSONObject;
import org.json.simple.JSONValue;

public class Boot 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 String bootOS;
	private String[] statusText;

	private HashMap<Integer, GearmanJob> pingJobs;
	private HashMap<Integer, GearmanJob> wolJobs;
	private HashMap<Integer, GearmanJob> pingWoLJobs;
	private HashMap<Integer, GearmanJob> osJobs;
	private HashMap<Integer, GearmanJob> whoJobs;
	private HashMap<Integer, GearmanJob> checkStatusJobs;
	private HashMap<Integer, GearmanJob> restartJobs;
	private HashMap<Integer, GearmanJob> pingRestartJobs;
	private HashMap<Integer, Integer> status;
	private HashMap<Integer, String> errors;
	private HashMap<Integer, Long> pingWolTime;
	private HashMap<Integer, Long> pingRestartTime;

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

	private final GearmanJobServerConnection gearmanConnection;
	private GearmanClient gearmanClient;

	public Boot(String serverAddress, int port,
			Vector<HashMap<String, String>> clients, int updateRate,
			String bootOS) {
		this.pingJobs = new HashMap<Integer, GearmanJob>();
		this.pingWoLJobs = new HashMap<Integer, GearmanJob>();
		this.wolJobs = new HashMap<Integer, GearmanJob>();
		this.osJobs = new HashMap<Integer, GearmanJob>();
		this.whoJobs = new HashMap<Integer, GearmanJob>();
		this.checkStatusJobs = new HashMap<Integer, GearmanJob>();
		this.restartJobs = new HashMap<Integer, GearmanJob>();
		this.pingRestartJobs = new HashMap<Integer, GearmanJob>();
		this.status = new HashMap<Integer, Integer>();
		this.errors = new HashMap<Integer, String>();
		this.pingWolTime = new HashMap<Integer, Long>();
		this.pingRestartTime = 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.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.bootOS = bootOS;
		this.statusText = new String[20];
		this.statusText[0] = "The booting 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 client is not alive.";
		this.statusText[4] = "The wake on LAN has been started.";
		this.statusText[5] = "The Magic packet has been send.";
		this.statusText[6] = "The ping after wake on LAN has been started.";
		this.statusText[7] = "Doing ping after wake on LAN again and again, until client is alive or two minutes has been elapsed";
		this.statusText[8] = "The check for the correct operating system has been started.";
		this.statusText[9] = "The wrong operating system is running.";
		this.statusText[10] = "The check if a user is logged in has been started.";
		this.statusText[11] = "A user is logged in.";
		this.statusText[12] = "The check if the user is working has been started.";
		this.statusText[13] = "The user is not working.";
		this.statusText[14] = "A restart of the client has been triggered.";
		this.statusText[15] = "The ping after restart has been started.";
		this.statusText[16] = "Doing ping after restart again and again, until client is alive or two minutes has been elapsed";
		this.statusText[17] = "The user is working.";
		this.statusText[18] = "Booting of the client has not been finished, due to an error.";
		this.statusText[19] = "Booting 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;
		System.out.println("Booting finished");
	}

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

		for (HashMap<String, String> client : clients) {
			String ipAddress = client.get("ip");
			String macAddress = client.get("mac");
			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 != "") {
							JSONObject resultObj = (JSONObject) JSONValue
									.parse(result);
							String alive = resultObj.get("alive").toString();

							if (alive.equals("true")) {
								System.out.println(ipAddress + " alive");
								status.put(clientID, 2); // alive
								pingJobs.remove(clientID);
							} else {
								System.out.println(ipAddress + " not alive");
								status.put(clientID, 3); // not alive
								pingJobs.remove(clientID);
							}
						}
					}
				}

				break;

			case 2:
				checkOS(client);

				break;

			case 3:
				wakeOnLan(client);

				break;

			case 4:
				GearmanJob wolJob = wolJobs.get(clientID);
				if (wolJob != null) {
					GearmanJobStatus jobStatus = gearmanClient
							.getJobStatus(wolJob);

					if (!jobStatus.isKnown() && wolJob.isDone()) {
						GearmanJobResult wolJobRes = wolJob.get();
						String result = ByteUtils.fromUTF8Bytes(wolJobRes
								.getResults());
						System.out.println(result.toString());
						if (result.equals("Magic packet send.\n")) {
							System.out.println(macAddress
									+ " Magic packet send.");
							status.put(clientID, 5); // magic packet send
							wolJobs.remove(clientID);
						} else {
							System.out.println(ipAddress
									+ " Cannot send magic packet.");
							this.errors
									.put(clientID,
											"Sending the magic packet has been failed.");
							// cannot send magic packet, go in errorState
							status.put(clientID, 18);
							wolJobs.remove(clientID);
						}
					}
				}

				break;

			case 5:
				Date date = new Date();
				Long timestamp = date.getTime();
				pingWolTime.put(clientID, timestamp);
				status.put(clientID, 6); // ping after wake on LAN

				break;

			case 6:
				pingWakeOnLan(client);

				break;

			case 7:
				GearmanJob pingJobWoL = pingWoLJobs.get(clientID);
				if (pingJobWoL != null) {
					Date currentDate = new Date();
					Long currentTimestamp = currentDate.getTime();
					// wait 2 min until WoL - Failed
					Long expectedTimestamp = this.pingWolTime.get(clientID) + 120000L;
					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 != "") {
								JSONObject resultObj = (JSONObject) JSONValue
										.parse(result);
								String alive = resultObj.get("alive")
										.toString();
								if (alive.equals("true")) {
									System.out.println(ipAddress
											+ " is alive after WoL");
									// alive, go in successState
									status.put(clientID, 19);
									pingWoLJobs.remove(clientID);
								} else
									System.out.println("ping again "
											+ ipAddress);
								status.put(clientID, 6); // again ping
								pingWoLJobs.remove(clientID);
							}
						}
					} else {
						System.out.println(ipAddress
								+ " is not alive after WoL");
						this.errors.put(clientID,
								"The wake on LAN has been failed.");
						status.put(clientID, 18); // not alive, go in errorState
						pingWoLJobs.remove(clientID);
					}
				}

				break;

			case 8:
				GearmanJob osJob = osJobs.get(clientID);

				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 != "") {
							JSONObject resultObj = (JSONObject) JSONValue
									.parse(result);
							/*
							 * String release =
							 * resultObj.get("Release").toString(); String
							 * distriputorID =
							 * resultObj.get("Distributor ID").toString();
							 */
							String description = resultObj.get("Description")
									.toString();

							if (description.equals(this.bootOS)) {
								System.out.println(ipAddress + " right OS");
								status.put(clientID, 19); // right os
								osJobs.remove(clientID);
							} else {
								System.out.println(ipAddress + " wrong OS");
								status.put(clientID, 9); // wrong os
								osJobs.remove(clientID);
							}
						} else {
							System.out.println(ipAddress + " Cannot check os");
							this.errors
									.put(clientID,
											"The check for correct operating system has been failed.");
							// cannot check os, go in errorState
							status.put(clientID, 18);
							osJobs.remove(clientID);
						}
					}
				}

				break;

			case 9:
				who(client);

				break;

			case 10:
				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 != "") {
							JSONObject resultObj = (JSONObject) JSONValue
									.parse(result);
							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 + " right User");
								status.put(clientID, 13); // right user
								whoJobs.remove(clientID);
							} else {
								System.out.println(ipAddress + " wrong User");
								status.put(clientID, 11); // wrong user
								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, 18);
							whoJobs.remove(clientID);
						}
					}
				}

				break;

			case 11:
				checkStatus(client);

				break;

			case 12:
				GearmanJob checkStatusJob = checkStatusJobs.get(clientID);

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

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

						if (result != "") {
							JSONObject resultObj = (JSONObject) JSONValue
									.parse(result);
							String rawoutput = resultObj.get("rawoutput")
									.toString();
							if (rawoutput.equals("is working")) {
								System.out.println(ipAddress + " is working");
								status.put(clientID, 17); // is working
								checkStatusJobs.remove(clientID);
							} else {
								System.out.println(ipAddress
										+ " is not working");
								status.put(clientID, 13); // is not working
								checkStatusJobs.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, 18);
							checkStatusJobs.remove(clientID);
						}
					}
				}

				break;

			case 13:
				restart(client);

				break;

			case 14:
				date = new Date();
				timestamp = date.getTime();
				pingRestartTime.put(clientID, timestamp);
				status.put(clientID, 15); // ping after restart

				break;

			case 15:
				pingRestart(client);

				break;

			case 16:
				GearmanJob pingJobRestart = pingRestartJobs.get(clientID);
				if (pingJobRestart != null) {
					Date currentDate = new Date();
					Long currentTimestamp = currentDate.getTime();
					// wait 2 min until Restart - Failed
					Long expectedTimestamp = this.pingRestartTime.get(clientID) + 120000L;
					if (expectedTimestamp >= currentTimestamp) {
						GearmanJobStatus jobStatus = gearmanClient
								.getJobStatus(pingJobRestart);
						if (!jobStatus.isKnown() && pingJobRestart.isDone()) {
							GearmanJobResult pingJobRes = pingJobRestart.get();
							String result = ByteUtils.fromUTF8Bytes(pingJobRes
									.getResults());
							if (result != "") {
								JSONObject resultObj = (JSONObject) JSONValue
										.parse(result);
								String alive = resultObj.get("alive")
										.toString();
								if (alive.equals("true")) {
									System.out.println(ipAddress
											+ " is alive after restart");
									// alive, go in successState
									status.put(clientID, 19);
									pingRestartJobs.remove(clientID);
								} else {
									System.out.println("ping again "
											+ ipAddress);
									status.put(clientID, 15); // again ping
									pingRestartJobs.remove(clientID);
								}
							}
						}
					} else {
						System.out.println(ipAddress
								+ " is not alive after restart");
						this.errors.put(clientID,
								"The restart has been failed.");
						status.put(clientID, 18); // not alive, go in errorState
						pingRestartJobs.remove(clientID);
					}
				}

				break;

			case 17:
				System.out.println("User is working Logik");

				break;

			case 18:
				System.out.println("Boot failed"); // errorState

				break;

			case 19:
				System.out.println("Boot successful"); // successState

				break;

			}

			if (clientStatus == 19) {
				allFinished = true;
			} else if (clientStatus == 18) {
				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 pingWakeOnLan(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, 7); // pingWol started
		pingWoLJobs.put(clientID, job);

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

	private void pingRestart(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, 16); // pingRestart started
		pingRestartJobs.put(clientID, job);

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

	private void wakeOnLan(HashMap<String, String> client) {
		String macAddress = client.get("mac");
		int clientID = Integer.parseInt(client.get("id"));

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

		status.put(clientID, 4); // wake on lan started
		wolJobs.put(clientID, job);

		System.out.println("wake on lan");
	}

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

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

		status.put(clientID, 8); // checkOS started
		osJobs.put(clientID, job);

		System.out.println("check OS " + 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, 10); // who started
		whoJobs.put(clientID, job);

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

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

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

		status.put(clientID, 12); // checkStatus started
		checkStatusJobs.put(clientID, job);

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

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

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

		status.put(clientID, 14); // restart started
		restartJobs.put(clientID, job);

		System.out.println("restart " + 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;
	}
}