Compare commits

...

10 Commits

19 changed files with 817 additions and 384 deletions

View File

@ -70,4 +70,14 @@
nbproject/build-impl.xml file.
-->
<target name="-post-compile">
<copy todir="${build.classes.dir}">
<fileset dir="resources"/>
</copy>
</target>
<target name="-post-jar">
<copy todir="${dist.jar.dir}">
<fileset dir="resources"/>
</copy>
</target>
</project>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
lib/snmp4j-3.8.2.jar Normal file

Binary file not shown.

Binary file not shown.

94
log.log
View File

@ -1,60 +1,34 @@
13.02.25 18:7:16 I ---------------------------------------------
13.02.25 18:7:16 I jNet Server
13.02.25 18:7:16 I Version: 1 (Thu Feb 13 09:04:35 CET 2025)
13.02.25 18:7:16 I ---------------------------------------------
13.02.25 18:7:16 I
13.02.25 18:7:16 I Loading config ...
13.02.25 18:7:16 I successfully
13.02.25 18:7:16 D Debug mode on
13.02.25 18:7:16 I Connecting to a selected database ...
13.02.25 18:7:16 I successfully
13.02.25 18:7:16 I Loading user list ...
13.02.25 18:7:16 I load 2 user(s)
13.02.25 18:7:16 I Loading map list ...
13.02.25 18:7:16 I load 6 map(s)
13.02.25 18:7:16 I Loading object list ...
13.02.25 18:7:17 I load 8 object(s)
13.02.25 18:7:17 I Loading object type ...
13.02.25 18:7:17 I load 12 type(s)
13.02.25 18:7:17 I Loading SNMP profile ...
13.02.25 18:7:17 I load 2 profile(s)
13.02.25 18:7:17 I Loading events ...
13.02.25 18:7:17 I load 30 event(s)
13.02.25 18:7:17 I Ping probe start
13.02.25 18:7:17 I Server is ready and listening on port 1225
13.02.25 18:7:49 D -> Message type: 1
13.02.25 18:7:49 I Authorization request send (kubernetes.docker.internal)
13.02.25 18:7:49 D <- Message type: 3
13.02.25 18:7:49 D -> Message type: 4
13.02.25 18:7:49 I User: michal logged in (kubernetes.docker.internal)
13.02.25 18:7:49 D <- Message type: 5
13.02.25 18:7:49 D <- Message type: 9
13.02.25 18:7:49 D <- For all. Message type: 7
13.02.25 18:7:49 D <- Message type: 13
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 8
13.02.25 18:7:49 D <- Message type: 11
13.02.25 18:7:49 D <- Message type: 11
13.02.25 18:7:49 D <- Message type: 100
13.02.25 18:7:49 D <- Message type: 100
13.02.25 18:7:49 D <- Message type: 100
13.02.25 18:7:49 D <- Message type: 100
13.02.25 18:7:49 D <- Message type: 100
13.02.25 18:7:49 D <- Message type: 100
13.02.25 18:7:49 D <- Message type: 14
13.02.25 18:7:49 D <- Message type: 110
13.02.25 18:7:49 D <- Message type: 107
13.02.25 18:7:49 D <- Message type: 107
13.02.25 18:8:31 D -> Message type: 105
13.02.25 18:8:31 D <- For all. Message type: 105
13.02.25 18:8:31 D <- For all. Message type: 108
15.02.25 20:20:50 I ---------------------------------------------
15.02.25 20:20:50 I jNet Server
15.02.25 20:20:50 I Version: 1 (Sat Feb 15 20:20:50 CET 2025)
15.02.25 20:20:50 I ---------------------------------------------
15.02.25 20:20:50 I
15.02.25 20:20:50 I Loading config ...
15.02.25 20:20:50 I successfully
15.02.25 20:20:50 D Debug mode on
15.02.25 20:20:50 I Connecting to a selected database ...
15.02.25 20:20:51 I successfully
15.02.25 20:20:51 I Loading user list ...
15.02.25 20:20:51 I load 2 user(s)
15.02.25 20:20:51 I Loading map list ...
15.02.25 20:20:51 I load 6 map(s)
15.02.25 20:20:51 I Loading object type ...
15.02.25 20:20:51 I load 13 type(s)
15.02.25 20:20:51 I Loading SNMP profile ...
15.02.25 20:20:51 I load 2 profile(s)
15.02.25 20:20:51 I Loading events ...
15.02.25 20:20:51 I load 75 event(s)
15.02.25 20:20:51 I Ping probe start
15.02.25 20:20:51 I Pridan host: 10.0.0.54
15.02.25 20:20:51 I Pridan host: 10.0.0.16
15.02.25 20:20:51 I Pridan host: 10.0.0.3
15.02.25 20:20:51 I Pridan host: 10.0.0.147
15.02.25 20:20:51 I Pridan host: 10.5.5.71
15.02.25 20:20:51 I Pridan host: 10.0.0.78
15.02.25 20:20:51 I Pridan host: 10.0.0.17
15.02.25 20:20:51 I Pridan host: 10.5.5.70
15.02.25 20:20:51 I Pridan host: 10.0.0.5
15.02.25 20:20:51 I Pridan host: 10.10.0.1
15.02.25 20:20:51 I Pridan host: 10.0.0.207
15.02.25 20:20:51 I Pridan host: 10.0.0.10
15.02.25 20:20:51 I Server is ready and listening on port 1225

View File

