fix:完善多机证书导入功能
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
package com.Sample;
|
||||
|
||||
import cn.hutool.core.date.StopWatch;
|
||||
import com.google.gson.Gson;
|
||||
import racal.sunyard.main.SydApi4j;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class TestCert {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
System.out.println("-----------start---------------");
|
||||
SydApi4j sydApi4j = new SydApi4j();
|
||||
String ipInfo = "/app/test/ipInfo.txt";
|
||||
String snmpInfo = "/app/test/snmp.txt";
|
||||
String certInfo = "/app/test/cert.txt";
|
||||
Map<String, String> map = readFileToMap(ipInfo);
|
||||
String ipInfos = map.get("ipList");
|
||||
List<String> ipList = Arrays.asList(ipInfos.split(","));
|
||||
int timeout = Integer.parseInt(map.get("timout"));
|
||||
String cert = readFileAsString(certInfo);
|
||||
String bkCode = map.get("bkcode");
|
||||
Map<String, String> snmpMap = readFileToMap(snmpInfo);
|
||||
Gson gson = new Gson();
|
||||
try {
|
||||
sydApi4j.importCertToServers(ipList, timeout, cert, bkCode, gson.toJson(snmpMap));
|
||||
} catch (Exception e) {
|
||||
System.out.println();
|
||||
System.out.println();
|
||||
System.out.println();
|
||||
System.out.println("---------------------证书导入失败日志----------------------");
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
System.out.println("------------end-----------------------");
|
||||
stopWatch.stop();
|
||||
System.out.println("耗时:" + stopWatch.getTotalTimeMillis() + "ms");
|
||||
|
||||
}
|
||||
public static Map<String, String> readFileToMap(String filePath) {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
// 跳过空行和注释行(假设以#开头的为注释)
|
||||
if (line.trim().isEmpty() || line.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 按分隔符分割键值(例如"="或":")
|
||||
String[] parts = line.split("=", 2); // 使用第二个参数限制分割次数
|
||||
if (parts.length == 2) {
|
||||
String key = parts[0].trim();
|
||||
String value = parts[1].trim();
|
||||
map.put(key, value);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
public static String readFileAsString(String filePath) {
|
||||
StringBuilder content = new StringBuilder();
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
content.append(line).append("\n");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return content.toString();
|
||||
}
|
||||
}
|
||||
@@ -120,5 +120,5 @@ public interface SydApi extends
|
||||
|
||||
public void setBindObject(Object bindObject);
|
||||
|
||||
void importCertToServers(List<String> addressList, int timeout, String cert);
|
||||
void importCertToServers(List<String> addressList, int timeout, String cert, String bkCode, String snmpConfig);
|
||||
}
|
||||
|
||||
@@ -137,6 +137,16 @@ public class SydApiException extends RuntimeException{
|
||||
}
|
||||
}
|
||||
|
||||
public SydApiException(String msg, int retCode, boolean flag){
|
||||
super(String.format(" %04X", retCode) + ":" + ( null == msg ? transMsg(retCode) : msg ));
|
||||
this.retCode = retCode;
|
||||
if (null == msg || "".equals(msg)){
|
||||
transMsg();
|
||||
}else {
|
||||
this.msg = msg;
|
||||
}
|
||||
}
|
||||
|
||||
public SydApiException(String msg, int ret, Throwable e) {
|
||||
super("SydApiException(code =" + String.format(" %04x", ret) + " : " + "msg =" + (msg == null ? "未定义的错误" : msg) + ")", e);
|
||||
this.retCode = ret;
|
||||
|
||||
@@ -11,10 +11,8 @@ import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Vector;
|
||||
|
||||
public class SnmpTrapSender {
|
||||
private static volatile SnmpTrapSender instance;
|
||||
public class SnmpTrapSender implements AutoCloseable{
|
||||
private Snmp snmp;
|
||||
private Properties config;
|
||||
|
||||
// 配置参数
|
||||
private String ip;
|
||||
@@ -23,50 +21,17 @@ public class SnmpTrapSender {
|
||||
private String community;
|
||||
private int version;
|
||||
|
||||
|
||||
private SnmpTrapSender() throws IOException {
|
||||
// loadConfig();
|
||||
ip = "172.16.18.113";
|
||||
port = 162;
|
||||
enterpriseOid = "1.3.6.1.4.1.2021.251.1";
|
||||
community = "public";
|
||||
version = 1;
|
||||
public SnmpTrapSender(Map<String, String> map) throws IOException {
|
||||
loadConfig(map);
|
||||
initializeSNMP();
|
||||
}
|
||||
|
||||
public static SnmpTrapSender getInstance() throws IOException {
|
||||
if (instance == null) {
|
||||
synchronized (SnmpTrapSender.class) {
|
||||
if (instance == null) {
|
||||
instance = new SnmpTrapSender();
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private void loadConfig() {
|
||||
try (InputStream input = getClass().getClassLoader().getResourceAsStream("test.properties")) {
|
||||
config = new Properties();
|
||||
config.load(input);
|
||||
|
||||
ip = config.getProperty("snmp.target.ip");
|
||||
port = Integer.parseInt(config.getProperty("snmp.target.port"));
|
||||
enterpriseOid = config.getProperty("enterprise.oid");
|
||||
community = config.getProperty("snmp.community");
|
||||
version = Integer.parseInt(config.getProperty("snmp.version"));
|
||||
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
throw new RuntimeException("加载配置文件失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void loadConfig(Map<String, String> map) {
|
||||
ip = map.getOrDefault("snmp.target.ip", null);
|
||||
// port = Integer.parseInt(map.getOrDefault("snmp.target.port", "0"));
|
||||
port = Integer.parseInt(map.getOrDefault("snmp.target.port", "162"));
|
||||
enterpriseOid = map.getOrDefault("enterprise.oid", null);
|
||||
community = map.getOrDefault("snmp.community", null);
|
||||
// version = Integer.parseInt(map.getOrDefault("snmp.version", "1"));
|
||||
community = map.getOrDefault("snmp.community", "public");
|
||||
version = Integer.parseInt(map.getOrDefault("snmp.version", "1"));
|
||||
}
|
||||
|
||||
private void initializeSNMP() throws IOException {
|
||||
@@ -109,10 +74,10 @@ public class SnmpTrapSender {
|
||||
pdu.add(new VariableBinding(SnmpConstants.sysUpTime,
|
||||
new TimeTicks(System.currentTimeMillis()/1000)));
|
||||
pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID,
|
||||
new OID(enterpriseOid + ".0.1")));
|
||||
pdu.add(new VariableBinding(new OID(enterpriseOid + ".1.1"),
|
||||
new OID(enterpriseOid + ".1.1")));
|
||||
pdu.add(new VariableBinding(new OID(enterpriseOid + ".2.1"),
|
||||
new OctetString(message)));
|
||||
pdu.add(new VariableBinding(new OID(enterpriseOid + ".1.2"),
|
||||
pdu.add(new VariableBinding(new OID(enterpriseOid + ".2.2"),
|
||||
new Integer32(severity)));
|
||||
}
|
||||
|
||||
@@ -126,9 +91,11 @@ public class SnmpTrapSender {
|
||||
return target;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
if (snmp != null) {
|
||||
snmp.close();
|
||||
snmp = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,8 +94,9 @@ public class AsyncTaskExecutor {
|
||||
private <T> CompletableFuture<T> handleRetry(TaskContext<T> context, Throwable ex) {
|
||||
if (context.canRetry()) {
|
||||
context.decreaseRetry();
|
||||
System.out.printf("[重试调度] ID: %s | 延迟: %ss | 剩余重试: %d | 错误: %s%n",
|
||||
System.out.printf("[重试调度] ID: %s| IP:%s | 延迟: %ss | 剩余重试: %d | 错误: %s%n",
|
||||
context.getTaskId(),
|
||||
context.getAddress(),
|
||||
context.getRetryDelay().getSeconds(),
|
||||
context.getRetriesLeft(),
|
||||
ex.getCause().getMessage());
|
||||
|
||||
@@ -25,7 +25,6 @@ import com.sunyard.trans.FullMode;
|
||||
import com.sunyard.trans.PacketSN;
|
||||
import com.sunyard.trans.RoundMode;
|
||||
import com.sunyard.util.*;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.bouncycastle.asn1.*;
|
||||
import org.bouncycastle.asn1.cms.ContentInfo;
|
||||
import org.bouncycastle.cms.SydCmsUtil;
|
||||
@@ -52,6 +51,7 @@ import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -1304,44 +1304,50 @@ public class SydApi4j implements SydApi {
|
||||
return dn;
|
||||
}
|
||||
|
||||
public void initSnmpTrapConfig(String config) {
|
||||
Gson gson = new Gson();
|
||||
Map<String, String> map =
|
||||
gson.fromJson(config, new TypeToken<Map<String, String>>() {}.getType());
|
||||
try {
|
||||
SnmpTrapSender.getInstance().loadConfig(map);
|
||||
} catch (IOException e) {
|
||||
throw new SydApiException("snmp配置错误", -1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void importCertToServers(List<String> addressList, int timeout, String cert) {
|
||||
if (CollectionUtils.isEmpty(addressList)) {
|
||||
throw new RuntimeException("签名服务器地址不能为空");
|
||||
public void importCertToServers(List<String> addressList, int timeout, String cert, String bkCode, String snmpConfig) {
|
||||
if (null == addressList || addressList.isEmpty()) {
|
||||
throw new IllegalArgumentException("签名服务器地址不能为空");
|
||||
}
|
||||
if (null == cert || cert.length() == 0) {
|
||||
throw new IllegalArgumentException("证书不能为空");
|
||||
}
|
||||
if (null == snmpConfig || snmpConfig.length() == 0) {
|
||||
throw new IllegalArgumentException("snmp配置不能为空");
|
||||
}
|
||||
List<TaskContext<String>> taskContexts =
|
||||
addressList.stream().map(p -> createTaskContext(p, timeout, cert)).collect(Collectors.toList());
|
||||
AsyncTaskExecutor executor = new AsyncTaskExecutor();
|
||||
List<TaskOutcome<String>> taskOutcomes = executor.execBatchTasks(taskContexts);
|
||||
//失败的记录日志
|
||||
List<String> failures = taskOutcomes.stream()
|
||||
.filter(out -> !out.isSuccess()).map(task -> task.getContext().getAddress())
|
||||
.collect(Collectors.toList());
|
||||
if (CollectionUtils.isNotEmpty(failures)) {
|
||||
List<String> failures = new ArrayList<>();
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
stringBuilder.append("日期:").append(LocalDateTime.now()).append("\n");
|
||||
for (TaskOutcome<String> taskOutcome : taskOutcomes) {
|
||||
if (!taskOutcome.isSuccess()) {
|
||||
failures.add(taskOutcome.getContext().getAddress());
|
||||
stringBuilder.append("ip:").append(taskOutcome.getContext().getAddress()).append("/证书导入失败:").append(taskOutcome.getError().getMessage()).append("\n");
|
||||
}
|
||||
}
|
||||
if (!failures.isEmpty()) {
|
||||
//记录失败日志
|
||||
stringBuilder.append("行号:").append(bkCode).append("\n").append("证书:").append(cert);
|
||||
//异步发送snmp trap消息
|
||||
String result = "[" + failures.stream()
|
||||
.map(Object::toString)
|
||||
.collect(Collectors.joining(",")) + "]";
|
||||
System.out.println(result);
|
||||
String message = "servers:" + result + ",import cert:" + cert + ",failed!";
|
||||
try {
|
||||
SnmpTrapSender.getInstance().sendTrap(message, 1);
|
||||
} catch (Exception e) {
|
||||
System.out.println("消息发送失败!");
|
||||
String message = "[SJJ1511] Certificate import failed - Servers:" + result + "| bkCode:[" + bkCode + "]";
|
||||
|
||||
Gson gson = new Gson();
|
||||
Map<String, String> map = gson.fromJson(snmpConfig, new TypeToken<Map<String, String>>() {}.getType());
|
||||
try (SnmpTrapSender sender = new SnmpTrapSender(map)) {
|
||||
sender.sendTrap(message, 2);
|
||||
System.out.println("snmp告警消息发送成功:" + message);
|
||||
} catch (IOException e) {
|
||||
System.out.println("snmp告警消息发送失败:" + e.getMessage());
|
||||
}
|
||||
throw new SydApiException(String.valueOf(stringBuilder), 56300, true);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2548,6 +2554,7 @@ public class SydApi4j implements SydApi {
|
||||
while (this.retryWhenNetError > 0) {
|
||||
try {
|
||||
println("Net error retry on " + this.retryWhenNetError);
|
||||
System.out.println("Net error retry on ");
|
||||
Socket socket = new Socket();
|
||||
SocketAddress address = new InetSocketAddress(ip, port);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user