WatchDog

1 resposta
E

Olá pessoal!

Gente preciso de uma ajuda. Procurei rapidamento no forum sobre algo relativo, mas não achei…

Bom, é o seguinte:

Preciso desenvolver um código com a idéia de um WatchDog(WD), mas não tão robusto.

O WD tem que pegar um endereço de um site qqr exemplo: http://site.com.br

Daí tenta fazer uma conexão ao site.

Se o tempo de conexão ultrapassar um timeout, ele desiste da conexão e restarta o tomcat.

Contudo eu não conheço mto da parte de conexões. ^^

Eu preparei a seguinte classe:

package br.org.reconcavo.site.utils;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class WatchDog {

	/** Default interval of time between checks, in milliseconds. */
	public static long DEFAULT_INTERVAL = 60000;

	private String site = new String("http://www.reconcavotecnologia.org.br/"); 

	/** The url to watch. */
	protected URL watchedURL;

	/** The interval of time between checks. */
	protected long interval = DEFAULT_INTERVAL;

	/**
	 * Returns the URL that will be watched.
	 *
	 * @return The URL being watched.
	 */
	public URL getURL() {
		return watchedURL;
	}

	/**
	 * Returns the interval of time, in milliseconds, between checks on the URL.
	 *
	 * @return An interval of time, in milliseconds.
	 */
	public long getInterval() {
		return interval;
	}


	public boolean execute(){
		try{
			Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress("192.168.0.13", 3128));
			this.watchedURL = new URL(this.site);
			URLConnection con = this.watchedURL.openConnection(proxy);
			con.setConnectTimeout((int)this.interval);
			con.connect();
			con.get
			
		}catch (Exception e){
			return false;
		}
	}
}

Mas não sei se estou no caminho certo.

Alguém já passou por algo parecido e pode me dá um help nesse task?

Obrigado desde já.

1 Resposta

E

Olá pessoal,

Apesar de não haverem respostas ao tópico, eu dei uma pesquisada por ai e consegui preparar algumas coisas.

Esse é o código atual, claro q precisando de algumas mudanças, mas refatorarei ele com o tempo. Ele tá funcionando, ao menos a parte de monitoramento, agora estou resolvendo a parte de restartar o Tomcat6 no windows. Acho q peguei um código básico, mas já tenho algumas idéias de como resolver o problema. Ao final posto a solução do problema.

Toda sorte fica ai para quem quiser dá uma olhada no processo de WatchDog:

import java.io.File;
import java.net.URL;
import java.net.URLConnection;

import org.apache.catalina.startup.Bootstrap;

public class WatchDog {

	/** Default interval of time between checks, in milliseconds. */
	public static long DEFAULT_INTERVAL = 6000;

	private String site = new String("http://localhost:8080/SiteReconcavo/");
	//new String("http://www.reconcavotecnologia.org.br/"); 

	/** The url to watch. */
	protected URL watchedURL;

	/** The interval of time between checks. */
	protected long interval = DEFAULT_INTERVAL;

	public WatchDog(){}

	public WatchDog(WatchDog wd){
		System.out.println("Entrei no Construtor!");
		this.acessa(wd).start();
	}

	/*
	public WatchDog(){
		try {
			this.iniciarThreads();	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void iniciarThreads() {
		try {

			int SLEEP_DADOS = 1000;

			InetAddress wdURL = InetAddress.getByName(Propriedades.WATCHDOG_URL.toString());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 */
	/**
	 * Returns the URL that will be watched.
	 *
	 * @return The URL being watched.
	 */
	public URL getURL() {
		return watchedURL;
	}

	/**
	 * Returns the interval of time, in milliseconds, between checks on the URL.
	 *
	 * @return An interval of time, in milliseconds.
	 */
	public long getInterval() {
		return interval;
	}

	public Thread acessa(final WatchDog wd){
		Thread t = new Thread() {
			public void run(){
				while (true) {
					try{
//						long tInicial = System.currentTimeMillis();
						wd.execute();
//						long tFinal = System.currentTimeMillis();
//						long limite = wd.getInterval();
//						if ((tInicial - tFinal) > limite)
//							wd.restartConnection();
					}catch (Exception e){
						System.out.println("WatchDog False!");
					}
				}
			}
		};
		t.setName("WATCH DOG SITE RECONCAVO!");
		return t;
	}


