chore: import upstream snapshot with attribution
MCP Bash Server CI / Test MCP Bash Server (dev) (push) Has been cancelled
MCP Bash Server CI / Test MCP Bash Server (release) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:11:39 +08:00
commit c8cebdfeee
4654 changed files with 626756 additions and 0 deletions
+184
View File
@@ -0,0 +1,184 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<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>hertzbeat</artifactId>
<groupId>org.apache.hertzbeat</groupId>
<version>2.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>hertzbeat-common-core</artifactId>
<name>${project.artifactId}</name>
<description>Framework-agnostic shared runtime models, utilities, and protocol support.</description>
<dependencies>
<!-- Tool dependencies -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
</dependency>
<!-- Use apache.http.conn.util instead of sun.net.util -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- caffeine-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<!-- kafka -->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<exclusions>
<exclusion>
<artifactId>snappy-java</artifactId>
<groupId>org.xerial.snappy</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- redis -->
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</dependency>
<!-- expr calculate -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jexl3</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.beetstra.jutf7/jutf7 -->
<dependency>
<groupId>com.beetstra.jutf7</groupId>
<artifactId>jutf7</artifactId>
<version>${jutf7.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>commons-compress</artifactId>
<groupId>org.apache.commons</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>${commons-compress.version}</version>
</dependency>
<dependency>
<groupId>org.apache.arrow</groupId>
<artifactId>arrow-vector</artifactId>
</dependency>
<dependency>
<groupId>org.apache.arrow</groupId>
<artifactId>arrow-memory-netty</artifactId>
</dependency>
<dependency>
<groupId>org.xerial.snappy</groupId>
<artifactId>snappy-java</artifactId>
<version>${snappy-java.version}</version>
</dependency>
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>${javaparser.version}</version>
<scope>test</scope>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
</dependency>
<!-- jackson for optional json processing -->
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>tools.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>tools.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<!-- swagger annotations (optional) -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<scope>provided</scope>
</dependency>
<!-- validation annotations (optional) -->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- jakarta annotations -->
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,107 @@
/*
* 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.arrow.vector.table;
import java.util.Iterator;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.dictionary.DictionaryProvider;
import org.apache.arrow.vector.types.pojo.Schema;
import org.apache.arrow.vector.util.TransferPair;
/**
* <p>A temporary Arrow Table implementation that uses Arrow's FieldVectors to store data.</p>
* <p>Instead of Table, due the table can not store the schema metadata, so we need to use ArrowTable to store the schema metadata.</p>
* <p>todo Improve the upstream branch `table` to support schema metadata.</p>
*/
@Slf4j
public class ArrowTable extends BaseTable {
/**
* Constructs new instance with the given rowCount, and containing the schema and each of the
* given vectors.
*
* @param fieldVectors the FieldVectors containing the table's data
* @param rowCount the number of rows in the table
* @param provider a dictionary provider, may be null if none of the vectors in the table are
* encoded
*/
public ArrowTable(List<FieldVector> fieldVectors, int rowCount, DictionaryProvider provider) {
super(fieldVectors, rowCount, provider);
}
/**
* Constructs a new instance containing the data from the argument. Vectors are shared between the
* Table and VectorSchemaRoot. Direct modification of those vectors is unsafe and should be
* avoided.
*
* @param vsr The VectorSchemaRoot providing data for this Table
*/
public ArrowTable(VectorSchemaRoot vsr) {
this(vsr.getFieldVectors(), vsr.getRowCount(), null);
try {
this.schema = Schema.fromJSON(vsr.getSchema().toJson());
} catch (Exception e) {
log.error("Failed to parse arrow table schema from VectorSchemaRoot", e);
}
vsr.clear();
}
@Override
public VectorSchemaRoot toVectorSchemaRoot() {
List<FieldVector> fieldVectorList = fieldVectors.stream()
.map(
v -> {
TransferPair transferPair = v.getTransferPair(v.getAllocator());
transferPair.transfer();
return (FieldVector) transferPair.getTo();
})
.toList();
VectorSchemaRoot vsr =
new VectorSchemaRoot(schema, fieldVectorList, rowCount);
clear();
return vsr;
}
public FieldVector getVector(String columnName) {
return super.getVector(columnName);
}
/** Returns a Row iterator for this Table. */
public Iterator<Row> iterator() {
return new Iterator<Row>() {
private final Row row = new Row(ArrowTable.this);
@Override
public Row next() {
row.next();
return row;
}
@Override
public boolean hasNext() {
return row.hasNext();
}
};
}
}
@@ -0,0 +1,66 @@
/*
* 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.common.cache;
/**
* common cache service
*/
public interface CommonCacheService<K, V> {
/**
* get cache by key use clazz
* @param key key
* @return object
*/
V get(K key);
/**
* set cache
* @param key key
* @param value value
*/
void put(K key, V value);
/**
* set cache and return oldValue if present
* @param key key
* @param value value
* @return old value
*/
V putAndGetOld(K key, V value);
/**
* if contain cache by key
* @param key key
* @return true is contain
*/
boolean containsKey(K key);
/**
* remove cache
* @param key key
* @return old value
*/
V remove(K key);
/**
* clear cache
* @return is clear success
*/
boolean clear();
}
@@ -0,0 +1,39 @@
/*
* 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.common.concurrent;
/**
* Task admission mode for managed executors.
*/
public enum AdmissionMode {
/**
* Start each task on its own virtual thread without an executor-level concurrency cap.
*/
UNBOUNDED_VT,
/**
* Reject immediately when the configured concurrency cap has been reached.
*/
LIMIT_AND_REJECT,
/**
* Block the submitter until a permit is available.
*/
LIMIT_AND_BLOCK
}
@@ -0,0 +1,48 @@
/*
* 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.common.concurrent;
import java.util.concurrent.RejectedExecutionException;
/**
* Generic background task executor abstraction for runtime components.
*/
public interface BackgroundTaskExecutor {
/**
* Execute a short-lived task.
*
* @param runnable task
* @throws RejectedExecutionException when execution is rejected
*/
void execute(Runnable runnable) throws RejectedExecutionException;
/**
* Execute a long-lived background task.
*
* @param runnable task
*/
void executeLongRunning(Runnable runnable);
/**
* Release executor resources.
*
* @throws Exception close exception
*/
void destroy() throws Exception;
}
@@ -0,0 +1,36 @@
/*
* 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.common.concurrent;
import java.util.concurrent.Executor;
/**
* Executor with a stable logical name and close semantics.
*/
public interface ManagedExecutor extends Executor, AutoCloseable {
/**
* Logical executor name for logging and metrics tags.
*
* @return executor name
*/
String name();
@Override
void close();
}
@@ -0,0 +1,428 @@
/*
* 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.common.concurrent;
import java.util.ArrayDeque;
import java.util.Objects;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Factory methods for managed executors.
*/
public final class ManagedExecutors {
private ManagedExecutors() {
}
/**
* Wrap an existing executor service.
*
* @param name executor name
* @param executorService delegate executor service
* @return managed executor wrapper
*/
public static ManagedExecutor wrap(String name, ExecutorService executorService) {
return new DefaultManagedExecutor(name, executorService, null, AdmissionMode.UNBOUNDED_VT);
}
/**
* Create a per-task virtual-thread executor with optional admission control.
*
* @param name executor name
* @param threadNamePrefix thread name prefix
* @param mode admission mode
* @param maxConcurrentTasks max concurrent tasks for limited modes
* @param handler uncaught exception handler
* @return managed executor
*/
public static ManagedExecutor newVirtualExecutor(String name, String threadNamePrefix, AdmissionMode mode,
int maxConcurrentTasks, Thread.UncaughtExceptionHandler handler) {
ThreadFactory threadFactory = Thread.ofVirtual()
.name(threadNamePrefix, 0)
.uncaughtExceptionHandler(handler)
.factory();
ExecutorService executorService = Executors.newThreadPerTaskExecutor(threadFactory);
return new DefaultManagedExecutor(name, executorService, semaphore(mode, maxConcurrentTasks), mode);
}
/**
* Create a platform-thread-per-task executor for a small number of long-running tasks.
*
* @param name executor name
* @param threadNamePrefix thread name prefix
* @param handler uncaught exception handler
* @return managed executor
*/
public static ManagedExecutor newPlatformExecutor(String name, String threadNamePrefix,
Thread.UncaughtExceptionHandler handler) {
ThreadFactory threadFactory = Thread.ofPlatform()
.daemon(true)
.name(threadNamePrefix, 0)
.uncaughtExceptionHandler(handler)
.factory();
ExecutorService executorService = Executors.newThreadPerTaskExecutor(threadFactory);
return new DefaultManagedExecutor(name, executorService, null, AdmissionMode.UNBOUNDED_VT);
}
/**
* Create a queued executor that preserves queue semantics while executing tasks on virtual threads.
*
* @param name executor name
* @param threadNamePrefix virtual-thread name prefix
* @param maxConcurrentTasks max concurrent tasks
* @param queueCapacity queue capacity, {@code <= 0} means unbounded
* @param handler uncaught exception handler
* @return managed executor
*/
public static ManagedExecutor newQueuedVirtualExecutor(String name, String threadNamePrefix, int maxConcurrentTasks,
int queueCapacity, Thread.UncaughtExceptionHandler handler) {
if (maxConcurrentTasks <= 0) {
throw new IllegalArgumentException("maxConcurrentTasks must be greater than zero for queued executors");
}
return new QueuedVirtualManagedExecutor(name, threadNamePrefix, maxConcurrentTasks, queueCapacity, handler);
}
/**
* Create a virtual-thread executor that preserves {@link java.util.concurrent.ThreadPoolExecutor}
* core/max/queue semantics with discard-oldest overflow handling.
*
* @param name executor name
* @param threadNamePrefix virtual-thread name prefix
* @param coreConcurrentTasks core concurrent tasks
* @param maxConcurrentTasks max concurrent tasks
* @param queueCapacity queue capacity
* @param handler uncaught exception handler
* @return managed executor
*/
public static ManagedExecutor newDiscardOldestVirtualExecutor(String name, String threadNamePrefix,
int coreConcurrentTasks, int maxConcurrentTasks,
int queueCapacity,
Thread.UncaughtExceptionHandler handler) {
if (coreConcurrentTasks <= 0) {
throw new IllegalArgumentException("coreConcurrentTasks must be greater than zero");
}
if (maxConcurrentTasks < coreConcurrentTasks) {
throw new IllegalArgumentException("maxConcurrentTasks must be greater than or equal to coreConcurrentTasks");
}
if (queueCapacity <= 0) {
throw new IllegalArgumentException("queueCapacity must be greater than zero");
}
return new DiscardOldestVirtualManagedExecutor(name, threadNamePrefix, coreConcurrentTasks,
maxConcurrentTasks, queueCapacity, handler);
}
private static Semaphore semaphore(AdmissionMode mode, int maxConcurrentTasks) {
if (mode == AdmissionMode.UNBOUNDED_VT) {
return null;
}
if (maxConcurrentTasks <= 0) {
throw new IllegalArgumentException("maxConcurrentTasks must be greater than zero for limited executors");
}
return new Semaphore(maxConcurrentTasks);
}
private static final class DefaultManagedExecutor implements ManagedExecutor {
private final String name;
private final ExecutorService delegate;
private final Semaphore permits;
private final AdmissionMode admissionMode;
private DefaultManagedExecutor(String name, ExecutorService delegate, Semaphore permits,
AdmissionMode admissionMode) {
this.name = Objects.requireNonNull(name, "name");
this.delegate = Objects.requireNonNull(delegate, "delegate");
this.permits = permits;
this.admissionMode = Objects.requireNonNull(admissionMode, "admissionMode");
}
@Override
public String name() {
return name;
}
@Override
public void execute(Runnable command) {
Objects.requireNonNull(command, "command");
acquirePermit();
boolean submitted = false;
try {
delegate.execute(() -> {
try {
command.run();
} finally {
releasePermit();
}
});
submitted = true;
} finally {
if (!submitted) {
releasePermit();
}
}
}
@Override
public void close() {
delegate.shutdownNow();
}
private void acquirePermit() {
if (permits == null) {
return;
}
switch (admissionMode) {
case LIMIT_AND_REJECT:
if (!permits.tryAcquire()) {
throw new RejectedExecutionException(name + " rejected task because concurrency limit was reached");
}
break;
case LIMIT_AND_BLOCK:
try {
permits.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RejectedExecutionException(name + " interrupted while waiting for an execution permit", e);
}
break;
case UNBOUNDED_VT:
break;
default:
throw new IllegalStateException("Unsupported admission mode: " + admissionMode);
}
}
private void releasePermit() {
if (permits != null) {
permits.release();
}
}
}
private static final class QueuedVirtualManagedExecutor implements ManagedExecutor {
private final String name;
private final ExecutorService delegate;
private final ExecutorService dispatcher;
private final BlockingDeque<Runnable> queue;
private final Semaphore permits;
private final Semaphore permitSignals;
private final AtomicBoolean closed;
private QueuedVirtualManagedExecutor(String name, String threadNamePrefix, int maxConcurrentTasks,
int queueCapacity, Thread.UncaughtExceptionHandler handler) {
this.name = Objects.requireNonNull(name, "name");
ThreadFactory virtualFactory = Thread.ofVirtual()
.name(threadNamePrefix, 0)
.uncaughtExceptionHandler(handler)
.factory();
this.delegate = Executors.newThreadPerTaskExecutor(virtualFactory);
this.queue = queueCapacity > 0 ? new LinkedBlockingDeque<>(queueCapacity) : new LinkedBlockingDeque<>();
this.permits = new Semaphore(maxConcurrentTasks);
this.permitSignals = new Semaphore(0);
this.closed = new AtomicBoolean(false);
ThreadFactory dispatcherFactory = Thread.ofPlatform()
.daemon(true)
.name(threadNamePrefix + "dispatcher-", 0)
.uncaughtExceptionHandler(handler)
.factory();
this.dispatcher = Executors.newSingleThreadExecutor(dispatcherFactory);
this.dispatcher.execute(this::dispatchLoop);
}
@Override
public String name() {
return name;
}
@Override
public void execute(Runnable command) {
Objects.requireNonNull(command, "command");
if (closed.get()) {
throw new RejectedExecutionException(name + " rejected task because executor is closed");
}
if (!queue.offerLast(command)) {
throw new RejectedExecutionException(name + " rejected task because queue capacity was reached");
}
}
@Override
public void close() {
if (!closed.compareAndSet(false, true)) {
return;
}
dispatcher.shutdownNow();
delegate.shutdownNow();
queue.clear();
}
private void dispatchLoop() {
try {
while (!Thread.currentThread().isInterrupted()) {
Runnable command = queue.takeFirst();
if (!permits.tryAcquire()) {
queue.putFirst(command);
permitSignals.acquire();
continue;
}
submit(command);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void submit(Runnable command) {
boolean submitted = false;
try {
delegate.execute(() -> {
try {
command.run();
} finally {
permits.release();
permitSignals.release();
}
});
submitted = true;
} finally {
if (!submitted) {
permits.release();
permitSignals.release();
}
}
}
}
private static final class DiscardOldestVirtualManagedExecutor implements ManagedExecutor {
private final String name;
private final ExecutorService delegate;
private final int coreConcurrentTasks;
private final int maxConcurrentTasks;
private final ArrayDeque<Runnable> queue;
private final int queueCapacity;
private final Object lock;
private boolean closed;
private int runningTasks;
private DiscardOldestVirtualManagedExecutor(String name, String threadNamePrefix, int coreConcurrentTasks,
int maxConcurrentTasks, int queueCapacity,
Thread.UncaughtExceptionHandler handler) {
this.name = Objects.requireNonNull(name, "name");
ThreadFactory virtualFactory = Thread.ofVirtual()
.name(threadNamePrefix, 0)
.uncaughtExceptionHandler(handler)
.factory();
this.delegate = Executors.newThreadPerTaskExecutor(virtualFactory);
this.coreConcurrentTasks = coreConcurrentTasks;
this.maxConcurrentTasks = maxConcurrentTasks;
this.queueCapacity = queueCapacity;
this.queue = new ArrayDeque<>(queueCapacity);
this.lock = new Object();
this.closed = false;
this.runningTasks = 0;
}
@Override
public String name() {
return name;
}
@Override
public void execute(Runnable command) {
Objects.requireNonNull(command, "command");
Runnable taskToStart = null;
synchronized (lock) {
if (closed) {
throw new RejectedExecutionException(name + " rejected task because executor is closed");
}
if (runningTasks < coreConcurrentTasks) {
runningTasks++;
taskToStart = command;
} else if (queue.size() < queueCapacity) {
queue.offerLast(command);
return;
} else if (runningTasks < maxConcurrentTasks) {
runningTasks++;
taskToStart = command;
} else {
queue.pollFirst();
queue.offerLast(command);
return;
}
}
submit(taskToStart);
}
@Override
public void close() {
synchronized (lock) {
if (closed) {
return;
}
closed = true;
queue.clear();
}
delegate.shutdownNow();
}
private void submit(Runnable command) {
boolean submitted = false;
try {
delegate.execute(() -> {
try {
command.run();
} finally {
onTaskComplete();
}
});
submitted = true;
} finally {
if (!submitted) {
synchronized (lock) {
runningTasks--;
}
throw new RejectedExecutionException(name + " rejected task because delegate submission failed");
}
}
}
private void onTaskComplete() {
Runnable nextTask = null;
synchronized (lock) {
if (closed) {
runningTasks--;
return;
}
nextTask = queue.pollFirst();
if (nextTask == null) {
runningTasks--;
return;
}
}
submit(nextTask);
}
}
}
@@ -0,0 +1,46 @@
/*
* 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.common.config;
import lombok.Getter;
import lombok.Setter;
/**
* Kafka properties
*/
@Getter
@Setter
public class BaseKafkaProperties {
/**
* kafka's connection server url
*/
private String servers = "127.0.0.1:9092";
/**
* The name of the topic that receives the data
*/
private String topic;
/**
* Consumer Group ID
*/
private String groupId;
}
@@ -0,0 +1,201 @@
/*
* 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.common.config;
import org.apache.hertzbeat.common.concurrent.AdmissionMode;
/**
* Framework-agnostic virtual-thread runtime configuration.
*/
public record VirtualThreadProperties(
boolean enabled,
PoolProperties collector,
PoolProperties common,
PoolProperties manager,
AlerterProperties alerter,
PoolProperties warehouse,
AsyncProperties async) {
private static final int DEFAULT_COLLECTOR_MAX_CONCURRENT_JOBS = 512;
private static final int DEFAULT_MANAGER_MAX_CONCURRENT_JOBS = 10;
private static final int DEFAULT_NOTIFY_MAX_CONCURRENT_JOBS = 64;
private static final int DEFAULT_PERIODIC_MAX_CONCURRENT_JOBS = 10;
private static final int DEFAULT_NOTIFY_MAX_CONCURRENT_PER_CHANNEL = 4;
public VirtualThreadProperties {
collector = normalizePool(collector, PoolProperties.collectorDefaults());
common = common == null ? PoolProperties.commonDefaults() : common;
manager = normalizePool(manager, PoolProperties.managerDefaults());
alerter = alerter == null ? AlerterProperties.defaults() : alerter;
warehouse = warehouse == null ? PoolProperties.warehouseDefaults() : warehouse;
async = async == null ? AsyncProperties.defaults() : async;
}
public VirtualThreadProperties() {
this(true, PoolProperties.collectorDefaults(), PoolProperties.commonDefaults(),
PoolProperties.managerDefaults(), AlerterProperties.defaults(),
PoolProperties.warehouseDefaults(), AsyncProperties.defaults());
}
/**
* Create a detached properties instance with runtime defaults.
*
* @return defaults instance
*/
public static VirtualThreadProperties defaults() {
return new VirtualThreadProperties();
}
/**
* Pool-level configuration.
*/
public record PoolProperties(
AdmissionMode mode,
int maxConcurrentJobs) {
public PoolProperties {
mode = mode == null ? AdmissionMode.UNBOUNDED_VT : mode;
}
public PoolProperties() {
this(AdmissionMode.UNBOUNDED_VT, 0);
}
public static PoolProperties collectorDefaults() {
return new PoolProperties(AdmissionMode.LIMIT_AND_REJECT, defaultCollectorConcurrency());
}
public static PoolProperties warehouseDefaults() {
return new PoolProperties();
}
public static PoolProperties commonDefaults() {
return new PoolProperties();
}
public static PoolProperties managerDefaults() {
return new PoolProperties(AdmissionMode.LIMIT_AND_REJECT, DEFAULT_MANAGER_MAX_CONCURRENT_JOBS);
}
public static PoolProperties alerterNotifyDefaults() {
return new PoolProperties(AdmissionMode.LIMIT_AND_REJECT, DEFAULT_NOTIFY_MAX_CONCURRENT_JOBS);
}
private static int defaultCollectorConcurrency() {
return DEFAULT_COLLECTOR_MAX_CONCURRENT_JOBS;
}
}
/**
* Alerter-specific executor configuration.
*/
public record AlerterProperties(
PoolProperties notifyPool,
int periodicMaxConcurrentJobs,
QueueProperties logWorker,
QueueProperties reduce,
QueueProperties windowEvaluator,
int notifyMaxConcurrentPerChannel) {
public AlerterProperties {
notifyPool = normalizePool(notifyPool, PoolProperties.alerterNotifyDefaults());
periodicMaxConcurrentJobs = periodicMaxConcurrentJobs <= 0
? DEFAULT_PERIODIC_MAX_CONCURRENT_JOBS : periodicMaxConcurrentJobs;
logWorker = normalizeQueue(logWorker, QueueProperties.logWorkerDefaults());
reduce = normalizeQueue(reduce, QueueProperties.reduceDefaults());
windowEvaluator = normalizeQueue(windowEvaluator, QueueProperties.windowEvaluatorDefaults());
notifyMaxConcurrentPerChannel = notifyMaxConcurrentPerChannel <= 0
? DEFAULT_NOTIFY_MAX_CONCURRENT_PER_CHANNEL : notifyMaxConcurrentPerChannel;
}
public AlerterProperties() {
this(PoolProperties.alerterNotifyDefaults(), DEFAULT_PERIODIC_MAX_CONCURRENT_JOBS,
QueueProperties.logWorkerDefaults(), QueueProperties.reduceDefaults(),
QueueProperties.windowEvaluatorDefaults(), DEFAULT_NOTIFY_MAX_CONCURRENT_PER_CHANNEL);
}
public static AlerterProperties defaults() {
return new AlerterProperties();
}
}
/**
* Queue-preserving executor configuration.
*/
public record QueueProperties(
int maxConcurrentJobs,
int queueCapacity) {
public QueueProperties() {
this(0, 0);
}
public static QueueProperties reduceDefaults() {
return new QueueProperties(2, 0);
}
public static QueueProperties logWorkerDefaults() {
return new QueueProperties(10, 1000);
}
public static QueueProperties windowEvaluatorDefaults() {
return new QueueProperties(2, 0);
}
}
/**
* Async executor configuration.
*/
public record AsyncProperties(
boolean enabled,
int concurrencyLimit,
boolean rejectWhenLimitReached,
long taskTerminationTimeout) {
public AsyncProperties() {
this(true, 256, true, 5000L);
}
public static AsyncProperties defaults() {
return new AsyncProperties();
}
}
private static PoolProperties normalizePool(PoolProperties configured, PoolProperties defaults) {
if (configured == null) {
return defaults;
}
if (configured.mode() != AdmissionMode.UNBOUNDED_VT && configured.maxConcurrentJobs() <= 0) {
return new PoolProperties(configured.mode(), defaults.maxConcurrentJobs());
}
return configured;
}
private static QueueProperties normalizeQueue(QueueProperties configured, QueueProperties defaults) {
if (configured == null) {
return defaults;
}
int maxConcurrentJobs = configured.maxConcurrentJobs() <= 0
? defaults.maxConcurrentJobs() : configured.maxConcurrentJobs();
int queueCapacity = configured.queueCapacity();
if (queueCapacity <= 0 && defaults.queueCapacity() > 0) {
queueCapacity = defaults.queueCapacity();
}
return new QueueProperties(maxConcurrentJobs, queueCapacity);
}
}
@@ -0,0 +1,199 @@
/*
* 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.common.constants;
/**
* AI constants
*/
public interface AiConstants {
/**
* zhiPu constants
*/
interface ZhiPuConstants {
/**
* zhiPu request url
*/
String URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
/**
* request role param
*/
String REQUEST_ROLE = "user";
/**
* The model outputs the maximum tokens, with a maximum output of 8192 and a default value of 3072
*/
Integer MAX_TOKENS = 3072;
/**
* The sampling temperature, which controls the randomness of the output, must be positive
* The value ranges from 0.0 to 1.0, and cannot be equal to 0. The default value is 0.95. The larger the value,
* the more random and creative the output will be. The smaller the value, the more stable or certain the output will be
* You are advised to adjust top_p or temperature parameters based on application scenarios, but do not adjust the two parameters at the same time
*/
float TEMPERATURE = 0.7f;
}
/**
* alibaba Ai constants
*/
interface AliAiConstants {
/**
* alibabaAi request url
*/
String URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
/**
* request role param
*/
String REQUEST_ROLE = "user";
/**
* The model outputs the maximum tokens, with a maximum output of 8192 and a default value of 3072
*/
Integer MAX_TOKENS = 3072;
/**
* The sampling temperature, which controls the randomness of the output, must be positive
* The value ranges from 0.0 to 1.0, and cannot be equal to 0. The default value is 0.95. The larger the value,
* the more random and creative the output will be. The smaller the value, the more stable or certain the output will be
* You are advised to adjust top_p or temperature parameters based on application scenarios, but do not adjust the two parameters at the same time
*/
float TEMPERATURE = 0.7f;
}
/**
* Kimi Ai constants
*/
interface KimiAiConstants {
/**
* Kimi Ai URL
*/
String URL = "https://api.moonshot.cn/v1/chat/completions";
/**
* request role param
*/
String REQUEST_ROLE = "user";
/**
* The model outputs the maximum tokens, with a maximum output of 8192 and a default value of 3072
*/
Integer MAX_TOKENS = 3072;
/**
* The sampling temperature, which controls the randomness of the output, must be positive
* The value ranges from 0.0 to 1.0, and cannot be equal to 0. The default value is 0.95. The larger the value,
* the more random and creative the output will be. The smaller the value, the more stable or certain the output will be
* You are advised to adjust top_p or temperature parameters based on application scenarios, but do not adjust the two parameters at the same time
*/
float TEMPERATURE = 0.7f;
}
/**
* sparkDesk constants
*/
interface SparkDeskConstants {
/**
* SparkDesk Ai URL
*/
String SPARK_ULTRA_URL = "https://spark-api-open.xf-yun.com/v1/chat/completions";
/**
* request role param
*/
String REQUEST_ROLE = "user";
/**
* The model outputs the maximum tokens, with a maximum output of 8192 and a default value of 3072
*/
Integer MAX_TOKENS = 3072;
/**
* The sampling temperature, which controls the randomness of the output, must be positive
* The value ranges from 0.0 to 1.0, and cannot be equal to 0. The default value is 0.95. The larger the value,
* the more random and creative the output will be. The smaller the value, the more stable or certain the output will be
* You are advised to adjust top_p or temperature parameters based on application scenarios, but do not adjust the two parameters at the same time
*/
float TEMPERATURE = 0.7f;
}
/**
* Ollama constants
*/
interface OllamaConstants {
/**
* request role param
*/
String REQUEST_ROLE = "user";
/**
* The model outputs the maximum tokens, with a maximum output of 8192 and a default value of 3072
*/
Integer MAX_TOKENS = 3072;
/**
* The sampling temperature, which controls the randomness of the output, must be positive
* The value ranges from 0.0 to 1.0, and cannot be equal to 0. The default value is 0.95. The larger the value,
* the more random and creative the output will be. The smaller the value, the more stable or certain the output will be
* You are advised to adjust top_p or temperature parameters based on application scenarios, but do not adjust the two parameters at the same time
*/
float TEMPERATURE = 0.7f;
}
/**
* OpenRouter constants
*/
interface OpenRouterConstants {
/**
* OpenRouter Ai URL
*/
String URL = "https://openrouter.ai/api/v1/chat/completions";
/**
* request role param
*/
String REQUEST_ROLE = "user";
/**
* The model outputs the maximum tokens, with a maximum output of 8192 and a default value of 3072
*/
Integer MAX_TOKENS = 3072;
/**
* The sampling temperature, which controls the randomness of the output, must be positive
* The value ranges from 0.0 to 1.0, and cannot be equal to 0. The default value is 0.95. The larger the value,
* the more random and creative the output will be. The smaller the value, the more stable or certain the output will be
* You are advised to adjust top_p or temperature parameters based on application scenarios, but do not adjust the two parameters at the same time
*/
float TEMPERATURE = 0.7f;
}
}
@@ -0,0 +1,67 @@
/*
* 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.common.constants;
import java.util.Arrays;
/**
* Ai type Enum
*/
public enum AiTypeEnum {
/**
* ZhiPu
*/
zhiPu,
/**
* sparkDesk
*/
sparkDesk,
/**
* alibabaAi
*/
alibabaAi,
/**
* Moonshot AI
*/
kimiAi,
/**
* Ollama AI
*/
ollama,
/**
* OpenRouter
*/
openRouter;
/**
* get type
*/
public static AiTypeEnum getTypeByName(String type) {
return Arrays.stream(values())
.filter(ai -> ai.name().equals(type))
.findFirst()
.orElse(null);
}
}
@@ -0,0 +1,36 @@
/*
* 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.common.constants;
/**
* collect code
*/
public interface CollectCodeConstants {
/** collect success **/
String SUCCESS = "0";
/** collector not available **/
String UN_AVAILABLE = "1";
/** peer network un reachable(icmp) **/
String UN_REACHABLE = "2";
/** peer network server un connectable(tcp,udp...) **/
String UN_CONNECTABLE = "3";
/** collect metrics data failed(http,ssh,snmp...) **/
String FAILED = "4";
/** collect metrics data timeout **/
String TIMEOUT = "5";
}
@@ -0,0 +1,410 @@
/*
* 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.common.constants;
/**
* Public Common Constant
*/
public interface CommonConstants {
/**
* Response status code: generic success
*/
byte SUCCESS_CODE = 0x00;
/**
* Response status code: generic failure
*/
byte FAIL_CODE = 0x0F;
/**
* Response status code: Parameter verification failed
*/
byte PARAM_INVALID_CODE = 0x01;
/**
* Response Status Code: Probe Failed
*/
byte DETECT_FAILED_CODE = 0x02;
/**
* Response status code: monitoring does not exist
*/
byte MONITOR_NOT_EXIST_CODE = 0x03;
/**
* Response Status Code: Monitor Service Conflict
*/
byte MONITOR_CONFLICT_CODE = 0x04;
/**
* Response status code: Incorrect login account password
*/
byte LOGIN_FAILED_CODE = 0x05;
/**
* Monitoring status 0: Paused, 1: Up, 2: Down
*/
byte MONITOR_PAUSED_CODE = 0x00;
/**
* Monitoring status 0: Paused, 1: Up, 2: Down
*/
byte MONITOR_UP_CODE = 0x01;
/**
* Monitoring status 0: Paused, 1: Up, 2: Down
*/
byte MONITOR_DOWN_CODE = 0x02;
/**
* scrape type static
*/
String SCRAPE_STATIC = "static";
/**
* scrape type
*/
String SCRAPE_HTTP_SD = "http_sd";
/**
* label key: instance
*/
String LABEL_INSTANCE = "instance";
/**
* label key: defineid
*/
String LABEL_DEFINE_ID = "defineid";
/**
* label key: alert name
*/
String LABEL_ALERT_NAME = "alertname";
/**
* label key: instance name
*/
String LABEL_INSTANCE_NAME = "instancename";
/**
* Alarm severity label key
*/
String LABEL_ALERT_SEVERITY = "severity";
/**
* Alarm severity fatal level
*/
String LABEL_ALERT_FATAL = "fatal";
/**
* alarm severity emergency level
*/
String ALERT_SEVERITY_EMERGENCY = "emergency";
/**
* alarm severity critical level
*/
String ALERT_SEVERITY_CRITICAL = "critical";
/**
* alarm severity warning level
*/
String ALERT_SEVERITY_WARNING = "warning";
/**
* alarm severity info level
*/
String ALERT_SEVERITY_INFO = "info";
/**
* Alarm status: firing
*/
String ALERT_STATUS_FIRING = "firing";
/**
* Alarm status: resolved
*/
String ALERT_STATUS_RESOLVED = "resolved";
/**
* Alarm status: pending
*/
String ALERT_STATUS_PENDING = "pending";
/**
* metric alert threshold type: realtime
*/
String METRIC_ALERT_THRESHOLD_TYPE_REALTIME = "realtime_metric";
/**
* metric alert threshold type: periodic
*/
String METRIC_ALERT_THRESHOLD_TYPE_PERIODIC = "periodic_metric";
/**
* log alert threshold type: realtime
*/
String LOG_ALERT_THRESHOLD_TYPE_REALTIME = "realtime_log";
/**
* log alert threshold type: periodic
*/
String LOG_ALERT_THRESHOLD_TYPE_PERIODIC = "periodic_log";
/**
* Alert mode label key
*/
String ALERT_MODE_LABEL = "alert_mode";
/**
* Alert mode: group
*/
String ALERT_MODE_GROUP = "group";
/**
* Alert mode: individual
*/
String ALERT_MODE_INDIVIDUAL = "individual";
/**
* Field parameter type: number
*/
byte TYPE_NUMBER = 0;
/**
* Field parameter type: String
*/
byte TYPE_STRING = 1;
/**
* Field parameter type: encrypted string
*/
byte TYPE_SECRET = 2;
/**
* Field parameter type: time
*/
byte TYPE_TIME = 3;
/**
* Collection metric value: null placeholder for empty value
*/
String NULL_VALUE = "&nbsp;";
/**
*
*/
String PROM_TIME = "timestamp";
/**
*
*/
String PROM_VALUE = "value";
/**
* prometheus metric value alias
*/
String PROM_METRIC_VALUE = "metric_value";
/**
* Parameter Type Number
*/
byte PARAM_TYPE_NUMBER = 0;
/**
* Parameter Type String
*/
byte PARAM_TYPE_STRING = 1;
/**
* Parameter Type Password
*/
byte PARAM_TYPE_PASSWORD = 2;
/**
* Parameter Type Map values
*/
byte PARAM_TYPE_MAP = 3;
/**
* Parameter Type arrays values
*/
byte PARAM_TYPE_ARRAY = 4;
/**
* cache key notice_rule
*/
String CACHE_NOTICE_RULE = "notice_rule";
/**
* cache key alert silence
*/
String CACHE_ALERT_SILENCE = "alert_silence";
/**
* cache key metric alert define
*/
String METRIC_CACHE_ALERT_DEFINE = "metric_alert_define";
/**
* cache key log alert define
*/
String LOG_CACHE_ALERT_DEFINE = "log_alert_define";
/**
* cache key alert converge
*/
String CACHE_ALERT_GROUP_CONVERGE = "alert_group_converge";
/**
* cache key alert inhibit
*/
String CACHE_ALERT_INHIBIT = "alert_inhibit";
/**
* collector status online 0
*/
byte COLLECTOR_STATUS_ONLINE = 0;
/**
* collector status offline 1
*/
byte COLLECTOR_STATUS_OFFLINE = 1;
/**
* default main collector name
*/
String MAIN_COLLECTOR_NODE = "main-default-collector";
/**
* locale spilt
*/
String LOCALE_SEPARATOR = "_";
/**
* ignore label
* Handle situations where recovery alarms are not configured, but need to be used to change task state
*/
String IGNORE = "ignore";
/**
* collector mode public
*/
String MODE_PUBLIC = "public";
/**
* collector mode private
*/
String MODE_PRIVATE = "private";
/**
* collector auth failed message
*/
String COLLECTOR_AUTH_FAILED = "Auth Failed";
/**
* for prometheus task name prefix
*/
String PROMETHEUS_APP_PREFIX = "_prometheus_";
/**
* prometheus
*/
String PROMETHEUS = "prometheus";
/**
* status page component state normal
*/
byte STATUS_PAGE_COMPONENT_STATE_NORMAL = 0;
/**
* status page component state abnormal
*/
byte STATUS_PAGE_COMPONENT_STATE_ABNORMAL = 1;
/**
* status page component state unknown
*/
byte STATUS_PAGE_COMPONENT_STATE_UNKNOWN = 2;
/**
* status page org state all normal
*/
byte STATUS_PAGE_ORG_STATE_ALL_NORMAL = 0;
/**
* status page org state some abnormal
*/
byte STATUS_PAGE_ORG_STATE_SOME_ABNORMAL = 1;
/**
* status page org state all abnormal
*/
byte STATUS_PAGE_ORG_STATE_ALL_ABNORMAL = 2;
/**
* status page component calculate method auto
*/
byte STATUE_PAGE_CALCULATE_METHOD_AUTO = 0;
/**
* status page component calculate method manual
*/
byte STATUS_PAGE_CALCULATE_METHOD_MANUAL = 1;
/**
* status page incident state investigating
*/
byte STATUS_PAGE_INCIDENT_STATE_INVESTIGATING = 0;
/**
* status page incident state identified
*/
byte STATUS_PAGE_INCIDENT_STATE_IDENTIFIED = 1;
/**
* status page incident state monitoring
*/
byte STATUS_PAGE_INCIDENT_STATE_MONITORING = 2;
/**
* status page incident state resolved
*/
byte STATUS_PAGE_INCIDENT_STATE_RESOLVED = 3;
/**
* status page incident state resolved
*/
byte MONITOR_TYPE_NORMAL = 0;
/**
* status page incident state resolved
*/
byte MONITOR_TYPE_PUSH_AUTO_CREATE = 1;
/**
* status page incident state resolved
*/
byte MONITOR_TYPE_DISCOVERY_AUTO_CREATE = 2;
/**
* JEXL custom function `json`
*/
String JEXL_CUSTOM_JSON_FUNCTION = "json";
}
@@ -0,0 +1,74 @@
/*
* 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.common.constants;
/**
* Extract all public strings that the project needs to configure in yml.
*/
public interface ConfigConstants {
/**
* System Constant: hertzbeat
*/
interface SystemConstant {
String PROJECT_NAME = "hertzbeat";
}
/**
* Package name constant.
*/
interface PkgConstant {
String PKG = "org.apache.hertzbeat";
}
/**
* hertzbeat project module constant.
*/
interface FunctionModuleConstants {
String MANAGER = "manager";
String ALERT = "alert";
String ALERTER = "alerter";
String COLLECTOR = "collector";
String COMMON = "common";
String WAREHOUSE = "warehouse";
String AI = "ai";
String STATUS = "status";
String SCHEDULER = "scheduler";
String PUSH = "push";
String DISPATCH = "dispatch";
String INFO = "info";
String GRAFANA = "grafana";
String LOG = "log";
}
}
@@ -0,0 +1,54 @@
/*
* 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.common.constants;
/**
* Queue dependent constant
*/
public interface DataQueueConstants {
/**
* Queue name prefix
*/
String PREFIX = "common.queue";
/**
* name
*/
String NAME = "type";
/**
* kafka
*/
String KAFKA = "kafka";
/**
* Local memory
*/
String IN_MEMORY = "memory";
/**
* redis
*/
String REDIS = "redis";
/**
* netty
*/
String NETTY = "netty";
}
@@ -0,0 +1,79 @@
/*
* 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.common.constants;
/**
* Export file type constants
*/
public interface ExportFileConstants {
/**
* Export file name constants.
*/
String FILE = "file";
/**
* Excel export files constants.
*/
interface ExcelFile {
/**
* Export file type.
*/
String TYPE = "EXCEL";
/**
* Export file suffix.
*/
String FILE_SUFFIX = ".xlsx";
}
/**
* Json export file constants.
*/
interface JsonFile {
/**
* Export file type.
*/
String TYPE = "JSON";
/**
* Export file suffix.
*/
String FILE_SUFFIX = ".json";
}
/**
* Yaml export file constants.
*/
interface YamlFile {
/**
* Export file type.
*/
String TYPE = "YAML";
/**
* Export file suffix.
*/
String FILE_SUFFIX = ".yaml";
}
}
@@ -0,0 +1,64 @@
/*
* 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.common.constants;
/**
* General Config Type Enum
*/
public enum GeneralConfigTypeEnum {
/**
* mute config
*/
mute,
/**
* template config
*/
template,
/**
* system secret config
*/
secret,
/**
* sms general config
*/
sms,
/**
* system config
*/
system,
/**
* mail general config
*/
email,
/**
* system store config
*/
oss,
/**
* model llm provider
*/
provider
}
@@ -0,0 +1,43 @@
/*
* 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.common.constants;
/**
* HertzBeat Reserved Keywords Enum
*/
public enum HertzBeatKeywordsEnum {
INSTANCE("instance", "metric_instance");
private final String keyword;
private final String alias;
HertzBeatKeywordsEnum(String keyword, String alias) {
this.keyword = keyword;
this.alias = alias;
}
public String getKeyword() {
return keyword;
}
public String getAlias() {
return alias;
}
}
@@ -0,0 +1,31 @@
/*
* 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.common.constants;
/**
* Import/Export task constants
*/
public interface ImExportTaskConstant {
/**
* If the number of tasks reaches this threshold, progress information will broadcast.
* Kept low so medium-sized imports (e.g. dozens of monitors) still report incremental progress.
*/
Integer IMPORT_TASK_PROCESS_THRESHOLD = 10;
}
@@ -0,0 +1,49 @@
/*
* 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.common.constants;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
/**
* Import/Export task status
*/
@Getter
@AllArgsConstructor
@ToString
public enum ImportTaskStatusEnum {
/**
* In progress
*/
IN_PROGRESS("IN_PROGRESS"),
/**
* Completed
*/
COMPLETED("COMPLETED"),
/**
* Failed
*/
FAILED("FAILED");
private final String value;
}
@@ -0,0 +1,85 @@
/*
* 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.common.constants;
import java.util.Arrays;
/**
* Jexl keywords enum
*/
public enum JexlKeywordsEnum {
/**
* Official reserved keywords
* @reference https://commons.apache.org/proper/commons-jexl/reference/syntax.html
*/
OR("or"),
AND("and"),
EQ("eq"),
NE("ne"),
LT("lt"),
GT("gt"),
LE("le"),
GE("ge"),
DIV("div"),
MOD("mod"),
NOT("not"),
NULL("null"),
TRUE("true"),
FALSE("false"),
NEW("new"),
VAR("var"),
DO("do"),
WHILE("while"),
BREAK("break"),
CONTINUE("continue"),
FUNCTION("function"),
RETURN("return"),
/**
* Syntax-reserved keywords
*/
IF("if"),
ELSE("else"),
FOR("for"),
/**
* Built-in functions reserve keywords
*/
SIZE("size"),
EMPTY("empty");
private final String keyword;
JexlKeywordsEnum(String keyword) {
this.keyword = keyword;
}
public String getKeyword() {
return keyword;
}
public static boolean match(String word) {
if (word == null || word.trim().isEmpty()) {
return false;
}
return Arrays.stream(values()).anyMatch(t -> t.keyword.equals(word));
}
}
@@ -0,0 +1,39 @@
/*
* 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.common.constants;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
/**
* Manager Event Type Enum
*/
@Getter
@AllArgsConstructor
@ToString
public enum ManagerEventTypeEnum {
/**
* IMPORT_TASK_EVENT
*/
IMPORT_TASK_EVENT("IMPORT_TASK_EVENT");
private final String value;
}
@@ -0,0 +1,42 @@
/*
* 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.common.constants;
/**
* Metric Data Field Constants
*/
public interface MetricDataConstants {
// key in Field
String TYPE = "type";
String LABEL = "label";
String UNIT = "unit";
// key in Schema metadata
String ID = "id";
String TENANT_ID = "tenantId";
String APP = "app";
String METRICS = "metrics";
String LABELS = "labels";
String ANNOTATIONS = "annotations";
String PRIORITY = "priority";
String TIME = "time";
String CODE = "code";
String MSG = "msg";
String INSTANCE_NAME = "instancename";
String INSTANCE = "instance";
}
@@ -0,0 +1,66 @@
/*
* 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.common.constants;
/**
* Http Constants.
*/
public interface NetworkConstants {
String KEEP_ALIVE = "Keep-Alive";
String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36";
String IPV6 = "ipv6";
String IPV4 = "ipv4";
String ERROR_MSG = "errorMsg";
String URL = "url";
String HTTP_HEADER = "http://";
String HTTPS_HEADER = "https://";
String RESPONSE_TIME = "responseTime";
String STATUS_CODE = "StatusCode";
String X_AUTH_TOKEN = "X-Auth-Token";
String LOCATION = "Location";
String BASIC = "Basic";
String AUTHORIZATION = "Authorization";
/**
* HttpClient Configuration Constants.
*/
interface HttpClientConstants {
int READ_TIME_OUT = 6 * 1000;
int WRITE_TIME_OUT = 6 * 1000;
int CONNECT_TIME_OUT = 6 * 1000;
int MAX_IDLE_CONNECTIONS = 20;
int KEEP_ALIVE_TIMEOUT = 30 * 1000;
}
}
@@ -0,0 +1,40 @@
/*
* 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.common.constants;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
/**
* Notify Level Enum
*/
@Getter
@AllArgsConstructor
@ToString
public enum NotifyLevelEnum {
SUCCESS("SUCCESS"),
ERROR("ERROR"),
INFO("INFO"),
WARNING("WARNING"),
BLANK("BLANK");
private final String value;
}
@@ -0,0 +1,33 @@
/*
* 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.common.constants;
/**
* plugin type
*/
public enum PluginType {
/**
* do something after alter
*/
POST_ALERT,
/**
* do something after collect
*/
POST_COLLECT
}
@@ -0,0 +1,42 @@
/*
* 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.common.constants;
/**
* Sign Constants
*/
public interface SignConstants {
String DOUBLE_MARK = ":";
String SINGLE_MARK = ";";
String WELL_NO = "#";
String LINE_FEED = "\n";
String CARRIAGE_RETURN = "\r";
String RIGHT_DASH = "/";
String COMMA = ",";
String BLANK = " ";
String DOT = ".";
}
@@ -0,0 +1,41 @@
/*
* 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.common.constants;
/**
* SMS provider constants
*/
public interface SmsConstants {
// Tencent cloud SMS
String TENCENT = "tencent";
// Alibaba Cloud SMS
String ALIBABA = "alibaba";
// UniSMS
String UNISMS = "unisms";
// Smslocal SMS
String SMSLOCAL = "smslocal";
// Aws cloud SMS
String AWS = "aws";
// Twilio SMS
String TWILIO = "twilio";
}
@@ -0,0 +1,50 @@
/*
* 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.common.constants;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
/**
* Theme Enum
*/
@Getter
@AllArgsConstructor
@ToString
public enum ThemeEnum {
COMPACT("compact"), DEFAULT("default"), LIGHT("light"), DARK("dark");
private final String value;
/**
* Convert theme to standard theme
*
* @param theme the input theme
* @return the converted theme
*/
public static String convert(String theme) {
if ((theme == null || theme.isEmpty())
|| ThemeEnum.COMPACT.getValue().equals(theme)
|| ThemeEnum.DEFAULT.getValue().equals(theme)) {
return ThemeEnum.LIGHT.getValue();
}
return theme;
}
}
@@ -0,0 +1,39 @@
/*
* 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.common.entity.arrow;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.arrow.vector.table.Row;
import org.apache.arrow.vector.types.pojo.Field;
/**
* A cell consisting of {@link Field} and value
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class ArrowCell extends DefaultMetadataReader {
private final String value;
private final Field field;
public ArrowCell(Field field, Row row) {
this.field = field;
this.value = row.getVarCharObj(field.getName());
this.metadata = field.getMetadata();
}
}
@@ -0,0 +1,52 @@
/*
* 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.common.entity.arrow;
import java.util.Map;
/**
* implementation of MetadataOperator
*/
public class DefaultMetadataReader implements MetadataReader {
protected Map<String, String> metadata;
@Override
public String getMetadataAsString(String key) {
return metadata.get(key);
}
@Override
public Boolean getMetadataAsBoolean(String key) {
return Boolean.parseBoolean(metadata.get(key));
}
@Override
public Byte getMetadataAsByte(String key) {
return Byte.parseByte(metadata.get(key));
}
@Override
public Integer getMetadataAsInteger(String key) {
return Integer.parseInt(metadata.get(key));
}
@Override
public Long getMetadataAsLong(String key) {
return Long.parseLong(metadata.get(key));
}
}
@@ -0,0 +1,32 @@
/*
* 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.common.entity.arrow;
/**
*/
public interface MetadataReader {
String getMetadataAsString(String key);
Boolean getMetadataAsBoolean(String key);
Byte getMetadataAsByte(String key);
Integer getMetadataAsInteger(String key);
Long getMetadataAsLong(String key);
}
@@ -0,0 +1,82 @@
/*
* 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.common.entity.arrow;
import lombok.Getter;
import org.apache.arrow.vector.table.Row;
import org.apache.arrow.vector.types.pojo.Field;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
/**
* A wrapper of row, which contains row info, fields info in this row and each cell of field.
* When using RowWrapper, it is necessary to call {@link RowWrapper#hasNextRow()} and {@link RowWrapper#nextRow()}
*/
public class RowWrapper {
private final Row currentRow;
private final Iterator<Row> rowIterator;
@Getter
private final List<Field> fieldList;
@Getter
private int rowIndex;
private int fieldIndex;
public RowWrapper(Row row, Iterator<Row> rowIterator, List<Field> fieldList, int rowIndex) {
this.currentRow = row;
this.rowIterator = rowIterator;
this.fieldList = fieldList;
this.fieldIndex = 0;
this.rowIndex = rowIndex;
}
public boolean hasNextRow() {
return rowIterator.hasNext();
}
public RowWrapper nextRow() {
return new RowWrapper(rowIterator.next(), rowIterator, fieldList, ++rowIndex);
}
/**
* <p>Get next cell in current row.
* <p>RowWrapper maintain a field index internally, which means cannot back to previous cell after call this method.
* However, you can use {@link RowWrapper#resetCellIndex()} to reset field index to the beginning.
* @return ArrowCell
*/
public ArrowCell nextCell() {
if (!hasNextCell() || currentRow == null) {
throw new NoSuchElementException("No more cells in current row");
}
return new ArrowCell(fieldList.get(fieldIndex++), currentRow);
}
public Stream<ArrowCell> cellStream() {
return fieldList.stream().map(field -> new ArrowCell(field, currentRow));
}
public boolean hasNextCell() {
return fieldIndex < fieldList.size();
}
public void resetCellIndex() {
this.fieldIndex = 0;
}
}
@@ -0,0 +1,84 @@
/*
* 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.common.entity.dto;
import static io.swagger.v3.oas.annotations.media.Schema.AccessMode.READ_WRITE;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Alarm Report Content Entity
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Alarm Report Content Entity")
public class AlertReport {
@Schema(title = "Alert record saas index ID")
private String alertId;
@Schema(title = "Alert Name")
private String alertName;
@Schema(title = "Alarm evaluation interval")
private Integer alertDuration;
@Schema(title = "Time when the log service receives the alarm message",
description = "Time when the log service receives the alarm message",
example = "1694589491000", accessMode = READ_WRITE)
private long alertTime;
@Schema(title = "Alarm priority. "
+ "0: high emergency alarm red "
+ "1: medium critical serious alarm Orange "
+ "2: low warning warning alarm yellow",
description = "Alarm priority. 0: high emergency alarm red "
+ "1: medium critical serious alarm Orange "
+ "2: low warning warning alarm yellow",
example = "1", accessMode = READ_WRITE)
private Integer priority;
@Schema(title = "Alarm type. 0: the default 1 is business system exception reporting",
description = "Alarm type. 0: the default 1 is business system exception reporting",
example = "0", accessMode = READ_WRITE)
private Integer reportType;
@Schema(title = "Alarm tag information",
description = "Alarm label information((monitorId:xxx,monitorName:xxx))",
example = "{\"key1\":\"value1\"}", accessMode = READ_WRITE)
private Map<String, String> labels;
@Schema(title = " Alarm marking (monitorId:xxx,monitorName:xxx)",
description = "Alarm labeling",
example = "{\"key1\":\"value1\"}"
, accessMode = READ_WRITE)
private Map<String, String> annotations;
@Schema(title = " Alarm content",
description = "Content of alarm",
example = "External alarm content",
accessMode = READ_WRITE)
private String content;
}
@@ -0,0 +1,47 @@
/*
* 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.common.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.hertzbeat.common.constants.CommonConstants;
/**
* collector info
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "collector info")
public class CollectorInfo {
@NotNull
private String name;
private String ip;
private String version;
@NotNull
private String mode = CommonConstants.MODE_PUBLIC;
}
@@ -0,0 +1,48 @@
/*
* 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.common.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* monitoring metrics field
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Monitoring Metrics Field")
public class Field {
@Schema(title = "Metrics Field Name")
private String name;
@Schema(title = "Field Type0-number 1-string")
private Byte type;
@Schema(title = "Field Unit")
private String unit;
@Schema(title = "Whether is a label")
private Boolean label;
}
@@ -0,0 +1,79 @@
/*
* 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.common.entity.dto;
import jakarta.annotation.Nullable;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.hertzbeat.common.constants.ImportTaskStatusEnum;
import org.apache.hertzbeat.common.constants.ManagerEventTypeEnum;
import org.apache.hertzbeat.common.constants.NotifyLevelEnum;
/**
* Import task message
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class ImportTaskMessage extends ManagerMessage {
/**
* Task name
*/
@NotNull
private String taskName;
/**
* Progress, expressed as a percentage
*/
@Nullable
private Integer progress;
/**
* Task Status,
* @see ImportTaskStatusEnum
*/
@NotNull
private String status;
/**
* If Fail, the error message
*/
@Nullable
private String errMsg;
public ImportTaskMessage(String notifyLevel, String managerEventType, String taskName, @Nullable Integer progress, String status, @Nullable String errMsg){
super(notifyLevel, managerEventType);
this.taskName = taskName;
this.progress = progress;
this.status = status;
this.errMsg = errMsg;
}
public static ManagerMessage createInProgressMessage(String taskName, Integer process){
return new ImportTaskMessage(NotifyLevelEnum.INFO.getValue(), ManagerEventTypeEnum.IMPORT_TASK_EVENT.getValue(), taskName, process, ImportTaskStatusEnum.IN_PROGRESS.getValue(), null);
}
public static ManagerMessage createCompletedMessage(String taskName){
return new ImportTaskMessage(NotifyLevelEnum.SUCCESS.getValue(), ManagerEventTypeEnum.IMPORT_TASK_EVENT.getValue(), taskName, null, ImportTaskStatusEnum.COMPLETED.getValue(), null);
}
public static ManagerMessage createFailedMessage(String taskName, String errMsg){
return new ImportTaskMessage(NotifyLevelEnum.ERROR.getValue(), ManagerEventTypeEnum.IMPORT_TASK_EVENT.getValue(), taskName, null, ImportTaskStatusEnum.FAILED.getValue(), errMsg);
}
}
@@ -0,0 +1,60 @@
/*
* 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.common.entity.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Email account configuration dto
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MailServerConfig {
@NotNull(message = "Type cannot be empty")
private Integer type;
@NotBlank(message = "Mail host cannot be empty")
private String emailHost;
@NotBlank(message = "Username cannot be empty")
@Email
private String emailUsername;
@NotBlank(message = "Password cannot be empty")
private String emailPassword;
@NotNull(message = "Mail port cannot be null")
@Max(message = "Mail port must be less than or equal to 65535", value = 65535)
@Min(message = "Mail port must be greater than or equal to 1", value = 1)
private Integer emailPort;
private boolean emailSsl = true;
private boolean emailStarttls = false;
private boolean enable = true;
}
@@ -0,0 +1,42 @@
/*
* 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.common.entity.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Manager Message Entity
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ManagerMessage {
/**
* Notify Level
* @see org.apache.hertzbeat.common.constants.NotifyLevelEnum
*/
private String notifyLevel;
/**
* Manager Event Type
* @see org.apache.hertzbeat.common.constants.ManagerEventTypeEnum
*/
private String managerEventType;
}
@@ -0,0 +1,90 @@
/*
* 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.common.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.apache.hertzbeat.common.constants.CommonConstants;
/**
* Unified message structure definition for front and back ends
* <p>
* {
* data:{....},
* msg: message,
* code: 3432
* }
*/
@Data
@Schema(description = "Common message structure")
public class Message<T> {
/**
* message body data
*/
@Schema(description = "Response Data")
private T data;
/**
* exception message when error happen or success message
*/
@Schema(title = "Other Message")
private String msg;
/**
* response code, not http code
*/
@Schema(title = "Response Code")
private byte code = CommonConstants.SUCCESS_CODE;
public static <T> Message<T> success() {
return new Message<>();
}
public static <T> Message<T> success(String msg) {
return new Message<>(msg);
}
public static <T> Message<T> fail(byte code, String msg) {
return new Message<>(code, msg);
}
public static <T> Message<T> success(T data) {
return new Message<>(data);
}
public static <T> Message<T> successWithData(T data) {
return new Message<>(data);
}
private Message() {
}
private Message(String msg) {
this.msg = msg;
}
private Message(byte code, String msg) {
this.code = code;
this.msg = msg;
}
private Message(T data) {
this.data = data;
}
}
@@ -0,0 +1,54 @@
/*
* 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.common.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Monitoring Metrics Data
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Monitoring Metrics Data")
public class MetricsData {
@Schema(title = "Monitoring Task ID")
private Long id;
@Schema(title = "Monitoring Type")
private String app;
@Schema(title = "Monitoring Metrics")
private String metrics;
@Schema(title = "Latest Collect Time")
private Long time;
@Schema(description = "Monitoring Metrics fields")
private List<Field> fields;
@Schema(description = "Monitoring Metrics DataRow")
private List<ValueRow> valueRows;
}
@@ -0,0 +1,53 @@
/*
* 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.common.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
/**
* Metric History Range Query Data
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Metric History Range Query Data")
public class MetricsHistoryData {
@Schema(title = "Monitor Instance (e.g., ip:port or domain)")
private String instance;
@Schema(title = "Monitoring Type")
private String app;
@Schema(title = "Monitoring Metrics")
private String metrics;
@Schema(title = "Monitoring Metrics Field")
private Field field;
@Schema(description = "Monitoring Range Query Data tags<==>values")
private Map<String, List<Value>> values;
}
@@ -0,0 +1,54 @@
/*
* 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.common.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Model Provider Configuration
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "LLM Model Provider configuration")
public class ModelProviderConfig {
@Schema(title = "Model type, text-generate, vision")
private String type;
@Schema(title = "Model Provider code, like openai, zai, bigmodel")
private String code;
@Schema(title = "custom the provider server base url")
private String baseUrl;
@Schema(title = "use the model id name, eg: gpt-5, glm-4.6")
private String model;
@Schema(title = "API Key", description = "API key", example = "sk-...")
@NotBlank(message = "API Key cannot be empty when enabled")
private String apiKey;
@Schema(title = "Participation Model", description = "model for participation", example = "PROTECTED")
@NotBlank(message = "API Key cannot be empty when enabled")
private String participationModel;
}
@@ -0,0 +1,100 @@
/*
* 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.common.entity.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.gson.JsonObject;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import tools.jackson.core.JsonParser;
import tools.jackson.databind.DeserializationContext;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ValueDeserializer;
import tools.jackson.databind.annotation.JsonDeserialize;
/**
* prometheus vector or matrix entity
*/
@lombok.Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@ToString
@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public class PromVectorOrMatrix {
private String status;
private Data data;
/**
* PromVectorOrMatrix.Data
*/
@lombok.Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@ToString
public static class Data {
String resultType;
List<Result> result;
}
/**
* PromVectorOrMatrix.Result
*/
@lombok.Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@ToString
public static class Result {
@JsonDeserialize(using = MetricJsonObjectDeserializer.class)
JsonObject metric;
List<Object> value;
List<List<Object>> values;
}
/**
* MetricJsonObjectDeserializer
*/
@EqualsAndHashCode(callSuper = true)
@lombok.Data
@NoArgsConstructor
@Accessors(chain = true)
public static class MetricJsonObjectDeserializer extends ValueDeserializer<JsonObject> {
@Override
public JsonObject deserialize(JsonParser jp, DeserializationContext ctxt) {
JsonNode node = jp.objectReadContext().readTree(jp);
JsonObject metric = new JsonObject();
if (node != null && node.isObject()) {
node.properties().forEach(entry ->
metric.addProperty(entry.getKey(), entry.getValue().asString())
);
}
return metric;
}
}
}
@@ -0,0 +1,40 @@
/*
* 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.common.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* collector info
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "manager server info")
public class ServerInfo {
/**
* the aes secret key value for aes encode decode
*/
private String aesSecret;
}
@@ -0,0 +1,62 @@
/*
* 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.common.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Monitoring Metrics Data
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Monitoring Metrics Data")
public class Value {
public Value(String origin) {
this.origin = origin;
}
public Value(String origin, long time) {
this.origin = origin;
this.time = time;
}
@Schema(title = "Origin Value")
private String origin;
@Schema(title = "Mean Avg Value")
private String mean;
@Schema(title = "Median Value, Not Support Now")
private String median;
@Schema(title = "Min Value")
private String min;
@Schema(title = "Max Value")
private String max;
@Schema(title = "Collect Data Time(effect when history range data)")
private Long time;
}
@@ -0,0 +1,43 @@
/*
* 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.common.entity.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Monitoring Metrics DataRow
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Monitoring Metrics DataRow")
public class ValueRow {
@Schema(title = "Value Row Labels")
private Map<String, String> labels;
@Schema(description = "Monitoring Metrics DataRow")
private List<Value> values;
}
@@ -0,0 +1,59 @@
/*
* 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.common.entity.dto.query;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Metric History Range Query Data
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Query Request Data")
public class DatasourceQuery {
@Schema(title = "Ref Id, unique id for the query")
private String refId;
@Schema(title = "datasource name")
private String datasource;
@Schema(title = "query expr, like prometheus query")
private String expr;
@Schema(title = "query expr type, like promql or sql or influxql")
private String exprType;
@Schema(title = "query range type, like range or instant")
private String timeType;
@Schema(title = "query range start time")
private Long start;
@Schema(title = "query range end time")
private Long end;
@Schema(title = "query time step, like 5m or 1h")
private String step;
}
@@ -0,0 +1,103 @@
/*
* 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.common.entity.dto.query;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Metric History Range Query Data
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Metric Query Data")
public class DatasourceQueryData {
@Schema(title = "Ref Id, unique id for the query")
private String refId;
@Schema(title = "query status code, 200 for success, other for error")
private Integer status;
@Schema(title = "query error message")
private String msg;
@Schema(title = "query result data frames")
private List<SchemaData> frames;
/**
* Schema Data
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public static final class SchemaData {
@Schema(title = "Metric Schema")
private MetricSchema schema;
@Schema(title = "metrics row values, first is the timestamp-ts", example = "[[29,32,44],[32,34,true]]")
private List<Object[]> data;
}
/**
* Metric Schema
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public static final class MetricSchema {
@Schema(title = "Metrics Field")
private List<MetricField> fields;
@Schema(title = "This frame labels")
private Map<String, String> labels;
@Schema(title = "Meta Information")
private Map<String, String> meta;
}
/**
* Metric Field
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public static final class MetricField {
@Schema(title = "Metric Field Name")
private String name;
@Schema(title = "Field Type: number, string, time, bool")
private String type;
@Schema(title = "Field Unit: %, Mb, Kbps etc.")
private String unit;
}
}
@@ -0,0 +1,55 @@
/*
* 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.common.entity.dto.sms;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Alibaba Cloud SMS configuration properties
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AlibabaSmsProperties {
/**
* Alibaba Cloud access key id
*/
@NotBlank(message = "AccessKeyId cannot be empty")
private String accessKeyId;
/**
* Alibaba Cloud access key secret
*/
@NotBlank(message = "AccessKeySecret cannot be empty")
private String accessKeySecret;
/**
* SMS signature
*/
@NotBlank(message = "SignName cannot be empty")
private String signName;
/**
* SMS template Code
*/
@NotBlank(message = "TemplateCode cannot be null")
private String templateCode;
}
@@ -0,0 +1,46 @@
/*
* 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.common.entity.dto.sms;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* AWS Cloud SMS configuration properties
*/
@Data
public class AwsSmsProperties {
/**
* AWS Cloud access key id
*/
@NotBlank(message = "AccessKeyId cannot be empty")
private String accessKeyId;
/**
* AWS Cloud access key secret
*/
@NotBlank(message = "AccessKeySecret cannot be empty")
private String accessKeySecret;
/**
* AWS Cloud region
*/
@NotBlank(message = "region cannot be empty")
private String region;
}
@@ -0,0 +1,73 @@
/*
* 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.common.entity.dto.sms;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Framework-agnostic SMS runtime configuration.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SmsConfig {
/**
* whether to enable SMS, default is false
*/
private boolean enable = false;
/**
* sms service provider
*/
@NotBlank(message = "Type cannot be empty")
private String type;
/**
* Tencent cloud SMS configuration
*/
private TencentSmsProperties tencent;
/**
* Aliyun SMS configuration
*/
private AlibabaSmsProperties alibaba;
/**
* UniSMS configuration
*/
private UniSmsProperties unisms;
/**
* Aws configuration
*/
private AwsSmsProperties aws;
/**
* Twilio SMS configuration
*/
private TwilioSmsProperties twilio;
/**
* Smslocal SMS configuration
*/
private SmslocalSmsProperties smslocal;
}
@@ -0,0 +1,37 @@
/*
* 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.common.entity.dto.sms;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Smslocal SMS Properties
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SmslocalSmsProperties {
/**
* SmsLocal account api key
*/
private String apiKey;
}
@@ -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.common.entity.dto.sms;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Tencent Cloud SMS properties
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TencentSmsProperties {
/**
* Tencent cloud account secret id
*/
@NotBlank(message = "SecretId cannot be empty")
private String secretId;
/**
* Tencent cloud account secret key
*/
@NotBlank(message = "SecretKey cannot be empty")
private String secretKey;
/**
* SMS app id
*/
@NotBlank(message = "AppId cannot be null")
private String appId;
/**
* SMS signature
*/
@NotBlank(message = "SignName cannot be empty")
private String signName;
/**
* SMS template ID
*/
@NotBlank(message = "templateId cannot be null")
private String templateId;
}
@@ -0,0 +1,49 @@
/*
* 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.common.entity.dto.sms;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Twilio SMS configuration properties
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TwilioSmsProperties {
/**
* Twilio Account SID
*/
@NotBlank(message = "Account SID cannot be empty")
private String accountSid;
/**
* Twilio Auth Token
*/
@NotBlank(message = "Auth Token cannot be empty")
private String authToken;
/**
* Twilio Issued Phone Number
*/
@NotBlank(message = "Twilio Phone Number cannot be empty")
private String twilioPhoneNumber;
}
@@ -0,0 +1,60 @@
/*
* 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.common.entity.dto.sms;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* UniSMS properties
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UniSmsProperties {
/**
* UniSMS access key id
*/
@NotBlank(message = "accessKeyId cannot be empty")
private String accessKeyId;
/**
* UniSMS access key secret, required for HMAC mode
*/
private String accessKeySecret;
/**
* SMS signature
*/
@NotBlank(message = "signature cannot be null")
private String signature;
/**
* SMS template ID
*/
@NotBlank(message = "templateId cannot be null")
private String templateId;
/**
* Authentication mode: simple or hmac, default is simple
*/
@NotBlank(message = "authMode cannot be null")
private String authMode = "simple";
}
@@ -0,0 +1,54 @@
/*
* 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.common.entity.job;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Monitoring configuration parameter properties and values
* During the process, you need to replace the content with the identifier ^_^key^_^
* in the protocol configuration parameter with the real value in the configuration parameter
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Configmap implements Serializable {
/**
* Parameter key, replace the content with the identifier ^^_key_^^ in the protocol
* configuration parameter with the real value in the configuration parameter
*/
private String key;
/**
* parameter value
*/
private Object value;
/**
* Parameter type
* 0: number 1: string 2: encrypted string 3: json string mapped by map
* number,string,secret
*/
private byte type = 1;
}
@@ -0,0 +1,375 @@
/*
* 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.common.entity.job;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.hertzbeat.common.entity.message.CollectRep;
import org.apache.hertzbeat.common.util.JsonUtil;
/**
* Collect task details.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Slf4j
public class Job {
/**
* Task Job id.
*/
private long id;
/**
* Tenant id.
*/
private long tenantId = 0;
/**
* Monitoring Task ID.
*/
private long monitorId;
/**
* metadata info bind with this job
* eg: instancename, instancehost
*/
private Map<String, String> metadata;
/**
* bind labels.
*/
private Map<String, String> labels;
/**
* bind annotations.
*/
private Map<String, String> annotations;
/**
* Is hide this app in main menus layout, only for app type, default true.
*/
private boolean hide = true;
/**
* Large categories of monitoring
* service-application service monitoring db-database
* monitoring custom-custom monitoring os-operating system monitoring...
*/
private String category;
/**
* Type of monitoring eg: linux | mysql | jvm.
*/
private String app;
/**
* The internationalized name of the monitoring type
* PING CONNECT.
*/
private Map<String, String> name;
/**
* The description and help of the monitoring type
* PING CONNECT - You can use the IP address or
* domain address of the peer service to monitor the PING connectivity between the local network and the peer network.
*/
private Map<String, String> help;
/**
* The monitor help link.
*/
private Map<String, String> helpLink;
/**
* Task dispatch start timestamp.
*/
private long timestamp;
/**
* Default task collection time interval (unit: second) eg: 30,60,600.
*/
private long defaultInterval = 600L;
/**
* Refresh time list for one cycle of the job.
*/
private ConcurrentLinkedDeque<Long> intervals;
/**
* Whether it is a recurring periodic task true is yes, false is no.
*/
private boolean isCyclic = false;
/**
* monitor input need params.
*/
private List<RuntimeParamDefine> params;
/**
* Metrics configuration eg: cpu memory.
*/
private List<Metrics> metrics;
/**
* Monitoring configuration parameter properties and values eg: username password timeout host.
*/
private List<Configmap> configmap;
/**
* Whether it is a service discovery job, true is yes, false is no.
*/
private boolean isSd = false;
/**
* Whether to use the Prometheus proxy.
*/
private boolean prometheusProxyMode = false;
/**
* Scheduling type: interval or cron.
*/
private String scheduleType = "interval";
/**
* Cron expression for scheduling, used when scheduleType is "cron".
*/
private String cronExpression = null;
/**
* the collect data response metrics as env configmap for other collect use. ^o^xxx^o^
*/
@JsonIgnore
private Map<String, Configmap> envConfigmaps;
/**
* collector use - timestamp when the task was scheduled by the time wheel.
*/
@JsonIgnore
private transient long dispatchTime;
/**
* collector usage - metric group task execution priority view
* 0 - availability
* 1 - cpu | memory
* 2 - health
* 3 - otherMetrics
* ....
* 126 - otherMetrics
* 127 - lastPriorMetrics
*/
@JsonIgnore
private transient LinkedList<Set<Metrics>> priorMetrics;
/**
* collector use - Temporarily store one-time task metrics response data.
*/
@JsonIgnore
private transient List<CollectRep.MetricsData> responseDataTemp;
/**
* collector use - construct to initialize metrics execution view.
*/
public synchronized void constructPriorMetrics() {
long now = System.currentTimeMillis();
Map<Byte, List<Metrics>> currentCollectMetrics = metrics.stream()
.filter(metrics -> (now >= metrics.getCollectTime() + metrics.getInterval() * 1000))
.peek(metric -> {
metric.setCollectTime(now);
// Determine whether to configure aliasFields If not, configure the default
if ((metric.getAliasFields() == null || metric.getAliasFields().isEmpty()) && metric.getFields() != null) {
metric.setAliasFields(metric.getFields().stream().map(Metrics.Field::getField).collect(Collectors.toList()));
}
// Set the default metrics execution priority, if not filled, the default last priority
if (metric.getPriority() == null) {
metric.setPriority(Byte.MAX_VALUE);
}
})
.collect(Collectors.groupingBy(Metrics::getPriority));
// the current collect metrics can not empty, if empty, add a default availability metrics
// due the metric collect is trigger by the previous metric collect
if (currentCollectMetrics.isEmpty()) {
Optional<Metrics> defaultMetricOption = metrics.stream().filter(metric -> metric.getPriority() == 0).findFirst();
if (defaultMetricOption.isPresent()) {
Metrics defaultMetric = defaultMetricOption.get();
defaultMetric.setCollectTime(now);
currentCollectMetrics.put((byte) 0, Collections.singletonList(defaultMetric));
} else {
log.error("metrics must has one priority 0 metrics at least.");
}
}
// Construct a linked list of task execution order of the metrics
priorMetrics = new LinkedList<>();
currentCollectMetrics.values().forEach(metric -> {
Set<Metrics> metricsSet = Collections.synchronizedSet(new HashSet<>(metric));
priorMetrics.add(metricsSet);
});
priorMetrics.sort(Comparator.comparing(e -> {
Optional<Metrics> metric = e.stream().findAny();
if (metric.isPresent()) {
return metric.get().getPriority();
}
return Byte.MAX_VALUE;
}));
envConfigmaps = new HashMap<>(8);
}
/**
* 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
* 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.
* The set returned empty means that there are still indicator collection tasks unfinished at the current level,
* and the task collection at the next level cannot be carried out
* Returns a set of data representation: get the next set of priority index collcet tasks
*/
public synchronized Set<Metrics> getNextCollectMetrics(Metrics metrics, boolean first) {
if (priorMetrics == null || priorMetrics.isEmpty()) {
return null;
}
Set<Metrics> metricsSet = priorMetrics.peek();
if (first) {
if (metricsSet.isEmpty()) {
log.error("metrics must has one [availability] metrics at least.");
}
return metricsSet;
}
if (metrics == null) {
log.error("metrics can not null when not first get");
return null;
}
if (!metricsSet.remove(metrics)) {
log.warn("Job {} appId {} app {} metrics {} remove empty error in priorMetrics.",
id, monitorId, app, metrics.getName());
}
if (metricsSet.isEmpty()) {
priorMetrics.poll();
if (priorMetrics.isEmpty()) {
return null;
}
Set<Metrics> source = priorMetrics.peek();
return new HashSet<>(source);
}
return Collections.emptySet();
}
public void addCollectMetricsData(CollectRep.MetricsData metricsData) {
if (responseDataTemp == null) {
responseDataTemp = new LinkedList<>();
}
responseDataTemp.add(metricsData);
}
public Map<String, Configmap> getEnvConfigmaps() {
return envConfigmaps;
}
public void addEnvConfigmaps(Map<String, Configmap> envConfigmaps) {
if (this.envConfigmaps == null) {
this.envConfigmaps = envConfigmaps;
} else {
this.envConfigmaps.putAll(envConfigmaps);
}
}
@Override
public Job clone() {
// deep clone
return JsonUtil.fromJson(JsonUtil.toJson(this), getClass());
}
public void initIntervals() {
List<Long> metricsIntervals = new LinkedList<>();
for (Metrics metrics: getMetrics()) {
metrics.setCollectTime(0L);
if (metrics.getInterval() <= 0) {
metrics.setInterval(defaultInterval);
}
if (!metricsIntervals.contains(metrics.getInterval())) {
metricsIntervals.add(metrics.getInterval());
}
}
generateMetricsIntervals(metricsIntervals);
}
/**
* The greatest common divisor.
*/
public static long gcd(long a, long b) {
while (b != 0) {
long temp = b;
b = a % b;
a = temp;
}
return a;
}
/**
* The least common multiple.
*/
public static long lcm(List<Long> array) {
if (array != null && !array.isEmpty()) {
long result = array.get(0);
for (int i = 1; i < array.size(); i++) {
result = result / gcd(result, array.get(i)) * array.get(i);
}
return result;
}
return 0;
}
/**
* @param metricsIntervals A unique list composed of intervals for all metrics
* Generate a list of refresh intervals for metric collection.
*/
public synchronized void generateMetricsIntervals(List<Long> metricsIntervals) {
// 1. To find the least common multiple (LCM) of all metric refresh intervals
long lcm = lcm(metricsIntervals);
List<Long> refreshTimes = new LinkedList<>();
// 2. Calculate all possible refresh intervals in one round
for (long interval : metricsIntervals) {
for (long t = interval; t <= lcm; t += interval) {
if (!refreshTimes.contains(t)) {
refreshTimes.add(t);
}
}
}
// 3. Sort from smallest to largest
Collections.sort(refreshTimes);
// 4. Calculate the refresh interval list for Job's cycle
LinkedList<Long> intervals = new LinkedList<>();
intervals.add(refreshTimes.get(0));
for (int i = 1; i < refreshTimes.size(); i++) {
intervals.add(refreshTimes.get(i) - refreshTimes.get(i - 1));
}
setIntervals(new ConcurrentLinkedDeque<>(intervals));
}
public synchronized long getInterval() {
if (this.intervals != null && !this.intervals.isEmpty()) {
Long interval = this.intervals.removeFirst();
if (interval != null) {
this.intervals.addLast(interval);
return interval;
}
}
return getDefaultInterval();
}
}
@@ -0,0 +1,406 @@
/*
* 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.common.entity.job;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.hertzbeat.common.entity.job.protocol.DnsProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.DnsSdProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.FtpProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.HttpProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.EurekaSdProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.ConsulSdProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.ModbusProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.NacosSdProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.PlcProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.RegistryProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.IcmpProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.ImapProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.IpmiProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.JdbcProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.JmxProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.KafkaProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.MemcachedProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.MongodbProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.MqttProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.NebulaGraphProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.NginxProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.NgqlProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.NtpProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.Pop3Protocol;
import org.apache.hertzbeat.common.entity.job.protocol.PrometheusProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.PushProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.RedfishProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.RedisProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.RocketmqProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.S7Protocol;
import org.apache.hertzbeat.common.entity.job.protocol.ScriptProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.SmtpProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.SnmpProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.SshProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.TelnetProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.UdpProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.WebsocketProtocol;
import org.apache.hertzbeat.common.entity.message.CollectRep;
import org.apache.hertzbeat.common.entity.job.protocol.ZookeeperSdProtocol;
/**
* Details of the monitoring metrics collected
* eg: cpu | memory | health
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Slf4j
@SuppressWarnings("checkstyle:MemberName")
public class Metrics {
/**
* public property-name eg: cpu | memory | health
*/
private String name;
/**
* metrics name's i18n value
* zh-CN: CPU信息
* en-US: CPU Info
*/
private Map<String, String> i18n;
/**
* collect protocol eg: sql, ssh, http, telnet, wmi, snmp, sdk
*/
private String protocol;
/**
* Range (0-127) metrics scheduling priority, the smaller the value, the higher the priority
* The collection task of the next priority metrics will be scheduled only after the scheduled collection with the higher priority is completed.
* The default priority of the availability metrics is 0, and the range of other common metrics is 1-127, that is,
* the subsequent metrics tasks will only be scheduled after the availability is collected successfully.
*/
private Byte priority;
/**
* The latest collect time
*/
private long collectTime;
/**
* Customize interval of metrics
* If not set, the collection interval set in the front-end page will be used by default
*/
private long interval;
/**
* Is it visible true or false
* if false, web ui will not see this metrics.
*/
private boolean visible = true;
/**
* Public attribute - collection and monitoring final result attribute set eg: speed | times | size
*/
private List<Field> fields;
/**
* Public attribute - collection and monitoring pre-query attribute set eg: size1 | size2 | speedSize
*/
private List<String> aliasFields;
/**
* Public attribute - expression calculation, map the pre-query attribute (pre Fields)
* with the final attribute (fields), and calculate the final attribute (fields) value
* eg: size = size1 + size2, speed = speedSize
*/
private List<String> calculates;
/**
* filters
* eg: class == 9 && name != 'java'
*/
private List<String> filters;
/**
* unit conversion expr
* eg:
* - heap_used=B->MB
* - heap_total=B->MB
* - disk_free=B->GB
* - disk_total=B->GB
*/
private List<String> units;
/**
* Monitoring configuration information using the http protocol
*/
private HttpProtocol http;
/**
* Monitoring configuration information for ping using the icmp protocol
*/
private IcmpProtocol icmp;
/**
* Monitoring configuration information using the telnet protocol
*/
private TelnetProtocol telnet;
/**
* Monitoring configuration information using the public smtp protocol
*/
private SmtpProtocol smtp;
/**
* Monitoring configuration information using the public ntp protocol
*/
private NtpProtocol ntp;
/**
* Monitoring configuration information using the websocket protocol
*/
private WebsocketProtocol websocket;
/**
* Monitoring configuration information using the memcached protocol
*/
private MemcachedProtocol memcached;
/**
* Monitoring configuration information using the nebulaGraph protocol
*/
private NebulaGraphProtocol nebulaGraph;
/**
* Use udp implemented by socket for service port detection configuration information
*/
private UdpProtocol udp;
/**
* Database configuration information implemented using the public jdbc specification
*/
private JdbcProtocol jdbc;
/**
* Monitoring configuration information using the public ssh protocol
*/
private SshProtocol ssh;
/**
* Monitoring configuration information using the public redis protocol
*/
private RedisProtocol redis;
/**
* Monitoring configuration information using the public mongodb protocol
*/
private MongodbProtocol mongodb;
/**
* Get monitoring configuration information using public JMX protocol
*/
private JmxProtocol jmx;
/**
* Monitoring configuration information using the public snmp protocol
*/
private SnmpProtocol snmp;
/**
* Monitoring configuration information using the public ftp protocol
*/
private FtpProtocol ftp;
/**
* Monitoring configuration information using the public rocketmq protocol
*/
private RocketmqProtocol rocketmq;
/**
* Monitoring configuration information using push style
*/
private PushProtocol push;
/**
* Monitoring configuration information using the public prometheus protocol
*/
private PrometheusProtocol prometheus;
/**
* Monitoring configuration information using the public DNS protocol
*/
private DnsProtocol dns;
/**
* Monitoring configuration information using the public Nginx protocol
*/
private NginxProtocol nginx;
/**
* Monitoring configuration information using the public pop3 protocol
*/
private Pop3Protocol pop3;
/**
* Monitoring configuration information using the public registry protocol
*/
private RegistryProtocol registry;
/**
* Monitoring configuration information using the public redfish protocol
*/
private RedfishProtocol redfish;
/**
* Monitoring configuration information using the public ngql protocol
*/
private NgqlProtocol ngql;
/**
* Monitoring configuration information using the public imap protocol
*/
private ImapProtocol imap;
/**
* Monitoring configuration information using the public script protocol
*/
private ScriptProtocol script;
/**
* Monitoring configuration information using the public mqtt protocol
*/
private MqttProtocol mqtt;
/**
* Monitoring configuration information using the public ipmi protocol
*/
private IpmiProtocol ipmi;
/**
* Monitoring configuration information using the public kafka protocol
*/
private KafkaProtocol kclient;
/**
* http sd protocol
*/
private HttpProtocol http_sd;
/**
* dns sd protocol
*/
private DnsSdProtocol dns_sd;
/**
* eureka sd protocol
*/
private EurekaSdProtocol eureka_sd;
/**
* consul sd protocol
*/
private ConsulSdProtocol consul_sd;
/**
* nacos sd protocol
*/
private NacosSdProtocol nacos_sd;
/*
* zookeeper sd protocol
*/
private ZookeeperSdProtocol zookeeper_sd;
/**
* Monitoring configuration information using the public plc protocol
*/
private PlcProtocol plc;
/**
* Monitoring configuration information using the public modBus protocol
*/
private ModbusProtocol modbus;
/**
* Monitoring configuration information using the public s7 protocol
*/
private S7Protocol s7;
/**
* collector use - Temporarily store subTask metrics response data
*/
@JsonIgnore
private transient AtomicReference<CollectRep.MetricsData.Builder> subTaskDataRef;
/**
* collector use - Temporarily store subTask running num
*/
@JsonIgnore
private transient AtomicInteger subTaskNum;
/**
* collector use - Temporarily store subTask id
*/
@JsonIgnore
private transient Integer subTaskId;
/**
* is has subTask
*
* @return true - has
*/
public boolean isHasSubTask() {
return subTaskNum != null;
}
/**
* consume subTask
*
* @param metricsData response data
* @return is last task?
*/
public boolean consumeSubTaskResponse(CollectRep.MetricsData metricsData) {
synchronized (subTaskNum) {
int index = subTaskNum.decrementAndGet();
if (subTaskDataRef.get() == null) {
subTaskDataRef.set(CollectRep.MetricsData.newBuilder(metricsData));
} else {
if (metricsData.getValuesCount() >= 1) {
CollectRep.MetricsData.Builder dataBuilder = subTaskDataRef.get();
for (CollectRep.ValueRow valueRow : metricsData.getValues()) {
if (valueRow.getColumnsCount() == dataBuilder.getFieldsCount()) {
dataBuilder.addValueRow(valueRow);
} else {
log.error("consume subTask data value not mapping filed");
}
}
subTaskDataRef.set(dataBuilder);
}
}
metricsData.close();
return index == 0;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Metrics metrics = (Metrics) o;
return name.equals(metrics.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
/**
* Metrics.Field
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public static class Field {
/**
* Metric name
*/
private String field;
/**
* metric field name's i18n value
* CPU Version
*/
private Map<String, String> i18n;
/**
* Metric type 0-number: number 1-string: string
*/
private byte type = 1;
/**
* Whether this field is the label
*/
private boolean label = false;
/**
* Metric unit
*/
private String unit;
}
}
@@ -0,0 +1,76 @@
/*
* 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.common.entity.job;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Framework-agnostic parameter definition used by runtime templates and jobs.
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RuntimeParamDefine {
private String app;
private Map<String, String> name;
private String field;
private String type;
private boolean required = false;
private String defaultValue;
private String placeholder;
private String range;
private Short limit;
private List<Option> options;
private String keyAlias;
private String valueAlias;
private boolean hide = false;
private Map<String, List<Object>> depend;
/**
* Runtime option definition.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public static final class Option {
private String label;
private String value;
}
}
@@ -0,0 +1,87 @@
/*
* 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.common.entity.job;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.hertzbeat.common.entity.job.protocol.CommonRequestProtocol;
import org.apache.hertzbeat.common.entity.job.protocol.Protocol;
/**
* ssh tunnel
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SshTunnel implements CommonRequestProtocol, Protocol {
/**
* enable ssh tunnel
*/
private String enable = "false";
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Peer host port
*/
private String port = "22";
/**
* TIME OUT PERIOD
*/
private String timeout = "6000";
/**
* UserName
*/
private String username;
/**
* Password (optional)
*/
private String password;
/**
* Private key (optional)
*/
private String privateKey;
/**
* private key passphrase (optional)
*/
private String privateKeyPassphrase;
/**
* share connection session
*/
private String shareConnection = "true";
@Override
public boolean isInvalid() {
// todo add
return false;
}
}
@@ -0,0 +1,28 @@
/*
* 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.common.entity.job.protocol;
/**
* Define common field method for each protocol in Metrics.
*/
public interface CommonRequestProtocol {
void setHost(String host);
void setPort(String port);
}
@@ -0,0 +1,42 @@
/*
* 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.common.entity.job.protocol;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* consul sd protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ConsulSdProtocol implements Protocol{
private String host;
private String port;
public boolean isInvalid() {
return StringUtils.isAnyBlank(host, port);
}
}
@@ -0,0 +1,51 @@
/*
* 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.common.entity.job.protocol;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* Dns protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class DnsProtocol implements CommonRequestProtocol, Protocol {
private String dnsServerIP;
private String port;
private String address;
private String timeout;
private String tcp;
private String queryClass;
private String recordType;
@Override
public boolean isInvalid() {
return StringUtils.isAnyBlank(dnsServerIP, port, address, timeout, tcp, queryClass, recordType);
}
@Override
public void setHost(String host) {
this.address = host;
}
}
@@ -0,0 +1,60 @@
/*
* 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.common.entity.job.protocol;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
/**
* Dns protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class DnsSdProtocol implements Protocol {
private String host;
private String port;
private String recordType;
private String recordName;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isAnyBlank(recordType, recordName)) {
return true;
}
return !isValidRecordType(recordType);
}
private boolean isValidRecordType(String type) {
return type.matches("^(?i)(A|AAAA|CNAME|MX|TXT|NS|SRV|PTR|SOA|CAA)$");
}
}
@@ -0,0 +1,51 @@
/*
* 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.common.entity.job.protocol;
import java.net.URI;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* eureka sd protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class EurekaSdProtocol implements Protocol{
private String url;
@Override
public boolean isInvalid() {
if (StringUtils.isBlank(url)) {
return true;
}
try {
URI uri = URI.create(url.trim());
return StringUtils.isBlank(uri.getHost())
|| (!"http".equalsIgnoreCase(uri.getScheme()) && !"https".equalsIgnoreCase(uri.getScheme()));
} catch (Exception e) {
return true;
}
}
}
@@ -0,0 +1,89 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* ftp protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class FtpProtocol implements CommonRequestProtocol, Protocol {
/**
* Peer host ip or domain name
*/
private String host;
/**
* port number
*/
private String port;
/**
* Redis Username (optional)
*/
private String username;
/**
* Redis password(optional)
*/
private String password;
/**
* file catalog
*/
private String direction;
/**
* Timeout
*/
private String timeout;
/**
* Whether ftp uses link encryption ssl/tls, i.e. ftp or sftp
*
*/
private String ssl = "false";
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port) || StringUtils.isBlank(direction) || StringUtils.isBlank(timeout)) {
return true;
}
if (!CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(ssl)
&& !"true".equalsIgnoreCase(ssl)
&& !"false".equalsIgnoreCase(ssl)) {
return true;
}
return "true".equalsIgnoreCase(ssl) && StringUtils.isAnyBlank(username, password);
}
}
@@ -0,0 +1,173 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* http protocol configuration
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class HttpProtocol implements CommonRequestProtocol, Protocol {
/**
* Peer host ip or domain name
*/
private String host;
/**
* port number
*/
private String port;
/**
* http/https The url link to which the request was made
*/
private String url;
/**
* timeout
*/
private String timeout;
/**
* Whether http uses link encryption ssl/tls, i.e. http or https
*/
private String ssl = "false";
/**
* http request methods: get, post, put, delete, patch
*/
private String method;
/**
* http requests carry headers eg: Content-Type = application/json
*/
private Map<String, String> headers;
/**
* http requests carry query parameters eg: localhost:80/api? paramKey=value
*/
private Map<String, String> params;
/**
* The body carried by an http request
*/
private String payload;
/**
* authentication information
*/
private Authorization authorization;
/**
* How response data is parsed
* default - Own rules for parsing data
* json_path Custom jsonPath scripts <a href="https://www.jsonpath.cn/">...</a>
* xml_path Custom xmlPath scripts
* prometheus Prometheus Data Rules
*/
private String parseType;
/**
* Data parsing scripts exist when parsed as jsonPath or xmlPath
*/
private String parseScript;
/**
* Content keywords
*/
private String keyword;
/**
* http success status code. default 200
* successCode means what http response status code we consider it collect success.
*/
private List<String> successCodes;
/**
* Whether to enable URL encoding for the path. Default is true.
* When true, the URL path will be encoded. When false, the URL path will not be encoded.
*/
private String enableUrlEncoding = "true";
/**
* authentication information
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Authorization {
/**
* certification typeBearer Token, Basic Auth, Digest Auth
*/
private String type;
/**
* Bearer Token's token
*/
private String bearerTokenToken;
/**
* Basic Auth 's username
*/
private String basicAuthUsername;
/**
* Basic Auth 's password
*/
private String basicAuthPassword;
/**
* Digest Auth 's username
*/
private String digestAuthUsername;
/**
* Digest Auth 's password
*/
private String digestAuthPassword;
}
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(ssl) && !"true".equalsIgnoreCase(ssl) && !"false".equalsIgnoreCase(ssl)) {
return true;
}
if (StringUtils.isNotBlank(method) && !isValidHttpMethod(method)) {
return true;
}
if (StringUtils.isNotBlank(enableUrlEncoding)
&& !"true".equalsIgnoreCase(enableUrlEncoding)
&& !"false".equalsIgnoreCase(enableUrlEncoding)) {
return true;
}
return false;
}
private boolean isValidHttpMethod(String method) {
return method.equalsIgnoreCase("get")
|| method.equalsIgnoreCase("post")
|| method.equalsIgnoreCase("put")
|| method.equalsIgnoreCase("delete")
|| method.equalsIgnoreCase("patch")
|| method.equalsIgnoreCase("head")
|| method.equalsIgnoreCase("options");
}
}
@@ -0,0 +1,44 @@
/*
* 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.common.entity.job.protocol;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* Dns protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class HttpSdProtocol implements Protocol {
private String url;
@Override
public boolean isInvalid() {
if (StringUtils.isBlank(url)) {
return true;
}
return !url.matches("^(?i)https?://.+");
}
}
@@ -0,0 +1,59 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* ICMP (PING) PROTOCOL CONFIGURATION
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class IcmpProtocol implements CommonRequestProtocol, Protocol {
/**
* ip address or domain name of the peer host
*/
private String host;
/**
* time out period
*/
private String timeout;
@Override
public void setPort(String port) {
}
@Override
public boolean isInvalid() {
if (!validateIpDomain(host)) {
return true;
}
return StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout);
}
}
@@ -0,0 +1,87 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* imap protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ImapProtocol implements CommonRequestProtocol, Protocol {
/**
* Receiving server address
*/
private String host;
/**
* Receiving server port
*/
private String port;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* Whether to enable SSL encryption [Email Transmission]
*/
private String ssl = "false";
/**
* IMAP Email address
*/
private String email;
/**
* Authorization code
*/
private String authorize;
/**
* Mailbox folder name
*/
private String folderName;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isAnyBlank(timeout, email, authorize, folderName)) {
return true;
}
if (!CommonUtil.isNumeric(timeout)) {
return true;
}
return StringUtils.isNotBlank(ssl)
&& !"true".equalsIgnoreCase(ssl)
&& !"false".equalsIgnoreCase(ssl);
}
}
@@ -0,0 +1,95 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* IPMI2 Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class IpmiProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Peer host port
*/
private String port;
/**
* UserName
*/
private String username;
/**
* Password
*/
private String password;
/**
* command type: Chassis | Sensor | Raw
*/
private String type;
/**
* (Optional) only used for the specific id search
*/
private String id;
/**
* (Optional) only used when type is Raw
*/
private Field field;
static class Field {
}
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port) || Integer.parseInt(port) <= 0) {
return true;
}
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
return true;
}
if (StringUtils.isBlank(type)) {
return true;
}
if (!"Chassis".equalsIgnoreCase(type)
&& !"Sensor".equalsIgnoreCase(type)
&& !"Raw".equalsIgnoreCase(type)) {
return true;
}
return "Raw".equalsIgnoreCase(type) && field == null;
}
}
@@ -0,0 +1,105 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.entity.job.SshTunnel;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* Database configuration information implemented by the common jdbc specification
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class JdbcProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Port number
*/
private String port;
/**
* Database user name (optional)
*/
private String username;
/**
* Database Password (optional)
*/
private String password;
/**
* Database
*/
private String database;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* TYPE OF DATABASE mysql oracle ...
*/
private String platform;
/**
* SQL query mode oneRow, multiRow, columns, runScript
*/
private String queryType;
/**
* sql
*/
private String sql;
/**
* DATABASE LINK URL eg: jdbc:mysql://localhost:3306/usthe
*/
private String url;
/**
* reuse connection session
*/
private String reuseConnection = "true";
/**
* ssh tunnel
*/
private SshTunnel sshTunnel;
@Override
public boolean isInvalid() {
if (StringUtils.isBlank(url)) {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(reuseConnection)
&& !"true".equalsIgnoreCase(reuseConnection)
&& !"false".equalsIgnoreCase(reuseConnection)) {
return true;
}
return false;
}
}
@@ -0,0 +1,96 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* Jmx protocol
**/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class JmxProtocol implements CommonRequestProtocol, Protocol {
/**
* JMX host ip or domain name
*/
private String host;
/**
* The port number
*/
private String port;
/**
* enable ssl?
*/
private String ssl = "false";
/**
* Jmx username (optional)
*/
private String username;
/**
* Jmx password (optional)
*/
private String password;
/**
* jmx protocol custom collection metric address
*/
private String url;
/**
* The name of the type where the outer layer of the jmx metric is located
*/
private String objectName;
@Override
public boolean isInvalid() {
if (StringUtils.isBlank(objectName)) {
return true;
}
if (StringUtils.isNotBlank(ssl)
&& !"true".equalsIgnoreCase(ssl)
&& !"false".equalsIgnoreCase(ssl)) {
return true;
}
if (StringUtils.isNotBlank(username) && StringUtils.isBlank(password)) {
return true;
}
if (StringUtils.isBlank(username) && StringUtils.isNotBlank(password)) {
return true;
}
if (StringUtils.isNotBlank(url)) {
return !url.startsWith("service:jmx:rmi:") || url.contains("/stub/");
}
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
return Integer.parseInt(port) <= 0;
}
}
@@ -0,0 +1,79 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* Kafka protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class KafkaProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Port number
*/
private String port;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* COMMAND
*/
private String command;
/**
* Monitor internal topic
*/
private String monitorInternalTopic = "false";
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(monitorInternalTopic)
&& !"true".equalsIgnoreCase(monitorInternalTopic)
&& !"false".equalsIgnoreCase(monitorInternalTopic)) {
return true;
}
return false;
}
}
@@ -0,0 +1,52 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* memcached protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class MemcachedProtocol implements CommonRequestProtocol, Protocol {
/**
* MEMCACHED HOST IP ADDRESS OR DOMAIN NAME
*/
private String host;
/**
* Memcached host port (default: 11211)
*/
private String port;
@Override
public boolean isInvalid() {
return !validateIpDomain(host) || !validPort(port);
}
}
@@ -0,0 +1,74 @@
/*
* 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.common.entity.job.protocol;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
import java.util.List;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
/**
* Modbus Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ModbusProtocol implements Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Port number
*/
private String port;
private String driverName;
private String addressSyntax;
private String slaveId;
private String timeout;
private List<String> registerAddresses;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isAnyBlank(driverName, addressSyntax, slaveId)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
return registerAddresses == null || registerAddresses.isEmpty();
}
}
@@ -0,0 +1,96 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* Mongodb Protocol
* @version 1.0
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class MongodbProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Port number
*/
private String port;
/**
* Mongodb model
*/
private String model;
/**
* Mongodb User name (optional)
*/
private String username;
/**
* Mongodb Password (optional)
*/
private String password;
/**
* Mongodb database name (optional)
*/
private String database;
/**
* Mongodb Authentication Database name (optional)
*/
private String authenticationDatabase;
/**
* run command
*/
private String command;
/**
* TIME OUT PERIOD
*/
private String timeout;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
return false;
}
}
@@ -0,0 +1,161 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* mqtt protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class MqttProtocol implements CommonRequestProtocol, Protocol {
/**
* mqtt client id
*/
private String clientId;
/**
* mqtt username
*/
private String username;
/**
* mqtt password
*/
private String password;
/**
* mqtt host
*/
private String host;
/**
* mqtt port
*/
private String port;
/**
* mqtt protocol version
* MQTT,MQTTS
*/
private String protocol;
/**
* mqtt connect timeout
* the maximum time to wait for a connection to be established
*/
private String timeout;
/**
* mqtt keepalive
* between ping requests to the broker to keep the connection alive
*/
private String keepalive;
/**
* mqtt topic name
*/
private String topic;
/**
* mqtt publish message
*/
private String testMessage;
/**
* mqtt tls version
* TLSv1.2, TLSv1.3
*/
private String tlsVersion;
/**
* mqtt tls insecure skip verify server certificate
*/
private String insecureSkipVerify;
/**
* mqtt tls ca cert
*/
private String caCert;
/**
* mqtt tls enable mutual auth
*/
private String enableMutualAuth;
/**
* mqtt tls client cert
*/
private String clientCert;
/**
* mqtt tls client key
*/
private String clientKey;
/**
* Determine whether authentication is required
* @return true if it has auth info
*/
public boolean hasAuth() {
return StringUtils.isNotBlank(this.username) && StringUtils.isNotBlank(this.password);
}
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(keepalive) && !CommonUtil.isNumeric(keepalive)) {
return true;
}
if (StringUtils.isNotBlank(protocol)
&& !"MQTT".equalsIgnoreCase(protocol)
&& !"MQTTS".equalsIgnoreCase(protocol)) {
return true;
}
if (StringUtils.isNotBlank(tlsVersion)
&& !"TLSv1.2".equalsIgnoreCase(tlsVersion)
&& !"TLSv1.3".equalsIgnoreCase(tlsVersion)) {
return true;
}
if (StringUtils.isNotBlank(insecureSkipVerify)
&& !"true".equalsIgnoreCase(insecureSkipVerify)
&& !"false".equalsIgnoreCase(insecureSkipVerify)) {
return true;
}
if (StringUtils.isNotBlank(enableMutualAuth)
&& !"true".equalsIgnoreCase(enableMutualAuth)
&& !"false".equalsIgnoreCase(enableMutualAuth)) {
return true;
}
if (StringUtils.isNotBlank(username) && StringUtils.isBlank(password)) {
return true;
}
if (StringUtils.isBlank(username) && StringUtils.isNotBlank(password)) {
return true;
}
if ("true".equalsIgnoreCase(enableMutualAuth)) {
if (StringUtils.isBlank(clientCert) || StringUtils.isBlank(clientKey)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,74 @@
/*
* 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.common.entity.job.protocol;
import org.apache.commons.lang3.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Nacos Service Discovery Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NacosSdProtocol implements Protocol {
/**
* Nacos server host
*/
private String host;
/**
* Nacos server port
*/
private String port;
/**
* Nacos namespace
*/
private String namespace;
/**
* Nacos username for authentication
*/
private String username;
/**
* Nacos password for authentication
*/
private String password;
/**
* Nacos Service Name
*/
private String serviceName;
/**
* Nacos Group Name
*/
private String groupName;
/**
* Check if the essential protocol parameters are invalid
* @return true if essential parameters are missing
*/
public boolean isInvalid() {
return StringUtils.isAnyBlank(host, port);
}
}
@@ -0,0 +1,79 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* NebulaGraph Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NebulaGraphProtocol implements CommonRequestProtocol, Protocol {
/**
* NebulaGraph host ip or domain name
*/
private String host;
/**
* NebulaGraph Graph service port default is 19669
* NebulaGraph Storage service port is 19779 by default
*/
private String port;
/**
* NebulaGraph Graph service monitoring API is /stats
* NebulaGraph Storage's service monitoring API is /rocksdb_stats
*/
private String url;
/**
* NebulaGraph monitors time intervals
*/
private String timePeriod;
/**
* TIMEOUT PERIOD
*/
private String timeout;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(timePeriod) && !CommonUtil.isNumeric(timePeriod)) {
return true;
}
return false;
}
}
@@ -0,0 +1,82 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* nginx protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NginxProtocol implements CommonRequestProtocol, Protocol {
/**
* nginx Host ip address or domain name
*/
private String host;
/**
* NGINX HOST PORT
*/
private String port;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* Monitor module page url
*/
private String url;
/**
* Whether nginx uses link encryption ssl/tls, i.e. http or https
*/
private String ssl = "false";
/**
* Validates the relevant parameters
* @return is invalid true or false
*/
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(ssl)
&& !"true".equalsIgnoreCase(ssl)
&& !"false".equalsIgnoreCase(ssl)) {
return true;
}
return false;
}
}
@@ -0,0 +1,98 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import java.util.List;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* NGQL protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NgqlProtocol implements CommonRequestProtocol, Protocol {
private static final Set<String> VALID_PARSE_TYPES = Set.of("oneRow", "multiRow", "filterCount", "columns");
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Peer host port
*/
private String port;
/**
* UserName
*/
private String username;
/**
* Password
*/
private String password;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* SpaceName in nebula graph
*/
private String spaceName;
/**
* ngql or open cypher
*/
private List<String> commands;
/**
* how to parse data
*/
private String parseType;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isAnyBlank(username, password, timeout, parseType)) {
return true;
}
if (!VALID_PARSE_TYPES.contains(parseType) || !CommonUtil.isNumeric(timeout)) {
return true;
}
if (commands == null || commands.isEmpty()) {
return true;
}
return commands.stream().anyMatch(StringUtils::isBlank);
}
}
@@ -0,0 +1,63 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* Ntp Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NtpProtocol implements CommonRequestProtocol, Protocol {
/**
* NTP host ip address or domain name
*/
private String host;
/**
* NTP host port
*/
private String port;
/**
* TIME OUT PERIOD
*/
private String timeout;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host)) {
return true;
}
if (StringUtils.isNotBlank(port) && !validPort(port)) {
return true;
}
return StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout);
}
}
@@ -0,0 +1,74 @@
/*
* 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.common.entity.job.protocol;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
import java.util.List;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
/**
* Plc Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PlcProtocol implements Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Port number
*/
private String port;
private String driverName;
private String addressSyntax;
private String slaveId;
private String timeout;
private List<String> registerAddresses;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isAnyBlank(driverName, addressSyntax, slaveId)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
return registerAddresses == null || registerAddresses.isEmpty();
}
}
@@ -0,0 +1,68 @@
/*
* 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.common.entity.job.protocol;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* pop3 protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Pop3Protocol implements CommonRequestProtocol, Protocol {
/**
* Receiving server address
*/
private String host;
/**
* Receiving server port
*/
private String port;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* Whether to enable SSL encryption [Email Transmission]
*/
private String ssl = "false";
/**
* pop Email address
*/
private String email;
/**
* Authorization code
*/
private String authorize;
@Override
public boolean isInvalid() {
return StringUtils.isAllBlank(host, port, timeout, ssl, email, authorize);
}
}
@@ -0,0 +1,139 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* Prometheus Protocol configuration
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PrometheusProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Peer host port
*/
private String port;
/**
* http/https metrics path
*/
private String path;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* http Whether to use link-encrypted ssl/tls, that is, http or https
*/
private String ssl = "false";
/**
* HTTP REQUEST METHOD: get, post, put, delete, patch
*/
private String method;
/**
* HTTP REQUESTS CARRY HEADERS eg: Content-Type = application/json
*/
private Map<String, String> headers;
/**
* HTTP REQUESTS CARRY QUERY PARAMETERS eg: localhost:80/api?paramKey=value
*/
private Map<String, String> params;
/**
* The request body carried by an http request
*/
private String payload;
/**
* Authentication information
*/
private Authorization authorization;
/**
* Authentication information
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Authorization {
/**
* Authentication typeBearer Token, Basic Auth, Digest Auth
*/
private String type;
/**
* Bearer Token's token
*/
private String bearerTokenToken;
/**
* Basic Auth 's username
*/
private String basicAuthUsername;
/**
* Basic Auth 's password
*/
private String basicAuthPassword;
/**
* Digest Auth 's username
*/
private String digestAuthUsername;
/**
* Digest Auth 's password
*/
private String digestAuthPassword;
}
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(ssl) && !"true".equalsIgnoreCase(ssl) && !"false".equalsIgnoreCase(ssl)) {
return true;
}
if (StringUtils.isNotBlank(method) && !isValidHttpMethod(method)) {
return true;
}
return false;
}
private boolean isValidHttpMethod(String method) {
return method.equalsIgnoreCase("get")
|| method.equalsIgnoreCase("post")
|| method.equalsIgnoreCase("put")
|| method.equalsIgnoreCase("delete")
|| method.equalsIgnoreCase("patch")
|| method.equalsIgnoreCase("head")
|| method.equalsIgnoreCase("options");
}
}
@@ -0,0 +1,31 @@
/*
* 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.common.entity.job.protocol;
/**
* Base class for all protocols
*/
public interface Protocol {
/**
* Check Protocol params valid.
* @return True or False.
*/
boolean isInvalid();
}
@@ -0,0 +1,69 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.isHasSchema;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.entity.dto.Field;
/**
* push protocol definition
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PushProtocol implements CommonRequestProtocol, Protocol {
private String host;
private String port;
private String uri = "/api/push";
private List<Field> fields;
@Override
public boolean isInvalid() {
if ((!validateIpDomain(host) && !isHasSchema(host)) || !validPort(port)) {
return true;
}
if (Integer.parseInt(port) <= 0) {
return true;
}
if (StringUtils.isBlank(uri) || !uri.startsWith("/") || StringUtils.containsWhitespace(uri)) {
return true;
}
if (fields == null || fields.isEmpty()) {
return true;
}
for (Field field : fields) {
if (field == null
|| StringUtils.isBlank(field.getName())
|| field.getType() == null
|| (field.getType() != 0 && field.getType() != 1)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,99 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.isHasSchema;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* Redfish Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RedfishProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Peer host port
*/
private String port;
/**
* UserName
*/
private String username;
/**
* Password
*/
private String password;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* Redfish Resource Name and Corresponding Collection URI
*/
private String schema;
private List<String> jsonPath;
@Override
public boolean isInvalid() {
if ((!validateIpDomain(host) && !isHasSchema(host)) || !validPort(port)) {
return true;
}
if (Integer.parseInt(port) <= 0) {
return true;
}
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
return true;
}
if (!StringUtils.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(schema)
&& (!schema.startsWith("/") || StringUtils.containsWhitespace(schema))) {
return true;
}
if (jsonPath == null || jsonPath.isEmpty()) {
return true;
}
for (String path : jsonPath) {
if (StringUtils.isBlank(path)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,93 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.entity.job.SshTunnel;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* Redis Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RedisProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Port number
*/
private String port;
/**
* Redis User name (optional)
*/
private String username;
/**
* Redis Password (optional)
*/
private String password;
/**
* 1 - single 2 - sentinel 3 - cluster
*/
private String pattern;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* SSH TUNNEL
*/
private SshTunnel sshTunnel;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(pattern) && !isValidPattern(pattern)) {
return true;
}
return false;
}
private boolean isValidPattern(String pattern) {
return "1".equals(pattern) || "2".equals(pattern) || "3".equals(pattern);
}
}
@@ -0,0 +1,55 @@
/*
* 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.common.entity.job.protocol;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
/**
* Registry protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RegistryProtocol implements CommonRequestProtocol, Protocol {
private String host;
private String port;
private String discoveryClientTypeName;
private String username;
private String password;
private String namespace;
private String serviceName;
private String groupName;
@Override
public boolean isInvalid() {
return validateIpDomain(host) && validPort(port)
&& StringUtils.isAnyBlank(host, String.valueOf(port), discoveryClientTypeName);
}
}
@@ -0,0 +1,86 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* rocketmq protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RocketmqProtocol implements CommonRequestProtocol, Protocol {
/**
* rocketmq namesrv host
*/
private String namesrvHost;
/**
* rocketmq namesrv port
*/
private String namesrvPort;
/**
* accessKey
*/
private String accessKey;
/**
* secretKey
*/
private String secretKey;
/**
* jsonpath parsing script
*/
private String parseScript;
@Override
public void setHost(String host) {
this.namesrvHost = host;
}
@Override
public void setPort(String port) {
this.namesrvPort = port;
}
@Override
public boolean isInvalid() {
if (!validateIpDomain(namesrvHost) || !validPort(namesrvPort)) {
return true;
}
if (StringUtils.isNotBlank(accessKey) && StringUtils.isBlank(secretKey)) {
return true;
}
if (StringUtils.isBlank(accessKey) && StringUtils.isNotBlank(secretKey)) {
return true;
}
return false;
}
}
@@ -0,0 +1,81 @@
/*
* 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.common.entity.job.protocol;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
import java.util.List;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
/**
* Modbus Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class S7Protocol implements Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Port number
*/
private String port;
private String driverName;
private String addressSyntax;
private String rackId;
private String slotId;
private String controllerType;
private String timeout;
private List<String> registerAddresses;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isAnyBlank(driverName, addressSyntax, controllerType)) {
return true;
}
if (!CommonUtil.isNumeric(rackId) || !CommonUtil.isNumeric(slotId)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
return registerAddresses == null || registerAddresses.isEmpty();
}
}
@@ -0,0 +1,100 @@
/*
* 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.common.entity.job.protocol;
import java.nio.charset.Charset;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
/**
* script protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ScriptProtocol implements CommonRequestProtocol, Protocol {
private static final Set<String> VALID_PARSE_TYPES = Set.of("oneRow", "multiRow", "netcat", "log");
private static final Set<String> VALID_SCRIPT_TOOLS = Set.of("bash", "cmd", "powershell");
/**
* OS charset
*/
private String charset;
/**
* Script working directory
*/
private String workDirectory;
/**
* Script command
*/
private String scriptCommand;
/**
* File name of script
*/
private String scriptPath;
/**
* Response data parsing modeoneRow, multiRow
*/
private String parseType;
/**
* Script tool name, exp: bash, cmd, powershell
*/
private String scriptTool;
@Override
public void setHost(String host) {
this.workDirectory = host;
}
@Override
public void setPort(String port) {
this.scriptPath = port;
}
@Override
public boolean isInvalid() {
if (StringUtils.isBlank(charset) || !isSupportedCharset(charset)) {
return true;
}
if (StringUtils.isBlank(parseType) || !VALID_PARSE_TYPES.contains(parseType)) {
return true;
}
if (StringUtils.isBlank(scriptTool) || !VALID_SCRIPT_TOOLS.contains(scriptTool)) {
return true;
}
return StringUtils.isAllBlank(scriptCommand, scriptPath);
}
private boolean isSupportedCharset(String charsetName) {
try {
return Charset.isSupported(charsetName);
} catch (Exception e) {
return false;
}
}
}
@@ -0,0 +1,70 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* Smtp Protocol
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SmtpProtocol implements CommonRequestProtocol, Protocol {
/**
* email Host ip address or domain name
*/
private String host;
/**
* EMAIL HOST PORT
*/
private String port;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* helo command tester (email)
*/
private String email;
/**
* Sent command
*/
private String cmd;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port) || StringUtils.isBlank(email)) {
return true;
}
return StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout);
}
}
@@ -0,0 +1,151 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* snmp Protocol configuration
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SnmpProtocol implements CommonRequestProtocol, Protocol {
private static final String OPERATION_GET = "get";
private static final String OPERATION_WALK = "walk";
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Peer host port
*/
private String port;
/**
* timeout
*/
private String timeout;
/**
* snmp version v1 v2c v3
* 0 = v1
* 1 = v2c
* 3 = v3
*/
private String version;
/**
* community name for v1 v2
*/
private String community;
/**
* username (optional)
*/
private String username;
/**
* auth password (optional)
*/
private String authPassphrase;
/**
* password(optional)
*/
private String privPassphrase;
/**
* operation: get, walk
*/
private String operation = "get";
/**
* oid map
*/
private Map<String, String> oids;
/**
* contextName
*/
private String contextName;
/**
* authPasswordEncryption
* v3 requires
*/
private String authPasswordEncryption;
/**
* privPasswordEncryption
* v3 requires
*/
private String privPasswordEncryption;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port) || StringUtils.isBlank(version)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(operation)
&& !OPERATION_GET.equalsIgnoreCase(operation)
&& !OPERATION_WALK.equalsIgnoreCase(operation)) {
return true;
}
if (oids == null || oids.isEmpty()) {
return true;
}
for (Map.Entry<String, String> entry : oids.entrySet()) {
if (StringUtils.isAnyBlank(entry.getKey(), entry.getValue())) {
return true;
}
}
if (isVersion3()) {
return StringUtils.isAnyBlank(username, authPassphrase, privPassphrase);
}
if (!isVersion1Or2c()) {
return true;
}
return StringUtils.isBlank(community);
}
private boolean isVersion1Or2c() {
return isVersion1() || isVersion2c();
}
private boolean isVersion1() {
return "0".equalsIgnoreCase(version) || "v1".equalsIgnoreCase(version);
}
private boolean isVersion2c() {
return "1".equalsIgnoreCase(version)
|| "2".equalsIgnoreCase(version)
|| "2c".equalsIgnoreCase(version)
|| "v2c".equalsIgnoreCase(version);
}
private boolean isVersion3() {
return "3".equalsIgnoreCase(version) || "v3".equalsIgnoreCase(version);
}
}
@@ -0,0 +1,144 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* ssh Protocol parameter configuration
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SshProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Peer host port
*/
private String port;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* UserName
*/
private String username;
/**
* Password (optional)
*/
private String password;
/**
* Private key (optional)
*/
private String privateKey;
/**
* private key passphrase (optional)
*/
private String privateKeyPassphrase;
/**
* reuse connection session
*/
private String reuseConnection = "true";
/**
* SSH execution script
*/
private String script;
/**
* Response data parsing modeoneRow, multiRow
*/
private String parseType;
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER PROXY HOST
*/
private String proxyHost;
/**
* Peer proxy host port
*/
private String proxyPort;
/**
* Proxy UserName
*/
private String proxyUsername;
/**
* Proxy Password (optional)
*/
private String proxyPassword;
/**
* flag of use proxy
*/
private String useProxy = "false";
/**
* Proxy private key (optional)
*/
private String proxyPrivateKey;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(reuseConnection)
&& !"true".equalsIgnoreCase(reuseConnection)
&& !"false".equalsIgnoreCase(reuseConnection)) {
return true;
}
if (StringUtils.isNotBlank(useProxy)
&& !"true".equalsIgnoreCase(useProxy)
&& !"false".equalsIgnoreCase(useProxy)) {
return true;
}
if ("true".equalsIgnoreCase(useProxy)) {
if (!validateIpDomain(proxyHost) || !validPort(proxyPort)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,67 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* telnet Protocol configuration
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TelnetProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Peer host port
*/
private String port;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* Sent command
*/
private String cmd;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
return StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout);
}
}
@@ -0,0 +1,75 @@
/*
* 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.common.entity.job.protocol;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validPort;
import static org.apache.hertzbeat.common.util.IpDomainUtil.validateIpDomain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.hertzbeat.common.util.CommonUtil;
/**
* Use udp implemented by socket for service port availability detection
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UdpProtocol implements CommonRequestProtocol, Protocol {
/**
* IP ADDRESS OR DOMAIN NAME OF THE PEER HOST
*/
private String host;
/**
* Port number
*/
private String port;
/**
* TIME OUT PERIOD
*/
private String timeout;
/**
* Custom protocol packet hexString Hexadecimal character string
*/
private String content;
@Override
public boolean isInvalid() {
if (!validateIpDomain(host) || !validPort(port)) {
return true;
}
if (StringUtils.isNotBlank(timeout) && !CommonUtil.isNumeric(timeout)) {
return true;
}
if (StringUtils.isNotBlank(content) && !isValidHexString(content)) {
return true;
}
return false;
}
private boolean isValidHexString(String hex) {
return hex.matches("^[0-9a-fA-F]+$");
}
}

Some files were not shown because too many files have changed in this diff Show More