提交 fcf2b9e4 编写于 作者: A ascrutae

修复部分问题

上级 ce81b2ee
......@@ -14,12 +14,10 @@ public class Config {
public static class ProcessThread {
public static long THREAD_WAIT_INTERVAL = 60 * 1000L;
// public static long THREAD_WAIT_INTERVAL = 5 * 1000L;
}
public static class ZKPath {
public static String CONNECT_STR = "127.0.0.1:2181";
public static int CONNECT_TIMEOUT = 1000;
......@@ -49,13 +47,13 @@ public class Config {
public static class DB {
public static String PASSWORD = "devrdbusr21";
public static String PASSWORD = "root";
public static String USER_NAME = "devrdbusr21";
public static String USER_NAME = "root";
public static String DRIVER_CLASS = "com.mysql.jdbc.Driver";
public static String URL = "jdbc:mysql://10.1.228.202:31316/test";
public static String URL = "jdbc:mysql://127.0.0.1:3316/test";
public static int MAX_IDLE = 1;
......@@ -83,15 +81,28 @@ public class Config {
public static int REDIS_MAX_TOTAL = 20;
public static boolean ALARM_OFF_FLAG = false;
public static String ALARM_TYPE_CONFIG_ID = "1004";
}
public static class MailSenderInfo {
public static String configId = "1000";
public static String MAIL_HOST = "mail.com";
public static String TRANSPORT_PROTOCOL = "smtp";
public static boolean SMTP_AUTH = true;
public static boolean SSL_ENABLE = false;
public static String USERNAME = "username";
public static String PASSWORD = "password";
public static String SENDER = "sender@mail.com";
}
public static class TemplateInfo {
public static String CONFIG_ID = "1001";
}
public static String PORTAL_URL = "http://127.0.0.1:8080/skywalking";
}
}
......@@ -3,34 +3,45 @@ package com.a.eye.skywalking.alarm.model;
public class AlarmType {
//告警类型名称
private String type;
//告警标签
private String label;
//告警描述
private String desc;
@Override
public String toString() {
return "AlarmType [type=" + type + ", label=" + label + ", desc=" + desc + "]";
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
//告警类型名称
private String type;
//告警标签
private String label;
//告警描述
private String desc;
public AlarmType(String type, String label, String desc) {
this.type = type;
this.label = label;
this.desc = desc;
}
@Override
public String toString() {
return "AlarmType [type=" + type + ", label=" + label + ", desc=" + desc + "]";
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
......@@ -2,7 +2,6 @@ package com.a.eye.skywalking.alarm.model;
public class ApplicationInfo {
private String appId;
private String configArgs;
private String UId;
private String toDoType;
private String appCode;
......@@ -19,9 +18,6 @@ public class ApplicationInfo {
this.appId = appId;
}
public String getConfigArgs() {
return configArgs;
}
public void setUId(String UId) {
this.UId = UId;
......@@ -31,14 +27,6 @@ public class ApplicationInfo {
return UId;
}
public void setToDoType(String toDoType) {
this.toDoType = toDoType;
}
public String getToDoType() {
return toDoType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
......
......@@ -18,9 +18,9 @@ import com.a.eye.skywalking.alarm.model.AlarmRule;
import com.a.eye.skywalking.alarm.model.AlarmType;
import com.a.eye.skywalking.alarm.model.ApplicationInfo;
import com.a.eye.skywalking.alarm.model.MailInfo;
import com.a.eye.skywalking.alarm.util.MailSender;
import com.a.eye.skywalking.alarm.util.RedisUtil;
import com.a.eye.skywalking.alarm.util.TemplateConfigurationUtil;
import com.a.eye.skywalking.alarm.util.MailUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
......@@ -35,189 +35,188 @@ import freemarker.template.TemplateException;
public class AlarmMessageProcessor {
private static Logger logger = LogManager
.getLogger(AlarmMessageProcessor.class);
private static final String TYPE_OF_EXCEPTION_WARNING = "default";
static List<AlarmType> alarmTypeList;
static Template t;
static {
alarmTypeList = AlarmTypeUtil.getAlarmTypeList();
}
public void process(UserInfo userInfo, AlarmRule rule)
throws TemplateException, IOException, SQLException {
Map<String, List<AlarmMessage>> warningMap = new HashMap<String, List<AlarmMessage>>();
Set<String> warningMessageKeys = new HashSet<String>();
long currentFireMinuteTime = System.currentTimeMillis() / (1000 * 60);
long warningTimeWindowSize = currentFireMinuteTime
- rule.getPreviousFireTimeM();
// 获取待发送数据
if (warningTimeWindowSize >= rule.getConfigArgsDescriber().getPeriod()) {
for (AlarmType alarmType : alarmTypeList) {
String type = alarmType.getType();
List<AlarmMessage> warningObjects = new ArrayList<AlarmMessage>();
for (ApplicationInfo applicationInfo : rule
.getApplicationInfos()) {
for (int period = 0; period < warningTimeWindowSize; period++) {
Long currentMinuteTime = currentFireMinuteTime - period
- 1;
String alarmKey = userInfo.getUserId() + "-"
+ applicationInfo.getAppCode() + "-"
+ currentMinuteTime;
if (!TYPE_OF_EXCEPTION_WARNING.equals(type)) {
alarmKey += "-" + type;
}
warningMessageKeys.add(alarmKey);
setAlarmMessages(alarmKey, warningObjects);
}
}
if (warningObjects.size() > 0) {
warningMap.put(type, warningObjects);
}
}
// 发送告警数据
int warningSize = this.getWarningSize(warningMap);
int exceptionAlarmSize = this.getExceptionSize(warningMap);
if (warningSize > 0) {
if ("0".equals(rule.getTodoType())) {
logger.info(
"A total of {} alarm information needs to be sent {}",
warningSize, rule.getConfigArgsDescriber()
.getMailInfo().getMailTo());
// 发送邮件
String subjects = generateSubject(userInfo.getUserName(),
exceptionAlarmSize, warningSize,
rule.getPreviousFireTimeM(), currentFireMinuteTime);
Map<String, Object> parameter = new HashMap<String, Object>();
parameter.put("alarmTypeList", alarmTypeList);
parameter.put("warningMap", warningMap);
parameter.put("name", userInfo.getUserName());
parameter.put("startDate", new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").format(new Date(rule
.getPreviousFireTimeM() * 10000 * 6)));
parameter.put("endDate", new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").format(new Date(
currentFireMinuteTime * 10000 * 6)));
String mailContext = generateContent(parameter);
if (mailContext.length() > 0) {
MailInfo mailInfo = rule.getConfigArgsDescriber()
.getMailInfo();
MailUtil.sendMail(mailInfo.getMailTo(),
mailInfo.getMailCc(), mailContext, subjects);
}
}
}
// 清理数据
for (String toBeRemovedKey : warningMessageKeys) {
expiredAlarmMessage(toBeRemovedKey);
}
// 修改-保存上次处理时间
dealPreviousFireTime(userInfo, rule, currentFireMinuteTime);
}
}
private void dealPreviousFireTime(UserInfo userInfo, AlarmRule rule,
long currentFireMinuteTime) {
rule.setPreviousFireTimeM(currentFireMinuteTime);
savePreviousFireTime(userInfo.getUserId(), rule.getRuleId(),
currentFireMinuteTime);
}
private String generateSubject(String userName, int exceptionAlarmSize,
int count, long startTime, long endTime) {
String title = (exceptionAlarmSize > 0 ? "[Error]" : "[Warning]")
+ " Dear "
+ userName
+ ", SkyWalking collects "
+ (exceptionAlarmSize > 0 ? exceptionAlarmSize
+ " tid of system exceptions, " : "");
if (count > exceptionAlarmSize) {
title += (count - exceptionAlarmSize) + " tid of warnings, ";
}
title += "between "
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(
startTime * 10000 * 6))
+ " to "
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(
endTime * 10000 * 6));
return title;
}
private void expiredAlarmMessage(final String key) {
RedisUtil.execute(new RedisUtil.Executable<Long>() {
@Override
public Long exe(Jedis client) {
return client.expire(key, 0);
}
});
}
private void savePreviousFireTime(final String userId, final String ruleId,
final long currentFireMinuteTime) {
RedisUtil.execute(new RedisUtil.Executable<Long>() {
@Override
public Long exe(Jedis client) {
return client.hset(userId, ruleId,
String.valueOf(currentFireMinuteTime));
}
});
}
private void setAlarmMessages(final String key,
final Collection<AlarmMessage> warningTracingIds) {
RedisUtil.execute(new RedisUtil.Executable<Object>() {
@Override
public Collection<String> exe(Jedis client) {
Map<String, String> result = client.hgetAll(key);
if (result != null) {
for (String traceid : result.keySet()) {
warningTracingIds.add(new AlarmMessage(traceid, result
.get(traceid)));
}
}
return null;
}
});
}
private String generateContent(Map parameter) throws IOException,
TemplateException, SQLException {
if (t == null) {
t = TemplateConfigurationUtil.getConfiguration().getTemplate(
"mail-template.ftl");
}
StringWriter out = new StringWriter();
t.process(parameter, out);
return out.getBuffer().toString();
}
private int getExceptionSize(Map<String, List<AlarmMessage>> warningMap) {
if (warningMap.containsKey(TYPE_OF_EXCEPTION_WARNING)) {
return warningMap.get(TYPE_OF_EXCEPTION_WARNING).size();
}
return 0;
}
private int getWarningSize(Map<String, List<AlarmMessage>> warningMap) {
int result = 0;
for (Entry<String, List<AlarmMessage>> entry : warningMap.entrySet()) {
if (entry.getValue() != null) {
result += entry.getValue().size();
}
}
return result;
}
private static Logger logger = LogManager
.getLogger(AlarmMessageProcessor.class);
private static final String TYPE_OF_EXCEPTION_WARNING = "default";
static List<AlarmType> alarmTypeList;
static Template t;
static {
alarmTypeList = AlarmTypeUtil.getAlarmTypeList();
}
public void process(UserInfo userInfo, AlarmRule rule)
throws TemplateException, IOException, SQLException {
Map<String, List<AlarmMessage>> warningMap = new HashMap<String, List<AlarmMessage>>();
Set<String> warningMessageKeys = new HashSet<String>();
long currentFireMinuteTime = System.currentTimeMillis() / (1000 * 60);
long warningTimeWindowSize = currentFireMinuteTime
- rule.getPreviousFireTimeM();
// 获取待发送数据
if (warningTimeWindowSize >= rule.getConfigArgsDescriber().getPeriod()) {
for (AlarmType alarmType : alarmTypeList) {
String type = alarmType.getType();
List<AlarmMessage> warningObjects = new ArrayList<AlarmMessage>();
for (ApplicationInfo applicationInfo : rule.getApplicationInfos()) {
for (int period = 0; period < warningTimeWindowSize; period++) {
Long currentMinuteTime = currentFireMinuteTime - period
- 1;
String alarmKey = userInfo.getUserName() + "-"
+ applicationInfo.getAppCode() + "-"
+ currentMinuteTime;
if (!TYPE_OF_EXCEPTION_WARNING.equals(type)) {
alarmKey += "-" + type;
}
warningMessageKeys.add(alarmKey);
setAlarmMessages(alarmKey, warningObjects);
}
}
if (warningObjects.size() > 0) {
warningMap.put(type, warningObjects);
}
}
// 发送告警数据
int warningSize = this.getWarningSize(warningMap);
int exceptionAlarmSize = this.getExceptionSize(warningMap);
if (warningSize > 0) {
if ("0".equals(rule.getTodoType())) {
logger.info(
"A total of {} alarm information needs to be sent {}",
warningSize, rule.getConfigArgsDescriber()
.getMailInfo().getMailTo());
// 发送邮件
String subjects = generateSubject(userInfo.getUserName(),
exceptionAlarmSize, warningSize,
rule.getPreviousFireTimeM(), currentFireMinuteTime);
Map<String, Object> parameter = new HashMap<String, Object>();
parameter.put("alarmTypeList", alarmTypeList);
parameter.put("warningMap", warningMap);
parameter.put("name", userInfo.getUserName());
parameter.put("startDate", new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").format(new Date(rule
.getPreviousFireTimeM() * 10000 * 6)));
parameter.put("endDate", new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").format(new Date(
currentFireMinuteTime * 10000 * 6)));
String mailContext = generateContent(parameter);
if (mailContext.length() > 0) {
MailInfo mailInfo = rule.getConfigArgsDescriber()
.getMailInfo();
MailSender.send(mailInfo.getMailTo(),
mailInfo.getMailCc(), mailContext, subjects);
}
}
}
// 清理数据
for (String toBeRemovedKey : warningMessageKeys) {
expiredAlarmMessage(toBeRemovedKey);
}
// 修改-保存上次处理时间
dealPreviousFireTime(userInfo, rule, currentFireMinuteTime);
}
}
private void dealPreviousFireTime(UserInfo userInfo, AlarmRule rule,
long currentFireMinuteTime) {
rule.setPreviousFireTimeM(currentFireMinuteTime);
savePreviousFireTime(userInfo.getUserId(), rule.getRuleId(),
currentFireMinuteTime);
}
private String generateSubject(String userName, int exceptionAlarmSize,
int count, long startTime, long endTime) {
String title = (exceptionAlarmSize > 0 ? "[Error]" : "[Warning]")
+ " Dear "
+ userName
+ ", SkyWalking collects "
+ (exceptionAlarmSize > 0 ? exceptionAlarmSize
+ " tid of system exceptions, " : "");
if (count > exceptionAlarmSize) {
title += (count - exceptionAlarmSize) + " tid of warnings, ";
}
title += "between "
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(
startTime * 10000 * 6))
+ " to "
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(
endTime * 10000 * 6));
return title;
}
private void expiredAlarmMessage(final String key) {
RedisUtil.execute(new RedisUtil.Executable<Long>() {
@Override
public Long exe(Jedis client) {
return client.expire(key, 0);
}
});
}
private void savePreviousFireTime(final String userId, final String ruleId,
final long currentFireMinuteTime) {
RedisUtil.execute(new RedisUtil.Executable<Long>() {
@Override
public Long exe(Jedis client) {
return client.hset(userId, ruleId,
String.valueOf(currentFireMinuteTime));
}
});
}
private void setAlarmMessages(final String key,
final Collection<AlarmMessage> warningTracingIds) {
RedisUtil.execute(new RedisUtil.Executable<Object>() {
@Override
public Collection<String> exe(Jedis client) {
Map<String, String> result = client.hgetAll(key);
if (result != null) {
for (String traceid : result.keySet()) {
warningTracingIds.add(new AlarmMessage(traceid, result
.get(traceid)));
}
}
return null;
}
});
}
private String generateContent(Map parameter) throws IOException,
TemplateException, SQLException {
if (t == null) {
t = TemplateConfigurationUtil.getConfiguration().getTemplate(
"mail-template.ftl");
}
StringWriter out = new StringWriter();
t.process(parameter, out);
return out.getBuffer().toString();
}
private int getExceptionSize(Map<String, List<AlarmMessage>> warningMap) {
if (warningMap.containsKey(TYPE_OF_EXCEPTION_WARNING)) {
return warningMap.get(TYPE_OF_EXCEPTION_WARNING).size();
}
return 0;
}
private int getWarningSize(Map<String, List<AlarmMessage>> warningMap) {
int result = 0;
for (Entry<String, List<AlarmMessage>> entry : warningMap.entrySet()) {
if (entry.getValue() != null) {
result += entry.getValue().size();
}
}
return result;
}
}
package com.a.eye.skywalking.alarm.util;
import java.util.ArrayList;
import java.util.List;
import com.a.eye.skywalking.alarm.dao.SystemConfigDao;
import com.a.eye.skywalking.alarm.model.AlarmType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.a.eye.skywalking.alarm.conf.Config;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
public class AlarmTypeUtil {
private static Logger logger = LogManager.getLogger(AlarmTypeUtil.class);
private static List<AlarmType> alarmTypeList;
static {
try {
String typeInfo = SystemConfigDao.getSystemConfig(Config.Alarm.ALARM_TYPE_CONFIG_ID);
alarmTypeList = new Gson().fromJson(typeInfo, new TypeToken<ArrayList<AlarmType>>() {
}.getType());
} catch (Exception e) {
logger.error("Failed to load alarm type info.", e);
System.exit(-1);
}
}
public static List<AlarmType> getAlarmTypeList() {
if (alarmTypeList == null || alarmTypeList.isEmpty()) {
alarmTypeList = new ArrayList<AlarmType>();
}
return alarmTypeList;
}
private static Logger logger = LogManager.getLogger(AlarmTypeUtil.class);
private static List<AlarmType> alarmTypeList;
static {
try {
alarmTypeList = new ArrayList<AlarmType>();
alarmTypeList.add(new AlarmType("default", "exception", "System Exception"));
alarmTypeList.add(new AlarmType("ExecuteTime-PossibleError", "remark", "Excution Time > 5s"));
alarmTypeList.add(new AlarmType("ExecuteTime-Warning", "remark", "Excution Time > 500ms"));
} catch (Exception e) {
logger.error("Failed to load alarm type info.", e);
System.exit(-1);
}
}
public static List<AlarmType> getAlarmTypeList() {
if (alarmTypeList == null || alarmTypeList.isEmpty()) {
alarmTypeList = new ArrayList<AlarmType>();
}
return alarmTypeList;
}
}
package com.a.eye.skywalking.alarm.util;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.a.eye.skywalking.alarm.conf.Config;
import com.a.eye.skywalking.alarm.dao.SystemConfigDao;
import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.gson.Gson;
public class MailUtil {
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
private static Logger logger = LogManager.getLogger(MailUtil.class);
public class MailSender {
private static String mailSender;
private static Properties config;
private static Logger logger = LogManager.getLogger(MailSender.class);
private static MailSender sender = new MailSender();
private String mailSender;
private Properties config;
static {
private MailSender() {
try {
String senderInfo = SystemConfigDao.getSystemConfig(Config.MailSenderInfo.configId);
config = new Gson().fromJson(senderInfo, Properties.class);
mailSender = config.getProperty("mail.sender");
config = new Properties();
config.setProperty("mail.transport.protocol", Config.MailSenderInfo.TRANSPORT_PROTOCOL);
config.setProperty("mail.smtp.auth", String.valueOf(Config.MailSenderInfo.SMTP_AUTH));
config.setProperty("mail.smtp.socketFactory.port", "465");
config.setProperty("mail.debug", "true");
//config.setProperty("mail.smtp.ssl.enable", "true");
if (Config.MailSenderInfo.SSL_ENABLE) {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
config.put("mail.smtp.ssl.enable", "true");
config.put("mail.smtp.ssl.socketFactory", sf);
}
} catch (Exception e) {
logger.error("Failed to load mail sender info.", e);
System.exit(-1);
}
mailSender = Config.MailSenderInfo.SENDER;
}
public static void sendMail(String[] recipientAccounts, String[] ccList, String content, String title) {
Session session = Session.getInstance(config);
public static void send(String[] recipientAccounts, String[] ccList, String content, String title) {
Session session = Session.getInstance(sender.config);
Transport ts = null;
try {
ts = session.getTransport();
ts.connect(config.getProperty("mail.host"), config.getProperty("mail.username"), config.getProperty("mail.password"));
ts.connect(Config.MailSenderInfo.MAIL_HOST, Config.MailSenderInfo.USERNAME, Config.MailSenderInfo.PASSWORD);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailSender));
message.setFrom(new InternetAddress(sender.mailSender));
InternetAddress[] recipientAccountArray = new InternetAddress[recipientAccounts.length];
for (int i = 0; i < recipientAccounts.length; i++) {
recipientAccountArray[i] = new InternetAddress(recipientAccounts[i]);
......@@ -59,7 +64,6 @@ public class MailUtil {
}
message.setSubject(title);
message.setContent(content, "text/html;charset=UTF-8");
ts.sendMessage(message, message.getAllRecipients());
} catch (AddressException e) {
......
......@@ -19,7 +19,7 @@ public class TemplateConfigurationUtil {
if (cfg == null) {
cfg = new Configuration(new Version("2.3.23"));
cfg.setDefaultEncoding("UTF-8");
cfg.setSharedVariable("portalAddr", SystemConfigDao.getSystemConfig(Config.TemplateInfo.CONFIG_ID));
cfg.setSharedVariable("portalAddr", Config.TemplateInfo.PORTAL_URL);
//获取资源路径
String classPath = cfg.getClass().getResource("/").getFile().toString();
......
......@@ -9,7 +9,7 @@ server.alarm_rule_activity_interval=3600000
processthread.thread_wait_interval=5000
#zookeeper连接地址
zkpath.connect_str=10.1.241.18:29181,10.1.241.19:29181,10.1.241.20:29181
zkpath.connect_str=127.0.0.1:2181
#zookeeper连接超时时间(单位:毫秒)
zkpath.connect_timeout=1000
#zookeeper重试次数
......@@ -35,11 +35,11 @@ coordinator.check_all_process_thread_interval=500
#数据库驱动类
db.driver_class=com.mysql.jdbc.Driver
#数据库连接地址
db.url=jdbc:mysql://10.1.241.20:31306/sw_db
db.url=jdbc:mysql://localhost:3307/test
#数据库用户名
db.user_name=sw_dbusr01
db.user_name=root
#数据库密码
db.password=sw_dbusr01
db.password=root
#数据库连接最大空闲数
db.max_idle=1
#数据库最大连接数
......@@ -48,7 +48,7 @@ db.max_pool_size=20
db.connect_timeout=10000
#告警信息存在的redis服务器地址
alarm.redis_server=10.1.241.18:16379
alarm.redis_server=127.0.0.1:6379
#redis的最大空闲连接数
alarm.redis_max_idle=20
#redis的最小空闲连接数
......@@ -61,15 +61,21 @@ alarm.alarm_off_flag=false
alarm.checker.turn_on_exception_checker=true
#告警检查器:执行时间超时告警检查
alarm.checker.turn_on_execute_time_checker=true
#告警类型配置id
alarm.alarm_type_config_id=1004
#邮件发送配置id
mailsenderinfo.configid=1000
mailsenderinfo.mail_host=smtp.qq.com
mailsenderinfo.transport_protocol=smtp
mailsenderinfo.smtp_auth=true
mailsenderinfo.smtp_start_ssl_enable=false
mailsenderinfo.username=skywalking
mailsenderinfo.password=skywalking
mailsenderinfo.sender=skywalking@foxmail.com
mailsenderinfo.ssl_enable=true
#邮件模板配置id
templateinfo.config_id=1001
templateinfo.portal_url=http://127.0.0.1:8080/skywalking
#尝试获取轮询锁的周期(单位:毫秒)
inspectthread.retry_get_inspect_lock_interval=10000
#尝试检查用户列表的周期(单位:毫秒)
inspectthread.check_user_list_interval=300000
\ No newline at end of file
inspectthread.check_user_list_interval=300000
......@@ -14,6 +14,7 @@
<module>skywalking-logging</module>
<module>skywalking-registry</module>
<module>skywalking-health-report</module>
<module>skywalking-util</module>
</modules>
<name>skywalking-commons</name>
......
......@@ -27,4 +27,6 @@ public interface ILog {
void debug(String format);
void debug(String format, Object... arguments);
void error(String format);
}
......@@ -65,4 +65,9 @@ public class NoopLogger implements ILog{
public void debug(String format, Object... arguments) {
}
@Override
public void error(String format) {
}
}
......@@ -72,4 +72,9 @@ public class Log4j2Logger implements ILog {
public void debug(String format, Object... arguments) {
logger.debug(format, arguments);
}
@Override
public void error(String format) {
logger.error(format);
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>skywalking-commons</artifactId>
<groupId>com.a.eye</groupId>
<version>2.0-2016</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>skywalking-util</artifactId>
<packaging>jar</packaging>
<name>skywalking-util</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.a.eye</groupId>
<artifactId>skywalking-network</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
package com.a.eye.skywalking.util;
import com.a.eye.skywalking.network.grpc.TraceId;
/**
* Created by xin on 2016/12/8.
*/
public class TraceIdUtil {
public static String formatTraceId(TraceId traceId) {
StringBuilder traceIdBuilder = new StringBuilder();
for (Long segment : traceId.getSegmentsList()) {
traceIdBuilder.append(segment).append(".");
}
return traceIdBuilder.substring(0, traceIdBuilder.length() - 1).toString();
}
}
......@@ -41,18 +41,19 @@ message TraceId {
message Span {
TraceId traceId = 1;
string levelId = 2; // parentLevelId + "." + levelId
string viewpoint = 3;
int64 starttime = 4;
int64 cost = 5;
int32 statusCode = 6;
string exceptionStack = 7;
string spanTypeDesc = 8;
string callType = 9;
int32 spanType = 10;
string applicationCode = 11;
string username = 12;
string businessKey = 13;
int32 processNo = 14;
string address = 15;
string parentLevelId=2;
int32 levelId = 3; // parentLevelId + "." + levelId
string viewpoint = 4;
int64 startTime = 5;
int64 cost = 6;
int32 statusCode = 7;
string exceptionStack = 8;
string spanTypeDesc = 9;
string callType = 10;
int32 spanType = 11;
string applicationCode = 12;
string username = 13;
string businessKey = 14;
int32 processNo = 15;
string address = 16;
}
......@@ -23,5 +23,11 @@
<compiler.version>1.6</compiler.version>
</properties>
<dependencies>
<dependency>
<groupId>com.a.eye</groupId>
<artifactId>skywalking-util</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
......@@ -119,4 +119,9 @@ public class EasyLogger implements com.a.eye.skywalking.logging.api.ILog {
public void debug(String format, Object... arguments) {
logger(DEBUG, replaceParam(format, arguments), null);
}
@Override
public void error(String format) {
logger(ERROR, format, null);
}
}
package com.a.eye.skywalking.plugin;
import com.a.eye.skywalking.util.StringUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
......@@ -7,8 +9,6 @@ import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.a.eye.skywalking.util.StringUtil;
public class PluginCfg {
public final static PluginCfg CFG = new PluginCfg();
......
......@@ -31,6 +31,16 @@
<version>1.17</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.a.eye</groupId>
<artifactId>skywalking-util</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
......
package com.a.eye.skywalking.storage.alarm;
import com.a.eye.skywalking.network.grpc.AckSpan;
import com.a.eye.skywalking.storage.alarm.checker.*;
import com.a.eye.skywalking.storage.alarm.sender.AlarmMessageSenderFactory;
import com.a.eye.skywalking.storage.data.spandata.AckSpanData;
import com.a.eye.skywalking.util.TraceIdUtil;
import com.lmax.disruptor.EventHandler;
import java.util.ArrayList;
......@@ -22,7 +22,7 @@ public class SpanAlarmHandler implements EventHandler<AckSpanData> {
}
private String generateAlarmMessageKey(AckSpanData span, FatalReason reason) {
return span.getUserName() + "-" + span.getApplicationCode() + "-" + (System.currentTimeMillis() / (10000 * 6)) + "-" + reason;
return span.getUserName() + "-" + span.getApplicationCode() + "-" + (System.currentTimeMillis() / (10000 * 6)) + reason.getDetail();
}
@Override
......@@ -30,7 +30,7 @@ public class SpanAlarmHandler implements EventHandler<AckSpanData> {
for (ISpanChecker spanChecker : spanCheckers) {
CheckResult result = spanChecker.check(spanData);
if (!result.isPassed()) {
AlarmMessageSenderFactory.getSender().send(generateAlarmMessageKey(spanData, result.getFatalReason()), result.getMessage());
AlarmMessageSenderFactory.getSender().send(generateAlarmMessageKey(spanData, result.getFatalReason()), TraceIdUtil.formatTraceId(spanData.getTraceId()), result.getMessage());
}
}
}
......
......@@ -4,5 +4,14 @@ package com.a.eye.skywalking.storage.alarm.checker;
* Created by xin on 2016/12/8.
*/
public enum FatalReason {
EXCEPTION_ERROR, EXECUTE_TIME_ERROR, EXECUTE_TIME_WARNING;
EXCEPTION_ERROR(""), EXECUTE_TIME_ERROR("-ExecuteTime-PossibleError"), EXECUTE_TIME_WARNING("-ExecuteTime-Warning");
private String detail;
FatalReason(String detail) {
this.detail = detail;
}
public String getDetail() {
return detail;
}
}
package com.a.eye.skywalking.storage.alarm.sender;
import com.a.eye.skywalking.logging.api.ILog;
import com.a.eye.skywalking.logging.api.LogManager;
import com.a.eye.skywalking.storage.config.Config;
import redis.clients.jedis.Jedis;
/**
* Created by xin on 2016/12/8.
*/
public class AlarmMessageSender {
private ILog logger = LogManager.getLogger(AlarmMessageSender.class);
public void send(String alarmKey, String message) {
public void send(String alarmKey, String traceId, String message) {
Jedis jedis = null;
try {
jedis = AlarmRedisConnector.getJedis();
jedis.hsetnx(alarmKey, traceId, message);
jedis.expire(alarmKey, Config.Alarm.ALARM_EXPIRE_SECONDS);
} catch (Exception e) {
AlarmRedisConnector.reportJedisFailure();
logger.error("Failed to set data.", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
package com.a.eye.skywalking.storage.alarm.sender;
import com.a.eye.skywalking.logging.api.ILog;
import com.a.eye.skywalking.logging.api.LogManager;
import com.a.eye.skywalking.storage.config.Config;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import static com.a.eye.skywalking.health.report.HealthCollector.getCurrentHeathReading;
import static com.a.eye.skywalking.health.report.HeathReading.ERROR;
import static com.a.eye.skywalking.health.report.HeathReading.INFO;
/**
* Created by xin on 2016/12/8.
*/
public class AlarmRedisConnector {
private static JedisPool jedisPool;
static {
new RedisInspector().connect().start();
}
public static Jedis getJedis() {
if (Config.Alarm.ALARM_OFF_FLAG) {
return null;
} else {
return jedisPool.getResource();
}
}
public static void reportJedisFailure() {
RedisInspector.needConnectInit = true;
}
private static class RedisInspector extends Thread {
private static ILog logger = LogManager.getLogger(RedisInspector.class);
private static boolean needConnectInit = true;
private String[] config;
public RedisInspector() {
super("RedisInspectorThread");
String redisServerConfig = Config.Alarm.REDIS_SERVER;
if (redisServerConfig == null || redisServerConfig.length() <= 0) {
logger.error("Redis server is not setting. Switch off alarm module. ");
Config.Alarm.ALARM_OFF_FLAG = true;
} else {
config = redisServerConfig.split(":");
if (config.length != 2) {
logger.error("Redis server address is illegal setting, need to be 'ip:port'. Switch off alarm module. ");
Config.Alarm.ALARM_OFF_FLAG = true;
}
}
this.setDaemon(true);
}
private RedisInspector connect() {
if (jedisPool != null && !jedisPool.isClosed()) {
jedisPool.close();
}
GenericObjectPoolConfig genericObjectPoolConfig = buildGenericObjectPoolConfig();
jedisPool = new JedisPool(genericObjectPoolConfig, config[0],
Integer.valueOf(config[1]));
// Test connect redis.
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.get("ok");
needConnectInit = false;
} catch (Exception e) {
logger.error("can't connect to redis["
+ Config.Alarm.REDIS_SERVER + "]", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return this;
}
@Override
public void run() {
if (Config.Alarm.ALARM_OFF_FLAG)
return;
while (true) {
try {
if (needConnectInit) {
connect();
}
if (needConnectInit) {
getCurrentHeathReading(null).updateData(ERROR, "alarm redis connect failue.");
} else {
getCurrentHeathReading(null).updateData(INFO, "alarm redis connectted.");
}
} catch (Throwable t) {
logger.error("redis init connect failue", t);
}
try {
Thread.sleep(Config.Alarm.ALARM_REDIS_INSPECTOR_INTERVAL);
} catch (InterruptedException e) {
logger.error("Failure sleep.", e);
}
}
}
private GenericObjectPoolConfig buildGenericObjectPoolConfig() {
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setTestOnBorrow(true);
genericObjectPoolConfig.setMaxIdle(Config.Alarm.REDIS_MAX_IDLE);
genericObjectPoolConfig.setMinIdle(Config.Alarm.REDIS_MIN_IDLE);
genericObjectPoolConfig.setMaxTotal(Config.Alarm.REDIS_MAX_TOTAL);
return genericObjectPoolConfig;
}
}
}
......@@ -44,6 +44,21 @@ public class Config {
}
public static class Alarm {
public static String REDIS_SERVER = "127.0.0.1:6379";
public static boolean ALARM_OFF_FLAG = false;
public static int ALARM_EXCEPTION_STACK_LENGTH = 300;
public static long ALARM_REDIS_INSPECTOR_INTERVAL = 100;
public static int REDIS_MAX_IDLE = 10;
public static int REDIS_MIN_IDLE = 1;
public static int REDIS_MAX_TOTAL = 30;
public static int ALARM_EXPIRE_SECONDS = 1000 * 60 * 90;
}
}
......@@ -52,7 +52,7 @@ public class IndexMetaInfo {
}
public String getLevelId() {
return spanData.getLevelId();
return spanData.getTraceLevelId();
}
public SpanType getSpanType() {
......
......@@ -41,7 +41,7 @@ public class AckSpanData extends AbstractSpanData {
}
@Override
public String getLevelId() {
public String getTraceLevelId() {
return buildLevelId(ackSpan.getParentLevel(), ackSpan.getLevelId());
}
......@@ -68,4 +68,8 @@ public class AckSpanData extends AbstractSpanData {
public String getApplicationCode(){
return ackSpan.getApplicationCode();
}
public TraceId getTraceId(){
return ackSpan.getTraceId();
}
}
......@@ -41,10 +41,20 @@ public class RequestSpanData extends AbstractSpanData {
}
@Override
public String getLevelId() {
public String getTraceLevelId() {
return buildLevelId(requestSpan.getParentLevel(), requestSpan.getLevelId());
}
public String getParentLevelId(){
return requestSpan.getParentLevel();
}
public int getLevelId(){
return requestSpan.getLevelId();
}
public String getAddress() {
return requestSpan.getAddress();
}
......@@ -72,4 +82,8 @@ public class RequestSpanData extends AbstractSpanData {
public int getType() {
return requestSpan.getSpanType();
}
public String getViewPoint(){
return requestSpan.getViewPointId();
}
}
......@@ -10,5 +10,5 @@ public interface SpanData {
Long[] getTraceIdSegments();
String getLevelId();
String getTraceLevelId();
}
......@@ -10,7 +10,7 @@ import java.util.*;
*/
public class SpanDataHelper {
public HashMap<String, RequestSpanData> levelIdRequestSpanDataMapping = new HashMap<String, RequestSpanData>();
public HashMap<String, AckSpanData> levelIdAckSpanDataMapping = new HashMap<String, AckSpanData>();
public HashMap<String, AckSpanData> levelIdAckSpanDataMapping = new HashMap<String, AckSpanData>();
private List<SpanData> data;
......@@ -21,9 +21,9 @@ public class SpanDataHelper {
public SpanDataHelper category() {
for (SpanData spanData : data) {
if (spanData instanceof RequestSpanData) {
levelIdRequestSpanDataMapping.put(spanData.getLevelId(), (RequestSpanData) spanData);
levelIdRequestSpanDataMapping.put(spanData.getTraceLevelId(), (RequestSpanData) spanData);
} else {
levelIdAckSpanDataMapping.put(spanData.getLevelId(), (AckSpanData) spanData);
levelIdAckSpanDataMapping.put(spanData.getTraceLevelId(), (AckSpanData) spanData);
}
}
......@@ -50,9 +50,10 @@ public class SpanDataHelper {
builder = builder.setExceptionStack(ackSpanData.getExceptionStack());
}
builder = builder.setLevelId(requestSpanData.getLevelId()).setProcessNo(requestSpanData.getProcessNo())
.setSpanType(requestSpanData.getType()).setStarttime(requestSpanData.getStartTime())
builder = builder.setLevelId(requestSpanData.getLevelId()).setParentLevelId(requestSpanData.getParentLevelId()).setProcessNo(requestSpanData.getProcessNo())
.setSpanType(requestSpanData.getType()).setStartTime(requestSpanData.getStartTime())
.setStatusCode(ackSpanData.getStatusCode())
.setViewpoint(requestSpanData.getViewPoint())
.setTraceId(TraceId.newBuilder().addAllSegments(Arrays.asList(requestSpanData.getTraceIdSegments())));
return builder.build();
}
......
......@@ -49,25 +49,25 @@ public class SpanAlarmHandlerTest {
@Test
public void testNormalSpan() throws Exception {
handler.onEvent(normalAckSpan, 1, false);
verify(messageHandler, never()).send(any(), anyString());
verify(messageHandler, never()).send(any(), any(), anyString());
}
@Test
public void testCostMuchSpan() throws Exception {
handler.onEvent(costMuchSpan, 1, false);
verify(messageHandler, times(1)).send(any(), anyString());
verify(messageHandler, times(1)).send(any(), any(), anyString());
}
@Test
public void testExceptionSpan() throws Exception {
handler.onEvent(exceptionSpan, 1, false);
verify(messageHandler, times(1)).send(any(), anyString());
verify(messageHandler, times(1)).send(any(), any(), anyString());
}
@Test
public void testCostTooMuchSpan() throws Exception {
handler.onEvent(costTooMuchSpan, 1, false);
verify(messageHandler, times(1)).send(any(), anyString());
verify(messageHandler, times(1)).send(any(), any(), anyString());
}
}
......@@ -110,5 +110,11 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.a.eye</groupId>
<artifactId>skywalking-util</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
......@@ -25,7 +25,7 @@ public class SearchClient {
}
public TraceNodesResult searchSpan(String traceId){
String[] traceIdSegments = traceId.split(".");
String[] traceIdSegments = traceId.split("\\.");
TraceNodesResult traceNodesResult = new TraceNodesResult();
if(traceIdSegments.length != 6){
return traceNodesResult;
......
package com.a.eye.skywalking.web.controller;
import com.a.eye.skywalking.util.StringUtil;
import com.a.eye.skywalking.web.common.BaseController;
import com.a.eye.skywalking.web.dao.inter.IAlarmRuleMaintainDao;
import com.a.eye.skywalking.web.dto.AlarmRuleInfo;
import com.a.eye.skywalking.web.dto.ConfigArgs;
import com.a.eye.skywalking.web.dto.LoginUserInfo;
import com.a.eye.skywalking.web.entity.AlarmRule;
import com.a.eye.skywalking.web.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
......@@ -97,7 +97,7 @@ public class AlarmRuleMaintainController extends BaseController {
public String loadAlarmRule(@PathVariable("applicationId") String applicationId, HttpServletRequest request) {
JSONObject jsonObject = new JSONObject();
try {
if (StringUtil.isBlank(applicationId)) {
if (StringUtil.isEmpty(applicationId)) {
jsonObject.put("code", "500");
jsonObject.put("message", "application Id cannot be null");
return jsonObject.toJSONString();
......
package com.a.eye.skywalking.web.controller;
import com.a.eye.skywalking.util.StringUtil;
import com.a.eye.skywalking.web.common.BaseController;
import com.a.eye.skywalking.web.dao.inter.IAlarmRuleMaintainDao;
import com.a.eye.skywalking.web.dao.inter.IApplicationsMaintainDao;
import com.a.eye.skywalking.web.dto.ApplicationInfo;
import com.a.eye.skywalking.web.dto.LoginUserInfo;
import com.a.eye.skywalking.web.util.StringUtil;
import com.a.eye.skywalking.web.entity.AlarmRule;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
......@@ -122,7 +122,7 @@ public class ApplicationConfigController extends BaseController {
public String updateApplication(@PathVariable("applicationId") String applicationId, String appInfo, HttpServletRequest request) {
JSONObject jsonObject = new JSONObject();
try {
if (StringUtil.isBlank(applicationId)) {
if (StringUtil.isEmpty(applicationId)) {
jsonObject.put("code", "500");
jsonObject.put("message", "applicationId cannot be null");
return jsonObject.toJSONString();
......@@ -203,7 +203,7 @@ public class ApplicationConfigController extends BaseController {
public String loadApplication(@PathVariable("applicationId") String applicationId, HttpServletRequest request) {
JSONObject jsonObject = new JSONObject();
try {
if (StringUtil.isBlank(applicationId)) {
if (StringUtil.isEmpty(applicationId)) {
jsonObject.put("code", "500");
jsonObject.put("message", "applicationId cannot be null");
return jsonObject.toJSONString();
......@@ -241,7 +241,7 @@ public class ApplicationConfigController extends BaseController {
public String delApplication(@PathVariable("applicationId") String applicationId, HttpServletRequest request) {
JSONObject jsonObject = new JSONObject();
try {
if (StringUtil.isBlank(applicationId)) {
if (StringUtil.isEmpty(applicationId)) {
jsonObject.put("code", "500");
jsonObject.put("message", "applicationId cannot be null");
return jsonObject.toJSONString();
......
......@@ -3,13 +3,13 @@ package com.a.eye.skywalking.web.controller;
import com.a.eye.skywalking.registry.RegistryCenterFactory;
import com.a.eye.skywalking.registry.api.RegistryCenter;
import com.a.eye.skywalking.registry.impl.zookeeper.ZookeeperConfig;
import com.a.eye.skywalking.util.StringUtil;
import com.a.eye.skywalking.web.client.routing.RoutingServerWatcher;
import com.a.eye.skywalking.web.common.BaseController;
import com.a.eye.skywalking.web.config.Config;
import com.a.eye.skywalking.web.config.ConfigInitializer;
import com.a.eye.skywalking.web.dto.TraceTreeInfo;
import com.a.eye.skywalking.web.service.inter.ITraceTreeService;
import com.a.eye.skywalking.web.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
......@@ -60,7 +60,7 @@ public class SearchController extends BaseController {
public String loadTraceTree(@RequestParam("traceId") String traceId) {
JSONObject jsonObject = new JSONObject();
try {
if (StringUtil.isBlank(traceId)) {
if (StringUtil.isEmpty(traceId)) {
jsonObject.put("code", "400");
jsonObject.put("result", "TraceId cannot be null");
return jsonObject.toJSONString();
......
package com.a.eye.skywalking.web.controller;
import com.a.eye.skywalking.util.StringUtil;
import com.a.eye.skywalking.web.dao.inter.IUserMaintainDao;
import com.a.eye.skywalking.web.dto.LoginUserInfo;
import com.a.eye.skywalking.web.entity.UserInfo;
import com.a.eye.skywalking.web.dto.SignInUserInfo;
import com.a.eye.skywalking.web.common.BaseController;
import com.a.eye.skywalking.web.util.Constants;
import com.a.eye.skywalking.web.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
......@@ -65,7 +65,7 @@ public class UserMaintainController extends BaseController {
}
private boolean validateUserInfo(UserInfo loginInfo, JSONObject result) {
if (StringUtil.isBlank(loginInfo.getUserName()) || StringUtil.isBlank(loginInfo.getPassword())) {
if (StringUtil.isEmpty(loginInfo.getUserName()) || StringUtil.isEmpty(loginInfo.getPassword())) {
result.put("code", "400");
result.put("message", "Username or password is null");
return true;
......@@ -90,7 +90,7 @@ public class UserMaintainController extends BaseController {
signInUserInfo.setRoleType(Constants.USR.ROLE_TYPE_USER);
signInUserInfo.setSts(Constants.USR.STR_VAL_A);
iUserMaintainDao.addUser(signInUserInfo);
if (StringUtil.isBlank(signInUserInfo.getUid())) {
if (StringUtil.isEmpty(signInUserInfo.getUid())) {
result.put("code", "500");
result.put("message", "Failed to register user" + signInUserInfo.getUserName());
return result.toJSONString();
......
package com.a.eye.skywalking.web.dao.impl;
import com.a.eye.skywalking.network.grpc.Span;
import com.a.eye.skywalking.network.grpc.TraceId;
import com.a.eye.skywalking.util.StringUtil;
import com.a.eye.skywalking.web.client.routing.SearchClient;
import com.a.eye.skywalking.web.dao.inter.ITraceNodeDao;
import com.a.eye.skywalking.web.dto.TraceNodeInfo;
import com.a.eye.skywalking.web.dto.TraceNodesResult;
import com.a.eye.skywalking.web.util.Constants;
import com.a.eye.skywalking.web.util.SortUtil;
import com.a.eye.skywalking.web.util.StringUtil;
import org.springframework.stereotype.Repository;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
* Created by xin on 16-3-30.
......@@ -27,23 +24,36 @@ public class TraceNodeDao implements ITraceNodeDao {
public TraceNodesResult queryTraceNodesByTraceId(String traceId)
throws IOException, IllegalAccessException, NoSuchMethodException,
InvocationTargetException {
List<Span> searchResult = new ArrayList<>();
return new SearchClient().searchSpan(traceId);
}
// TODO: 2016/12/10
private Collection<TraceNodeInfo> generateTestData() {
long startTime = System.currentTimeMillis();
TraceId traceId = TraceId.newBuilder()
.addSegments(202016)
.addSegments(startTime)
.addSegments(-1)
.addSegments(1234)
.addSegments(1234)
.addSegments(1234).build();
Span rootSpan = Span.newBuilder().setSpanType(1).setAddress("127.0.0.1/ascrutae").setApplicationCode("test")
.setCallType("S").setCost(200).setLevelId(0).setViewpoint("provider://127.0.0.1:20880/com.a.eye.dubbo.provider.GreetService.sayHello()")
.setProcessNo(19872)
.setTraceId(traceId).setStartTime(startTime)
.setStatusCode(0).setUsername("test").build();
Span span = Span.newBuilder().setSpanType(1).setAddress("127.0.0.1/ascrutae").setApplicationCode("test")
.setCallType("S").setCost(100).setParentLevelId("0").setLevelId(0).setViewpoint("consumer://127.0.0.1:20880/com.a.eye.dubbo.provider.GreetService.sayHello()")
.setProcessNo(19872)
.setTraceId(traceId).setStartTime(startTime + 50)
.setStatusCode(0).setUsername("test").build();
SearchClient client = new SearchClient();
TraceNodesResult result = client.searchSpan(traceId);
Map<String, TraceNodeInfo> traceNodeInfoMap = new HashMap<>();
searchResult.forEach((span -> {
traceNodeInfoMap.put(span.getLevelId(), new TraceNodeInfo(span));
}));
List<TraceNodeInfo> nodeInfos = new ArrayList<>();
nodeInfos.add(new TraceNodeInfo(rootSpan));
nodeInfos.add(new TraceNodeInfo(span));
Map<String, TraceNodeInfo> traceLogMap = new HashMap<String, TraceNodeInfo>();
Map<String, TraceNodeInfo> rpcMap = new HashMap<String, TraceNodeInfo>();
traceNodeInfoMap.entrySet().forEach((entry -> {
SortUtil.addCurNodeTreeMapKey(traceLogMap, entry.getKey(), entry.getValue());
}));
computeRPCInfo(rpcMap, traceLogMap);
result.setResult(traceLogMap.values());
return result;
return nodeInfos;
}
private void computeRPCInfo(Map<String, TraceNodeInfo> rpcMap, Map<String, TraceNodeInfo> traceLogMap) {
......@@ -54,8 +64,8 @@ public class TraceNodeDao implements ITraceNodeDao {
if (traceLogMap.containsKey(colId)) {
TraceNodeInfo logVO = traceLogMap.get(colId);
TraceNodeInfo serverLog = rpcVO.getValue();
if (StringUtil.isBlank(logVO.getStatusCodeStr()) || Constants.STATUS_CODE_9.equals(logVO.getStatusCodeStr())) {
serverLog.setColId(colId);
if (StringUtil.isEmpty(logVO.getStatusCodeStr()) || Constants.STATUS_CODE_9.equals(logVO.getStatusCodeStr())) {
//serverLog.setColId(colId);
traceLogMap.put(colId, serverLog);
} else {
TraceNodeInfo clientLog = traceLogMap.get(colId);
......@@ -63,9 +73,9 @@ public class TraceNodeDao implements ITraceNodeDao {
clientLog.setViewPointId(serverLog.getViewPointId());
clientLog.setViewPointIdSub(serverLog.getViewPointIdSub());
clientLog.setAddress(serverLog.getAddress());
if (StringUtil.isBlank(clientLog.getExceptionStack())) {
if (StringUtil.isEmpty(clientLog.getExceptionStack())) {
clientLog.setExceptionStack(serverLog.getExceptionStack());
}else{
} else {
clientLog.setServerExceptionStr(serverLog.getServerExceptionStr());
}
}
......
......@@ -8,20 +8,21 @@ import com.a.eye.skywalking.network.grpc.Span;
public class FullSpan {
private String parentLevelId;
protected String traceId;
protected String levelId = "";
protected int levelId;
protected String viewPointId;
protected String applicationId;
protected String callType;
protected long cost;
protected long cost;
protected String businessKey;
protected String exceptionStack;
protected byte statusCode = 0;
protected String spanTypeDesc;
protected String username;
protected long startDate;
protected long startDate;
protected String spanType;
protected String address = "";
protected String address = "";
protected String processNo = "";
public FullSpan() {
......@@ -35,12 +36,13 @@ public class FullSpan {
}
this.traceId = traceId.substring(0, traceId.length() - 1);
this.levelId = span.getLevelId();
this.parentLevelId = span.getParentLevelId();
this.applicationId = span.getApplicationCode();
this.callType = span.getCallType();
this.businessKey = span.getBusinessKey();
this.spanTypeDesc = span.getSpanTypeDesc();
this.username = span.getUsername();
this.startDate = span.getStarttime();
this.startDate = span.getStartTime();
this.viewPointId = span.getViewpoint();
this.spanType = span.getSpanType() + "";
this.address = span.getAddress();
......@@ -48,14 +50,14 @@ public class FullSpan {
this.cost = span.getCost();
this.exceptionStack = span.getExceptionStack();
this.statusCode = (byte)span.getStatusCode();
this.statusCode = (byte) span.getStatusCode();
}
public String getTraceId() {
return traceId;
}
public String getLevelId() {
public int getLevelId() {
return levelId;
}
......@@ -119,7 +121,7 @@ public class FullSpan {
return spanType;
}
public void setLevelId(String levelId) {
public void setLevelId(int levelId) {
this.levelId = levelId;
}
......@@ -128,7 +130,7 @@ public class FullSpan {
}
public String getTraceLevelId() {
return getLevelId();
return parentLevelId == null || parentLevelId.length() == 0? levelId + "" : parentLevelId + "." + levelId;
}
public void setViewPointId(String viewPointId) {
......@@ -142,4 +144,8 @@ public class FullSpan {
public String getProcessNo() {
return processNo;
}
public String getParentLevelId() {
return parentLevelId;
}
}
package com.a.eye.skywalking.web.dto;
import com.a.eye.skywalking.network.grpc.Span;
import com.a.eye.skywalking.util.StringUtil;
import com.a.eye.skywalking.web.util.Constants;
import com.a.eye.skywalking.web.util.StringUtil;
import java.util.ArrayList;
import java.util.Iterator;
......@@ -40,17 +40,19 @@ public class TraceNodeInfo extends FullSpan {
private String serverExceptionStr;
private String parentLevel;
public TraceNodeInfo() {
}
public TraceNodeInfo(Span span) {
super(span);
this.colId = this.levelId;
this.colId = getTraceLevelId();
// 处理类型key-value
String spanTypeStr = String.valueOf(span.getSpanTypeDesc());
if (StringUtil.isBlank(spanTypeStr) || Constants.SPAN_TYPE_MAP.containsKey(spanTypeStr)) {
if (StringUtil.isEmpty(spanTypeStr) || Constants.SPAN_TYPE_MAP.containsKey(spanTypeStr)) {
this.spanTypeStr = Constants.SPAN_TYPE_U;
}
this.spanTypeStr = spanTypeStr;
......@@ -63,7 +65,7 @@ public class TraceNodeInfo extends FullSpan {
// 处理状态key-value
String statusCodeStr = String.valueOf(getStatusCode());
if (StringUtil.isBlank(statusCodeStr) || Constants.STATUS_CODE_MAP.containsKey(statusCodeStr)) {
if (StringUtil.isEmpty(statusCodeStr) || Constants.STATUS_CODE_MAP.containsKey(statusCodeStr)) {
this.statusCodeStr = Constants.STATUS_CODE_9;
}
String statusCodeName = Constants.STATUS_CODE_MAP.get(statusCodeStr);
......@@ -71,7 +73,7 @@ public class TraceNodeInfo extends FullSpan {
this.statusCodeName = statusCodeName;
this.applicationIdStr = this.applicationId;
if (!StringUtil.isBlank(this.viewPointId) && this.viewPointId.length() > 60) {
if (!StringUtil.isEmpty(this.viewPointId) && this.viewPointId.length() > 60) {
this.viewPointIdSub = this.viewPointId.substring(0, 30) + "..." + this.viewPointId
.substring(this.viewPointId.length() - 30);
} else {
......@@ -80,6 +82,8 @@ public class TraceNodeInfo extends FullSpan {
this.addTimeLine(this.startDate, this.cost);
this.endDate = this.startDate + this.cost;
this.parentLevel = getParentLevelId();
}
public String getColId() {
......@@ -167,4 +171,8 @@ public class TraceNodeInfo extends FullSpan {
public void setExceptionStack(String exceptionStack) {
this.exceptionStack = exceptionStack;
}
public String getParentLevel() {
return parentLevel;
}
}
......@@ -51,7 +51,7 @@ public class TraceTreeService implements ITraceTreeService {
if (endTime.get(0) < arg1.getEndDate()) {
endTime.set(0, arg1.getEndDate());
}
return SpanLevelIdComparators.ascCompare(arg0.getColId(), arg1.getColId());
return SpanLevelIdComparators.ascCompare(arg0.getTraceLevelId(), arg1.getTraceLevelId());
}
});
......@@ -63,10 +63,6 @@ public class TraceTreeService implements ITraceTreeService {
traceTreeInfo.setHasBeenSpiltNodes(traceNodeInfoList.subList(0, subIndex));
traceTreeInfo.setBeginTime(traceNodeInfoList.get(0).getStartDate());
traceTreeInfo.setEndTime(endTime.get(0));
if (traceNodeInfoList.get(0) != null) {
traceTreeInfo.fillCallChainTreeToken(ReplaceAddressUtil.replace(traceNodeInfoList.get(0).getViewPointId(),
traceNodeInfoList.get(0).getApplicationId()));
}
}
return traceTreeInfo;
......
/**
*
*/
package com.a.eye.skywalking.web.util;
import com.a.eye.skywalking.web.dto.TimeLineEntry;
import com.a.eye.skywalking.web.dto.TraceNodeInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Map;
public class SortUtil {
private static Logger logger = LogManager.getLogger(SortUtil.class);
public static void addCurNodeTreeMapKey(Map<String, TraceNodeInfo> reMap, String colId,
TraceNodeInfo tmpEntry) {
reMap.put(colId, tmpEntry);
// 根据当前Id查找上级,如果不存在,插入空,再看上级,如果不存在还插入空,直到根"0"
while (colId.indexOf(Constants.VAL_SPLIT_CHAR) > -1) {
colId = colId.substring(0, colId.lastIndexOf(Constants.VAL_SPLIT_CHAR));
if (!addParentNodeTreeMapKey(reMap, colId)) {
break;
}
}
}
private static boolean addParentNodeTreeMapKey(Map<String, TraceNodeInfo> reMap, String colId) {
if (reMap.containsKey(colId)) {
return false;
} else {
// 增加虚拟节点
reMap.put(colId, addLostBuriedPointEntry(colId));
// 根据当前Id查找上级,如果不存在,插入空,再看上级,如果不存在还插入空,直到根"0"
while (colId.indexOf(Constants.VAL_SPLIT_CHAR) > -1) {
colId = colId.substring(0, colId.lastIndexOf(Constants.VAL_SPLIT_CHAR));
if (!addParentNodeTreeMapKey(reMap, colId)) {
break;
}
}
return false;
}
}
/***
* 补充丢失的链路信息
*
* @param colId
* @return
*/
public static TraceNodeInfo addLostBuriedPointEntry(String colId) {
TraceNodeInfo result = new TraceNodeInfo();
result.setColId(colId);
result.setLevelId(colId);
result.getTimeLineList().add(new TimeLineEntry());
// 其它默认值
return result;
}
}
package com.a.eye.skywalking.web.util;
public class StringUtil {
public static boolean isBlank(String str) {
if (str == null || str.length() == 0) {
return true;
}
return false;
}
}
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sw_db
jdbc.username=sw_dbusr
jdbc.password=sw_dbusr
jdbc.url=jdbc:mysql://localhost:3307/test
jdbc.username=root
jdbc.password=root
jdbc.maxTotal=200
jdbc.maxIdle=50
jdbc.maxWaitMillis=1000
......
......@@ -96,22 +96,3 @@ CREATE TABLE IF NOT EXISTS `exclude_rule` (
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `system_config`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `system_config` ;
CREATE TABLE IF NOT EXISTS `system_config` (
`config_id` INT UNSIGNED NOT NULL,
`conf_key` VARCHAR(200) NOT NULL,
`conf_value` VARCHAR(500) NOT NULL,
`val_type` VARCHAR(45) NOT NULL,
`val_desc` VARCHAR(200) NULL,
`create_time` DATETIME NULL,
`sts` VARCHAR(2) NOT NULL,
`modify_time` DATETIME NULL,
PRIMARY KEY (`config_id`),
UNIQUE INDEX `conf_key_UNIQUE` (`conf_key` ASC))
ENGINE = InnoDB;
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册