Compare commits
No commits in common. "master" and "feature/task-30-docker" have entirely different histories.
master
...
feature/ta
|
@ -40,7 +40,7 @@ pipeline {
|
||||||
stage('Remove old image') {
|
stage('Remove old image') {
|
||||||
steps {
|
steps {
|
||||||
sh """
|
sh """
|
||||||
sshpass -p ${SSH_PASS} ssh -o StrictHostKeyChecking=no ${SSH_USER}@${SSH_HOST} -p ${SSH_PORT} 'docker image rm -f ${IMAGE_NAME}-app:${IMAGE_VERSION} || true'
|
sshpass -p ${SSH_PASS} ssh -o StrictHostKeyChecking=no ${SSH_USER}@${SSH_HOST} -p ${SSH_PORT} 'docker image rm -f ${IMAGE_NAME}:${IMAGE_VERSION} || true'
|
||||||
"""
|
"""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,4 +3,19 @@ services:
|
||||||
app:
|
app:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
restart: always
|
depends_on:
|
||||||
|
- db
|
||||||
|
networks:
|
||||||
|
default:
|
||||||
|
|
||||||
|
db:
|
||||||
|
image: postgres:latest
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: servermonitorbot
|
||||||
|
POSTGRES_PASSWORD: servermonitorbot
|
||||||
|
POSTGRES_DB: servermonitorbot
|
||||||
|
networks:
|
||||||
|
default:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
default:
|
||||||
|
|
48
pom.xml
48
pom.xml
|
@ -5,7 +5,7 @@
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>3.4.0</version>
|
<version>3.1.2</version>
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
</parent>
|
</parent>
|
||||||
<groupId>ru.ldeloff</groupId>
|
<groupId>ru.ldeloff</groupId>
|
||||||
|
@ -15,6 +15,10 @@
|
||||||
<description>ServerMonitorBot</description>
|
<description>ServerMonitorBot</description>
|
||||||
<properties>
|
<properties>
|
||||||
<java.version>17</java.version>
|
<java.version>17</java.version>
|
||||||
|
<flyway.version>9.16.0</flyway.version>
|
||||||
|
<db.url>${database.url}</db.url>
|
||||||
|
<db.user>${database.username}</db.user>
|
||||||
|
<db.password>${database.password}</db.password>
|
||||||
<start-class>ru.ldeloff.servermonitorbot.ServerMonitorBotApplication</start-class>
|
<start-class>ru.ldeloff.servermonitorbot.ServerMonitorBotApplication</start-class>
|
||||||
</properties>
|
</properties>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -22,6 +26,7 @@
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter</artifactId>
|
<artifactId>spring-boot-starter</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
|
@ -40,13 +45,26 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.telegram</groupId>
|
<groupId>org.telegram</groupId>
|
||||||
<artifactId>telegrambots</artifactId>
|
<artifactId>telegrambots</artifactId>
|
||||||
<version>6.9.7.1</version>
|
<version>6.8.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.jcraft</groupId>
|
<groupId>com.jcraft</groupId>
|
||||||
<artifactId>jsch</artifactId>
|
<artifactId>jsch</artifactId>
|
||||||
<version>0.1.55</version>
|
<version>0.1.55</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.postgresql</groupId>
|
||||||
|
<artifactId>postgresql</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.flywaydb</groupId>
|
||||||
|
<artifactId>flyway-core</artifactId>
|
||||||
|
<version>${flyway.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -62,6 +80,32 @@
|
||||||
</exclude>
|
</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
</configuration>
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.flywaydb</groupId>
|
||||||
|
<artifactId>flyway-maven-plugin</artifactId>
|
||||||
|
<version>${flyway.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>migrate</id>
|
||||||
|
<phase>deploy</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>migrate</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<url>${database.url}</url>
|
||||||
|
<user>${database.username}</user>
|
||||||
|
<password>${database.password}</password>
|
||||||
|
<locations>
|
||||||
|
<location>classpath:db/migration</location>
|
||||||
|
</locations>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<goals>
|
<goals>
|
||||||
|
|
|
@ -3,12 +3,10 @@ package ru.ldeloff.servermonitorbot;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
import ru.ldeloff.servermonitorbot.config.SshConfig;
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServers;
|
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@EnableScheduling
|
@EnableConfigurationProperties(SshConfig.class)
|
||||||
@EnableConfigurationProperties(SshServers.class)
|
|
||||||
public class ServerMonitorBotApplication {
|
public class ServerMonitorBotApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
|
@ -1,149 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.commands;
|
|
||||||
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.Setter;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.Role;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
|
||||||
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
@Slf4j
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public abstract class CommandTemplate {
|
|
||||||
|
|
||||||
private final UpdateUtil updateUtil;
|
|
||||||
private final ServerListButtons serverListButtons;
|
|
||||||
public final SshService sshService;
|
|
||||||
private final MessagingService messagingService;
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
private List<Role> expectedRole = List.of(Role.ADMIN);
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
public boolean execute(Update update) {
|
|
||||||
if (!isExecute(update)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
User user = updateUtil.getUser(update);
|
|
||||||
String message = updateUtil.getMessage(update);
|
|
||||||
SendMessage answer = new SendMessage();
|
|
||||||
answer.setChatId(user.getTelegramId());
|
|
||||||
answer.setText(message);
|
|
||||||
|
|
||||||
if (!updateUtil.roleChecker(update, expectedRole)) {
|
|
||||||
logNotAuth(user, message);
|
|
||||||
messagingService.send(actionForNotAuth(user, answer));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
String type = checkTypeCommand(update);
|
|
||||||
switch (type) {
|
|
||||||
case "aggregate":
|
|
||||||
logSuccess(user, message);
|
|
||||||
messagingService.send(executeAggregate(user, answer));
|
|
||||||
return true;
|
|
||||||
case "command":
|
|
||||||
logSuccess(user, message);
|
|
||||||
messagingService.send(executeCommand(user, answer));
|
|
||||||
return true;
|
|
||||||
default:
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Методы для проверки команды
|
|
||||||
private boolean isExecute(Update update) {
|
|
||||||
if (update.hasMessage()) {
|
|
||||||
if (update.getMessage().hasText()) {
|
|
||||||
String messageText = update.getMessage().getText();
|
|
||||||
if (Objects.equals(messageText, name)) {
|
|
||||||
log.debug("Команда {} будет выполнена", messageText);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (update.hasCallbackQuery()) {
|
|
||||||
String [] tags = update.getCallbackQuery().getData().split(":");
|
|
||||||
if (tags.length > 1) {
|
|
||||||
if (Objects.equals(tags[0], name)) {
|
|
||||||
log.debug("Команда {} будет выполнена", tags[0]);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log.debug("Команда не будет выполнена");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log.debug("Команда не будет выполнена");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
private String checkTypeCommand(Update update) {
|
|
||||||
if (update.hasMessage()) {
|
|
||||||
if (update.getMessage().hasText()) {
|
|
||||||
return "aggregate";
|
|
||||||
}
|
|
||||||
} else if (update.hasCallbackQuery()) {
|
|
||||||
String [] tags = update.getCallbackQuery().getData().split(":");
|
|
||||||
if (tags.length > 1) {
|
|
||||||
return "command";
|
|
||||||
} else {
|
|
||||||
return "error";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "error";
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Методы при верных условиях
|
|
||||||
void logSuccess(User user, String message) {
|
|
||||||
log.info("Получена команда '{}' от {} ({}). OK", message, user.getLogin(), user.getTelegramId());
|
|
||||||
}
|
|
||||||
|
|
||||||
public SendMessage executeAggregate(User user, SendMessage message) {
|
|
||||||
return serverListButtons.uiForm(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
SendMessage executeCommand(User user, SendMessage message) {
|
|
||||||
String [] tags = Arrays.stream(message.getText().split(":"))
|
|
||||||
.map(String::trim)
|
|
||||||
.toArray(String[]::new);
|
|
||||||
|
|
||||||
if (tags[1].equals("all")) {
|
|
||||||
message.setText(executeCommandAllHost());
|
|
||||||
} else {
|
|
||||||
message.setText(Objects.requireNonNull(executeCommandSpecificHost(tags[1])));
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
private String executeCommandAllHost() {
|
|
||||||
List<SshServer> servers = sshService.getHealthSshServers();
|
|
||||||
StringBuilder response = new StringBuilder();
|
|
||||||
servers.forEach(server -> response.append(executeCommandSpecificHost(server.getName())).append("\n"));
|
|
||||||
return response.toString();
|
|
||||||
}
|
|
||||||
public abstract String executeCommandSpecificHost(String serverName);
|
|
||||||
|
|
||||||
// Методы при неверных условиях
|
|
||||||
void logNotAuth(User user, String message) {
|
|
||||||
log.warn("Получена команда '" + message + "' от " + user.getLogin()
|
|
||||||
+ " (" + user.getTelegramId() + "). Нет прав");
|
|
||||||
}
|
|
||||||
private SendMessage actionForNotAuth(User user, SendMessage message) {
|
|
||||||
message.setText("У пользователя " + user.getLogin() + " (" + user.getTelegramId()
|
|
||||||
+ ") недостаточно прав для выполнения этой команды");
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,49 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.commands.cpu.temp.service;
|
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
|
||||||
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Slf4j
|
|
||||||
public class CpuTemp extends CommandTemplate {
|
|
||||||
|
|
||||||
public CpuTemp(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
|
||||||
super(updateUtil, serverListButtons, sshService, messagingService);
|
|
||||||
setName("CPU.temp");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
try {
|
|
||||||
Optional<SshServer> server = sshService.getAllSshServers()
|
|
||||||
.stream()
|
|
||||||
.filter(x -> x.getName().equals(serverName))
|
|
||||||
.findFirst();
|
|
||||||
if (server.isPresent()) {
|
|
||||||
SshCommand result = sshService.execute(new SshCommand("cat /sys/class/thermal/thermal_zone0/temp", 100, server.get()));
|
|
||||||
return server.get().getName() + ": \n" +
|
|
||||||
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" :
|
|
||||||
String.format("%.1f",
|
|
||||||
Double.parseDouble(result.getResponse().replaceAll("\n", ""))/1000))
|
|
||||||
+ "°C";
|
|
||||||
} else {
|
|
||||||
log.error("Ошибка при выполнении команды 'CPUtemp'. Искомый сервер ({}) не найден", serverName);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
log.error("Ошибка при выполнении команды 'CPUtemp'" ,e.getMessage());
|
|
||||||
return "Сервер " + serverName + " не поддерживает команду 'CPUtemp'";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,87 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.commands.hdd.mdadm.service;
|
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
|
||||||
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Slf4j
|
|
||||||
public class MdadmStatus extends CommandTemplate {
|
|
||||||
|
|
||||||
public MdadmStatus(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
|
||||||
super(updateUtil, serverListButtons, sshService, messagingService);
|
|
||||||
setName("MDADM");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
Optional<SshServer> server = sshService.getAllSshServers()
|
|
||||||
.stream()
|
|
||||||
.filter(x -> x.getName().equals(serverName))
|
|
||||||
.findFirst();
|
|
||||||
if (server.isPresent()) {
|
|
||||||
// узнаю скок рейдов
|
|
||||||
SshCommand sshCommandRaid = sshService.execute(new SshCommand("mdadm --detail --scan", 500, server.get()));
|
|
||||||
List<String> raidNames = parseRaidNames(sshCommandRaid);
|
|
||||||
// Для каждого рейда надо выяснить статус
|
|
||||||
StringBuilder result = new StringBuilder();
|
|
||||||
raidNames.forEach(raid -> {
|
|
||||||
result.append(raid).append(":\n");
|
|
||||||
SshCommand sshCommandHdd = sshService.execute(new SshCommand("mdadm --detail " + raid, 500, server.get()));
|
|
||||||
List<String> hdds = parseHddState(sshCommandHdd);
|
|
||||||
hdds.forEach(hdd -> result.append(hdd).append("\n"));
|
|
||||||
});
|
|
||||||
return server.get().getName() + ": \n" + result;
|
|
||||||
} else {
|
|
||||||
log.error("Ошибка при выполнении команды 'mdadm'. Искомый сервер ({}) не найден", serverName);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> parseRaidNames(SshCommand result) {
|
|
||||||
List<String> names = new ArrayList<>();
|
|
||||||
Arrays.stream(result.getResponse().split("\n"))
|
|
||||||
.map(line -> line.split(" "))
|
|
||||||
.filter(lineArray -> lineArray.length >= 2)
|
|
||||||
.map(lineArray -> lineArray[1])
|
|
||||||
.forEach(names::add);
|
|
||||||
return names;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> parseHddState(SshCommand result) {
|
|
||||||
List<String> names = new ArrayList<>();
|
|
||||||
names.add("Number Name State");
|
|
||||||
|
|
||||||
String[] lines = result.getResponse().split("\n");
|
|
||||||
|
|
||||||
boolean foundHeader = false;
|
|
||||||
|
|
||||||
for (String line : lines) {
|
|
||||||
if (!foundHeader) {
|
|
||||||
if ( line.contains("Number") &&
|
|
||||||
line.contains("Major") &&
|
|
||||||
line.contains("Minor") &&
|
|
||||||
line.contains("RaidDevice") ) {
|
|
||||||
foundHeader = true;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
List<String> elements = Arrays.stream(line.split(" "))
|
|
||||||
.filter(x -> !Objects.equals(x, "")).toList();
|
|
||||||
|
|
||||||
names.add(elements.get(0) + ", "
|
|
||||||
+ elements.get(6) + ", "
|
|
||||||
+ elements.get(4) + " "
|
|
||||||
+ elements.get(5));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return names;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,39 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.commands.hdd.temp.service;
|
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
|
||||||
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Slf4j
|
|
||||||
public class HddTemp extends CommandTemplate {
|
|
||||||
public HddTemp(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
|
||||||
super(updateUtil, serverListButtons, sshService, messagingService);
|
|
||||||
setName("HDD.temp");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
Optional<SshServer> server = sshService.getAllSshServers()
|
|
||||||
.stream()
|
|
||||||
.filter(x -> x.getName().equals(serverName))
|
|
||||||
.findFirst();
|
|
||||||
if (server.isPresent()) {
|
|
||||||
SshCommand result = sshService.execute(new SshCommand("hddtemp /dev/sd*", 500, server.get()));
|
|
||||||
return server.get().getName() + ": \n" +
|
|
||||||
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" : result.getResponse());
|
|
||||||
} else {
|
|
||||||
log.error("Ошибка при выполнении команды 'hddtemp'. Искомый сервер (" + serverName + ") не найден");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,18 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.commands.statuschecker.scheduler;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.scheduling.annotation.Scheduled;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class CheckSessionStatusScheduler {
|
|
||||||
|
|
||||||
private final SshService sshService;
|
|
||||||
|
|
||||||
@Scheduled(fixedRateString = "${ssh.checkConnectionDelay}")
|
|
||||||
public void updateSessionStatusCheck() {
|
|
||||||
sshService.updateConnection();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,28 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.commands.statuschecker.service;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
|
||||||
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class CheckSessionStatus extends CommandTemplate {
|
|
||||||
|
|
||||||
public CheckSessionStatus(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
|
||||||
super(updateUtil, serverListButtons, sshService, messagingService);
|
|
||||||
setName("Статус");
|
|
||||||
}
|
|
||||||
|
|
||||||
public SendMessage executeAggregate(User user, SendMessage message) {
|
|
||||||
return super.sshService.getStatusSessions(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,40 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.commands.uname.service;
|
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
|
||||||
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Slf4j
|
|
||||||
public class Uname extends CommandTemplate {
|
|
||||||
|
|
||||||
public Uname(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
|
||||||
super(updateUtil, serverListButtons, sshService, messagingService);
|
|
||||||
setName("uname");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
Optional<SshServer> server = sshService.getAllSshServers()
|
|
||||||
.stream()
|
|
||||||
.filter(x -> x.getName().equals(serverName))
|
|
||||||
.findFirst();
|
|
||||||
if (server.isPresent()) {
|
|
||||||
SshCommand result = sshService.execute(new SshCommand("uname -a", 100, server.get()));
|
|
||||||
return server.get().getName() + ": " +
|
|
||||||
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" : result.getResponse());
|
|
||||||
} else {
|
|
||||||
log.error("Ошибка при выполнении команды 'uname'. Искомый сервер ({}) не найден", serverName);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,9 +1,11 @@
|
||||||
package ru.ldeloff.servermonitorbot.model.server;
|
package ru.ldeloff.servermonitorbot.config;
|
||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshServer;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
@ -11,6 +13,6 @@ import java.util.List;
|
||||||
@ConfigurationProperties(prefix = "ssh")
|
@ConfigurationProperties(prefix = "ssh")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
public class SshServers {
|
public class SshConfig {
|
||||||
private List<SshServer> servers;
|
private List<SshServer> servers;
|
||||||
}
|
}
|
|
@ -2,37 +2,16 @@ package ru.ldeloff.servermonitorbot.config;
|
||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import ru.ldeloff.servermonitorbot.model.user.User;
|
import ru.ldeloff.servermonitorbot.model.dto.InitUserDto;
|
||||||
import ru.ldeloff.servermonitorbot.service.RoleService;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Component
|
@Configuration
|
||||||
@ConfigurationProperties(prefix = "bot")
|
@ConfigurationProperties(prefix = "bot")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
public class UserConfig {
|
public class UserConfig {
|
||||||
|
private List<InitUserDto> users;
|
||||||
private List<UserProperty> users;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private RoleService roleService;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
public static class UserProperty {
|
|
||||||
private Long telegramId;
|
|
||||||
private String role;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<User> getUsers() {
|
|
||||||
return users.stream().map(user -> new User()
|
|
||||||
.setTelegramId(user.getTelegramId())
|
|
||||||
.setRole(roleService.findRoleByName(user.getRole()))
|
|
||||||
).toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,60 +1,98 @@
|
||||||
package ru.ldeloff.servermonitorbot.controller;
|
package ru.ldeloff.servermonitorbot.controller;
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
|
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
|
||||||
import org.telegram.telegrambots.meta.api.objects.Message;
|
|
||||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||||
import ru.ldeloff.servermonitorbot.model.TelegramBot;
|
import ru.ldeloff.servermonitorbot.model.TelegramBot;
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
import ru.ldeloff.servermonitorbot.repository.SshRepository;
|
||||||
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
import ru.ldeloff.servermonitorbot.service.command.FirstUseCommand;
|
||||||
import ru.ldeloff.servermonitorbot.view.SwitchToMainMenu;
|
import ru.ldeloff.servermonitorbot.service.command.GetStatusSessions;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.SwitchToMainMenu;
|
||||||
import java.util.Map;
|
import ru.ldeloff.servermonitorbot.service.command.cputemp.CpuTempAggregateCommand;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.cputemp.CpuTempCommand;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.hddtemp.HddTempAggregateCommand;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.hddtemp.HddTempCommand;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.uname.UnameAggregateCommand;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.uname.UnameCommand;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
|
@Slf4j
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class TelegramBotController extends TelegramLongPollingBot {
|
public class TelegramBotController extends TelegramLongPollingBot {
|
||||||
|
final TelegramBot telegramBot;
|
||||||
|
final SshRepository sshRepository;
|
||||||
|
|
||||||
private final Map<String, CommandTemplate> commands;
|
final FirstUseCommand firstUseCommand;
|
||||||
|
final GetStatusSessions getStatusSessions;
|
||||||
private final TelegramBot telegramBot;
|
final UnameAggregateCommand unameAggregateCommand;
|
||||||
private final SwitchToMainMenu switchToMainMenu;
|
final SwitchToMainMenu switchToMainMenu;
|
||||||
private final SshService sshService;
|
final UnameCommand unameCommand;
|
||||||
|
final CpuTempAggregateCommand cpuTempAggregateCommand;
|
||||||
|
final CpuTempCommand cpuTempCommand;
|
||||||
|
final HddTempAggregateCommand hddTempAggregateCommand;
|
||||||
|
final HddTempCommand hddTempCommand;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onUpdateReceived(Update update) {
|
public void onUpdateReceived(Update update) {
|
||||||
boolean result = false;
|
if (update.hasMessage()) {
|
||||||
for (Map.Entry<String, CommandTemplate> entry : commands.entrySet()) {
|
if (update.getMessage().hasText()) {
|
||||||
result = entry.getValue().execute(update);
|
String messageText = update.getMessage().getText();
|
||||||
if (result) {
|
switch (messageText) {
|
||||||
break;
|
case "/start" -> {
|
||||||
|
firstUseCommand.execute(update, this);
|
||||||
|
}
|
||||||
|
case "Статус" -> {
|
||||||
|
getStatusSessions.execute(update, this);
|
||||||
|
}
|
||||||
|
case "uname" -> {
|
||||||
|
unameAggregateCommand.execute(update, this);
|
||||||
|
}
|
||||||
|
case "CPU.temp" -> {
|
||||||
|
cpuTempAggregateCommand.execute(update, this);
|
||||||
|
}
|
||||||
|
case "HDD.temp" -> {
|
||||||
|
hddTempAggregateCommand.execute(update, this);
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
switchToMainMenu.execute(update, this);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
} else if (update.hasCallbackQuery()) {
|
||||||
if (!result) {
|
String [] tags = update.getCallbackQuery().getData().split(":");
|
||||||
Message message = update.getMessage();
|
if (tags.length > 1) {
|
||||||
if (message!=null) {
|
switch (tags[0]) {
|
||||||
message.setText("Not found");
|
case "uname" -> {
|
||||||
|
unameCommand.execute(update, this);
|
||||||
|
}
|
||||||
|
case "CPU.temp" -> {
|
||||||
|
cpuTempCommand.execute(update, this);
|
||||||
|
}
|
||||||
|
case "HDD.temp" -> {
|
||||||
|
hddTempCommand.execute(update, this);
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
switchToMainMenu.execute(update, this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
switchToMainMenu.execute(update, this);
|
||||||
}
|
}
|
||||||
update.setMessage(message);
|
|
||||||
switchToMainMenu.execute(update);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getBotUsername() {
|
public String getBotUsername() {
|
||||||
return telegramBot.getBotUsername();
|
return telegramBot.getBotUsername();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getBotToken() {
|
public String getBotToken() {
|
||||||
return telegramBot.getBotToken();
|
return telegramBot.getBotToken();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onClosing() {
|
public void onClosing() {
|
||||||
super.onClosing();
|
super.onClosing();
|
||||||
sshService.disconnectAllConnections();
|
sshRepository.disconnectSessions();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,26 +1,34 @@
|
||||||
package ru.ldeloff.servermonitorbot.init;
|
package ru.ldeloff.servermonitorbot.init;
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.boot.ApplicationArguments;
|
import org.springframework.boot.ApplicationArguments;
|
||||||
import org.springframework.boot.ApplicationRunner;
|
import org.springframework.boot.ApplicationRunner;
|
||||||
import org.springframework.core.annotation.Order;
|
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import ru.ldeloff.servermonitorbot.config.UserConfig;
|
import ru.ldeloff.servermonitorbot.config.UserConfig;
|
||||||
import ru.ldeloff.servermonitorbot.service.UserService;
|
import ru.ldeloff.servermonitorbot.mapper.UserMapper;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.dto.InitUserDto;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Slf4j
|
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
|
||||||
@Order(2)
|
|
||||||
public class AddUsers implements ApplicationRunner {
|
public class AddUsers implements ApplicationRunner {
|
||||||
|
final List<InitUserDto> initUsers;
|
||||||
final UserConfig userConfig;
|
|
||||||
final UserService userService;
|
final UserService userService;
|
||||||
|
final UserMapper userMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public AddUsers(UserConfig userConfig, UserService userService, UserMapper userMapper) {
|
||||||
|
this.initUsers = userConfig.getUsers();
|
||||||
|
this.userService = userService;
|
||||||
|
this.userMapper = userMapper;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run(ApplicationArguments args) {
|
public void run(ApplicationArguments args) throws Exception {
|
||||||
userConfig.getUsers().forEach(userService::saveOrUpdateUser);
|
initUsers.forEach(initUserDto -> {
|
||||||
log.info("Загружены и обновлены пользователи");
|
User user = userService.saveOrUpdateUser(userMapper.dtoToUser(initUserDto));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,33 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.init;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.boot.ApplicationArguments;
|
|
||||||
import org.springframework.boot.ApplicationRunner;
|
|
||||||
import org.springframework.core.annotation.Order;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.view.TelegramBotKeyboard;
|
|
||||||
|
|
||||||
@Slf4j
|
|
||||||
@Component
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
@Order(3)
|
|
||||||
public class ReloadNotification implements ApplicationRunner {
|
|
||||||
|
|
||||||
private final TelegramBotKeyboard telegramBotKeyboard;
|
|
||||||
private final MessagingService messagingService;
|
|
||||||
private final UserService userService;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run(ApplicationArguments args) {
|
|
||||||
userService.getAllUsers().forEach(user -> {
|
|
||||||
SendMessage sendMessage = new SendMessage();
|
|
||||||
sendMessage.setChatId(user.getTelegramId());
|
|
||||||
sendMessage.setText("Бот перезапущен");
|
|
||||||
messagingService.send(telegramBotKeyboard.uiForm(sendMessage));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,21 +1,20 @@
|
||||||
package ru.ldeloff.servermonitorbot.init;
|
package ru.ldeloff.servermonitorbot.init;
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.boot.ApplicationArguments;
|
import org.springframework.boot.ApplicationArguments;
|
||||||
import org.springframework.boot.ApplicationRunner;
|
import org.springframework.boot.ApplicationRunner;
|
||||||
import org.springframework.core.annotation.Order;
|
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
import ru.ldeloff.servermonitorbot.repository.SshRepository;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
|
||||||
@Order(4)
|
|
||||||
public class SshConnect implements ApplicationRunner {
|
public class SshConnect implements ApplicationRunner {
|
||||||
|
final SshRepository sshRepository;
|
||||||
|
|
||||||
final SshService sshService;
|
public SshConnect(SshRepository sshRepository) {
|
||||||
|
this.sshRepository = sshRepository;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run(ApplicationArguments args) {
|
public void run(ApplicationArguments args) throws Exception {
|
||||||
sshService.updateConnection();
|
sshRepository.connectToAllServer();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,26 @@
|
||||||
package ru.ldeloff.servermonitorbot.init;
|
package ru.ldeloff.servermonitorbot.init;
|
||||||
|
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.ApplicationArguments;
|
import org.springframework.boot.ApplicationArguments;
|
||||||
import org.springframework.boot.ApplicationRunner;
|
import org.springframework.boot.ApplicationRunner;
|
||||||
import org.springframework.core.annotation.Order;
|
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.telegram.telegrambots.meta.TelegramBotsApi;
|
import org.telegram.telegrambots.meta.TelegramBotsApi;
|
||||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
||||||
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
|
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
|
||||||
import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
|
import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
|
||||||
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
@NoArgsConstructor
|
||||||
@Order(1)
|
|
||||||
public class StartBot implements ApplicationRunner {
|
public class StartBot implements ApplicationRunner {
|
||||||
private final TelegramBotController telegramBot;
|
private TelegramBotController telegramBot;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public StartBot(TelegramBotController telegramBot) {
|
||||||
|
this.telegramBot = telegramBot;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run(ApplicationArguments args) {
|
public void run(ApplicationArguments args) {
|
||||||
|
@ -27,6 +29,7 @@ public class StartBot implements ApplicationRunner {
|
||||||
botsApi.registerBot(telegramBot);
|
botsApi.registerBot(telegramBot);
|
||||||
log.info("Бот запущен");
|
log.info("Бот запущен");
|
||||||
} catch (TelegramApiException e) {
|
} catch (TelegramApiException e) {
|
||||||
|
e.printStackTrace();
|
||||||
log.error(e.getMessage());
|
log.error(e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,22 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.mapper;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.dto.InitUserDto;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class UserMapper {
|
||||||
|
final RoleService roleService;
|
||||||
|
|
||||||
|
public UserMapper(RoleService roleService) {
|
||||||
|
this.roleService = roleService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public User dtoToUser(InitUserDto initUserDto) {
|
||||||
|
User user = new User();
|
||||||
|
user.setTelegramId(initUserDto.getTelegramId());
|
||||||
|
user.setRole(roleService.findRoleByName(initUserDto.getRole()));
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
}
|
|
@ -4,11 +4,10 @@ import jakarta.validation.constraints.Min;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
public class SshCommand {
|
public class Command {
|
||||||
@NotNull
|
@NotNull
|
||||||
private String command;
|
private String command;
|
||||||
@NotNull
|
@NotNull
|
||||||
|
@ -18,7 +17,7 @@ public class SshCommand {
|
||||||
private SshServer sshServer;
|
private SshServer sshServer;
|
||||||
private String response;
|
private String response;
|
||||||
|
|
||||||
public SshCommand(String command, int timeout, SshServer sshServer) {
|
public Command(String command, int timeout, SshServer sshServer) {
|
||||||
this.command = command;
|
this.command = command;
|
||||||
this.timeout = timeout;
|
this.timeout = timeout;
|
||||||
this.sshServer = sshServer;
|
this.sshServer = sshServer;
|
|
@ -0,0 +1,17 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.model;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Data
|
||||||
|
@Table(name = "roles")
|
||||||
|
public class Role {
|
||||||
|
@Id
|
||||||
|
@Column(name = "id")
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private long id;
|
||||||
|
|
||||||
|
@Column(name = "name")
|
||||||
|
private String name;
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package ru.ldeloff.servermonitorbot.model.server;
|
package ru.ldeloff.servermonitorbot.model;
|
||||||
|
|
||||||
import com.jcraft.jsch.Session;
|
import com.jcraft.jsch.Session;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
@ -21,5 +21,4 @@ public class SshServer {
|
||||||
@NotNull
|
@NotNull
|
||||||
private String password;
|
private String password;
|
||||||
private Session session;
|
private Session session;
|
||||||
private ServerStatus status;
|
|
||||||
}
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.model;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Data
|
||||||
|
@Table(name = "users")
|
||||||
|
public class User {
|
||||||
|
@Id
|
||||||
|
@Column(name = "id")
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(name = "telegram_id")
|
||||||
|
private Long telegramId;
|
||||||
|
|
||||||
|
@ManyToOne
|
||||||
|
@JoinColumn(name = "role_id")
|
||||||
|
private Role role;
|
||||||
|
|
||||||
|
@Transient
|
||||||
|
private String login;
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
public class InitUserDto {
|
||||||
|
@NotNull
|
||||||
|
private long telegramId;
|
||||||
|
@NotNull
|
||||||
|
private String role;
|
||||||
|
}
|
|
@ -1,7 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.model.server;
|
|
||||||
|
|
||||||
public enum ServerStatus {
|
|
||||||
ONLINE,
|
|
||||||
OFFLINE,
|
|
||||||
CONNECTION_LOST
|
|
||||||
}
|
|
|
@ -1,7 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.model.user;
|
|
||||||
|
|
||||||
public enum Role {
|
|
||||||
ADMIN,
|
|
||||||
USER,
|
|
||||||
ANONYMOUS
|
|
||||||
}
|
|
|
@ -1,12 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.model.user;
|
|
||||||
|
|
||||||
import lombok.Data;
|
|
||||||
import lombok.experimental.Accessors;
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@Accessors(chain = true)
|
|
||||||
public class User {
|
|
||||||
private Long telegramId;
|
|
||||||
private Role role;
|
|
||||||
private String login;
|
|
||||||
}
|
|
|
@ -1,13 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.model.user;
|
|
||||||
|
|
||||||
import lombok.Getter;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Component
|
|
||||||
public class Users {
|
|
||||||
private final List<User> users = new ArrayList<>();
|
|
||||||
}
|
|
|
@ -0,0 +1,13 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.repository;
|
||||||
|
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.Role;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface RoleRepository extends JpaRepository<Role, Long> {
|
||||||
|
Optional<Role> findRoleByName(String name);
|
||||||
|
Optional<Role> findRoleById(Long id);
|
||||||
|
}
|
|
@ -1,12 +1,16 @@
|
||||||
package ru.ldeloff.servermonitorbot.repository;
|
package ru.ldeloff.servermonitorbot.repository;
|
||||||
|
|
||||||
import com.jcraft.jsch.JSchException;
|
import com.jcraft.jsch.JSchException;
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
import com.jcraft.jsch.Session;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshServer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
public interface SshRepository {
|
public interface SshRepository {
|
||||||
|
void connectToAllServer();
|
||||||
void connect(SshServer sshServer) throws JSchException;
|
Session connectToServer(SshServer sshServer) throws JSchException;
|
||||||
|
void disconnectSessions();
|
||||||
void disconnect(SshServer sshServer);
|
String getStatusSessions();
|
||||||
|
List<SshServer> getSshServers();
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,35 +3,86 @@ package ru.ldeloff.servermonitorbot.repository;
|
||||||
import com.jcraft.jsch.JSch;
|
import com.jcraft.jsch.JSch;
|
||||||
import com.jcraft.jsch.JSchException;
|
import com.jcraft.jsch.JSchException;
|
||||||
import com.jcraft.jsch.Session;
|
import com.jcraft.jsch.Session;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.config.SshConfig;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshServer;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
@Repository
|
@Repository
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class SshRepositoryImpl implements SshRepository {
|
public class SshRepositoryImpl implements SshRepository {
|
||||||
|
|
||||||
@Value("${ssh.timeout:5000}")
|
private final List<SshServer> sshServers;
|
||||||
private int TIMEOUT;
|
|
||||||
|
@Autowired
|
||||||
|
public SshRepositoryImpl(SshConfig sshConfig) {
|
||||||
|
this.sshServers = sshConfig.getServers();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Session> sessions = new ArrayList<>();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void connect(SshServer sshServer) throws JSchException {
|
public void connectToAllServer() {
|
||||||
|
sshServers.forEach(sshServer -> {
|
||||||
|
try {
|
||||||
|
Session session = connectToServer(sshServer);
|
||||||
|
sshServer.setSession(session);
|
||||||
|
log.info("Успешно подключён к " + sshServer.getHost());
|
||||||
|
sessions.add(session);
|
||||||
|
} catch (JSchException e) {
|
||||||
|
log.warn("Не удалось соединиться с " + sshServer.getHost() + ": " + e.getMessage());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Session connectToServer(SshServer sshServer) throws JSchException {
|
||||||
Session session = new JSch().getSession(sshServer.getUser(),
|
Session session = new JSch().getSession(sshServer.getUser(),
|
||||||
sshServer.getHost(),
|
sshServer.getHost(),
|
||||||
sshServer.getPort());
|
sshServer.getPort());
|
||||||
session.setPassword(sshServer.getPassword());
|
session.setPassword(sshServer.getPassword());
|
||||||
session.setConfig("StrictHostKeyChecking", "no");
|
session.setConfig("StrictHostKeyChecking", "no");
|
||||||
session.setTimeout(TIMEOUT);
|
|
||||||
|
|
||||||
session.connect();
|
session.connect();
|
||||||
|
return session;
|
||||||
sshServer.setSession(session);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void disconnect(SshServer sshServer) {
|
public void disconnectSessions() {
|
||||||
sshServer.getSession().disconnect();
|
if (!sessions.isEmpty()) {
|
||||||
|
sessions.forEach(Session::disconnect);
|
||||||
|
sessions.forEach(sessions::remove);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getStatusSessions() {
|
||||||
|
StringBuilder text = new StringBuilder("Статус соединения: \n");
|
||||||
|
sshServers.forEach(server -> {
|
||||||
|
text.append(server.getName())
|
||||||
|
.append(": ")
|
||||||
|
.append(checkStatusServer(server))
|
||||||
|
.append("\n");
|
||||||
|
});
|
||||||
|
return String.valueOf(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SshServer> getSshServers() {
|
||||||
|
return sshServers;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String checkStatusServer(SshServer server) {
|
||||||
|
if (Objects.isNull(server.getSession())) {
|
||||||
|
return "нет соединения";
|
||||||
|
} else {
|
||||||
|
return server.getSession().isConnected() ? "OK" : "отключён";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,10 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.repository;
|
||||||
|
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface UserRepository extends JpaRepository<User, Long> {
|
||||||
|
User getByTelegramId(long id);
|
||||||
|
}
|
|
@ -1,11 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service;
|
|
||||||
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
|
|
||||||
public interface MessagingService {
|
|
||||||
void sendMessageToAll(String message);
|
|
||||||
|
|
||||||
void sendMessageToAdmins(String message);
|
|
||||||
|
|
||||||
void send(SendMessage message);
|
|
||||||
}
|
|
|
@ -1,48 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.context.ApplicationContext;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
|
||||||
import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
|
|
||||||
|
|
||||||
|
|
||||||
@Slf4j
|
|
||||||
@Service
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class MessagingServiceImpl implements MessagingService {
|
|
||||||
|
|
||||||
private final UserService userService;
|
|
||||||
private final ApplicationContext applicationContext;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void sendMessageToAll(String message) {
|
|
||||||
userService.getAllUsers().forEach(user -> {
|
|
||||||
SendMessage sendMessage = new SendMessage();
|
|
||||||
sendMessage.setChatId(user.getTelegramId());
|
|
||||||
sendMessage.setText(message);
|
|
||||||
send(sendMessage);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void sendMessageToAdmins(String message) {
|
|
||||||
userService.getAllAdmins().forEach(user -> {
|
|
||||||
SendMessage sendMessage = new SendMessage();
|
|
||||||
sendMessage.setChatId(user.getTelegramId());
|
|
||||||
sendMessage.setText(message);
|
|
||||||
send(sendMessage);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void send(SendMessage message) {
|
|
||||||
try {
|
|
||||||
applicationContext.getBean(TelegramBotController.class).execute(message);
|
|
||||||
} catch (TelegramApiException e) {
|
|
||||||
log.warn("Ошибка при отправке сообщения", e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,7 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service;
|
|
||||||
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.Role;
|
|
||||||
|
|
||||||
public interface RoleService {
|
|
||||||
Role findRoleByName(String name);
|
|
||||||
}
|
|
|
@ -1,14 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.Role;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class RoleServiceImpl implements RoleService {
|
|
||||||
@Override
|
|
||||||
public Role findRoleByName(String name) {
|
|
||||||
return Role.valueOf(name);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service;
|
|
||||||
|
|
||||||
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public interface SshService {
|
|
||||||
|
|
||||||
void updateConnection();
|
|
||||||
|
|
||||||
void disconnectAllConnections();
|
|
||||||
|
|
||||||
SendMessage getStatusSessions(SendMessage update);
|
|
||||||
|
|
||||||
List<SshServer> getAllSshServers();
|
|
||||||
|
|
||||||
List<SshServer> getHealthSshServers();
|
|
||||||
|
|
||||||
SshCommand execute(SshCommand sshCommand);
|
|
||||||
|
|
||||||
List<SshCommand> execute(List<SshCommand> sshCommands);
|
|
||||||
}
|
|
|
@ -1,146 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service;
|
|
||||||
|
|
||||||
import com.jcraft.jsch.ChannelExec;
|
|
||||||
import com.jcraft.jsch.JSchException;
|
|
||||||
import com.jcraft.jsch.Session;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.server.ServerStatus;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServers;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
|
||||||
import ru.ldeloff.servermonitorbot.repository.SshRepository;
|
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Slf4j
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class SshServiceImpl implements SshService {
|
|
||||||
|
|
||||||
private final SshServers sshServers;
|
|
||||||
private final SshRepository sshRepository;
|
|
||||||
private final MessagingService messagingService;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void updateConnection() {
|
|
||||||
sshServers.getServers().forEach(sshServer -> {
|
|
||||||
try {
|
|
||||||
sshRepository.connect(sshServer);
|
|
||||||
updateServerStatus(sshServer, ServerStatus.ONLINE);
|
|
||||||
log.info("Успешно подключён к {}", sshServer.getHost());
|
|
||||||
} catch (JSchException e) {
|
|
||||||
if (sshServer.getStatus() == null) {
|
|
||||||
updateServerStatus(sshServer, ServerStatus.OFFLINE);
|
|
||||||
}
|
|
||||||
if (sshServer.getStatus() == ServerStatus.ONLINE) {
|
|
||||||
updateServerStatus(sshServer, ServerStatus.CONNECTION_LOST);
|
|
||||||
}
|
|
||||||
log.warn("Не удалось соединиться с {}: {}", sshServer.getHost(), e.getMessage());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void disconnectAllConnections() {
|
|
||||||
sshServers.getServers().forEach(sshRepository::disconnect);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public SendMessage getStatusSessions(SendMessage message) {
|
|
||||||
StringBuilder text = new StringBuilder("Статус соединения (может выполняться долго): \n");
|
|
||||||
sshServers.getServers().forEach(server -> text.append(server.getName())
|
|
||||||
.append(": ")
|
|
||||||
.append(checkStatusServer(server))
|
|
||||||
.append("\n"));
|
|
||||||
message.setText(text.toString());
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String checkStatusServer(SshServer server) {
|
|
||||||
if (Objects.isNull(server.getSession())) {
|
|
||||||
return "нет соединения";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (server.getSession().isConnected()) {
|
|
||||||
return "OK";
|
|
||||||
} else {
|
|
||||||
return "потеряно соединение";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean checkHealth(SshServer server) {
|
|
||||||
if (Objects.isNull(server.getSession())) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return server.getSession().isConnected();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<SshServer> getAllSshServers() {
|
|
||||||
return sshServers.getServers();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<SshServer> getHealthSshServers() {
|
|
||||||
return sshServers.getServers().stream().filter(this::checkHealth).toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public SshCommand execute(SshCommand sshCommand) {
|
|
||||||
List<SshCommand> sshCommands = new ArrayList<>();
|
|
||||||
sshCommands.add(sshCommand);
|
|
||||||
return execute(sshCommands).get(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<SshCommand> execute(List<SshCommand> sshCommands) {
|
|
||||||
Session session = sshCommands.get(0).getSshServer().getSession(); // подразумевается, что в листе с командами сервер один и тот же
|
|
||||||
ChannelExec channel = null;
|
|
||||||
try {
|
|
||||||
channel = (ChannelExec) session.openChannel("exec");
|
|
||||||
ChannelExec finalChannel = channel;
|
|
||||||
|
|
||||||
sshCommands.forEach(command -> {
|
|
||||||
try {
|
|
||||||
finalChannel.setCommand(command.getCommand());
|
|
||||||
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
|
|
||||||
finalChannel.setOutputStream(responseStream);
|
|
||||||
finalChannel.connect();
|
|
||||||
while (finalChannel.isConnected()) {
|
|
||||||
Thread.sleep(command.getTimeout());
|
|
||||||
}
|
|
||||||
String responseString = new String(responseStream.toByteArray());
|
|
||||||
command.setResponse(responseString);
|
|
||||||
} catch (JSchException | InterruptedException e) {
|
|
||||||
log.warn(e.getMessage());
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (JSchException e) {
|
|
||||||
log.warn(e.getMessage());
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
} finally {
|
|
||||||
if (channel != null) {
|
|
||||||
channel.disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return sshCommands;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateServerStatus(SshServer server, ServerStatus newStatus) {
|
|
||||||
ServerStatus oldStatus = server.getStatus();
|
|
||||||
if (oldStatus != newStatus) {
|
|
||||||
server.setStatus(newStatus);
|
|
||||||
messagingService.sendMessageToAdmins("Server status changed for " + server.getName() +
|
|
||||||
": " + oldStatus + " -> " + newStatus);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,16 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service;
|
|
||||||
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.User;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public interface UserService {
|
|
||||||
|
|
||||||
void saveOrUpdateUser(User user);
|
|
||||||
|
|
||||||
User getByTelegramId(Long id);
|
|
||||||
|
|
||||||
List<User> getAllUsers();
|
|
||||||
|
|
||||||
List<User> getAllAdmins();
|
|
||||||
}
|
|
|
@ -1,42 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.Role;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.Users;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Slf4j
|
|
||||||
@Service
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class UserServiceImpl implements UserService {
|
|
||||||
|
|
||||||
private final Users users;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void saveOrUpdateUser(User user) {
|
|
||||||
if (getByTelegramId(user.getTelegramId()) == null) {
|
|
||||||
users.getUsers().add(user);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public User getByTelegramId(Long telegramId) {
|
|
||||||
return users.getUsers().stream()
|
|
||||||
.filter(user -> user.getTelegramId().equals(telegramId))
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<User> getAllUsers() {return users.getUsers(); }
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<User> getAllAdmins() {
|
|
||||||
return users.getUsers().stream().filter(user -> user.getRole().equals(Role.ADMIN)).toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -0,0 +1,87 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||||
|
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
||||||
|
import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Slf4j
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public abstract class CommandTemplate {
|
||||||
|
final UserService userService;
|
||||||
|
final RoleService roleService;
|
||||||
|
long expectedRole = 2L;
|
||||||
|
public abstract SendMessage actionForAuth(User user, SendMessage message);
|
||||||
|
|
||||||
|
public SendMessage actionForNotAuth(User user, SendMessage message) {
|
||||||
|
message.setText("У пользователя " + user.getLogin() + " (" + user.getTelegramId()
|
||||||
|
+ ") недостаточно прав для выполнения этой команды");
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
public void execute(Update update, TelegramBotController bot) {
|
||||||
|
User user = getUser(update);
|
||||||
|
String message = getMessage(update);
|
||||||
|
SendMessage answer = new SendMessage();
|
||||||
|
answer.setChatId(user.getTelegramId());
|
||||||
|
answer.setText(message);
|
||||||
|
if (user.getRole().getId() <= expectedRole) {
|
||||||
|
logSuccess(user, message);
|
||||||
|
sendMessage(actionForAuth(user, answer), bot);
|
||||||
|
} else {
|
||||||
|
logNotAuth(user, message);
|
||||||
|
sendMessage(actionForNotAuth(user, answer), bot);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
protected void logSuccess(User user, String message) {
|
||||||
|
log.info("Получена команда '" + message + "' от " + user.getLogin()
|
||||||
|
+ " (" + user.getTelegramId() + "). OK");
|
||||||
|
}
|
||||||
|
protected void logNotAuth(User user, String message) {
|
||||||
|
log.warn("Получена команда '" + message + "' от " + user.getLogin()
|
||||||
|
+ " (" + user.getTelegramId() + "). Нет прав");
|
||||||
|
}
|
||||||
|
private User getUser(Update update) {
|
||||||
|
long id = -1L;
|
||||||
|
String login = null;
|
||||||
|
if (update.hasMessage()) {
|
||||||
|
id = update.getMessage().getChat().getId();
|
||||||
|
login = update.getMessage().getChat().getUserName();
|
||||||
|
} else if (update.hasCallbackQuery()) {
|
||||||
|
id = update.getCallbackQuery().getMessage().getChat().getId();
|
||||||
|
login = update.getCallbackQuery().getMessage().getChat().getUserName();
|
||||||
|
}
|
||||||
|
User user = userService.getByTelegramId(id);
|
||||||
|
if (user == null) {
|
||||||
|
user = new User();
|
||||||
|
user.setTelegramId(id);
|
||||||
|
user.setRole(roleService.findRoleById(3L));
|
||||||
|
}
|
||||||
|
user.setLogin(login);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getMessage(Update update) {
|
||||||
|
if (update.hasMessage()) {
|
||||||
|
return update.getMessage().getText();
|
||||||
|
} else if (update.hasCallbackQuery()) {
|
||||||
|
return update.getCallbackQuery().getData();
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendMessage(SendMessage message, TelegramBotController bot) {
|
||||||
|
try {
|
||||||
|
bot.execute(message);
|
||||||
|
} catch (TelegramApiException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
log.warn(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
import ru.ldeloff.servermonitorbot.utils.ui.TelegramBotKeyboard;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class FirstUseCommand extends CommandTemplate {
|
||||||
|
final TelegramBotKeyboard telegramBotKeyboard;
|
||||||
|
|
||||||
|
public FirstUseCommand(UserService userService, RoleService roleService, TelegramBotKeyboard telegramBotKeyboard) {
|
||||||
|
super(userService, roleService);
|
||||||
|
this.telegramBotKeyboard = telegramBotKeyboard;
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public SendMessage actionForAuth(User user, SendMessage message) {
|
||||||
|
message.setText("Добро пожаловать " + user.getLogin() + "!");
|
||||||
|
return telegramBotKeyboard.uiForm(message);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class GetStatusSessions extends CommandTemplate {
|
||||||
|
final SshService sshService;
|
||||||
|
|
||||||
|
public GetStatusSessions(UserService userService, RoleService roleService, SshService sshService) {
|
||||||
|
super(userService, roleService);
|
||||||
|
this.sshService = sshService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage actionForAuth(User user, SendMessage message) {
|
||||||
|
return sshService.getStatusSessions(message);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
import ru.ldeloff.servermonitorbot.utils.ui.TelegramBotKeyboard;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class SwitchToMainMenu extends CommandTemplate {
|
||||||
|
final TelegramBotKeyboard telegramBotKeyboard;
|
||||||
|
|
||||||
|
public SwitchToMainMenu(UserService userService, RoleService roleService, TelegramBotKeyboard telegramBotKeyboard) {
|
||||||
|
super(userService, roleService);
|
||||||
|
this.telegramBotKeyboard = telegramBotKeyboard;
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public SendMessage actionForAuth(User user, SendMessage message) {
|
||||||
|
message.setText("Неверная команда. Попробуем сначала.");
|
||||||
|
return telegramBotKeyboard.uiForm(message);
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public void logSuccess(User user, String message) {
|
||||||
|
log.warn("Получена несуществующая команда '" + message + "' от " + user.getLogin()
|
||||||
|
+ " (" + user.getTelegramId() + "). OK");
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public void logNotAuth(User user, String message) {
|
||||||
|
log.warn("Получена несуществующая команда '" + message + "' от " + user.getLogin()
|
||||||
|
+ " (" + user.getTelegramId() + "). Нет прав");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command.cputemp;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
import ru.ldeloff.servermonitorbot.utils.ui.uname.ServerListButtons;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class CpuTempAggregateCommand extends CommandTemplate {
|
||||||
|
final ServerListButtons serverListButtons;
|
||||||
|
|
||||||
|
public CpuTempAggregateCommand(UserService userService, RoleService roleService, ServerListButtons serverListButtons) {
|
||||||
|
super(userService, roleService);
|
||||||
|
this.serverListButtons = serverListButtons;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage actionForAuth(User user, SendMessage message) {
|
||||||
|
return serverListButtons.uiForm(message);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,67 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command.cputemp;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.Command;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshServer;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
import ru.ldeloff.servermonitorbot.utils.SshServerUtils;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class CpuTempCommand extends CommandTemplate {
|
||||||
|
final SshService sshService;
|
||||||
|
public CpuTempCommand(UserService userService, RoleService roleService, SshService sshService) {
|
||||||
|
super(userService, roleService);
|
||||||
|
this.sshService = sshService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage actionForAuth(User user, SendMessage message) {
|
||||||
|
String [] tags = Arrays.stream(message.getText().split(":"))
|
||||||
|
.map(String::trim)
|
||||||
|
.toArray(String[]::new);
|
||||||
|
|
||||||
|
if (tags[1].equals("all")) {
|
||||||
|
message.setText(hddTempAllHost());
|
||||||
|
} else {
|
||||||
|
message.setText(Objects.requireNonNull(hddTempSpecificHost(tags[1])));
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String hddTempAllHost() {
|
||||||
|
List<SshServer> servers = SshServerUtils.filterGoodServers(sshService.getSshServers());
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
servers.forEach(server -> response.append(hddTempSpecificHost(server.getName())).append("\n"));
|
||||||
|
return response.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String hddTempSpecificHost(String serverName) {
|
||||||
|
Optional<SshServer> server = sshService.getSshServers()
|
||||||
|
.stream()
|
||||||
|
.filter(x -> x.getName().equals(serverName))
|
||||||
|
.findFirst();
|
||||||
|
if (server.isPresent()) {
|
||||||
|
Command result = sshService.execute(new Command("cat /sys/class/thermal/thermal_zone0/temp", 100, server.get()));
|
||||||
|
return server.get().getName() + ": \n" +
|
||||||
|
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" :
|
||||||
|
String.format("%.1f",
|
||||||
|
Double.parseDouble(result.getResponse().replaceAll("\n", ""))/1000))
|
||||||
|
+ "°C";
|
||||||
|
} else {
|
||||||
|
log.error("Ошибка при выполнении команды 'CPUtemp'. Искомый сервер (" + serverName + ") не найден");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command.hddtemp;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
import ru.ldeloff.servermonitorbot.utils.ui.uname.ServerListButtons;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class HddTempAggregateCommand extends CommandTemplate {
|
||||||
|
final ServerListButtons serverListButtons;
|
||||||
|
|
||||||
|
public HddTempAggregateCommand(UserService userService, RoleService roleService, ServerListButtons serverListButtons) {
|
||||||
|
super(userService, roleService);
|
||||||
|
this.serverListButtons = serverListButtons;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage actionForAuth(User user, SendMessage message) {
|
||||||
|
return serverListButtons.uiForm(message);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,64 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command.hddtemp;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.Command;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshServer;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
import ru.ldeloff.servermonitorbot.utils.SshServerUtils;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class HddTempCommand extends CommandTemplate {
|
||||||
|
final SshService sshService;
|
||||||
|
public HddTempCommand(UserService userService, RoleService roleService, SshService sshService) {
|
||||||
|
super(userService, roleService);
|
||||||
|
this.sshService = sshService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage actionForAuth(User user, SendMessage message) {
|
||||||
|
String [] tags = Arrays.stream(message.getText().split(":"))
|
||||||
|
.map(String::trim)
|
||||||
|
.toArray(String[]::new);
|
||||||
|
|
||||||
|
if (tags[1].equals("all")) {
|
||||||
|
message.setText(hddTempAllHost());
|
||||||
|
} else {
|
||||||
|
message.setText(Objects.requireNonNull(hddTempSpecificHost(tags[1])));
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String hddTempAllHost() {
|
||||||
|
List<SshServer> servers = SshServerUtils.filterGoodServers(sshService.getSshServers());
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
servers.forEach(server -> response.append(hddTempSpecificHost(server.getName())).append("\n"));
|
||||||
|
return response.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String hddTempSpecificHost(String serverName) {
|
||||||
|
Optional<SshServer> server = sshService.getSshServers()
|
||||||
|
.stream()
|
||||||
|
.filter(x -> x.getName().equals(serverName))
|
||||||
|
.findFirst();
|
||||||
|
if (server.isPresent()) {
|
||||||
|
Command result = sshService.execute(new Command("hddtemp /dev/sd*", 500, server.get()));
|
||||||
|
return server.get().getName() + ": \n" +
|
||||||
|
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" : result.getResponse());
|
||||||
|
} else {
|
||||||
|
log.error("Ошибка при выполнении команды 'hddtemp'. Искомый сервер (" + serverName + ") не найден");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command.uname;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
import ru.ldeloff.servermonitorbot.utils.ui.uname.ServerListButtons;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class UnameAggregateCommand extends CommandTemplate {
|
||||||
|
final ServerListButtons serverListButtons;
|
||||||
|
|
||||||
|
public UnameAggregateCommand(UserService userService, RoleService roleService, ServerListButtons serverListButtons) {
|
||||||
|
super(userService, roleService);
|
||||||
|
this.serverListButtons = serverListButtons;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage actionForAuth(User user, SendMessage message) {
|
||||||
|
return serverListButtons.uiForm(message);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,63 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.command.uname;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.Command;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshServer;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
||||||
|
import ru.ldeloff.servermonitorbot.utils.SshServerUtils;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class UnameCommand extends CommandTemplate {
|
||||||
|
final SshService sshService;
|
||||||
|
public UnameCommand(UserService userService, RoleService roleService, SshService sshService) {
|
||||||
|
super(userService, roleService);
|
||||||
|
this.sshService = sshService;
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public SendMessage actionForAuth(User user, SendMessage message) {
|
||||||
|
String [] tags = Arrays.stream(message.getText().split(":"))
|
||||||
|
.map(String::trim)
|
||||||
|
.toArray(String[]::new);
|
||||||
|
|
||||||
|
if (tags[1].equals("all")) {
|
||||||
|
message.setText(unameAllHost());
|
||||||
|
} else {
|
||||||
|
message.setText(Objects.requireNonNull(unameSpecificHost(tags[1])));
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String unameAllHost() {
|
||||||
|
List<SshServer> servers = SshServerUtils.filterGoodServers(sshService.getSshServers());
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
servers.forEach(server -> response.append(unameSpecificHost(server.getName())).append("\n"));
|
||||||
|
return response.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String unameSpecificHost(String serverName) {
|
||||||
|
Optional<SshServer> server = sshService.getSshServers()
|
||||||
|
.stream()
|
||||||
|
.filter(x -> x.getName().equals(serverName))
|
||||||
|
.findFirst();
|
||||||
|
if (server.isPresent()) {
|
||||||
|
Command result = sshService.execute(new Command("uname -a", 100, server.get()));
|
||||||
|
return server.get().getName() + ": " +
|
||||||
|
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" : result.getResponse());
|
||||||
|
} else {
|
||||||
|
log.error("Ошибка при выполнении команды 'uname'. Искомый сервер (" + serverName + ") не найден");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.role;
|
||||||
|
|
||||||
|
import ru.ldeloff.servermonitorbot.model.Role;
|
||||||
|
|
||||||
|
public interface RoleService {
|
||||||
|
Role findRoleByName(String name);
|
||||||
|
|
||||||
|
Role findRoleById(Long id);
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.role;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.Role;
|
||||||
|
import ru.ldeloff.servermonitorbot.repository.RoleRepository;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RoleServiceImpl implements RoleService {
|
||||||
|
private final RoleRepository roleRepository;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Role findRoleByName(String name) {
|
||||||
|
Optional<Role> role = roleRepository.findRoleByName(name.toUpperCase(Locale.ROOT));
|
||||||
|
//noinspection OptionalGetWithoutIsPresent
|
||||||
|
return role.orElseGet(() -> roleRepository.findRoleByName("ANONYMOUS").get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Role findRoleById(Long id) {
|
||||||
|
Optional<Role> role = roleRepository.findRoleById(id);
|
||||||
|
return role.orElseGet(() -> roleRepository.findRoleByName("ANONYMOUS").get());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.ssh;
|
||||||
|
|
||||||
|
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.Command;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshServer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface SshService {
|
||||||
|
SendMessage getStatusSessions(SendMessage update);
|
||||||
|
|
||||||
|
List<SshServer> getSshServers();
|
||||||
|
Command execute(Command command);
|
||||||
|
List<Command> execute(List<Command> commands);
|
||||||
|
}
|
|
@ -0,0 +1,74 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.ssh;
|
||||||
|
|
||||||
|
import com.jcraft.jsch.ChannelExec;
|
||||||
|
import com.jcraft.jsch.JSchException;
|
||||||
|
import com.jcraft.jsch.Session;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.Command;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshServer;
|
||||||
|
import ru.ldeloff.servermonitorbot.repository.SshRepository;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SshServiceImpl implements SshService {
|
||||||
|
final SshRepository sshRepository;
|
||||||
|
@Override
|
||||||
|
public SendMessage getStatusSessions(SendMessage message) {
|
||||||
|
message.setText(sshRepository.getStatusSessions());
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public List<SshServer> getSshServers() {
|
||||||
|
return sshRepository.getSshServers();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Command execute(Command command) {
|
||||||
|
List<Command> commands = new ArrayList<>();
|
||||||
|
commands.add(command);
|
||||||
|
return execute(commands).get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Command> execute(List<Command> commands) {
|
||||||
|
Session session = commands.get(0).getSshServer().getSession(); // подразумевается, что в листе с командами сервер один и тот же
|
||||||
|
ChannelExec channel = null;
|
||||||
|
try {
|
||||||
|
channel = (ChannelExec) session.openChannel("exec");
|
||||||
|
ChannelExec finalChannel = channel;
|
||||||
|
|
||||||
|
commands.forEach(command -> {
|
||||||
|
try {
|
||||||
|
finalChannel.setCommand(command.getCommand());
|
||||||
|
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
|
||||||
|
finalChannel.setOutputStream(responseStream);
|
||||||
|
finalChannel.connect();
|
||||||
|
while (finalChannel.isConnected()) {
|
||||||
|
Thread.sleep(command.getTimeout());
|
||||||
|
}
|
||||||
|
String responseString = new String(responseStream.toByteArray());
|
||||||
|
command.setResponse(responseString);
|
||||||
|
} catch (JSchException | InterruptedException e) {
|
||||||
|
log.warn(e.getMessage());
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (JSchException e) {
|
||||||
|
log.warn(e.getMessage());
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
} finally {
|
||||||
|
if (channel != null) {
|
||||||
|
channel.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return commands;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.user;
|
||||||
|
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
|
||||||
|
public interface UserService {
|
||||||
|
User saveOrUpdateUser(User user);
|
||||||
|
|
||||||
|
User getByTelegramId(Long id);
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service.user;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.repository.UserRepository;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
public class UserServiceImpl implements UserService {
|
||||||
|
|
||||||
|
final UserRepository userRepository;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public User saveOrUpdateUser(User user) {
|
||||||
|
User existUser = userRepository.getByTelegramId(user.getTelegramId());
|
||||||
|
if (existUser != null) {
|
||||||
|
user.setId(existUser.getId());
|
||||||
|
}
|
||||||
|
return userRepository.save(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public User getByTelegramId(Long id) {
|
||||||
|
return userRepository.getByTelegramId(id);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,51 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.util;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.Role;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.UserService;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class UpdateUtil {
|
|
||||||
|
|
||||||
private final UserService userService;
|
|
||||||
|
|
||||||
public User getUser(Update update) {
|
|
||||||
long id = -1L;
|
|
||||||
String login = null;
|
|
||||||
if (update.hasMessage()) {
|
|
||||||
id = update.getMessage().getChat().getId();
|
|
||||||
login = update.getMessage().getChat().getUserName();
|
|
||||||
} else if (update.hasCallbackQuery()) {
|
|
||||||
id = update.getCallbackQuery().getMessage().getChatId();
|
|
||||||
login = update.getCallbackQuery().getFrom().getUserName();
|
|
||||||
}
|
|
||||||
User user = userService.getByTelegramId(id);
|
|
||||||
if (user == null) {
|
|
||||||
user = new User();
|
|
||||||
user.setTelegramId(id);
|
|
||||||
user.setRole(Role.ANONYMOUS);
|
|
||||||
}
|
|
||||||
user.setLogin(login);
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMessage(Update update) {
|
|
||||||
if (update.hasMessage()) {
|
|
||||||
return update.getMessage().getText();
|
|
||||||
} else if (update.hasCallbackQuery()) {
|
|
||||||
return update.getCallbackQuery().getData();
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean roleChecker(Update update, List<Role> expectedRoles) {
|
|
||||||
User user = getUser(update);
|
|
||||||
return expectedRoles.contains(user.getRole());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -0,0 +1,17 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.utils;
|
||||||
|
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshServer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public class SshServerUtils {
|
||||||
|
public static List<SshServer> filterGoodServers(List<SshServer> sshServers) {
|
||||||
|
List<SshServer> goodSshServers = sshServers.stream()
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.filter(server -> Objects.nonNull(server.getSession()))
|
||||||
|
.filter(server -> server.getSession().isConnected())
|
||||||
|
.toList();
|
||||||
|
return goodSshServers;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,40 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.utils.ui;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
|
||||||
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton;
|
||||||
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class TelegramBotKeyboard implements UiFormer {
|
||||||
|
private final String STATUS = "Статус";
|
||||||
|
private final String UNAME = "uname";
|
||||||
|
private final String CPU_TEMP = "CPU.temp";
|
||||||
|
private final String HDD_TEMP = "HDD.temp";
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage uiForm(SendMessage message) {
|
||||||
|
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
|
||||||
|
replyKeyboardMarkup.setResizeKeyboard(true);
|
||||||
|
replyKeyboardMarkup.setOneTimeKeyboard(false);
|
||||||
|
|
||||||
|
ArrayList<KeyboardRow> keyboardRows = new ArrayList<>();
|
||||||
|
|
||||||
|
KeyboardRow keyboardRow = new KeyboardRow();
|
||||||
|
keyboardRows.add(keyboardRow);
|
||||||
|
|
||||||
|
keyboardRow.add(new KeyboardButton(STATUS));
|
||||||
|
keyboardRow.add(new KeyboardButton(UNAME));
|
||||||
|
keyboardRow.add(new KeyboardButton(CPU_TEMP));
|
||||||
|
keyboardRow.add(new KeyboardButton(HDD_TEMP));
|
||||||
|
|
||||||
|
replyKeyboardMarkup.setKeyboard(keyboardRows);
|
||||||
|
message.setReplyMarkup(replyKeyboardMarkup);
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package ru.ldeloff.servermonitorbot.view;
|
package ru.ldeloff.servermonitorbot.utils.ui;
|
||||||
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
|
|
@ -1,11 +1,12 @@
|
||||||
package ru.ldeloff.servermonitorbot.view;
|
package ru.ldeloff.servermonitorbot.utils.ui.uname;
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
||||||
|
import ru.ldeloff.servermonitorbot.utils.ui.UiFormer;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
@ -20,9 +21,10 @@ public class ServerListButtons implements UiFormer {
|
||||||
@Override
|
@Override
|
||||||
public SendMessage uiForm(SendMessage message) {
|
public SendMessage uiForm(SendMessage message) {
|
||||||
List<List<InlineKeyboardButton>> keyboard = new ArrayList<>();
|
List<List<InlineKeyboardButton>> keyboard = new ArrayList<>();
|
||||||
|
|
||||||
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
|
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
|
||||||
|
|
||||||
sshService.getAllSshServers().forEach(sshServer -> {
|
sshService.getSshServers().forEach(sshServer -> {
|
||||||
if (Objects.nonNull(sshServer.getSession())) {
|
if (Objects.nonNull(sshServer.getSession())) {
|
||||||
if (sshServer.getSession().isConnected()) {
|
if (sshServer.getSession().isConnected()) {
|
||||||
List<InlineKeyboardButton> keyboardRow = new ArrayList<>();
|
List<InlineKeyboardButton> keyboardRow = new ArrayList<>();
|
|
@ -1,33 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.view;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
|
||||||
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class FirstUseCommand extends CommandTemplate {
|
|
||||||
|
|
||||||
private final TelegramBotKeyboard telegramBotKeyboard;
|
|
||||||
|
|
||||||
public FirstUseCommand(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, TelegramBotKeyboard telegramBotKeyboard, MessagingService messagingService) {
|
|
||||||
super(updateUtil, serverListButtons, sshService, messagingService);
|
|
||||||
this.telegramBotKeyboard = telegramBotKeyboard;
|
|
||||||
setName("/start");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public SendMessage executeAggregate(User user, SendMessage message) {
|
|
||||||
message.setText("Добро пожаловать " + user.getLogin() + "!");
|
|
||||||
return telegramBotKeyboard.uiForm(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,37 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.view;
|
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
|
||||||
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.SshService;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Slf4j
|
|
||||||
public class SwitchToMainMenu extends CommandTemplate {
|
|
||||||
|
|
||||||
private final TelegramBotKeyboard telegramBotKeyboard;
|
|
||||||
|
|
||||||
public SwitchToMainMenu(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, TelegramBotKeyboard telegramBotKeyboard, MessagingService messagingService) {
|
|
||||||
super(updateUtil, serverListButtons, sshService, messagingService);
|
|
||||||
this.telegramBotKeyboard = telegramBotKeyboard;
|
|
||||||
setName("Not found");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public SendMessage executeAggregate(User user, SendMessage message) {
|
|
||||||
SendMessage answer = new SendMessage();
|
|
||||||
answer.setChatId(user.getTelegramId());
|
|
||||||
answer.setText("Неверная команда. Попробуем сначала.");
|
|
||||||
return telegramBotKeyboard.uiForm(answer);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,70 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.view;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.context.ApplicationContext;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
|
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton;
|
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.Role;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.user.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
|
||||||
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import static ru.ldeloff.servermonitorbot.model.user.Role.ADMIN;
|
|
||||||
import static ru.ldeloff.servermonitorbot.model.user.Role.USER;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class TelegramBotKeyboard implements UiFormer {
|
|
||||||
|
|
||||||
private final UserService userService;
|
|
||||||
private final ApplicationContext applicationContext;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public SendMessage uiForm(SendMessage message) {
|
|
||||||
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
|
|
||||||
replyKeyboardMarkup.setResizeKeyboard(true);
|
|
||||||
replyKeyboardMarkup.setOneTimeKeyboard(false);
|
|
||||||
|
|
||||||
String chatId = message.getChatId();
|
|
||||||
User user = userService.getByTelegramId(Long.parseLong(chatId));
|
|
||||||
|
|
||||||
ArrayList<KeyboardRow> keyboardRows = formKeyboard(user);
|
|
||||||
replyKeyboardMarkup.setKeyboard(keyboardRows);
|
|
||||||
message.setReplyMarkup(replyKeyboardMarkup);
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ArrayList<KeyboardRow> formKeyboard(User user) {
|
|
||||||
Role role = user.getRole();
|
|
||||||
Map<String, CommandTemplate> commands = applicationContext.getBeansOfType(CommandTemplate.class);
|
|
||||||
commands.remove("firstUseCommand");
|
|
||||||
commands.remove("switchToMainMenu");
|
|
||||||
|
|
||||||
int buttonOnLine = 3;
|
|
||||||
|
|
||||||
ArrayList<KeyboardRow> keyboardRows = new ArrayList<>();
|
|
||||||
KeyboardRow keyboardRow = new KeyboardRow();
|
|
||||||
|
|
||||||
for (Map.Entry<String, CommandTemplate> entry : commands.entrySet()) {
|
|
||||||
if (entry.getValue().getExpectedRole().contains(role)) {
|
|
||||||
keyboardRow.add(new KeyboardButton(entry.getValue().getName()));
|
|
||||||
}
|
|
||||||
if (keyboardRow.size()>=buttonOnLine) {
|
|
||||||
keyboardRows.add(keyboardRow);
|
|
||||||
keyboardRow = new KeyboardRow();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!keyboardRow.isEmpty()) {
|
|
||||||
keyboardRows.add(keyboardRow);
|
|
||||||
}
|
|
||||||
return keyboardRows;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,6 +1,15 @@
|
||||||
spring:
|
spring:
|
||||||
application:
|
application:
|
||||||
name: ServerMonitorBot
|
name: ServerMonitorBot
|
||||||
|
datasource:
|
||||||
|
url: jdbc:postgresql://db:5432/servermonitorbot
|
||||||
|
username: servermonitorbot
|
||||||
|
password: servermonitorbot
|
||||||
|
jpa:
|
||||||
|
hibernate:
|
||||||
|
ddl-auto: none
|
||||||
|
flyway:
|
||||||
|
locations: classpath:db/migration
|
||||||
bot:
|
bot:
|
||||||
name: "ServerMonitorBot"
|
name: "ServerMonitorBot"
|
||||||
token: "token"
|
token: "token"
|
||||||
|
@ -8,8 +17,6 @@ bot:
|
||||||
- telegramId: 123456789
|
- telegramId: 123456789
|
||||||
role: admin
|
role: admin
|
||||||
ssh:
|
ssh:
|
||||||
checkConnectionDelay: 300000
|
|
||||||
timeout: 5000
|
|
||||||
servers:
|
servers:
|
||||||
-
|
-
|
||||||
name: "Server Name"
|
name: "Server Name"
|
||||||
|
@ -17,12 +24,6 @@ ssh:
|
||||||
port: 22
|
port: 22
|
||||||
user: "user"
|
user: "user"
|
||||||
password: "pass"
|
password: "pass"
|
||||||
-
|
|
||||||
name: "Server Name 2"
|
|
||||||
host: "url 2"
|
|
||||||
port: 22
|
|
||||||
user: "user 2"
|
|
||||||
password: "pass 2"
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,15 @@
|
||||||
|
--changeset L_DelOff:create_table_users rollbackSplitStatements:true
|
||||||
|
--comment: Создание таблицы пользователей
|
||||||
|
CREATE TABLE users
|
||||||
|
(
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
login VARCHAR(128),
|
||||||
|
id_role integer
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE users IS 'Пользователи';
|
||||||
|
COMMENT ON COLUMN users.id IS 'Идентификатор пользователя';
|
||||||
|
COMMENT ON COLUMN users.login IS 'Логин пользователя';
|
||||||
|
COMMENT ON COLUMN users.id_role IS 'Ссылка на роль пользователя';
|
||||||
|
|
||||||
|
--rollback DROP TABLE users;
|
|
@ -0,0 +1,13 @@
|
||||||
|
--changeset L_DelOff:create_table_roles rollbackSplitStatements:true
|
||||||
|
--comment: Создание таблицы ролей
|
||||||
|
CREATE TABLE roles
|
||||||
|
(
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
role VARCHAR(128)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE roles IS 'Пользователи';
|
||||||
|
COMMENT ON COLUMN roles.id IS 'Идентификатор пользователя';
|
||||||
|
COMMENT ON COLUMN roles.role IS 'Логин пользователя';
|
||||||
|
|
||||||
|
--rollback DROP TABLE roles;
|
|
@ -0,0 +1,2 @@
|
||||||
|
ALTER TABLE users
|
||||||
|
ADD COLUMN role_id INT NOT NULL REFERENCES roles(id);
|
|
@ -0,0 +1,2 @@
|
||||||
|
INSERT INTO roles (id, role) VALUES (1, 'ADMIN');
|
||||||
|
INSERT INTO roles (id, role) VALUES (2, 'USER');
|
|
@ -0,0 +1 @@
|
||||||
|
INSERT INTO roles (id, role) VALUES (3, 'ANONYMOUS');
|
|
@ -0,0 +1,9 @@
|
||||||
|
ALTER TABLE users
|
||||||
|
DROP COLUMN login;
|
||||||
|
|
||||||
|
ALTER TABLE users
|
||||||
|
ADD COLUMN telegram_id INTEGER UNIQUE;
|
||||||
|
COMMENT ON COLUMN users.telegram_id IS 'Telegram ID пользователя';
|
||||||
|
|
||||||
|
ALTER TABLE users
|
||||||
|
DROP COLUMN id_role;
|
|
@ -0,0 +1,6 @@
|
||||||
|
ALTER TABLE roles
|
||||||
|
DROP COLUMN role;
|
||||||
|
|
||||||
|
ALTER TABLE roles
|
||||||
|
ADD COLUMN name VARCHAR(128);
|
||||||
|
COMMENT ON COLUMN roles.name IS 'Имя роли';
|
|
@ -0,0 +1,4 @@
|
||||||
|
TRUNCATE TABLE roles CASCADE;
|
||||||
|
INSERT INTO roles (id, name) VALUES (1, 'ADMIN');
|
||||||
|
INSERT INTO roles (id, name) VALUES (2, 'USER');
|
||||||
|
INSERT INTO roles (id, name) VALUES (3, 'ANONYMOUS');
|
Loading…
Reference in New Issue