@ -35,30 +35,26 @@ dist.jlink.dir=${dist.dir}/jlink
dist.jlink.output=${dist.jlink.dir}/jNetServer
endorsed.classpath=
excludes=
file.reference.apache-commons-configuration2-2.9.0.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\apache-commons-configuration2-2.9.0.jar
file.reference.apache-commons-lang3-3.12.0.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\apache-commons-lang3-3.12.0.jar
file.reference.apache-commons-logging-1.2.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\apache-commons-logging-1.2.jar
file.reference.apache-commons-text-1.10.0.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\apache-commons-text-1.10.0.jar
file.reference.icmp4j-all.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\icmp4j-all.jar
file.reference.jna-5.3.1.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\jna-5.3.1.jar
file.reference.jna-platform-5.9.0.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\jna-platform-5.9.0.jar
file.reference.mysql-connector-java-8.0.15.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\mysql-connector-java-8.0.15.jar
file.reference.netty-all-4.1.68.Final.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\netty-all-4.1.68.Final.jar
file.reference.spring-security-crypto-5.8.0.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\spring-security-crypto-5.8.0.jar
file.reference.apache-commons-configuration2-2.9.0.jar=lib\\apache-commons-configuration2-2.9.0.jar
file.reference.apache-commons-lang3-3.12.0.jar=lib\\apache-commons-lang3-3.12.0.jar
file.reference.apache-commons-logging-1.2.jar=lib\\apache-commons-logging-1.2.jar
file.reference.apache-commons-text-1.10.0.jar=lib\\apache-commons-text-1.10.0.jar
file.reference.mysql-connector-java-8.0.15.jar=lib\\mysql-connector-java-8.0.15.jar
file.reference.netty-all-4.1.68.Final.jar=lib\\netty-all-4.1.68.Final.jar
file.reference.snmp4j-3.8.2.jar=lib\\snmp4j-3.8.2.jar
file.reference.spring-security-crypto-5.8.0.jar=lib\\spring-security-crypto-5.8.0.jar
includes=**
jar.compress=false
javac.classpath=\
${file.reference.mysql-connector-java-8.0.15.jar}:\
${reference.jNetLib.jar}:\
${file.reference.apache-commons-configuration2-2.9.0.jar}:\
${file.reference.apache-commons-lang3-3.12.0.jar}:\
${file.reference.netty-all-4.1.68.Final.jar}:\
${file.reference.icmp4j-all.jar}:\
${file.reference.apache-commons-logging-1.2.jar}:\
${file.reference.apache-commons-text-1.10.0.jar}:\
${file.reference.jna-5.3.1.jar}:\
${file.reference.jna-platform-5.9.0.jar}:\
${file.reference.mysql-connector-java-8.0.15.jar}:\
${file.reference.netty-all-4.1.68.Final.jar}:\
${file.reference.spring-security-crypto-5.8.0.jar}:\
${file.reference.apache-commons-configuration2-2.9.0.jar}
${file.reference.snmp4j-3.8.2.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false

View File

@ -164,7 +164,10 @@ public class Database {
Map m = new Map(
rs.getInt("id"),
rs.getString("name"),
rs.getBoolean("locked"));
rs.getBoolean("locked"),
getMapObject(rs.getInt("id")),
getMapConnection(rs.getInt("id"))
);
list.add(m);
}
rs.close();
@ -225,6 +228,38 @@ public class Database {
return list;
}
/**
* vráti seznam cpojeni v dane mape
* @param mapId
* @return
*/
public static ArrayList<jnet.lib.object.Connection> getMapConnection(int mapId) {
ArrayList<jnet.lib.object.Connection> list = new ArrayList<>();
String sql = "SELECT * FROM objectConnection WHERE map = " + mapId;
try {
Statement statement = getCurrentConnection().createStatement();
ResultSet r = statement.executeQuery(sql);
while (r.next()) {
int objId = r.getInt("id");
list.add(new jnet.lib.object.Connection(
objId,
r.getInt("sourceObject"),
r.getInt("destinationObject"),
r.getInt("type"),
r.getInt("map"),
r.getBoolean("readTraffic"),
r.getInt("sourceTraffic"),
r.getInt("sourceInterface")
));
}
r.close();
statement.close();
} catch (SQLException ex) {
LogFile.printErr("MySQL exception: " + ex.getMessage() + "query: " + sql);
}
return list;
}
/**
* vrati seznam objektu
*
@ -507,13 +542,40 @@ public class Database {
return mo;
}
/**
* prida nove propojeni mezi objekty
* @param c
* @return
*/
public static jnet.lib.object.Connection addConnection(jnet.lib.object.Connection c){
String query = "INSERT INTO objectConnection ("
+ "sourceObject,"
+ "destinationObject,"
+ "objectConnection.type,"
+ "map,"
+ "readTraffic,"
+ "sourceTraffic,"
+ "sourceInterface"
+ ") VALUES ("
+ "'" + c.getSourceObj() + "',"
+ "'" + c.getDestinationObj() + "',"
+ "'" + c.getType() + "',"
+ "'" + c.getMap() + "',"
+ "'" + (c.isReadTraffic() ? "1" : "0") + "',"
+ "'" + c.getTrafficObject() + "',"
+ "'" + c.getTrafficIface() + "'"
+ ")";
c.setId(insert(query));
return c;
}
/**
* nastaví stav zámku mapy
*
* @param state stav
* @param map map id
*/
static void mapLock(int state, int map) {
public static void mapLock(int state, int map) {
update("UPDATE maps SET locked='" + state + "' WHERE id=" + map);
}
@ -706,4 +768,13 @@ public class Database {
}
}
public static void editConnection(jnet.lib.object.Connection c) {
String sql = "UPDATE objectConnection SET "
+ "type='" + c.getType() + "',"
+ "readTraffic='" + (c.isReadTraffic() ? 1:0) + "',"
+ "sourceTraffic='" + c.getTrafficObject() + "',"
+ "sourceInterface='" + c.getTrafficIface() + "' "
+ "WHERE id='" + c.getId() + "'";
update(sql);
}
}

View File

