getlog.jsp 14.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ page import="java.util.Properties" %>
<%@ page import="java.io.*" %>
<%@ page import="java.text.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.net.*" %>
<%@ page import="java.util.zip.*" %>
<%@ page import="java.math.*" %>
<%@ page import="java.nio.charset.Charset" %>
<%@ page import="java.util.regex.*" %>

<%

	weaver.hrm.User user = (weaver.hrm.User)request.getSession(true).getAttribute("weaver_user@bean");
	String ip = getIpAddress(request);
	if(user==null && !(ip!=null && innerIP(ip))){
		return ;
	}


	String startStr =  request.getParameter("startDate");
	String endStr =  request.getParameter("endDate");
	String logTypeStr =  request.getParameter("loytype");
	messageStr = new StringBuilder("");

	
	String ecologyPathtmp = request.getRealPath("/");
	if(!ecologyPathtmp.endsWith(File.separator)){
		ecologyPathtmp=ecologyPathtmp+File.separator;
	}
	final String ecologyPath = ecologyPathtmp;
	final String ResinPath = System.getProperty("user.dir")+File.separator;
	//out.println(ResinPath+"<br>");
	String outPath = ecologyPath+File.separator+"getlog"+File.separator+"log"; // 日志输出目录
	List dates = getDateList(startStr,endStr);
	File outFile = null;
	try{
		outFile = new File(outPath);
		if (!outFile.exists()) {
			outFile.mkdirs();
		}
	}catch (Exception e) {
			e.printStackTrace();
	}
	String outLogPath = outFile+File.separator+getInnerIp()+"downLog.zip";
	Map logtype =  new HashMap(){	// 日志类型路径
		{
			put("thread", ecologyPath+"log"+File.separator+"thread");  
			put("mem", ecologyPath+"log"+File.separator+"mem"); 
			put("ecology", ecologyPath+"log"); 
			put("sql", ecologyPath+"log"+File.separator+"sql"); 
			
			put("sqllog", ecologyPath+"sqllog"); 
			
			put("security", ecologyPath+"WEB-INF"+File.separator+"securitylog"); 
			put("Resin", ResinPath+"log"); 
			put("integration", ecologyPath+"log"+File.separator+"integration"); 
			
			put("monitorevent", ResinPath+"monitor"+File.separator+"resin"+File.separator+"app"+File.separator+"data"+File.separator+"event"); //运维平台的事件日志
			put("monitorPool", ResinPath+"monitor"+File.separator+"resin"+File.separator+"app"+File.separator+"data"+File.separator+"pool"); 
			put("monitorcpu", ResinPath+"monitor"+File.separator+"resin"+File.separator+"app"+File.separator+"data"+File.separator+"cpu"); 
			put("resinconf",  ResinPath+"conf"+File.separator+"resin.conf"); 
			put("ecoloyweaver",  ecologyPath+"WEB-INF"+File.separator+"prop"+File.separator); 
			put("monitorlog",  ResinPath+"monitor"+File.separator+"resin"+File.separator+"log");
			put("monitorconcurrent",  ResinPath+"monitor"+File.separator+"resin"+File.separator+"app"+File.separator+"data"+File.separator+"concurrent"); 
			
		}
	};
	
    	
    	
    	Map logMap = getLogType(logTypeStr,logtype);
    	Set keys = logMap.keySet();
        FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(outLogPath);
	        ZipOutputStream zos = new ZipOutputStream(fos);
			zos.setLevel(1);
			Iterator it = keys.iterator();
			
	    	while(it.hasNext()) {
				String key = (String) it.next();
				for(int i=0;i< dates.size();i++){
					String date = (String)dates.get(i);
				boolean isToDay = isToDay(date);
				List fileNames = transition(key,(String)logtype.get(key),date,isToDay);
					for(int j=0;j<fileNames.size();j++){
						String fileName = (String)fileNames.get(j);
						//out.println(fileName+"<br>");
							String basePath = date+File.separator;
							if("sqllog".equals(key)){
								basePath+=("sqllog"+File.separator);
							}
							if("monitorevent".equals(key)){
								basePath+=("event"+File.separator);
							}
							if("monitorlog".equals(key)){
								basePath+=("monitorlog"+File.separator);
							}
						compressbyType(fileName,zos,basePath);
					}
				}
	    	}
	    	
			try{
			zos.close();
			}catch(Exception es){}
			if(fos!=null)
			fos.close();
			File outLog = new File(outLogPath);
			String fileSize = getFileSize(outLog);
			out.println(fileSize+","+messageStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
        long end = System.currentTimeMillis();
       // out.println(end - start);
%>
<%!

	public static boolean innerIP(String ip) {
        String pattern = "((192\\.168|172\\.([1][6-9]|[2]\\d|3[01]))"
                + "(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){2}|"
                + "^(\\D)*10(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){3})";
        Pattern reg = Pattern.compile(pattern);
        Matcher match = reg.matcher(ip);
        return match.find()||ip.equals("127.0.0.1");
    }
	
	public String getIpAddress(HttpServletRequest request) {
	    String ip = request.getHeader("x-forwarded-for");
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getRemoteAddr();
	    }
	    if (ip.contains(",")) {
	        return ip.split(",")[0];
	    } else {
	        return ip;
	    }
	}
	
	
	private StringBuilder messageStr = new StringBuilder("");
	
	private Map getLogType (String logTypeStr,Map logtype){
		Map resultmap = new HashMap();
		String[] strs = logTypeStr.split(",");
		for(int i=0;i<strs.length;i++){
			String str = strs[i];
			if(str.equals("monitor")){
				resultmap.put("thread", logtype.get("thread"));
				resultmap.put("mem", logtype.get("mem"));
				resultmap.put("sql", logtype.get("sql"));
				resultmap.put("monitorevent", logtype.get("monitorevent"));
				resultmap.put("monitorPool", logtype.get("monitorPool"));
				resultmap.put("monitorcpu", logtype.get("monitorcpu"));
				resultmap.put("resinconf", logtype.get("resinconf"));
				resultmap.put("ecoloyweaver", logtype.get("ecoloyweaver"));
				resultmap.put("monitorconcurrent", logtype.get("monitorconcurrent"));
				resultmap.put("monitorlog", logtype.get("monitorlog"));
			}
			if(str.equals("Resin")){
				resultmap.put("Resin", logtype.get("Resin"));
			}
			if(str.equals("security")){
				resultmap.put("security", logtype.get("security"));
			}
			if(str.equals("ecology")){
				resultmap.put("ecology", logtype.get("ecology"));
			}
			if(str.equals("sql")){
				resultmap.put("sql", logtype.get("sql"));
			}
			if(str.equals("integration")){
				resultmap.put("integration", logtype.get("integration"));
			}
		}
		return resultmap;
	}

	private List getDateList(String startDate,String endDate){
		ArrayList list = new ArrayList();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date start = sdf.parse(startDate);
			Date end = sdf.parse(endDate);
	        Calendar tempStart = Calendar.getInstance();
	        tempStart.setTime(start);
		     while(start.getTime()<=end.getTime()){
		    	 list.add(sdf.format(tempStart.getTime()));
		         tempStart.add(Calendar.DAY_OF_YEAR, 1);
		         start = tempStart.getTime();
		     }
		} catch (Exception e) {
			e.printStackTrace();
		}
	    return list;
	}

	private boolean isToDay(String date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String toDay = sdf.format(new Date());
		return date.equals(toDay);
	}

	public List transition(String key,String path,String date,boolean isToDay){//转换真实的日志文件
		List list = new ArrayList();
		if("thread".equals(key)){
			list.add(path+File.separator+date);
		}else if("mem".equals(key)){
			list.add(path+File.separator+"memory_"+date+".log");
		}else if("ecology".equals(key)){
			if(isToDay){
				list.add(path+File.separator+"ecology");
			}else{
				list.add(path+File.separator+"ecology_"+getDateStr(date)+".log");
			}
		}else if("sql".equals(key)){
			list.add(path+File.separator+"sqlcount_"+date+".log");
			list.add(path+File.separator+"sqltime_"+date+".log");
		}else if("integration".equals(key)){
			if(isToDay){
				list.add(path+File.separator+"integration.log");
			}else{
				list.add(path+File.separator+"integration.log_"+getDateStr(date)+".log");
			}
		}else if("security".equals(key)){
			list.add(path+File.separator+"systemRunInfo"+date+".log");
			list.add(path+File.separator+"systemSecurity"+date+".log");
		}else if("Resin".equals(key)){
			if(isToDay){
				list.add(path+File.separator+"stdout.log");
				list.add(path+File.separator+"stderr.log");
			}else{
				list.add(path+File.separator+"stdout-"+getDateStr(date)+".log.gz");
				list.add(path+File.separator+"stderr-"+getDateStr(date)+".log.gz");
			}
			list.add(path+File.separator+"watchdog-manager.log");
			list.add(path+File.separator+"jvm-default.log");
		}else if("sqllog".equals(key)){
			list.add(path+File.separator+getSqlPathByDate(date));
			list.add(path+File.separator);
		}
		else if("monitorevent".equals(key)){
			list.addAll(eventLog(path,date));
		}
		else if("monitorPool".equals(key)){
			list.add(path+File.separator+"pool_"+getDateStr(date)+"_ecology.log");
			list.add(path+File.separator+"pool_"+getDateStr(date)+"_ecology.zip");
		}
		else if("monitorlog".equals(key)){
			if(isToDay){
				list.add(path+File.separator+"stdout.log");
				list.add(path+File.separator+"stderr-log");
			}else{
				list.add(path+File.separator+"stdout-"+getDateStr(date)+".log.gz");
				list.add(path+File.separator+"stderr-"+getDateStr(date)+".log.gz");
			}
		}
		else if("monitorconcurrent".equals(key)){
			list.add(path+File.separator+"concurrent_"+getDateStr(date)+".log");
			list.add(path+File.separator+"concurrent_"+getDateStr(date)+".zip");
		}
		else if("monitorcpu".equals(key)){
			list.add(path+File.separator+"cpu_"+getDateStr(date)+".log");
			list.add(path+File.separator+"cpu_"+getDateStr(date)+".zip");
		}
		else if("resinconf".equals(key)){
			list.add(path);
		}
		else if("ecoloyweaver".equals(key)){
			dealWidthWeaverProp(path+"weaver.properties",new File(path+"weaversecurity.properties"));
			list.add(path+"weaversecurity.properties");
		}
		return list;
	}

	private void dealWidthWeaverProp(String path,File outFile){//处理weaver.prop密码问题
		File file = new File(path);
		if (!file.exists()) {
        	return;
        }
		InputStreamReader reader = null;
		java.io.Writer outWriter = null;
		try {
			if(!file.exists()){
				file.createNewFile();
			}
			Properties registerProp = new Properties();
			reader = new InputStreamReader(new FileInputStream(file));
			registerProp.load(reader);
			reader.close();
			outWriter = new FileWriter(outFile);
			registerProp.put("ecology.password","***********");
			registerProp.store(outWriter, "");
			outWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
				if(reader!=null){
					reader.close();
				}
				if(outWriter!=null){
					outWriter.close();
				}
			}catch (Exception e) {
			}
		}
	}
	
	
	private List eventLog(String path ,String date){
		List list = new ArrayList();
		File file = new File(path);
		if (!file.exists()) {
        	return list;
        }
		File[] filelists = new File(path).listFiles();
		date = getDateStr(date);
		for(int i=0;i<filelists.length;i++){
			File filelist = filelists[i];
			if(filelist.getName().indexOf(date)!=-1){
				list.add(filelist.getAbsolutePath());
			}
		}
		return list;
	}
	
	private String getSqlPathByDate(String date){
		return date.replace("-",File.separator);
	}

	public String getFileSize(File file){
		if(!file.exists()){
			return "0KB";
		}
		long length = file.length();
		
		 BigDecimal b1 = new BigDecimal(Double.toString(length));
	     BigDecimal b2 = new BigDecimal(Double.toString(1024));
	     BigDecimal b3 =  b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);
	     b3.floatValue();
		if(b3.floatValue()>1024){
			return b3.divide(b2,2,BigDecimal.ROUND_HALF_UP).floatValue()+"M";
		}else{
			return b3.floatValue()+"KB";
		}
	}

	private String getInnerIp() {
		try {
			Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
				Enumeration nii = ni.getInetAddresses();
				while (nii.hasMoreElements()) {
					InetAddress inetAddress = (InetAddress) nii.nextElement();
					if (inetAddress.getHostAddress().indexOf(":") == -1) {
						String ip = inetAddress.getHostAddress();
						if (ip.startsWith("10.") || ip.startsWith("192.168.")) {// ||
							return ip;
						} else {
							if (ip.startsWith("172.")) {

									return ip;

							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "127.0.0.1";
	}

	private String getDateStr(String date){
		date  = date.replaceAll("-", "");
		return date;
	}

    /**
     * 按照原路径的类型就行压缩。文件路径直接把文件压缩
     * @param src
     * @param zos
     * @param baseDir
     */
     private  void compressbyType(String src, ZipOutputStream zos,String baseDir) {
		 File srcFile = new File(src);
            if (!srcFile.exists()) {
            	return;
            }
            //判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
            if (srcFile.isFile()) {
                //src是文件,调用此方法
                compressFile(srcFile, zos,baseDir);
            }else if(srcFile.isDirectory()) {
            	compressDir(srcFile, zos,baseDir);
            }
        }

        /**
         * 压缩文件,取后面的80M内容
        */
        private void compressFile(File file, ZipOutputStream zos,String baseDir) {
            if (!file.exists())
                return;
            try {
                RandomAccessFile fileRead = new RandomAccessFile(file, "r"); //用读模式
                long fileLength = fileRead.length();//获得文件长度
                if(file.getName().endsWith(".log") && fileLength>1073741820) {//如果文件超过80M,则只取文件倒数80M内容
	                messageStr.append("、").append(file.getName());
                	fileRead.seek(fileLength-1073741820);
                }else {
                	fileRead.seek(0);
                }
                ZipEntry entry = new ZipEntry(baseDir+file.getName());
                zos.putNextEntry(entry);
                int hasRead;
                byte[] buf = new byte[1024];
                while ((hasRead = fileRead.read(buf)) != -1) {
                    zos.write(buf, 0, hasRead);
                }
                fileRead.close();
            } catch (Exception e) {
				 
            }
        }
         
        /**
         * 压缩文件夹
         */
        private void compressDir(File dir, ZipOutputStream zos,String baseDir) {
            if (!dir.exists())
                return;
            File[] files = dir.listFiles();
            for (int i=0;i<files.length;i++) {
				File file = files[i]; 
                compressFile(file, zos,baseDir+dir.getName()+File.separator);
            }
    }

%>