Move logger to file and adjust path string in publish contoller

This commit is contained in:
Hepatica
2024-08-11 01:59:54 +02:00
parent 4e94641571
commit 1f3086c96c
5 changed files with 204 additions and 127 deletions

View File

@@ -10,6 +10,7 @@ add_executable(SpCloudMain
"Service/AuthorizationService.cpp" "Service/AuthorizationService.cpp"
"Service/FileProcessingService.cpp" "Service/FileProcessingService.cpp"
"Service/CommandService.cpp" "Service/CommandService.cpp"
"Service/Logger.cpp"
) )
if (CMAKE_VERSION VERSION_GREATER 3.12) if (CMAKE_VERSION VERSION_GREATER 3.12)

View File

@@ -14,9 +14,8 @@ private:
FileProcessingService file_processing; FileProcessingService file_processing;
//std::string publish_app_path = "/mnt/c/Users/Danil/SpCloudApp";//Todo change to linux path std::string publish_app_path = "/mnt/c/Users/Danil/SpCloudApp";
//std::string publish_app_path = "/home/danilt2000/SpCloudMain/SpCloudApp";//Todo change to linux path //std::string publish_app_path = "/home/danilt2000/SpCloud/";
std::string publish_app_path = "/home/danilt2000/SpCloud/";//Todo change to linux path
//std::string publish_app_path = "C:/Temps/";// Todo delete if not needed //std::string publish_app_path = "C:/Temps/";// Todo delete if not needed
public: public:
@@ -33,66 +32,68 @@ public:
}); });
} }
private: private:
void process_publish(const httplib::Request& req, httplib::Response& res) void process_publish(const httplib::Request& req, httplib::Response& res)
{
if (this->authorization.is_user_authorized())
{ {
if (this->authorization.is_user_authorized()) const auto& content = req.files.begin()->second.content;
{
const auto& content = req.files.begin()->second.content;
const auto& filename = this->publish_app_path + req.files.begin()->second.filename; const auto& filename = this->publish_app_path + req.files.begin()->second.filename;
if (filename.size() >= 4 && filename.substr(filename.size() - 4) == ".rar") { if (filename.size() >= 4 && filename.substr(filename.size() - 4) == ".rar") {
if (file_processing.save_file(filename, content)) { //if (file_processing.save_file_with_retry(filename, content)) {
if (file_processing.save_file(filename, content)) {
std::string random_string = generate_random_string(20);//Todo think about change //Todo uncommit later
//std::string random_string = generate_random_string(20);//Todo think about change
file_processing.unzip(filename, this->publish_app_path + random_string); //file_processing.unzip(filename, this->publish_app_path + random_string);
this->dotnet_publish(this->publish_app_path + random_string); //this->dotnet_publish(this->publish_app_path + random_string);
res.set_content("File uploaded successfully: " + filename, "text/plain"); res.set_content("File uploaded successfully: " + filename, "text/plain");
}
else {
res.status = 500;
res.set_content("Failed to save file, please ensure you are putting rar file"
+ filename, "text/plain");
}
} }
else { else {
res.status = 400; res.status = 500;
res.set_content("Invalid file type. Only .rar files are allowed.", res.set_content("Failed to save file, please ensure you are putting rar file"
"text/plain"); + filename, "text/plain");
} }
} }
else else {
{ res.status = 400;
//Todo add logging and exiting from function with bead request res.set_content("Invalid file type. Only .rar files are allowed.",
"text/plain");
} }
} }
else
void dotnet_publish(const std::string& path)
{ {
std::string dll_file_name = file_processing.find_file_by_suffix(path, "dll"); //Todo add logging and exiting from function with bead request
}
}
std::string command = R"(dotnet )" + path + "/" + dll_file_name; void dotnet_publish(const std::string& path)
{
std::string dll_file_name = file_processing.find_file_by_suffix(path, "dll");
std::thread commandThread(&CommandService::execute_command, command); std::string command = R"(dotnet )" + path + "/" + dll_file_name;
commandThread.detach(); std::thread commandThread(&CommandService::execute_command, command);
commandThread.detach();
}
static std::string generate_random_string(size_t length, const std::string& char_set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_int_distribution<> distribution(0, char_set.size() - 1);
std::string random_string;
for (size_t i = 0; i < length; ++i) {
char random_char = char_set[distribution(generator)];
random_string += random_char;
} }
static std::string generate_random_string(size_t length, const std::string& char_set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") { return random_string;
std::random_device rd; }
std::mt19937 generator(rd());
std::uniform_int_distribution<> distribution(0, char_set.size() - 1);
std::string random_string;
for (size_t i = 0; i < length; ++i) {
char random_char = char_set[distribution(generator)];
random_string += random_char;
}
return random_string;
}
}; };

