Skip to content
Open
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
Expand Up @@ -17,24 +17,40 @@

package org.apache.hertzbeat.alert.util;

import java.util.Arrays;
import java.util.List;
import java.util.Comparator;
import java.util.Map;
import java.util.Objects;

/**
* alert util
*/
public class AlertUtil {

/**
* calculate fingerprint
* @param fingerPrints finger prints
* Calculate an in-memory alert cache coordinate.
*
* <p>This value is rebuilt from persisted alert labels when the process
* starts. It is not the durable {@code SingleAlert.fingerprint} used by
* persistence, grouping, silence, or inhibition.</p>
*
* @param fingerPrints labels used by the calculator cache
* @return deterministic cache coordinate
*/
public static String calculateFingerprint(Map<String, String> fingerPrints) {
List<String> keyList = fingerPrints.keySet().stream().filter(Objects::nonNull).sorted().toList();
List<String> valueList = fingerPrints.values().stream().filter(Objects::nonNull).sorted().toList();
return Arrays.hashCode(keyList.toArray(new String[0])) + "-"
+ Arrays.hashCode(valueList.toArray(new String[0]));
StringBuilder canonicalLabels = new StringBuilder();
fingerPrints.entrySet().stream()
.sorted(Map.Entry.comparingByKey(Comparator.nullsFirst(Comparator.naturalOrder())))
.forEach(entry -> {
appendLengthPrefixed(canonicalLabels, entry.getKey());
appendLengthPrefixed(canonicalLabels, entry.getValue());
});
return CryptoUtils.sha256Hex(canonicalLabels.toString());
}

private static void appendLengthPrefixed(StringBuilder target, String value) {
if (value == null) {
target.append("-1:");
return;
}
target.append(value.length()).append(':').append(value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.when;

/**
Expand Down Expand Up @@ -132,4 +133,28 @@ void testHistorical() {
historicalSingleAlert = alarmCacheManager.getFiring(4L, fingerprint);
assertNull(historicalSingleAlert);
}
}

@Test
void restartShouldRebuildCacheKeyWithoutChangingPersistedFingerprint() {
Map<String, String> labels = Map.of(
CommonConstants.LABEL_DEFINE_ID, "7",
CommonConstants.LABEL_ALERT_NAME, "disk_full",
"instance", "db-1");
SingleAlert persistedAlert = SingleAlert.builder()
.id(99L)
.fingerprint("alertname:disk_full,define_id:7,instance:db-1")
.labels(labels)
.status(CommonConstants.ALERT_STATUS_FIRING)
.build();
when(singleAlertDao.querySingleAlertsByStatus(CommonConstants.ALERT_STATUS_FIRING))
.thenReturn(Collections.singletonList(persistedAlert));

alarmCacheManager = new AlarmCacheManager(singleAlertDao);
String rebuiltCacheKey = AlertUtil.calculateFingerprint(labels);
SingleAlert resolved = alarmCacheManager.removeFiring(7L, rebuiltCacheKey);

assertSame(persistedAlert, resolved);
assertEquals("alertname:disk_full,define_id:7,instance:db-1", resolved.getFingerprint());
assertNull(alarmCacheManager.getFiring(7L, rebuiltCacheKey));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.apache.hertzbeat.alert.reduce;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
Expand All @@ -28,6 +29,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.hertzbeat.common.entity.alerter.SingleAlert;
import org.apache.hertzbeat.common.config.VirtualThreadProperties;
import org.junit.jupiter.api.AfterEach;
Expand Down Expand Up @@ -85,6 +87,28 @@ void testReduceAndSendAlarmRunsOnVirtualThread() throws Exception {
assertTrue(virtualThread.get());
}

@Test
void durableFingerprintShouldRemainIndependentFromCalculatorCacheKey() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<String> durableFingerprint = new AtomicReference<>();
doAnswer(invocation -> {
durableFingerprint.set(invocation.getArgument(0, SingleAlert.class).getFingerprint());
latch.countDown();
return null;
}).when(alarmGroupReduce).processGroupAlert(any(SingleAlert.class));
SingleAlert alert = SingleAlert.builder()
.labels(new HashMap<>(Map.of(
"instance", "db-1",
"alertname", "disk_full",
"timestamp", "not-part-of-identity")))
.build();

alarmCommonReduce.reduceAndSendAlarm(alert);

assertTrue(latch.await(5, TimeUnit.SECONDS));
assertEquals("alertname:disk_full,instance:db-1", durableFingerprint.get());
}

@Test
void testReduceAndSendAlarmQueuesWhenConcurrencyLimitReached() throws Exception {
VirtualThreadProperties properties = new VirtualThreadProperties(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.hertzbeat.alert.util;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;

/**
* Test case for {@link AlertUtil}.
*/
class AlertUtilTest {

@Test
void calculateFingerprintPreservesLabelPairing() {
Map<String, String> first = new LinkedHashMap<>();
first.put("environment", "production");
first.put("team", "payments");

Map<String, String> swapped = new LinkedHashMap<>();
swapped.put("environment", "payments");
swapped.put("team", "production");

assertNotEquals(
AlertUtil.calculateFingerprint(first),
AlertUtil.calculateFingerprint(swapped));
}

@Test
void calculateFingerprintIsIndependentOfMapIterationOrder() {
Map<String, String> first = new LinkedHashMap<>();
first.put("environment", "production");
first.put("team", "payments");

Map<String, String> reversed = new LinkedHashMap<>();
reversed.put("team", "payments");
reversed.put("environment", "production");

assertEquals(
AlertUtil.calculateFingerprint(first),
AlertUtil.calculateFingerprint(reversed));
}
}
Loading