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

[improve] refactor code #1901

Merged
merged 6 commits into from
May 4, 2024
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
Expand Up @@ -44,7 +44,4 @@ public class CollectorInfo {

@NotNull
private String mode = CommonConstants.MODE_PUBLIC;

// todo more

}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public class Job {
*/
private boolean hide = true;
/**
* Large categories of monitoring
* Large categories of monitoring
* service-application service monitoring db-database
* monitoring custom-custom monitoring os-operating system monitoring...
*/
Expand Down Expand Up @@ -126,7 +126,7 @@ public class Job {
*/
@JsonIgnore
private transient long dispatchTime;

/**
* collector usage - metric group task execution priority view
* 0 - availability
Expand Down Expand Up @@ -183,8 +183,8 @@ public synchronized void constructPriorMetrics() {
* collector use - to get the next set of priority metric group tasks
*
* @param metrics Current Metrics
* @param first Is it the first time to get
* @return Metrics Tasks
* @param first Is it the first time to get
* @return Metrics Tasks
* Returning null means: the job has been completed, and the collection of all metrics has ended
* Returning the empty set metrics that there are still metrics collection tasks at the current
* level that have not been completed,and the next level metrics task collection cannot be performed.
Expand Down Expand Up @@ -238,7 +238,7 @@ public void addEnvConfigmaps(Map<String, Configmap> envConfigmaps) {
if (this.envConfigmaps == null) {
this.envConfigmaps = envConfigmaps;
} else {
this.envConfigmaps.putAll(envConfigmaps);
this.envConfigmaps.putAll(envConfigmaps);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ public class CollectorJobScheduler implements CollectorScheduling, CollectJobSch

@Override
public void collectorGoOnline(String identity, CollectorInfo collectorInfo) {
if (identity == null) {
log.error("identity can not be null if collector not existed");
return;
}
Optional<Collector> collectorOptional = collectorDao.findCollectorByName(identity);
Collector collector;
if (collectorOptional.isPresent()) {
Expand All @@ -109,9 +113,12 @@ public void collectorGoOnline(String identity, CollectorInfo collectorInfo) {
log.error("collectorInfo can not null when collector not existed");
return;
}
collector = Collector.builder().name(identity).ip(collectorInfo.getIp())
collector = Collector.builder()
.name(identity)
.ip(collectorInfo.getIp())
.mode(collectorInfo.getMode())
.status(CommonConstants.COLLECTOR_STATUS_ONLINE).build();
.status(CommonConstants.COLLECTOR_STATUS_ONLINE)
.build();
}
collectorDao.save(collector);
ConsistentHash.Node node = new ConsistentHash.Node(identity, collector.getMode(),
Expand All @@ -122,114 +129,104 @@ public void collectorGoOnline(String identity, CollectorInfo collectorInfo) {
List<CollectorMonitorBind> binds = collectorMonitorBindDao.findCollectorMonitorBindsByCollector(identity);
for (CollectorMonitorBind bind : binds) {
Optional<Monitor> monitorOptional = monitorDao.findById(bind.getMonitorId());
if (monitorOptional.isPresent()) {
Monitor monitor = monitorOptional.get();
if (monitor.getStatus() == CommonConstants.UN_MANAGE_CODE) {
continue;
if (monitorOptional.isEmpty()) {
continue;
}
Monitor monitor = monitorOptional.get();
if (monitor.getStatus() == CommonConstants.UN_MANAGE_CODE) {
continue;
}
try {
// build collect job entity
Job appDefine = appService.getAppDefine(monitor.getApp());
if (CommonConstants.PROMETHEUS.equals(monitor.getApp())) {
appDefine.setApp(CommonConstants.PROMETHEUS_APP_PREFIX + monitor.getName());
}
try {
// build collect job entity
Job appDefine = appService.getAppDefine(monitor.getApp());
if (CommonConstants.PROMETHEUS.equals(monitor.getApp())) {
appDefine.setApp(CommonConstants.PROMETHEUS_APP_PREFIX + monitor.getName());
appDefine.setMonitorId(monitor.getId());
appDefine.setInterval(monitor.getIntervals());
appDefine.setCyclic(true);
appDefine.setTimestamp(System.currentTimeMillis());
List<Param> params = paramDao.findParamsByMonitorId(monitor.getId());
List<Configmap> configmaps = params.stream()
.map(param -> new Configmap(param.getField(), param.getParamValue(),
param.getType())).collect(Collectors.toList());
List<ParamDefine> paramDefaultValue = appDefine.getParams().stream()
.filter(item -> StringUtils.hasText(item.getDefaultValue()))
.toList();
paramDefaultValue.forEach(defaultVar -> {
if (configmaps.stream().noneMatch(item -> item.getKey().equals(defaultVar.getField()))) {
Configmap configmap = new Configmap(defaultVar.getField(), defaultVar.getDefaultValue(), (byte) 1);
configmaps.add(configmap);
}
appDefine.setMonitorId(monitor.getId());
appDefine.setInterval(monitor.getIntervals());
appDefine.setCyclic(true);
appDefine.setTimestamp(System.currentTimeMillis());
List<Param> params = paramDao.findParamsByMonitorId(monitor.getId());
List<Configmap> configmaps = params.stream()
.map(param -> new Configmap(param.getField(), param.getParamValue(),
param.getType())).collect(Collectors.toList());
List<ParamDefine> paramDefaultValue = appDefine.getParams().stream()
.filter(item -> StringUtils.hasText(item.getDefaultValue()))
.collect(Collectors.toList());
paramDefaultValue.forEach(defaultVar -> {
if (configmaps.stream().noneMatch(item -> item.getKey().equals(defaultVar.getField()))) {
// todo type
Configmap configmap = new Configmap(defaultVar.getField(), defaultVar.getDefaultValue(), (byte) 1);
configmaps.add(configmap);
}
});
appDefine.setConfigmap(configmaps);
long jobId = addAsyncCollectJob(appDefine, identity);
monitor.setJobId(jobId);
monitorDao.save(monitor);
} catch (Exception e) {
log.error("insert pinned monitor job: {} in collector: {} error,continue next monitor", monitor, identity, e);
}
});
appDefine.setConfigmap(configmaps);
long jobId = addAsyncCollectJob(appDefine, identity);
monitor.setJobId(jobId);
monitorDao.save(monitor);
} catch (Exception e) {
log.error("insert pinned monitor job: {} in collector: {} error,continue next monitor", monitor, identity, e);
}
}
}

@Override
public void collectorGoOffline(String identity) {
Optional<Collector> collectorOptional = collectorDao.findCollectorByName(identity);
if (collectorOptional.isPresent()) {
log.info("the collector: {} is going offline now.", identity);
Collector collector = collectorOptional.get();
collector.setStatus(CommonConstants.COLLECTOR_STATUS_OFFLINE);
collectorDao.save(collector);
consistentHash.removeNode(identity);
reBalanceCollectorAssignJobs();
if (collectorOptional.isEmpty()) {
log.info("the collector : {} not found.", identity);
return;
}
Collector collector = collectorOptional.get();
collector.setStatus(CommonConstants.COLLECTOR_STATUS_OFFLINE);
collectorDao.save(collector);
consistentHash.removeNode(identity);
reBalanceCollectorAssignJobs();
log.info("the collector: {} go offline success.", identity);
}

@Override
public void reBalanceCollectorAssignJobs() {
consistentHash.getAllNodes().entrySet().parallelStream().forEach(entry -> {
String collectorName = entry.getKey();
AssignJobs assignJobs = entry.getValue().getAssignJobs();
if (assignJobs != null) {
if (CommonConstants.MAIN_COLLECTOR_NODE.equals(collectorName)) {
if (!assignJobs.getAddingJobs().isEmpty()) {
Set<Long> addedJobIds = new HashSet<>(8);
for (Long addingJobId : assignJobs.getAddingJobs()) {
Job job = jobContentCache.get(addingJobId);
if (job == null) {
log.error("assigning job {} content is null.", addingJobId);
continue;
}
addedJobIds.add(addingJobId);
collectJobService.addAsyncCollectJob(job);
}
assignJobs.addAssignJobs(addedJobIds);
assignJobs.removeAddingJobs(addedJobIds);
}
if (!assignJobs.getRemovingJobs().isEmpty()) {
assignJobs.getRemovingJobs().forEach(jobId -> collectJobService.cancelAsyncCollectJob(jobId));
assignJobs.clearRemovingJobs();
}
} else {
if (!assignJobs.getAddingJobs().isEmpty()) {
Set<Long> addedJobIds = new HashSet<>(8);
for (Long addingJobId : assignJobs.getAddingJobs()) {
Job job = jobContentCache.get(addingJobId);
if (job == null) {
log.error("assigning job {} content is null.", addingJobId);
continue;
}
addedJobIds.add(addingJobId);
ClusterMsg.Message message = ClusterMsg.Message.newBuilder()
.setDirection(ClusterMsg.Direction.REQUEST)
.setType(ClusterMsg.MessageType.ISSUE_CYCLIC_TASK)
.setMsg(JsonUtil.toJson(job))
.build();
this.manageServer.sendMsg(collectorName, message);
}
assignJobs.addAssignJobs(addedJobIds);
assignJobs.removeAddingJobs(addedJobIds);
if (collectorName == null || assignJobs == null) {
return;
}
if (assignJobs.getAddingJobs() != null && !assignJobs.getAddingJobs().isEmpty()) {
Set<Long> addedJobIds = new HashSet<>(8);
for (Long addingJobId : assignJobs.getAddingJobs()) {
Job job = jobContentCache.get(addingJobId);
if (job == null) {
log.error("assigning job {} content is null.", addingJobId);
continue;
}
if (!assignJobs.getRemovingJobs().isEmpty()) {
addedJobIds.add(addingJobId);
if (CommonConstants.MAIN_COLLECTOR_NODE.equals(collectorName)) {
collectJobService.addAsyncCollectJob(job);
} else {
ClusterMsg.Message message = ClusterMsg.Message.newBuilder()
.setDirection(ClusterMsg.Direction.REQUEST)
.setType(ClusterMsg.MessageType.DELETE_CYCLIC_TASK)
.setMsg(JsonUtil.toJson(assignJobs.getRemovingJobs()))
.setType(ClusterMsg.MessageType.ISSUE_CYCLIC_TASK)
.setMsg(JsonUtil.toJson(job))
.build();
this.manageServer.sendMsg(collectorName, message);
assignJobs.clearRemovingJobs();
}
}
assignJobs.addAssignJobs(addedJobIds);
assignJobs.removeAddingJobs(addedJobIds);
}
if (assignJobs.getRemovingJobs() != null && !assignJobs.getRemovingJobs().isEmpty()) {
if (CommonConstants.MAIN_COLLECTOR_NODE.equals(collectorName)) {
assignJobs.getRemovingJobs().forEach(jobId -> collectJobService.cancelAsyncCollectJob(jobId));
} else {
ClusterMsg.Message message = ClusterMsg.Message.newBuilder()
.setDirection(ClusterMsg.Direction.REQUEST)
.setType(ClusterMsg.MessageType.DELETE_CYCLIC_TASK)
.setMsg(JsonUtil.toJson(assignJobs.getRemovingJobs()))
.build();
this.manageServer.sendMsg(collectorName, message);
}
assignJobs.clearRemovingJobs();
}
});
}
Expand Down Expand Up @@ -461,5 +458,4 @@ public void collectSyncJobResponse(List<CollectRep.MetricsData> metricsDataList)
public void setManageServer(ManageServer manageServer) {
this.manageServer = manageServer;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@
import org.apache.hertzbeat.common.support.SpringContextHolder;
import org.apache.hertzbeat.warehouse.WarehouseWorkerPool;
import org.apache.hertzbeat.warehouse.controller.MetricsDataController;
import org.apache.hertzbeat.warehouse.store.HistoryIotDbDataStorage;
import org.apache.hertzbeat.warehouse.store.HistoryTdEngineDataStorage;
import org.apache.hertzbeat.warehouse.store.RealTimeMemoryDataStorage;
import org.apache.hertzbeat.warehouse.store.RealTimeRedisDataStorage;
import org.apache.hertzbeat.warehouse.store.history.iotdb.IotDbDataStorage;
import org.apache.hertzbeat.warehouse.store.history.tdengine.TdEngineDataStorage;
import org.apache.hertzbeat.warehouse.store.realtime.memory.MemoryDataStorage;
import org.apache.hertzbeat.warehouse.store.realtime.redis.RedisDataStorage;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
Expand Down Expand Up @@ -99,10 +99,10 @@ void testAutoImport() {
assertNotNull(ctx.getBean(WarehouseWorkerPool.class));

// default DataStorage is RealTimeMemoryDataStorage
assertNotNull(ctx.getBean(RealTimeMemoryDataStorage.class));
assertThrows(NoSuchBeanDefinitionException.class, () -> ctx.getBean(RealTimeRedisDataStorage.class));
assertThrows(NoSuchBeanDefinitionException.class, () -> ctx.getBean(HistoryTdEngineDataStorage.class));
assertThrows(NoSuchBeanDefinitionException.class, () -> ctx.getBean(HistoryIotDbDataStorage.class));
assertNotNull(ctx.getBean(MemoryDataStorage.class));
assertThrows(NoSuchBeanDefinitionException.class, () -> ctx.getBean(RedisDataStorage.class));
assertThrows(NoSuchBeanDefinitionException.class, () -> ctx.getBean(TdEngineDataStorage.class));
assertThrows(NoSuchBeanDefinitionException.class, () -> ctx.getBean(IotDbDataStorage.class));

assertNotNull(ctx.getBean(MetricsDataController.class));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

package org.apache.hertzbeat.warehouse.config;
package org.apache.hertzbeat.warehouse;

import org.springframework.context.annotation.ComponentScan;

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@
import org.apache.hertzbeat.common.entity.dto.Value;
import org.apache.hertzbeat.common.entity.dto.ValueRow;
import org.apache.hertzbeat.common.entity.message.CollectRep;
import org.apache.hertzbeat.warehouse.store.AbstractHistoryDataStorage;
import org.apache.hertzbeat.warehouse.store.AbstractRealTimeDataStorage;
import org.apache.hertzbeat.warehouse.store.HistoryJpaDatabaseDataStorage;
import org.apache.hertzbeat.warehouse.store.RealTimeMemoryDataStorage;
import org.apache.hertzbeat.warehouse.store.history.AbstractHistoryDataStorage;
import org.apache.hertzbeat.warehouse.store.history.jpa.JpaDatabaseDataStorage;
import org.apache.hertzbeat.warehouse.store.realtime.AbstractRealTimeDataStorage;
import org.apache.hertzbeat.warehouse.store.realtime.memory.MemoryDataStorage;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand Down Expand Up @@ -90,9 +90,9 @@ public ResponseEntity<Message<MetricsData>> getMetricsData(
AbstractRealTimeDataStorage realTimeDataStorage = realTimeDataStorages.stream()
.filter(AbstractRealTimeDataStorage::isServerAvailable)
.max((o1, o2) -> {
if (o1 instanceof RealTimeMemoryDataStorage) {
if (o1 instanceof MemoryDataStorage) {
return -1;
} else if (o2 instanceof RealTimeMemoryDataStorage) {
} else if (o2 instanceof MemoryDataStorage) {
return 1;
} else {
return 0;
Expand Down Expand Up @@ -156,9 +156,9 @@ public ResponseEntity<Message<MetricsHistoryData>> getMetricHistoryData(
) {
AbstractHistoryDataStorage historyDataStorage = historyDataStorages.stream()
.filter(AbstractHistoryDataStorage::isServerAvailable).max((o1, o2) -> {
if (o1 instanceof HistoryJpaDatabaseDataStorage) {
if (o1 instanceof JpaDatabaseDataStorage) {
return -1;
} else if (o2 instanceof HistoryJpaDatabaseDataStorage) {
} else if (o2 instanceof JpaDatabaseDataStorage) {
return 1;
} else {
return 0;
Expand Down
Loading
Loading