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




                                               
                      
                         
                                 











                                                        
                                 



                                      

                                                        
                                     
                              

                                           
 

                                                                   
                                                      
                                                     
                                                            
                                                              
                                                    
                                                        
                                                 
                                                



                                                          
 





                                                                                  
                                                                   
                                                
































                                                                                                          


                                                                          
                                                             
                 






                                   



                                                                                   













                                                                                





                                                                                     



                                                                           

                                                                



                                                                          
 

                                             
 
                                      
 











                                                                                                  
                                                                        

                                                                                                     
                                                                                            

                                                                                                     
 




                                                                                                                 
                                                                                                   





                                                                                                                           
                                                                

                                                                                                                    
                                                                      



                                                                                                                                             




                                                                                          
 
                                      
 
                               
                                            
 
                                      
 
                               










                                                                                                 
                                                                        

                                                                                                     
                                                                                            







                                                                                                             
 

                                                                                                    


                                                                                                                   


                                                                                                    


                                                                                                                  

                                                                                                 
                                                                


                                                                                                                                           
                                                                      






                                                                                                                                                     

                                                                                         


                                                 
 
                                      
 
                               
                                                   
 
                                      
 
                               

                                                                                        
                                                                                  
                                                                                     
 

                                                                                                 

                                                                                                 
                                                                        

                                                                                                     
                                                                                            



                                                                                                            
                                                                                                


                                                                                                                   
                                                                      

                                                                                                                                                 



                                                                                                        
                                                                                         
                                                                                                
                                                         



















                                                                               



                                                                                            
                                                                    
                                                                                               
                                                                   






                                                                                                            
                                                                                

                                                                                                             
                                                                                                    


                                                                                                             

                                                                                                                           

                                                                                                                
                                                                                                                  
                                                                                                          
                                                                                          
                                                                                                                  
                                                                                                                                                            

                                                                                                          
                                                                         
                                                                        
                                                                                  

                                                                                                                                                           
                                                                              

                                                                                                                                                                    



                                                                                                                  

                                                                                                  





                                                                                              
                                                                    


                                                                                                         


                                                                                  
 
                                      
 
                               
                                           



                                      
                                                                        
 
                                                    
                                                                                  
                                                                             
 

                                                                                         


                                                                                                 
                                                                        

                                                                                                     
                                                                                            















                                                                                                                 
                                                                                     


                                                                                                               
                                                                                                
                                                                                            


                                                                                                                  
                                                                                                



                                                                                                                                               
                                                                              







                                                                                                                                                           
                                                                 

                                                                                            
                                                                                                                       
                                                                      

                                                                                                                                                   



                                                                                                         
                                                                                         
                                                                                        
                                                         






                                                 


                                                                                   
                                                         



                                      




                                                                                                         
 

                                      
                                



                                                                                                             
 
                                      
 
                         





                                                                          
                                                   
























                                                                                       
 
                                                          






                                                                                      
                                                       
                                           
 
                                                       
         
 
                                                                 


                                                                  

                                                                                 

                                          
                                                            
                                                  
 
                                                              
         
 







                                                                                       
                                                                



                                                        
 
                                                         


                                                                  

                                                                                     

                                          
                                                       
                                          
 
                                                      

         

                                                                     

                                                        

         

                                                                  
                                                          
                                   


                                     
                                          




                                               



                                                             



                                      
 
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 String eventName;
	private Vector<HashMap<String, String>> clients;
	private final int updateRate;
	private long waitTime;
	private Vector<String> psWhitelist;
	private Vector<String> psBlacklist;

	private final GearmanJobServerConnection gearmanConnection;
	private GearmanClient gearmanClient;
	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, Long> pingShutdownTime;
	private HashMap<Integer, Integer> status;
	private HashMap<Integer, String> errors;
	private HashMap<Integer, Boolean> finishedClients;
	private Boolean finished;
	private Boolean error;
	private String[] statusText;

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

	public void run() {
		workerLoop();
	}

	private void workerLoop() {
		long beginTime;
		long timeTaken;
		long timeLeft;
		final 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;
				Thread.sleep(timeLeft);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		finished = true;
		if (error) {
			System.out.println("Shutdown of " + eventName + " failed");
		} else {
			System.out.println("Shutdown of " + eventName + " finished");
		}
	}

	private Boolean update() throws IllegalStateException, IOException,
			InterruptedException, ExecutionException {
		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.");
								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.");
								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");
								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 = 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 anymore");
										// 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 command");
										// still alive, ping again
										status.put(clientID, 7);
									}
								} else {
									System.out
											.println(ipAddress
													+ " Cannot send the ping after shutdown message.");
									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");
						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 whitelistFound = false;
								boolean blacklistFound = false;

								for (String blackEntry : psBlacklist) {
									if (ps.toString().contains(blackEntry)) {
										blacklistFound = true;
									}
								}

								for (String whiteEntry : psWhitelist) {
									if (ps.toString().contains(whiteEntry)) {
										whitelistFound = true;
									}
								}

								if (blacklistFound) {
									System.out.println(ipAddress
											+ " is working");
									status.put(clientID, 11); // is working
									psJobs.remove(clientID);
								} else if (whitelistFound) {
									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.");
									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);
								}
							} else {
								System.out.println(ipAddress
										+ " Cannot check if user is working.");
								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:
				System.out.println("User has been working");
				errors.put(clientID, "The user has been working.");
				// user has been working, go in errorState
				status.put(clientID, 12);

				break;

			case 12:
				if (!finishedClients.get(clientID)) {
					System.out.println(ipAddress + " shutdown failed"); // errorState
					finishedClients.put(clientID, true);
					error = true;
				}

				break;

			case 13:
				if (!finishedClients.get(clientID)) {
					System.out.println(ipAddress + " shutdown finished"); // successState
					finishedClients.put(clientID, true);
				}

				break;

			}
		}

		boolean allFinished = false;
		for (HashMap<String, String> client : clients) {
			int clientID = Integer.parseInt(client.get("id"));
			if (finishedClients.get(clientID)) {
				allFinished = 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 = status.get(clientID);
		return statusText[clientStatus];
	}

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

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

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

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

	public String getEventName() {
		return eventName;
	}
}