ServerMonitor.java
  1 /*
  2  * ServerMonitor.java
  3  *
  4  * Created on April 29, 2004, 12:40 PM
  5  *
  6  *  Copyright 2004 Andrew Kaluzniacki. All Rights Reserved.
  7  *  http://drewk.net
  8  *
  9  *
 10  *  ToDO: handle many hosts - initialize by config file - propertiesfile maybe
 11  */
 12 
 13 /**
 14  *
 15  * @author  drew
 16  */
 17 
 18 import java.io.IOException;
 19 import java.io.OutputStreamWriter;
 20 import java.io.PrintWriter;
 21 import java.net.Socket;
 22 import java.net.UnknownHostException;
 23 import java.net.URL;
 24 import java.net.URLConnection;
 25 import java.util.Date;
 26 
 27 /**
 28  * ServerMonitor is a class for monitoring a server by checking to see if a
 29  * Socket connection can be made to named host at a specific port.
 30  */
 31 public class ServerMonitor {
 32     
 33     private String host = null;
 34     private int port = 0;
 35     private String errorString = null;
 36     private boolean sentMail = false;
 37     
 38     /**
 39      * Creates a new instance of ServerMonitor
 40      * @param host name of host to monitor
 41      * @param port port on host to be monitored
 42      */
 43     public ServerMonitor(String host, int port) {
 44         this.host = host;
 45         this.port = port;
 46     }
 47     
 48     /**
 49      * Check if a socket connection can be made to host:port
 50      * @return true if connection made.
 51      * false if no connection, and errorString is set to reason.
 52      */
 53     public boolean checkServer() {
 54         
 55         Socket socket = null;
 56         
 57         boolean retValue = false;
 58         errorString = "Success";
 59         
 60         try {
 61             socket = new Socket(host, port);
 62             retValue = true;
 63         } catch (UnknownHostException e) {
 64             errorString = "Unknown host exception:" + host;
 65         } catch (IOException e) {
 66             errorString = "IOException connecting to:" + host;
 67         }
 68         
 69         if (socket != null) {
 70             try {
 71                 socket.close();
 72             }  catch (IOException e) {
 73                 System.out.println("IOException closing socket:" + e);
 74             }
 75         }
 76         
 77         return retValue;
 78     }
 79     
 80     /**
 81      * Send email to notify administrator of failure.
 82      * This is only done once.
 83      */
 84     public void emailAdmin(String adminEmail, String smtpHost) {
 85         
 86         if (sentMail) { // only once
 87             return;
 88         }
 89         
 90         sentMail = true;
 91         
 92         System.out.println("Sending mail to admin.");
 93         
 94         try {
 95             System.getProperties().put("mail.host", smtpHost);
 96             URL u = new URL("mailto:" + adminEmail);
 97             URLConnection c = u.openConnection();
 98             c.setDoInput(false);
 99             c.setDoOutput(true);
100             c.connect();
101             PrintWriter mail_out =
102             new PrintWriter(new OutputStreamWriter(c.getOutputStream() ) );
103             
104             mail_out.println("To:" + adminEmail);
105             mail_out.println("Subject:[Server Monitor] " + host);
106             mail_out.println();
107             
108             mail_out.println("Check the log. This will be the only message until you restart ServerMonitor.");
109             mail_out.close();
110         } catch (Exception e) {
111             System.out.println("ERROR: unable to send mail. " + e);
112             sentMail = false;
113         }
114         
115     }
116     
117     
118     /**
119      * Returns a string describing the result of last call to checkServer
120      * @return status string
121      */
122     public String getError() { return errorString; }
123     
124     /**
125      * Run the ServerMonitor
126      * @param args the command line arguments - none<br>
127      *  Arguments are passed as system properties.<br>
128      *  sm.host<br>
129      *  sm.port<br>
130      *  sm.interval [minutes]<br>
131      *  sm.refHost<br>
132      *  sm.refPort<br>
133      *  sm.adminEmail<br>
134      *  sm.smtpHost<br>
135      *
136      * @throws InterruptedException only if the call to sleep is interupted.
137      */
138     public static void main(String[] args) throws InterruptedException {
139          
140         
141         String host = System.getProperty("sm.host", "localhost");
142         
143         int port = Integer.getInteger("sm.port", 80).intValue();
144    
145         int intervalMinutes = Integer.getInteger("sm.interval", 10).intValue();
146         
147         String refHost = System.getProperty("sm.refHost", "localhost");
148         
149         int refPort = Integer.getInteger("sm.refPort", 80).intValue();
150             
151         String adminEmail = System.getProperty("sm.adminEmail", "root@localhost");
152         
153         String smtpHost = System.getProperty("sm.smtpHost", "localhost");
154  
155         
156         System.out.println("Starting ServerMonitor. host:" + host + " port:" +
157         port + " refHost:" + refHost + " refPort:" +
158         refPort + " interval:" + intervalMinutes +
159         " adminEmail:" + adminEmail + " smtpHost:" + smtpHost);
160         
161         ServerMonitor sm = new ServerMonitor(host, port);
162         ServerMonitor rm = new ServerMonitor(refHost , refPort);
163         
164         
165         while (true) {
166             Date date = new Date();
167             if (sm.checkServer()) {
168                 System.out.println( "[" + date + "] " + host +
169                 " seems to be running.");
170             } else {
171                 System.out.println( "[" + date + "] Error: " + host +
172                 " not reachable. " + sm.getError());
173                 if (rm.checkServer()) {
174                     System.out.println( "     Checking reference host. " + refHost +
175                     " seems to be running.");
176                 } else {
177                     System.out.println( "     Checking reference host.  Error: " +
178                     refHost + " not reachable. " + rm.getError());
179                 }
180                 
181                 sm.emailAdmin(adminEmail, smtpHost);
182             }
183             long millis = intervalMinutes * ( 60 * 1000 );
184             Thread.sleep(millis);
185         }
186     }
187 }
188