View File

@@ -1,27 +1,92 @@
// ReSharper disable CppClangTidyBugproneSuspiciousInclude // ReSharper disable CppClangTidyBugproneSuspiciousInclude
#include <filesystem> #include <filesystem>
#include <fstream> #include <fstream>
#include <future>
#include <string> #include <string>
#include <thread> #include <thread>
#include <sys/stat.h> #include <sys/stat.h>
#include "CommandService.cpp" #include "CommandService.cpp"
//#include <Poco/Mutex.h>
//#include <Poco/Path.h>
//#include <Poco/FileStr*/eam.h >
class FileProcessingService class FileProcessingService
{ {
public: public:
FileProcessingService() FileProcessingService(/*&Logger logger*/)
{ {
} }
bool save_file(const std::string& filename, const std::string& content) { bool save_file(const std::string& filename, const std::string& content) {
//std::lock_guard<std::mutex> lock(file_mutex); // Блокируем мьютекс//Todo TEST STABILITY OF THIS
std::ofstream ofs(filename, std::ios::binary); std::ofstream ofs(filename, std::ios::binary);
if (!ofs) return false; if (!ofs) return false;
ofs << content; ofs << content;
return ofs.good(); return ofs.good();
} }
//bool save_file(const std::string& filename, const std::string& content) {
// Mutex::ScopedLock lock(file_mutex); // Блокируем мьютекс
// try {
// Poco::File file(filename);
// Poco::FileOutputStream ofs(filename, std::ios::binary | std::ios::trunc);
// if (!ofs.good()) {
// std::cerr << "Error opening file: " << filename << std::endl;
// return false;
// }
// ofs.write(content.c_str(), content.size());
// if (!ofs.good()) {
// std::cerr << "Error writing to file: " << filename << std::endl;
// return false;
// }
// ofs.close(); // Явно закрываем файл
// }
// catch (const Poco::Exception& ex) {
// std::cerr << "Poco exception: " << ex.displayText() << std::endl;
// return false;
// }
// return true;
//}
//bool save_file_with_timeout(const std::string& filename, const std::string& content, std::chrono::milliseconds timeout) {
// // Запускаем асинхронную задачу для записи файла
// auto future = std::async(std::launch::async, &FileProcessingService::save_file, this, filename, content);
// // Ожидаем завершения задачи или истечения тайм-аута
// if (future.wait_for(timeout) == std::future_status::ready) {
// return future.get(); // Возвращаем результат записи
// }
// else {
// std::cerr << "Timeout occurred while saving file: " << filename << std::endl;
// return false; // Тайм-аут
// }
//}
//bool save_file_with_retry(const std::string& filename, const std::string& content, int max_retries = 5, std::chrono::milliseconds timeout = std::chrono::milliseconds(1000)) {
// for (int i = 0; i < max_retries; ++i) {
// if (save_file_with_timeout(filename, content, timeout)) {
// return true;
// }
// std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Пауза перед повторной попыткой
// }
// std::cerr << "Failed to save file after " << max_retries << " attempts: " << filename << std::endl;
// return false;
//}
void create_directory(const std::string& path) { void create_directory(const std::string& path) {
std::filesystem::create_directories(path); std::filesystem::create_directories(path);
} }
@@ -32,7 +97,6 @@ public:
//Windows version //Windows version
//std::string command = R"(powershell -Command "& \"C:\Program Files\WinRAR\WinRAR.exe\" x \")" + file_path + R"(\" \")" + final_files_directory + R"(\")"; //std::string command = R"(powershell -Command "& \"C:\Program Files\WinRAR\WinRAR.exe\" x \")" + file_path + R"(\" \")" + final_files_directory + R"(\")";
std::cout << "unzip start\n";
//Linux version //Linux version
//std::string command = "unzip " + file_path + " -d " + final_files_directory; //std::string command = "unzip " + file_path + " -d " + final_files_directory;
@@ -69,4 +133,7 @@ public:
// int result = system(command.c_str());//Todo solve unsafe warning // int result = system(command.c_str());//Todo solve unsafe warning
//} //}
/*private:
std::mutex file_mutex; */// Мьютекс для синхронизации доступа к файлу
}; };

