first
commit
0fa5d6e97c
|
|
@ -0,0 +1,77 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>jnet</groupId>
|
||||
<artifactId>jNetServer</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<build>
|
||||
<finalName>jNetServer</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-resources</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy-resources</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>false</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<outputDirectory>${project.build.directory}</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>false</shadedArtifactAttached>
|
||||
<shadedClassifierName>null</shadedClassifierName>
|
||||
<transformers>
|
||||
<transformer>
|
||||
<mainClass>${exec.mainClass}</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
<filters>
|
||||
<filter>
|
||||
<artifact>*:*</artifact>
|
||||
<excludes>
|
||||
<exclude>META-INF/*.SF</exclude>
|
||||
<exclude>META-INF/*.DSA</exclude>
|
||||
<exclude>META-INF/*.RSA</exclude>
|
||||
</excludes>
|
||||
</filter>
|
||||
</filters>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
<configuration>
|
||||
<release>${maven.compiler.release}</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<properties>
|
||||
<maven.compiler.release>21</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<exec.mainClass>jnet.server.Server</exec.mainClass>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,205 @@
|
|||
25.08.26 22:50:20 I ---------------------------------------------
|
||||
25.08.26 22:50:20 I jNet Server
|
||||
25.08.26 22:50:20 I Version: 1 (Tue Aug 25 22:22:02 CEST 2026)
|
||||
25.08.26 22:50:20 I ---------------------------------------------
|
||||
25.08.26 22:50:20 I
|
||||
25.08.26 22:50:20 I Loading config ...
|
||||
25.08.26 22:50:20 I successfully
|
||||
25.08.26 22:50:20 D Debug mode on
|
||||
25.08.26 22:50:20 I Connecting to database ...
|
||||
25.08.26 22:50:20 I successfully
|
||||
25.08.26 22:50:20 I Loading user list ...
|
||||
25.08.26 22:50:21 I load 3 user(s)
|
||||
25.08.26 22:50:21 I Loading node icon ...
|
||||
25.08.26 22:50:21 I load 9 icon(s)
|
||||
25.08.26 22:50:21 I Loading map and object list ...
|
||||
25.08.26 22:50:21 I load 8 maps
|
||||
25.08.26 22:50:21 I Loading events list ...
|
||||
25.08.26 22:50:21 I load 424 events
|
||||
25.08.26 22:50:21 I Loading SNMP profile list ...
|
||||
25.08.26 22:50:21 I load 5 profile(s)
|
||||
25.08.26 22:50:21 I Loading SNMP template list ...
|
||||
25.08.26 22:50:21 I load 4 templates(s)
|
||||
25.08.26 22:50:21 I Loading SNMP template value map list ...
|
||||
25.08.26 22:50:21 I load 1 value map(s)
|
||||
25.08.26 22:50:21 I Spoustim SNMP monitor (dotaz=5000ms, davka=2000ms)
|
||||
25.08.26 22:50:21 I SNMP zarizeni pridano: ID=3
|
||||
25.08.26 22:50:21 I SNMP zarizeni pridano: ID=5
|
||||
25.08.26 22:50:21 I SNMP zarizeni pridano: ID=6
|
||||
25.08.26 22:50:21 I SNMP zarizeni pridano: ID=7
|
||||
25.08.26 22:50:21 I SNMP zarizeni pridano: ID=8
|
||||
25.08.26 22:50:21 I SNMP zarizeni pridano: ID=9
|
||||
25.08.26 22:50:21 I SNMP zarizeni pridano: ID=10
|
||||
25.08.26 22:50:21 I SNMP zarizeni pridano: ID=11
|
||||
25.08.26 22:50:21 I SNMP zarizeni pridano: ID=12
|
||||
25.08.26 22:50:21 I Nacteno 9 monitoru, preskoceno 2
|
||||
25.08.26 22:50:21 I Monitor spusten, interval=5000ms, zarizeni=9
|
||||
25.08.26 22:50:21 I TrafficBatchDispatcher spusten, interval=2000ms
|
||||
25.08.26 22:50:21 I SNMP monitor spusten, zarizeni=9
|
||||
25.08.26 22:50:26 I Ping probe starting...
|
||||
25.08.26 22:50:26 I Loaded 16 targets.
|
||||
25.08.26 22:50:26 I OS is Windows - using PingEngine (subprocess ping)
|
||||
25.08.26 22:50:26 I Targets set.
|
||||
25.08.26 22:50:26 I Starting engine...
|
||||
25.08.26 22:50:26 I Engine started successfully.
|
||||
25.08.26 22:50:27 I Starting Netty on port 1225
|
||||
25.08.26 22:50:28 I New client: /127.0.0.1:60521
|
||||
25.08.26 22:50:28 D Received message ID: 501
|
||||
25.08.26 22:50:28 D Received message ID: 502
|
||||
25.08.26 22:50:29 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:0:27 D Received message ID: 522
|
||||
25.08.26 23:0:27 D Received message ID: 522
|
||||
25.08.26 23:0:38 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:60521
|
||||
25.08.26 23:0:38 I Client: kubernetes.docker.internal/127.0.0.1:60521 disconnected
|
||||
25.08.26 23:0:44 I New client: /127.0.0.1:54057
|
||||
25.08.26 23:0:45 D Received message ID: 501
|
||||
25.08.26 23:0:45 D Received message ID: 502
|
||||
25.08.26 23:0:45 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:0:51 D Received message ID: 522
|
||||
25.08.26 23:0:51 D Received message ID: 522
|
||||
25.08.26 23:1:17 D CHANGE: Node 27 (10.10.0.254) -> DOWN
|
||||
25.08.26 23:1:26 D CHANGE: Node 27 (10.10.0.254) -> UP, odezva 3 ms
|
||||
25.08.26 23:3:30 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:54057
|
||||
25.08.26 23:3:30 I Client: kubernetes.docker.internal/127.0.0.1:54057 disconnected
|
||||
25.08.26 23:3:35 I New client: /127.0.0.1:56285
|
||||
25.08.26 23:3:36 D Received message ID: 501
|
||||
25.08.26 23:3:36 D Received message ID: 502
|
||||
25.08.26 23:3:36 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:3:42 D Received message ID: 522
|
||||
25.08.26 23:5:42 D Received message ID: 522
|
||||
25.08.26 23:5:47 D Received message ID: 522
|
||||
25.08.26 23:5:54 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:56285
|
||||
25.08.26 23:5:54 I Client: kubernetes.docker.internal/127.0.0.1:56285 disconnected
|
||||
25.08.26 23:6:00 I New client: /127.0.0.1:57030
|
||||
25.08.26 23:6:00 D Received message ID: 501
|
||||
25.08.26 23:6:00 D Received message ID: 502
|
||||
25.08.26 23:6:01 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:6:07 D Received message ID: 522
|
||||
25.08.26 23:7:11 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:57030
|
||||
25.08.26 23:7:11 I Client: kubernetes.docker.internal/127.0.0.1:57030 disconnected
|
||||
25.08.26 23:7:18 I New client: /127.0.0.1:49421
|
||||
25.08.26 23:7:18 D Received message ID: 501
|
||||
25.08.26 23:7:18 D Received message ID: 502
|
||||
25.08.26 23:7:18 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:7:30 D Received message ID: 522
|
||||
25.08.26 23:9:12 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:49421
|
||||
25.08.26 23:9:12 I Client: kubernetes.docker.internal/127.0.0.1:49421 disconnected
|
||||
25.08.26 23:9:18 I New client: /127.0.0.1:51870
|
||||
25.08.26 23:9:18 D Received message ID: 501
|
||||
25.08.26 23:9:18 D Received message ID: 502
|
||||
25.08.26 23:9:18 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:9:26 D Received message ID: 522
|
||||
25.08.26 23:18:15 D Received message ID: 522
|
||||
25.08.26 23:25:48 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:51870
|
||||
25.08.26 23:25:48 I Client: kubernetes.docker.internal/127.0.0.1:51870 disconnected
|
||||
25.08.26 23:25:54 I New client: /127.0.0.1:56407
|
||||
25.08.26 23:25:55 D Received message ID: 501
|
||||
25.08.26 23:25:55 D Received message ID: 502
|
||||
25.08.26 23:25:55 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:26:02 D Received message ID: 522
|
||||
25.08.26 23:31:08 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:56407
|
||||
25.08.26 23:31:08 I Client: kubernetes.docker.internal/127.0.0.1:56407 disconnected
|
||||
25.08.26 23:31:14 I New client: /127.0.0.1:49795
|
||||
25.08.26 23:31:14 D Received message ID: 501
|
||||
25.08.26 23:31:14 D Received message ID: 502
|
||||
25.08.26 23:31:14 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:31:19 D Received message ID: 522
|
||||
25.08.26 23:33:57 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:49795
|
||||
25.08.26 23:33:57 I Client: kubernetes.docker.internal/127.0.0.1:49795 disconnected
|
||||
25.08.26 23:34:01 I New client: /127.0.0.1:60168
|
||||
25.08.26 23:34:01 D Received message ID: 501
|
||||
25.08.26 23:34:01 D Received message ID: 502
|
||||
25.08.26 23:34:01 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:34:06 D Received message ID: 522
|
||||
25.08.26 23:34:36 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:60168
|
||||
25.08.26 23:34:36 I Client: kubernetes.docker.internal/127.0.0.1:60168 disconnected
|
||||
25.08.26 23:34:43 I New client: /127.0.0.1:59836
|
||||
25.08.26 23:34:43 D Received message ID: 501
|
||||
25.08.26 23:34:43 D Received message ID: 502
|
||||
25.08.26 23:34:43 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:34:59 D Received message ID: 522
|
||||
25.08.26 23:35:49 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:59836
|
||||
25.08.26 23:35:49 I Client: kubernetes.docker.internal/127.0.0.1:59836 disconnected
|
||||
25.08.26 23:35:55 I New client: /127.0.0.1:59863
|
||||
25.08.26 23:35:55 D Received message ID: 501
|
||||
25.08.26 23:35:55 D Received message ID: 502
|
||||
25.08.26 23:35:55 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:35:59 D Received message ID: 522
|
||||
25.08.26 23:37:05 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:59863
|
||||
25.08.26 23:37:05 I Client: kubernetes.docker.internal/127.0.0.1:59863 disconnected
|
||||
25.08.26 23:37:11 I New client: /127.0.0.1:62977
|
||||
25.08.26 23:37:12 D Received message ID: 501
|
||||
25.08.26 23:37:12 D Received message ID: 502
|
||||
25.08.26 23:37:12 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:37:15 D Received message ID: 510
|
||||
25.08.26 23:37:20 D Received message ID: 522
|
||||
25.08.26 23:37:35 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:62977
|
||||
25.08.26 23:37:35 I Client: kubernetes.docker.internal/127.0.0.1:62977 disconnected
|
||||
25.08.26 23:37:42 I New client: /127.0.0.1:64746
|
||||
25.08.26 23:37:42 D Received message ID: 501
|
||||
25.08.26 23:37:42 D Received message ID: 502
|
||||
25.08.26 23:37:42 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:37:47 D Received message ID: 522
|
||||
25.08.26 23:37:59 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:64746
|
||||
25.08.26 23:37:59 I Client: kubernetes.docker.internal/127.0.0.1:64746 disconnected
|
||||
25.08.26 23:38:05 I New client: /127.0.0.1:64756
|
||||
25.08.26 23:38:05 D Received message ID: 501
|
||||
25.08.26 23:38:05 D Received message ID: 502
|
||||
25.08.26 23:38:05 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:38:09 D Received message ID: 522
|
||||
25.08.26 23:38:53 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:64756
|
||||
25.08.26 23:38:53 I Client: kubernetes.docker.internal/127.0.0.1:64756 disconnected
|
||||
25.08.26 23:38:59 I New client: /127.0.0.1:65125
|
||||
25.08.26 23:38:59 D Received message ID: 501
|
||||
25.08.26 23:38:59 D Received message ID: 502
|
||||
25.08.26 23:38:59 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:39:03 D Received message ID: 522
|
||||
25.08.26 23:40:22 D Received message ID: 511
|
||||
25.08.26 23:40:24 D Received message ID: 510
|
||||
25.08.26 23:40:27 D Received message ID: 510
|
||||
25.08.26 23:40:32 D Received message ID: 513
|
||||
25.08.26 23:40:35 D Received message ID: 522
|
||||
25.08.26 23:40:47 D Received message ID: 522
|
||||
25.08.26 23:40:54 D Received message ID: 521
|
||||
25.08.26 23:40:54 I SNMP zarizeni pridano: ID=14
|
||||
25.08.26 23:41:10 D Received message ID: 510
|
||||
25.08.26 23:41:19 D Received message ID: 522
|
||||
25.08.26 23:41:23 D Received message ID: 521
|
||||
25.08.26 23:41:23 I SNMP zarizeni odebrano: ID=14
|
||||
25.08.26 23:41:29 D Received message ID: 522
|
||||
25.08.26 23:41:34 D Received message ID: 521
|
||||
25.08.26 23:41:41 D Received message ID: 522
|
||||
25.08.26 23:41:44 D Received message ID: 522
|
||||
25.08.26 23:41:46 D Received message ID: 521
|
||||
25.08.26 23:41:46 I SNMP zarizeni pridano: ID=14
|
||||
25.08.26 23:42:34 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:65125
|
||||
25.08.26 23:42:34 I Client: kubernetes.docker.internal/127.0.0.1:65125 disconnected
|
||||
25.08.26 23:42:40 I New client: /127.0.0.1:59187
|
||||
25.08.26 23:42:40 D Received message ID: 501
|
||||
25.08.26 23:42:40 D Received message ID: 502
|
||||
25.08.26 23:42:40 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:42:47 D Received message ID: 522
|
||||
25.08.26 23:44:08 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:59187
|
||||
25.08.26 23:44:08 I Client: kubernetes.docker.internal/127.0.0.1:59187 disconnected
|
||||
25.08.26 23:44:14 I New client: /127.0.0.1:58695
|
||||
25.08.26 23:44:14 D Received message ID: 501
|
||||
25.08.26 23:44:14 D Received message ID: 502
|
||||
25.08.26 23:44:14 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:44:19 D Received message ID: 522
|
||||
25.08.26 23:44:37 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:58695
|
||||
25.08.26 23:44:37 I Client: kubernetes.docker.internal/127.0.0.1:58695 disconnected
|
||||
25.08.26 23:44:43 I New client: /127.0.0.1:60314
|
||||
25.08.26 23:44:43 D Received message ID: 501
|
||||
25.08.26 23:44:43 D Received message ID: 502
|
||||
25.08.26 23:44:43 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:44:47 D Received message ID: 522
|
||||
25.08.26 23:45:13 I Client abruptly disconnected: kubernetes.docker.internal/127.0.0.1:60314
|
||||
25.08.26 23:45:13 I Client: kubernetes.docker.internal/127.0.0.1:60314 disconnected
|
||||
25.08.26 23:45:19 I New client: /127.0.0.1:60329
|
||||
25.08.26 23:45:19 D Received message ID: 501
|
||||
25.08.26 23:45:19 D Received message ID: 502
|
||||
25.08.26 23:45:19 I User: michal logged in (127.0.0.1)
|
||||
25.08.26 23:45:24 D Received message ID: 522
|
||||
25.08.26 23:48:24 D Received message ID: 522
|
||||
25.08.26 23:48:27 D CHANGE: Node 25 (10.10.0.39) -> DOWN
|
||||
25.08.26 23:48:36 D CHANGE: Node 25 (10.10.0.39) -> UP, odezva 3 ms
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<actions>
|
||||
<action>
|
||||
<actionName>run</actionName>
|
||||
<packagings>
|
||||
<packaging>jar</packaging>
|
||||
</packagings>
|
||||
<goals>
|
||||
<goal>process-classes</goal>
|
||||
<goal>org.codehaus.mojo:exec-maven-plugin:3.5.1:exec</goal>
|
||||
</goals>
|
||||
<properties>
|
||||
<exec.vmArgs>-Dio.netty.noUnsafe=true -Dio.netty.tryUnsafe=false</exec.vmArgs>
|
||||
<exec.args>${exec.vmArgs} -classpath %classpath ${exec.mainClass} ${exec.appArgs}</exec.args>
|
||||
<exec.appArgs></exec.appArgs>
|
||||
<exec.mainClass>${packageClassName}</exec.mainClass>
|
||||
<exec.executable>java</exec.executable>
|
||||
</properties>
|
||||
</action>
|
||||
<action>
|
||||
<actionName>debug</actionName>
|
||||
<packagings>
|
||||
<packaging>jar</packaging>
|
||||
</packagings>
|
||||
<goals>
|
||||
<goal>process-classes</goal>
|
||||
<goal>org.codehaus.mojo:exec-maven-plugin:3.5.1:exec</goal>
|
||||
</goals>
|
||||
<properties>
|
||||
<exec.vmArgs>-Dio.netty.noUnsafe=true -Dio.netty.tryUnsafe=false -agentlib:jdwp=transport=dt_socket,server=n,address=${jpda.address}</exec.vmArgs>
|
||||
<exec.args>${exec.vmArgs} -classpath %classpath ${exec.mainClass} ${exec.appArgs}</exec.args>
|
||||
<exec.appArgs></exec.appArgs>
|
||||
<exec.mainClass>${packageClassName}</exec.mainClass>
|
||||
<exec.executable>java</exec.executable>
|
||||
<jpda.listen>true</jpda.listen>
|
||||
</properties>
|
||||
</action>
|
||||
<action>
|
||||
<actionName>profile</actionName>
|
||||
<packagings>
|
||||
<packaging>jar</packaging>
|
||||
</packagings>
|
||||
<goals>
|
||||
<goal>process-classes</goal>
|
||||
<goal>org.codehaus.mojo:exec-maven-plugin:3.5.1:exec</goal>
|
||||
</goals>
|
||||
<properties>
|
||||
<exec.vmArgs>-Dio.netty.noUnsafe=true -Dio.netty.tryUnsafe=false</exec.vmArgs>
|
||||
<exec.args>${exec.vmArgs} -classpath %classpath ${exec.mainClass} ${exec.appArgs}</exec.args>
|
||||
<exec.mainClass>${packageClassName}</exec.mainClass>
|
||||
<exec.executable>java</exec.executable>
|
||||
<exec.appArgs></exec.appArgs>
|
||||
</properties>
|
||||
</action>
|
||||
</actions>
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>jnet</groupId>
|
||||
<artifactId>jNetServer</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.release>21</maven.compiler.release>
|
||||
<exec.mainClass>jnet.server.Server</exec.mainClass>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>4.1.118.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.78.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcpkix-jdk18on</artifactId>
|
||||
<version>1.78.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>jNetLib</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<type>jar</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<version>8.3.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.java.dev.jna</groupId>
|
||||
<artifactId>jna</artifactId>
|
||||
<version>5.14.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<!-- Zakážeme standardní kopírování resources do JARu -->
|
||||
<resources>
|
||||
<!-- prázdné -->
|
||||
</resources>
|
||||
<!-- Nastavení názvu výsledného JAR -->
|
||||
<finalName>jNetServer</finalName>
|
||||
<plugins>
|
||||
<!-- Kopírování resources do target/ (vedle JARu) -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-resources</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy-resources</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>false</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<outputDirectory>${project.build.directory}</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- Shade plugin – vytvoří fat JAR a nastaví Main-Class -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<!-- Potlačí vytvoření original- JARu -->
|
||||
<shadedArtifactAttached>false</shadedArtifactAttached>
|
||||
<shadedClassifierName>null</shadedClassifierName>
|
||||
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>${exec.mainClass}</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
<!-- Vyřazení bezpečnostních podpisů (aby se předešlo konfliktům) -->
|
||||
<filters>
|
||||
<filter>
|
||||
<artifact>*:*</artifact>
|
||||
<excludes>
|
||||
<exclude>META-INF/*.SF</exclude>
|
||||
<exclude>META-INF/*.DSA</exclude>
|
||||
<exclude>META-INF/*.RSA</exclude>
|
||||
</excludes>
|
||||
</filter>
|
||||
</filters>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- Kompilátor -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
<configuration>
|
||||
<release>${maven.compiler.release}</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,193 @@
|
|||
package jnet.server;
|
||||
|
||||
import jnet.server.dao.SnmpDao;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.object.*;
|
||||
import jnet.server.dao.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Fasádní wrapper, který zachovává původní statické rozhraní třídy Database.
|
||||
* Všechny metody delegují na odpovídající DAO instance.
|
||||
*/
|
||||
public final class Database {
|
||||
|
||||
private static final UserDao userDao = new UserDao();
|
||||
private static final SiteDao siteDao = new SiteDao();
|
||||
private static final NodeDao nodeDao = new NodeDao();
|
||||
private static final EventDao eventDao = new EventDao();
|
||||
private static final SnmpDao snmpDao = new SnmpDao();
|
||||
private static final ObjectTypeDao objectTypeDao = new ObjectTypeDao();
|
||||
private static final ConnectionDao connectionDao = new ConnectionDao();
|
||||
|
||||
|
||||
// Veřejný konstruktor pro případy, kdy je v kódu voláno new Database()
|
||||
public Database() {}
|
||||
|
||||
// -------- inicializace --------
|
||||
|
||||
public static void connect(String host, String port, String database, String user, String password) {
|
||||
ConnectionManager.init(host, port, database, user, password);
|
||||
}
|
||||
|
||||
// -------- User --------
|
||||
|
||||
public static boolean verifyUser(String username, String password) {
|
||||
return userDao.verifyUser(username, password);
|
||||
}
|
||||
|
||||
public static User getUserInfo(String username) {
|
||||
return userDao.getUserInfo(username);
|
||||
}
|
||||
|
||||
public static ArrayList<User> getUsers() {
|
||||
return new ArrayList<>(userDao.getUsers());
|
||||
}
|
||||
|
||||
public static int addUser(User user) {
|
||||
return userDao.addUser(user);
|
||||
}
|
||||
|
||||
public static void editUser(User u) {
|
||||
userDao.editUser(u);
|
||||
}
|
||||
|
||||
// -------- ObjectType --------
|
||||
|
||||
public static ArrayList<ObjectType> getObjectType() {
|
||||
return new ArrayList<>(objectTypeDao.getObjectTypes());
|
||||
}
|
||||
|
||||
public static int addObjectType(ObjectType ot) {
|
||||
return objectTypeDao.addObjectType(ot);
|
||||
}
|
||||
|
||||
// -------- Site --------
|
||||
|
||||
public static ArrayList<Site> getSiteList() {
|
||||
return new ArrayList<>(siteDao.getSiteList());
|
||||
}
|
||||
|
||||
public static int addSite(String name) {
|
||||
return siteDao.addSite(name);
|
||||
}
|
||||
|
||||
public static void removeSite(int id) {
|
||||
siteDao.removeSite(id);
|
||||
}
|
||||
|
||||
public static void setSiteLock(boolean state, int map) {
|
||||
siteDao.setSiteLock(state, map);
|
||||
}
|
||||
|
||||
// -------- Node --------
|
||||
|
||||
public static ArrayList<Node> getNodeList(int siteId) {
|
||||
return new ArrayList<>(nodeDao.getNodesForSite(siteId));
|
||||
}
|
||||
|
||||
public static int addNode(Node mo) {
|
||||
return nodeDao.addNode(mo);
|
||||
}
|
||||
|
||||
public static void removeNode(int id) {
|
||||
nodeDao.removeNode(id);
|
||||
}
|
||||
|
||||
public static void nodeUpdatePosition(int nodeId, int x, int y) {
|
||||
nodeDao.updatePosition(nodeId, x, y);
|
||||
}
|
||||
|
||||
public static void editNode(Node node) {
|
||||
nodeDao.updateNode(node);
|
||||
}
|
||||
|
||||
// -------- NodeConnection (spojení) --------
|
||||
|
||||
public static List<NodeConnection> getNodeConnectionList(int nodeId) {
|
||||
return connectionDao.getConnectionsForNode(nodeId);
|
||||
}
|
||||
|
||||
public static List<NodeConnection> getSiteConnectionList(int siteId) {
|
||||
return connectionDao.getConnectionsForSite(siteId);
|
||||
}
|
||||
|
||||
public static int addNodeConnection(NodeConnection nc) {
|
||||
return connectionDao.addConnection(nc);
|
||||
}
|
||||
|
||||
public static void removeNodeConnection(int id) {
|
||||
connectionDao.removeNodeConnection(id);
|
||||
}
|
||||
|
||||
public static void editNodeconnection(NodeConnection connection) {
|
||||
connectionDao.editNodeconnection(connection);
|
||||
}
|
||||
|
||||
// -------- Event --------
|
||||
|
||||
public static long insertEvent(int nodeId, int status, long time) {
|
||||
return eventDao.insertEvent(nodeId, status, time);
|
||||
}
|
||||
|
||||
public static void endEvent(long eventId, long time) {
|
||||
eventDao.endEvent(eventId, time);
|
||||
}
|
||||
|
||||
public static List<Event> getAllEvents() {
|
||||
return eventDao.getAllEvents();
|
||||
}
|
||||
|
||||
// -------- SNMP --------
|
||||
|
||||
public static List<SnmpProfile> getSnmpProfile() {
|
||||
return snmpDao.getAllProfile();
|
||||
}
|
||||
|
||||
public static List<SnmpTemplate> getSnmpTemplate(){
|
||||
return snmpDao.getSnmpTemplate();
|
||||
}
|
||||
|
||||
public static List<SnmpValueMap> getSnmpValueMapList() {
|
||||
return snmpDao.getSnmpValueMapList();
|
||||
}
|
||||
|
||||
public static void addNodeProbe(NodeProbe probe) {
|
||||
snmpDao.addNodeProbe(probe);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// -------- zachování zastaralých metod pro kompatibilitu --------
|
||||
|
||||
@Deprecated
|
||||
public static void query(String sqlQuery) {
|
||||
try {
|
||||
siteDao.executeUpdate(sqlQuery); // používáme existující DAO instanci
|
||||
} catch (Exception e) {
|
||||
LogFile.printErr("MySQL exception: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static int insert(String sqlQuery) {
|
||||
return siteDao.insertAndGetId(sqlQuery);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static void update(String sql) {
|
||||
try {
|
||||
siteDao.executeUpdate(sql);
|
||||
} catch (Exception e) {
|
||||
LogFile.printErr("MySQL exception: " + e.getMessage() + " SQL: " + sql);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
static boolean remove(String table, int id) {
|
||||
return siteDao.deleteById(table, id);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package jnet.server;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.Status;
|
||||
import jnet.lib.object.Event;
|
||||
import jnet.server.networkserver.NettyServerManager;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
public class EventManager {
|
||||
|
||||
private static final Map<Integer, Long> openEventIds = new HashMap<>();
|
||||
|
||||
static public void insertOfflineEvent(int nodeId) {
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
long eventId = Database.insertEvent(nodeId, Status.OFFLINE, now);
|
||||
|
||||
if (eventId > 0) {
|
||||
openEventIds.put(nodeId, eventId);
|
||||
Event e = new Event(eventId, nodeId, Status.OFFLINE, now);
|
||||
Server.events.add(e);
|
||||
ServerHandler.sendAll(new Message(Message.EVENT_NEW, e));
|
||||
}
|
||||
}
|
||||
|
||||
static public void endEvent(int nodeId) {
|
||||
|
||||
Long eventId = openEventIds.get(nodeId);
|
||||
if (eventId != null) {
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
Database.endEvent(eventId, now);
|
||||
|
||||
openEventIds.remove(nodeId);
|
||||
|
||||
for (Event event : Server.events) {
|
||||
if (event.getId() == eventId) {
|
||||
event.setEnd(now);
|
||||
ServerHandler.sendAll(new Message(Message.EVENT_UPDATE, event));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
package jnet.server;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
import jnet.lib.ApacheConfig;
|
||||
import org.apache.commons.configuration2.Configuration;
|
||||
import org.apache.commons.configuration2.ex.ConfigurationException;
|
||||
import jnet.lib.BuilddDate;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.object.Event;
|
||||
import jnet.lib.object.ObjectType;
|
||||
import jnet.lib.object.OnlineClients;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.lib.object.SnmpProfile;
|
||||
import jnet.lib.object.User;
|
||||
import jnet.server.networkserver.NettyServerManager;
|
||||
import jnet.server.probe.Ping;
|
||||
import jnet.server.trafficmonitor.SnmpMonitorService;
|
||||
import jnet.lib.object.SnmpTemplate;
|
||||
import jnet.lib.object.SnmpValueMap;
|
||||
import jnet.server.probe.snmp.SnmpBatchProcessor;
|
||||
import jnet.server.probe.snmp.SnmpProbeManager;
|
||||
|
||||
public class Server {
|
||||
|
||||
// verze serveru
|
||||
public static final int VERSION = 1;
|
||||
// minimální verze klienta
|
||||
public static final int MINIMAL_CLIENT_VERSION = 1;
|
||||
|
||||
public static Configuration config;
|
||||
public static Database database;
|
||||
public static SnmpMonitorService snmpMonitorService;
|
||||
public static SnmpProbeManager snmpProbeManager;
|
||||
|
||||
public static List<OnlineClients> onlineClients = new ArrayList<>();
|
||||
public static List<Site> site = new ArrayList<>();
|
||||
public static List<ObjectType> objectType = new ArrayList<>();
|
||||
public static List<SnmpProfile> snmpProfile = new ArrayList<>();
|
||||
public static List<User> users = new ArrayList<>();
|
||||
public static List<Event> events = new ArrayList<>();
|
||||
public static List<SnmpTemplate> snmpTemplate = new ArrayList<>();
|
||||
public static List<SnmpValueMap> snmpValueMap = new ArrayList<>();
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Prague"));
|
||||
|
||||
LogFile.clear();
|
||||
LogFile.setDebug(false);
|
||||
LogFile.printInfo("---------------------------------------------");
|
||||
LogFile.printInfo(" jNet Server ");
|
||||
LogFile.printInfo(" Version: " + VERSION + " (" + BuilddDate.get() + ")");
|
||||
LogFile.printInfo("---------------------------------------------");
|
||||
LogFile.printInfo("");
|
||||
|
||||
// Nahrani konfigurace
|
||||
LogFile.printInfo("Loading config ...");
|
||||
try {
|
||||
config = ApacheConfig.loadProperties();
|
||||
LogFile.printInfo(" successfully");
|
||||
} catch (ConfigurationException ex) {
|
||||
LogFile.printInfo(" fail: " + ex.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
// Debug mode
|
||||
if (config.getBoolean("debug")) {
|
||||
LogFile.setDebug(true);
|
||||
LogFile.printDebug("Debug mode on");
|
||||
}
|
||||
|
||||
// Pripojeni k databazi
|
||||
database = new Database();
|
||||
database.connect(
|
||||
config.getString("mysql_server"),
|
||||
config.getString("mysql_port"),
|
||||
config.getString("mysql_database"),
|
||||
config.getString("mysql_user"),
|
||||
config.getString("mysql_password")
|
||||
);
|
||||
|
||||
// nacteni uzivatelu
|
||||
LogFile.printInfo("Loading user list ...");
|
||||
users = Database.getUsers();
|
||||
LogFile.printInfo(" load " + users.size() + " user(s)");
|
||||
|
||||
// nacteni node icon
|
||||
LogFile.printInfo("Loading node icon ...");
|
||||
objectType = Database.getObjectType();
|
||||
LogFile.printInfo(" load " + objectType.size() + " icon(s)");
|
||||
|
||||
// nacteni map a objektu z databaze
|
||||
LogFile.printInfo("Loading map and object list ...");
|
||||
site = Database.getSiteList();
|
||||
LogFile.printInfo(" load " + site.size() + " maps");
|
||||
|
||||
// nacteni logu
|
||||
LogFile.printInfo("Loading events list ...");
|
||||
events = Database.getAllEvents();
|
||||
LogFile.printInfo(" load " + events.size() + " events");
|
||||
|
||||
// nacteni SNMP profilu
|
||||
LogFile.printInfo("Loading SNMP profile list ...");
|
||||
snmpProfile = Database.getSnmpProfile();
|
||||
LogFile.printInfo(" load " + snmpProfile.size() + " profile(s)");
|
||||
|
||||
// nacteni SNMP sablon
|
||||
LogFile.printInfo("Loading SNMP template list ...");
|
||||
snmpTemplate = Database.getSnmpTemplate();
|
||||
LogFile.printInfo(" load " + snmpTemplate.size() + " templates(s)");
|
||||
|
||||
// nacteni SNMP sablon -value map
|
||||
LogFile.printInfo("Loading SNMP template value map list ...");
|
||||
snmpValueMap = Database.getSnmpValueMapList();
|
||||
LogFile.printInfo(" load " + snmpValueMap.size() + " value map(s)");
|
||||
|
||||
// ============================================================
|
||||
// 🆕 SPUŠTĚNÍ traffic SNMP MONITORU
|
||||
// ============================================================
|
||||
// Spustíme SNMP monitoring s intervalem z configu (např. 30 sekund)
|
||||
long snmpInterval = config.getLong("snmp.interval", 30000); // default 30s
|
||||
long batchInterval = config.getLong("snmp.batchInterval", 2000);
|
||||
snmpMonitorService.start(snmpInterval, batchInterval);
|
||||
// ============================================================
|
||||
|
||||
// Vytvoření SnmpProbeManager
|
||||
snmpProbeManager = new SnmpProbeManager();
|
||||
|
||||
// Vytvoření batch processoru s intervalem 5 sekund (lze z configu)
|
||||
int batchSeconds = config.getInt("snmp.batchIntervalSec", 5);
|
||||
SnmpBatchProcessor batchProcessor = new SnmpBatchProcessor(batchSeconds);
|
||||
batchProcessor.init(snmpProbeManager); // zaregistruje se a spustí scheduler
|
||||
|
||||
// Načtení úloh
|
||||
snmpProbeManager.loadTask();
|
||||
|
||||
// spustěni ping probe
|
||||
Ping.start();
|
||||
|
||||
// Netty server vlákna
|
||||
NettyServerManager nettyServer = new NettyServerManager();
|
||||
nettyServer.start(config.getInt("server_port", 8443));
|
||||
|
||||
// Shutdown hook pro případ vypnutí z OS (Ctrl+C, kill/SIGTERM)
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
LogFile.printInfo("Shutdown signal received...");
|
||||
// 🆕 Zastavení SNMP monitoru
|
||||
snmpMonitorService.stop();
|
||||
snmpProbeManager.close();
|
||||
nettyServer.stop();
|
||||
}));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package jnet.server;
|
||||
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.NodeState;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
|
||||
public class SiteOperation {
|
||||
|
||||
public static void updateNodeStatus(NodeState ns){
|
||||
// zmení status v seznamu
|
||||
for (Site site : Server.site) {
|
||||
for (Node node : site.getNode()) {
|
||||
if (node.getId() == ns.getId()) {
|
||||
node.setStatus(ns.getState());
|
||||
break; // ID je unikátní, po nalezení končíme
|
||||
}
|
||||
}
|
||||
}
|
||||
ServerHandler.sendAll(new Message(Message.NODE_STATUS_CHANGE, ns));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
package jnet.server.dao;
|
||||
|
||||
import jnet.lib.LogFile;
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class AbstractDao {
|
||||
|
||||
protected Connection getConnection() throws SQLException {
|
||||
return ConnectionManager.getConnection();
|
||||
}
|
||||
|
||||
// -------- veřejné helpery pro všechny potomky i fasádu --------
|
||||
|
||||
public int insertAndGetId(String sql, Object... params) {
|
||||
try (PreparedStatement pstmt = getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
|
||||
setParameters(pstmt, params);
|
||||
//System.err.println(pstmt.toString());
|
||||
pstmt.executeUpdate();
|
||||
try (ResultSet rs = pstmt.getGeneratedKeys()) {
|
||||
if (rs.next()) return rs.getInt(1);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
LogFile.printErr("Insert failed: " + e.getMessage() + " SQL: " + sql);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public boolean deleteById(String table, int id) {
|
||||
String sql = "DELETE FROM " + table + " WHERE id = ?";
|
||||
try (PreparedStatement pstmt = getConnection().prepareStatement(sql)) {
|
||||
pstmt.setInt(1, id);
|
||||
return pstmt.executeUpdate() > 0;
|
||||
} catch (SQLException e) {
|
||||
LogFile.printErr("Delete failed: " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void executeUpdate(String sql, Object... params) throws SQLException {
|
||||
try (PreparedStatement pstmt = getConnection().prepareStatement(sql)) {
|
||||
setParameters(pstmt, params);
|
||||
pstmt.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
// -------- chráněné helpery pro query (zůstávají protected) --------
|
||||
|
||||
protected <T> T querySingle(String sql, ResultSetMapper<T> mapper, Object... params) {
|
||||
try (PreparedStatement pstmt = getConnection().prepareStatement(sql)) {
|
||||
setParameters(pstmt, params);
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) return mapper.map(rs);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
LogFile.printErr("Query failed: " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected <T> List<T> queryList(String sql, ResultSetMapper<T> mapper, Object... params) {
|
||||
List<T> list = new ArrayList<>();
|
||||
try (PreparedStatement pstmt = getConnection().prepareStatement(sql)) {
|
||||
setParameters(pstmt, params);
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
while (rs.next()) list.add(mapper.map(rs));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
LogFile.printErr("Query failed: " + e.getMessage());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private void setParameters(PreparedStatement pstmt, Object... params) throws SQLException {
|
||||
for (int i = 0; i < params.length; i++) {
|
||||
pstmt.setObject(i + 1, params[i]);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
protected interface ResultSetMapper<T> {
|
||||
T map(ResultSet rs) throws SQLException;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
package jnet.server.dao;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import jnet.lib.object.NodeConnection;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.object.Node;
|
||||
|
||||
public class ConnectionDao extends AbstractDao {
|
||||
|
||||
/**
|
||||
* Vrátí všechna spojení, do kterých daný uzel vstupuje nebo z nich
|
||||
* vystupuje.
|
||||
*/
|
||||
public List<NodeConnection> getConnectionsForNode(int nodeId) {
|
||||
String sql = "SELECT DISTINCT * FROM connection WHERE nodeFrom = ? OR nodeTo = ?";
|
||||
return queryList(sql, rs -> new NodeConnection(
|
||||
rs.getInt("id"),
|
||||
rs.getInt("siteId"),
|
||||
rs.getInt("nodeFrom"),
|
||||
rs.getInt("nodeTo"),
|
||||
rs.getInt("typeConnection"),
|
||||
rs.getBoolean("readTraffic"),
|
||||
rs.getInt("trafficNode"),
|
||||
rs.getInt("trafficIface")
|
||||
), nodeId, nodeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrátí všechna spojení, která mají alespoň jeden konec v seznamu uzlů.
|
||||
* Používá se pro efektivní načtení všech spojení na mapě najednou.
|
||||
*/
|
||||
public List<NodeConnection> getConnectionsForNodeList(List<Integer> nodeIds) {
|
||||
if (nodeIds == null || nodeIds.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
// Sestavíme dynamický IN dotaz
|
||||
StringBuilder sql = new StringBuilder("SELECT DISTINCT * FROM connection WHERE nodeFrom IN (");
|
||||
for (int i = 0; i < nodeIds.size(); i++) {
|
||||
sql.append("?");
|
||||
if (i < nodeIds.size() - 1) {
|
||||
sql.append(",");
|
||||
}
|
||||
}
|
||||
sql.append(") OR nodeTo IN (");
|
||||
for (int i = 0; i < nodeIds.size(); i++) {
|
||||
sql.append("?");
|
||||
if (i < nodeIds.size() - 1) {
|
||||
sql.append(",");
|
||||
}
|
||||
}
|
||||
sql.append(")");
|
||||
|
||||
// Parametry: dvakrát stejný seznam
|
||||
List<Object> params = new ArrayList<>();
|
||||
params.addAll(nodeIds);
|
||||
params.addAll(nodeIds);
|
||||
|
||||
return queryList(sql.toString(), rs -> new NodeConnection(
|
||||
rs.getInt("id"),
|
||||
rs.getInt("siteId"),
|
||||
rs.getInt("nodeFrom"),
|
||||
rs.getInt("nodeTo"),
|
||||
rs.getInt("typeConnection"),
|
||||
rs.getBoolean("readTraffic"),
|
||||
rs.getInt("trafficNode"),
|
||||
rs.getInt("trafficIface")
|
||||
), params.toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrátí unikátní spojení pro daný seznam uzlů podle node ID (bez duplicit).
|
||||
*/
|
||||
public List<NodeConnection> getUniqueConnectionsForNodes(List<Node> nodes) {
|
||||
List<Integer> ids = new ArrayList<>();
|
||||
for (Node n : nodes) {
|
||||
ids.add(n.getId());
|
||||
}
|
||||
List<NodeConnection> all = getConnectionsForNodeList(ids);
|
||||
// odstranění duplicit podle id
|
||||
Set<Integer> seen = new HashSet<>();
|
||||
List<NodeConnection> unique = new ArrayList<>();
|
||||
for (NodeConnection nc : all) {
|
||||
if (seen.add(nc.getId())) {
|
||||
unique.add(nc);
|
||||
}
|
||||
}
|
||||
return unique;
|
||||
}
|
||||
|
||||
public int addConnection(NodeConnection nc) {
|
||||
String sql = "INSERT INTO connection (siteId, nodeFrom, nodeTo, typeConnection, readTraffic, trafficNode, trafficIface) "
|
||||
+ "VALUES (?,?,?,?,?,?,?)";
|
||||
return insertAndGetId(sql,
|
||||
nc.getSite(),
|
||||
nc.getNodeFrom(),
|
||||
nc.getNodeTo(),
|
||||
nc.getType(),
|
||||
(nc.isReadTraffic() ? 1:0),
|
||||
nc.getTrafficNode(),
|
||||
nc.getTrafficIface()
|
||||
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrátí unikátní spojení pro danou site
|
||||
*/
|
||||
public List<NodeConnection> getConnectionsForSite(int siteId) {
|
||||
String sql = "SELECT * FROM connection WHERE siteId = ?";
|
||||
return queryList(sql, rs -> new NodeConnection(
|
||||
rs.getInt("id"),
|
||||
rs.getInt("siteId"),
|
||||
rs.getInt("nodeFrom"),
|
||||
rs.getInt("nodeTo"),
|
||||
rs.getInt("typeConnection"),
|
||||
rs.getBoolean("readTraffic"),
|
||||
rs.getInt("trafficNode"),
|
||||
rs.getInt("trafficIface")
|
||||
), siteId);
|
||||
}
|
||||
|
||||
public void removeNodeConnection(int id) {
|
||||
if (deleteById("connection", id)) {
|
||||
LogFile.printInfo("Node connection ID " + id + " removed from database");
|
||||
} else {
|
||||
LogFile.printErr("Node connection ID " + id + " not removed from database");
|
||||
}
|
||||
}
|
||||
|
||||
public void editNodeconnection(NodeConnection connection) {
|
||||
try {
|
||||
executeUpdate(
|
||||
"UPDATE connection SET typeConnection=?, readTraffic=?, trafficNode=?, trafficIface=? WHERE id=?",
|
||||
connection.getType(),
|
||||
(connection.isReadTraffic() ? 1:0),
|
||||
connection.getTrafficNode(),
|
||||
connection.getTrafficIface(),
|
||||
connection.getId() // poslední parametr pro WHERE
|
||||
);
|
||||
} catch (SQLException e) {
|
||||
LogFile.printErr("Chyba při aktualizaci connection: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
package jnet.server.dao;
|
||||
|
||||
import jnet.lib.LogFile;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public final class ConnectionManager {
|
||||
|
||||
private static final int VALIDATION_TIMEOUT = 2;
|
||||
|
||||
private static String host;
|
||||
private static String port;
|
||||
private static String database;
|
||||
private static String user;
|
||||
private static String password;
|
||||
private static Connection connection = null;
|
||||
|
||||
private ConnectionManager() {}
|
||||
|
||||
public static void init(String host, String port, String database, String user, String password) {
|
||||
ConnectionManager.host = host;
|
||||
ConnectionManager.port = port;
|
||||
ConnectionManager.database = database;
|
||||
ConnectionManager.user = user;
|
||||
ConnectionManager.password = password;
|
||||
connection = createConnection();
|
||||
}
|
||||
|
||||
private static Connection createConnection() {
|
||||
try {
|
||||
String url = String.format(
|
||||
"jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Europe/Prague",
|
||||
host, port, database
|
||||
);
|
||||
LogFile.printInfo("Connecting to database ...");
|
||||
Connection conn = DriverManager.getConnection(url, user, password);
|
||||
LogFile.printInfo(" successfully");
|
||||
return conn;
|
||||
} catch (SQLException ex) {
|
||||
LogFile.printErr("MySQL connection exception: " + ex.getMessage());
|
||||
System.exit(1);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrátí platné spojení – pokud je staré uzavřené (timeout), automaticky ho obnoví.
|
||||
*/
|
||||
public static Connection getConnection() throws SQLException {
|
||||
if (connection == null || !connection.isValid(VALIDATION_TIMEOUT)) {
|
||||
LogFile.printInfo("Database connection lost, reconnecting...");
|
||||
connection = createConnection();
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
package jnet.server.dao;
|
||||
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.object.Event;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.List;
|
||||
|
||||
public class EventDao extends AbstractDao {
|
||||
|
||||
public long insertEvent(int nodeId, int status, long time) {
|
||||
String sql = "INSERT INTO events (node, status, start) VALUES (?, ?, ?)";
|
||||
return insertAndGetId(sql, nodeId, status, new Timestamp(time));
|
||||
}
|
||||
|
||||
public void endEvent(long eventId, long time) {
|
||||
try {
|
||||
executeUpdate("UPDATE events SET end = ? WHERE id = ?", new Timestamp(time), eventId);
|
||||
} catch (Exception e) {
|
||||
LogFile.printErr("MySQL exception: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public List<Event> getAllEvents() {
|
||||
String sql = "SELECT * FROM events";
|
||||
return queryList(sql, rs -> {
|
||||
Timestamp start = rs.getTimestamp("start");
|
||||
Timestamp end = rs.getTimestamp("end");
|
||||
long startMillis = start.getTime();
|
||||
Long endMillis = (end != null) ? end.getTime() : 0L;
|
||||
return new Event(
|
||||
rs.getLong("id"),
|
||||
rs.getInt("node"),
|
||||
rs.getInt("status"),
|
||||
startMillis,
|
||||
endMillis,
|
||||
rs.getInt("duration")
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
package jnet.server.dao;
|
||||
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.Status;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.NodeProbe;
|
||||
import jnet.lib.object.NodeConnection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public class NodeDao extends AbstractDao {
|
||||
|
||||
private final ConnectionDao connectionDao = new ConnectionDao();
|
||||
|
||||
public List<Node> getNodesForSite(int siteId) {
|
||||
String sql = "SELECT * FROM node WHERE siteId = ?";
|
||||
return queryList(sql, this::mapNode, siteId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pro daný seznam uzlů vrátí všechna jejich spojení (bez duplicit).
|
||||
*/
|
||||
public List<NodeConnection> getConnectionsForNodes(List<Node> nodes) {
|
||||
return connectionDao.getUniqueConnectionsForNodes(nodes);
|
||||
}
|
||||
|
||||
public int addNode(Node node) {
|
||||
String sql = "INSERT INTO node (name, ip, x, y, type, siteId, icon, ping, user, password, "
|
||||
+ "description, location, snmpProfile, winbox, winboxPort, ssh, sshPort, web, "
|
||||
+ "webPort, webVerze, telnet, telnetPort, sms, smsPort, smsVerze) "
|
||||
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
|
||||
return insertAndGetId(sql,
|
||||
node.getName(), node.getIp(), node.getX(), node.getY(),
|
||||
node.getType(), node.getSiteId(), node.getIcon(), node.isPing(),
|
||||
node.getUser(), node.getPassword(), node.getDescription(),
|
||||
node.getLocation(), node.getSnmpProfile(),
|
||||
node.isWinbox(), node.getWinboxPort(),
|
||||
node.isSsh(), node.getSshPort(),
|
||||
node.isWeb(), node.getWebPort(), node.getWebVerze(),
|
||||
node.isTelnet(), node.getTelnetPort(),
|
||||
node.isSms(), node.getSmsPort(), node.getSmsVerze()
|
||||
);
|
||||
}
|
||||
|
||||
public void removeNode(int id) {
|
||||
if (deleteById("node", id)) {
|
||||
LogFile.printInfo("Node ID " + id + " removed from database");
|
||||
} else {
|
||||
LogFile.printErr("Node ID " + id + " not removed from database");
|
||||
}
|
||||
}
|
||||
|
||||
public void updatePosition(int nodeId, int x, int y) {
|
||||
try {
|
||||
executeUpdate("UPDATE node SET x = ?, y = ? WHERE id = ?", x, y, nodeId);
|
||||
} catch (SQLException e) {
|
||||
LogFile.printErr("MySQL exception: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Node mapNode(ResultSet rs) throws SQLException {
|
||||
return new Node(
|
||||
rs.getInt("id"),
|
||||
rs.getString("name"),
|
||||
rs.getInt("siteId"),
|
||||
rs.getInt("x"),
|
||||
rs.getInt("y"),
|
||||
rs.getInt("type"),
|
||||
rs.getInt("icon"),
|
||||
rs.getString("ip"),
|
||||
rs.getString("user"),
|
||||
rs.getString("password"),
|
||||
rs.getString("description"),
|
||||
rs.getString("location"),
|
||||
rs.getInt("snmpProfile"),
|
||||
Status.NA,
|
||||
rs.getBoolean("ping"),
|
||||
rs.getInt("winbox") == 1,
|
||||
rs.getString("winboxPort"),
|
||||
rs.getInt("ssh") == 1,
|
||||
rs.getString("sshPort"),
|
||||
rs.getInt("web") == 1,
|
||||
rs.getString("webPort"),
|
||||
rs.getInt("webVerze"),
|
||||
rs.getInt("telnet") == 1,
|
||||
rs.getString("telnetPort"),
|
||||
rs.getInt("sms") == 1,
|
||||
rs.getString("smsPort"),
|
||||
rs.getInt("smsVerze"),
|
||||
rs.getInt("siteLink"),
|
||||
getNodeProbe(rs.getInt("id"))
|
||||
);
|
||||
}
|
||||
|
||||
public void updateNode(Node node) {
|
||||
try {
|
||||
executeUpdate(
|
||||
"UPDATE node SET name=?, siteId=?, type=?, x=?, y=?, ip=?, ping=?, icon=?, user=?, password=?, description=?, location=?, snmpProfile=?, winbox=?, winboxPort=?, ssh=?, sshPort=?, web=?, webPort=?, webVerze=?, telnet=?, telnetPort=?, sms=?, smsPort=?, smsVerze=?, siteLink=? WHERE id=?",
|
||||
node.getName(),
|
||||
node.getSiteId(),
|
||||
node.getType(),
|
||||
node.getX(),
|
||||
node.getY(),
|
||||
node.getIp(),
|
||||
(node.isPing() ? 1 : 0),
|
||||
node.getIcon(), // může být null
|
||||
node.getUser(),
|
||||
node.getPassword(),
|
||||
node.getDescription(), // může být null
|
||||
node.getLocation(), // může být null
|
||||
node.getSnmpProfile(), // může být null
|
||||
(node.isWinbox() ? 1 : 0), // může být null
|
||||
node.getWinboxPort(), // může být null
|
||||
(node.isSsh() ? 1 : 0), // může být null
|
||||
node.getSshPort(), // může být null
|
||||
(node.isWeb() ? 1 : 0), // může být null
|
||||
node.getWebPort(), // může být null
|
||||
node.getWebVerze(), // může být null
|
||||
(node.isTelnet() ? 1 : 0), // může být null
|
||||
node.getTelnetPort(), // může být null
|
||||
(node.isSms() ? 1 : 0), // může být null
|
||||
node.getSmsPort(), // může být null
|
||||
node.getSmsVerze(), // může být null
|
||||
node.getSiteLink(), // může být null
|
||||
node.getId() // poslední parametr pro WHERE
|
||||
);
|
||||
} catch (SQLException e) {
|
||||
LogFile.printErr("Chyba při aktualizaci uzlu: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private List<NodeProbe> getNodeProbe(int nodeId) {
|
||||
String sql = "SELECT * FROM nodeProbe WHERE node_id = ?";
|
||||
return queryList(sql, this::mapNodeProbe, nodeId);
|
||||
}
|
||||
|
||||
private NodeProbe mapNodeProbe(ResultSet rs) throws SQLException {
|
||||
return new NodeProbe(rs.getInt("id"),
|
||||
rs.getString("name"),
|
||||
rs.getString("oid"),
|
||||
rs.getString("snmp_data_type"),
|
||||
rs.getString("conversion_type"),
|
||||
rs.getDouble("conversion_value"),
|
||||
rs.getString("conversion_expression"),
|
||||
rs.getString("unit"),
|
||||
rs.getInt("value_map_id"),
|
||||
rs.getInt("interval_time")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package jnet.server.dao;
|
||||
|
||||
import jnet.lib.object.ObjectType;
|
||||
import java.util.List;
|
||||
|
||||
public class ObjectTypeDao extends AbstractDao {
|
||||
|
||||
public List<ObjectType> getObjectTypes() {
|
||||
String sql = "SELECT * FROM objectType";
|
||||
return queryList(sql, rs -> new ObjectType(
|
||||
rs.getInt("id"),
|
||||
rs.getString("name"),
|
||||
rs.getString("image")
|
||||
));
|
||||
}
|
||||
|
||||
public int addObjectType(ObjectType ot) {
|
||||
String sql = "INSERT INTO objectType (name, image) VALUES (?, ?)";
|
||||
return insertAndGetId(sql, ot.getName(), ot.getImgStr());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package jnet.server.dao;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.NodeConnection;
|
||||
import jnet.lib.object.Site;
|
||||
import java.util.List;
|
||||
|
||||
public class SiteDao extends AbstractDao {
|
||||
|
||||
private final NodeDao nodeDao = new NodeDao();
|
||||
private final ConnectionDao connectionDao = new ConnectionDao();
|
||||
|
||||
public List<Site> getSiteList() {
|
||||
String sql = "SELECT * FROM site";
|
||||
return queryList(sql, rs -> {
|
||||
int siteId = rs.getInt("id");
|
||||
List<Node> nodes = nodeDao.getNodesForSite(siteId);
|
||||
List<NodeConnection> connections = connectionDao.getConnectionsForSite(siteId);
|
||||
return new Site(
|
||||
siteId,
|
||||
rs.getString("name"),
|
||||
rs.getBoolean("locked"),
|
||||
nodes,
|
||||
connections
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public int addSite(String name) {
|
||||
return insertAndGetId("INSERT INTO site (name) VALUES (?)", name);
|
||||
}
|
||||
|
||||
public void removeSite(int id) {
|
||||
if (deleteById("site", id)) {
|
||||
LogFile.printInfo("Site ID " + id + " removed from database");
|
||||
} else {
|
||||
LogFile.printErr("Site ID " + id + " not removed from database");
|
||||
}
|
||||
}
|
||||
|
||||
public void setSiteLock(boolean locked, int siteId) {
|
||||
try {
|
||||
executeUpdate("UPDATE site SET locked = ? WHERE id = ?", locked, siteId);
|
||||
} catch (SQLException e) {
|
||||
LogFile.printErr("MySQL exception: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
package jnet.server.dao;
|
||||
|
||||
import java.util.List;
|
||||
import jnet.lib.object.NodeProbe;
|
||||
import jnet.lib.object.SnmpProfile;
|
||||
import jnet.lib.object.SnmpTemplate;
|
||||
import jnet.lib.object.SnmpValueMap;
|
||||
|
||||
public class SnmpDao extends AbstractDao {
|
||||
|
||||
public List<SnmpProfile> getAllProfile() {
|
||||
String sql = "SELECT * FROM snmpProfile";
|
||||
return queryList(sql, rs -> {
|
||||
return new SnmpProfile(
|
||||
rs.getInt("id"),
|
||||
rs.getString("name"),
|
||||
rs.getInt("version"),
|
||||
rs.getString("port"),
|
||||
rs.getString("communityRead"),
|
||||
rs.getString("communityWrite")
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public List<SnmpTemplate> getSnmpTemplate() {
|
||||
String sql = "SELECT * FROM snmp_oid_template";
|
||||
return queryList(sql, rs -> {
|
||||
return new SnmpTemplate(
|
||||
rs.getInt("id"),
|
||||
rs.getInt("device_type"),
|
||||
rs.getString("name"),
|
||||
rs.getString("oid"),
|
||||
rs.getString("snmp_data_type"),
|
||||
rs.getString("conversion_type"),
|
||||
rs.getDouble("conversion_value"),
|
||||
rs.getString("conversion_expression"),
|
||||
rs.getString("unit"),
|
||||
rs.getInt("value_map_id"),
|
||||
rs.getString("description")
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public List<SnmpValueMap> getSnmpValueMapList() {
|
||||
String sql = "SELECT * FROM snmp_value_map";
|
||||
return queryList(sql, rs -> new SnmpValueMap(
|
||||
rs.getInt("id"),
|
||||
rs.getString("name"),
|
||||
getSnmpValueMapItem(rs.getInt("id"))
|
||||
));
|
||||
}
|
||||
|
||||
private List<SnmpValueMap.Item> getSnmpValueMapItem(int id) {
|
||||
String sql = "SELECT * FROM snmp_value_map_item WHERE map_id = ?";
|
||||
return queryList(sql, rs -> new SnmpValueMap.Item(
|
||||
rs.getInt("id"),
|
||||
rs.getString("raw_value"),
|
||||
rs.getString("mapped_value")
|
||||
), id);
|
||||
}
|
||||
|
||||
public int addNodeProbe(NodeProbe probe) {
|
||||
String sql = "INSERT INTO nodeProbe (name, node_id, oid, snmp_data_type, conversion_type, conversion_value, conversion_expression, value_map_id, unit, interval_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
return insertAndGetId(
|
||||
sql,
|
||||
probe.getName(),
|
||||
probe.getNodeId(),
|
||||
probe.getOid(),
|
||||
probe.getDataType(),
|
||||
probe.getConversionType(),
|
||||
probe.getConversionValue(),
|
||||
probe.getConversionExpression(),
|
||||
probe.getValueMap(),
|
||||
probe.getUnit(),
|
||||
probe.getInterval()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
package jnet.server.dao;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import jnet.lib.PasswordHashing;
|
||||
import jnet.lib.object.User;
|
||||
import java.util.List;
|
||||
import jnet.lib.LogFile;
|
||||
|
||||
public class UserDao extends AbstractDao {
|
||||
|
||||
public boolean verifyUser(String username, String plainPassword) {
|
||||
String sql = "SELECT password FROM users WHERE username = ?";
|
||||
String storedHash = querySingle(sql, rs -> rs.getString("password"), username);
|
||||
return storedHash != null && PasswordHashing.verify(plainPassword, storedHash);
|
||||
}
|
||||
|
||||
public User getUserInfo(String username) {
|
||||
String sql = "SELECT * FROM users WHERE username = ?";
|
||||
return querySingle(sql, rs -> new User(
|
||||
rs.getInt("id"),
|
||||
rs.getString("username"),
|
||||
rs.getString("password"),
|
||||
rs.getBoolean("add_map"),
|
||||
rs.getBoolean("remove_map"),
|
||||
rs.getBoolean("edit_map"),
|
||||
rs.getBoolean("add_object"),
|
||||
rs.getBoolean("remove_object"),
|
||||
rs.getBoolean("edit_object"),
|
||||
rs.getBoolean("edit_server")
|
||||
), username);
|
||||
}
|
||||
|
||||
public List<User> getUsers() {
|
||||
String sql = "SELECT * FROM users";
|
||||
return queryList(sql, rs -> new User(
|
||||
rs.getInt("id"),
|
||||
rs.getString("username"),
|
||||
"",
|
||||
rs.getBoolean("add_map"),
|
||||
rs.getBoolean("remove_map"),
|
||||
rs.getBoolean("edit_map"),
|
||||
rs.getBoolean("add_object"),
|
||||
rs.getBoolean("remove_object"),
|
||||
rs.getBoolean("edit_object"),
|
||||
rs.getBoolean("edit_server")
|
||||
));
|
||||
}
|
||||
|
||||
public int addUser(User user) {
|
||||
String sql = "INSERT INTO users (username, password, add_map, remove_map, edit_map, "
|
||||
+ "add_object, remove_object, edit_object, edit_server) VALUES (?,?,?,?,?,?,?,?,?)";
|
||||
return insertAndGetId(sql,
|
||||
user.getUsername(), user.getPassword(),
|
||||
user.isAddMap(), user.isRemoveMap(), user.isEditMap(),
|
||||
user.isAddObject(), user.isRemoveObject(), user.isEditObject(),
|
||||
user.isEditServer()
|
||||
);
|
||||
}
|
||||
|
||||
public void editUser(User u) {
|
||||
try {
|
||||
if (u.getPassword() == null) {
|
||||
executeUpdate(
|
||||
//edit bez zmeny hesla
|
||||
"UPDATE users SET username=?, add_map=?, remove_map=?, edit_map=?, add_object=?, remove_object=?, edit_object=?, edit_server=? WHERE id=?",
|
||||
u.getUsername(),
|
||||
(u.isAddMap() ? 1 : 0),
|
||||
(u.isRemoveMap() ? 1 : 0),
|
||||
(u.isEditMap() ? 1 : 0),
|
||||
(u.isAddObject() ? 1 : 0),
|
||||
(u.isRemoveObject() ? 1 : 0),
|
||||
(u.isEditObject() ? 1 : 0),
|
||||
(u.isEditServer() ? 1 : 0),
|
||||
u.getId() // poslední parametr pro WHERE
|
||||
);
|
||||
} else {
|
||||
executeUpdate(
|
||||
// edit se zmenou hesla
|
||||
"UPDATE users SET username=?, password=?, add_map=?, remove_map=?, edit_map=?, add_object=?, remove_object=?, edit_object=?, edit_server=? WHERE id=?",
|
||||
u.getUsername(),
|
||||
u.getPassword(),
|
||||
(u.isAddMap() ? 1 : 0),
|
||||
(u.isRemoveMap() ? 1 : 0),
|
||||
(u.isEditMap() ? 1 : 0),
|
||||
(u.isAddObject() ? 1 : 0),
|
||||
(u.isRemoveObject() ? 1 : 0),
|
||||
(u.isEditObject() ? 1 : 0),
|
||||
(u.isEditServer() ? 1 : 0),
|
||||
u.getId() // poslední parametr pro WHERE
|
||||
);
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
LogFile.printErr("Chyba při aktualizaci uzlu: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import jnet.lib.Message;
|
||||
|
||||
|
||||
public class MessageRegister {
|
||||
|
||||
private final Map<Integer, Register> register = new HashMap<>();
|
||||
|
||||
// Konstruktor - při vytvoření registru se sám naplní
|
||||
public MessageRegister() {
|
||||
register.put(Message.CLIENT_TYPE, new RegisterClientVersion());
|
||||
register.put(Message.AUTH_DATA, new RegisterClientAuth());
|
||||
register.put(Message.SITE_ADD, new RegisterSiteAdd());
|
||||
register.put(Message.NODE_ICON_NEW, new RegisterNodeIconNew());
|
||||
register.put(Message.USER_ADD, new RegisterUserAdd());
|
||||
register.put(Message.SITE_DELETE, new RegisterSideDelete());
|
||||
register.put(Message.NODE_POSITION_CHANGE, new RegisterNodePositionChange());
|
||||
register.put(Message.NODE_ADD, new RegisterNodeAdd());
|
||||
register.put(Message.SITE_SET_LOCK, new RegisterSiteSetLock());
|
||||
register.put(Message.NODE_DELETE, new RegisterNodeDelete());
|
||||
register.put(Message.NODE_CHANGE, new RegisterNodeChange());
|
||||
register.put(Message.SNMP_TEST, new RegisterSnmpTest());
|
||||
register.put(Message.SERVER_RESTART, new RegisterServerRestart());
|
||||
register.put(Message.SERVER_UPTIME, new RegisterServerUptime());
|
||||
register.put(Message.USER_EDIT, new RegisterUserEdit());
|
||||
register.put(Message.NODE_SNMP_INFO, new RegisterSnmpNodeInfo());
|
||||
register.put(Message.NODE_SNMP_INTERFACE, new RegisterSnmpNodeInterface());
|
||||
register.put(Message.NODE_MOVE_TO_SITE, new RegisterNodeMoveToSite());
|
||||
register.put(Message.NODE_CONNECTION_NEW, new RegisterNodeConnectionNew());
|
||||
register.put(Message.NODE_CONNECTION_EDIT, new RegisterNodeConnectionEdit());
|
||||
register.put(Message.NODE_CONNECTION_SNMP_INTERFACE, new RegisterNodeConnectionSnmpInterface());
|
||||
register.put(Message.NODE_PROBE_NEW, new RegisterNodeProbeNew());
|
||||
register.put(Message.NODE_CONNECTION_DELETE, new RegisterNodeConnectionDelete());
|
||||
}
|
||||
|
||||
public Register getRegister(int typ) {
|
||||
return register.get(typ);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
|
||||
|
||||
public interface Register {
|
||||
void processing(ChannelHandlerContext ctx, Message msg);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import com.mysql.cj.xdevapi.Client;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import java.net.InetSocketAddress;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.ObjectType;
|
||||
import jnet.lib.object.OnlineClients;
|
||||
import jnet.lib.object.ServerConfig;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
public class RegisterClientAuth implements Register {
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
String[] userData = (String[]) msg.getMsg();
|
||||
String username = userData[0];
|
||||
String password = userData[1];
|
||||
|
||||
InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
|
||||
String ip = remoteAddress.getAddress().getHostAddress();
|
||||
int port = remoteAddress.getPort(); // 54321
|
||||
|
||||
int platform = Integer.parseInt(userData[2]);
|
||||
|
||||
if (Database.verifyUser(username, password)) {
|
||||
LogFile.printInfo("User: " + username + " logged in (" + ip + ")");
|
||||
// odeslani potvreni autorizace
|
||||
ctx.writeAndFlush(new Message(Message.AUTH_OK, null));
|
||||
// odeslat informace o prihlasenem uzivateli, opravneni atd
|
||||
ctx.writeAndFlush(new Message(Message.USER_INFO, Database.getUserInfo(username)));
|
||||
// pridani uzivatele mezi pripojene kanaly
|
||||
ServerHandler.addChannel(ctx);
|
||||
// pridat do seznamu klientu
|
||||
Server.onlineClients.add(new OnlineClients(
|
||||
String.valueOf(ctx.channel().id()),
|
||||
username, // username
|
||||
remoteAddress.getAddress().getHostName(), // ip adresa
|
||||
String.valueOf(port), // port
|
||||
platform));
|
||||
// odeslat vsem nový seznam pripojenych klientu
|
||||
ServerHandler.sendAll(new Message(Message.ONLINE_CLIENTS, Server.onlineClients));
|
||||
// odeslat nastaveni serveru
|
||||
ServerConfig sc = new ServerConfig(
|
||||
Server.config.getInt("ping_repeat"),
|
||||
Server.config.getInt("ping_attempt"),
|
||||
Server.config.getInt("ping_timeout"),
|
||||
Server.config.getInt("instability_attempt"),
|
||||
Server.config.getInt("instability_limit"),
|
||||
Server.config.getBoolean("debug"));
|
||||
ctx.writeAndFlush(new Message(Message.SERVER_CONFIG, sc));
|
||||
// odeslat seznam uzivatelu
|
||||
ctx.writeAndFlush(new Message(Message.USER_LIST, Server.users));
|
||||
// odeslat seznam icon
|
||||
ctx.writeAndFlush(new Message(Message.NODE_ICON_LIST, Server.objectType));
|
||||
// odeslat seznam udalosti
|
||||
ctx.writeAndFlush(new Message(Message.EVENT_LIST, Server.events));
|
||||
// odeslat seznam site
|
||||
ctx.writeAndFlush(new Message(Message.SITE_LIST, Server.site));
|
||||
// odeslat seznam snmp profilu
|
||||
ctx.writeAndFlush(new Message(Message.SNMP_PROFILE_LIST, Server.snmpProfile));
|
||||
// odeslat seznam snmp sablon
|
||||
ctx.writeAndFlush(new Message(Message.SNMP_TEMPLATE_LIST, Server.snmpTemplate));
|
||||
// odeslat seznam snmp value map
|
||||
ctx.writeAndFlush(new Message(Message.SNMP_TEMPLATE_VALUE_MAP_LIST, Server.snmpValueMap));
|
||||
|
||||
} else {
|
||||
LogFile.printErr("User:" + username + " has not been logged in - Incorrect user data (" + ip + ")");
|
||||
// odeslání selhani autorizace
|
||||
ctx.writeAndFlush(new Message(Message.AUTH_FAIL, null));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.server.Server;
|
||||
|
||||
|
||||
class RegisterClientVersion implements Register {
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
int clientVersion = (int) msg.getMsg();
|
||||
|
||||
if (clientVersion < Server.MINIMAL_CLIENT_VERSION) {
|
||||
// verze klienta je mensi nez pozadovana -> vyzadat aktualizaci klienta
|
||||
ctx.writeAndFlush(new Message(Message.CLIENT_UPDATE, null));
|
||||
} else {
|
||||
// verze klienta je ok -> vyzadat aktualizaci
|
||||
ctx.writeAndFlush(new Message(Message.AUTH_REQUEST, null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
import jnet.server.probe.Ping;
|
||||
|
||||
|
||||
public class RegisterNodeAdd implements Register {
|
||||
|
||||
public RegisterNodeAdd() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
Node node = (Node) msg.getMsg();
|
||||
// vlozi do databaze a získa id
|
||||
int id = Database.addNode(node);
|
||||
node.setId(id);
|
||||
// vlozi do seznamu
|
||||
for (Site site : Server.site) {
|
||||
if (site.getId() == node.getSiteId()) {
|
||||
site.getNode().add(node);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// odesle novy node klientum
|
||||
ServerHandler.sendAll(new Message(Message.NODE_NEW, node));
|
||||
// pokud je povolen ping zaradí ke sledovani
|
||||
if (node.isPing()) {
|
||||
Ping.addOrUpdateTarget(node.getId(), node.getIp());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import java.util.List;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
import jnet.server.probe.Ping;
|
||||
|
||||
public class RegisterNodeChange implements Register {
|
||||
|
||||
public RegisterNodeChange() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
Node newNode = (Node) msg.getMsg();
|
||||
for (Site site : Server.site) {
|
||||
List<Node> nodes = site.getNode(); // nebo použijte rozhraní
|
||||
for (int i = 0; i < nodes.size(); i++) {
|
||||
if (nodes.get(i).getId() == newNode.getId()) {
|
||||
// nahradi node v seznamu
|
||||
nodes.set(i, newNode);
|
||||
// aktualizuje v databazi
|
||||
Database.editNode(newNode);
|
||||
// aktualizuje ping
|
||||
if (newNode.isPing()) {
|
||||
// aktualizuje
|
||||
Ping.addOrUpdateTarget(newNode.getId(), newNode.getIp());
|
||||
} else {
|
||||
// odebere target z pingu
|
||||
Ping.removeTarget(newNode.getId());
|
||||
}
|
||||
// odesle zmenu klientum
|
||||
ServerHandler.sendAll(Message.NODE_UPDATE, newNode);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
import jnet.server.probe.Ping;
|
||||
|
||||
|
||||
public class RegisterNodeConnectionDelete implements Register {
|
||||
|
||||
public RegisterNodeConnectionDelete() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
int id = (int) msg.getMsg();
|
||||
|
||||
// smazani z lokalniho seznamu
|
||||
for (Site site : Server.site) {
|
||||
// odebere ze seznamu
|
||||
site.getNodeConnection().removeIf(nodeConnection -> nodeConnection.getId() == id);
|
||||
// odebere z databaze
|
||||
Database.removeNodeConnection(id);
|
||||
// smazani z traffic monitoru
|
||||
Server.snmpMonitorService.removeDevice(id);
|
||||
// odesle informaci vsem
|
||||
ServerHandler.sendAll(Message.NODE_CONNECTION_REMOVE, id);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import java.util.List;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.NodeConnection;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.lib.object.SnmpProfile;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
public class RegisterNodeConnectionEdit implements Register {
|
||||
|
||||
public RegisterNodeConnectionEdit() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
NodeConnection nc = (NodeConnection) msg.getMsg();
|
||||
|
||||
for (Site site : Server.site) {
|
||||
List<NodeConnection> connection = site.getNodeConnection(); // nebo použijte rozhraní
|
||||
for (int i = 0; i < connection.size(); i++) {
|
||||
if (connection.get(i).getId() == nc.getId()) {
|
||||
// nahradi node v seznamu
|
||||
connection.set(i, nc);
|
||||
// aktualizuje v databazi
|
||||
Database.editNodeconnection(nc);
|
||||
// odebere traffic monitor
|
||||
Server.snmpMonitorService.removeDevice(nc.getId());
|
||||
// a pokud je zapnute cteni znovu ho prida
|
||||
if (nc.isReadTraffic()) {
|
||||
// ziska info o node
|
||||
Node node = site.getNode().stream()
|
||||
.filter(n -> n.getId() == nc.getTrafficNode())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
// ziska info o profilu
|
||||
SnmpProfile profile = Server.snmpProfile.stream()
|
||||
.filter(p -> p.getId() == node.getSnmpProfile())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
// prida ke čtení
|
||||
Server.snmpMonitorService.addDevice(nc.getId(), node.getIp(), profile.getPort(), profile.getCommunityRead(), profile.getVersion(), nc.getTrafficIface());
|
||||
// odesle infomaci o zmene
|
||||
ServerHandler.sendAll(Message.NODE_CONNECTION_CHANGE, nc);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.NodeConnection;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.lib.object.SnmpProfile;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
public class RegisterNodeConnectionNew implements Register {
|
||||
|
||||
private Node node = null;
|
||||
|
||||
public RegisterNodeConnectionNew() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
NodeConnection nc = (NodeConnection) msg.getMsg();
|
||||
|
||||
// ulozeni do databaze
|
||||
int id = Database.addNodeConnection(nc);
|
||||
|
||||
// vlozen id
|
||||
nc.setId(id);
|
||||
|
||||
// ulozeni do mistniho seznamu
|
||||
for (Site site : Server.site) {
|
||||
if (site.getId() == nc.getSite()) {
|
||||
site.getNodeConnection().add(nc);
|
||||
|
||||
// je-li zapnuto cteni trafficu
|
||||
if (nc.isReadTraffic()) {
|
||||
node = site.getNode().stream()
|
||||
.filter(n -> n.getId() == nc.getTrafficNode())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// odeslani zmeny site
|
||||
ServerHandler.sendAll(Message.NODE_CONNECTION_ADD, nc);
|
||||
|
||||
// je-li zapnuto cteni trafficu
|
||||
if (nc.isReadTraffic() && node != null) {
|
||||
SnmpProfile profile = Server.snmpProfile.stream()
|
||||
.filter(p -> p.getId() == node.getSnmpProfile())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
Server.snmpMonitorService.addDevice(nc.getId(), node.getIp(), profile.getPort(), profile.getCommunityRead(), profile.getVersion(), nc.getTrafficIface());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Interface;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.SnmpProfile;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.snmp.SNMPInterfaceScanner;
|
||||
|
||||
|
||||
public class RegisterNodeConnectionSnmpInterface implements Register {
|
||||
|
||||
public RegisterNodeConnectionSnmpInterface() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
try {
|
||||
Object[] data = (Object[]) msg.getMsg();
|
||||
String frame = (String) data[0];
|
||||
Node node = (Node) data[1];
|
||||
// zjistit snmp profile
|
||||
SnmpProfile snmpProfile = Server.snmpProfile.stream()
|
||||
.filter(profile -> profile.getId() == node.getSnmpProfile())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (snmpProfile != null) {
|
||||
// odeslat pozadavek
|
||||
SNMPInterfaceScanner scanner = new SNMPInterfaceScanner(
|
||||
node.getIp(),
|
||||
snmpProfile.getPort(),
|
||||
snmpProfile.getCommunityRead(),
|
||||
snmpProfile.getVersion()
|
||||
);
|
||||
|
||||
List<Interface> ifaces = scanner.scanInterfaces();
|
||||
Object[] result = {frame, ifaces};
|
||||
ctx.writeAndFlush(new Message(Message.NODE_CONNECTION_SNMP_INTERFACE_RESULT, result));
|
||||
}
|
||||
|
||||
} catch (IOException ex) {
|
||||
LogFile.printErr("SNMP interface scan error: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import java.util.Objects;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
import jnet.server.probe.Ping;
|
||||
|
||||
|
||||
public class RegisterNodeDelete implements Register{
|
||||
|
||||
public RegisterNodeDelete() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
int nodeId = (int) msg.getMsg();
|
||||
for (Site site : Server.site) {
|
||||
// odebere ze seznamu
|
||||
site.getNode().removeIf(node -> node.getId() == nodeId);
|
||||
// odebere z databaze
|
||||
Database.removeNode(nodeId);
|
||||
// odebere target z pingu
|
||||
Ping.removeTarget(nodeId);
|
||||
// odesle informaci vsem
|
||||
ServerHandler.sendAll(Message.NODE_REMOVE, nodeId);
|
||||
break;
|
||||
}
|
||||
// smazat z eventu
|
||||
Server.events.removeIf(event -> Objects.equals(event.getNode(), nodeId));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.ObjectType;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
public class RegisterNodeIconNew implements Register {
|
||||
|
||||
public RegisterNodeIconNew() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
ObjectType not = (ObjectType) msg.getMsg();
|
||||
// ulozit do databaze
|
||||
int id = Database.addObjectType(not);
|
||||
// pridat do seznamu
|
||||
not.setId(id);
|
||||
Server.objectType.add(not);
|
||||
// odeslat vsem novy seznam
|
||||
ServerHandler.sendAll(new Message(Message.NODE_ICON_LIST, Server.objectType));
|
||||
// klientovi odeslat pokyn k aktualizaci tabulky
|
||||
ctx.writeAndFlush(new Message(Message.NODE_ICON_REFRESH, null));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
public class RegisterNodeMoveToSite implements Register {
|
||||
|
||||
public RegisterNodeMoveToSite() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
int[] data = (int[]) msg.getMsg();
|
||||
int nodeId = data[0];
|
||||
int targetSiteId = data[1];
|
||||
int newX = data[2];
|
||||
int newY = data[3];
|
||||
Node node = new Node();
|
||||
|
||||
for (Site site : Server.site) { // Server.site je List<Site>
|
||||
for (Node n : site.getNode()) {
|
||||
if (n.getId() == nodeId) {
|
||||
// najdeme node v puvodni mape a ulozime si ho
|
||||
node = n;
|
||||
// odebereme z puvodni site
|
||||
site.getNode().remove(n);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nastavime nové hodnoty x a y
|
||||
node.setX(newX);
|
||||
node.setY(newY);
|
||||
node.setSiteId(targetSiteId);
|
||||
|
||||
// najdeme cilovou site a vlozime do ni node
|
||||
for (Site site : Server.site) { // Server.site je List<Site>
|
||||
if (site.getId() == targetSiteId) {
|
||||
site.getNode().add(node);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// upravime v databazi
|
||||
Database.editNode(node);
|
||||
|
||||
// odesleme delete z puvodni site klientum
|
||||
ServerHandler.sendAll(Message.NODE_REMOVE, nodeId);
|
||||
|
||||
// odesleme klientum node do nove site
|
||||
ServerHandler.sendAll(Message.NODE_NEW, node);
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
|
||||
public class RegisterNodePositionChange implements Register {
|
||||
|
||||
public RegisterNodePositionChange() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
int[] data = (int[]) msg.getMsg();
|
||||
int nodeId = data[0];
|
||||
int x = data[1];
|
||||
int y = data[2];
|
||||
|
||||
// najit node v seznamu a upravit mu pozici
|
||||
boolean changed = false;
|
||||
for (Site site : Server.site) {
|
||||
for (Node node : site.getNode()) {
|
||||
if (node.getId() == nodeId) {
|
||||
// zmenit v seznamu
|
||||
node.setX(x);
|
||||
node.setY(y);
|
||||
// zmenit v databazi
|
||||
Database.nodeUpdatePosition(nodeId, x, y);
|
||||
// odeslat novou pozici klientum
|
||||
ServerHandler.sendAll(new Message(Message.NODE_CHANGE_POSITION, msg.getMsg()));
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.NodeProbe;
|
||||
import jnet.server.Database;
|
||||
|
||||
|
||||
public class RegisterNodeProbeNew implements Register {
|
||||
|
||||
public RegisterNodeProbeNew() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
NodeProbe probe = (NodeProbe) msg.getMsg();
|
||||
|
||||
// vlozeni do databaze
|
||||
Database.addNodeProbe(probe);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.Message;
|
||||
import jnet.server.Server;
|
||||
|
||||
|
||||
public class RegisterServerRestart implements Register {
|
||||
|
||||
public RegisterServerRestart() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
restartServer();
|
||||
}
|
||||
|
||||
private void restartServer() {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
try {
|
||||
String java = System.getProperty("java.home") + "/bin/java";
|
||||
File jarFile = new File(Server.class
|
||||
.getProtectionDomain().getCodeSource().getLocation().getPath());
|
||||
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add(java);
|
||||
command.add("-jar");
|
||||
command.add(jarFile.getAbsolutePath());
|
||||
|
||||
new ProcessBuilder(command).start();
|
||||
System.exit(0);
|
||||
} catch (IOException ex) {
|
||||
LogFile.printErr("Restart failed! " + ex.getMessage());
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
LogFile.printErr("Restart failed! " + e.getMessage());
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import jnet.lib.Message;
|
||||
|
||||
|
||||
public class RegisterServerUptime implements Register {
|
||||
|
||||
public RegisterServerUptime() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
|
||||
ctx.writeAndFlush(new Message(Message.SERVER_UPTIME_RESULT, uptime));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
public class RegisterSideDelete implements Register {
|
||||
|
||||
public RegisterSideDelete() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
int id = (int) msg.getMsg();
|
||||
// odebere ze seznamu
|
||||
Server.site.removeIf(site -> site.getId() == id);
|
||||
// odebere z databaze
|
||||
Database.removeSite(id);
|
||||
// odessle novy seznam map
|
||||
ServerHandler.sendAll(new Message(Message.SITE_LIST, Server.site));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
|
||||
public class RegisterSiteAdd implements Register {
|
||||
|
||||
public RegisterSiteAdd() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
String name = (String) msg.getMsg();
|
||||
// vlozeni do databaze a ziskani id vlozeneho radku
|
||||
int siteId = Database.addSite(name);
|
||||
// priprava Site objektu
|
||||
Site site= new Site(siteId, name);
|
||||
// pridání do seznamu na serveru
|
||||
Server.site.add(site);
|
||||
// odeslani nove mapy vsem klientum
|
||||
ServerHandler.sendAll(new Message(Message.SITE_NEW, site));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
|
||||
public class RegisterSiteSetLock implements Register{
|
||||
|
||||
public RegisterSiteSetLock() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
Object[] data = (Object[]) msg.getMsg();
|
||||
|
||||
for (Site site : Server.site) {
|
||||
if (site.getId() == (int) data[0]) {
|
||||
// zamknout v lokalnim seznamu
|
||||
site.setLock((boolean) data[1]);
|
||||
// zamknout v databazi
|
||||
Database.setSiteLock((boolean) data[1], (int) data[0]);
|
||||
// odeslat informaci klientum
|
||||
ServerHandler.sendAll(new Message(Message.SITE_LOCK, data));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import java.io.IOException;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.DeviceInfo;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.SnmpProfile;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.snmp.SNMPDeviceInfo;
|
||||
|
||||
public class RegisterSnmpNodeInfo implements Register {
|
||||
|
||||
public RegisterSnmpNodeInfo() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
try {
|
||||
Object[] data = (Object[]) msg.getMsg();
|
||||
String frame = (String) data[0];
|
||||
Node node = (Node) data[1];
|
||||
// zjistit snmp profile
|
||||
SnmpProfile snmpProfile = Server.snmpProfile.stream()
|
||||
.filter(profile -> profile.getId() == node.getSnmpProfile())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (snmpProfile != null) {
|
||||
// odeslat pozadavek
|
||||
SNMPDeviceInfo snmp = new SNMPDeviceInfo(node.getIp(), snmpProfile.getPort(), snmpProfile.getCommunityRead(), snmpProfile.getVersion());
|
||||
DeviceInfo info = snmp.getDeviceInfo(); // spojení se automaticky uzavře
|
||||
Object[] result = {frame, info};
|
||||
ctx.writeAndFlush(new Message(Message.NODE_SNMP_INFO_RESULT, result));
|
||||
}
|
||||
|
||||
} catch (IOException ex) {
|
||||
LogFile.printErr("SNMP info error: " + ex.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.Interface;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.SnmpProfile;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.snmp.SNMPInterfaceScanner;
|
||||
|
||||
|
||||
public class RegisterSnmpNodeInterface implements Register {
|
||||
|
||||
public RegisterSnmpNodeInterface() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
try {
|
||||
Object[] data = (Object[]) msg.getMsg();
|
||||
String frame = (String) data[0];
|
||||
Node node = (Node) data[1];
|
||||
// zjistit snmp profile
|
||||
SnmpProfile snmpProfile = Server.snmpProfile.stream()
|
||||
.filter(profile -> profile.getId() == node.getSnmpProfile())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (snmpProfile != null) {
|
||||
// odeslat pozadavek
|
||||
SNMPInterfaceScanner scanner = new SNMPInterfaceScanner(
|
||||
node.getIp(),
|
||||
snmpProfile.getPort(),
|
||||
snmpProfile.getCommunityRead(),
|
||||
snmpProfile.getVersion()
|
||||
);
|
||||
|
||||
List<Interface> ifaces = scanner.scanInterfaces();
|
||||
Object[] result = {frame, ifaces};
|
||||
ctx.writeAndFlush(new Message(Message.NODE_SNMP_INTERFACE_RESULT, result));
|
||||
}
|
||||
|
||||
} catch (IOException ex) {
|
||||
LogFile.printErr("SNMP interface scan error: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import org.snmp4j.CommunityTarget;
|
||||
import org.snmp4j.PDU;
|
||||
import org.snmp4j.Snmp;
|
||||
import org.snmp4j.Target;
|
||||
import org.snmp4j.TransportMapping;
|
||||
import org.snmp4j.event.ResponseEvent;
|
||||
import org.snmp4j.mp.SnmpConstants;
|
||||
import org.snmp4j.smi.Address;
|
||||
import org.snmp4j.smi.GenericAddress;
|
||||
import org.snmp4j.smi.OID;
|
||||
import org.snmp4j.smi.OctetString;
|
||||
import org.snmp4j.smi.VariableBinding;
|
||||
import org.snmp4j.transport.DefaultUdpTransportMapping;
|
||||
|
||||
public class RegisterSnmpTest implements Register {
|
||||
|
||||
public RegisterSnmpTest() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
Object[] data = (Object[]) msg.getMsg();
|
||||
String ip = (String) data[0];
|
||||
String port = (String) data[1];
|
||||
int version = (int) data[2];
|
||||
String communityRead = (String) data[3];
|
||||
String frame = (String) data[4];
|
||||
|
||||
String result = testSnmpGet(ip, port, communityRead, ".1.3.6.1.2.1.1.1.0", version, 5*1000);
|
||||
if (result.startsWith("ERROR:")) {
|
||||
Object[] reply = {frame, false};
|
||||
ctx.writeAndFlush(new Message(Message.SNMP_TEST_RESULT, reply));
|
||||
} else {
|
||||
Object[] reply = {frame, true};
|
||||
ctx.writeAndFlush(new Message(Message.SNMP_TEST_RESULT, reply));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Otestuje SNMP GET na zadaném zařízení.
|
||||
*
|
||||
* @param ip IP adresa (např. "192.168.1.100")
|
||||
* @param community Komunitní řetězec (např. "public")
|
||||
* @param oid OID ve tvaru ".1.3.6.1.2.1.1.1.0" nebo "1.3.6.1.2.1.1.1.0"
|
||||
* @param timeoutMs Timeout v milisekundách (např. 3000)
|
||||
* @return String s hodnotou OID, nebo zpráva začínající "ERROR: " při chybě
|
||||
*/
|
||||
public static String testSnmpGet(String ip, String port, String community, String oid,
|
||||
int version, int timeoutMs) {
|
||||
try (TransportMapping<?> transport = new DefaultUdpTransportMapping();
|
||||
Snmp snmp = new Snmp(transport)) {
|
||||
transport.listen();
|
||||
|
||||
Address targetAddress = GenericAddress.parse("udp:" + ip + "/"+port);
|
||||
Target target;
|
||||
|
||||
if (version == 1 || version == 2) {
|
||||
// SNMPv1 nebo v2c
|
||||
CommunityTarget ct = new CommunityTarget();
|
||||
ct.setCommunity(new OctetString(community));
|
||||
ct.setVersion(version == 1 ? SnmpConstants.version1 : SnmpConstants.version2c);
|
||||
target = ct;
|
||||
} else if (version == 3) {
|
||||
// SNMPv3 – vyžaduje další údaje (uživatel, auth, priv)
|
||||
// Zde je potřeba předat i jméno, hesla – proto raději udělejte přetíženou verzi
|
||||
return "ERROR: Pro SNMPv3 použijte speciální funkci s parametry auth/priv.";
|
||||
} else {
|
||||
return "ERROR: Neznámá verze SNMP (povoleno 1, 2, 3)";
|
||||
}
|
||||
|
||||
target.setAddress(targetAddress);
|
||||
target.setTimeout(timeoutMs);
|
||||
target.setRetries(1);
|
||||
|
||||
PDU pdu = new PDU();
|
||||
pdu.add(new VariableBinding(new OID(oid)));
|
||||
pdu.setType(PDU.GET);
|
||||
|
||||
ResponseEvent event = snmp.send(pdu, target);
|
||||
PDU response = event.getResponse();
|
||||
|
||||
if (response == null) {
|
||||
return "ERROR: Žádná odpověď (timeout)";
|
||||
}
|
||||
VariableBinding vb = response.get(0);
|
||||
return (vb == null) ? "ERROR: Prázdná odpověď" : vb.getVariable().toString();
|
||||
|
||||
} catch (Exception e) {
|
||||
return "ERROR: " + e.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.PasswordHashing;
|
||||
import jnet.lib.object.User;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
|
||||
public class RegisterUserAdd implements Register {
|
||||
|
||||
public RegisterUserAdd() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
User u = (User) msg.getMsg();
|
||||
u.setPassword(PasswordHashing.hash(u.getPassword()));
|
||||
//pridáni do databáze a nastaveni id
|
||||
u.setId(Database.addUser(u));
|
||||
// přidání do seznamu
|
||||
Server.users.add(u);
|
||||
// odeslat klientum novy seznam uzivatelu
|
||||
ServerHandler.sendAll(new Message(Message.USER_LIST, Server.users));
|
||||
// odeslat klientovi infomraci o pridani a aktualizaci tabulky
|
||||
ctx.writeAndFlush(new Message(Message.USER_REFRESH, null));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
package jnet.server.message;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.PasswordHashing;
|
||||
import jnet.lib.object.User;
|
||||
import jnet.server.Database;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
public class RegisterUserEdit implements Register {
|
||||
|
||||
public RegisterUserEdit() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processing(ChannelHandlerContext ctx, Message msg) {
|
||||
User u = (User) msg.getMsg();
|
||||
// bude se editovat heslo ?
|
||||
if (u.getPassword() != null) {
|
||||
u.setPassword(PasswordHashing.hash(u.getPassword()));
|
||||
}
|
||||
// ulozeni do databaze
|
||||
Database.editUser(u);
|
||||
// aktualizace v seznamu
|
||||
for (int i = 0; i < Server.users.size(); i++) {
|
||||
if (Server.users.get(i).getId() == u.getId()) {
|
||||
// nahradi node v seznamu
|
||||
Server.users.set(i, u);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// odeslat klientum novy seznam uzivatelu
|
||||
ServerHandler.sendAll(new Message(Message.USER_LIST, Server.users));
|
||||
// odeslat klientovi infomraci o pridani a aktualizaci tabulky
|
||||
ctx.writeAndFlush(new Message(Message.USER_REFRESH, null));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
package jnet.server.networkserver;
|
||||
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
import jnet.lib.LogFile;
|
||||
|
||||
public class NettyServerManager {
|
||||
|
||||
private EventLoopGroup boss;
|
||||
private EventLoopGroup worker;
|
||||
private ChannelFuture serverChannelFuture;
|
||||
|
||||
public void start(int port) {
|
||||
Thread serverThread = new Thread(() -> {
|
||||
boss = new NioEventLoopGroup(1);
|
||||
worker = new NioEventLoopGroup();
|
||||
|
||||
try {
|
||||
SslContext sslCtx = SslUtil.createServerSslContext();
|
||||
ServerBootstrap b = new ServerBootstrap();
|
||||
b.group(boss, worker)
|
||||
.channel(NioServerSocketChannel.class)
|
||||
.childHandler(new ServerInitializer(sslCtx))
|
||||
.childOption(ChannelOption.SO_KEEPALIVE, true);
|
||||
|
||||
LogFile.printInfo("Starting Netty on port " + port);
|
||||
serverChannelFuture = b.bind(port).sync();
|
||||
|
||||
// Čeká na uzavření kanálu
|
||||
serverChannelFuture.channel().closeFuture().sync();
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
LogFile.printInfo("Netty server interrupted.");
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (Exception e) {
|
||||
LogFile.printInfo("Netty error: " + e.getMessage());
|
||||
} finally {
|
||||
stop();
|
||||
}
|
||||
}, "Netty-Server-Thread");
|
||||
|
||||
serverThread.start();
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
if (boss != null && !boss.isShuttingDown()) {
|
||||
LogFile.printInfo("Shutting down Netty gracefully...");
|
||||
// Gracefully uzavře kanály, počká na dokončení probíhajících zápisů a ukončí vlákna
|
||||
boss.shutdownGracefully();
|
||||
worker.shutdownGracefully();
|
||||
LogFile.printInfo("Netty stopped.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package jnet.server.networkserver;
|
||||
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
|
||||
public class SecureServer {
|
||||
public static void main(String[] args) throws Exception {
|
||||
SslContext sslCtx = SslUtil.createServerSslContext();
|
||||
|
||||
EventLoopGroup boss = new NioEventLoopGroup(1);
|
||||
EventLoopGroup worker = new NioEventLoopGroup();
|
||||
|
||||
try {
|
||||
ServerBootstrap b = new ServerBootstrap();
|
||||
b.group(boss, worker)
|
||||
.channel(NioServerSocketChannel.class)
|
||||
.childHandler(new ServerInitializer(sslCtx))
|
||||
.childOption(ChannelOption.SO_KEEPALIVE, true);
|
||||
|
||||
b.bind(8443).sync().channel().closeFuture().sync();
|
||||
} finally {
|
||||
boss.shutdownGracefully();
|
||||
worker.shutdownGracefully();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
package jnet.server.networkserver;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import io.netty.channel.group.ChannelGroup;
|
||||
import io.netty.channel.group.DefaultChannelGroup;
|
||||
import io.netty.util.concurrent.GlobalEventExecutor;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.OnlineClients;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.message.MessageRegister;
|
||||
import jnet.server.message.Register;
|
||||
|
||||
public class ServerHandler extends SimpleChannelInboundHandler<Object> {
|
||||
|
||||
private final MessageRegister messageRegistr = new MessageRegister();
|
||||
|
||||
private static final ChannelGroup allChannels
|
||||
= new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
|
||||
|
||||
@Override
|
||||
public void channelActive(ChannelHandlerContext ctx) {
|
||||
LogFile.printInfo("New client: " + ctx.channel().remoteAddress());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelInactive(ChannelHandlerContext ctx) {
|
||||
LogFile.printInfo("Client: " + ctx.channel().remoteAddress() + " disconnected");
|
||||
// odebere kanal
|
||||
allChannels.remove(ctx.channel());
|
||||
// odebere ze seznamu klientu
|
||||
Server.onlineClients.removeIf(onlineClient
|
||||
-> onlineClient.getId().equals(String.valueOf(ctx.channel().id()))
|
||||
);
|
||||
// odesle zmenu stavajicim klientum
|
||||
sendAll(new Message(Message.ONLINE_CLIENTS, Server.onlineClients));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
|
||||
|
||||
if (msg instanceof Message) {
|
||||
Message message = (Message) msg;
|
||||
LogFile.printDebug("Received message ID: " + message.getType());
|
||||
Register register = messageRegistr.getRegister(message.getType());
|
||||
if (register != null) {
|
||||
register.processing(ctx, message);
|
||||
}
|
||||
|
||||
} else {
|
||||
LogFile.printDebug("Unknown message received");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
||||
if (cause instanceof java.net.SocketException && cause.getMessage().contains("Connection reset")) {
|
||||
LogFile.printInfo("Client abruptly disconnected: " + ctx.channel().remoteAddress());
|
||||
} else {
|
||||
cause.printStackTrace();
|
||||
}
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
public static void addChannel(ChannelHandlerContext ctx) {
|
||||
allChannels.add(ctx.channel());
|
||||
}
|
||||
|
||||
public static ChannelGroup getAllChannels() {
|
||||
return allChannels;
|
||||
}
|
||||
|
||||
public static void sendAll(Message msq) {
|
||||
getAllChannels().writeAndFlush(msq);
|
||||
}
|
||||
|
||||
public static void sendAll(int type, Object msg) {
|
||||
getAllChannels().writeAndFlush(new Message(type, msg));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
package jnet.server.networkserver;
|
||||
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.handler.codec.serialization.ClassResolvers;
|
||||
import io.netty.handler.codec.serialization.ObjectDecoder;
|
||||
import io.netty.handler.codec.serialization.ObjectEncoder;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
|
||||
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
|
||||
|
||||
private final SslContext sslCtx;
|
||||
|
||||
public ServerInitializer(SslContext sslCtx) {
|
||||
this.sslCtx = sslCtx;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void initChannel(SocketChannel ch) {
|
||||
ch.pipeline()
|
||||
.addLast("ssl", sslCtx.newHandler(ch.alloc()))
|
||||
// ObjectDecoder používá LengthFieldBasedFrameDecoder automaticky
|
||||
//.addLast("objectDecoder", new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
|
||||
//.addLast("objectEncoder", new ObjectEncoder())
|
||||
.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
|
||||
.addLast(new ObjectEncoder())
|
||||
.addLast("handler", new ServerHandler());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package jnet.server.networkserver;
|
||||
|
||||
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
import io.netty.handler.ssl.SslContextBuilder;
|
||||
import io.netty.handler.ssl.util.SelfSignedCertificate;
|
||||
|
||||
public class SslUtil {
|
||||
public static SslContext createServerSslContext() throws Exception {
|
||||
SelfSignedCertificate ssc = new SelfSignedCertificate();
|
||||
return SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
package jnet.server.probe;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.OSDetector;
|
||||
import jnet.lib.Status;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.NodeState;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.EventManager;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.SiteOperation;
|
||||
import jnet.server.probe.ping.MonitorEngine;
|
||||
import jnet.server.probe.ping.PingEngine;
|
||||
import jnet.server.probe.ping.RawIcmpPingEngine;
|
||||
|
||||
public class Ping {
|
||||
|
||||
private static MonitorEngine engine;
|
||||
|
||||
public static void start() {
|
||||
try {
|
||||
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||
scheduler.schedule(() -> {
|
||||
run();
|
||||
}, 5, TimeUnit.SECONDS);
|
||||
scheduler.shutdown();
|
||||
scheduler.awaitTermination(10, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException ex) {
|
||||
LogFile.printErr("Failed runing ping probe: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void run() {
|
||||
LogFile.printInfo("Ping probe starting...");
|
||||
|
||||
// Vytvoření mapy nodeId -> IP
|
||||
Map<String, String> nodeIdToIp = new HashMap<>();
|
||||
for (Site site : Server.site) {
|
||||
for (Node node : site.getNode()) {
|
||||
if (node.getType() == 1 && node.isPing()) {
|
||||
// prida jen kdyz je typ=1 (zarizeni) a ping je zapnut
|
||||
nodeIdToIp.put(String.valueOf(node.getId()), node.getIp());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
LogFile.printInfo("Loaded " + nodeIdToIp.size() + " targets.");
|
||||
|
||||
if (nodeIdToIp.isEmpty()) {
|
||||
LogFile.printInfo("No targets to monitor, exiting.");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (OSDetector.isWindows()) {
|
||||
LogFile.printInfo("OS is Windows - using PingEngine (subprocess ping)");
|
||||
// OPRAVA: cyklus každých 10 sekund, timeout 2 sekundy
|
||||
engine = new PingEngine(10, 10, 2);
|
||||
} else if (OSDetector.isDebian()) {
|
||||
LogFile.printInfo("OS is Debian - using RawIcmpPingEngine");
|
||||
engine = new RawIcmpPingEngine(10, 3000, 2);
|
||||
} else {
|
||||
LogFile.printInfo("OS is undefined - ping not running");
|
||||
return;
|
||||
}
|
||||
engine.setTargets(nodeIdToIp);
|
||||
LogFile.printInfo("Targets set.");
|
||||
|
||||
// Listener pro změny stavu
|
||||
engine.addListener(event -> {
|
||||
// Sestavíme text s latencí
|
||||
String latencyText = event.up() ? event.latencyMs() + " ms" : "N/A";
|
||||
// Toto se vypíše při každé kontrole (i když není změna)
|
||||
// Detailní výpis všech informací
|
||||
// LogFile.printDebug("Listener: node=" + event.nodeId() +
|
||||
// ", ip=" + event.ip() +
|
||||
// ", up=" + event.up() +
|
||||
// ", latency=" + latencyText +
|
||||
// ", firstReport=" + event.firstReport() +
|
||||
// ", stateChanged=" + event.stateChanged());
|
||||
//
|
||||
NodeState nodeState = null;
|
||||
if (event.firstReport()) {
|
||||
if (event.up()) {
|
||||
nodeState = new NodeState(Integer.parseInt(event.nodeId()), Status.OK);
|
||||
} else {
|
||||
EventManager.insertOfflineEvent(Integer.parseInt(event.nodeId()));
|
||||
nodeState = new NodeState(Integer.parseInt(event.nodeId()), Status.OFFLINE);
|
||||
}
|
||||
SiteOperation.updateNodeStatus(nodeState);
|
||||
} else if (event.stateChanged()) {
|
||||
LogFile.printDebug("CHANGE: " + event.describe());
|
||||
if (event.up()) {
|
||||
EventManager.endEvent(Integer.parseInt(event.nodeId()));
|
||||
nodeState = new NodeState(Integer.parseInt(event.nodeId()), Status.OK);
|
||||
} else {
|
||||
EventManager.insertOfflineEvent(Integer.parseInt(event.nodeId()));
|
||||
nodeState = new NodeState(Integer.parseInt(event.nodeId()), Status.OFFLINE);
|
||||
}
|
||||
SiteOperation.updateNodeStatus(nodeState);
|
||||
}
|
||||
});
|
||||
|
||||
LogFile.printInfo("Starting engine...");
|
||||
try {
|
||||
engine.start();
|
||||
LogFile.printInfo("Engine started successfully.");
|
||||
} catch (Exception e) {
|
||||
LogFile.printErr("Failed to start engine: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void addOrUpdateTarget(int nodeId, String ip) {
|
||||
engine.addOrUpdateTarget(String.valueOf(nodeId), ip);
|
||||
}
|
||||
|
||||
public static void removeTarget(int nodeId) {
|
||||
engine.removeTarget(String.valueOf(nodeId));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import com.sun.jna.Library;
|
||||
import com.sun.jna.Native;
|
||||
import com.sun.jna.Pointer;
|
||||
import com.sun.jna.ptr.IntByReference;
|
||||
|
||||
/**
|
||||
* Mapovani vybranych funkci standardni C knihovny (libc) pres JNA.
|
||||
* Umoznuje otevrit RAW ICMP socket, coz standardni java.net API neumoznuje.
|
||||
*
|
||||
* DULEZITE: otevreni SOCK_RAW socketu vyzaduje bud beh pod rootem, nebo
|
||||
* capability CAP_NET_RAW nastavenou na java binarce:
|
||||
*
|
||||
* sudo setcap cap_net_raw+ep $(readlink -f $(which java))
|
||||
*
|
||||
* (Pozor: setcap se musi nastavit na *skutecny* java binary, ne na symlink
|
||||
* spravovany update-alternatives, ktery se muze pri aktualizaci JDK zmenit -
|
||||
* pouzijte radeji plnou cestu k danemu JDK, viz README.)
|
||||
*/
|
||||
public interface CLibrary extends Library {
|
||||
|
||||
CLibrary INSTANCE = Native.load("c", CLibrary.class);
|
||||
|
||||
int socket(int domain, int type, int protocol);
|
||||
|
||||
int close(int fd);
|
||||
|
||||
int sendto(int sockfd, byte[] buf, int len, int flags, SockAddrIn destAddr, int addrlen);
|
||||
|
||||
int recvfrom(int sockfd, byte[] buf, int len, int flags, Pointer srcAddr, Pointer addrlen);
|
||||
|
||||
int setsockopt(int sockfd, int level, int optname, Timeval optval, int optlen);
|
||||
|
||||
int setsockopt(int sockfd, int level, int optname, IntByReference optval, int optlen);
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Sestaveni/parsovani ICMP paketu (RFC 792) na bajtove urovni.
|
||||
*/
|
||||
public final class IcmpPacketBuilder {
|
||||
|
||||
private static final int ICMP_ECHO_REQUEST = 8;
|
||||
private static final int ICMP_ECHO_REPLY = 0;
|
||||
|
||||
private IcmpPacketBuilder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sestavi ICMP echo request packet (hlavicka + payload) vcetne spocitaneho checksumu.
|
||||
*/
|
||||
public static byte[] buildEchoRequest(int identifier, int sequence, byte[] payload) {
|
||||
byte[] packet = new byte[8 + payload.length];
|
||||
packet[0] = (byte) ICMP_ECHO_REQUEST;
|
||||
packet[1] = 0; // code
|
||||
packet[2] = 0; // checksum - doplnime az po spocitani
|
||||
packet[3] = 0;
|
||||
packet[4] = (byte) ((identifier >> 8) & 0xFF);
|
||||
packet[5] = (byte) (identifier & 0xFF);
|
||||
packet[6] = (byte) ((sequence >> 8) & 0xFF);
|
||||
packet[7] = (byte) (sequence & 0xFF);
|
||||
System.arraycopy(payload, 0, packet, 8, payload.length);
|
||||
|
||||
int checksum = checksum(packet);
|
||||
packet[2] = (byte) ((checksum >> 8) & 0xFF);
|
||||
packet[3] = (byte) (checksum & 0xFF);
|
||||
return packet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standardni 16-bitovy jednickovy doplnkovy soucet (one's complement checksum)
|
||||
* pouzivany ICMP i IP hlavickami.
|
||||
*/
|
||||
static int checksum(byte[] buf) {
|
||||
int sum = 0;
|
||||
int i = 0;
|
||||
int length = buf.length;
|
||||
|
||||
while (length > 1) {
|
||||
int word = ((buf[i] << 8) & 0xFF00) | (buf[i + 1] & 0xFF);
|
||||
sum += word;
|
||||
if ((sum & 0xFFFF0000) != 0) {
|
||||
sum &= 0xFFFF;
|
||||
sum += 1;
|
||||
}
|
||||
i += 2;
|
||||
length -= 2;
|
||||
}
|
||||
|
||||
if (length > 0) {
|
||||
sum += (buf[i] << 8) & 0xFF00;
|
||||
if ((sum & 0xFFFF0000) != 0) {
|
||||
sum &= 0xFFFF;
|
||||
sum += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return (~sum) & 0xFFFF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rozparsuje surova prijata data z raw socketu (obsahuji IP hlavicku + ICMP zpravu)
|
||||
* a vrati identifier/sequence z ICMP echo reply, nebo null, pokud to neni echo reply.
|
||||
*/
|
||||
public static ParsedReply parseEchoReply(byte[] buf, int length) {
|
||||
if (length < 20) return null; // min. delka IP hlavicky
|
||||
|
||||
int ihl = (buf[0] & 0x0F) * 4; // Internet Header Length v bajtech
|
||||
if (length < ihl + 8) return null;
|
||||
|
||||
int type = buf[ihl] & 0xFF;
|
||||
if (type != ICMP_ECHO_REPLY) return null;
|
||||
|
||||
int identifier = ((buf[ihl + 4] & 0xFF) << 8) | (buf[ihl + 5] & 0xFF);
|
||||
int sequence = ((buf[ihl + 6] & 0xFF) << 8) | (buf[ihl + 7] & 0xFF);
|
||||
byte[] sourceAddress = Arrays.copyOfRange(buf, 12, 16);
|
||||
|
||||
return new ParsedReply(identifier, sequence, sourceAddress);
|
||||
}
|
||||
|
||||
public record ParsedReply(int identifier, int sequence, byte[] sourceAddress) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Reprezentuje jeden monitorovany cil - IP adresu se jejim aktualnim stavem.
|
||||
* Pole jsou volatile/atomicka, protoze do nich zapisuji paralelni ping-vlakna
|
||||
* a zaroven se z nich cte pri generovani web dashboardu.
|
||||
*/
|
||||
public class IpTarget {
|
||||
|
||||
public final String nodeId; // unikátní identifikátor (primární klíč)
|
||||
public volatile String ip; // IP adresa (může se měnit, volatile pro viditelnost)
|
||||
|
||||
public volatile boolean up = false;
|
||||
public volatile boolean everChecked = false;
|
||||
public volatile long lastLatencyMs = -1;
|
||||
|
||||
public volatile LocalDateTime lastChange;
|
||||
public volatile LocalDateTime lastCheck;
|
||||
|
||||
public volatile int consecutiveFails = 0;
|
||||
public volatile int consecutiveOk = 0;
|
||||
|
||||
public IpTarget(String nodeId, String ip) {
|
||||
this.nodeId = nodeId;
|
||||
this.ip = ip;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Spolecne rozhrani pro monitorovaci engine - umoznuje mit vice implementaci
|
||||
* (subprocess ping vs. raw ICMP socket) se stejnym verejnym API, takze zbytek
|
||||
* aplikace (napr. napojeni na Netty) neni na konkretni implementaci zavisly.
|
||||
*/
|
||||
public interface MonitorEngine {
|
||||
|
||||
void addOrUpdateTarget(String nodeId, String ip);
|
||||
|
||||
void removeTarget(String nodeId);
|
||||
|
||||
void setTargets(Map<String, String> nodeIdToIp); // nodeId -> IP
|
||||
|
||||
Collection<IpTarget> getTargets();
|
||||
|
||||
void addListener(StatusListener listener);
|
||||
|
||||
void removeListener(StatusListener listener);
|
||||
|
||||
void start();
|
||||
|
||||
void stop();
|
||||
}
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import jnet.lib.LogFile;
|
||||
|
||||
public class PingEngine implements MonitorEngine {
|
||||
|
||||
private final ConcurrentHashMap<String, IpTarget> targets = new ConcurrentHashMap<>();
|
||||
private final CopyOnWriteArrayList<StatusListener> listeners = new CopyOnWriteArrayList<>();
|
||||
|
||||
private final ExecutorService pingPool;
|
||||
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||
private final int cycleIntervalSeconds;
|
||||
private final int pingTimeoutSeconds;
|
||||
|
||||
private ScheduledFuture<?> cycleHandle;
|
||||
private Path watchedFile;
|
||||
private long watchedFileLastModified = -1;
|
||||
|
||||
public PingEngine(int threadPoolSize, int cycleIntervalSeconds, int pingTimeoutSeconds) {
|
||||
this.pingPool = Executors.newFixedThreadPool(threadPoolSize);
|
||||
this.cycleIntervalSeconds = cycleIntervalSeconds;
|
||||
this.pingTimeoutSeconds = pingTimeoutSeconds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addOrUpdateTarget(String nodeId, String ip) {
|
||||
//LogFile.printDebug("ADD ping target (node: " + nodeId + " ip: " + ip + ")");
|
||||
targets.compute(nodeId, (k, existing) -> {
|
||||
if (existing == null) {
|
||||
return new IpTarget(nodeId, ip);
|
||||
} else {
|
||||
if (!existing.ip.equals(ip)) {
|
||||
existing.ip = ip;
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTarget(String nodeId) {
|
||||
targets.remove(nodeId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTargets(Map<String, String> nodeIdToIp) {
|
||||
targets.keySet().retainAll(nodeIdToIp.keySet());
|
||||
for (Map.Entry<String, String> entry : nodeIdToIp.entrySet()) {
|
||||
addOrUpdateTarget(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<IpTarget> getTargets() {
|
||||
return targets.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addListener(StatusListener listener) {
|
||||
listeners.add(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeListener(StatusListener listener) {
|
||||
listeners.remove(listener);
|
||||
}
|
||||
|
||||
public void enableFileWatch(Path file) {
|
||||
this.watchedFile = file;
|
||||
reloadFromFileIfChanged();
|
||||
}
|
||||
|
||||
private void reloadFromFileIfChanged() {
|
||||
if (watchedFile == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
File f = watchedFile.toFile();
|
||||
if (!f.exists()) {
|
||||
return;
|
||||
}
|
||||
long modified = f.lastModified();
|
||||
if (modified == watchedFileLastModified) {
|
||||
return;
|
||||
}
|
||||
watchedFileLastModified = modified;
|
||||
|
||||
Set<String> seen = new HashSet<>();
|
||||
List<String> lines = Files.readAllLines(watchedFile);
|
||||
for (String raw : lines) {
|
||||
String line = raw.trim();
|
||||
if (line.isEmpty() || line.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
String[] parts = line.split(",", 2);
|
||||
String nodeId = parts[0].trim();
|
||||
String ip = parts.length > 1 ? parts[1].trim() : nodeId;
|
||||
if (nodeId.isEmpty() || ip.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
seen.add(nodeId);
|
||||
addOrUpdateTarget(nodeId, ip);
|
||||
}
|
||||
targets.keySet().retainAll(seen);
|
||||
} catch (IOException e) {
|
||||
System.err.println("Chyba při načítání " + watchedFile + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
cycleHandle = scheduler.scheduleAtFixedRate(
|
||||
this::runCycle, 0, cycleIntervalSeconds, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (cycleHandle != null) {
|
||||
cycleHandle.cancel(true);
|
||||
}
|
||||
scheduler.shutdownNow();
|
||||
pingPool.shutdownNow();
|
||||
}
|
||||
|
||||
private void runCycle() {
|
||||
reloadFromFileIfChanged();
|
||||
|
||||
for (IpTarget target : targets.values()) {
|
||||
CompletableFuture
|
||||
.supplyAsync(() -> PingUtil.ping(target.ip, pingTimeoutSeconds), pingPool)
|
||||
.thenAccept(latencyMs -> handleResult(target, latencyMs))
|
||||
.exceptionally(ex -> {
|
||||
System.err.println("Chyba při pingu " + target.ip + ": " + ex.getMessage());
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== OPRAVENÁ METODA ====================
|
||||
private void handleResult(IpTarget target, long latencyMs) {
|
||||
boolean nowUp = latencyMs >= 0;
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
boolean everCheckedBefore = target.everChecked;
|
||||
|
||||
// ULOŽÍME STARÝ STAV PŘED PŘEPSÁNÍM
|
||||
boolean previouslyReportedUp = target.up;
|
||||
|
||||
target.up = nowUp;
|
||||
target.lastLatencyMs = nowUp ? latencyMs : -1;
|
||||
target.lastCheck = now;
|
||||
target.everChecked = true;
|
||||
|
||||
if (nowUp) {
|
||||
target.consecutiveOk++;
|
||||
target.consecutiveFails = 0;
|
||||
} else {
|
||||
target.consecutiveFails++;
|
||||
target.consecutiveOk = 0;
|
||||
}
|
||||
|
||||
// POROVNÁVÁME S ULOŽENÝM STARÝM STAVEM
|
||||
boolean stateChanged = everCheckedBefore && (nowUp != previouslyReportedUp);
|
||||
if (stateChanged) {
|
||||
target.lastChange = now;
|
||||
}
|
||||
|
||||
boolean firstReport = !everCheckedBefore;
|
||||
|
||||
StatusEvent event = new StatusEvent(
|
||||
target.nodeId,
|
||||
target.ip,
|
||||
nowUp,
|
||||
target.lastLatencyMs,
|
||||
stateChanged,
|
||||
firstReport,
|
||||
now
|
||||
);
|
||||
|
||||
for (StatusListener listener : listeners) {
|
||||
listener.onUpdate(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Provadi ICMP ping pomoci systemoveho prikazu "ping".
|
||||
*
|
||||
* Proc systemovy prikaz a ne InetAddress.isReachable()?
|
||||
* - isReachable() potrebuje bezet pod rootem, aby pouzil skutecne ICMP echo,
|
||||
* jinak casto padne zpet na TCP echo (port 7), coz na vetsine cilu neprojde.
|
||||
* - Systemovy binarni "ping" na Linuxu ma nastaveny setuid bit, takze funguje
|
||||
* spolehlive i pod beznym uzivatelem.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Provádí ICMP ping pomocí systemového příkazu "ping".
|
||||
* Detekuje OS a používá správnou syntaxi (Windows vs. Linux).
|
||||
*/
|
||||
public class PingUtil {
|
||||
|
||||
// Regex pro Linux: time=1.23 ms nebo time<1 ms
|
||||
private static final Pattern LINUX_TIME_PATTERN = Pattern.compile("time[=<]\\s*([0-9.]+)");
|
||||
// Regex pro Windows: čas=1ms nebo time=1ms (anglická lokalizace) nebo doba=1ms
|
||||
private static final Pattern WINDOWS_TIME_PATTERN = Pattern.compile("(?:čas|time|doba)[=<]\\s*([0-9.]+)");
|
||||
|
||||
/**
|
||||
* Odešle jeden ICMP echo request.
|
||||
*
|
||||
* @param ip cílová IP adresa nebo hostname
|
||||
* @param timeoutSeconds timeout pro odpověď v sekundách
|
||||
* @return latenci v ms, nebo -1 pokud cil neodpověděl
|
||||
*/
|
||||
public static long ping(String ip, int timeoutSeconds) {
|
||||
try {
|
||||
ProcessBuilder pb;
|
||||
if (isWindows()) {
|
||||
// Windows: ping -n 1 -w timeoutMs ip
|
||||
int timeoutMs = timeoutSeconds * 1000;
|
||||
pb = new ProcessBuilder("ping", "-n", "1", "-w", String.valueOf(timeoutMs), ip);
|
||||
} else {
|
||||
// Linux/Unix: ping -c 1 -W timeoutSeconds ip
|
||||
pb = new ProcessBuilder("ping", "-c", "1", "-W", String.valueOf(timeoutSeconds), ip);
|
||||
}
|
||||
pb.redirectErrorStream(true);
|
||||
Process proc = pb.start();
|
||||
|
||||
String lastTimeMatch = null;
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(proc.getInputStream()))) {
|
||||
String line;
|
||||
Pattern pattern = isWindows() ? WINDOWS_TIME_PATTERN : LINUX_TIME_PATTERN;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
Matcher m = pattern.matcher(line);
|
||||
if (m.find()) {
|
||||
lastTimeMatch = m.group(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boolean finished = proc.waitFor(timeoutSeconds + 2L, TimeUnit.SECONDS);
|
||||
if (!finished) {
|
||||
proc.destroyForcibly();
|
||||
return -1;
|
||||
}
|
||||
|
||||
int exitCode = proc.exitValue();
|
||||
// Na Windows je exit code 0 při úspěchu, na Linuxu také
|
||||
if (exitCode == 0 && lastTimeMatch != null) {
|
||||
return Math.round(Double.parseDouble(lastTimeMatch));
|
||||
}
|
||||
return -1;
|
||||
} catch (Exception e) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isWindows() {
|
||||
return System.getProperty("os.name").toLowerCase().contains("win");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,276 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import com.sun.jna.Native;
|
||||
import com.sun.jna.NativeLong;
|
||||
import com.sun.jna.Pointer;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class RawIcmpPingEngine implements MonitorEngine {
|
||||
|
||||
private static final int AF_INET = 2;
|
||||
private static final int SOCK_RAW = 3;
|
||||
private static final int IPPROTO_ICMP = 1;
|
||||
private static final int SOL_SOCKET = 1;
|
||||
private static final int SO_RCVTIMEO = 20;
|
||||
private static final int SO_RCVBUF = 8;
|
||||
|
||||
private final ConcurrentHashMap<String, IpTarget> targets = new ConcurrentHashMap<>();
|
||||
private final CopyOnWriteArrayList<StatusListener> listeners = new CopyOnWriteArrayList<>();
|
||||
|
||||
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||
private final ExecutorService receiveExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
private final int cycleIntervalSeconds;
|
||||
private final int replyWaitMillis;
|
||||
private final int downThreshold;
|
||||
private final int identifier;
|
||||
|
||||
private final ConcurrentHashMap<Integer, IpTarget> sequenceToTarget = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Integer, Long> sequenceSentAtNanos = new ConcurrentHashMap<>();
|
||||
private final AtomicInteger sequenceCounter = new AtomicInteger(0);
|
||||
|
||||
private int socketFd = -1;
|
||||
private volatile boolean running = false;
|
||||
private ScheduledFuture<?> cycleHandle;
|
||||
|
||||
public RawIcmpPingEngine(int cycleIntervalSeconds, int replyWaitMillis) {
|
||||
this(cycleIntervalSeconds, replyWaitMillis, 2);
|
||||
}
|
||||
|
||||
public RawIcmpPingEngine(int cycleIntervalSeconds, int replyWaitMillis, int downThreshold) {
|
||||
this.cycleIntervalSeconds = cycleIntervalSeconds;
|
||||
this.replyWaitMillis = replyWaitMillis;
|
||||
this.downThreshold = Math.max(1, downThreshold);
|
||||
this.identifier = (int) (ProcessHandle.current().pid() & 0xFFFF);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addOrUpdateTarget(String nodeId, String ip) {
|
||||
targets.compute(nodeId, (k, existing) -> {
|
||||
if (existing == null) {
|
||||
return new IpTarget(nodeId, ip);
|
||||
} else {
|
||||
if (!existing.ip.equals(ip)) {
|
||||
existing.ip = ip;
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTarget(String nodeId) {
|
||||
targets.remove(nodeId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTargets(Map<String, String> nodeIdToIp) {
|
||||
targets.keySet().retainAll(nodeIdToIp.keySet());
|
||||
for (Map.Entry<String, String> entry : nodeIdToIp.entrySet()) {
|
||||
addOrUpdateTarget(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<IpTarget> getTargets() {
|
||||
return targets.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addListener(StatusListener listener) {
|
||||
listeners.add(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeListener(StatusListener listener) {
|
||||
listeners.remove(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
openSocket();
|
||||
running = true;
|
||||
receiveExecutor.submit(this::receiveLoop);
|
||||
cycleHandle = scheduler.scheduleAtFixedRate(this::runCycle, 0, cycleIntervalSeconds, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
running = false;
|
||||
if (cycleHandle != null) cycleHandle.cancel(true);
|
||||
scheduler.shutdownNow();
|
||||
receiveExecutor.shutdownNow();
|
||||
closeSocket();
|
||||
}
|
||||
|
||||
private void openSocket() {
|
||||
socketFd = CLibrary.INSTANCE.socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
|
||||
if (socketFd < 0) {
|
||||
throw new IllegalStateException(
|
||||
"Nepodařilo se otevřít RAW ICMP socket (errno=" + Native.getLastError() + "). "
|
||||
+ "Běžte program jako root, nebo nastavte capability: "
|
||||
+ "sudo setcap cap_net_raw+ep <cesta-k-java-binarce>");
|
||||
}
|
||||
|
||||
Timeval tv = new Timeval();
|
||||
tv.tv_sec = new NativeLong(0);
|
||||
tv.tv_usec = new NativeLong(200_000);
|
||||
CLibrary.INSTANCE.setsockopt(socketFd, SOL_SOCKET, SO_RCVTIMEO, tv, tv.size());
|
||||
|
||||
setReceiveBufferSize(1 << 20);
|
||||
}
|
||||
|
||||
private void setReceiveBufferSize(int bytes) {
|
||||
com.sun.jna.ptr.IntByReference size = new com.sun.jna.ptr.IntByReference(bytes);
|
||||
CLibrary.INSTANCE.setsockopt(socketFd, SOL_SOCKET, SO_RCVBUF, size, 4);
|
||||
}
|
||||
|
||||
private void closeSocket() {
|
||||
if (socketFd >= 0) {
|
||||
CLibrary.INSTANCE.close(socketFd);
|
||||
socketFd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
private void runCycle() {
|
||||
try {
|
||||
runCycleInternal();
|
||||
} catch (Throwable t) {
|
||||
System.err.println("runCycle selhal, cyklus VŠAK pokračuje dál:");
|
||||
t.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void runCycleInternal() {
|
||||
Set<Integer> sequencesThisCycle = new HashSet<>();
|
||||
|
||||
for (IpTarget target : targets.values()) {
|
||||
int seq = sequenceCounter.updateAndGet(v -> (v + 1) & 0xFFFF);
|
||||
sequencesThisCycle.add(seq);
|
||||
sequenceToTarget.put(seq, target);
|
||||
|
||||
SockAddrIn addr = new SockAddrIn();
|
||||
addr.sin_family = AF_INET;
|
||||
try {
|
||||
addr.sin_addr = InetAddress.getByName(target.ip).getAddress();
|
||||
} catch (Exception e) {
|
||||
sequenceToTarget.remove(seq);
|
||||
continue;
|
||||
}
|
||||
|
||||
byte[] payload = new byte[32];
|
||||
byte[] packet = IcmpPacketBuilder.buildEchoRequest(identifier, seq, payload);
|
||||
|
||||
sequenceSentAtNanos.put(seq, System.nanoTime());
|
||||
int sent = CLibrary.INSTANCE.sendto(socketFd, packet, packet.length, 0, addr, addr.size());
|
||||
if (sent < 0) {
|
||||
System.err.println("sendto selhal pro " + target.ip + " (errno=" + Native.getLastError() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
scheduler.schedule(() -> evaluateTimeouts(sequencesThisCycle), replyWaitMillis, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private void receiveLoop() {
|
||||
byte[] buffer = new byte[1024];
|
||||
while (running) {
|
||||
try {
|
||||
int received = CLibrary.INSTANCE.recvfrom(socketFd, buffer, buffer.length, 0, Pointer.NULL, Pointer.NULL);
|
||||
if (received > 0) {
|
||||
IcmpPacketBuilder.ParsedReply reply = IcmpPacketBuilder.parseEchoReply(buffer, received);
|
||||
if (reply != null && reply.identifier() == identifier) {
|
||||
handleReply(reply.sequence());
|
||||
}
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
System.err.println("receiveLoop selhal, pokračuje dál:");
|
||||
t.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleReply(int sequence) {
|
||||
IpTarget target = sequenceToTarget.remove(sequence);
|
||||
Long sentAtNanos = sequenceSentAtNanos.remove(sequence);
|
||||
if (target == null || sentAtNanos == null) return;
|
||||
|
||||
long latencyMs = Math.max(0, (System.nanoTime() - sentAtNanos) / 1_000_000);
|
||||
updateTarget(target, true, latencyMs);
|
||||
}
|
||||
|
||||
private void evaluateTimeouts(Set<Integer> sequencesFromThisCycle) {
|
||||
for (Integer seq : sequencesFromThisCycle) {
|
||||
IpTarget target = sequenceToTarget.remove(seq);
|
||||
sequenceSentAtNanos.remove(seq);
|
||||
if (target != null) {
|
||||
updateTarget(target, false, -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== UPRAVENÁ METODA ====================
|
||||
private void updateTarget(IpTarget target, boolean rawUp, long latencyMs) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
boolean previouslyReportedUp = target.up;
|
||||
boolean everCheckedBefore = target.everChecked;
|
||||
|
||||
|
||||
if (rawUp) {
|
||||
target.consecutiveOk++;
|
||||
target.consecutiveFails = 0;
|
||||
} else {
|
||||
target.consecutiveFails++;
|
||||
target.consecutiveOk = 0;
|
||||
}
|
||||
|
||||
boolean reportedUp;
|
||||
if (rawUp) {
|
||||
reportedUp = true;
|
||||
} else if (!everCheckedBefore) {
|
||||
reportedUp = false;
|
||||
} else {
|
||||
reportedUp = previouslyReportedUp && target.consecutiveFails < downThreshold;
|
||||
}
|
||||
|
||||
boolean stateChanged = everCheckedBefore && (reportedUp != previouslyReportedUp);
|
||||
boolean firstReport = !everCheckedBefore;
|
||||
|
||||
target.up = reportedUp;
|
||||
if (rawUp) {
|
||||
target.lastLatencyMs = latencyMs;
|
||||
} else if (!reportedUp) {
|
||||
target.lastLatencyMs = -1;
|
||||
}
|
||||
target.lastCheck = now;
|
||||
target.everChecked = true;
|
||||
if (stateChanged) target.lastChange = now;
|
||||
|
||||
StatusEvent event = new StatusEvent(
|
||||
target.nodeId,
|
||||
target.ip,
|
||||
reportedUp,
|
||||
target.lastLatencyMs,
|
||||
stateChanged,
|
||||
firstReport,
|
||||
now
|
||||
);
|
||||
|
||||
for (StatusListener listener : listeners) {
|
||||
listener.onUpdate(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import com.sun.jna.Structure;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Odpovida C strukture "struct sockaddr_in" (viz <netinet/in.h>).
|
||||
* sin_addr drzime primo jako 4 bajty (presne v poradi, v jakem je vraci
|
||||
* InetAddress.getAddress() - tedy uz ve "network byte order"), abychom se
|
||||
* vyhnuli zamene endianity pri prevodu na/z int.
|
||||
*
|
||||
* DULEZITE: trida MUSI byt public, jinak na ni JNA nemuze sahat reflexi
|
||||
* z jineho balicku (IllegalAccessException i pres public pole uvnitr).
|
||||
*/
|
||||
public class SockAddrIn extends Structure {
|
||||
public short sin_family;
|
||||
public short sin_port;
|
||||
public byte[] sin_addr = new byte[4];
|
||||
public byte[] sin_zero = new byte[8];
|
||||
|
||||
@Override
|
||||
protected List<String> getFieldOrder() {
|
||||
return Arrays.asList("sin_family", "sin_port", "sin_addr", "sin_zero");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
public interface StatusChangeListener {
|
||||
void onStatusChanged(String ip, String newStatus);
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Jedna udalost o vysledku kontroly konkretni IP adresy.
|
||||
* Predava se registrovanym listenerum (napr. pro broadcast pres Netty).
|
||||
*
|
||||
* @param ip IP adresa / hostname
|
||||
* @param id id cile
|
||||
* @param up true = cil odpovedel, false = neodpovedel (timeout)
|
||||
* @param latencyMs latence v ms, pokud up == true; pokud up == false, je vzdy -1
|
||||
* @param stateChanged true, pokud se stav zmenil oproti predchozi kontrole (UP<->DOWN)
|
||||
* @param timestamp cas kontroly
|
||||
*/
|
||||
public record StatusEvent(
|
||||
String nodeId,
|
||||
String ip,
|
||||
boolean up,
|
||||
long latencyMs,
|
||||
boolean stateChanged,
|
||||
boolean firstReport, // true pro první hlášení po kontrole
|
||||
LocalDateTime timestamp
|
||||
) {
|
||||
public String describe() {
|
||||
if (up) {
|
||||
return "Node " + nodeId + " (" + ip + ") -> UP, odezva " + latencyMs + " ms";
|
||||
} else {
|
||||
return "Node " + nodeId + " (" + ip + ") -> DOWN";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
/**
|
||||
* Implementujte toto rozhrani, abyste dostavali vysledky kontrol.
|
||||
* Volano asynchronne z interniho ping-poolu po KAZDE kontrole (nejen pri
|
||||
* zmene stavu) - v StatusEvent.stateChanged() poznate, jestli doslo ke zmene.
|
||||
*
|
||||
* Typicke pouziti: v implementaci rozeslat zpravu vsem pripojenym Netty
|
||||
* klientum (napr. pres ChannelGroup.writeAndFlush(...)).
|
||||
*
|
||||
* Implementace by mela byt rychla a neblokujici - vola se primo z vlakna
|
||||
* ping-poolu.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface StatusListener {
|
||||
void onUpdate(StatusEvent event);
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package jnet.server.probe.ping;
|
||||
|
||||
import com.sun.jna.NativeLong;
|
||||
import com.sun.jna.Structure;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Odpovida C strukture "struct timeval" (viz <sys/time.h>), pouzivane pro
|
||||
* nastaveni SO_RCVTIMEO (timeout na recvfrom).
|
||||
*
|
||||
* DULEZITE: trida MUSI byt public, jinak na ni JNA nemuze sahat reflexi
|
||||
* z jineho balicku (IllegalAccessException i pres public pole uvnitr).
|
||||
*/
|
||||
public class Timeval extends Structure {
|
||||
public NativeLong tv_sec;
|
||||
public NativeLong tv_usec;
|
||||
|
||||
@Override
|
||||
protected List<String> getFieldOrder() {
|
||||
return Arrays.asList("tv_sec", "tv_usec");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package jnet.server.probe.snmp;
|
||||
|
||||
|
||||
public class MonitorConfig {
|
||||
public int id; // unikátní ID, které si uživatel zvolí
|
||||
public String ip;
|
||||
public String community;
|
||||
public String port = "161";
|
||||
public int version;
|
||||
public String oid;
|
||||
public int interval; // v sekundách
|
||||
|
||||
public MonitorConfig() {}
|
||||
|
||||
public MonitorConfig(int id, String ip, String community, String port, int version, String oid, int interval) {
|
||||
this.id = id;
|
||||
this.ip = ip;
|
||||
this.community = community;
|
||||
this.port = port;
|
||||
this.version = version;
|
||||
this.oid = oid;
|
||||
this.interval = interval;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
package jnet.server.probe.snmp;
|
||||
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.NodeProbe;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.server.Server;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
import jnet.lib.Message;
|
||||
import org.snmp4j.smi.Variable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import jnet.lib.object.SnmpResult;
|
||||
|
||||
/**
|
||||
* Zpracovává výsledky SNMP dotazů:
|
||||
* - ihned aktualizuje lokální cache (NodeProbe.value)
|
||||
* - ukládá výsledky/chyby do fronty
|
||||
* - každých N sekund odešle dávku všem klientům
|
||||
*/
|
||||
public class SnmpBatchProcessor implements SnmpResultListener, AutoCloseable {
|
||||
|
||||
private final BlockingQueue<SnmpResult> queue = new LinkedBlockingQueue<>();
|
||||
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||
private final int batchIntervalSeconds;
|
||||
private SnmpProbeManager manager;
|
||||
|
||||
public SnmpBatchProcessor(int batchIntervalSeconds) {
|
||||
this.batchIntervalSeconds = batchIntervalSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inicializuje procesor: zaregistruje se jako listener a spustí periodické odesílání.
|
||||
* @param manager SnmpProbeManager, ke kterému se připojí
|
||||
*/
|
||||
public void init(SnmpProbeManager manager) {
|
||||
this.manager = manager;
|
||||
manager.addListener(this);
|
||||
start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Spustí periodické odesílání dávek.
|
||||
*/
|
||||
private void start() {
|
||||
scheduler.scheduleAtFixedRate(this::flushBatch, batchIntervalSeconds, batchIntervalSeconds, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zastaví periodickou úlohu, odešle zbylé položky a odregistruje se z manageru.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
scheduler.shutdownNow();
|
||||
// odešle zbylé položky
|
||||
flushBatch();
|
||||
if (manager != null) {
|
||||
manager.removeListener(this);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Implementace SnmpResultListener ---
|
||||
|
||||
@Override
|
||||
public void onResult(int taskId, String oid, Variable value) {
|
||||
// 1. Ihned aktualizovat lokální cache (NodeProbe)
|
||||
updateNodeProbeValue(taskId, value);
|
||||
// 2. Zařadit do fronty pro dávkové odeslání
|
||||
queue.offer(new SnmpResult(taskId, oid, value, null, true));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(int taskId, String oid, String error) {
|
||||
// Chyby také zařadíme do fronty (pro informování klientů)
|
||||
queue.offer(new SnmpResult(taskId, oid, null, error, false));
|
||||
}
|
||||
|
||||
// --- interní metody ---
|
||||
|
||||
/**
|
||||
* Vybere všechny položky z fronty a odešle je jako jednu dávku.
|
||||
*/
|
||||
private void flushBatch() {
|
||||
List<SnmpResult> batch = new ArrayList<>();
|
||||
queue.drainTo(batch);
|
||||
if (!batch.isEmpty()) {
|
||||
// Předpokládáme, že Message.SNMP_PROBE_BATCH je definováno
|
||||
ServerHandler.sendAll(Message.SNMP_PROBE_VALUE, batch);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Najde NodeProbe podle taskId a nastaví mu hodnotu.
|
||||
* (Převzato z původního listeneru v Server.java)
|
||||
*/
|
||||
private void updateNodeProbeValue(int idProbe, Object value) {
|
||||
for (Site site : Server.site) {
|
||||
for (Node node : site.getNode()) {
|
||||
for (NodeProbe nodeProbe : node.getProbe()) {
|
||||
if (nodeProbe.getId() == idProbe) {
|
||||
nodeProbe.setValue((Variable) value);
|
||||
return; // nalezeno
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
package jnet.server.probe.snmp;
|
||||
|
||||
import org.snmp4j.CommunityTarget;
|
||||
import org.snmp4j.PDU;
|
||||
import org.snmp4j.Snmp;
|
||||
import org.snmp4j.event.ResponseEvent;
|
||||
import org.snmp4j.smi.OID;
|
||||
import org.snmp4j.smi.VariableBinding;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import org.snmp4j.smi.Variable;
|
||||
|
||||
public class SnmpMonitorTask implements Runnable {
|
||||
private final int taskId;
|
||||
private final Snmp snmp;
|
||||
private final CommunityTarget target;
|
||||
private final OID oid;
|
||||
private final String identifier;
|
||||
private final List<SnmpResultListener> listeners;
|
||||
|
||||
public SnmpMonitorTask(int taskId, Snmp snmp, CommunityTarget target, OID oid,
|
||||
String identifier, List<SnmpResultListener> listeners) {
|
||||
this.taskId = taskId;
|
||||
this.snmp = snmp;
|
||||
this.target = target;
|
||||
this.oid = oid;
|
||||
this.identifier = identifier;
|
||||
this.listeners = listeners;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
PDU pdu = new PDU();
|
||||
pdu.add(new VariableBinding(oid));
|
||||
pdu.setType(PDU.GET);
|
||||
|
||||
ResponseEvent event = snmp.send(pdu, target);
|
||||
|
||||
if (event == null) {
|
||||
notifyError("Žádná odpověď (timeout)");
|
||||
return;
|
||||
}
|
||||
PDU response = event.getResponse();
|
||||
if (response == null) {
|
||||
notifyError("Timeout / agent nedostupný");
|
||||
return;
|
||||
}
|
||||
int errorStatus = response.getErrorStatus();
|
||||
if (errorStatus != PDU.noError) {
|
||||
notifyError("SNMP chyba: " + response.getErrorStatusText());
|
||||
return;
|
||||
}
|
||||
VariableBinding vb = response.get(0);
|
||||
if (vb != null) {
|
||||
Variable value = vb.getVariable();
|
||||
notifyResult(value);
|
||||
// také log
|
||||
// System.out.println("[" + getCurrentTime() + "] [Task " + taskId + "] " + identifier + " = " + value);
|
||||
} else {
|
||||
notifyError("Prázdná odpověď");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
notifyError("Výjimka: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyResult(Variable value) {
|
||||
for (SnmpResultListener l : listeners) {
|
||||
try { l.onResult(taskId, oid.toString(), value); } catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyError(String error) {
|
||||
for (SnmpResultListener l : listeners) {
|
||||
try { l.onError(taskId, oid.toString(), error); } catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
private String getCurrentTime() {
|
||||
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
package jnet.server.probe.snmp;
|
||||
|
||||
|
||||
import org.snmp4j.CommunityTarget;
|
||||
import org.snmp4j.Snmp;
|
||||
import org.snmp4j.TransportMapping;
|
||||
import org.snmp4j.mp.SnmpConstants;
|
||||
import org.snmp4j.smi.OID;
|
||||
import org.snmp4j.smi.OctetString;
|
||||
import org.snmp4j.smi.UdpAddress;
|
||||
import org.snmp4j.transport.DefaultUdpTransportMapping;
|
||||
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.NodeProbe;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.lib.object.SnmpProfile;
|
||||
import jnet.server.Server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.SocketException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class SnmpProbeManager implements AutoCloseable {
|
||||
private Snmp snmp = null;
|
||||
private ScheduledExecutorService scheduler = null;
|
||||
private final ConcurrentHashMap<Integer, TaskEntry> tasks = new ConcurrentHashMap<>();
|
||||
private final List<SnmpResultListener> listeners = new CopyOnWriteArrayList<>();
|
||||
|
||||
private static class TaskEntry {
|
||||
final MonitorConfig config;
|
||||
final ScheduledFuture<?> future;
|
||||
final SnmpMonitorTask task;
|
||||
TaskEntry(MonitorConfig config, ScheduledFuture<?> future, SnmpMonitorTask task) {
|
||||
this.config = config;
|
||||
this.future = future;
|
||||
this.task = task;
|
||||
}
|
||||
}
|
||||
|
||||
public SnmpProbeManager() {
|
||||
try {
|
||||
TransportMapping<?> transport = new DefaultUdpTransportMapping();
|
||||
transport.listen();
|
||||
this.snmp = new Snmp(transport);
|
||||
this.scheduler = Executors.newScheduledThreadPool(10);
|
||||
} catch (SocketException ex) {
|
||||
System.getLogger(SnmpProbeManager.class.getName()).log(System.Logger.Level.ERROR, (String) null, ex);
|
||||
} catch (IOException ex) {
|
||||
System.getLogger(SnmpProbeManager.class.getName()).log(System.Logger.Level.ERROR, (String) null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void loadTask() {
|
||||
for (Site site : Server.site) {
|
||||
for (Node node : site.getNode()) {
|
||||
SnmpProfile profile = Server.snmpProfile.stream()
|
||||
.filter(p -> p.getId() == node.getSnmpProfile())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
for (NodeProbe nodeProbe : node.getProbe()) {
|
||||
MonitorConfig mc = new MonitorConfig(
|
||||
nodeProbe.getId(),
|
||||
node.getIp(),
|
||||
profile.getCommunityRead(),
|
||||
profile.getPort(),
|
||||
profile.getVersion(),
|
||||
nodeProbe.getOid(),
|
||||
nodeProbe.getInterval()
|
||||
);
|
||||
addTask(mc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Přidá úlohu s ID z config.id. Pokud už ID existuje, vyhodí výjimku.
|
||||
*/
|
||||
public synchronized void addTask(MonitorConfig cfg) {
|
||||
if (tasks.containsKey(cfg.id)) {
|
||||
throw new IllegalArgumentException("Task s ID " + cfg.id + " již existuje.");
|
||||
}
|
||||
CommunityTarget target = createTarget(cfg);
|
||||
OID oid = new OID(cfg.oid);
|
||||
String identifier = cfg.ip + ":" + cfg.oid;
|
||||
|
||||
SnmpMonitorTask task = new SnmpMonitorTask(cfg.id, snmp, target, oid, identifier, listeners);
|
||||
ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(task, 0, cfg.interval, TimeUnit.SECONDS);
|
||||
tasks.put(cfg.id, new TaskEntry(cfg, future, task));
|
||||
// System.out.println("[Manager] Přidána úloha " + cfg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Odebere úlohu podle ID.
|
||||
*/
|
||||
public synchronized boolean removeTask(int id) {
|
||||
TaskEntry entry = tasks.remove(id);
|
||||
if (entry != null) {
|
||||
entry.future.cancel(false);
|
||||
System.out.println("[Manager] Odebrána úloha ID " + id);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrátí kopii seznamu aktivních úloh.
|
||||
*/
|
||||
public synchronized List<MonitorConfig> getTasks() {
|
||||
List<MonitorConfig> list = new ArrayList<>();
|
||||
for (TaskEntry e : tasks.values()) {
|
||||
list.add(e.config);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// --- Listener registrace ---
|
||||
public void addListener(SnmpResultListener listener) {
|
||||
listeners.add(listener);
|
||||
}
|
||||
|
||||
public void removeListener(SnmpResultListener listener) {
|
||||
listeners.remove(listener);
|
||||
}
|
||||
|
||||
// --- pomocné ---
|
||||
private CommunityTarget createTarget(MonitorConfig cfg) {
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setAddress(new UdpAddress(cfg.ip + "/" + cfg.port));
|
||||
target.setCommunity(new OctetString(cfg.community));
|
||||
target.setVersion(SnmpConstants.version2c);
|
||||
target.setTimeout(3000);
|
||||
target.setRetries(1);
|
||||
return target;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
// System.out.println("[Manager] Ukončuji...");
|
||||
try { snmp.close(); } catch (IOException e) { e.printStackTrace(); }
|
||||
scheduler.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
package jnet.server.probe.snmp;
|
||||
|
||||
import org.snmp4j.smi.Variable;
|
||||
|
||||
|
||||
public interface SnmpResultListener {
|
||||
/** Zavolá se při úspěšném přečtení hodnoty. */
|
||||
void onResult(int taskId, String oid, Variable value);
|
||||
|
||||
/** Zavolá se při chybě (timeout, SNMP chyba, výjimka). */
|
||||
void onError(int taskId, String oid, String error);
|
||||
}
|
||||
|
|
@ -0,0 +1,177 @@
|
|||
package jnet.server.snmp;
|
||||
|
||||
import org.snmp4j.*;
|
||||
import org.snmp4j.event.ResponseEvent;
|
||||
import org.snmp4j.smi.*;
|
||||
import org.snmp4j.transport.DefaultUdpTransportMapping;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import jnet.lib.object.DeviceInfo;
|
||||
|
||||
public class SNMPDeviceInfo {
|
||||
|
||||
private Snmp snmp;
|
||||
private TransportMapping<UdpAddress> transport; // ← nová členská proměnná pro uzavření
|
||||
private String address;
|
||||
private String community;
|
||||
private int version;
|
||||
|
||||
// SNMP OID pro základní informace
|
||||
private static final OID SYS_NAME_OID = new OID("1.3.6.1.2.1.1.5.0");
|
||||
private static final OID SYS_DESCR_OID = new OID("1.3.6.1.2.1.1.1.0");
|
||||
private static final OID SYS_UPTIME_OID = new OID("1.3.6.1.2.1.1.3.0");
|
||||
private static final OID SYS_CONTACT_OID = new OID("1.3.6.1.2.1.1.4.0");
|
||||
private static final OID SYS_LOCATION_OID = new OID("1.3.6.1.2.1.1.6.0");
|
||||
private static final OID SYS_OBJECT_ID_OID = new OID("1.3.6.1.2.1.1.2.0");
|
||||
|
||||
// OID databáze výrobců
|
||||
private static final Map<String, String> DEVICE_OID_MAP = new HashMap<>();
|
||||
|
||||
static {
|
||||
DEVICE_OID_MAP.put("1.3.6.1.4.1.9", "Cisco");
|
||||
DEVICE_OID_MAP.put("1.3.6.1.4.1.11", "Hewlett-Packard (HP)");
|
||||
DEVICE_OID_MAP.put("1.3.6.1.4.1.25506.11.1.184", "Hewlett-Packard (HP)");
|
||||
DEVICE_OID_MAP.put("1.3.6.1.4.1.14988", "Mikrotik");
|
||||
DEVICE_OID_MAP.put("1.3.6.1.4.1.41112.1.3.1", "Ubiquiti Networks");
|
||||
DEVICE_OID_MAP.put("1.3.6.1.4.1.259.10.1.43.101", "EdgeCore");
|
||||
DEVICE_OID_MAP.put("1.3.6.1.4.1.11863.5.1048577", "TP-Link");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.43", "Lexmark");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.311", "Microsoft");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.3224", "Fortinet");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.8072", "Net-SNMP");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.2021", "Linux Host");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.171", "D-Link");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.12148", "MikroTik");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.2636", "Juniper Networks");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.674", "Dell");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.2352", "Allied Telesis");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.807", "IBM");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.562", "Alcatel");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.14988", "Ubiquiti Networks");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.22610", "Ruckus Wireless");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.318", "APC (Schneider Electric)");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.2011", "Huawei");
|
||||
// DEVICE_OID_MAP.put("1.3.6.1.4.1.4826", "Opengear");
|
||||
}
|
||||
|
||||
public SNMPDeviceInfo(String ip, String port, String community, int version) throws IOException {
|
||||
this.address = ip + "/" + port;
|
||||
this.community = community;
|
||||
this.version = version;
|
||||
|
||||
this.transport = new DefaultUdpTransportMapping(); // uložíme si transport
|
||||
snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
}
|
||||
|
||||
/**
|
||||
* Získání základních informací o zařízení. Po dokončení (i při výjimce) se
|
||||
* automaticky uzavře SNMP spojení.
|
||||
*/
|
||||
public DeviceInfo getDeviceInfo() throws IOException {
|
||||
try {
|
||||
DeviceInfo di = new DeviceInfo(
|
||||
getAsString(SYS_NAME_OID),
|
||||
getAsString(SYS_DESCR_OID),
|
||||
formatUptime(getAsString(SYS_UPTIME_OID)), // ← formátujeme uptime
|
||||
getAsString(SYS_CONTACT_OID),
|
||||
getAsString(SYS_LOCATION_OID),
|
||||
getDeviceVendor()
|
||||
);
|
||||
return di;
|
||||
} finally {
|
||||
close(); // ← spojení se vždy uzavře
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Získá sysObjectID a přeloží na výrobce.
|
||||
*
|
||||
* @return Výrobce nebo "Neznámý" + OID
|
||||
* @throws IOException
|
||||
*/
|
||||
public String getDeviceVendor() throws IOException {
|
||||
String sysObjectID = getAsString(SYS_OBJECT_ID_OID);
|
||||
|
||||
for (String oidPrefix : DEVICE_OID_MAP.keySet()) {
|
||||
if (sysObjectID.startsWith(oidPrefix)) {
|
||||
return DEVICE_OID_MAP.get(oidPrefix);
|
||||
}
|
||||
}
|
||||
return "Neznámý výrobce (" + sysObjectID + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
* Získání hodnoty SNMP OID jako String.
|
||||
*/
|
||||
private String getAsString(OID oid) throws IOException {
|
||||
CommunityTarget target = createTarget();
|
||||
PDU pdu = new PDU();
|
||||
pdu.add(new VariableBinding(oid));
|
||||
pdu.setType(PDU.GET);
|
||||
|
||||
ResponseEvent event = snmp.get(pdu, target);
|
||||
if (event != null && event.getResponse() != null) {
|
||||
return event.getResponse().get(0).getVariable().toString();
|
||||
} else {
|
||||
return "No response";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Převede SNMP sysUpTime (setiny sekundy) na čitelný formát D HH:MM:SS
|
||||
*
|
||||
* @param sysUpTime setiny sekundy (centiseconds)
|
||||
* @return čitelný uptime
|
||||
*/
|
||||
private static String formatUptime(String sysUpTime) {
|
||||
try {
|
||||
long centiseconds = Long.parseLong(sysUpTime);
|
||||
long totalSeconds = centiseconds / 100;
|
||||
long days = totalSeconds / 86400;
|
||||
long hours = (totalSeconds % 86400) / 3600;
|
||||
long minutes = (totalSeconds % 3600) / 60;
|
||||
long seconds = totalSeconds % 60;
|
||||
|
||||
return String.format("%d dní, %02d:%02d:%02d", days, hours, minutes, seconds);
|
||||
} catch (NumberFormatException e) {
|
||||
return sysUpTime;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vytvoření SNMP cíle (target).
|
||||
*/
|
||||
private CommunityTarget createTarget() {
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(this.community));
|
||||
target.setAddress(new UdpAddress(this.address));
|
||||
target.setVersion(this.version);
|
||||
target.setRetries(2);
|
||||
target.setTimeout(1500);
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uzavře SNMP spojení a uvolní všechny prostředky. Lze volat i ručně, ale v
|
||||
* běžném použití se zavolá automaticky z getDeviceInfo().
|
||||
*/
|
||||
public void close() {
|
||||
try {
|
||||
if (snmp != null) {
|
||||
snmp.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Chyba při zavírání Snmp: " + e.getMessage());
|
||||
}
|
||||
if (transport != null) {
|
||||
try {
|
||||
transport.close();
|
||||
} catch (IOException e) {
|
||||
System.err.println("Chyba při zavírání transportu: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,310 @@
|
|||
package jnet.server.snmp;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import jnet.lib.object.Interface;
|
||||
import org.snmp4j.CommunityTarget;
|
||||
import org.snmp4j.PDU;
|
||||
import org.snmp4j.Snmp;
|
||||
import org.snmp4j.TransportMapping;
|
||||
import org.snmp4j.event.ResponseEvent;
|
||||
import org.snmp4j.mp.SnmpConstants;
|
||||
import org.snmp4j.smi.OID;
|
||||
import org.snmp4j.smi.OctetString;
|
||||
import org.snmp4j.smi.UdpAddress;
|
||||
import org.snmp4j.smi.VariableBinding;
|
||||
import org.snmp4j.transport.DefaultUdpTransportMapping;
|
||||
|
||||
public class SNMPInterfaceScanner {
|
||||
|
||||
private Snmp snmp;
|
||||
private String address;
|
||||
private String community;
|
||||
private int version;
|
||||
|
||||
// OID pro rozhraní v IF-MIB
|
||||
private static final String IF_INDEX_OID = "1.3.6.1.2.1.2.2.1.1"; // ifIndex
|
||||
private static final String IF_DESCR_OID = "1.3.6.1.2.1.2.2.1.2"; // ifDescr
|
||||
private static final String IF_SPEED_OID = "1.3.6.1.2.1.2.2.1.5"; // ifSpeed
|
||||
private static final String IF_TYPE_OID = "1.3.6.1.2.1.2.2.1.3"; // ifType
|
||||
private static final String IF_MAC_OID = "1.3.6.1.2.1.2.2.1.6"; // ifPhysAddress (opraveno)
|
||||
private static final String IF_STATUS_OID = "1.3.6.1.2.1.2.2.1.8"; // ifOperStatus
|
||||
private static final String IF_STATUS_ADM_OID = "1.3.6.1.2.1.2.2.1.7"; // ifAdminStatus
|
||||
private static final String IF_LAST_CHANGE_OID = "1.3.6.1.2.1.2.2.1.9"; // ifLastChange (TimeTicks)
|
||||
|
||||
public SNMPInterfaceScanner(String address, String port, String community, int version) throws IOException {
|
||||
this.address = address + "/" + port;
|
||||
this.community = community;
|
||||
this.version = version;
|
||||
|
||||
TransportMapping<UdpAddress> transport = new DefaultUdpTransportMapping();
|
||||
snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
}
|
||||
|
||||
/**
|
||||
* Získání detailních informací o všech interfaces
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
public List<Interface> scanInterfaces() throws IOException {
|
||||
List<Interface> list = new ArrayList<>();
|
||||
CommunityTarget target = createTarget();
|
||||
OID oid = new OID(IF_INDEX_OID); // Start na ifIndex
|
||||
boolean finished = false;
|
||||
|
||||
try {
|
||||
while (!finished) {
|
||||
PDU pdu = new PDU();
|
||||
pdu.add(new VariableBinding(oid));
|
||||
pdu.setType(PDU.GETNEXT);
|
||||
|
||||
ResponseEvent response = snmp.send(pdu, target);
|
||||
if (response == null || response.getResponse() == null) {
|
||||
System.out.println("Žádná odpověď od SNMP agenta.");
|
||||
break;
|
||||
}
|
||||
|
||||
VariableBinding vb = response.getResponse().get(0);
|
||||
if (vb == null) {
|
||||
break;
|
||||
}
|
||||
OID nextOid = vb.getOid();
|
||||
|
||||
// Pokud jsme mimo tabulku, ukončit cyklus
|
||||
if (!nextOid.startsWith(new OID(IF_INDEX_OID))) {
|
||||
finished = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
int ifIndex = vb.getVariable().toInt();
|
||||
|
||||
// Načtení jednotlivých atributů - ošetřeno proti null
|
||||
String ifDescr = getSnmpValue(IF_DESCR_OID + "." + ifIndex, target);
|
||||
String ifType = getSnmpValue(IF_TYPE_OID + "." + ifIndex, target);
|
||||
String ifStatus = getSnmpValue(IF_STATUS_OID + "." + ifIndex, target);
|
||||
String ifSpeedRaw = getSnmpValue(IF_SPEED_OID + "." + ifIndex, target);
|
||||
String ifMacRaw = getSnmpValue(IF_MAC_OID + "." + ifIndex, target);
|
||||
String ifStatusAdm = getSnmpValue(IF_STATUS_ADM_OID + "." + ifIndex, target);
|
||||
String ifLastChange = getSnmpValue(IF_LAST_CHANGE_OID + "." + ifIndex, target);
|
||||
|
||||
// Parsování rychlosti s ošetřením
|
||||
long ifSpeed = 0;
|
||||
if (ifSpeedRaw != null && !ifSpeedRaw.equals("Neznámé")) {
|
||||
try {
|
||||
ifSpeed = Long.parseLong(ifSpeedRaw);
|
||||
} catch (NumberFormatException e) {
|
||||
ifSpeed = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Formátování MAC adresy
|
||||
String ifMac = formatMac(ifMacRaw);
|
||||
|
||||
// Formátování TimeTicks (ifLastChange)
|
||||
String lastChangeFormatted = formatTimeTicks(ifLastChange);
|
||||
|
||||
list.add(new Interface(
|
||||
ifIndex, // index
|
||||
ifDescr != null ? ifDescr : "Neznámé", // description
|
||||
getInterfaceStatus(ifStatus), // operStatus
|
||||
formatIfSpeed(ifSpeed), // speed
|
||||
getInterfaceType(ifType), // type
|
||||
ifMac, // mac
|
||||
convertIfAdminStatus(ifStatusAdm), // adminStatus
|
||||
lastChangeFormatted // lastChange (formátovaný)
|
||||
));
|
||||
|
||||
// Posuneme OID na další položku
|
||||
oid = nextOid;
|
||||
}
|
||||
} finally {
|
||||
// Zajištění uvolnění zdrojů
|
||||
if (snmp != null) {
|
||||
try {
|
||||
snmp.close();
|
||||
} catch (IOException e) {
|
||||
// logování chyby
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pomocná metoda pro vytvoření SNMP cíle (target) s ohledem na verzi
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private CommunityTarget createTarget() {
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(community));
|
||||
target.setAddress(new UdpAddress(address));
|
||||
// Nastavení SNMP verze podle parametru
|
||||
if (version == 1) {
|
||||
target.setVersion(SnmpConstants.version1);
|
||||
} else {
|
||||
target.setVersion(SnmpConstants.version2c); // výchozí v2c
|
||||
}
|
||||
target.setRetries(2);
|
||||
target.setTimeout(1500);
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Získání hodnoty pro dané OID pomocí GET. Vrací null v případě chyby.
|
||||
*/
|
||||
private String getSnmpValue(String oid, CommunityTarget target) throws IOException {
|
||||
PDU pdu = new PDU();
|
||||
pdu.add(new VariableBinding(new OID(oid)));
|
||||
pdu.setType(PDU.GET);
|
||||
|
||||
ResponseEvent response = snmp.send(pdu, target);
|
||||
if (response != null && response.getResponse() != null) {
|
||||
VariableBinding vb = response.getResponse().get(0);
|
||||
if (vb != null && vb.getVariable() != null) {
|
||||
return vb.getVariable().toString();
|
||||
}
|
||||
}
|
||||
return null; // nebo "Neznámé", ale raději null pro ošetření
|
||||
}
|
||||
|
||||
/**
|
||||
* Převede číselné označení typu rozhraní na název
|
||||
*/
|
||||
private String getInterfaceType(String type) {
|
||||
if (type == null) return "Neznámé";
|
||||
switch (type) {
|
||||
case "1": return "Jiné";
|
||||
case "6": return "Ethernet";
|
||||
case "7": return "ISO 8802-3";
|
||||
case "9": return "Token Ring";
|
||||
case "15": return "FDDI";
|
||||
case "23": return "PPP";
|
||||
case "24": return "Loopback";
|
||||
case "28": return "ATM";
|
||||
case "32": return "Frame Relay";
|
||||
case "37": return "IP-over-ATM";
|
||||
case "53": return "Fibre Channel";
|
||||
case "62": return "Fast Ethernet (100 Mbps)";
|
||||
case "69": return "Gigabit Ethernet (1 Gbps)";
|
||||
case "71": return "WiFi (802.11)";
|
||||
case "94": return "ATM Subinterface";
|
||||
case "117": return "Gigabit Ethernet (1 Gbps)";
|
||||
case "131": return "Tunnel";
|
||||
case "135": return "VLAN";
|
||||
case "136": return "LACP (Link Aggregation)";
|
||||
case "161": return "ISDN";
|
||||
case "169": return "DSL";
|
||||
case "175": return "DOCSIS (kabelový modem)";
|
||||
case "181": return "ATM (PON)";
|
||||
case "182": return "Ethernet (PON)";
|
||||
case "209": return "Bridge";
|
||||
case "237": return "LTE";
|
||||
case "243": return "5G";
|
||||
default: return "(" + type + ") Neznámé";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Převede číselné označení operativního stavu rozhraní na název
|
||||
*/
|
||||
private String getInterfaceStatus(String status) {
|
||||
if (status == null) return "Neznámé";
|
||||
switch (status) {
|
||||
case "1": return "Up";
|
||||
case "2": return "Down";
|
||||
case "3": return "Testing";
|
||||
case "4": return "Unknown";
|
||||
case "5": return "Dormant";
|
||||
case "6": return "notPresent";
|
||||
case "7": return "lowerLayerDown";
|
||||
default: return "Neznámé (" + status + ")";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Převede administrátorský stav na text
|
||||
*/
|
||||
private static String convertIfAdminStatus(String status) {
|
||||
if (status == null) return "Unknown";
|
||||
switch (status) {
|
||||
case "1": return "Up";
|
||||
case "2": return "Down";
|
||||
case "3": return "Testing";
|
||||
default: return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formátuje rychlost (v bitech za sekundu) do čitelné podoby.
|
||||
*/
|
||||
private static String formatIfSpeed(long ifSpeed) {
|
||||
String[] UNITS = {"bps", "kbps", "Mbps", "Gbps", "Tbps"};
|
||||
if (ifSpeed <= 0) {
|
||||
return "-";
|
||||
}
|
||||
int unitIndex = 0;
|
||||
double speed = ifSpeed;
|
||||
while (speed >= 1000 && unitIndex < UNITS.length - 1) {
|
||||
speed /= 1000;
|
||||
unitIndex++;
|
||||
}
|
||||
long roundedSpeed = Math.round(speed);
|
||||
DecimalFormat df = new DecimalFormat("#,###");
|
||||
return df.format(roundedSpeed) + " " + UNITS[unitIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* Formátuje MAC adresu z řetězce (hex bez oddělovačů) do tvaru xx:xx:xx:xx:xx:xx
|
||||
*/
|
||||
private static String formatMac(String macRaw) {
|
||||
if (macRaw == null || macRaw.isEmpty() || macRaw.equals("Neznámé")) {
|
||||
return "Neznámé";
|
||||
}
|
||||
// Očekáváme hex řetězec bez oddělovačů, např. "001122334455"
|
||||
String cleaned = macRaw.replaceAll("[^0-9a-fA-F]", "");
|
||||
if (cleaned.length() != 12) {
|
||||
return macRaw; // vrátíme původní, pokud neodpovídá délce
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < cleaned.length(); i += 2) {
|
||||
if (i > 0) sb.append(":");
|
||||
sb.append(cleaned.substring(i, i + 2));
|
||||
}
|
||||
return sb.toString().toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Převede TimeTicks (setiny sekundy) na čitelný řetězec "X dní, Y hodin, Z minut, W sekund"
|
||||
* Pokud je vstup null nebo nečíselný, vrátí "Neznámé".
|
||||
*/
|
||||
private static String formatTimeTicks(String timeTicks) {
|
||||
if (timeTicks == null || timeTicks.isEmpty()) {
|
||||
return "Neznámé";
|
||||
}
|
||||
long ticks;
|
||||
try {
|
||||
ticks = Long.parseLong(timeTicks);
|
||||
} catch (NumberFormatException e) {
|
||||
return "Neznámé";
|
||||
}
|
||||
long totalSeconds = ticks / 100; // setiny → sekundy
|
||||
long days = totalSeconds / 86400;
|
||||
long hours = (totalSeconds % 86400) / 3600;
|
||||
long minutes = (totalSeconds % 3600) / 60;
|
||||
long seconds = totalSeconds % 60;
|
||||
|
||||
if (days > 0) {
|
||||
return String.format("%d dní, %d hodin, %d minut, %d sekund", days, hours, minutes, seconds);
|
||||
} else if (hours > 0) {
|
||||
return String.format("%d hodin, %d minut, %d sekund", hours, minutes, seconds);
|
||||
} else if (minutes > 0) {
|
||||
return String.format("%d minut, %d sekund", minutes, seconds);
|
||||
} else {
|
||||
return String.format("%d sekund", seconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,200 @@
|
|||
package jnet.server.snmp;
|
||||
|
||||
import org.snmp4j.PDU;
|
||||
import org.snmp4j.Snmp;
|
||||
import org.snmp4j.TransportMapping;
|
||||
import org.snmp4j.event.ResponseEvent;
|
||||
import org.snmp4j.event.ResponseListener;
|
||||
import org.snmp4j.smi.*;
|
||||
import org.snmp4j.transport.DefaultUdpTransportMapping;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.snmp4j.CommunityTarget;
|
||||
|
||||
public class SNMPTrafficMonitor {
|
||||
|
||||
private final String address;
|
||||
private final String port;
|
||||
private final String community;
|
||||
private final int version;
|
||||
private final int interfaceIndex;
|
||||
|
||||
private final List<TrafficListener> listeners = new ArrayList<>();
|
||||
private Snmp snmp;
|
||||
private ScheduledExecutorService executor;
|
||||
private ScheduledFuture<?> scheduledFuture;
|
||||
|
||||
// Sdílené proměnné přístupné z callbacku – musí být volatile
|
||||
private volatile long prevInOctets = -1;
|
||||
private volatile long prevOutOctets = -1;
|
||||
private volatile long prevTimestamp = -1;
|
||||
|
||||
// OIDy pro SNMP dotaz na traffic (32bitové – hrozí přetečení)
|
||||
// Pro produkční použití preferujte 64bitové HC OIDy:
|
||||
// ifHCInOctets = 1.3.6.1.2.1.31.1.1.1.6
|
||||
// ifHCOutOctets = 1.3.6.1.2.1.31.1.1.1.10
|
||||
private static final String IF_IN_OCTETS = "1.3.6.1.2.1.2.2.1.10"; // Inbound traffic
|
||||
private static final String IF_OUT_OCTETS = "1.3.6.1.2.1.2.2.1.16"; // Outbound traffic
|
||||
|
||||
public SNMPTrafficMonitor(String targetAddress, String port, String community, int version, int interfaceIndex) {
|
||||
this.address = targetAddress;
|
||||
this.port = port;
|
||||
this.community = community;
|
||||
this.version = version;
|
||||
this.interfaceIndex = interfaceIndex;
|
||||
}
|
||||
|
||||
public void addTrafficListener(TrafficListener listener) {
|
||||
listeners.add(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Spustí periodické dotazování SNMP agenta.
|
||||
*
|
||||
* @param intervalMs Interval mezi dotazy v milisekundách.
|
||||
* @throws IOException Při chybě otevření transportního spojení.
|
||||
*/
|
||||
public void startMonitoring(long intervalMs) throws IOException {
|
||||
TransportMapping<UdpAddress> transport = new DefaultUdpTransportMapping();
|
||||
snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
|
||||
executor = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "SNMPTrafficMonitor");
|
||||
t.setDaemon(true); // aby nebránil ukončení JVM
|
||||
return t;
|
||||
});
|
||||
|
||||
scheduledFuture = executor.scheduleAtFixedRate(() -> {
|
||||
try {
|
||||
queryTraffic();
|
||||
} catch (IOException e) {
|
||||
System.err.println("Chyba při SNMP dotazu: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}, 0, intervalMs, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zastaví periodické dotazování a uvolní zdroje.
|
||||
*
|
||||
* @throws IOException Při chybě uzavírání SNMP session.
|
||||
*/
|
||||
public void stopMonitoring() throws IOException {
|
||||
if (scheduledFuture != null) {
|
||||
scheduledFuture.cancel(false);
|
||||
}
|
||||
if (executor != null) {
|
||||
executor.shutdown();
|
||||
try {
|
||||
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
if (snmp != null) {
|
||||
snmp.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Odešle asynchronní SNMP GET dotaz a výsledky předá listenerům.
|
||||
*/
|
||||
private void queryTraffic() throws IOException {
|
||||
PDU pdu = new PDU();
|
||||
pdu.add(new VariableBinding(new OID(IF_IN_OCTETS + "." + interfaceIndex)));
|
||||
pdu.add(new VariableBinding(new OID(IF_OUT_OCTETS + "." + interfaceIndex)));
|
||||
pdu.setType(PDU.GET);
|
||||
|
||||
CommunityTarget target = createTarget();
|
||||
|
||||
snmp.send(pdu, target, null, new ResponseListener() {
|
||||
@Override
|
||||
public void onResponse(ResponseEvent event) {
|
||||
PDU response = event.getResponse();
|
||||
if (response == null) {
|
||||
System.err.println("SNMP dotaz timeout nebo žádná odpověď.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
long inOctets = response.get(0).getVariable().toLong();
|
||||
long outOctets = response.get(1).getVariable().toLong();
|
||||
long currentTimestamp = System.currentTimeMillis();
|
||||
|
||||
// Pokud máme předchozí hodnoty, spočítáme přenosovou rychlost
|
||||
if (prevInOctets != -1 && prevOutOctets != -1) {
|
||||
// Ošetření přetečení 32bitových čítačů (wrap-around)
|
||||
long inDelta = inOctets - prevInOctets;
|
||||
if (inDelta < 0) {
|
||||
inDelta += 1L << 32; // přičteme rozsah 32bitového čítače
|
||||
}
|
||||
long outDelta = outOctets - prevOutOctets;
|
||||
if (outDelta < 0) {
|
||||
outDelta += 1L << 32;
|
||||
}
|
||||
|
||||
double elapsedSeconds = (currentTimestamp - prevTimestamp) / 1000.0;
|
||||
if (elapsedSeconds > 0) {
|
||||
long inBps = (long) (inDelta / elapsedSeconds);
|
||||
long outBps = (long) (outDelta / elapsedSeconds);
|
||||
notifyListeners(inBps, outBps);
|
||||
} else {
|
||||
System.err.println("Časový interval je nulový nebo záporný.");
|
||||
}
|
||||
}
|
||||
|
||||
// Uložení aktuálních hodnot pro další výpočet
|
||||
prevInOctets = inOctets;
|
||||
prevOutOctets = outOctets;
|
||||
prevTimestamp = currentTimestamp;
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("Chyba při zpracování SNMP odpovědi: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void notifyListeners(long inBps, long outBps) {
|
||||
for (TrafficListener listener : listeners) {
|
||||
try {
|
||||
listener.onTrafficUpdate(inBps, outBps);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Chyba v listeneru: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vytvoření SNMP cíle (target) podle nastavení.
|
||||
*/
|
||||
private CommunityTarget createTarget() {
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(community));
|
||||
target.setAddress(new UdpAddress(address + "/" + port));
|
||||
target.setVersion(version);
|
||||
target.setRetries(2);
|
||||
target.setTimeout(1500);
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Listener pro příjem aktualizací přenosové rychlosti. Hodnoty jsou v
|
||||
* Bytech za sekundu (Bps).
|
||||
*/
|
||||
public interface TrafficListener {
|
||||
|
||||
void onTrafficUpdate(long inBps, long outBps);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
package jnet.server.trafficmonitor;
|
||||
|
||||
public class DeviceConfig {
|
||||
private final int id;
|
||||
private final String ip;
|
||||
private final String port;
|
||||
private final String community;
|
||||
private final int version;
|
||||
private final int interfaceIndex;
|
||||
|
||||
public DeviceConfig(int id, String ip, String port, String community, int version, int interfaceIndex) {
|
||||
if (id <= 0) throw new IllegalArgumentException("ID musí být kladné číslo");
|
||||
this.id = id;
|
||||
this.ip = ip;
|
||||
this.port = port;
|
||||
this.community = community;
|
||||
this.version = version;
|
||||
this.interfaceIndex = interfaceIndex;
|
||||
}
|
||||
|
||||
public int getId() { return id; }
|
||||
public String getIp() { return ip; }
|
||||
public String getPort() { return port; }
|
||||
public String getCommunity() { return community; }
|
||||
public int getVersion() { return version; }
|
||||
public int getInterfaceIndex() { return interfaceIndex; }
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof DeviceConfig)) return false;
|
||||
return id == ((DeviceConfig) o).id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() { return Integer.hashCode(id); }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DeviceConfig{id=" + id + ", ip=" + ip + ", iface=" + interfaceIndex + "}";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
package jnet.server.trafficmonitor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
public class DeviceManager {
|
||||
private final Map<Integer, DeviceConfig> devices = new ConcurrentHashMap<>();
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
|
||||
public void addDevice(DeviceConfig config) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
int id = config.getId();
|
||||
if (devices.containsKey(id))
|
||||
throw new IllegalArgumentException("ID " + id + " již existuje.");
|
||||
devices.put(id, config);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public DeviceConfig removeDevice(int deviceId) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
return devices.remove(deviceId);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public DeviceConfig updateDevice(int deviceId, DeviceConfig newConfig) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
if (deviceId != newConfig.getId())
|
||||
throw new IllegalArgumentException("ID se neshodují.");
|
||||
return devices.put(deviceId, newConfig);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public DeviceConfig getDevice(int deviceId) {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return devices.get(deviceId);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public List<DeviceConfig> getAllDevices() {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return new ArrayList<>(devices.values());
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public List<Integer> getDeviceIds() {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return new ArrayList<>(devices.keySet());
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasDevice(int deviceId) {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return devices.containsKey(deviceId);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public int size() {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return devices.size();
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
package jnet.server.trafficmonitor;
|
||||
|
||||
import jnet.lib.LogFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public class MultiDeviceSnmpMonitor {
|
||||
private final DeviceManager deviceManager = new DeviceManager();
|
||||
private final SnmpPoller poller;
|
||||
private final List<TrafficListener> listeners = new CopyOnWriteArrayList<>();
|
||||
|
||||
private ScheduledExecutorService executor;
|
||||
private ScheduledFuture<?> scheduledFuture;
|
||||
private volatile boolean running = false;
|
||||
|
||||
public MultiDeviceSnmpMonitor() {
|
||||
TrafficListener internal = new TrafficListener() {
|
||||
@Override
|
||||
public void onTrafficUpdate(int id, long in, long out) {
|
||||
listeners.forEach(l -> { try { l.onTrafficUpdate(id, in, out); } catch (Exception ignored) {} });
|
||||
}
|
||||
@Override public void onDeviceAdded(int id) { listeners.forEach(l -> { try { l.onDeviceAdded(id); } catch (Exception ignored) {} }); }
|
||||
@Override public void onDeviceRemoved(int id) { listeners.forEach(l -> { try { l.onDeviceRemoved(id); } catch (Exception ignored) {} }); }
|
||||
@Override public void onDeviceUpdated(int id) { listeners.forEach(l -> { try { l.onDeviceUpdated(id); } catch (Exception ignored) {} }); }
|
||||
};
|
||||
poller = new SnmpPoller(deviceManager, internal);
|
||||
}
|
||||
|
||||
public void addTrafficListener(TrafficListener listener) { if (listener != null) listeners.add(listener); }
|
||||
public void removeTrafficListener(TrafficListener listener) { listeners.remove(listener); }
|
||||
|
||||
public void addDevice(DeviceConfig config) {
|
||||
deviceManager.addDevice(config);
|
||||
poller.resetHistory(config.getId());
|
||||
listeners.forEach(l -> { try { l.onDeviceAdded(config.getId()); } catch (Exception ignored) {} });
|
||||
}
|
||||
|
||||
public void removeDevice(int deviceId) {
|
||||
if (deviceManager.removeDevice(deviceId) != null) {
|
||||
poller.resetHistory(deviceId);
|
||||
listeners.forEach(l -> { try { l.onDeviceRemoved(deviceId); } catch (Exception ignored) {} });
|
||||
}
|
||||
}
|
||||
|
||||
public void updateDevice(int deviceId, DeviceConfig newConfig) {
|
||||
DeviceConfig old = deviceManager.updateDevice(deviceId, newConfig);
|
||||
poller.resetHistory(deviceId);
|
||||
if (old == null) {
|
||||
listeners.forEach(l -> { try { l.onDeviceAdded(deviceId); } catch (Exception ignored) {} });
|
||||
} else {
|
||||
listeners.forEach(l -> { try { l.onDeviceUpdated(deviceId); } catch (Exception ignored) {} });
|
||||
}
|
||||
}
|
||||
|
||||
public List<Integer> getDeviceIds() { return deviceManager.getDeviceIds(); }
|
||||
public DeviceConfig getDeviceConfig(int deviceId) { return deviceManager.getDevice(deviceId); }
|
||||
public boolean hasDevice(int deviceId) { return deviceManager.hasDevice(deviceId); }
|
||||
|
||||
public void startMonitoring(long intervalMs) throws IOException {
|
||||
if (running) { LogFile.printInfo("Monitor již běží."); return; }
|
||||
poller.start();
|
||||
executor = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "SnmpMonitor"); t.setDaemon(true); return t; });
|
||||
running = true;
|
||||
scheduledFuture = executor.scheduleAtFixedRate(poller::pollAllDevices, 0, intervalMs, TimeUnit.MILLISECONDS);
|
||||
LogFile.printInfo("Monitor spuštěn, interval=" + intervalMs + "ms, zařízení=" + deviceManager.size());
|
||||
}
|
||||
|
||||
public void stopMonitoring() throws IOException {
|
||||
if (!running) return;
|
||||
running = false;
|
||||
if (scheduledFuture != null) { scheduledFuture.cancel(false); scheduledFuture = null; }
|
||||
if (executor != null) { executor.shutdownNow(); executor = null; }
|
||||
poller.stop();
|
||||
LogFile.printInfo("Monitor zastaven.");
|
||||
}
|
||||
|
||||
public boolean isRunning() { return running; }
|
||||
}
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
package jnet.server.trafficmonitor;
|
||||
|
||||
import jnet.lib.LogFile;
|
||||
import jnet.lib.object.Node;
|
||||
import jnet.lib.object.NodeConnection;
|
||||
import jnet.lib.object.Site;
|
||||
import jnet.lib.object.SnmpProfile;
|
||||
import jnet.server.Server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import jnet.lib.object.TrafficData;
|
||||
|
||||
public class SnmpMonitorService {
|
||||
|
||||
private static final MultiDeviceSnmpMonitor monitor = new MultiDeviceSnmpMonitor();
|
||||
private static final TrafficBatchDispatcher dispatcher = new TrafficBatchDispatcher(2000);
|
||||
private static final Map<Integer, TrafficData> lastTrafficData = new ConcurrentHashMap<>();
|
||||
private static volatile boolean running = false;
|
||||
|
||||
static {
|
||||
// Připojíme dispatcher k monitoru
|
||||
monitor.addTrafficListener(new TrafficListener() {
|
||||
@Override
|
||||
public void onTrafficUpdate(int deviceId, long inBps, long outBps) {
|
||||
long now = System.currentTimeMillis();
|
||||
lastTrafficData.put(deviceId,
|
||||
new TrafficData(deviceId, inBps, outBps, now)
|
||||
);
|
||||
dispatcher.onTrafficUpdate(deviceId, inBps, outBps);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeviceAdded(int deviceId) {
|
||||
LogFile.printInfo("SNMP zařízení přidáno: ID=" + deviceId);
|
||||
dispatcher.onDeviceAdded(deviceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeviceRemoved(int deviceId) {
|
||||
LogFile.printInfo("SNMP zařízení odebráno: ID=" + deviceId);
|
||||
lastTrafficData.remove(deviceId);
|
||||
dispatcher.onDeviceRemoved(deviceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeviceUpdated(int deviceId) {
|
||||
LogFile.printInfo("SNMP zařízení aktualizováno: ID=" + deviceId);
|
||||
dispatcher.onDeviceUpdated(deviceId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// VEŘEJNÉ METODY
|
||||
// ------------------------------------------------------------------------
|
||||
public static void start(long intervalMs) {
|
||||
start(intervalMs, 2000);
|
||||
}
|
||||
|
||||
public static void start(long intervalMs, long batchIntervalMs) {
|
||||
if (running) {
|
||||
LogFile.printInfo("SNMP monitor již běží");
|
||||
return;
|
||||
}
|
||||
|
||||
LogFile.printInfo("Spouštím SNMP monitor (dotaz=" + intervalMs + "ms, dávka=" + batchIntervalMs + "ms)");
|
||||
|
||||
// Načtení zařízení z databáze
|
||||
try {
|
||||
loadProbe();
|
||||
} catch (Exception e) {
|
||||
LogFile.printInfo("Chyba při načítání zařízení: " + e.getMessage());
|
||||
}
|
||||
|
||||
// Spuštění monitoru
|
||||
try {
|
||||
monitor.startMonitoring(intervalMs);
|
||||
dispatcher.start();
|
||||
running = true;
|
||||
LogFile.printInfo("SNMP monitor spuštěn, zařízení=" + monitor.getDeviceIds().size());
|
||||
} catch (IOException e) {
|
||||
LogFile.printInfo("Chyba při spouštění: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void stop() {
|
||||
if (!running) return;
|
||||
|
||||
LogFile.printInfo("Zastavuji SNMP monitor...");
|
||||
try {
|
||||
monitor.stopMonitoring();
|
||||
} catch (IOException e) {
|
||||
LogFile.printInfo("Chyba při zastavování monitoru: " + e.getMessage());
|
||||
}
|
||||
dispatcher.stop();
|
||||
running = false;
|
||||
LogFile.printInfo("SNMP monitor zastaven");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// NAČÍTÁNÍ Z DATABÁZE
|
||||
// ------------------------------------------------------------------------
|
||||
private static void loadProbe() {
|
||||
int added = 0;
|
||||
int skipped = 0;
|
||||
|
||||
for (Site site : Server.site) {
|
||||
for (NodeConnection nc : site.getNodeConnection()) {
|
||||
if (!nc.isReadTraffic()) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
Node node = site.getNode().stream()
|
||||
.filter(n -> n.getId() == nc.getTrafficNode())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (node == null) {
|
||||
LogFile.printDebug("Uzel ID=" + nc.getTrafficNode() + " nenalezen");
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
SnmpProfile profile = Server.snmpProfile.stream()
|
||||
.filter(p -> p.getId() == node.getSnmpProfile())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (profile == null) {
|
||||
LogFile.printDebug("SNMP profil ID=" + node.getSnmpProfile() + " nenalezen");
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
monitor.addDevice(new DeviceConfig(
|
||||
nc.getId(),
|
||||
node.getIp(),
|
||||
profile.getPort(),
|
||||
profile.getCommunityRead(),
|
||||
profile.getVersion(),
|
||||
nc.getTrafficIface()
|
||||
));
|
||||
added++;
|
||||
} catch (Exception e) {
|
||||
LogFile.printInfo("Chyba při přidávání ID=" + nc.getId() + ": " + e.getMessage());
|
||||
skipped++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LogFile.printInfo("Načteno " + added + " monitorů, přeskočeno " + skipped);
|
||||
}
|
||||
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// PŘÍSTUP K DATŮM
|
||||
// ------------------------------------------------------------------------
|
||||
public static TrafficData getLastTrafficData(int deviceId) {
|
||||
return lastTrafficData.get(deviceId);
|
||||
}
|
||||
|
||||
public static Map<Integer, TrafficData> getAllTrafficData() {
|
||||
return new ConcurrentHashMap<>(lastTrafficData);
|
||||
}
|
||||
|
||||
public static List<Integer> getDeviceIds() {
|
||||
return monitor.getDeviceIds();
|
||||
}
|
||||
|
||||
public static boolean isRunning() {
|
||||
return running;
|
||||
}
|
||||
|
||||
public static void addDevice(int id, String ip, String port, String community, int version, int interfaceIndex) {
|
||||
//int id = monitor.getDeviceIds().stream().max(Integer::compareTo).orElse(0) + 1;
|
||||
monitor.addDevice(new DeviceConfig(id, ip, port, community, version, interfaceIndex));
|
||||
}
|
||||
|
||||
public static void removeDevice(int deviceId) {
|
||||
monitor.removeDevice(deviceId);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
package jnet.server.trafficmonitor;
|
||||
|
||||
import org.snmp4j.*;
|
||||
import org.snmp4j.event.ResponseEvent;
|
||||
import org.snmp4j.event.ResponseListener;
|
||||
import org.snmp4j.smi.*;
|
||||
import org.snmp4j.transport.DefaultUdpTransportMapping;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class SnmpPoller {
|
||||
private static final String IF_HC_IN_OCTETS = "1.3.6.1.2.1.31.1.1.1.6";
|
||||
private static final String IF_HC_OUT_OCTETS = "1.3.6.1.2.1.31.1.1.1.10";
|
||||
|
||||
private final DeviceManager deviceManager;
|
||||
private final TrafficListener listener;
|
||||
private Snmp snmp;
|
||||
private TransportMapping<UdpAddress> transport;
|
||||
|
||||
private final Map<Integer, Long> prevIn = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, Long> prevOut = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, Long> prevTimestamp = new ConcurrentHashMap<>();
|
||||
|
||||
public SnmpPoller(DeviceManager deviceManager, TrafficListener listener) {
|
||||
this.deviceManager = deviceManager;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
public void start() throws IOException {
|
||||
transport = new DefaultUdpTransportMapping();
|
||||
snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
}
|
||||
|
||||
public void stop() throws IOException {
|
||||
if (snmp != null) { snmp.close(); snmp = null; }
|
||||
if (transport != null) { transport.close(); transport = null; }
|
||||
}
|
||||
|
||||
public void pollAllDevices() {
|
||||
for (DeviceConfig config : deviceManager.getAllDevices()) {
|
||||
try {
|
||||
pollDevice(config);
|
||||
} catch (IOException e) {
|
||||
System.err.println("Chyba při dotazu ID=" + config.getId() + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void pollDevice(DeviceConfig config) throws IOException {
|
||||
if (snmp == null) throw new IllegalStateException("SnmpPoller nebyl spuštěn.");
|
||||
|
||||
PDU pdu = new PDU();
|
||||
pdu.add(new VariableBinding(new OID(IF_HC_IN_OCTETS + "." + config.getInterfaceIndex())));
|
||||
pdu.add(new VariableBinding(new OID(IF_HC_OUT_OCTETS + "." + config.getInterfaceIndex())));
|
||||
pdu.setType(PDU.GET);
|
||||
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(config.getCommunity()));
|
||||
target.setAddress(new UdpAddress(config.getIp() + "/" + config.getPort()));
|
||||
target.setVersion(config.getVersion());
|
||||
target.setRetries(2);
|
||||
target.setTimeout(1500);
|
||||
|
||||
int id = config.getId();
|
||||
snmp.send(pdu, target, null, new ResponseListener() {
|
||||
@Override
|
||||
public void onResponse(ResponseEvent event) {
|
||||
PDU response = event.getResponse();
|
||||
if (response == null) return;
|
||||
try {
|
||||
long inOctets = response.get(0).getVariable().toLong();
|
||||
long outOctets = response.get(1).getVariable().toLong();
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
Long oldIn = prevIn.get(id);
|
||||
Long oldOut = prevOut.get(id);
|
||||
Long oldTime = prevTimestamp.get(id);
|
||||
|
||||
if (oldIn != null && oldOut != null && oldTime != null) {
|
||||
long inDelta = Math.max(0, inOctets - oldIn);
|
||||
long outDelta = Math.max(0, outOctets - oldOut);
|
||||
double elapsed = (now - oldTime) / 1000.0;
|
||||
if (elapsed > 0 && listener != null) {
|
||||
listener.onTrafficUpdate(id, (long)(inDelta / elapsed), (long)(outDelta / elapsed));
|
||||
}
|
||||
}
|
||||
prevIn.put(id, inOctets);
|
||||
prevOut.put(id, outOctets);
|
||||
prevTimestamp.put(id, now);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Chyba zpracování ID=" + id + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void resetHistory(int deviceId) {
|
||||
prevIn.remove(deviceId);
|
||||
prevOut.remove(deviceId);
|
||||
prevTimestamp.remove(deviceId);
|
||||
}
|
||||
|
||||
public void resetAllHistory() {
|
||||
prevIn.clear();
|
||||
prevOut.clear();
|
||||
prevTimestamp.clear();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
package jnet.server.trafficmonitor;
|
||||
|
||||
import jnet.lib.LogFile;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import jnet.lib.Message;
|
||||
import jnet.lib.object.TrafficData;
|
||||
import jnet.server.networkserver.ServerHandler;
|
||||
|
||||
public class TrafficBatchDispatcher implements TrafficListener {
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// INTERNÍ STAV
|
||||
// ------------------------------------------------------------------------
|
||||
private final BlockingQueue<TrafficData> queue = new LinkedBlockingQueue<>();
|
||||
private final ScheduledExecutorService scheduler;
|
||||
private ScheduledFuture<?> scheduledFuture;
|
||||
private volatile boolean running = false;
|
||||
private final long batchIntervalMs;
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// KONSTRUKTOR
|
||||
// ------------------------------------------------------------------------
|
||||
public TrafficBatchDispatcher(long batchIntervalMs) {
|
||||
this.batchIntervalMs = batchIntervalMs;
|
||||
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "TrafficBatchDispatcher");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// SPUŠTĚNÍ / ZASTAVENÍ
|
||||
// ------------------------------------------------------------------------
|
||||
public void start() {
|
||||
if (running) return;
|
||||
running = true;
|
||||
scheduledFuture = scheduler.scheduleAtFixedRate(
|
||||
this::dispatchBatch,
|
||||
batchIntervalMs,
|
||||
batchIntervalMs,
|
||||
TimeUnit.MILLISECONDS
|
||||
);
|
||||
LogFile.printInfo("TrafficBatchDispatcher spuštěn, interval=" + batchIntervalMs + "ms");
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (!running) return;
|
||||
running = false;
|
||||
if (scheduledFuture != null) {
|
||||
scheduledFuture.cancel(false);
|
||||
scheduledFuture = null;
|
||||
}
|
||||
scheduler.shutdownNow();
|
||||
LogFile.printInfo("TrafficBatchDispatcher zastaven");
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return running;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// ODESÍLÁNÍ DÁVEK
|
||||
// ------------------------------------------------------------------------
|
||||
private void dispatchBatch() {
|
||||
if (!running) return;
|
||||
|
||||
List<TrafficData> batch = new ArrayList<>();
|
||||
queue.drainTo(batch);
|
||||
|
||||
if (batch.isEmpty()) return;
|
||||
|
||||
// Odeslání přes Netty
|
||||
try {
|
||||
ServerHandler.sendAll(Message.NODE_CONNECTION_TRAFFIC, batch);
|
||||
|
||||
// LogFile.printDebug("Odeslána dávka: " + batch.size() + " traffic záznamů");
|
||||
} catch (Exception e) {
|
||||
LogFile.printInfo("Chyba při odesílání traffic dávky: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// IMPLEMENTACE TrafficListener
|
||||
// ------------------------------------------------------------------------
|
||||
@Override
|
||||
public void onTrafficUpdate(int deviceId, long inBps, long outBps) {
|
||||
if (running) {
|
||||
queue.offer(new TrafficData(deviceId, inBps, outBps, System.currentTimeMillis()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeviceAdded(int deviceId) {
|
||||
// Volitelné: můžeme odeslat notifikaci o novém zařízení
|
||||
if (running) {
|
||||
// NettyServerHandler.sendAll(new Message("DEVICE_ADDED", deviceId));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeviceRemoved(int deviceId) {
|
||||
// Volitelné: můžeme odeslat notifikaci o odebrání
|
||||
if (running) {
|
||||
// NettyServerHandler.sendAll(new Message("DEVICE_REMOVED", deviceId));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeviceUpdated(int deviceId) {
|
||||
// Volitelné: můžeme odeslat notifikaci o aktualizaci
|
||||
if (running) {
|
||||
// NettyServerHandler.sendAll(new Message("DEVICE_UPDATED", deviceId));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
package jnet.server.trafficmonitor;
|
||||
|
||||
public interface TrafficListener {
|
||||
void onTrafficUpdate(int deviceId, long inBps, long outBps);
|
||||
default void onDeviceAdded(int deviceId) {}
|
||||
default void onDeviceRemoved(int deviceId) {}
|
||||
default void onDeviceUpdated(int deviceId) {}
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
mysql_server=192.168.122.245
|
||||
mysql_port=3306
|
||||
#mysql_server=10.2.4.141
|
||||
#mysql_port=3360
|
||||
mysql_user=jnet
|
||||
mysql_password=Michal2407
|
||||
mysql_database=jnet
|
||||
server_port=1225
|
||||
debug=true
|
||||
ping_attempt=4
|
||||
ping_timeout=2
|
||||
ping_repeat=3
|
||||
instability_attempt=2
|
||||
instability_limit=1
|
||||
snmp.interval=5000
|
||||
snmp.batchInterval=2000
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
[Unit]
|
||||
Description=jNetServer
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=root
|
||||
Group=root
|
||||
WorkingDirectory=/var/jNetServer
|
||||
ExecStart=/usr/bin/java -jar /var/jNetServer/jNetServer.jar
|
||||
SuccessExitStatus=143
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
|
||||
ruční spustění
|
||||
|
||||
cd /var/jNetServer/
|
||||
java -jar jNetServer.jar
|
||||
|
||||
|
||||
instalace java
|
||||
sudo apt install openjdk-21-jdk
|
||||
|
||||
|
||||
service zkopirovat do
|
||||
/etc/systemd/system/myapp.service
|
||||
|
||||
Znovu načíst systemd
|
||||
sudo systemctl daemon-reload
|
||||
|
||||
Spustit službu
|
||||
sudo systemctl start myapp.service
|
||||
|
||||
Povolit automatické spouštění při startu systému
|
||||
sudo systemctl enable myapp.service
|
||||
|
||||
Zkontrolovat stav služby
|
||||
sudo systemctl status myapp.service
|
||||
Loading…
Reference in New Issue