	public boolean execute(){
		try{
			System.out.println("Entrei no WatchDog!");
//			Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress("192.168.0.13", 3128));
			this.watchedURL = new URL(this.site);
//			URLConnection con = this.watchedURL.openConnection(proxy);
			URLConnection con = this.watchedURL.openConnection();
			con.setConnectTimeout((int)this.interval);
			con.connect();
			System.out.println("WatchDog True!");
			Thread.sleep(3000);
			return true;
		}catch (Exception e){
			System.out.println("WatchDog False!");
			this.restartTomcat();
			return false;
		}
	}

	public void restartTomcat(){
		System.out.println("Entrei no Verify!");
		try{
			String so = System.getProperty("os.name");
			System.out.println("SISTEMA OP => |"+so+"|");
//			"linux" "windows xp"
			if (so.equalsIgnoreCase("Windows XP")){
				System.out.println("=========ENTREI XP===========");
				Runtime runTime = Runtime.getRuntime();
//				String callAndArgs = new String("Arquivos de programas/Apache Software Foundation/Tomcat 6.0/bin/tomcat5.exe");
//				String callAndArgs = new String("C:\\Arquivos de programas\\Apache Software Foundation\\Tomcat 6.0\\bin\\");
//				File caminho = new File(callAndArgs);
				try {
					/*
					String[] arg = {"start", "stop"};
					Process child = runTime.exec("arquivos de programas/Apache Software Foundation/Tomcat 6.0/bin/tomcat5.exe");
					Process child = runTime.exec("tomcat6.exe",arg, caminho);
					 "C:\Arquivos de programas\Apache Software Foundation\Tomcat 6.0\bin\tomcat6.exe" //RS//Tomcat6
					Process child = runTime.exec("C:\\Arquivos de programas\\Apache Software Foundation\\Tomcat 6.0\\bin\\tomcat6.exe //RS//Tomcat6");
					Bootstrap bs = new Bootstrap();
					bs.setCatalinaHome(System.getenv("CATALINA_HOME"));
					bs.s
					System.out.println(bs.getCatalinaHome());
					bs.stop();
					bs.start();
					String tomcat_home = System.getenv("CATALINA_HOME");
					String java_home = System.getenv("JAVA_HOME");
					System.out.println("TOMCAT HOME "+tomcat_home);
					String prog = "java";
					String endorsed = " -Djava.endorsed.dirs=\"" + tomcat_home + "/common/endorsed\"";
					String classpath = " -classpath \"" + java_home + "/lib/tools.jar;" + tomcat_home + "/bin/bootstrap.jar\"";
					String cat_base = " -Dcatalina.base=\"" + tomcat_home + "\"";
					String cat_home = " -Dcatalina.home=\"" + tomcat_home + "\"";
					String temp = " -Djava.io.tmpdir=" + tomcat_home + "/temp";
					String bootclass = " org.apache.catalina.startup.Bootstrap";
					String commandStart = " start";
					String commandStop = " stop";
					
					String exeStart = prog + endorsed + classpath + cat_base + cat_home + temp + bootclass + commandStart;
					String exeStop = prog + endorsed + classpath + cat_base + cat_home + temp + bootclass + commandStop;
					*/
//					Process child = runTime.exec("C:\\Arquivos de programas\\Apache Software Foundation\\Tomcat 6.0\\bin\\tomcat6.exe //RS");
					/*
					System.out.println("1");
					Process child = runTime.exec(exeStop);
					System.out.println("2");
					child = runTime.exec(exeStart);
					System.out.println("3");
					*/
				} catch (Exception e) {
					e.printStackTrace();
				}				
			}
			else
				if (so.equalsIgnoreCase("linux")){ 
					(new ProcessBuilder("konsole")).command("sh /var/lib/tomcat5.5/bin/shutdown.sh");
					(new ProcessBuilder("konsole")).command("sh /var/lib/tomcat5.5/bin/startup.sh");
				}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		WatchDog wd = new WatchDog(); 
		new WatchDog(wd);
	}
}

Novamente, o código não tá refatorado e tá cheio de informações inúteis de teste.

Mas qm precisar de um WatchDog, já tem no q se basear.

Flwz

Criado 21 de maio de 2008
Ultima resposta 29 de mai. de 2008
Respostas 1
Participantes 1