網頁主動探測工具

壹頁書發表於2014-11-24
單位的專案是IBatis做的,每個查詢的SQL裡面都有很多判斷
上次最佳化SQL之後,其中的一個分支報錯,但是作為dba,不可能排查每一個分支.
所以,乾脆用爬蟲爬過所有的網頁,主動探測程式的異常.
這樣有兩個好處
1.可以主動檢視網頁是否異常 (500錯誤,404錯誤)
2.可以篩查速度較慢的網頁,從這個方向也可以定位慢SQL吧.(也有伺服器資源不足,造成網路超時的情況)

前提,
必須是網際網路公司,大多數網頁不用登入也可以瀏覽

首先,建表
CREATE SEQUENCE seq_probe_id INCREMENT BY 1 START WITH 1 NOMAXvalue NOCYCLE CACHE 2000;

create table probe( 
    id int primary key,
    host varchar(40) not null, 
    path varchar(500) not null,
    state int not null,
    taskTime int not null, 
    type varchar(10) not null,
    createtime date default sysdate not null 
) ;
其中host是域名,path是網頁的相對路徑,state是HTTP狀態碼,taskTime是網頁獲取時間,單位是毫秒,type是型別(html,htm,jpg等)

程式結構


程式分三個主要步驟,再分別用三個佇列實現生產者消費者模式.
1.連線.根據連線佇列的目標,使用Socket獲取網頁,然後放入解析佇列
2.解析.根據解析佇列的內容,使用正規表示式獲取該網頁的合法連線,將其再放入連線佇列.然後將解析的網頁放入持久化佇列
3.持久化.將持久化佇列的內容存入資料庫,以便查詢。

