Обновление cpp-сервера
This commit is contained in:
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.16)
|
||||
cmake_policy(SET CMP0077 NEW)
|
||||
set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
|
||||
|
||||
# Проект Traffic Analysis. Названия CMake-таргетов имеют префикс "ta_" (первые буквы слов в названии проекта)
|
||||
# Проект Log Analysis. Названия CMake-таргетов имеют префикс "la_" (первые буквы слов в названии проекта)
|
||||
project(traffic_analysis)
|
||||
|
||||
# Указываем переменные
|
||||
@@ -18,3 +18,4 @@ add_subdirectory(controllers)
|
||||
add_subdirectory(json)
|
||||
add_subdirectory(server)
|
||||
add_subdirectory(storage)
|
||||
add_subdirectory(utils)
|
||||
|
||||
@@ -14,4 +14,5 @@ target_include_directories(${PROJECT_NAME} PUBLIC include)
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
la_json
|
||||
la_storage
|
||||
la_utils
|
||||
)
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace controllers::anomaly_logs::fields {
|
||||
/// @defgroup Поля запроса
|
||||
/// @{
|
||||
constexpr std::string_view last_index = "last_index";
|
||||
/// @}
|
||||
|
||||
/// @defgroup Поля ответа
|
||||
/// @{
|
||||
constexpr std::string_view id = "id";
|
||||
constexpr std::string_view class_id = "class_id";
|
||||
constexpr std::string_view data = "data";
|
||||
/// @}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace controllers::anomaly_logs::details {
|
||||
struct AnomalyLogRow {
|
||||
int64_t id;
|
||||
int64_t class_id;
|
||||
std::string data;
|
||||
};
|
||||
|
||||
std::vector<AnomalyLogRow> AnomalyLogsQuery(int64_t last_id);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
namespace fields::anomaly_logs {
|
||||
/// @defgroup Поля запроса anomaly_logs
|
||||
/// @{
|
||||
constexpr const char* last_index = "last_index";
|
||||
/// @}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
namespace controllers::anomaly_logs {
|
||||
/// @brief Контроллер для обработки запроса получения аномальных логов
|
||||
class Get : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit Get();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct AnomalyLogRow {
|
||||
int64_t index;
|
||||
std::string data;
|
||||
};
|
||||
|
||||
std::vector<AnomalyLogRow> AnomalyLogsQuery(int64_t last_index);
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
/// @brief Контроллер для обработки запроса получения аномальных логов
|
||||
class AnomalyLogsController : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit AnomalyLogsController();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
@@ -4,24 +4,32 @@
|
||||
|
||||
#include <json/json.h>
|
||||
|
||||
class ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
/// @param[in] name Название контроллера
|
||||
explicit ControllerBase(std::string name);
|
||||
namespace controllers {
|
||||
class ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
/// @param[in] resource Ресурс контроллера
|
||||
/// @param[in] operation Операция контроллера
|
||||
explicit ControllerBase(std::string resource, std::string operation);
|
||||
|
||||
/// @brief Деструктор
|
||||
virtual ~ControllerBase() = default;
|
||||
/// @brief Деструктор
|
||||
virtual ~ControllerBase() = default;
|
||||
|
||||
/// @brief Получение названия контроллера
|
||||
/// @returns Название контроллера
|
||||
[[nodiscard]] const std::string& Name() const;
|
||||
/// @brief Получение ресурса контроллера
|
||||
/// @returns Ресурс контроллера
|
||||
[[nodiscard]] const std::string& Resource() const;
|
||||
|
||||
/// @brief Вызов логики контроллера
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ контроллера
|
||||
virtual json operator()(const json& parameters) const = 0;
|
||||
/// @brief Получение Ресурса контроллера
|
||||
/// @returns Ресурс контроллера
|
||||
[[nodiscard]] const std::string& Operation() const;
|
||||
|
||||
protected:
|
||||
std::string name_; ///< Название контроллера
|
||||
};
|
||||
/// @brief Вызов логики контроллера
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ контроллера
|
||||
virtual json operator()(const json& parameters) const = 0;
|
||||
|
||||
protected:
|
||||
std::string resource_; ///< Ресурс контроллера
|
||||
std::string operation_; ///< Операция контроллера
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,37 +4,33 @@
|
||||
#include <unordered_map>
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
#include <controllers/fields.h>
|
||||
|
||||
/// @brief Диспетчер контроллеров. Отвечает за передачу запроса нужному контроллеру
|
||||
class Dispatcher {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
Dispatcher() = default;
|
||||
namespace controllers {
|
||||
/// @brief Диспетчер контроллеров. Отвечает за передачу запроса нужному контроллеру
|
||||
class Dispatcher {
|
||||
public:
|
||||
using Controllers = std::unordered_map<std::string, std::unique_ptr<ControllerBase>>;
|
||||
|
||||
/// @brief Конструктор
|
||||
Dispatcher() = default;
|
||||
|
||||
/// @brief Добавление контроллера
|
||||
/// @tparam Controller Тип контроллера
|
||||
template <typename Controller>
|
||||
void AddController();
|
||||
|
||||
/// @brief Получение контроллеров
|
||||
/// @returns Контроллеры
|
||||
const Controllers& GetControllers() const;
|
||||
|
||||
private:
|
||||
Controllers controllers_; ///< Контроллеры
|
||||
};
|
||||
|
||||
/// @brief Добавление контроллера
|
||||
/// @tparam Controller Тип контроллера
|
||||
template <typename Controller>
|
||||
void AddController();
|
||||
|
||||
/// @brief Обработка запроса
|
||||
/// @param[in] request Тело запроса
|
||||
/// @returns Тело ответа
|
||||
std::string operator()(const char* request) const;
|
||||
|
||||
private:
|
||||
/// @brief Реализация обработки запроса
|
||||
/// @param[in] request Тело запроса
|
||||
/// @returns Тело ответа
|
||||
json CallImpl(const char* request, std::string& command) const;
|
||||
|
||||
private:
|
||||
std::unordered_map<std::string, std::unique_ptr<ControllerBase>> controllers_; ///< Контроллеры
|
||||
};
|
||||
|
||||
template <typename Controller>
|
||||
void Dispatcher::AddController() {
|
||||
auto controller = std::make_unique<Controller>();
|
||||
auto name = controller->Name();
|
||||
controllers_.insert({ std::move(name), std::move(controller) });
|
||||
void Dispatcher::AddController() {
|
||||
auto controller = std::make_unique<Controller>();
|
||||
std::string path = '/' + controller->Resource() + '/' + controller->Operation();
|
||||
controllers_.insert({ std::move(path), std::move(controller) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/// @brief Поля запроса
|
||||
namespace fields::request {
|
||||
static const char* command = "command"; ///< Название команды / Название контроллера
|
||||
static const char* parameters = "parameters"; ///< Параметры
|
||||
}
|
||||
|
||||
/// @brief Поля ответа
|
||||
namespace fields::response {
|
||||
static const char* command = "command"; ///< Название команды / Название контроллера
|
||||
static const char* status = "status"; ///< Статус ответа (ok/error)
|
||||
static const char* result = "result"; ///< Результат (в случае статуса ok)
|
||||
static const char* error_message = "error_message"; ///< Сообщение об ошибке (в случае статуса error)
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <json/json.h>
|
||||
|
||||
/// @brief Парсинг строки в json
|
||||
/// @param[in] data Строка
|
||||
/// @throws std::runtime_error В случае ошибки парсинга (например, некорректный формат)
|
||||
/// @returns json
|
||||
json ParseJson(const char* data);
|
||||
|
||||
/// @brief Проверка наличия необходимых ключей
|
||||
/// @param[in] json Объект, который надо проверить
|
||||
/// @param[in] fields Необходимые ключи
|
||||
/// @throws std::runtime_error В случае отсутствия хотя бы одного ключа
|
||||
void CheckForRequiredFields(const json& json, std::initializer_list<std::string_view> fields);
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace controllers::logs_classes::fields {
|
||||
/// @defgroup Поля ответа
|
||||
/// @{
|
||||
constexpr std::string_view id = "id";
|
||||
constexpr std::string_view name = "name";
|
||||
constexpr std::string_view description = "description";
|
||||
/// @}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace controllers::logs_classes::details {
|
||||
struct LogsClassesRow {
|
||||
int64_t id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
};
|
||||
|
||||
std::vector<LogsClassesRow> LogsClassesQuery();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
namespace controllers::logs_classes {
|
||||
/// @brief Контроллер для обработки запроса получения классов логов
|
||||
class Get : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit Get();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
namespace controllers::logs_classes {
|
||||
/// @brief Контроллер для обработки запроса обновления класса логов
|
||||
class Put : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit Put();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace controllers::statistics::details {
|
||||
struct StatisticsRow {
|
||||
std::string name;
|
||||
size_t value;
|
||||
};
|
||||
|
||||
std::vector<StatisticsRow> StatisticsQuery();
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
namespace fields::statistics {
|
||||
/// @defgroup Поля запроса statistics
|
||||
/// @{
|
||||
constexpr const char* table = "table";
|
||||
constexpr const char* date = "date";
|
||||
/// @}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
namespace controllers::statistics {
|
||||
/// @brief Контроллер для обработки запроса статистики
|
||||
class Get : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit Get();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
|
||||
/// @brief Алиас для набора данных. Ключ является типом транспорта,
|
||||
/// значение -- массив из 24 чисел, представляющих количество учтённых транспортных средств для каждого часа
|
||||
using Datasets = std::unordered_map<std::string, std::vector<uint16_t>>;
|
||||
|
||||
/// @brief Получение наборов данных из хранилища
|
||||
/// @param[in] table Название таблицы
|
||||
/// @param[in] date Дата
|
||||
/// @returns Наборы данных
|
||||
Datasets GetDatasets(std::string_view table, std::string_view date);
|
||||
|
||||
/// @brief Получение процентного отношения каждого типа
|
||||
/// @param[in] datasets Наборы данных
|
||||
/// @param[in] hour Номер часа
|
||||
/// @returns Процентное отношение
|
||||
std::unordered_map<std::string, double> GetTypesPercentage(const Datasets& datasets, size_t hour);
|
||||
|
||||
/// @brief Распределить количество учтённых транспортных средств указаного типа пропорционально к остальным типам
|
||||
/// @param[in, out] datasets Наборы данных
|
||||
/// @param[in] type_to_distribute Тип, который нужно распределить
|
||||
/// @param[in] stock_type Тип, которому уйдёт излишек из-за неточности при работе с вещественными числами
|
||||
void DistributeType(Datasets& datasets, const std::string& type_to_distribute, const std::string& stock_type);
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct StatisticsRow {
|
||||
std::string name;
|
||||
size_t value;
|
||||
};
|
||||
|
||||
std::vector<StatisticsRow> StatisticsQuery();
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
/// @brief Контроллер для обработки запроса статистики
|
||||
class StatisticsController : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit StatisticsController();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/anomaly_logs/details/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
namespace controllers::anomaly_logs::details {
|
||||
std::vector<AnomalyLogRow> AnomalyLogsQuery(int64_t last_id) {
|
||||
std::ostringstream query;
|
||||
query << "select id, class_id, data from anomaly_logs where id > " << last_id << ";";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<AnomalyLogRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
AnomalyLogRow anomaly_log_row{
|
||||
row[0].as<int64_t>(),
|
||||
row[1].as<int64_t>(),
|
||||
row[2].as<std::string>(),
|
||||
};
|
||||
|
||||
result.push_back(std::move(anomaly_log_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <controllers/anomaly_logs/get.h>
|
||||
#include <controllers/anomaly_logs/details/fields.h>
|
||||
#include <controllers/anomaly_logs/details/query.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
using namespace controllers::anomaly_logs;
|
||||
|
||||
Get::Get() : ControllerBase("anomaly_logs", "get") {}
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
utils::CheckForRequiredFields(parameters, { fields::last_index });
|
||||
|
||||
auto last_index = parameters[fields::last_index].get<int64_t>();
|
||||
|
||||
auto rows = details::AnomalyLogsQuery(last_index);
|
||||
|
||||
json result = json::array();
|
||||
for (auto& row : rows) {
|
||||
json item = json::object();
|
||||
item[fields::id] = row.id;
|
||||
item[fields::class_id] = row.class_id;
|
||||
item[fields::data] = std::move(row.data);
|
||||
|
||||
result.push_back(std::move(item));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/anomaly_logs/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
std::vector<AnomalyLogRow> AnomalyLogsQuery(int64_t last_index) {
|
||||
std::ostringstream query;
|
||||
query << "select id, data from anomaly_logs where id > " << last_index << ";";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<AnomalyLogRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
AnomalyLogRow anomaly_log_row{ row[0].as<int64_t>(), row[1].as<std::string>() };
|
||||
result.push_back(std::move(anomaly_log_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
#include <controllers/implementation.h>
|
||||
#include <controllers/anomaly_logs_controller.h>
|
||||
#include <controllers/anomaly_logs/fields.h>
|
||||
#include <controllers/anomaly_logs/query.h>
|
||||
|
||||
AnomalyLogsController::AnomalyLogsController() : ControllerBase("anomaly_logs") {}
|
||||
|
||||
json AnomalyLogsController::operator()(const json& parameters) const {
|
||||
CheckForRequiredFields(parameters, { fields::anomaly_logs::last_index });
|
||||
|
||||
auto last_index = parameters[fields::anomaly_logs::last_index].get<int64_t>();
|
||||
|
||||
auto rows = AnomalyLogsQuery(last_index);
|
||||
|
||||
json result = json::object();
|
||||
for (const auto& row : rows) {
|
||||
result[std::to_string(row.index)] = row.data;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,7 +1,16 @@
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
ControllerBase::ControllerBase(std::string name) : name_(std::move(name)) {}
|
||||
using namespace controllers;
|
||||
|
||||
const std::string& ControllerBase::Name() const {
|
||||
return name_;
|
||||
ControllerBase::ControllerBase(std::string resource, std::string operation)
|
||||
: resource_(std::move(resource))
|
||||
, operation_(std::move(operation))
|
||||
{}
|
||||
|
||||
const std::string& ControllerBase::Resource() const {
|
||||
return resource_;
|
||||
}
|
||||
|
||||
const std::string& ControllerBase::Operation() const {
|
||||
return operation_;
|
||||
}
|
||||
|
||||
@@ -1,52 +1,7 @@
|
||||
#include <controllers/dispatcher.h>
|
||||
#include <controllers/implementation.h>
|
||||
|
||||
std::string Dispatcher::operator()(const char* request) const {
|
||||
// todo: формирование успешного и ошибочного ответов
|
||||
using namespace controllers;
|
||||
|
||||
std::string command;
|
||||
json result;
|
||||
try {
|
||||
result = CallImpl(request, command);
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
json json;
|
||||
json[fields::response::command] = command;
|
||||
json[fields::response::status] = "error";
|
||||
json[fields::response::error_message] = e.what();
|
||||
|
||||
result = json.dump();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
json json;
|
||||
json[fields::response::command] = command;
|
||||
json[fields::response::status] = "ok";
|
||||
json[fields::response::result] = result;
|
||||
|
||||
result = json.dump();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
json Dispatcher::CallImpl(const char* request, std::string& command) const {
|
||||
// Проверяем корректность формата запроса
|
||||
auto json = ParseJson(request);
|
||||
|
||||
// Проверяем наличие необходимых ключей
|
||||
CheckForRequiredFields(json, { fields::request::command, fields::request::parameters });
|
||||
|
||||
// Проверяем наличие команды с указанным именем
|
||||
command = json[fields::request::command].get<std::string>();
|
||||
if (!controllers_.count(command)) {
|
||||
return "unknown command '" + command + "'";
|
||||
}
|
||||
|
||||
// Получаем команду по имени
|
||||
const auto& controller = *controllers_.at(command);
|
||||
|
||||
// Формируем и возвращаем ответ
|
||||
auto parameters = json[fields::request::parameters];
|
||||
return controller(parameters);
|
||||
const Dispatcher::Controllers& Dispatcher::GetControllers() const {
|
||||
return controllers_;
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <controllers/implementation.h>
|
||||
|
||||
json ParseJson(const char* data) {
|
||||
json json;
|
||||
try {
|
||||
json = json::parse(data);
|
||||
} catch (const std::exception& e) {
|
||||
throw std::runtime_error("failed to parse request");
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
void CheckForRequiredFields(const json& json, std::initializer_list<std::string_view> fields) {
|
||||
for (const auto& field : fields)
|
||||
if (!json.contains(field)) {
|
||||
std::ostringstream message;
|
||||
message << "request doesn't contain required field '" << field << "'";
|
||||
throw std::runtime_error(message.str());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/logs_classes/details/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
namespace controllers::logs_classes::details {
|
||||
std::vector<LogsClassesRow> LogsClassesQuery() {
|
||||
std::ostringstream query;
|
||||
query << "select id, name, description from logs_classes;";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<LogsClassesRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
LogsClassesRow logs_classes_row{
|
||||
row[0].as<int64_t>(),
|
||||
row[1].as<std::string>(),
|
||||
row[2].as<std::string>(),
|
||||
};
|
||||
|
||||
result.push_back(std::move(logs_classes_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#include <controllers/logs_classes/get.h>
|
||||
#include <controllers/logs_classes/details/fields.h>
|
||||
#include <controllers/logs_classes/details/query.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
using namespace controllers::logs_classes;
|
||||
|
||||
Get::Get() : ControllerBase("logs_classes", "put") {}
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
utils::CheckForRequiredFields(parameters, { fields::id, fields::description });
|
||||
|
||||
|
||||
details::LogsClassesQuery();
|
||||
|
||||
json result = json::array();
|
||||
for (auto& row : rows) {
|
||||
json item = json::object();
|
||||
item[fields::id] = row.id;
|
||||
item[fields::name] = std::move(row.name);
|
||||
item[fields::description] = std::move(row.description);
|
||||
|
||||
result.push_back(std::move(item));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#include <controllers/logs_classes/put.h>
|
||||
#include <controllers/logs_classes/details/fields.h>
|
||||
#include <controllers/logs_classes/details/query.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
using namespace controllers::logs_classes;
|
||||
|
||||
Get::Get() : ControllerBase("logs_classes", "get") {}
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
auto rows = details::LogsClassesQuery();
|
||||
|
||||
json result = json::array();
|
||||
for (auto& row : rows) {
|
||||
json item = json::object();
|
||||
item[fields::id] = row.id;
|
||||
item[fields::name] = std::move(row.name);
|
||||
item[fields::description] = std::move(row.description);
|
||||
|
||||
result.push_back(std::move(item));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/statistics/details/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
namespace controllers::statistics::details {
|
||||
std::vector<StatisticsRow> StatisticsQuery() {
|
||||
std::ostringstream query;
|
||||
query << "select name, value from statistics;";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<StatisticsRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
StatisticsRow statistics_row{ row[0].as<std::string>(), row[1].as<size_t>() };
|
||||
result.push_back(std::move(statistics_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#include <controllers/statistics/get.h>
|
||||
#include <controllers/statistics/details/query.h>
|
||||
|
||||
using namespace controllers::statistics;
|
||||
|
||||
Get::Get() : ControllerBase("statistics", "get") {}
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
auto rows = details::StatisticsQuery();
|
||||
|
||||
json result;
|
||||
for (auto& row : rows) {
|
||||
result[std::move(row.name)] = row.value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/statistics/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
std::vector<StatisticsRow> StatisticsQuery() {
|
||||
std::ostringstream query;
|
||||
query << "select name, value from statistics;";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<StatisticsRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
StatisticsRow statistics_row{ row[0].as<std::string>(), row[1].as<size_t>() };
|
||||
result.push_back(std::move(statistics_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
#include <controllers/implementation.h>
|
||||
#include <controllers/statistics_controller.h>
|
||||
#include <controllers/statistics/query.h>
|
||||
|
||||
StatisticsController::StatisticsController() : ControllerBase("statistics") {}
|
||||
|
||||
json StatisticsController::operator()(const json& parameters) const {
|
||||
auto rows = StatisticsQuery();
|
||||
|
||||
json result;
|
||||
for (const auto& row : rows) {
|
||||
result[row.name] = row.value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#include <string>
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
namespace server::details {
|
||||
class ControllerInvoker {
|
||||
public:
|
||||
explicit ControllerInvoker(const controllers::ControllerBase* controller);
|
||||
|
||||
std::string operator()(const char* request) const;
|
||||
private:
|
||||
const controllers::ControllerBase* controller_;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#include <controllers/dispatcher.h>
|
||||
|
||||
namespace server::details {
|
||||
/// @brief Парсинг строки в json
|
||||
/// @param[in] data Строка
|
||||
/// @throws std::runtime_error В случае ошибки парсинга (например, некорректный формат)
|
||||
/// @returns json
|
||||
json ParseJson(const char* data);
|
||||
|
||||
controllers::Dispatcher CreateDispatcher();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
|
||||
/// @brief Поля запроса
|
||||
namespace server::details::fields::request {
|
||||
constexpr std::string_view command = "command"; ///< Название команды / Название контроллера
|
||||
constexpr std::string_view parameters = "parameters"; ///< Параметры
|
||||
}
|
||||
|
||||
/// @brief Поля ответа
|
||||
namespace server::details::fields::response {
|
||||
constexpr std::string_view command = "command"; ///< Название команды / Название контроллера
|
||||
constexpr std::string_view status = "status"; ///< Статус ответа (ok/error)
|
||||
constexpr std::string_view result = "result"; ///< Результат (в случае статуса ok)
|
||||
constexpr std::string_view error_message = "error_message"; ///< Сообщение об ошибке (в случае статуса error)
|
||||
}
|
||||
@@ -1,12 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include <controllers/dispatcher.h>
|
||||
|
||||
namespace seasocks {
|
||||
class Server;
|
||||
}
|
||||
|
||||
class WebSocketServer {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
/// @param[in] dispatcher Диспетчер контроллеров
|
||||
explicit WebSocketServer(Dispatcher&& dispatcher);
|
||||
explicit WebSocketServer(const controllers::Dispatcher& dispatcher);
|
||||
|
||||
~WebSocketServer();
|
||||
|
||||
/// @brief Начать обслуживание запросов
|
||||
/// @param[in] path Директория со статическими ресурсами
|
||||
@@ -14,5 +23,5 @@ public:
|
||||
void Serve(const std::string& path, int port);
|
||||
|
||||
protected:
|
||||
Dispatcher dispatcher_; ///< Диспетчер контроллеров
|
||||
};
|
||||
std::unique_ptr<seasocks::Server> server_; ///< Сервер
|
||||
};
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
#include <seasocks/WebSocket.h>
|
||||
|
||||
#include <controllers/dispatcher.h>
|
||||
#include <server/details/controller_invoker.h>
|
||||
|
||||
class AnalysisWebSocketHandler : public seasocks::WebSocket::Handler {
|
||||
public:
|
||||
explicit AnalysisWebSocketHandler(const Dispatcher& dispatcher);
|
||||
explicit AnalysisWebSocketHandler(const controllers::ControllerBase* controller);
|
||||
|
||||
void onConnect(seasocks::WebSocket* socket) override;
|
||||
|
||||
@@ -15,5 +15,5 @@ public:
|
||||
void onDisconnect(seasocks::WebSocket* socket) override;
|
||||
|
||||
private:
|
||||
const Dispatcher& dispatcher_;
|
||||
server::details::ControllerInvoker controller_invoker_;
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
#include <server/details/controller_invoker.h>
|
||||
#include <server/details/details.h>
|
||||
#include <server/details/fields.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
using namespace server::details;
|
||||
|
||||
namespace {
|
||||
json CallImpl(const controllers::ControllerBase& controller, const char* request, std::string& command) {
|
||||
// Проверяем корректность формата запроса
|
||||
auto json = ParseJson(request);
|
||||
|
||||
// Проверяем наличие необходимых ключей
|
||||
utils::CheckForRequiredFields(json, { fields::request::parameters });
|
||||
|
||||
// Формируем и возвращаем ответ
|
||||
auto parameters = json[fields::request::parameters];
|
||||
return controller(parameters);
|
||||
}
|
||||
}
|
||||
|
||||
ControllerInvoker::ControllerInvoker(const controllers::ControllerBase* controller) : controller_(controller) {}
|
||||
|
||||
std::string ControllerInvoker::operator()(const char* request) const {
|
||||
std::string command;
|
||||
json result;
|
||||
try {
|
||||
result = CallImpl(*controller_, request, command);
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
json json;
|
||||
json[fields::response::command] = command;
|
||||
json[fields::response::status] = "error";
|
||||
json[fields::response::error_message] = e.what();
|
||||
|
||||
result = json.dump();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
json json;
|
||||
json[fields::response::command] = command;
|
||||
json[fields::response::status] = "ok";
|
||||
json[fields::response::result] = result;
|
||||
|
||||
result = json.dump();
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <controllers/anomaly_logs/get.h>
|
||||
#include <controllers/logs_classes/get.h>
|
||||
#include <controllers/statistics/get.h>
|
||||
#include <server/details/details.h>
|
||||
|
||||
namespace server::details {
|
||||
json ParseJson(const char* data) {
|
||||
json json;
|
||||
try {
|
||||
json = json::parse(data);
|
||||
} catch (const std::exception& e) {
|
||||
throw std::runtime_error("failed to parse request");
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
controllers::Dispatcher CreateDispatcher() {
|
||||
using namespace controllers;
|
||||
|
||||
Dispatcher result;
|
||||
result.AddController<anomaly_logs::Get>();
|
||||
result.AddController<logs_classes::Get>();
|
||||
result.AddController<statistics::Get>();
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
#include <iostream>
|
||||
|
||||
#include <configuration/configuration.h>
|
||||
#include <controllers/dispatcher.h>
|
||||
#include <controllers/anomaly_logs_controller.h>
|
||||
#include <controllers/statistics_controller.h>
|
||||
#include <json/json.h>
|
||||
#include <server/logger.h>
|
||||
#include <server/server.h>
|
||||
#include <server/details/details.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
void Log(LogLevel level, const char* message) {
|
||||
@@ -30,7 +28,7 @@ void ConnectToStorage(const json& configuration) {
|
||||
Logger::Get().Write(LogLevel::Info, "connected to postgresql");
|
||||
}
|
||||
|
||||
json ParseConfiguration2(const std::string& path_to_configuration) {
|
||||
json ParseConfiguration(const std::string& path_to_configuration) {
|
||||
json required_keys;
|
||||
required_keys["server"] = { "path", "port" };
|
||||
required_keys["storage"] = { "database", "username", "password", "host", "port" };
|
||||
@@ -46,7 +44,7 @@ int main(int argc, char** argv) {
|
||||
|
||||
try {
|
||||
// Парсим конфигурационный файл
|
||||
auto configuration = ParseConfiguration2(argv[1]);
|
||||
auto configuration = ParseConfiguration(argv[1]);
|
||||
|
||||
// Настраиваем логирование
|
||||
Logger::Get().SetSettings(LogLevel::Info, Log);
|
||||
@@ -54,13 +52,11 @@ int main(int argc, char** argv) {
|
||||
// Подключаемся к базе данных
|
||||
ConnectToStorage(configuration);
|
||||
|
||||
// Создаём и заполняем диспетчер контроллеров
|
||||
Dispatcher dispatcher;
|
||||
dispatcher.AddController<AnomalyLogsController>();
|
||||
dispatcher.AddController<StatisticsController>();
|
||||
// Создаём диспетчер контроллеров
|
||||
controllers::Dispatcher dispatcher = server::details::CreateDispatcher();
|
||||
|
||||
// Создаём и запускаем сервер
|
||||
WebSocketServer server(std::move(dispatcher));
|
||||
WebSocketServer server(dispatcher);
|
||||
|
||||
const std::string path = configuration["server"]["path"].get<std::string>();
|
||||
const int port = configuration["server"]["port"].get<int>();
|
||||
|
||||
@@ -6,13 +6,16 @@
|
||||
#include <server/websockets_handler.h>
|
||||
#include <server/websockets_logger.h>
|
||||
|
||||
WebSocketServer::WebSocketServer(Dispatcher&& dispatcher) : dispatcher_(std::move(dispatcher)) {}
|
||||
WebSocketServer::WebSocketServer(const controllers::Dispatcher& dispatcher) : server_(std::make_unique<seasocks::Server>(std::make_shared<WebSocketsLogger>())) {
|
||||
for (const auto& [path, controller] : dispatcher.GetControllers()) {
|
||||
server_->addWebSocketHandler(path.c_str(), std::make_shared<AnalysisWebSocketHandler>(controller.get()));
|
||||
}
|
||||
|
||||
server_->addPageHandler(std::make_shared<seasocks::RootPageHandler>());
|
||||
}
|
||||
|
||||
WebSocketServer::~WebSocketServer() = default;
|
||||
|
||||
void WebSocketServer::Serve(const std::string& path, int port) {
|
||||
auto logger = std::make_shared<WebSocketsLogger>();
|
||||
|
||||
seasocks::Server server(logger);
|
||||
server.addPageHandler(std::make_shared<seasocks::RootPageHandler>());
|
||||
server.addWebSocketHandler("/", std::make_shared<AnalysisWebSocketHandler>(dispatcher_));
|
||||
server.serve(path.c_str(), port);
|
||||
server_->serve(path.c_str(), port);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#include <server/logger.h>
|
||||
#include <server/websockets_handler.h>
|
||||
|
||||
AnalysisWebSocketHandler::AnalysisWebSocketHandler(const Dispatcher& dispatcher) : dispatcher_(dispatcher) {}
|
||||
AnalysisWebSocketHandler::AnalysisWebSocketHandler(const controllers::ControllerBase* controller) : controller_invoker_(controller) {}
|
||||
|
||||
void AnalysisWebSocketHandler::onConnect(seasocks::WebSocket* socket) {
|
||||
Logger::Get().Write(LogLevel::Info, "new client connected");
|
||||
@@ -11,7 +11,7 @@ void AnalysisWebSocketHandler::onConnect(seasocks::WebSocket* socket) {
|
||||
|
||||
void AnalysisWebSocketHandler::onData(seasocks::WebSocket* socket, const char* data) {
|
||||
try {
|
||||
auto response = dispatcher_(data);
|
||||
auto response = controller_invoker_(data);
|
||||
socket->send(response.c_str());
|
||||
} catch (const std::exception& e) {
|
||||
std::ostringstream message;
|
||||
@@ -22,6 +22,4 @@ void AnalysisWebSocketHandler::onData(seasocks::WebSocket* socket, const char* d
|
||||
}
|
||||
}
|
||||
|
||||
void AnalysisWebSocketHandler::onDisconnect(seasocks::WebSocket* socket) {
|
||||
|
||||
}
|
||||
void AnalysisWebSocketHandler::onDisconnect(seasocks::WebSocket* socket) {}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
create database log_analysis;
|
||||
|
||||
create table statistics(
|
||||
name varchar(64),
|
||||
value int,
|
||||
primary key (name)
|
||||
);
|
||||
|
||||
insert into statistics (name, value) values ('total', 0), ('anomaly', 0), ('not anomaly', 0), ('undefined', 0);
|
||||
|
||||
create table logs_classes(
|
||||
id serial,
|
||||
name text,
|
||||
description text,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
insert into logs_classes (name, description) values ('unknown', '');
|
||||
|
||||
create table anomaly_logs(
|
||||
id serial,
|
||||
class_id int references logs_classes(id),
|
||||
data text,
|
||||
primary key (id)
|
||||
);
|
||||
@@ -0,0 +1,11 @@
|
||||
project(la_utils)
|
||||
|
||||
file(GLOB_RECURSE SOURCES src/*.cpp)
|
||||
|
||||
add_library(${PROJECT_NAME})
|
||||
|
||||
target_sources(${PROJECT_NAME} PRIVATE ${SOURCES})
|
||||
|
||||
target_include_directories(${PROJECT_NAME} PUBLIC include PRIVATE ${THIRD_PARTY_DIR}/include)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME} PUBLIC la_json)
|
||||
@@ -0,0 +1,12 @@
|
||||
#include <string_view>
|
||||
#include <initializer_list>
|
||||
|
||||
#include <json/json.h>
|
||||
|
||||
namespace utils {
|
||||
/// @brief Проверка наличия необходимых ключей
|
||||
/// @param[in] json Объект, который надо проверить
|
||||
/// @param[in] fields Необходимые ключи
|
||||
/// @throws std::runtime_error В случае отсутствия хотя бы одного ключа
|
||||
void CheckForRequiredFields(const json& json, std::initializer_list<std::string_view> fields);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <utils/utils.h>
|
||||
|
||||
namespace utils {
|
||||
void CheckForRequiredFields(const json& json, std::initializer_list<std::string_view> fields) {
|
||||
for (const auto& field : fields)
|
||||
if (!json.contains(field)) {
|
||||
std::ostringstream message;
|
||||
message << "request doesn't contain required field '" << field << "'";
|
||||
throw std::runtime_error(message.str());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user