*관련 : mon.html
package newscrap_restarter; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; /* * 이 프로그램은 신문스크랩 서버의 불안정으로 인해 서비스가 정상적이지 못할때 아파치를 리스타트해주는 프로그램입니다. * 제품의 원천적인 안정화 조치 완료 전까지만 임시로 운영할 프로그램입니다. * 현재 불안정 증상은 아파치는 떠 있는데 데이터쿼리(아래 예)의 결과가 정상으로 리턴되지 않는 것입니다. * 예: http://x.x.x.x/newscrap/search.php?keyword=&lastdate=20130124&usedate=false&startdate=20130124 * 오류 발생시 응답 : <?xml version="1.0" encoding="UTF-8"?>DB Error: connect failed * 즉 오류 발생시 정상적인 XML이 리턴되지 않고 있음. * 이 프로그램은 주기적으로 데이터를 서버로 요청하다가 정상적인 XML이 리턴되지 않는 경우 서비스의 오류로 판단하고 * 아파치를 재기동 합니다. */ public class NewscrapRestarter { // 프로세스 하나만 동작시키기위해.. private static final String PID_FILENAME = "/newscrap_restarter.pid"; private String BASE_URL = "http://x.x.x.x/newscrap/search.php?keyword=&lastdate=xxxxxxxx" + "&usedate=false&startdate=xxxxxxxx"; // 현재 에러 발생 상태인지 private boolean isErrorStatus = true; public static void main(String[] args) { new NewscrapRestarter().monitor(); } private void monitor() { if (pidFileExists()) { log("pid file already exists - " + PID_FILENAME); return; } try { createPidFile(); } catch (IOException e2) { log("error while create pid file - " + PID_FILENAME); return; } while (true) { try { getAndParseXML(); isErrorStatus = false; log("OK"); } catch (Exception e) { isErrorStatus = true; Date now1 = new Date(); err("", now1); e.printStackTrace(System.err); log("errors while getAndParseXML", now1); sms("errors while getAndParseXML", now1); try { restartApache(); } catch (Exception e1) { Date now2 = new Date(); err("", now2); e1.printStackTrace(System.err); log("errors while restarting Apache", now2); sms("errors while restarting Apache", now2); } } sleep(); } } private boolean pidFileExists() { File pidFile = new File(PID_FILENAME); return pidFile.exists(); } private void createPidFile() throws IOException { File pidFile = new File(PID_FILENAME); pidFile.deleteOnExit(); pidFile.createNewFile(); } private void sleep() { try { Thread.sleep(getSleepTime()); } catch (InterruptedException e) { e.printStackTrace(); } } private long getSleepTime() { if (isErrorStatus) return 1000 * 5; return 1000 * 10; } // process에서 output을 받아야 process 처리와 동기화 됨 private void restartApache() throws Exception { Process process; log("Apache2.2 service stopping.."); process = Runtime.getRuntime().exec( new String[] { "net", "stop", "Apache2.2" }); err(getOutput(process)); log("Apache2.2 service stopped."); log("Apache2.2 service starting.."); process = Runtime.getRuntime().exec( new String[] { "net", "start", "Apache2.2" }); err(getOutput(process)); log("Apache2.2 service started"); } private String getOutput(Process process) throws IOException { StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } private void log(String msg) { log(msg, new Date()); } private void log(String msg, Date now) { System.out.println(now + ":" + msg); } private void err(String msg) { err(msg, new Date()); } private void err(String msg, Date now) { System.err.println(now + ":" + msg); } private void sms(String msg, Date now) { // TODO implement send sms // System.out.println("SMS-->" + msg + "," + now); } // private boolean isValidXML(Document doc) { // NodeList nodeList = doc.getChildNodes(); // for (int i = 0; i < nodeList.getLength(); i++) { // Node node = nodeList.item(i); // System.out.println(node); // NodeList childNodes = node.getChildNodes(); // for (int j = 0; j < childNodes.getLength(); j++) { // Node childNode = childNodes.item(j); // System.out.println(childNode); // } // } // return true; // } private Document getAndParseXML() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); return db.parse(new URL(makeURL()).openStream()); // FileInputStream fis = new FileInputStream("d:/z.xml"); // return db.parse(fis); } private String makeURL() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String yyyyMMdd = sdf.format(new Date()); return makeURL(BASE_URL, yyyyMMdd); } String makeURL(String baseUrl, String yyyyMMdd) { return baseUrl.replaceAll("xxxxxxxx", yyyyMMdd); } }