程式使用三個步驟並行,每個步驟可以併發的方式.
但是通常來說,解析和持久化可以分別用單執行緒的方式執行.


  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.InputStreamReader;
  4. import java.io.OutputStreamWriter;
  5. import java.net.InetAddress;
  6. import java.net.Socket;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.PreparedStatement;
  10. import java.sql.SQLException;
  11. import java.util.ArrayList;
  12. import java.util.Iterator;
  13. import java.util.List;
  14. import java.util.Set;
  15. import java.util.concurrent.BlockingQueue;
  16. import java.util.concurrent.ConcurrentSkipListSet;
  17. import java.util.concurrent.CopyOnWriteArrayList;
  18. import java.util.concurrent.ExecutorService;
  19. import java.util.concurrent.Executors;
  20. import java.util.concurrent.LinkedBlockingQueue;
  21. import java.util.concurrent.atomic.AtomicInteger;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;

  24. public class Probe {

  25.     private static final BlockingQueue<Task> CONNECTLIST = new LinkedBlockingQueue<Task>();
  26.     private static final BlockingQueue<Task> PARSELIST = new LinkedBlockingQueue<Task>();
  27.     private static final BlockingQueue<Task> PERSISTENCELIST = new LinkedBlockingQueue<Task>();
  28.     private static ExecutorService CONNECTTHREADPOOL;
  29.     private static ExecutorService PARSETHREADPOOL;
  30.     private static ExecutorService PERSISTENCETHREADPOOL;
  31.     private static final List<String> DOMAINLIST = new CopyOnWriteArrayList<>();

  32.     static {
  33.         CONNECTTHREADPOOL = Executors.newFixedThreadPool(200);
  34.         PARSETHREADPOOL = Executors.newSingleThreadExecutor();
  35.         PERSISTENCETHREADPOOL = Executors.newFixedThreadPool(1);
  36.         DOMAINLIST.add("域名");
  37.     }

  38.     public static void main(String args[]) throws Exception {
  39.         long start = System.currentTimeMillis();
  40.         CONNECTLIST.put(new Task("域名", 80, "/static/index.html"));

  41.         for (int i = 0; i < 600; i++) {
  42.             CONNECTTHREADPOOL.submit(new ConnectHandler(CONNECTLIST, PARSELIST));
  43.         }
  44.         PARSETHREADPOOL.submit(new ParseHandler(CONNECTLIST, PARSELIST, PERSISTENCELIST, DOMAINLIST));
  45.         PERSISTENCETHREADPOOL.submit(new PersistenceHandler(PERSISTENCELIST));

  46.         while (true) {
  47.             Thread.sleep(1000);
  48.             long end = System.currentTimeMillis();
  49.             float interval = ((end - start) / 1000);
  50.             int connectTotal = ConnectHandler.GETCOUNT();
  51.             int parseTotal = ParseHandler.GETCOUNT();
  52.             int persistenceTotal = PersistenceHandler.GETCOUNT();

  53.             int connectps = Math.round(connectTotal / interval);
  54.             int parseps = Math.round(parseTotal / interval);
  55.             int persistenceps = Math.round(persistenceTotal / interval);
  56.             System.out.print("\r連線總數:" + connectTotal + " \t每秒連線:" + connectps + "\t連線佇列剩餘:" + CONNECTLIST.size()
  57.                     + " \t解析總數:" + parseTotal + " \t每秒解析:" + parseps + "\t解析佇列剩餘:" + PARSELIST.size() + " \t持久化總數:"
  58.                     + persistenceTotal + " \t每秒持久化:" + persistenceps + "\t持久化佇列剩餘:" + PERSISTENCELIST.size());
  59.         }
  60.     }
  61. }

  62. class Task {
  63.     public Task() {
  64.     }

  65.     public void init(String host, int port, String path) {
  66.         this.setCurrentPath(path);
  67.         this.host = host;
  68.         this.port = port;
  69.     }

  70.     public Task(String host, int port, String path) {
  71.         init(host, port, path);
  72.     }

  73.     private String host;
  74.     private int port;
  75.     private String currentPath;
  76.     private long taskTime;
  77.     private String type;
  78.     private String content;
  79.     private int state;

  80.     public int getState() {
  81.         return state;
  82.     }

  83.     public void setState(int state) {
  84.         this.state = state;
  85.     }

  86.     public String getCurrentPath() {
  87.         return currentPath;
  88.     }

  89.     public void setCurrentPath(String currentPath) {
  90.         this.currentPath = currentPath;
  91.         this.type = currentPath.substring(currentPath.indexOf(".") + 1,
  92.                 currentPath.indexOf("?") != -1 ? currentPath.indexOf("?") : currentPath.length());

  93.     }

  94.     public long getTaskTime() {
  95.         return taskTime;
  96.     }

  97.     public void setTaskTime(long taskTime) {
  98.         this.taskTime = taskTime;
  99.     }

  100.     public String getType() {
  101.         return type;
  102.     }

  103.     public void setType(String type) {
  104.         this.type = type;
  105.     }

  106.     public String getHost() {
  107.         return host;
  108.     }

  109.     public int getPort() {
  110.         return port;
  111.     }

  112.     public String getContent() {
  113.         return content;
  114.     }

  115.     public void setContent(String content) {
  116.         this.content = content;

  117.     }
  118. }

  119. class ParseHandler implements Runnable {
  120.     private static Set<String> SET = new ConcurrentSkipListSet<String>();

  121.     public static int GETCOUNT() {
  122.         return COUNT.get();
  123.     }

  124.     private static final AtomicInteger COUNT = new AtomicInteger();
  125.     private BlockingQueue<Task> connectlist;
  126.     private BlockingQueue<Task> parselist;
  127.     private BlockingQueue<Task> persistencelist;
  128.     List<String> domainlist;

  129.     private interface Filter {
  130.         void doFilter(Task fatherTask, Task newTask, String path, Filter chain);
  131.     }

  132.     private class FilterChain implements Filter {
  133.         private List<Filter> list = new ArrayList<Filter>();

  134.         {
  135.             addFilter(new TwoLevel());
  136.             addFilter(new OneLevel());
  137.             addFilter(new FullPath());
  138.             addFilter(new Root());
  139.             addFilter(new Default());
  140.         }

  141.         private void addFilter(Filter filter) {
  142.             list.add(filter);
  143.         }

  144.         private Iterator<Filter> it = list.iterator();

  145.         @Override
  146.         public void doFilter(Task fatherTask, Task newTask, String path, Filter chain) {
  147.             if (it.hasNext()) {
  148.                 it.next().doFilter(fatherTask, newTask, path, chain);
  149.             }
  150.         }

  151.     }

  152.     private class TwoLevel implements Filter {

  153.         @Override
  154.         public void doFilter(Task fatherTask, Task newTask, String path, Filter chain) {
  155.             if (path.startsWith("../../")) {
  156.                 String prefix = getPrefix(fatherTask.getCurrentPath(), 3);
  157.                 newTask.init(fatherTask.getHost(), fatherTask.getPort(), path.replace("../../", prefix));
  158.             } else {
  159.                 chain.doFilter(fatherTask, newTask, path, chain);
  160.             }

  161.         }
  162.     }

  163.     private class OneLevel implements Filter {

  164.         @Override
  165.         public void doFilter(Task fatherTask, Task newTask, String path, Filter chain) {
  166.             if (path.startsWith("../")) {
  167.                 String prefix = getPrefix(fatherTask.getCurrentPath(), 2);
  168.                 newTask.init(fatherTask.getHost(), fatherTask.getPort(), path.replace("../", prefix));
  169.             } else {
  170.                 chain.doFilter(fatherTask, newTask, path, chain);
  171.             }

  172.         }

  173.     }

  174.     private class FullPath implements Filter {

  175.         @Override
  176.         public void doFilter(Task fatherTask, Task newTask, String path, Filter chain) {
  177.             if (path.startsWith("http://")) {
  178.                 Iterator<String> it = domainlist.iterator();
  179.                 boolean flag = false;
  180.                 while (it.hasNext()) {
  181.                     String domain = it.next();
  182.                     if (path.startsWith("http://" + domain + "/")) {
  183.                         newTask.init(domain, fatherTask.getPort(), path.replace("http://" + domain + "/", "/"));
  184.                         flag = true;
  185.                         break;
  186.                     }
  187.                 }
  188.                 if (!flag) {
  189.                     newTask = null;
  190.                 }
  191.             } else {
  192.                 chain.doFilter(fatherTask, newTask, path, chain);
  193.             }
  194.         }

  195.     }

  196.     private class Root implements Filter {

  197.         @Override
  198.         public void doFilter(Task fatherTask, Task newTask, String path, Filter chain) {
  199.             if (path.startsWith("/")) {
  200.                 newTask.init(fatherTask.getHost(), fatherTask.getPort(), path);
  201.             } else {
  202.                 chain.doFilter(fatherTask, newTask, path, chain);
  203.             }
  204.         }

  205.     }

  206.     private class Default implements Filter {

  207.         @Override
  208.         public void doFilter(Task fatherTask, Task newTask, String path, Filter chain) {
  209.             String prefix = getPrefix(fatherTask.getCurrentPath(), 1);
  210.             newTask.init(fatherTask.getHost(), fatherTask.getPort(), prefix + "/" + path);
  211.         }

  212.     }

  213.     public ParseHandler(BlockingQueue<Task> connectlist, BlockingQueue<Task> parselist,
  214.             BlockingQueue<Task> persistencelist, List<String> domainlist) {
  215.         this.connectlist = connectlist;
  216.         this.parselist = parselist;
  217.         this.persistencelist = persistencelist;
  218.         this.domainlist = domainlist;
  219.     }

  220.     private Pattern pattern = Pattern.compile("\"[^\"]+\\.htm[^\"]*\"");

  221.     private void handler() {
  222.         try {
  223.             Task task = parselist.take();
  224.             parseTaskState(task);
  225.             if (200 == task.getState()) {
  226.                 Matcher matcher = pattern.matcher(task.getContent());
  227.                 while (matcher.find()) {
  228.                     String path = matcher.group();
  229.                     if (!path.contains(" ") && !path.contains("\t") && !path.contains("(") && !path.contains(")")
  230.                             && !path.contains(":")) {
  231.                         path = path.substring(1, path.length() - 1);
  232.                         if (!SET.contains(path)) {
  233.                             SET.add(path);
  234.                             createNewTask(task, path);
  235.                         }
  236.                     }

  237.                 }
  238.             }
  239.             task.setContent(null);
  240.             persistencelist.put(task);
  241.         } catch (Exception e) {
  242.             // TODO Auto-generated catch block
  243.             e.printStackTrace();
  244.         }
  245.     }

  246.     private void parseTaskState(Task task) {
  247.         if (task.getContent().startsWith("HTTP/1.1")) {
  248.             task.setState(Integer.parseInt(task.getContent().substring(9, 12)));
  249.         } else {
  250.             task.setState(Integer.parseInt(task.getContent().substring(19, 22)));
  251.         }
  252.     }

  253.     /**
  254.      * @param fatherTask
  255.      * @param path
  256.      * @throws Exception
  257.      */
  258.     private void createNewTask(Task fatherTask, String path) throws Exception {
  259.         Task newTask = new Task();
  260.         FilterChain filterchain = new FilterChain();
  261.         filterchain.doFilter(fatherTask, newTask, path, filterchain);
  262.         if (newTask != null) {
  263.             connectlist.put(newTask);
  264.         }
  265.     }

  266.     private String getPrefix(String s, int count) {
  267.         String prefix = s;
  268.         while (count > 0) {
  269.             prefix = prefix.substring(0, prefix.lastIndexOf("/"));
  270.             count--;
  271.         }
  272.         return "".equals(prefix) ? "/" : prefix;
  273.     }

  274.     @Override
  275.     public void run() {
  276.         while (true) {
  277.             this.handler();
  278.             COUNT.addAndGet(1);
  279.         }
  280.     }

  281. }

  282. class ConnectHandler implements Runnable {
  283.     public static int GETCOUNT() {
  284.         return COUNT.get();
  285.     }

  286.     private static final AtomicInteger COUNT = new AtomicInteger();
  287.     private BlockingQueue<Task> connectlist;
  288.     private BlockingQueue<Task> parselist;

  289.     public ConnectHandler(BlockingQueue<Task> connectlist, BlockingQueue<Task> parselist) {
  290.         this.connectlist = connectlist;
  291.         this.parselist = parselist;
  292.     }

  293.     private void handler() {
  294.         try {
  295.             Task task = connectlist.take();
  296.             long start = System.currentTimeMillis();
  297.             getHtml(task);
  298.             long end = System.currentTimeMillis();
  299.             task.setTaskTime(end - start);
  300.             parselist.put(task);
  301.         } catch (Exception e) {
  302.             // TODO Auto-generated catch block
  303.             e.printStackTrace();
  304.         }
  305.     }

  306.     private void getHtml(Task task) throws Exception {
  307.         StringBuilder sb = new StringBuilder(2048);
  308.         InetAddress addr = InetAddress.getByName(task.getHost());

  309.         // 建立一個Socket

  310.         Socket socket = new Socket(addr, task.getPort());

  311.         // 傳送命令,無非就是在Socket傳送流的基礎上加多一些握手資訊,詳情請了解HTTP協議
  312.         BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
  313.         wr.write("GET " + task.getCurrentPath() + " HTTP/1.0\r\n");
  314.         wr.write("HOST:" + task.getHost() + "\r\n");
  315.         wr.write("Accept:*/*\r\n");
  316.         wr.write("\r\n");
  317.         wr.flush();

  318.         // 接收Socket返回的結果,並列印出來
  319.         BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  320.         String line;
  321.         while ((line = rd.readLine()) != null) {
  322.             sb.append(line);
  323.         }
  324.         wr.close();
  325.         rd.close();
  326.         task.setContent(sb.toString());
  327.         socket.close();
  328.     }

  329.     @Override
  330.     public void run() {
  331.         while (true) {
  332.             this.handler();
  333.             COUNT.addAndGet(1);
  334.         }
  335.     }
  336. }


  337. class PersistenceHandler implements Runnable {
  338.     static {
  339.         try {
  340.             Class.forName("oracle.jdbc.OracleDriver");
  341.         } catch (ClassNotFoundException e) {
  342.             // TODO Auto-generated catch block
  343.             e.printStackTrace();
  344.         }
  345.     }

  346.     public static int GETCOUNT() {
  347.         return COUNT.get();
  348.     }

  349.     private static final AtomicInteger COUNT = new AtomicInteger();
  350.     private BlockingQueue<Task> persistencelist;

  351.     public PersistenceHandler(BlockingQueue<Task> persistencelist) {
  352.         this.persistencelist = persistencelist;
  353.         try {
  354.             conn = DriverManager.getConnection("jdbc:oracle:thin:127.0.0.1:1521:orcl", "edmond", "edmond");
  355.             ps = conn
  356.                     .prepareStatement("insert into probe(id,host,path,state,tasktime,type) values(seq_probe_id.nextval,?,?,?,?,?)");
  357.         } catch (SQLException e) {
  358.             // TODO Auto-generated catch block
  359.             e.printStackTrace();
  360.         }
  361.     }

  362.     private Connection conn;
  363.     private PreparedStatement ps;

  364.     @Override
  365.     public void run() {
  366.         while (true) {
  367.             this.handler();
  368.             COUNT.addAndGet(1);
  369.         }
  370.     }

  371.     private void handler() {
  372.         try {
  373.             Task task = persistencelist.take();
  374.             ps.setString(1, task.getHost());
  375.             ps.setString(2, task.getCurrentPath());
  376.             ps.setInt(3, task.getState());
  377.             ps.setLong(4, task.getTaskTime());
  378.             ps.setString(5, task.getType());

  379.             ps.executeUpdate();
  380.             conn.commit();
  381.         } catch (InterruptedException e) {
  382.             e.printStackTrace();
  383.         } catch (SQLException e) {
  384.             e.printStackTrace();
  385.         }
  386.     }
  387. }

ParseHandler 使用了一個職責鏈模式,
TwoLevel 處理../../開頭的連線(../../sucai/sucai.htm)
OneLevel 處理../開頭的連線(../sucai/sucai.htm)
FullPath 處理絕對路徑的連線(http://域名/sucai/sucai.htm)
Root 處理/開頭的連線(/sucai/sucai.htm)
Default 處理常規的連線(sucai.htm)


ParseHandler FullPath 過濾需要一個白名單.
這樣可以使程式在固定的域名爬行

ParseHandler parseTaskState
解析狀態碼 可能需要根據實際情況進行調整
比如網頁404,伺服器可能會返回一個錯誤頁,而不是通常的HTTP狀態碼。

第一版僅僅實現了功能,錯誤處理不完整,
所以僅僅在定製的域名下生效,其實並不通用,後續會逐步完善.

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1344706/,如需轉載,請註明出處,否則將追究法律責任。

相關文章