Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[monitor]bugfix: fix only one filter label can be set when notification #140

Merged
merged 1 commit into from
May 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.usthe.common.entity.alerter;

import com.google.gson.reflect.TypeToken;
import com.usthe.common.util.GsonUtil;

import javax.persistence.AttributeConverter;
import java.lang.reflect.Type;
import java.util.Map;

/**
Expand All @@ -19,6 +21,7 @@ public String convertToDatabaseColumn(Map<String, String> attribute) {

@Override
public Map<String, String> convertToEntityAttribute(String dbData) {
return GsonUtil.fromJson(dbData, Map.class);
Type type = new TypeToken<Map<String, String>>(){}.getType();
return GsonUtil.fromJson(dbData, type);
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package com.usthe.common.entity.manager;

import com.google.gson.reflect.TypeToken;
import com.usthe.common.util.GsonUtil;

import javax.persistence.AttributeConverter;
import java.util.LinkedList;
import java.lang.reflect.Type;
import java.util.List;

/**
Expand All @@ -20,14 +21,7 @@ public String convertToDatabaseColumn(List<Byte> attribute) {

@Override
public List<Byte> convertToEntityAttribute(String dbData) {
List list = GsonUtil.fromJson(dbData, List.class);
List<Byte> bytes = new LinkedList<>();
if (list != null) {
for (Object item : list) {
byte value = Double.valueOf(String.valueOf(item)).byteValue();
bytes.add(value);
}
}
return bytes;
Type type = new TypeToken<List<Byte>>(){}.getType();
return GsonUtil.fromJson(dbData, type);
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.usthe.common.entity.manager;

import com.google.gson.reflect.TypeToken;
import com.usthe.common.util.GsonUtil;

import javax.persistence.AttributeConverter;
import java.lang.reflect.Type;
import java.util.List;

/**
Expand All @@ -19,6 +21,7 @@ public String convertToDatabaseColumn(List<ParamDefine.Option> attribute) {

@Override
public List<ParamDefine.Option> convertToEntityAttribute(String dbData) {
return GsonUtil.fromJson(dbData, List.class);
Type type = new TypeToken<List<ParamDefine.Option>>(){}.getType();
return GsonUtil.fromJson(dbData, type);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.usthe.common.entity.manager;

import com.google.gson.reflect.TypeToken;
import com.usthe.common.util.GsonUtil;

import javax.persistence.AttributeConverter;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* json 互转 tag list 对象字段为数据String字段
* @author tom
* @date 2021/12/4 07:54
*/
public class JsonTagListAttributeConverter implements AttributeConverter<List<NoticeRule.TagItem>, String> {

@Override
public String convertToDatabaseColumn(List<NoticeRule.TagItem> attribute) {
return GsonUtil.toJson(attribute);
}

@Override
public List<NoticeRule.TagItem> convertToEntityAttribute(String dbData) {
try {
Type type = new TypeToken<List<NoticeRule.TagItem>>(){}.getType();
return GsonUtil.fromJson(dbData, type);
} catch (Exception e) {
// history data handler
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = GsonUtil.fromJson(dbData, type);
return map.entrySet().stream().map(entry -> new NoticeRule.TagItem(entry.getKey(), entry.getValue())).collect(Collectors.toList());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.usthe.common.entity.manager;

import com.usthe.common.entity.alerter.JsonMapAttributeConverter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
Expand All @@ -10,10 +9,10 @@
import org.hibernate.validator.constraints.Length;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import static io.swagger.annotations.ApiModelProperty.AccessMode.READ_ONLY;
import static io.swagger.annotations.ApiModelProperty.AccessMode.READ_WRITE;
Expand Down Expand Up @@ -75,10 +74,9 @@ public class NoticeRule {
@Convert(converter = JsonByteListAttributeConverter.class)
private List<Byte> priorities;

@ApiModelProperty(value = "告警信息标签(monitorId:xxx,monitorName:xxx)", example = "{key1:value1}", accessMode = READ_WRITE, position = 8)
@Convert(converter = JsonMapAttributeConverter.class)
@SuppressWarnings("JpaAttributeTypeInspection")
private Map<String, String> tags;
@ApiModelProperty(value = "告警信息标签(monitorId:xxx,monitorName:xxx)", example = "{name: key1, value: value1}", accessMode = READ_WRITE, position = 8)
@Convert(converter = JsonTagListAttributeConverter.class)
private List<TagItem> tags;

@ApiModelProperty(value = "The creator of this record",
notes = "此条记录创建者",
Expand All @@ -102,4 +100,17 @@ public class NoticeRule {
@Column(insertable = false, updatable = false)
private LocalDateTime gmtUpdate;


@AllArgsConstructor
@NoArgsConstructor
@Data
public static class TagItem {

@ApiModelProperty(value = "Tag Name")
@NotBlank
private String name;

@ApiModelProperty(value = "Tag Value")
private String value;
}
}
5 changes: 5 additions & 0 deletions common/src/main/java/com/usthe/common/util/GsonUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import io.etcd.jetcd.ByteSequence;

import javax.annotation.concurrent.ThreadSafe;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

/**
Expand All @@ -31,6 +32,10 @@ public static <T> T fromJson(String jsonStr, Class<T> clazz) {
return gson.fromJson(jsonStr, clazz);
}

public static <T> T fromJson(String jsonStr, Type typeOfT) {
return gson.fromJson(jsonStr, typeOfT);
}

public static <T> T fromJson(ByteSequence byteSequence, Class<T> clazz) {
if (byteSequence == null || byteSequence.isEmpty()) {
return null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.usthe.manager.service.impl;

import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.usthe.common.entity.alerter.Alert;
import com.usthe.common.util.CommonConstants;
import com.usthe.manager.component.alerter.DispatcherAlarm;
Expand All @@ -18,7 +16,7 @@
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -92,29 +90,35 @@ public List<NoticeReceiver> getReceiverFilterRule(Alert alert) {
// todo use cache 使用缓存
List<NoticeRule> rules = noticeRuleDao.findNoticeRulesByEnableTrue();

// todo The temporary rule is to forward all, and then implement more matching rules: alarm status selection, monitoring type selection, etc.
// 暂时规则是全部转发 后面实现更多匹配规则:告警状态选择 监控类型选择等
Set<Long> receiverIds = rules.stream()
.filter(NoticeRule::isFilterAll)
.map(NoticeRule::getReceiverId)
.collect(Collectors.toSet());
// 除了全部转发的 其他的按照tags标签和告警级别过滤匹配
Set<Long> receiverIdsByMatch = rules.stream()
.filter(rule -> !rule.isFilterAll())
// The temporary rule is to forward all, and then implement more matching rules: alarm status selection, monitoring type selection, etc.
// 规则是全部转发, 告警状态选择, 监控类型选择等(按照tags标签和告警级别过滤匹配)
Set<Long> filterReceivers = rules.stream()
.filter(rule -> {
MapDifference<String, Object> difference = Maps.difference(alert.getTags(), rule.getTags() == null ? Maps.newHashMap() : rule.getTags());
Map<String, Object> difMap= difference.entriesInCommon();
if (rule.getPriorities() == null || rule.getPriorities().isEmpty()) {
return !difMap.isEmpty();
} else {
if (rule.isFilterAll()) {
return true;
}
// filter priorities
if (rule.getPriorities() != null && !rule.getPriorities().isEmpty()) {
boolean priorityMatch = rule.getPriorities().stream().anyMatch(item -> item != null && item == alert.getPriority());
return priorityMatch && !difMap.isEmpty();
if (!priorityMatch) {
return false;
}
}
}).map(NoticeRule::getReceiverId)
// filter tags
if (rule.getTags() != null && !rule.getTags().isEmpty()) {
return rule.getTags().stream().anyMatch(tagItem -> {
if (!alert.getTags().containsKey(tagItem.getName())) {
return false;
}
String alertTagValue = alert.getTags().get(tagItem.getName());
return Objects.equals(tagItem.getValue(), alertTagValue);
});
}
return true;
})
.map(NoticeRule::getReceiverId)
.collect(Collectors.toSet());

receiverIds.addAll(receiverIdsByMatch);
return noticeReceiverDao.findAllById(receiverIds);
return noticeReceiverDao.findAllById(filterReceivers);
}

@Override
Expand Down
4 changes: 2 additions & 2 deletions web-app/src/app/layout/basic/basic.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ import { CONSTS } from 'src/app/shared/consts';
</layout-default>
<global-footer style="border-top: 1px solid #e5e5e5; min-height: 120px; text-shadow: 0 1px 0 #fff;margin:0;">
<div style="margin-top: 30px">
HertzBeat {{ version }}<br />
HertzBeat {{ version }}<br />
Copyright
<i nz-icon nzType="copyright"></i> 2022
<i nz-icon nzType="copyright"></i> 2022
<a href="https://hertzbeat.com" target="_blank">https://www.hertzbeat.com</a>
<br />
Licensed under the Apache License, Version 2.0
Expand Down
10 changes: 5 additions & 5 deletions web-app/src/app/layout/passport/passport.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
<global-footer [links]="links">
<div style="margin-top: 0px">
HertzBeat {{ version }}<br />
Copyright
<i nz-icon nzType="copyright" nzTheme="outline"></i>
2022
<a href="https://hertzbeat.com" target="_blank">https://www.hertzbeat.com</a>
<br />
Copyright
<i nz-icon nzType="copyright" nzTheme="outline"></i>
2022
<a href="https://hertzbeat.com" target="_blank">https://www.hertzbeat.com</a>
<br />
Licensed under the Apache License, Version 2.0
</div>
</global-footer>
Expand Down
7 changes: 6 additions & 1 deletion web-app/src/app/pojo/NoticeRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ export class NoticeRule {
filterAll: boolean = true;
// 告警级别过滤
priorities!: number[];
tags!: Record<string, string>;
tags!: TagItem[];
creator!: string;
modifier!: string;
gmtCreate!: number;
gmtUpdate!: number;
}

export class TagItem {
name!: string;
value!: string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { NzNotificationService } from 'ng-zorro-antd/notification';
import { finalize } from 'rxjs/operators';

import { NoticeReceiver } from '../../../pojo/NoticeReceiver';
import { NoticeRule } from '../../../pojo/NoticeRule';
import { NoticeRule, TagItem } from '../../../pojo/NoticeRule';
import { NoticeReceiverService } from '../../../service/notice-receiver.service';
import { NoticeRuleService } from '../../../service/notice-rule.service';
import { TagService } from '../../../service/tag.service';
Expand Down Expand Up @@ -275,8 +275,11 @@ export class AlertNoticeComponent implements OnInit {
});
this.filterTags = [];
if (rule.tags != undefined) {
Object.keys(rule.tags).forEach(name => {
let tag = `${name}:${rule.tags[name]}`;
rule.tags.forEach(item => {
let tag = `${item.name}`;
if (item.value != undefined) {
tag = `${tag}:${item.value}`;
}
this.filterTags.push(tag);
this.tagsOption.push({
value: tag,
Expand Down Expand Up @@ -344,9 +347,13 @@ export class AlertNoticeComponent implements OnInit {
this.tagsOption = [];
if (page.content != undefined) {
page.content.forEach(item => {
let tag = `${item.name}`;
if (item.value != undefined) {
tag = `${tag}:${item.value}`;
}
this.tagsOption.push({
value: `${item.name}:${item.value}`,
label: `${item.name}:${item.value}`
value: tag,
label: tag
});
});
}
Expand Down Expand Up @@ -386,11 +393,17 @@ export class AlertNoticeComponent implements OnInit {
this.rule.receiverName = option.label;
}
});
this.rule.tags = {};
this.rule.tags = [];
this.filterTags.forEach(tag => {
let tmp: string[] = tag.split(':');
if (tmp.length == 2) {
this.rule.tags[tmp[0]] = tmp[1];
let tagItem = new TagItem();
if (tmp.length == 1) {
tagItem.name = tmp[0];
this.rule.tags.push(tagItem);
} else if (tmp.length == 2) {
tagItem.name = tmp[0];
tagItem.value = tmp[1];
this.rule.tags.push(tagItem);
}
});
if (this.rule.priorities != undefined) {
Expand Down