View File

@@ -0,0 +1,70 @@
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
enum LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL };
class Logger {
public:
// Constructor: Opens the log file in append mode
Logger( std::string& filename)
{
logFile.open(filename, std::ios::app);
if (!logFile.is_open()) {
std::cerr << "Error opening log file." << '\n';
}
}
// Destructor: Closes the log file
~Logger() { logFile.close(); }
// Logs a message with a given log level
void log(LogLevel level, const std::string& message)
{
// Get current timestamp
time_t now = time(0);
tm* timeinfo = localtime(&now);
char timestamp[20];
strftime(timestamp, sizeof(timestamp),
"%Y-%m-%d %H:%M:%S", timeinfo);
// Create log entry
std::ostringstream logEntry;
logEntry << "[" << timestamp << "] "
<< levelToString(level) << ": " << message
<< std::endl;
// Output to console
std::cout << logEntry.str();
// Output to log file
if (logFile.is_open()) {
logFile << logEntry.str();
logFile.flush(); // Ensure immediate write to file
}
}
private:
std::ofstream logFile; // File stream for the log file
// Converts log level to a string for output
std::string levelToString(LogLevel level)
{
switch (level) {
case DEBUG:
return "DEBUG";
case INFO:
return "INFO";
case WARNING:
return "WARNING";
case ERROR:
return "ERROR";
case CRITICAL:
return "CRITICAL";
default:
return "UNKNOWN";
}
}
};

View File

@@ -7,77 +7,15 @@
#include "httplib.h" #include "httplib.h"
#include "Controllers/PublishController.cpp" #include "Controllers/PublishController.cpp"
//#include "Service/AuthorizationService.cpp" //#include "Service/AuthorizationService.cpp"
#include "Service/Logger.cpp"
//#include "Service/FileProcessingService.cpp" //#include "Service/FileProcessingService.cpp"
using namespace std; using namespace std;
enum LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL };
class Logger {
public:
// Constructor: Opens the log file in append mode
Logger(const string& filename)
{
logFile.open(filename, ios::app);
if (!logFile.is_open()) {
cerr << "Error opening log file." << endl;
}
}
// Destructor: Closes the log file
~Logger() { logFile.close(); }
// Logs a message with a given log level
void log(LogLevel level, const string& message)
{
// Get current timestamp
time_t now = time(0);
tm* timeinfo = localtime(&now);
char timestamp[20];
strftime(timestamp, sizeof(timestamp),
"%Y-%m-%d %H:%M:%S", timeinfo);
// Create log entry
ostringstream logEntry;
logEntry << "[" << timestamp << "] "
<< levelToString(level) << ": " << message
<< endl;
// Output to console
cout << logEntry.str();
// Output to log file
if (logFile.is_open()) {
logFile << logEntry.str();
logFile.flush(); // Ensure immediate write to file
}
}
private:
ofstream logFile; // File stream for the log file
// Converts log level to a string for output
string levelToString(LogLevel level)
{
switch (level) {
case DEBUG:
return "DEBUG";
case INFO:
return "INFO";
case WARNING:
return "WARNING";
case ERROR:
return "ERROR";
case CRITICAL:
return "CRITICAL";
default:
return "UNKNOWN";
}
}
};
int main() int main()
{ {
Logger logger("logfile.txt"); string logger_name = "logfile.txt";
Logger logger(logger_name);
std::cout << "SpCloud start\n"; std::cout << "SpCloud start\n";
@@ -96,8 +34,8 @@ int main()
httplib::Headers test = req.headers; httplib::Headers test = req.headers;
}); });
// Предполагается, что эти классы определены где-то еще
AuthorizationService authorization_service; AuthorizationService authorization_service;
FileProcessingService file_processing; FileProcessingService file_processing;
PublishController publish_controller(svr, authorization_service, file_processing); PublishController publish_controller(svr, authorization_service, file_processing);