CronScheduleThread.java
19.5 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package com.sitech.ismp.coll.cron;
import com.sitech.base.AgentProperties;
import com.sitech.base.Config;
import com.sitech.ismp.coll.CollBase;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.ismp.coll.busi.util.FilesOperation;
import com.sitech.ismp.messageObject.ScheduleLog;
import com.sitech.jmx.manage.CollScheduleManager;
import com.sitech.util.FileUtils;
import com.sitech.util.Formater;
import com.sitech.util.JSONUtil;
import com.sitech.util.RandomGUID;
import com.sitech.util.mq.MQConstants;
import com.sitech.util.mq.MQSender;
import com.sitech.util.mq.MQSenderFactory;
import com.sitech.util.mq.TunnelFactory;
import com.sitech.util.upload.FTPIF;
import com.sitech.util.upload.FTPSrv;
import com.sitech.util.upload.RemoteFile;
import com.sitech.util.upload.SFTPClient;
import org.apache.log4j.Logger;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
/**
* 北京crontab调度
*/
public class CronScheduleThread extends CollBase {
/** 脚本保存路径 */
static final String SCRIPT_PATH = AgentProperties.AGENT_HOME+"/script/cron/";
private String schId;
private String requestId;
private String shContent;
private String triggerType;
private String agentId;
private String shName;
private String oprType;
private String shellName;
private String nextFireTime;
private String targetDir;
private String targetFile;
private String overDir;
private String overFile;
private String unitId;
private String agentHome;
private String execUser;
/**
* 脚本下发
* @param params
*/
public void scriptSync2Agent(HashMap<String, String> params){
try{
init(params);
createScript();
}catch (Exception e){
logger.error("Exception while scriptSync2Agent", e);
}
}
private void createScript(){
String endTime = Formater.datetimeToString(new Date(),"yyyy-MM-dd HH:mm:ss");
Map<String,Object> extInfo = new HashMap<String, Object>();
boolean flag = isShellExist();
if(flag){
deleteShellScript();
}
String scriptSyncStatus = "0";
try{
sendScheduleLogs("agent准备生成脚本!", requestId, CronConstants.SEQ_1, CronConstants.BLANK_STR, extInfo);
flag = createShellScript();
if(isShellExist()){
scriptSyncStatus = "1";
extInfo.put("SCRIPT_SYNC_STATUS",scriptSyncStatus);
sendScheduleLogs("agent同步脚本成功!", requestId, CronConstants.SEQ_2, CronConstants.BLANK_STR, extInfo);
}else{
scriptSyncStatus = "0";
extInfo.put("SCRIPT_SYNC_STATUS",scriptSyncStatus);
sendScheduleLogs("agent同步脚本文件失败[没有生成脚本文件]!", requestId, CronConstants.SEQ_2, CronConstants.BLANK_STR, extInfo);
}
}catch (Exception e){
sendScheduleLogs("agent同步脚本文件失败["+e.getMessage()+"]!", requestId, CronConstants.SEQ_2, CronConstants.BLANK_STR, extInfo);
}
}
/**
* 附件下发
* @param params
*/
public void ftpHostAttachment(HashMap<String,String> params){
init(params);
getFtpFile();
}
/**
* 校验文件目录和文件是否存在
* @param params
*/
public void checkDirFileExist(HashMap<String,String> params){
init(params);
Map<String,Object> extInfo = new HashMap<String, Object>();
StringBuffer sb = new StringBuffer();
String dirStr = "";
String fileStr = "";
try{
String endTime = Formater.datetimeToString(new Date(),"yyyy-MM-dd HH:mm:ss");
File dirFile = new File(targetDir);
if(!dirFile.exists()){
dirStr = "DIR_EXIST=0";
fileStr = "FILE_EXIST=0";
}else{
dirStr = "DIR_EXIST=1";
File file = new File(targetDir+"/"+targetFile);
if(file.exists()){
fileStr = "FILE_EXIST=1";
}else{
fileStr = "FILE_EXIST=0";
}
}
sendScheduleLogs(sb.append(dirStr).append("\t").append(fileStr).toString() , requestId, CronConstants.SEQ_1, endTime, extInfo);
}catch (Exception e){
logger.error("[Cron Schedule] Exception while checkDirFileExist",e);
}
}
private void getFtpFile(){
Map<String,Object> extInfo = new HashMap<String, Object>();
String endTime = Formater.datetimeToString(new Date(),"yyyy-MM-dd HH:mm:ss");
try{
File dirFile = new File(targetDir);
//校验目录是否存在,不存在则创建
if (!dirFile.exists()) {
if ("1".equals(overDir)) {
sendScheduleLogs("agent开始创建" + targetDir + "...", requestId, CronConstants.SEQ_1, CronConstants.BLANK_STR, extInfo);
dirFile.mkdirs();
} else {
sendScheduleLogs(targetDir + "目录不存在", requestId, CronConstants.SEQ_1, endTime, extInfo);
return;
}
}
//生成文件前再次校验目录是否存在
if (dirFile.exists()) {
File file = new File(targetDir + "/" + targetFile);
if ("1".equals(overFile)) {
sendScheduleLogs("agent开始ftp获取" + targetFile + "...", requestId, CronConstants.SEQ_2, CronConstants.BLANK_STR, extInfo);
beginGetFtpFile();
} else {
sendScheduleLogs("agent开始校验" + targetFile + "是否存在...", requestId, CronConstants.SEQ_2, CronConstants.BLANK_STR, extInfo);
if (file.exists()) {
sendScheduleLogs(targetFile + "已存在!", requestId, CronConstants.SEQ_3, endTime, extInfo);
} else {
sendScheduleLogs("agent开始生成ftp脚本...", requestId, CronConstants.SEQ_3, CronConstants.BLANK_STR, extInfo);
beginGetFtpFile();
}
}
} else {
throw new RuntimeException("Dir " + targetDir + " not Exist");
}
}catch (Exception e){
logger.error("[Cron Schedule] Exception while ftpHostAttachment",e);
}
}
private void beginGetFtpFile() {
createShellScript();
Map<String, Object> extInfo = new HashMap<String, Object>();
if (isShellExist()) {
sendScheduleLogs("agent生成脚本成功!", requestId, CronConstants.SEQ_4, CronConstants.BLANK_STR, extInfo);
sendScheduleLogs("agent开始ftp获取" + targetFile, requestId, CronConstants.SEQ_5, CronConstants.BLANK_STR, extInfo);
} else {
sendScheduleLogs("agent创建脚本文件失败[没有生成脚本文件]!", requestId, CronConstants.SEQ_4, CronConstants.BLANK_STR, extInfo);
}
writeNoticeFile("6", requestId);
}
/*
private FTPIF getFtpClient(HashMap<String,String> params) {
String host = params.get("HOST").trim();
int port = Integer.valueOf(params.get("PORT").trim());
String username = params.get("USER_NAME").trim();
String password = params.get("PASSWORD").trim();
String encode = params.get("ENCODE").trim();
int timeout = 60*1000;
FTPIF ftpClient = new FTPSrv();
try {
logger.info("[Cron Schedule] ftp " + host + ", LOGIN:" + username + "...");
ftpClient.login(host, username, password);
} catch (Exception e) {
logger.warn("[Cron Schedule] ftp " + host + ", LOGIN:" + username + " FAILED!");
try {
ftpClient = new SFTPClient();
logger.info("[Cron Schedule] sftp " + username + "@" + host);
ftpClient.login(host, username, password);
} catch (Exception e1) {
logger.warn("[Cron Schedule] sftp " + username + "@" + host + " FAILED!");
ftpClient = null;
}
}
return ftpClient;
}
*/
/**
* 更新调度任务,发送更新日志
* @param params
*/
public void updateCronSchedule(HashMap<String, String> params){
// Map<String, Object> schedules = CollScheduleManager.getScheduleDetailList();
}
public Vector<TblATO_KPIDETAIL> checkScript(HashMap<String, String> params) {
try{
init(params);
checkManualScript();
writeNoticeFile("4",requestId);
}catch (Exception e){
logger.error("[Cron Schedule] Exception while checkScript",e);
}
return getKPISet();
}
private void checkManualScript(){
Map<String,Object> extInfo = new HashMap<String, Object>();
boolean flag = isShellExist();
if(flag){
deleteShellScript();
}
try{
sendScheduleLogs("agent准备生成脚本!", requestId, CronConstants.SEQ_1, CronConstants.BLANK_STR, extInfo);
flag = createShellScript();
if(isShellExist()){
sendScheduleLogs("agent生成脚本成功!", requestId, CronConstants.SEQ_2, CronConstants.BLANK_STR, extInfo);
}else{
sendScheduleLogs("agent创建脚本文件失败[没有生成脚本文件]!", requestId, CronConstants.SEQ_2, CronConstants.BLANK_STR, extInfo);
}
}catch (Exception e){
logger.error("[Cron Schedule] Exception while execCronSchedule",e);
}
sendScheduleLogs("agent开始执行脚本...", requestId, "3", CronConstants.BLANK_STR, extInfo);
}
/**
* 执行调度
* CM-10-10-12-51 执行时间
* CM-10-10-12-50 脚本内容
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> execCronSchedule(HashMap<String, String> params) {
try{
init(params);
String requestId = RandomGUID.getRandomGUID();
execSchedule(requestId);
writeNoticeFile("3", requestId);
}catch (Exception e){
logger.error("[Cron Schedule] Exception while execCronSchedule",e);
}
return super.getKPISet();
}
/**
* 执行脚本
* 执行脚本前需要比对脚本内容是否发生变化
*/
private void execSchedule(String requestId) {
sendScheduleLogs("agent准备生成脚本...", requestId, CronConstants.SEQ_0, CronConstants.BLANK_STR, null);
File localFile = new File(SCRIPT_PATH + shellName);
checkFile(localFile, shContent);
if (createShellScript(SCRIPT_PATH, shellName, shContent)) {
sendScheduleLogs("agent生成脚本成功!", requestId, CronConstants.SEQ_1, CronConstants.BLANK_STR, null);
} else {
sendScheduleLogs("agent生成脚本失败!", requestId, CronConstants.SEQ_1, CronConstants.BLANK_STR, null);
return;
}
sendScheduleLogs("agent开始执行脚本...", requestId, CronConstants.SEQ_2, CronConstants.BLANK_STR, null);
}
private void checkFile(File localFile, String shContent) {
String unit_id = unitId + "-" + schId;
try{
if (localFile.exists()) {
// 若脚本已经存在,则比对是否发生变化
logger.info("ShellFile[" + localFile.getName() + "] is exist, Start create compare info!");
String compareRst = compareScript(localFile, shContent);
// 若脚本不存在,则上报脚本创建时间和脚本内容
super.addKPI(unit_id, "CM-10-10-12-51", Formater.datetimeToString(new Date(localFile.lastModified())));
super.addKPI(unit_id, "CM-10-10-12-50", compareRst);
deleteShellScript();
} else {
// 若脚本不存在,则上报脚本创建时间和脚本内容
super.addKPI(unit_id, "CM-10-10-12-51", Formater.datetimeToString(new Date()));
super.addKPI(unit_id, "CM-10-10-12-50", shContent.replaceAll("\n","#SP#"));
}
}catch (Exception e){
logger.error("Exception while checkFile " + localFile.getName(), e);
}
}
/**
* 比对脚本是否发生变化
* @param localFile
* @param content
* @return
* @throws Exception
*/
private String compareScript(File localFile, String content) throws Exception{
String compareRst = "null";
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
StringBuffer tmpsb = new StringBuffer("");
try{
br = new BufferedReader(new FileReader(localFile));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
tmpsb.append(line+"#SP#");
}
if(!sb.toString().equals(content)){
compareRst = tmpsb.toString();
}
return compareRst;
}catch (Exception e){
throw new Exception("Exception while compare file " + localFile.getName(), e);
}finally {
if (null != br) {
try {
br.close();
} catch (Exception e) {
}
}
}
}
/**
* 比对脚本是否发生变化
* @param unit_id
* @param nextSeq
* @return
* @throws Exception
*/
private CollBase compareScript(String unit_id, String nextSeq) throws Exception{
CollBase collResult = new CollBase();
String localName = SCRIPT_PATH + shellName;
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
String line = "";
try{
File localFile = new File(localName);
Date mdfTime = new Date(localFile.lastModified());
String mdfDateTime = Formater.datetimeToString(mdfTime,"yyyy-MM-dd HH:mm:ss");
br = new BufferedReader(new FileReader(localName));
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
String contentVal = sb.toString();
if(shContent.equals(contentVal)){
contentVal = "null";
}
collResult.addKPI(unit_id,"CM-10-10-12-51",mdfDateTime);
collResult.addKPI(unit_id,"CM-10-10-12-50",contentVal);
}catch (Exception e){
logger.error("Exception while compareScript",e);
throw e;
}
return collResult;
}
/**
* 判断shell脚本是否已经存在
* @return
*/
private boolean isShellExist(){
FileUtils fu = new FileUtils();
return fu.isExists(SCRIPT_PATH, shellName);
}
private boolean createShellScript(String path, String fileName, String shContent) {
boolean flag = false;
try {
if (FileUtils.writeFile(path, fileName, shContent, false)) {
flag = isShellExist();
}
} catch (Exception e) {
flag = false;
logger.error("Exception while createShellScript " + fileName, e);
}
return flag;
}
private boolean createShellScript(){
logger.info("Create Shell_Name is :"+shellName);
return FileUtils.writeFile(SCRIPT_PATH, shellName, shContent, false);
}
private boolean deleteShellScript(){
FileUtils fu = new FileUtils();
return fu.delFile(SCRIPT_PATH, shellName);
}
private void init(HashMap<String, String> params){
unitId = params.get("UNIT_ID")==null?"":params.get("UNIT_ID");
schId = params.get("SCHEDULE_ID")==null?"":params.get("SCHEDULE_ID");
requestId = params.get("REQUEST_ID")==null?"":params.get("REQUEST_ID");
shName = params.get("SHELL_NAME")==null?"":params.get("SHELL_NAME");
shContent = params.get("SHELL_CONTENT")==null?"":params.get("SHELL_CONTENT").replaceAll("\r", "");
triggerType = params.get("TRIGGER_TYPE")==null?"":params.get("TRIGGER_TYPE");
execUser = params.get("EXEC_USER")==null?"":params.get("EXEC_USER");
agentId = AgentProperties.AGENT_ID;
agentHome = AgentProperties.AGENT_HOME;
oprType = params.get("OPERATE_TYPE")==null?"":params.get("OPERATE_TYPE");
nextFireTime = params.get("NEXT_FIRE_TIME")==null?"":params.get("NEXT_FIRE_TIME");
targetDir = params.get(CronConstants.ATTACH_PATH)==null?"":params.get(CronConstants.ATTACH_PATH);// 附件路径
targetFile = params.get(CronConstants.ATTACH_FILE)==null?"":params.get(CronConstants.ATTACH_FILE);// 文件名称
overDir = params.get(CronConstants.ATTACH_MKDIR)==null?"":params.get(CronConstants.ATTACH_MKDIR);// 是否新建路径 0不创建,1创建
overFile = params.get(CronConstants.ATTACH_CONVER)==null?"":params.get(CronConstants.ATTACH_CONVER);// 是否覆盖文件 0不覆盖 1覆盖
shellName = schId+"_"+shName;
logger.info("CronScheduleParams:SCH_ID["+schId+"],REQ_ID["+requestId+"],OPERATE_TYPE["+oprType+"]");
}
/**
*
* @param logContent 日志内容
* @param reqId
* @param seq
* @param endTime
* @param extInfo
*/
private void sendScheduleLogs(String logContent, String reqId, String seq, String endTime, Map<String,Object> extInfo){
ScheduleLog log = new ScheduleLog();
log.setLogType(CronConstants.SCHEDULE_LOG_MANUAL);
if( "0".equals(seq)){
log.setBeginTime(Formater.datetimeToString(new Date()));
}
if(null!=endTime && !"".equals(endTime.trim())){
log.setEndTime(endTime);
}
log.setOperateType(oprType);
log.setAgentId(agentId);
log.setNextFireTime(nextFireTime);
log.setType("std_out");
log.setSchId(schId);
log.setRequestId(reqId);
log.setSeq(seq);
log.setLogInfo(logContent);
log.setTrigerType(triggerType);
log.setExtInfo(extInfo == null ? new HashMap<String, Object>() : extInfo);
logger.info("sendScheduleLogs: " + JSONUtil.toJSON(log));
TunnelFactory.getTunnel(MQConstants.Q_ROPORT_FROM_AGENT).writeData(log);
}
/**
* 生成notice文件,通知crontab执行脚本
*/
private void writeNoticeFile(String seq, String guid) {
try {
String noticePath = agentHome + "/notice/cron/";
if (null != execUser && !"".equals(execUser)) {
noticePath += execUser + "/";
}
String tempPath = agentHome + "/script/cron/cron_tmp/";
String fileName = "notice_" + guid + ".sh";
logger.info("Create NoticeFile: " + fileName);
String content = CronConstants.NOTICE_CONTENT;
content = content.replaceAll("#AGENT_HOME#", agentHome);
content = content.replaceAll("#AGENT_ID#", agentId);
content = content.replaceAll("#REQUEST_ID#", guid);
content = content.replaceAll("#SCHEDULE_ID#", schId);
content = content.replaceAll("#OPERATE_TYPE#", oprType);
content = content.replaceAll("#TRRIGGER_TYPE#", triggerType);
content = content.replaceAll("#SEQ#", seq);
content = content.replaceAll("#SHELL_NAME#", shellName);
FileUtils.writeFile(tempPath, fileName, content, false);
FileUtils.createNewFile(noticePath, fileName);
} catch (Exception e) {
logger.error("Exception while writeNoticeFile", e);
}
}
}