@ -11,7 +11,6 @@ import jnet.lib.OSValidator;
import jnet.lib.PropertiesManager;
import jnet.lib.object.Event;
import jnet.lib.object.Map;
import jnet.lib.object.MapObject;
import jnet.lib.object.ObjectType;
import jnet.lib.object.OnlineClients;
import jnet.lib.object.SnmpProbe;
@ -19,6 +18,7 @@ import jnet.lib.object.SnmpProfile;
import jnet.lib.object.User;
import jnet.server.network.NettyServer;
import jnet.server.probe.NettyPing;
import jnet.server.probe.TrafficProbe;
public class Server {
@ -28,26 +28,39 @@ public class Server {
// minimální verze klienta
public static final int MINIMAL_CLIENT_VERSION = 1;
public static PropertiesManager config;
public static List<Map> maps = new ArrayList<>();
public static ArrayList<MapObject> mapObject= new ArrayList<>();
public static ArrayList<OnlineClients> onlineClients = new ArrayList<>();
public static ArrayList<ObjectType> objectType = new ArrayList<>();
public static ArrayList<SnmpProfile> snmpProfile = new ArrayList<>();
public static ArrayList<SnmpProbe> snmpProbe = new ArrayList<>();
public static ArrayList<User> users = new ArrayList<>();
public static ArrayList<Event> events = new ArrayList<>();
public static List<OnlineClients> onlineClients = new ArrayList<>();
public static List<ObjectType> objectType = new ArrayList<>();
public static List<SnmpProfile> snmpProfile = new ArrayList<>();
public static List<SnmpProbe> snmpProbe = new ArrayList<>();
public static List<User> users = new ArrayList<>();
public static List<Event> events = new ArrayList<>();
public static void main(String[] args) {
// // Zde můžete zadat index rozhraní, které chcete monitorovat (např. 1 pro eth0)
// int interfaceIndex = 1;
//
// // Vytvoření instance monitoru pro zadaný index rozhraní
// try {
// SNMPTrafficMonitor monitor = new SNMPTrafficMonitor("10.0.0.16", "161", "public", 0);
// monitor.startMonitoring(interfaceIndex);
//
// // Po 60 sekundách zastavíme monitoring
// Thread.sleep(60000); // Monitoring běží 60 sekund
// monitor.stopMonitoring();
// monitor.stop();
// } catch (Exception ex) {
// Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
// }
// pokud je hostitelsky system windows otevre logovaci okno
if (OSValidator.isWindows()) {
new LogWindow();
}
LogFile.clear();
LogFile.setDebug(false);
LogFile.printInfo("---------------------------------------------");
@ -56,7 +69,6 @@ public class Server {
LogFile.printInfo("---------------------------------------------");
LogFile.printInfo("");
///
/// nahrani konfigurace
///
@ -71,8 +83,6 @@ public class Server {
System.exit(0);
}
///
/// debug rezim ?
///
@ -101,10 +111,6 @@ public class Server {
maps = Database.getMapList();
LogFile.printInfo(" load " + maps.size() + " map(s)");
LogFile.printInfo("Loading object list ...");
mapObject = Database.getAllMapObject();
LogFile.printInfo(" load " + mapObject.size() + " object(s)");
LogFile.printInfo("Loading object type ...");
objectType = Database.getObjectType();
LogFile.printInfo(" load " + objectType.size() + " type(s)");
@ -116,13 +122,10 @@ public class Server {
// LogFile.printInfo("Loading SNMP template ...");
// snmpProbe = Database.getSnmpProbe();
// LogFile.printInfo(" load " + snmpProbe.size() + " template(s)");
LogFile.printInfo("Loading events ...");
events = Database.getEvents();
LogFile.printInfo(" load " + events.size() + " event(s)");
///
/// spusteni serveru
///
@ -141,7 +144,10 @@ public class Server {
// p2.start();
NettyPing np = new NettyPing();
np.start();
np.start();
TrafficProbe t = new TrafficProbe();
t.start();
}

View File

@ -4,12 +4,17 @@ import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.function.Consumer;
import jnet.lib.LogFile;
import jnet.lib.Message;
import jnet.lib.PasswordHashing;
import jnet.lib.object.Connection;
import jnet.lib.object.Event;
import jnet.lib.object.Map;
import jnet.lib.object.MapObject;
@ -18,6 +23,11 @@ import jnet.lib.object.OnlineClients;
import jnet.lib.object.ServerConfig;
import jnet.lib.object.SnmpProfile;
import jnet.lib.object.User;
import jnet.lib.snmp.DeviceInfo;
import jnet.lib.snmp.Interface;
import jnet.lib.snmp.SNMPDeviceInfo;
import jnet.lib.snmp.SNMPInterfaceScanner;
import jnet.lib.snmp.SNMPTester;
public class ServerMessageParser {
@ -25,282 +35,455 @@ public class ServerMessageParser {
private static final ChannelGroup channels = new DefaultChannelGroup(
"containers", GlobalEventExecutor.INSTANCE);
private static final java.util.Map<Integer, Consumer<Message>> handlers = new HashMap<>();
public ServerMessageParser(Channel currentClient) {
this.currentClient = currentClient;
// Inicializace mapy typu zprávy na odpovídající metody
handlers.put(Message.CLIENT_VERSION, this::handleClientVersion);
handlers.put(Message.AUTH, this::handleAuth);
handlers.put(Message.RESTART, this::handleRestart);
handlers.put(Message.UPTIME, this::handleUptime);
handlers.put(Message.NEW_OBJECT_TYPE, this::handleNewObjectType);
handlers.put(Message.SET_MAP_LOCK, this::handleSetMapLock);
handlers.put(Message.ADD_OBJECT, this::handleAddObject);
handlers.put(Message.REMOVE_OBJECT, this::handleRemoveObject);
handlers.put(Message.MAP_REMOVE, this::handleMapRemove);
handlers.put(Message.MAP_ADD, this::handleMapAdd);
handlers.put(Message.OBJECT_MOVE, this::handleObjectMove);
handlers.put(Message.UPDATE_OBJECT, this::handleUpdateObject);
handlers.put(Message.DELETE_LOG, this::handleDeleteLog);
handlers.put(Message.USER, this::handleUser);
handlers.put(Message.USER_EDIT, this::handleUserEdit);
handlers.put(Message.SERVER_CONFIG, this::handleServerConfig);
handlers.put(Message.SNMP_OBJECT_INFO, this::handleSnmpObjectInfo);
handlers.put(Message.SNMP_OBJECT_INTERFACE, this::handleSnmpObjectInterface);
handlers.put(Message.SNMP_TEST, this::handleSnmpTest);
handlers.put(Message.SNMP_CONNECTION_INTERFACE, this::handleSnmpConnectionInterface);
handlers.put(Message.CONNECTION_NEW, this::handlerConnectionNew);
handlers.put(Message.CONNECTION_UPDATE, this::handlerConnectionUpdate);
}
public void parse(Message msg) {
LogFile.printDebug("-> Message type: " + msg.getType());
ListIterator<Map> iteratorMap = Server.maps.listIterator();
ListIterator<MapObject> iteratorMapObject = Server.mapObject.listIterator();
switch (msg.getType()) {
case Message.CLIENT_VERSION:
int client_version = (int) msg.getMsg();
if (client_version < Server.MINIMAL_CLIENT_VERSION) {
LogFile.printInfo("Outdated client. Sent update request (" + ((InetSocketAddress) currentClient.remoteAddress()).getHostName() + ")");
send(new Message(Message.UPDATE, null));
} else {
LogFile.printInfo("Authorization request send (" + ((InetSocketAddress) currentClient.remoteAddress()).getHostName() + ")");
// oodeslat pozadavek na autorizacni udaje
send(new Message(Message.AUTH_REQUEST, null));
}
break;
case Message.AUTH:
String[] userData = (String[]) msg.getMsg();
String username = userData[0];
String password = userData[1];
int platform = Integer.parseInt(userData[2]);
User u = Database.getUserInfo(username);
if (PasswordHashing.verify(password, u.getPassword())) {
LogFile.printInfo("User: " + username + " logged in (" + ((InetSocketAddress) currentClient.remoteAddress()).getAddress().getHostName() + ")");
// odeslat informaci uzivateli o jeho uspesnem prihlaseni
send(new Message(Message.AUTH_SUCEFULL, null));
// pridani uzivatele mezi pripojene kanaly
channels.add(currentClient);
// vložit uživatele na seznam online uživatelů
InetSocketAddress socketAddress = (InetSocketAddress) currentClient.remoteAddress();
String clientIp = socketAddress.getAddress().getHostAddress();
String clientPort = String.valueOf(socketAddress.getPort());
Server.onlineClients.add(new OnlineClients(
String.valueOf(u.getId()),
u.getUsername(),
clientIp,
clientPort,
platform));
// odeslat informace o prihlasenem uzivateli, opravneni atd
send(new Message(Message.USER_INFO, u));
// odeslat vsem nový seznam pripojenych klientu
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"));
send(new Message(Message.SERVER_CONFIG, sc));
// odeslat typy objektu
for (ObjectType ot : Server.objectType) {
send(new Message(Message.OBJECT_TYPE, ot));
}
// odesila seznam uzivatelu
for (User us : Server.users) {
send(new Message(Message.USER, us));
}
// odeslat seznam map
for (Map i : Server.maps) {
send(new Message(Message.MAP, i));
}
// odeslat seznam objektu
send(Message.OBJECT_LIST, Server.mapObject);
// odeslat seznam udalosti
send(new Message(Message.EVENT_LIST, Server.events));
// odeslat seznam snmp profilů
for (SnmpProfile i : Server.snmpProfile) {
send(new Message(Message.SNMP_PROFILE, i));
}
} else {
LogFile.printInfo("Authorization failed (ser: " + username + " )");
}
break;
case Message.RESTART:
LogFile.printInfo("Prijat pozadavek na restart serveru");
Server.restartServer();
break;
case Message.UPTIME:
long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
send(Message.UPTIME, uptime);
break;
case Message.NEW_OBJECT_TYPE:
ObjectType not = (ObjectType) msg.getMsg();
int id = Database.addObjectType(not);
not.setId(id);
Server.objectType.add(not);
sendAll(new Message(Message.OBJECT_TYPE, not));
break;
case Message.SET_MAP_LOCK:
int[] data_lock = (int[]) msg.getMsg();
while (iteratorMap.hasNext()) {
Map map = iteratorMap.next();
if (map.getId() == data_lock[0]) {
map.setLock((data_lock[1] == 1));
break;
}
}
// upravit informaci v databazi
Database.mapLock(data_lock[1], data_lock[0]);
// odeslani informace ostatnim
sendAll(new Message(Message.SET_MAP_LOCK, data_lock));
break;
case Message.ADD_OBJECT:
MapObject mo = Database.addMapObject((MapObject) msg.getMsg());
// pridat do seznamu
Server.mapObject.add(mo);
// odesle všem novy objekt
sendAll(new Message(Message.ADD_OBJECT, mo));
// prida event a odesle ho
Event event = Database.addEvent(mo.getId(), "Přidáno", Event.TYPE_INFO);
sendAll(new Message(Message.EVENT_NEW, event));
// pokud je object vypnuty prida log
if (!mo.isActive()) {
Event event_disable = Database.addEvent(mo.getId(), "Ping vypnut", Event.TYPE_PING_OFF);
sendAll(new Message(Message.EVENT_NEW, event_disable));
}
break;
case Message.REMOVE_OBJECT:
while (iteratorMapObject.hasNext()) {
MapObject obj = iteratorMapObject.next();
if (obj.getId() == (int) msg.getMsg()) {
// odebere z databaze
Database.removeObject(obj.getId());
// odesle informaci o odebrani objektu klientum
sendAll(new Message(Message.REMOVE_OBJECT, obj.getId()));
// odebere ze seznamu
iteratorMapObject.remove();
break;
}
}
break;
case Message.MAP_REMOVE:
while (iteratorMap.hasNext()) {
Map map = iteratorMap.next();
if (map.getId() == (int) msg.getMsg()) {
// odebere z databaze
Database.removeMap(map.getId());
// odesle informaci o odebrani objektu klientum
sendAll(new Message(Message.MAP_REMOVE, map.getId()));
// odebere ze seznamu
iteratorMap.remove();
break;
}
}
break;
case Message.MAP_ADD:
Map map = new Map((String) msg.getMsg());
// přidání mapy do databaze
map.setId(Database.addMap(map.getName()));
//odeslání mapy klientum
send(new Message(Message.MAP, map));
// pridani mapy do seznamu
iteratorMap.add(map);
break;
case Message.OBJECT_MOVE:
int[] data = (int[]) msg.getMsg();
// 0 = obj id
// 2 = x
// 2 = y
// zmenit v databázi
Database.objectMove(data[0], data[1], data[2]);
// zmenit v seznamu
while (iteratorMapObject.hasNext()) {
MapObject obj = iteratorMapObject.next();
if (obj.getId() == data[0]) {
// zmenit pozici
obj.setX(data[1]);
obj.setY(data[2]);
// zapsat zmenu do databaze
Database.objectMove(data[0], data[1], data[2]);
// preposlat zmenu klientum
sendAll(new Message(Message.UPDATE_OBJECT, obj));
break;
}
}
break;
case Message.UPDATE_OBJECT:
MapObject mo_u = (MapObject) msg.getMsg();
// zmenit v databazi
Database.updateObject(mo_u);
// zmenit v seznamu
while (iteratorMapObject.hasNext()) {
if (iteratorMapObject.next().getId() == mo_u.getId()) {
iteratorMapObject.set(mo_u);
break;
}
}
// preposlat zmenu klientum
sendAll(new Message(Message.UPDATE_OBJECT, mo_u));
break;
case Message.DELETE_LOG:
int objId = (int) msg.getMsg();
// vymaže logy v databazi
Database.deleteObjectLog(objId);
// vymaze logy v listu
ListIterator<Event> iterator = Server.events.listIterator();
while (iterator.hasNext()) {
if (iterator.next().getObject() == objId) {
iterator.remove();
break;
}
}
sendAll(new Message(Message.DELETE_LOG, objId));
break;
case Message.USER:
User user = (User) msg.getMsg();
user.setPassword(PasswordHashing.hash(user.getPassword()));
//pridáni do databáze a nastaveni id
user.setId(Database.addUser(user));
// přidání do seznamu
Server.users.add(user);
// odeslat klientum nového uživatele
send(new Message(Message.USER, user));
break;
case Message.USER_EDIT:
User ue = (User) msg.getMsg();
// upraveni v databázi
Database.editUser(ue);
// zmenit v seznamu
ListIterator<User> iteratorUser = Server.users.listIterator();
while (iteratorUser.hasNext()) {
User next = iteratorUser.next();
if (next.getId() == ue.getId()) {
iteratorUser.set(ue);
break;
}
}
// preposlat zmenu klientum
sendAll(new Message(Message.USER_EDIT, ue));
break;
case Message.SERVER_CONFIG:
ServerConfig sc = (ServerConfig) msg.getMsg();
// ulozeni
Server.config.setInt("ping_repeat", sc.getPingRepeat());
Server.config.setInt("ping_attempt", sc.getPingAttempt());
Server.config.setInt("ping_timeout", sc.getPingTimeout());
Server.config.setInt("instability_attempt", sc.getInstabilityAttempt());
Server.config.setInt("instability_limit", sc.getInstabilityLimit());
Server.config.save();
//odeslani vsem
sendAll(Message.SERVER_CONFIG, sc);
break;
default:
LogFile.printErr("Neznamy typ zpravy");
Consumer<Message> handler = handlers.get(msg.getType());
if (handler != null) {
handler.accept(msg);
} else {
LogFile.printErr("Neznamy typ zpravy");
}
}
private void handleClientVersion(Message msg) {
int client_version = (int) msg.getMsg();
if (client_version < Server.MINIMAL_CLIENT_VERSION) {
LogFile.printInfo("Outdated client. Sent update request (" + ((InetSocketAddress) currentClient.remoteAddress()).getHostName() + ")");
send(new Message(Message.UPDATE, null));
} else {
LogFile.printInfo("Authorization request send (" + ((InetSocketAddress) currentClient.remoteAddress()).getHostName() + ")");
// oodeslat pozadavek na autorizacni udaje
send(new Message(Message.AUTH_REQUEST, null));
}
}
private void handleAuth(Message msg) {
String[] userData = (String[]) msg.getMsg();
String username = userData[0];
String password = userData[1];
int platform = Integer.parseInt(userData[2]);
User u = Database.getUserInfo(username);
if (PasswordHashing.verify(password, u.getPassword())) {
LogFile.printInfo("User: " + username + " logged in (" + ((InetSocketAddress) currentClient.remoteAddress()).getAddress().getHostName() + ")");
// odeslat informaci uzivateli o jeho uspesnem prihlaseni
send(new Message(Message.AUTH_SUCEFULL, null));
// pridani uzivatele mezi pripojene kanaly
channels.add(currentClient);
// vložit uživatele na seznam online uživatelů
InetSocketAddress socketAddress = (InetSocketAddress) currentClient.remoteAddress();
String clientIp = socketAddress.getAddress().getHostAddress();
String clientPort = String.valueOf(socketAddress.getPort());
Server.onlineClients.add(new OnlineClients(
String.valueOf(u.getId()),
u.getUsername(),
clientIp,
clientPort,
platform));
// odeslat informace o prihlasenem uzivateli, opravneni atd
send(new Message(Message.USER_INFO, u));
// odeslat vsem nový seznam pripojenych klientu
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"));
send(new Message(Message.SERVER_CONFIG, sc));
// odeslat typy objektu
for (ObjectType ot : Server.objectType) {
send(new Message(Message.OBJECT_TYPE, ot));
}
// odesila seznam uzivatelu
for (User us : Server.users) {
send(new Message(Message.USER, us));
}
// odeslat seznam map
for (Map i : Server.maps) {
send(new Message(Message.MAP, i));
}
// odeslat seznam udalosti
send(new Message(Message.EVENT_LIST, Server.events));
// odeslat seznam snmp profilů
for (SnmpProfile i : Server.snmpProfile) {
send(new Message(Message.SNMP_PROFILE, i));
}
} else {
LogFile.printInfo("Authorization failed (ser: " + username + " )");
}
}
private void handleRestart(Message msg) {
LogFile.printInfo("Prijat pozadavek na restart serveru");
Server.restartServer();
}
private void handleUptime(Message msg) {
long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
send(Message.UPTIME, uptime);
}
private void handleNewObjectType(Message msg) {
ObjectType not = (ObjectType) msg.getMsg();
int id = Database.addObjectType(not);
not.setId(id);
Server.objectType.add(not);
sendAll(new Message(Message.OBJECT_TYPE, not));
}
private void handleSetMapLock(Message msg) {
int[] data_lock = (int[]) msg.getMsg();
for (Map map : Server.maps) {
if (map.getId() == data_lock[0]) {
map.setLock((data_lock[1] == 1));
break;
}
}
// upravit informaci v databazi
Database.mapLock(data_lock[1], data_lock[0]);
// odeslani informace ostatnim
sendAll(new Message(Message.SET_MAP_LOCK, data_lock));
}
private void handleAddObject(Message msg) {
MapObject mo = Database.addMapObject((MapObject) msg.getMsg());
// pridat do seznamu
for (Map map : Server.maps) {
if (map.getId() == mo.getMap()) {
map.getObjects().add(mo);
}
}
// odesle všem novy objekt
sendAll(new Message(Message.ADD_OBJECT, mo));
// prida event a odesle ho
Event event = Database.addEvent(mo.getId(), "Přidáno", Event.TYPE_INFO);
sendAll(new Message(Message.EVENT_NEW, event));
// pokud je object vypnuty prida log
if (!mo.isActive()) {
Event event_disable = Database.addEvent(mo.getId(), "Ping vypnut", Event.TYPE_PING_OFF);
sendAll(new Message(Message.EVENT_NEW, event_disable));
}
}
private void handleRemoveObject(Message msg) {
for (Map map : Server.maps) {
for (MapObject object : map.getObjects()) {
if (object.getId() == (int) msg.getMsg()) {
// odebere z databaze
Database.removeObject(object.getId());
// odesle informaci o odebrani objektu klientum
sendAll(new Message(Message.REMOVE_OBJECT, object.getId()));
// odebere ze seznamu
map.getObjects().remove(object);
break;
}
}
}
}
private void handleMapRemove(Message msg) {
for (Map map : Server.maps) {
if (map.getId() == (int) msg.getMsg()) {
// odebere z databaze
Database.removeMap(map.getId());
// odesle informaci o odebrani objektu klientum
sendAll(new Message(Message.MAP_REMOVE, map.getId()));
// odebere ze seznamu
Server.maps.remove(map);
break;
}
}
}
private void handleMapAdd(Message msg) {
Map map = new Map((String) msg.getMsg());
// přidání mapy do databaze
map.setId(Database.addMap(map.getName()));
//odeslání mapy klientum
send(new Message(Message.MAP, map));
// pridani mapy do seznamu
Server.maps.add(map);
}
private void handleObjectMove(Message msg) {
int[] data = (int[]) msg.getMsg();
// 0 = obj id
// 2 = x
// 2 = y
// zmenit v databázi
Database.objectMove(data[0], data[1], data[2]);
// zmenit v seznamu
for (Map mapa : Server.maps) {
for (MapObject object : mapa.getObjects()) {
if (object.getId() == data[0]) {
// zmenit pozici
object.setX(data[1]);
object.setY(data[2]);
// zapsat zmenu do databaze
Database.objectMove(data[0], data[1], data[2]);
// preposlat zmenu klientum
sendAll(new Message(Message.UPDATE_OBJECT, object));
break;
}
}
}
}
private void handleUpdateObject(Message msg) {
MapObject mo_u = (MapObject) msg.getMsg();
// zmenit v databazi
Database.updateObject(mo_u);
// zmenit v seznamu
for (Map m : Server.maps) {
for (int i = 0; i < m.getObjects().size(); i++) {
if (m.getObjects().get(i).getId() == mo_u.getId()) {
// pokud je object vypnuty a dřív nebyl prida log
if (!mo_u.isActive() && m.getObjects().get(i).isActive()) {
Event event_disable = Database.addEvent(mo_u.getId(), "Ping vypnut", Event.TYPE_PING_OFF);
sendAll(new Message(Message.EVENT_NEW, event_disable));
}
// pokud je object zapnutý a dřív nebyl prida log
if (mo_u.isActive() && !m.getObjects().get(i).isActive()) {
Event event_disable = Database.addEvent(mo_u.getId(), "Ping zapnut", Event.TYPE_PING_OFF);
sendAll(new Message(Message.EVENT_NEW, event_disable));
}
// zmeni objekt v seznamu
m.getObjects().set(i, mo_u);
break;
}
}
}
// preposlat zmenu klientum
sendAll(new Message(Message.UPDATE_OBJECT, mo_u));
}
private void handleDeleteLog(Message msg) {
int objId = (int) msg.getMsg();
// vymaže logy v databazi
Database.deleteObjectLog(objId);
// vymaze logy v listu
ListIterator<Event> iterator = Server.events.listIterator();
while (iterator.hasNext()) {
if (iterator.next().getObject() == objId) {
iterator.remove();
break;
}
}
sendAll(new Message(Message.DELETE_LOG, objId));
}
private void handleUser(Message msg) {
User user = (User) msg.getMsg();
user.setPassword(PasswordHashing.hash(user.getPassword()));
//pridáni do databáze a nastaveni id
user.setId(Database.addUser(user));
// přidání do seznamu
Server.users.add(user);
// odeslat klientum nového uživatele
send(new Message(Message.USER, user));
}
private void handleUserEdit(Message msg) {
User ue = (User) msg.getMsg();
// upraveni v databázi
Database.editUser(ue);
// zmenit v seznamu
ListIterator<User> iteratorUser = Server.users.listIterator();
while (iteratorUser.hasNext()) {
User next = iteratorUser.next();
if (next.getId() == ue.getId()) {
iteratorUser.set(ue);
break;
}
}
// preposlat zmenu klientum
sendAll(new Message(Message.USER_EDIT, ue));
}
private void handleServerConfig(Message msg) {
ServerConfig sc = (ServerConfig) msg.getMsg();
// ulozeni
Server.config.setInt("ping_repeat", sc.getPingRepeat());
Server.config.setInt("ping_attempt", sc.getPingAttempt());
Server.config.setInt("ping_timeout", sc.getPingTimeout());
Server.config.setInt("instability_attempt", sc.getInstabilityAttempt());
Server.config.setInt("instability_limit", sc.getInstabilityLimit());
Server.config.save();
//odeslani vsem
sendAll(Message.SERVER_CONFIG, sc);
}
private void handleSnmpObjectInfo(Message msg) {
Object[] msg_object = (Object[]) msg.getMsg();
String frameName = (String) msg_object[0];
MapObject obj = (MapObject) msg_object[1];
Thread t1 = new Thread() {
@Override
public void run() {
try {
for (SnmpProfile snmpProfile : Server.snmpProfile) {
if (snmpProfile.getId() == obj.getSnmpProfile()) {
SNMPDeviceInfo snmp = new SNMPDeviceInfo(obj.getIp(), snmpProfile.getPort(), snmpProfile.getCommunityRead(), snmpProfile.getVersion());
DeviceInfo di = snmp.getDeviceInfo();
Object[] o = {frameName, di};
send(Message.SNMP_OBJECT_INFO, o);
break;
}
}
} catch (IOException e) {
LogFile.printErr("SNMP error: " + e.getMessage());
}
}
};
t1.start();
}
private void handleSnmpObjectInterface(Message msg) {
Object[] msg_object = (Object[]) msg.getMsg();
String frameName = (String) msg_object[0];
MapObject obj = (MapObject) msg_object[1];
Thread t1 = new Thread() {
@Override
public void run() {
try {
for (SnmpProfile snmpProfile : Server.snmpProfile) {
if (snmpProfile.getId() == obj.getSnmpProfile()) {
SNMPInterfaceScanner snmp = new SNMPInterfaceScanner(obj.getIp(), snmpProfile.getPort(), snmpProfile.getCommunityRead(), snmpProfile.getVersion());
List<Interface> list = snmp.scanInterfaces();
Object[] o = {frameName, list};
send(Message.SNMP_OBJECT_INTERFACE, o);
break;
}
}
} catch (Exception ex) {
LogFile.printErr("SNMP error: " + ex.getMessage());
}
}
};
t1.start();
}
private void handleSnmpTest(Message msg) {
Object[] msg_object = (Object[]) msg.getMsg();
String frameName = (String) msg_object[0];
MapObject obj = (MapObject) msg_object[1];
Thread t1 = new Thread() {
@Override
public void run() {
try {
for (SnmpProfile snmpProfile : Server.snmpProfile) {
if (snmpProfile.getId() == obj.getSnmpProfile()) {
SNMPTester test = new SNMPTester(obj.getIp(), snmpProfile.getPort(), snmpProfile.getCommunityRead(), snmpProfile.getVersion());
Boolean result = test.testSnmp();
Object[] o = {frameName, result};
send(Message.SNMP_TEST, o);
break;
}
}
} catch (Exception ex) {
LogFile.printErr("SNMP error: " + ex.getMessage());
}
}
};
t1.start();
}
private void handleSnmpConnectionInterface(Message msg) {
Object[] msg_object = (Object[]) msg.getMsg();
String frameName = (String) msg_object[0];
MapObject obj = (MapObject) msg_object[1];
Thread t1 = new Thread() {
@Override
public void run() {
try {
for (SnmpProfile snmpProfile : Server.snmpProfile) {
if (snmpProfile.getId() == obj.getSnmpProfile()) {
SNMPInterfaceScanner snmp = new SNMPInterfaceScanner(obj.getIp(), snmpProfile.getPort(), snmpProfile.getCommunityRead(), snmpProfile.getVersion());
List<Interface> list = snmp.scanInterfaces();
Object[] o = {frameName, list};
send(Message.SNMP_CONNECTION_INTERFACE, o);
break;
}
}
} catch (Exception ex) {
LogFile.printErr("SNMP error: " + ex.getMessage());
}
}
};
t1.start();
}
private void handlerConnectionNew(Message msg) {
Connection c = Database.addConnection((Connection) msg.getMsg());
for (Map map : Server.maps) {
if (map.getId() == c.getMap()) {
map.getConnection().add(c);
}
}
sendAll(Message.CONNECTION_NEW, c);
}
private void handlerConnectionUpdate(Message msg) {
Connection c = (Connection) msg.getMsg();
// upravi v databezi
Database.editConnection(c);
// upravi v seznamu
for (Map map : Server.maps) {
List<Connection> connections = map.getConnection();
for (int i = 0; i < connections.size(); i++) {
if (connections.get(i).getId() == c.getId()) {
connections.set(i, c);
}
}
}
// odesle vsem zmenu
sendAll(Message.CONNECTION_UPDATE, c);
}
/**
*
*
* @param message
*/
public void send(Message message) {
currentClient.writeAndFlush(message);
LogFile.printDebug("<- Message type: " + message.getType());

View File

@ -5,25 +5,45 @@ import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jnet.lib.LogFile;
import jnet.lib.Status;
import jnet.lib.object.Map;
import jnet.lib.object.MapObject;
import jnet.server.Server;
public class NettyPing extends Thread {
private static final HashedWheelTimer TIMER = new HashedWheelTimer(); // Netty časovač
private static final Set<MapObject> activeHosts = ConcurrentHashMap.newKeySet(); // Dynamická správa hostů
public NettyPing() {
}
// @Override
// public void run() {
// LogFile.printInfo("Ping probe start");
// for (Map map : Server.maps) {
// for (MapObject mapObject : map.getObjects()) {
// schedulePing(mapObject);
// }
// }
// }
@Override
public void run() {
LogFile.printInfo("Ping probe start");
for (MapObject mapObject : Server.mapObject) {
schedulePing(mapObject);
}
TIMER.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) {
updateHosts(); // Pravidelně kontroluje `Server.maps` a pinguje aktivní hosty
timeout.timer().newTimeout(this, Server.config.getInt("ping_repeat"), TimeUnit.SECONDS);
}
}, 0, TimeUnit.SECONDS);
}
private static void schedulePing(MapObject object) {
@ -36,10 +56,44 @@ public class NettyPing extends Thread {
}, 0, TimeUnit.SECONDS);
}
private static void updateHosts() {
Set<MapObject> currentHosts = new HashSet<>();
// Procházení všech hostů v Server.maps
for (Map map : Server.maps) {
for (MapObject object : map.getObjects()) {
if (object.isActive()) {
currentHosts.add(object);
}
}
}
// Přidání nových hostů k monitorování
for (MapObject obj : currentHosts) {
if (activeHosts.add(obj)) { // Přidá pouze pokud tam ještě není
LogFile.printDebug("Ping probe add: " + obj.getIp());
}
}
// Odebrání hostů, které už nejsou v Server.maps
activeHosts.removeIf(obj -> {
if (!currentHosts.contains(obj)) {
LogFile.printInfo("Odebran host: " + obj.getIp());
return true;
}
return false;
});
// Ping všech aktivních hostů
for (MapObject obj : activeHosts) {
pingHost(obj);
}
}
private static void pingHost(MapObject object) {
try {
String command = System.getProperty("os.name").startsWith("Windows")
? "ping -n 1 -w " + String.valueOf((Server.config.getInt("ping_timeout")*1000)) + " " + object.getIp() // Timeout 2000 ms (Windows)
? "ping -n 1 -w " + String.valueOf((Server.config.getInt("ping_timeout") * 1000)) + " " + object.getIp() // Timeout 2000 ms (Windows)
: "ping -c 1 -W " + String.valueOf(Server.config.getInt("ping_timeout")) + " " + object.getIp(); // Timeout 2 sec (Linux)
Process process = Runtime.getRuntime().exec(command);
@ -72,7 +126,7 @@ public class NettyPing extends Thread {
}
}
private static int extractTime(String line) {
private static int extractTimeV1(String line) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.contains("time=") || part.contains("čas=")) {
@ -82,4 +136,15 @@ public class NettyPing extends Thread {
return -1;
}
private static int extractTime(String line) {
// Regulární výrazy pro Windows i Linux formát
Pattern pattern = Pattern.compile("time[=<](\\d+)");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return Integer.parseInt(matcher.group(1));
}
return -1; // Pokud se nepodaří najít čas
}
}

View File

@ -10,6 +10,7 @@ import jnet.lib.LogFile;
import jnet.lib.Message;
import jnet.lib.Status;
import jnet.lib.object.Event;
import jnet.lib.object.Map;
import jnet.lib.object.MapObject;
import jnet.server.Database;
import jnet.server.Server;
@ -41,7 +42,8 @@ public class Ping extends Thread {
// Naplánování periodického provádění kontrol
scheduledExecutorService.scheduleAtFixedRate(() -> {
for (MapObject mo : Server.mapObject) {
for (Map map : Server.maps) {
for (MapObject mo : map.getObjects()) {
if (mo.isActive()) {
// Vytvoření úkolu pro pingování každé IP adresy
executorService.submit(() -> {
@ -59,6 +61,8 @@ public class Ping extends Thread {
}
}
}
}, 0, PERIOD, TimeUnit.SECONDS);
}

View File

@ -0,0 +1,124 @@
package jnet.server.probe;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import jnet.lib.LogFile;
import jnet.lib.Message;
import jnet.lib.object.Connection;
import jnet.lib.object.MapObject;
import jnet.lib.object.SnmpProfile;
import jnet.lib.snmp.SNMPTrafficMonitor;
import jnet.lib.snmp.SNMPTrafficMonitor.TrafficListener;
import jnet.server.Server;
import jnet.server.ServerMessageParser;
public class TrafficProbe extends Thread {
private static final int TIME = 3; // kontrola každé 3 sekundy
private final Map<Integer, TProbe> activeProbes = new HashMap<>();
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
@Override
public void run() {
LogFile.printInfo("Traffic probe start");
scheduler.scheduleAtFixedRate(this::updateProbe, 0, TIME, TimeUnit.SECONDS);
}
private void updateProbe() {
Set<Integer> currentProbeIds = new HashSet<>();
// Projde všechny connections a zjistí, které je potřeba monitorovat
for (jnet.lib.object.Map map : Server.maps) {
for (Connection connection : map.getConnection()) {
if (connection.isReadTraffic()) {
currentProbeIds.add(connection.getId());
if (!activeProbes.containsKey(connection.getId())) {
addProbe(connection);
}
}
}
}
// Odebrání neaktuálních probe
activeProbes.keySet().removeIf(id -> !currentProbeIds.contains(id));
}
private void addProbe(Connection c) {
try {
String host = "";
String port = "161";
String community = "public";
int version = 1;
for (jnet.lib.object.Map map : Server.maps) {
for (MapObject object : map.getObjects()) {
if (object.getId() == c.getSourceObj()) {
host = object.getIp();
SnmpProfile profile = Server.snmpProfile.stream()
.filter(p -> p.getId() == object.getSnmpProfile())
.findFirst()
.orElse(null);
if (profile != null) {
port = profile.getPort();
community = profile.getCommunityRead();
version = profile.getVersion();
}
break;
}
}
}
SNMPTrafficMonitor monitor = new SNMPTrafficMonitor(host, port, community, version, c.getTrafficIface());
monitor.addTrafficListener(new TrafficListener() {
@Override
public void onTrafficUpdate(long inBps, long outBps) {
Object[] o = {c.getId(), inBps, outBps};
ServerMessageParser.sendAll(Message.TRAFFIC, o);
}
});
activeProbes.put(c.getId(), new TProbe(c, monitor));
monitor.startMonitoring(2000);
LogFile.printInfo("Traffic probe add: " + c.getId());
} catch (IOException ex) {
LogFile.printErr("Traffic probe error: " + ex.getMessage());
}
}
public void stopProbe() {
scheduler.shutdown();
activeProbes.values().forEach(probe -> {
try {
probe.getMonitor().stopMonitoring();
} catch (IOException e) {
LogFile.printErr("Error stopping monitor for probe: " + probe.getConnection().getId() + " - " + e.getMessage());
}
});
activeProbes.clear();
LogFile.printInfo("Traffic probe stopped");
}
private static class TProbe {
private final Connection connection;
private final SNMPTrafficMonitor monitor;
public TProbe(Connection connection, SNMPTrafficMonitor monitor) {
this.connection = connection;
this.monitor = monitor;
}
public Connection getConnection() {
return connection;
}
public SNMPTrafficMonitor getMonitor() {
return monitor;
}
}
}