Compare commits

...

10 Commits

Author SHA1 Message Date
cf8738aee9 dropshell release 2025.0518.2236
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
2025-05-18 22:37:00 +12:00
d80820db15 Back to issue from pre-refactor!
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
2025-05-18 20:23:15 +12:00
fb6974b51a Working on backup/restore.
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
2025-05-18 20:19:47 +12:00
263edd9b50 dropshell release 2025.0518.1558
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
2025-05-18 15:58:29 +12:00
e45afe460b Backups seem to be working
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
.
2025-05-18 15:43:19 +12:00
630a9fd19a Add backupdata
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
2025-05-18 15:41:51 +12:00
f89d90c12b dropshell release 2025.0518.1451
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
2025-05-18 14:51:53 +12:00
5883c62c54 Tidy output
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
2025-05-18 14:29:51 +12:00
b278e81533 info for table print
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
2025-05-18 14:03:12 +12:00
6c99b429b9 dropshell release 2025.0518.1356
Some checks failed
Dropshell Test / Build_and_Test (push) Has been cancelled
2025-05-18 13:56:52 +12:00
26 changed files with 1221 additions and 684 deletions

View File

@ -0,0 +1,174 @@
#include <unistd.h>
#include <cstring>
#include <iostream>
#include <sstream>
#include <filesystem>
#include "utils/output.hpp"
#include "utils/assert.hpp"
#include "utils/utils.hpp"
#include "command_registry.hpp"
#include "config.hpp"
#include "services.hpp"
#include "servers.hpp"
#include "server_env_manager.hpp"
#include "templates.hpp"
#include "utils/directories.hpp"
#include "shared_commands.hpp"
namespace dropshell
{
int backupdata_handler(const CommandContext &ctx);
static std::vector<std::string> backupdata_name_list = {"backupdata", "bd", "backup", "bup"};
// Static registration
struct BackupDataCommandRegister
{
BackupDataCommandRegister()
{
CommandRegistry::instance().register_command({backupdata_name_list,
backupdata_handler,
shared_commands::std_autocomplete_allowall,
false, // hidden
true, // requires_config
true, // requires_install
2, // min_args (after command)
2, // max_args (after command)
"backupdata SERVER SERVICE",
"Backup data for a service on a server.",
// heredoc
R"(
backupdata SERVER SERVICE Backup data for a service on a server.
backupdata SERVER all Backup data for all services on a server.
Note: This command will not create any data or configuration.
It will simply backup the data on the remote server, saving it to a local file.
Restore the data with restore.
)"});
}
} backupdata_command_register;
namespace shared_commands
{
bool backupdata_service(const std::string &server, const std::string &service)
{
server_env_manager server_env(server);
if (!server_env.is_valid())
{
error << "Server " << server << " is not valid" << std::endl;
return false;
}
LocalServiceInfo sinfo = get_service_info(server, service);
if (!SIvalid(sinfo))
{
error << "Service " << service << " is not valid" << std::endl;
return false;
}
const std::string command = "backup";
if (!gTemplateManager().template_command_exists(sinfo.template_name, command))
{
info << service << " has no data to backup" << std::endl;
debug << "(no backup script for " << sinfo.template_name << ")" << std::endl;
return true; // nothing to back up.
}
// Check if basic installed stuff is in place.
std::string remote_service_template_path = remotepath::service_template(server, service);
std::string remote_command_script_file = remote_service_template_path + "/" + command + ".sh";
std::string remote_service_config_path = remotepath::service_config(server, service);
if (!server_env.check_remote_items_exist({remotepath::service(server, service),
remote_command_script_file,
remotefile::service_env(server, service)}))
{
error << "Error: Required service directories not found on remote server" << std::endl;
info << "Is the service installed?" << std::endl;
return false;
}
// Create backups directory on server if it doesn't exist
std::string remote_backups_dir = remotepath::backups(server);
debug << "Remote backups directory on " << server << ": " << remote_backups_dir << std::endl;
std::string mkdir_cmd = "mkdir -p " + quote(remote_backups_dir);
if (!execute_ssh_command(server_env.get_SSH_INFO(), sCommand("", mkdir_cmd, {}), cMode::Defaults))
{
error << "Failed to create backups directory on server" << std::endl;
return false;
}
// Create backups directory locally if it doesn't exist
std::string local_backups_dir = gConfig().get_local_backup_path();
if (local_backups_dir.empty())
{
error << "Error: Local backups directory not found" << std::endl;
info << "Run 'dropshell edit' to configure DropShell" << std::endl;
return false;
}
if (!std::filesystem::exists(local_backups_dir))
std::filesystem::create_directories(local_backups_dir);
// Get current datetime for backup filename
shared_commands::cBackupFileName backup_filename_construction(server, service, sinfo.template_name);
if (!backup_filename_construction.is_valid())
{
error << "Invalid backup filename" << std::endl;
return false;
}
// Construct backup filename
std::string backup_filename = backup_filename_construction.get_filename();
std::string remote_backup_file_path = remote_backups_dir + "/" + backup_filename;
std::string local_backup_file_path = (std::filesystem::path(local_backups_dir) / backup_filename).string();
// assert that the backup filename is valid - -_- appears exactly 3 times in local_backup_file_path.
ASSERT(3 == count_substring(magic_string(), local_backup_file_path), "Invalid backup filename");
{ // Run backup script
shared_commands::cRemoteTempFolder remote_temp_folder(server_env);
if (!server_env.run_remote_template_command(service, command, {}, false, {{"BACKUP_FILE", remote_backup_file_path}, {"TEMP_DIR", remote_temp_folder.path()}}))
{
error << "Backup script failed on remote server: " << remote_backup_file_path << std::endl;
return false;
}
// Copy backup file from server to local
if (!shared_commands::scp_file_from_remote(server_env, remote_backup_file_path, local_backup_file_path, false))
{
error << "Failed to copy backup file from server" << std::endl;
return false;
}
} // dtor of remote_temp_folder will clean up the temp folder on the server
info << "Backup created successfully. Restore with:" << std::endl;
info << " dropshell restore " << server << " " << service << " " << backup_filename << std::endl;
return true;
}
} // namespace shared_commands
int backupdata_handler(const CommandContext &ctx)
{
ASSERT(ctx.args.size() == 2, "Invalid number of arguments");
std::string server = safearg(ctx.args, 0);
std::string service = safearg(ctx.args, 1);
if (service == "all")
{
// backup all services on the server
maketitle("Backing up data for all services on " + server);
bool okay = true;
std::vector<LocalServiceInfo> services = get_server_services_info(server);
for (const LocalServiceInfo &si : services)
okay &= shared_commands::backupdata_service(server, si.service_name);
return okay ? 0 : 1;
}
return shared_commands::backupdata_service(server, service) ? 0 : 1;
}
} // namespace dropshell

View File

@ -0,0 +1,44 @@
#include "command_registry.hpp"
#include "config.hpp"
#include "utils/output.hpp"
#include "utils/assert.hpp"
namespace dropshell {
void colours_autocomplete(const CommandContext& ctx) {}
int colours_handler(const CommandContext& ctx)
{
info << "Colours:" << std::endl;
debug << "Debug Example: The quick brown fox jumps over the lazy dog." << std::endl;
info << "Info Example: The quick brown fox jumps over the lazy dog." << std::endl;
warning << "Warning Example: The quick brown fox jumps over the lazy dog." << std::endl;
error << "Error Example: The quick brown fox jumps over the lazy dog." << std::endl;
return 0;
}
static std::vector<std::string> colours_name_list={"colours","c","--colours","-c"};
// Static registration
struct ColoursCommandRegister {
ColoursCommandRegister() {
CommandRegistry::instance().register_command({
colours_name_list,
colours_handler,
colours_autocomplete,
true, // hidden
false, // requires_config
false, // requires_install
0, // min_args (after command)
0, // max_args (after command)
"colours",
"Show the colours used by dropshell.",
// heredoc
R"(
Show the colours used by dropshell.
)"
});
}
} colours_command_register;
} // namespace dropshell

View File

@ -11,7 +11,6 @@ namespace dropshell
{ {
int create_service_handler(const CommandContext &ctx); int create_service_handler(const CommandContext &ctx);
bool create_service(const std::string &server_name, const std::string &template_name, const std::string &service_name, bool silent);
void create_service_autocomplete(const CommandContext &ctx); void create_service_autocomplete(const CommandContext &ctx);
static std::vector<std::string> create_service_name_list = {"create-service"}; static std::vector<std::string> create_service_name_list = {"create-service"};
@ -45,7 +44,7 @@ namespace dropshell
std::string service = safearg(ctx.args, 1); std::string service = safearg(ctx.args, 1);
std::string template_name = safearg(ctx.args, 2); std::string template_name = safearg(ctx.args, 2);
return create_service(server, template_name, service, false) ? 0 : 1; return shared_commands::create_service(server, template_name, service) ? 0 : 1;
} }
void create_service_autocomplete(const CommandContext &ctx) void create_service_autocomplete(const CommandContext &ctx)
@ -58,12 +57,15 @@ namespace dropshell
{ {
std::set<std::string> templates = gTemplateManager().get_template_list(); std::set<std::string> templates = gTemplateManager().get_template_list();
for (const auto &template_name : templates) for (const auto &template_name : templates)
std::cout << template_name << std::endl; rawout << template_name << std::endl;
} }
} }
} }
bool create_service(const std::string &server_name, const std::string &template_name, const std::string &service_name, bool silent) namespace shared_commands
{
bool create_service(const std::string &server_name, const std::string &template_name, const std::string &service_name)
{ {
if (server_name.empty() || template_name.empty() || service_name.empty()) if (server_name.empty() || template_name.empty() || service_name.empty())
return false; return false;
@ -72,44 +74,34 @@ namespace dropshell
if (service_dir.empty()) if (service_dir.empty())
{ {
if (!silent) error << "Couldn't locate server " << server_name << " in any config directory" << std::endl;
{ info << "Please check the server name is correct and try again" << std::endl;
std::cerr << "Error: Couldn't locate server " << server_name << " in any config directory" << std::endl; info << "You can list all servers with 'dropshell servers'" << std::endl;
std::cerr << "Please check the server name is correct and try again" << std::endl; info << "You can create a new server with 'dropshell create-server " << server_name << "'" << std::endl;
std::cerr << "You can list all servers with 'dropshell servers'" << std::endl;
std::cerr << "You can create a new server with 'dropshell create-server " << server_name << "'" << std::endl;
}
return false; return false;
} }
if (std::filesystem::exists(service_dir)) if (std::filesystem::exists(service_dir))
{ {
if (!silent) error << "Service already exists: " << service_name << std::endl;
{ debug << "Current service path: " << service_dir << std::endl;
std::cerr << "Error: Service already exists: " << service_name << std::endl;
std::cerr << "Current service path: " << service_dir << std::endl;
}
return false; return false;
} }
template_info tinfo = gTemplateManager().get_template_info(template_name); template_info tinfo = gTemplateManager().get_template_info(template_name);
if (!tinfo.is_set()) if (!tinfo.is_set())
{ {
if (!silent) error << "Template '" << template_name << "' not found" << std::endl;
{ info << "Please check the template name is correct and try again" << std::endl;
std::cerr << "Error: Template '" << template_name << "' not found" << std::endl; info << "You can list all templates with 'dropshell templates'" << std::endl;
std::cerr << "Please check the template name is correct and try again" << std::endl; info << "You can create a new template with 'dropshell create-template " << template_name << "'" << std::endl;
std::cerr << "You can list all templates with 'dropshell templates'" << std::endl;
std::cerr << "You can create a new template with 'dropshell create-template " << template_name << "'" << std::endl;
}
return false; return false;
} }
// check template is all good. // check template is all good.
if (!gTemplateManager().test_template(tinfo.local_template_path())) if (!gTemplateManager().test_template(tinfo.local_template_path()))
{ {
if (!silent) error << "Template '" << template_name << "' is not valid" << std::endl;
std::cerr << "Error: Template '" << template_name << "' is not valid" << std::endl;
return false; return false;
} }
@ -119,15 +111,14 @@ namespace dropshell
// copy the template config files to the service directory // copy the template config files to the service directory
recursive_copy(tinfo.local_template_path() / "config", service_dir); recursive_copy(tinfo.local_template_path() / "config", service_dir);
if (!silent) info << "Service " << service_name << " created successfully" << std::endl;
{ info << std::endl;
std::cout << "Service " << service_name << " created successfully" << std::endl; info << "To complete the installation, please:" << std::endl;
std::cout << std::endl; info << "1. edit the service config file: dropshell edit " << server_name << " " << service_name << std::endl;
std::cout << "To complete the installation, please:" << std::endl; info << "2. install the remote service: dropshell install " << server_name << " " << service_name << std::endl;
std::cout << "1. edit the service config file: dropshell edit " << server_name << " " << service_name << std::endl;
std::cout << "2. install the remote service: dropshell install " << server_name << " " << service_name << std::endl;
}
return true; return true;
} }
} // namespace shared_commands
} // namespace dropshell } // namespace dropshell

View File

@ -66,13 +66,13 @@ bool edit_file(const std::string &file_path, bool has_bb64)
// Check if stdin is connected to a terminal if EDITOR is not set // Check if stdin is connected to a terminal if EDITOR is not set
editor_cmd = "nano -w " + quote(file_path); editor_cmd = "nano -w " + quote(file_path);
} else { } else {
std::cerr << "Error: Standard input is not a terminal and EDITOR environment variable is not set." << std::endl; error << "Standard input is not a terminal and EDITOR environment variable is not set." << std::endl;
std::cerr << "Try setting the EDITOR environment variable (e.g., export EDITOR=nano) or run in an interactive terminal." << std::endl; info << "Try setting the EDITOR environment variable (e.g., export EDITOR=nano) or run in an interactive terminal." << std::endl;
std::cerr << "You can manually edit the file at: " << file_path << std::endl; info << "You can manually edit the file at: " << file_path << std::endl;
return false; return false;
} }
std::cout << "Editing file: " << file_path << std::endl; info << "Editing file: " << file_path << std::endl;
if (has_bb64) { if (has_bb64) {
return execute_local_command("", editor_cmd, {}, nullptr, cMode::Interactive); return execute_local_command("", editor_cmd, {}, nullptr, cMode::Interactive);
@ -119,14 +119,14 @@ int edit_server(const std::string &server_name)
std::string config_file = localfile::server_json(server_name); std::string config_file = localfile::server_json(server_name);
if (!edit_file(config_file, true)) { if (!edit_file(config_file, true)) {
std::cerr << "Error: Failed to edit server config" << std::endl; error << "Failed to edit server config" << std::endl;
std::cerr << "You can manually edit this file at: " << config_file << std::endl; info << "You can manually edit this file at: " << config_file << std::endl;
return 1; return 1;
} }
std::cout << "If you have changed DROPSHELL_DIR, you should manually move the files to the new location NOW." << std::endl info << "If you have changed DROPSHELL_DIR, you should manually move the files to the new location NOW." << std::endl;
<< "You can ssh in to the remote server with: dropshell ssh "<<server_name<< std::endl info << "You can ssh in to the remote server with: dropshell ssh "<<server_name<< std::endl;
<< "Once moved, reinstall all services with: dropshell install " << server_name << std::endl; info << "Once moved, reinstall all services with: dropshell install " << server_name << std::endl;
return 0; return 0;
} }
@ -138,12 +138,12 @@ int edit_service_config(const std::string &server, const std::string &service)
std::string config_file = localfile::service_env(server, service); std::string config_file = localfile::service_env(server, service);
if (!std::filesystem::exists(config_file)) if (!std::filesystem::exists(config_file))
{ {
std::cerr << "Error: Service config file not found: " << config_file << std::endl; error << "Service config file not found: " << config_file << std::endl;
return 1; return 1;
} }
if (edit_file(config_file, true) && std::filesystem::exists(config_file)) if (edit_file(config_file, true) && std::filesystem::exists(config_file))
std::cout << "To apply your changes, run:\n dropshell install " + server + " " + service << std::endl; info << "To apply your changes, run:\n dropshell install " + server + " " + service << std::endl;
return 0; return 0;
} }
@ -167,7 +167,7 @@ int edit_handler(const CommandContext& ctx) {
return 0; return 0;
} }
std::cout << "Edit handler called with " << ctx.args.size() << " args\n"; info << "Edit handler called with " << ctx.args.size() << " args\n";
return -1; return -1;
} }

View File

@ -45,7 +45,7 @@ namespace dropshell
{ {
if (ctx.args.size() < 1) if (ctx.args.size() < 1)
{ {
std::cerr << "Error: Server name is required" << std::endl; error << "Server name is required" << std::endl;
return 1; return 1;
} }

View File

@ -48,7 +48,7 @@ void help_autocomplete(const CommandContext& ctx) {
if (ctx.args.size() == 1) { if (ctx.args.size() == 1) {
// list all commands // list all commands
for (const auto& cmd : CommandRegistry::instance().list_primary_commands(false)) { for (const auto& cmd : CommandRegistry::instance().list_primary_commands(false)) {
std::cout << cmd << std::endl; rawout << cmd << std::endl;
} }
} }
return; return;
@ -58,13 +58,13 @@ void show_command(const std::string& cmd) {
const auto& cmd_info = CommandRegistry::instance().find_command(cmd); const auto& cmd_info = CommandRegistry::instance().find_command(cmd);
if (!cmd_info) if (!cmd_info)
{ {
std::cout << "Unknown command: " << cmd << std::endl; error << "Unknown command: " << cmd << std::endl;
return; return;
} }
std::cout << " "; info << " ";
print_left_aligned(cmd_info->help_usage, 32); info << left_align(cmd_info->help_usage, 32);
std::cout << cmd_info->help_description << std::endl; info << cmd_info->help_description << std::endl;
} }
extern const std::string VERSION; extern const std::string VERSION;
@ -77,28 +77,26 @@ int show_command_help(const std::string& cmd) {
const auto& cmd_info = CommandRegistry::instance().find_command(cmd); const auto& cmd_info = CommandRegistry::instance().find_command(cmd);
if (!cmd_info) if (!cmd_info)
{ {
std::cout << "Unknown command: " << cmd << std::endl; error << "Unknown command: " << cmd << std::endl;
return 1; return 1;
} }
info << "Command " << cmd << " usage:" << std::endl;
info << " ";
info << left_align(cmd_info->help_usage, 32);
info << cmd_info->help_description << std::endl;
std::cout << std::endl; info << std::endl;
std::cout << "Usage: " << std::endl;
std::cout << " ";
print_left_aligned(cmd_info->help_usage, 30);
std::cout << cmd_info->help_description << std::endl;
std::cout << std::endl; info << " Equivalent names: ";
std::cout << " Equivalent names: ";
bool first = true; bool first = true;
for (const auto& name : cmd_info->names) { for (const auto& name : cmd_info->names) {
if (!first) std::cout << ", "; if (!first) info << ", ";
std::cout << name; info << name;
first = false; first = false;
} }
std::cout << std::endl << std::endl; info << std::endl;
std::cout << cmd_info->full_help << std::endl << std::endl; info << cmd_info->full_help << std::endl << std::endl;
return 0; return 0;
} }
@ -108,12 +106,12 @@ int help_handler(const CommandContext& ctx) {
if (ctx.args.size() > 0) if (ctx.args.size() > 0)
return show_command_help(ctx.args[0]); return show_command_help(ctx.args[0]);
std::cout << std::endl; info << std::endl;
maketitle("DropShell version " + VERSION); maketitle("DropShell version " + VERSION);
std::cout << std::endl; info << std::endl;
std::cout << "A tool for managing remote servers, by " << AUTHOR << std::endl; info << "A tool for managing remote servers, by " << AUTHOR << std::endl;
std::cout << std::endl; info << std::endl;
std::cout << "dropshell ..." << std::endl; info << "dropshell ..." << std::endl;
show_command("help"); show_command("help");
show_command("edit"); show_command("edit");
@ -136,56 +134,6 @@ int help_handler(const CommandContext& ctx) {
return 0; return 0;
} }
// void show_command(const std::string& cmd) {
// const auto& cmd_info = CommandRegistry::instance().find_command(cmd);
// if (cmd_info) {
// std::cout << " " << cmd_info->help_usage
// << std::string(' ', std::min(1,(int)(30-cmd_info->help_usage.length())))
// << cmd_info->help_description << std::endl;
// }
// }
// bool print_help() {
// std::cout << std::endl;
// maketitle("DropShell version " + VERSION);
// std::cout << std::endl;
// std::cout << "A tool for managing server configurations" << std::endl;
// std::cout << std::endl;
// std::cout << "dropshell ..." << std::endl;
// show_command("help");
// show_command("edit");
// if (gConfig().is_config_set()) {
// std::cout << " templates List all available templates" << std::endl;
// std::cout << std::endl;
// std::cout << std::endl;
// std::cout << "Service commands: (if no service is specified, all services for the server are affected)" << std::endl;
// std::cout << " list [SERVER] [SERVICE] List status/details of all servers/server/service." << std::endl;
// std::cout << " edit [SERVER] [SERVICE] Edit the configuration of dropshell/server/service." << std::endl;
// std::cout << std::endl;
// std::cout << " install SERVER [SERVICE] Install/reinstall/update service(s). Safe/non-destructive." << std::endl;
// std::cout << " uninstall SERVER [SERVICE] Uninstalls the service on the remote server. Leaves data intact." << std::endl;
// std::cout << " nuke SERVER SERVICE Nuke the service, deleting ALL local and remote data." << std::endl;
// std::cout << std::endl;
// std::cout << " COMMAND SERVER [SERVICE] Run a command on service(s), e.g." << std::endl;
// std::cout << " backup, restore, start, stop, logs" << std::endl;
// std::cout << std::endl;
// std::cout << " ssh SERVER SERVICE Launch an interactive shell on a server or service" << std::endl;
// std::cout << std::endl;
// std::cout << "Creation commands: (apply to the first local config directory)"<<std::endl;
// std::cout << " create-template TEMPLATE" << std::endl;
// std::cout << " create-server SERVER" << std::endl;
// std::cout << " create-service SERVER TEMPLATE SERVICE" << std::endl;
// }
// else {
// show_command("help");
// show_command("edit");
// std::cout << std::endl;
// std::cout << "Other commands available once initialised." << std::endl;
// }
// return true;
// }
} // namespace dropshell } // namespace dropshell

View File

@ -53,11 +53,13 @@ namespace dropshell
} }
} install_command_register; } install_command_register;
namespace shared_commands
{
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// install service over ssh : SHARED COMMAND // install service over ssh : SHARED COMMAND
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
bool install_service(const std::string &server, const std::string &service, bool silent) bool install_service(const std::string &server, const std::string &service)
{ {
LocalServiceInfo service_info = get_service_info(server, service); LocalServiceInfo service_info = get_service_info(server, service);
if (!SIvalid(service_info)) if (!SIvalid(service_info))
@ -104,7 +106,7 @@ namespace dropshell
debug << "Copying: [LOCAL] " << tinfo.local_template_path() << std::endl debug << "Copying: [LOCAL] " << tinfo.local_template_path() << std::endl
<< std::string(8, ' ') << "[REMOTE] " << remotepath::service_template(server, service) << "/" << std::endl; << std::string(8, ' ') << "[REMOTE] " << remotepath::service_template(server, service) << "/" << std::endl;
if (!shared_commands::rsync_tree_to_remote(tinfo.local_template_path().string(), remotepath::service_template(server, service), if (!shared_commands::rsync_tree_to_remote(tinfo.local_template_path().string(), remotepath::service_template(server, service),
server_env, silent)) server_env, false))
{ {
std::cerr << "Failed to copy template files using rsync" << std::endl; std::cerr << "Failed to copy template files using rsync" << std::endl;
return false; return false;
@ -114,7 +116,7 @@ namespace dropshell
debug << "Copying: [LOCAL] " << localpath::service(server, service) << std::endl debug << "Copying: [LOCAL] " << localpath::service(server, service) << std::endl
<< std::string(8, ' ') << "[REMOTE] " << remotepath::service_config(server, service) << std::endl; << std::string(8, ' ') << "[REMOTE] " << remotepath::service_config(server, service) << std::endl;
if (!shared_commands::rsync_tree_to_remote(localpath::service(server, service), remotepath::service_config(server, service), if (!shared_commands::rsync_tree_to_remote(localpath::service(server, service), remotepath::service_config(server, service),
server_env, silent)) server_env, false))
{ {
std::cerr << "Failed to copy service files using rsync" << std::endl; std::cerr << "Failed to copy service files using rsync" << std::endl;
return false; return false;
@ -123,7 +125,7 @@ namespace dropshell
// Run install script // Run install script
{ {
info << "Running " << service_info.template_name << " install script on " << server << "..." << std::endl; info << "Running " << service_info.template_name << " install script on " << server << "..." << std::endl;
server_env.run_remote_template_command(service, "install", {}, silent, {}); server_env.run_remote_template_command(service, "install", {}, false, {});
} }
// print health tick // print health tick
@ -131,6 +133,7 @@ namespace dropshell
return true; return true;
} }
} // namespace shared_commands
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// update_dropshell // update_dropshell
@ -305,14 +308,15 @@ namespace dropshell
info << "done." << std::endl; info << "done." << std::endl;
// add in bb64. We can't use execute_remote_command() here, as that relies on bb64 which we're installing! // add in bb64. We can't use execute_remote_command() here, as that relies on bb64 which we're installing!
info << "Installing bb64 on " << server << "..." << std::endl << std::flush; info << "Installing bb64 on " << server << "..." << std::endl
<< std::flush;
std::string remote_cmd = std::string remote_cmd =
"ssh -p " + server_env.get_SSH_INFO().port + " " + server_env.get_SSH_INFO().user + "@" + server_env.get_SSH_INFO().host + "ssh -p " + server_env.get_SSH_INFO().port + " " + server_env.get_SSH_INFO().user + "@" + server_env.get_SSH_INFO().host +
" 'mkdir -p " + quote(agent_path) + " && curl -fsSL \"https://gitea.jde.nz/public/bb64/releases/download/latest/install.sh\" | bash -s -- " + " 'mkdir -p " + quote(agent_path) + " && curl -fsSL \"https://gitea.jde.nz/public/bb64/releases/download/latest/install.sh\" | bash -s -- " +
quote(agent_path) + " " + quote("$(id -u " + server_env.get_SSH_USER() + "):$(id -g " + server_env.get_SSH_USER() + ")") + "'"; quote(agent_path) + " " + quote("$(id -u " + server_env.get_SSH_USER() + "):$(id -g " + server_env.get_SSH_USER() + ")") + "'";
//std::cout << "Executing: " << remote_cmd << std::endl; // std::cout << "Executing: " << remote_cmd << std::endl;
if (!execute_local_command("", remote_cmd, {}, nullptr, cMode::Silent)) if (!execute_local_command("", remote_cmd, {}, nullptr, cMode::Silent))
error << "Failed to download bb64 to " << agent_path << " on remote server." << std::endl; error << "Failed to download bb64 to " << agent_path << " on remote server." << std::endl;
else else
@ -362,7 +366,7 @@ namespace dropshell
std::vector<LocalServiceInfo> services = get_server_services_info(server); std::vector<LocalServiceInfo> services = get_server_services_info(server);
for (const auto &service : services) for (const auto &service : services)
{ {
if (!install_service(server, service.service_name, false)) if (!shared_commands::install_service(server, service.service_name))
okay = false; okay = false;
} }
return okay ? 0 : 1; return okay ? 0 : 1;
@ -370,7 +374,7 @@ namespace dropshell
else else
{ // install the specific service. { // install the specific service.
std::string service = safearg(ctx.args, 1); std::string service = safearg(ctx.args, 1);
return install_service(server, service, false) ? 0 : 1; return shared_commands::install_service(server, service) ? 0 : 1;
} }
} }

View File

@ -130,7 +130,7 @@ void show_server_details(const std::string& server_name) {
info << std::string(40, '-') << std::endl; info << std::string(40, '-') << std::endl;
// Try to connect to the server // Try to connect to the server
std::string cmd = "ssh -o ConnectTimeout=5 " + ssh_user + "@" + ssh_address + " -p " + ssh_port + " 'echo connected' 2>/dev/null"; std::string cmd = "ssh -o ConnectTimeout=5 " + ssh_user + "@" + ssh_address + " -p " + ssh_port + " 'true' 2>/dev/null";
int result = system(cmd.c_str()); int result = system(cmd.c_str());
if (result == 0) { if (result == 0) {
info << "Status: Online" << std::endl; info << "Status: Online" << std::endl;

View File

@ -10,16 +10,18 @@
#include "utils/assert.hpp" #include "utils/assert.hpp"
namespace dropshell { namespace dropshell
{
int nuke_handler(const CommandContext& ctx); int nuke_handler(const CommandContext &ctx);
static std::vector<std::string> nuke_name_list={"nuke"}; static std::vector<std::string> nuke_name_list = {"nuke"};
// Static registration // Static registration
struct NukeCommandRegister { struct NukeCommandRegister
NukeCommandRegister() { {
CommandRegistry::instance().register_command({ NukeCommandRegister()
nuke_name_list, {
CommandRegistry::instance().register_command({nuke_name_list,
nuke_handler, nuke_handler,
shared_commands::std_autocomplete, shared_commands::std_autocomplete,
false, // hidden false, // hidden
@ -41,13 +43,15 @@ struct NukeCommandRegister {
both on the dropshell host and on the remote server. both on the dropshell host and on the remote server.
Use with caution! Use with caution!
)" )"});
});
} }
} nuke_command_register; } nuke_command_register;
int nuke_one(std::string server, std::string service) namespace shared_commands
{ {
bool nuke_service(const std::string &server, const std::string &service)
{
server_env_manager server_env(server); server_env_manager server_env(server);
// step 1 - nuke on remote server. // step 1 - nuke on remote server.
@ -57,7 +61,7 @@ int nuke_one(std::string server, std::string service)
service_info = get_service_info(server, service); service_info = get_service_info(server, service);
if (!SIvalid(service_info)) if (!SIvalid(service_info))
std::cerr << "Warning: Invalid service: " << service << std::endl; error << "Invalid service: " << service << std::endl;
if (server_env.check_remote_dir_exists(remotepath::service(server, service))) if (server_env.check_remote_dir_exists(remotepath::service(server, service)))
{ {
@ -65,53 +69,54 @@ int nuke_one(std::string server, std::string service)
// otherwise just uninstall. // otherwise just uninstall.
if (gTemplateManager().template_command_exists(service_info.template_name, "nuke")) if (gTemplateManager().template_command_exists(service_info.template_name, "nuke"))
{ {
std::cout << "Running nuke script for " << service << " on " << server << std::endl; info << "Running nuke script for " << service << " on " << server << std::endl;
if (!server_env.run_remote_template_command(service, "nuke", {}, false, {})) if (!server_env.run_remote_template_command(service, "nuke", {}, false, {}))
std::cerr << "Warning: Failed to run nuke script: " << service << std::endl; warning << "Failed to run nuke script: " << service << std::endl;
} }
else else
{ {
std::cout << "No nuke script found for " << service << " on " << server << std::endl; info << "No nuke script found for " << service << " on " << server << std::endl;
std::cout << "Running uninstall script instead and will clean directories." << std::endl; info << "Running uninstall script instead and will clean directories." << std::endl;
if (!server_env.run_remote_template_command(service, "uninstall", {}, false, {})) if (!server_env.run_remote_template_command(service, "uninstall", {}, false, {}))
std::cerr << "Warning: Failed to uninstall service: " << service << std::endl; warning << "Failed to uninstall service: " << service << std::endl;
} }
// Remove the service directory from the server, running in a docker container as root. // Remove the service directory from the server, running in a docker container as root.
if (server_env.remove_remote_dir(remotepath::service(server, service), true)) if (server_env.remove_remote_dir(remotepath::service(server, service), true))
{ {
ASSERT(!server_env.check_remote_dir_exists(remotepath::service(server, service)), "Service directory still found on server after uninstall"); ASSERT(!server_env.check_remote_dir_exists(remotepath::service(server, service)), "Service directory still found on server after uninstall");
std::cout << "Remote service directory removed: " << remotepath::service(server, service) << std::endl; info << "Remote service directory removed: " << remotepath::service(server, service) << std::endl;
} }
else else
std::cerr << "Warning: Failed to remove remote service directory" << std::endl; warning << "Failed to remove remote service directory" << std::endl;
} }
else else
std::cerr << "Warning: Service not found on remote server: " << remotepath::service(server, service) << std::endl; warning << "Service not found on remote server: " << remotepath::service(server, service) << std::endl;
} }
else else
std::cerr << "Warning: Can't nuke the remote service as the server is invalid: " << server << std::endl; warning << "Can't nuke the remote service as the server is invalid: " << server << std::endl;
// step 2 - nuke the local service directory. // step 2 - nuke the local service directory.
std::string local_service_path = localpath::service(server, service); std::string local_service_path = localpath::service(server, service);
if (local_service_path.empty() || !std::filesystem::exists(local_service_path)) if (local_service_path.empty() || !std::filesystem::exists(local_service_path))
{ {
std::cerr << "Warning: Local service directory not found: " << local_service_path << std::endl; warning << "Local service directory not found: " << local_service_path << std::endl;
} }
else else
{ {
auto itemsdeleted = std::filesystem::remove_all(local_service_path); auto itemsdeleted = std::filesystem::remove_all(local_service_path);
if (itemsdeleted == 0) if (itemsdeleted == 0)
std::cerr << "Error: Failed to remove local service directory" << std::endl; error << "Failed to remove local service directory" << std::endl;
} }
std::cout << "Nuked service " << service << " on server " << server << std::endl; info << "Nuked service " << service << " on server " << server << std::endl;
return 0; return true;
} }
} // namespace shared_commands
int nuke_handler(const CommandContext &ctx) int nuke_handler(const CommandContext &ctx)
{ {
ASSERT(ctx.args.size() == 2, "Usage: nuke SERVER SERVICE|all (requires 2 args - you supplied " + std::to_string(ctx.args.size()) + ")"); ASSERT(ctx.args.size() == 2, "Usage: nuke SERVER SERVICE|all (requires 2 args - you supplied " + std::to_string(ctx.args.size()) + ")");
ASSERT(gConfig().is_config_set(), "No configuration found. Please run 'dropshell config' to set up your configuration."); ASSERT(gConfig().is_config_set(), "No configuration found. Please run 'dropshell config' to set up your configuration.");
@ -126,24 +131,24 @@ int nuke_handler(const CommandContext &ctx)
std::string server_path = localpath::server(server); std::string server_path = localpath::server(server);
if (server_path.empty()) if (server_path.empty())
{ {
std::cerr << "Error: Server not found: " << server << std::endl; error << "Server not found: " << server << std::endl;
return 1; return 1;
} }
for (const auto& entry : std::filesystem::directory_iterator(server_path)) for (const auto &entry : std::filesystem::directory_iterator(server_path))
{ {
if (entry.is_directory() && entry.path().filename().string().find(".") != 0) if (entry.is_directory() && entry.path().filename().string().find(".") != 0)
{ {
std::string service_name = entry.path().filename().string(); std::string service_name = entry.path().filename().string();
rval |= nuke_one(server, service_name); rval |= (shared_commands::nuke_service(server, service_name) ? 0 : 1);
} }
} }
return rval; return rval;
} }
else else
{ {
return nuke_one(server, service); return (shared_commands::nuke_service(server, service) ? 0 : 1);
}
} }
}
} // namespace dropshell } // namespace dropshell

View File

@ -0,0 +1,251 @@
#include <unistd.h>
#include <cstring>
#include <iostream>
#include <sstream>
#include <filesystem>
#include "utils/output.hpp"
#include "utils/assert.hpp"
#include "utils/utils.hpp"
#include "command_registry.hpp"
#include "config.hpp"
#include "services.hpp"
#include "servers.hpp"
#include "server_env_manager.hpp"
#include "templates.hpp"
#include "utils/directories.hpp"
#include "shared_commands.hpp"
namespace dropshell
{
int restoredata_handler(const CommandContext &ctx);
void restoredata_autocomplete(const CommandContext &ctx);
static std::vector<std::string> restoredata_name_list = {"restoredata", "rd", "restore", "rest"};
// Static registration
struct RestoreDataCommandRegister
{
RestoreDataCommandRegister()
{
CommandRegistry::instance().register_command({restoredata_name_list,
restoredata_handler,
restoredata_autocomplete,
false, // hidden
true, // requires_config
true, // requires_install
3, // min_args (after command)
3, // max_args (after command)
"restoredata SERVER SERVICE BACKUP_FILE|latest",
"Restore data for a service on a server, overwriting the existing data.",
// heredoc
R"(
restoredata SERVER SERVICE BACKUP_FILE Restore data to a service on a server. Destructive.
restoredata SERVER SERVICE latest Restore the latest backup for the given service.
Note: This command will not create any service configuration, you need
to have a valid service installed first.
The backup file must be in the local backups directory.
WARNING: This will permanently overwrite the service's data on the remote server!
)"});
}
} restoredata_command_register;
std::vector<shared_commands::cBackupFileName> get_backup_files(const std::string &server, const std::string &match_service = "", const std::string &match_template_name = "")
{
std::string local_backups_dir = gConfig().get_local_backup_path();
if (local_backups_dir.empty() || !std::filesystem::exists(local_backups_dir))
{
error << "Error: Local backups directory not found: " << local_backups_dir << std::endl;
return {};
}
std::vector<shared_commands::cBackupFileName> backups;
for (const auto &entry : std::filesystem::directory_iterator(local_backups_dir))
{
if (!entry.is_regular_file())
continue;
std::string filename = entry.path().filename().string();
shared_commands::cBackupFileName backup_details(filename);
if (backup_details.is_valid())
if (match_service.empty() || backup_details.get_service() == match_service)
if (match_template_name.empty() || backup_details.get_template_name() == match_template_name)
backups.push_back(backup_details);
}
// sort backups by datetime
std::sort(backups.begin(), backups.end(), [](const shared_commands::cBackupFileName &a, const shared_commands::cBackupFileName &b)
{ return a.get_datetime() > b.get_datetime(); });
return backups;
}
int restoredata_handler(const CommandContext &ctx)
{
ASSERT(ctx.args.size() == 3, "Invalid number of arguments");
std::string server = ctx.args[0];
std::string service = ctx.args[1];
std::string backup_arg = ctx.args[2];
server_env_manager server_env(server);
if (!server_env.is_valid())
{
error << "Server " << server << " is not valid" << std::endl;
return 1;
}
LocalServiceInfo service_info = get_service_info(server, service);
if (!SIvalid(service_info))
{
error << "Service " << service << " is not valid" << std::endl;
return 1;
}
std::optional<shared_commands::cBackupFileName> backup_details;
if (backup_arg == "latest")
{ // special case.
std::vector<shared_commands::cBackupFileName> backups = get_backup_files(server, service, service_info.template_name); // this service only (and also match template in case something changed there!).
if (backups.empty())
{
error << "No backups found for " << server << "/" << service << std::endl;
debug << "Template also has to match with the service template: " << service_info.template_name << std::endl;
return 1;
}
backup_details = backups[0];
} else {
backup_details = shared_commands::cBackupFileName(backup_arg);
if (!backup_details->is_valid())
{
error << "Invalid backup file: " << backup_arg << std::endl;
return 1;
}
}
ASSERT(backup_details.has_value() && backup_details->is_valid(), "Invalid backup file.");
std::string local_backups_dir = gConfig().get_local_backup_path();
if (local_backups_dir.empty() || !std::filesystem::exists(local_backups_dir))
{
error << "Error: Local backups directory not found: " << local_backups_dir << std::endl;
return 1;
}
std::string local_backup_file_path = (std::filesystem::path(local_backups_dir) / backup_details->get_filename()).string();
if (!std::filesystem::exists(local_backup_file_path))
{
error << "Error: Backup file not found at " << local_backup_file_path << std::endl;
return 1;
}
if (backup_details->get_template_name() != service_info.template_name)
{
error << "Error: Backup template does not match service template. Can't restore." << std::endl;
debug << "Backup template: " << backup_details->get_template_name() << std::endl;
debug << "Service template: " << service_info.template_name << std::endl;
debug << "Backup file: " << local_backup_file_path << std::endl;
return 1;
}
info << "Restoring " << backup_details->get_datetime() << " backup of " << backup_details->get_service() << " taken from " << backup_details->get_server() << ", onto " << server << "/" << service << std::endl;
info << std::endl;
warning << "*** ALL DATA FOR " << server << "/" << service << " WILL BE OVERWRITTEN! ***" << std::endl;
// run the restore script
info << "OK, here goes..." << std::endl;
{ // backup existing service
info << "1) Backing up old service... " << std::endl;
if (!shared_commands::backupdata_service(server, service))
{
error << "Error: Backup failed, restore aborted." << std::endl;
error << "You can try using dropshell install " << server << " " << service << " to install the service afresh." << std::endl;
error << "Otherwise, stop the service, create and initialise a new one, then restore to that." << std::endl;
return 1;
}
info << "Backup complete." << std::endl;
}
{ // nuke the old service
info << "2) Nuking old service..." << std::endl;
if (!shared_commands::nuke_service(server, service))
return 1;
}
{ // create the new service
info << "3) Creating new service..." << std::endl;
if (!shared_commands::create_service(server, service_info.template_name, service))
return 1;
}
{ // installing fresh service
info << "4) Install of fresh service..." << std::endl;
if (!shared_commands::install_service(server, service))
return 1;
}
{ // restore service from backup
info << "5) Restoring service data from backup..." << std::endl;
std::string remote_backups_dir = remotepath::backups(server);
std::string remote_backup_file_path = remote_backups_dir + "/" + backup_details->get_filename();
// Copy backup file from local to server
if (!shared_commands::scp_file_to_remote(server_env, local_backup_file_path, remote_backup_file_path, false))
{
error << "Failed to copy backup file from local to server" << std::endl;
return 1;
}
shared_commands::cRemoteTempFolder remote_temp_folder(server_env);
server_env.run_remote_template_command(service, "restore", {}, false, {{"BACKUP_FILE", remote_backup_file_path}, {"TEMP_DIR", remote_temp_folder.path()}});
} // dtor of remote_temp_folder will clean up the temp folder on the server
{ // healthcheck the service
info << "5) Healthchecking service..." << std::endl;
std::string green_tick = "\033[32m✓\033[0m";
std::string red_cross = "\033[31m✗\033[0m";
bool healthy = (server_env.run_remote_template_command(service, "status", {}, false, {}));
info << (healthy ? green_tick : red_cross) << " Service is " << (healthy ? "healthy" : "NOT healthy") << std::endl;
}
return 0;
}
void restoredata_autocomplete(const CommandContext &ctx)
{
shared_commands::std_autocomplete(ctx);
if (ctx.args.size() == 2) // next arg is the backup file
{
std::string server = ctx.args[0];
std::string service = ctx.args[1];
LocalServiceInfo service_info = get_service_info(server, service);
if (!SIvalid(service_info))
{
error << "Service " << service << " is not valid" << std::endl;
return;
}
std::string template_name = service_info.template_name;
std::vector<shared_commands::cBackupFileName> backups = get_backup_files(server, "", template_name); // any service, but must match template.
// print most recent backup for each {host,service} pair
std::map<std::string, std::string> unique_backups;
for (const auto &backup : backups)
{
std::string key = backup.get_server() + "-" + backup.get_service();
if (unique_backups.find(key) == unique_backups.end())
unique_backups[key] = backup.get_filename();
}
for (const auto &[key, value] : unique_backups)
rawout << value << std::endl;
}
}
} // namespace dropshell

View File

@ -5,6 +5,7 @@
#include "directories.hpp" #include "directories.hpp"
#include "services.hpp" #include "services.hpp"
#include "servers.hpp" #include "servers.hpp"
#include "utils/output.hpp"
namespace dropshell namespace dropshell
{ {
@ -23,7 +24,7 @@ namespace dropshell
std::vector<ServerInfo> servers = get_configured_servers(); std::vector<ServerInfo> servers = get_configured_servers();
for (const auto &server : servers) for (const auto &server : servers)
{ {
std::cout << server.name << std::endl; rawout << server.name << std::endl;
} }
} }
else if (ctx.args.size() == 1) else if (ctx.args.size() == 1)
@ -32,7 +33,7 @@ namespace dropshell
std::vector<LocalServiceInfo> services = get_server_services_info(ctx.args[0]); std::vector<LocalServiceInfo> services = get_server_services_info(ctx.args[0]);
for (const auto &service : services) for (const auto &service : services)
{ {
std::cout << service.service_name << std::endl; rawout << service.service_name << std::endl;
} }
} }
} }
@ -44,7 +45,7 @@ namespace dropshell
{ {
std_autocomplete(ctx); std_autocomplete(ctx);
if (ctx.args.size() == 1) if (ctx.args.size() == 1)
std::cout << "all" << std::endl; rawout << "all" << std::endl;
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -88,7 +89,7 @@ namespace dropshell
std::string p = remotepath::temp_files(server_env.get_server_name()) + "/" + random_alphanumeric_string(10); std::string p = remotepath::temp_files(server_env.get_server_name()) + "/" + random_alphanumeric_string(10);
std::string mkdir_cmd = "mkdir -p " + quote(p); std::string mkdir_cmd = "mkdir -p " + quote(p);
if (!execute_ssh_command(server_env.get_SSH_INFO(), sCommand("", mkdir_cmd, {}), cMode::Silent)) if (!execute_ssh_command(server_env.get_SSH_INFO(), sCommand("", mkdir_cmd, {}), cMode::Silent))
std::cerr << "Failed to create temp directory on server" << std::endl; error << "Failed to create temp directory on server" << std::endl;
else else
mPath = p; mPath = p;
} }
@ -114,14 +115,12 @@ namespace dropshell
server_env_manager env(server_name); server_env_manager env(server_name);
if (!env.is_valid()) if (!env.is_valid())
{ {
std::cerr << "Error: Invalid server environment" << std::endl; error << "Invalid server environment" << std::endl;
return status; return status;
} }
std::string output; std::string output;
if (!execute_ssh_command(env.get_SSH_INFO(), sCommand(remotepath::agent(server_name), if (!execute_ssh_command(env.get_SSH_INFO(), sCommand(remotepath::agent(server_name), "./_allservicesstatus.sh", {{"HOST_NAME", server_name}, {"SERVER", server_name}, {"AGENT_PATH", remotepath::agent(server_name)}}),
"./_allservicesstatus.sh",
{{"HOST_NAME", server_name}, {"SERVER", server_name}, {"AGENT_PATH", remotepath::agent(server_name)}}),
cMode::CaptureOutput | cMode::Silent, cMode::CaptureOutput | cMode::Silent,
&output)) &output))
return status; return status;
@ -166,8 +165,6 @@ namespace dropshell
return status; return status;
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// healthtick : SHARED COMMAND // healthtick : SHARED COMMAND
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -206,7 +203,6 @@ namespace dropshell
return ":error:"; return ":error:";
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// is_healthy : SHARED COMMAND // is_healthy : SHARED COMMAND
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -215,7 +211,7 @@ namespace dropshell
server_env_manager env(server); server_env_manager env(server);
if (!env.is_valid()) if (!env.is_valid())
{ {
std::cerr << "Error: Server service not initialized" << std::endl; error << "Server service not initialized" << std::endl;
return HealthStatus::ERROR; return HealthStatus::ERROR;
} }
@ -236,7 +232,6 @@ namespace dropshell
return HealthStatus::HEALTHY; return HealthStatus::HEALTHY;
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// healthmark : SHARED COMMAND // healthmark : SHARED COMMAND
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -246,6 +241,91 @@ namespace dropshell
return HealthStatus2String(status); return HealthStatus2String(status);
} }
// ------------------------------------------------------------------------------------------------
// cBackupFileName : SHARED CLASS
// ------------------------------------------------------------------------------------------------
cBackupFileName::cBackupFileName(const std::string &server, const std::string &service, const std::string &template_name)
{
mServer = server;
mService = service;
mTemplateName = template_name;
// Get current datetime for backup filename
auto now = std::chrono::system_clock::now();
auto time = std::chrono::system_clock::to_time_t(now);
std::stringstream datetime;
datetime << std::put_time(std::localtime(&time), "%Y-%m-%d_%H-%M-%S");
mDatetime = datetime.str();
}
cBackupFileName::cBackupFileName(const std::string &filename)
{
// Parse the filename according to the format:
// server + magic_string() + template_name + magic_string() + service + magic_string() + datetime + ".tgz"
std::string name = filename;
if (name.size() > 4 && name.substr(name.size() - 4) == ".tgz")
name = name.substr(0, name.size() - 4);
std::string sep = magic_string();
size_t first = name.find(sep);
size_t second = name.find(sep, first + sep.size());
size_t third = name.find(sep, second + sep.size());
if (first == std::string::npos || second == std::string::npos || third == std::string::npos)
{
mServer = mService = mTemplateName = mDatetime = "";
return;
}
mServer = name.substr(0, first);
mTemplateName = name.substr(first + sep.size(), second - (first + sep.size()));
mService = name.substr(second + sep.size(), third - (second + sep.size()));
mDatetime = name.substr(third + sep.size());
}
std::string cBackupFileName::get_filename() const
{
return mServer + magic_string() + mTemplateName + magic_string() + mService + magic_string() + mDatetime + ".tgz";
}
std::string cBackupFileName::get_server() const { return mServer; }
std::string cBackupFileName::get_service() const { return mService; }
std::string cBackupFileName::get_template_name() const { return mTemplateName; }
std::string cBackupFileName::get_datetime() const { return mDatetime; }
bool cBackupFileName::is_valid() const
{
// All fields must be non-empty, and none may contain the magic string
return !mServer.empty() && !mService.empty() && !mTemplateName.empty() && !mDatetime.empty() &&
!has_magic_string(mServer) && !has_magic_string(mService) && !has_magic_string(mTemplateName);
}
// ------------------------------------------------------------------------------------------------
// scp_file_to_remote : SHARED COMMAND
// ------------------------------------------------------------------------------------------------
bool scp_file_to_remote(const server_env_manager &server_env, const std::string &local_path, const std::string &remote_path, bool silent)
{
if (!server_env.is_valid())
{
error << "Invalid server environment" << std::endl;
return false;
}
ASSERT(!remote_path.empty() && !local_path.empty(), "Remote or local path not specified. Can't scp.");
std::string scp_cmd = "scp -P " + server_env.get_SSH_PORT() + " " + quote(local_path) + " " + server_env.get_SSH_USER() + "@" + server_env.get_SSH_HOST() + ":" + quote(remote_path) + (silent ? " > /dev/null 2>&1" : "");
return execute_local_command("", scp_cmd, {}, nullptr, (silent ? cMode::Silent : cMode::Defaults));
}
// ------------------------------------------------------------------------------------------------
// scp_file_from_remote : SHARED COMMAND
// ------------------------------------------------------------------------------------------------
bool scp_file_from_remote(const server_env_manager &server_env, const std::string &remote_path, const std::string &local_path, bool silent)
{
if (!server_env.is_valid())
{
error << "Invalid server environment" << std::endl;
return false;
}
ASSERT(!remote_path.empty() && !local_path.empty(), "Remote or local path not specified. Can't scp.");
std::string scp_cmd = "scp -P " + server_env.get_SSH_PORT() + " " + server_env.get_SSH_USER() + "@" + server_env.get_SSH_HOST() + ":" + quote(remote_path) + " " + quote(local_path) + (silent ? " > /dev/null 2>&1" : "");
return execute_local_command("", scp_cmd, {}, nullptr, (silent ? cMode::Silent : cMode::Defaults));
}
} // namespace shared_commands } // namespace shared_commands
} // namespace dropshell } // namespace dropshell

View File

@ -57,6 +57,44 @@ namespace dropshell
void std_autocomplete(const CommandContext &ctx); void std_autocomplete(const CommandContext &ctx);
void std_autocomplete_allowall(const CommandContext &ctx); void std_autocomplete_allowall(const CommandContext &ctx);
class cBackupFileName
{
public:
cBackupFileName(const std::string &server, const std::string &service, const std::string &template_name);
cBackupFileName(const std::string &filename);
std::string get_filename() const;
std::string get_server() const;
std::string get_service() const;
std::string get_template_name() const;
std::string get_datetime() const;
bool is_valid() const;
private:
std::string mServer;
std::string mService;
std::string mTemplateName;
std::string mDatetime;
};
bool scp_file_to_remote(const server_env_manager &server_env, const std::string &local_path, const std::string &remote_path, bool silent);
bool scp_file_from_remote(const server_env_manager &server_env, const std::string &remote_path, const std::string &local_path, bool silent);
// defined in backupdata.cpp, used by restoredata.cpp.
bool backupdata_service(const std::string& server, const std::string& service);
// defined in uninstall.cpp
bool uninstall_service(const std::string &server, const std::string &service);
// defined in nuke.cpp
bool nuke_service(const std::string &server, const std::string &service);
// defined in install.cpp
bool install_service(const std::string &server, const std::string &service);
// defined in create-service.cpp
bool create_service(const std::string &server_name, const std::string &template_name, const std::string &service_name);
} // namespace shared_commands } // namespace shared_commands
} // namespace dropshell } // namespace dropshell

View File

@ -45,7 +45,7 @@ namespace dropshell
server_env_manager server_env(server); server_env_manager server_env(server);
if (!server_env.is_valid()) if (!server_env.is_valid())
{ {
std::cerr << "Error: Server " << server << " is not valid" << std::endl; error << "Server " << server << " is not valid" << std::endl;
return false; return false;
} }
execute_ssh_command(server_env.get_SSH_INFO(), sCommand(remotepath::DROPSHELL_DIR(server), "ls --color && bash", {}), cMode::Interactive); execute_ssh_command(server_env.get_SSH_INFO(), sCommand(remotepath::DROPSHELL_DIR(server), "ls --color && bash", {}), cMode::Interactive);
@ -57,26 +57,26 @@ namespace dropshell
server_env_manager server_env(server); server_env_manager server_env(server);
if (!server_env.is_valid()) if (!server_env.is_valid())
{ {
std::cerr << "Error: Server " << server << " is not valid" << std::endl; error << "Server " << server << " is not valid" << std::endl;
return false; return false;
} }
LocalServiceInfo sinfo = get_service_info(server, service); LocalServiceInfo sinfo = get_service_info(server, service);
if (!SIvalid(sinfo)) if (!SIvalid(sinfo))
{ {
std::cerr << "Error: Service " << service << " is not valid" << std::endl; error << "Service " << service << " is not valid" << std::endl;
return false; return false;
} }
if (!gTemplateManager().has_template(sinfo.template_name)) if (!gTemplateManager().has_template(sinfo.template_name))
{ {
std::cerr << "Error: Template " << sinfo.template_name << " is not valid" << std::endl; error << "Template " << sinfo.template_name << " is not valid" << std::endl;
return false; return false;
} }
if (!gTemplateManager().template_command_exists(sinfo.template_name, "ssh")) if (!gTemplateManager().template_command_exists(sinfo.template_name, "ssh"))
{ {
std::cerr << "Error: Template " << sinfo.template_name << " does not have an ssh command" << std::endl; error << "Template " << sinfo.template_name << " does not have an ssh command" << std::endl;
return false; return false;
} }
@ -88,7 +88,7 @@ namespace dropshell
{ {
if (ctx.args.size() < 1) if (ctx.args.size() < 1)
{ {
std::cerr << "Error: Server name is required" << std::endl; error << "Server name is required" << std::endl;
return 1; return 1;
} }

View File

@ -6,6 +6,7 @@
#include "server_env_manager.hpp" #include "server_env_manager.hpp"
#include "services.hpp" #include "services.hpp"
#include "servers.hpp" #include "servers.hpp"
#include "utils/output.hpp"
namespace dropshell namespace dropshell
{ {
@ -46,7 +47,7 @@ namespace dropshell
server_env_manager server_env(server); server_env_manager server_env(server);
if (!server_env.is_valid()) if (!server_env.is_valid())
{ {
std::cerr << "Error: Server " << server << " is not valid" << std::endl; error << "Server " << server << " is not valid" << std::endl;
return false; return false;
} }
@ -55,10 +56,10 @@ namespace dropshell
if (started) if (started)
{ {
std::cout << "Service " << service << " on server " << server << " started." << std::endl; info << "Service " << service << " on server " << server << " started." << std::endl;
return true; return true;
} }
std::cerr << "Error: Failed to start service " << service << " on server " << server << std::endl; error << "Failed to start service " << service << " on server " << server << std::endl;
return false; return false;
} }

View File

@ -6,6 +6,7 @@
#include "server_env_manager.hpp" #include "server_env_manager.hpp"
#include "services.hpp" #include "services.hpp"
#include "servers.hpp" #include "servers.hpp"
#include "utils/output.hpp"
namespace dropshell namespace dropshell
{ {
@ -46,7 +47,7 @@ namespace dropshell
server_env_manager server_env(server); server_env_manager server_env(server);
if (!server_env.is_valid()) if (!server_env.is_valid())
{ {
std::cerr << "Error: Server " << server << " is not valid" << std::endl; error << "Server " << server << " is not valid" << std::endl;
return false; return false;
} }
@ -55,10 +56,10 @@ namespace dropshell
if (stopped) if (stopped)
{ {
std::cout << "Service " << service << " on server " << server << " stopped." << std::endl; info << "Service " << service << " on server " << server << " stopped." << std::endl;
return true; return true;
} }
std::cerr << "Error: Failed to stop service " << service << " on server " << server << std::endl; error << "Failed to stop service " << service << " on server " << server << std::endl;
return false; return false;
} }
@ -66,7 +67,7 @@ namespace dropshell
{ {
if (ctx.args.size() < 2) if (ctx.args.size() < 2)
{ {
std::cerr << "Error: Server name and service name are both required" << std::endl; error << "Server name and service name are both required" << std::endl;
return 1; return 1;
} }

View File

@ -41,51 +41,49 @@ namespace dropshell
} }
} uninstall_command_register; } uninstall_command_register;
bool uninstall_service(const std::string &server, const std::string &service, bool silent = false) namespace shared_commands {
bool uninstall_service(const std::string &server, const std::string &service)
{ {
if (!silent)
maketitle("Uninstalling " + service + " on " + server); maketitle("Uninstalling " + service + " on " + server);
server_env_manager server_env(server); server_env_manager server_env(server);
if (!server_env.is_valid()) if (!server_env.is_valid())
{ {
std::cerr << "Invalid server: " << server << std::endl; error << "Invalid server: " << server << std::endl;
return false; // should never hit this. return false; // should never hit this.
} }
// 2. Check if service directory exists on server // 2. Check if service directory exists on server
if (!server_env.check_remote_dir_exists(remotepath::service(server, service))) if (!server_env.check_remote_dir_exists(remotepath::service(server, service)))
{ {
std::cerr << "Service is not installed: " << service << std::endl; error << "Service is not installed: " << service << std::endl;
return true; // Nothing to uninstall return true; // Nothing to uninstall
} }
// 3. Run uninstall script if it exists // 3. Run uninstall script if it exists
std::string uninstall_script = remotepath::service_template(server, service) + "/uninstall.sh"; std::string uninstall_script = remotepath::service_template(server, service) + "/uninstall.sh";
if (!server_env.run_remote_template_command(service, "uninstall", {}, silent, {})) if (!server_env.run_remote_template_command(service, "uninstall", {}, false, {}))
if (!silent) warning << "Uninstall script failed, but continuing with directory removal" << std::endl;
std::cerr << "Warning: Uninstall script failed, but continuing with directory removal" << std::endl;
// 4. Remove the service directory from the server, running in a docker container as root. // 4. Remove the service directory from the server, running in a docker container as root.
if (server_env.remove_remote_dir(remotepath::service(server, service), silent)) if (server_env.remove_remote_dir(remotepath::service(server, service), false))
{ {
ASSERT(!server_env.check_remote_dir_exists(remotepath::service(server, service)), "Service directory still found on server after uninstall"); ASSERT(!server_env.check_remote_dir_exists(remotepath::service(server, service)), "Service directory still found on server after uninstall");
if (!silent) info << "Removed remote service directory " << remotepath::service(server, service) << std::endl;
std::cout << "Removed remote service directory " << remotepath::service(server, service) << std::endl;
} }
else if (!silent) else
std::cerr << "Warning: Failed to remove remote service directory" << std::endl; warning << "Failed to remove remote service directory" << std::endl;
if (!silent) info << "Completed service " << service << " uninstall on " << server << std::endl;
std::cout << "Completed service " << service << " uninstall on " << server << std::endl;
return true; return true;
} }
} // namespace shared_commands
int uninstall_handler(const CommandContext &ctx) int uninstall_handler(const CommandContext &ctx)
{ {
if (ctx.args.size() < 1) if (ctx.args.size() < 1)
{ {
std::cerr << "Error: uninstall requires a server and a service (or all)" << std::endl; error << "uninstall requires a server and a service (or all)" << std::endl;
return 1; return 1;
} }
@ -98,14 +96,14 @@ namespace dropshell
std::vector<LocalServiceInfo> services = get_server_services_info(server); std::vector<LocalServiceInfo> services = get_server_services_info(server);
for (const auto &service : services) for (const auto &service : services)
{ {
if (!uninstall_service(server, service.service_name)) if (!shared_commands::uninstall_service(server, service.service_name))
okay = false; okay = false;
} }
return okay ? 0 : 1; return okay ? 0 : 1;
} }
std::string service = safearg(ctx.args, 1); std::string service = safearg(ctx.args, 1);
return uninstall_service(server, service) ? 0 : 1; return shared_commands::uninstall_service(server, service) ? 0 : 1;
} }
} // namespace dropshell } // namespace dropshell

View File

@ -6,6 +6,9 @@
#include "utils/json.hpp" #include "utils/json.hpp"
#include <filesystem> #include <filesystem>
#include "utils/execute.hpp" #include "utils/execute.hpp"
#include "output.hpp"
namespace dropshell { namespace dropshell {
@ -150,7 +153,7 @@ std::vector<std::string> config::get_local_server_definition_paths() {
if (path.is_string() && !path.empty()) if (path.is_string() && !path.empty())
paths.push_back(path); paths.push_back(path);
else else
std::cerr << "Warning: Invalid server definition path: " << path << std::endl; warning << "Invalid server definition path: " << path << std::endl;
} }
return paths; return paths;
} }

View File

@ -50,33 +50,33 @@ int main(int argc, char* argv[]) {
return 0; return 0;
} }
const CommandInfo* info = CommandRegistry::instance().find_command(ctx.command); const CommandInfo* cmdinfo = CommandRegistry::instance().find_command(ctx.command);
if (!info) { if (!cmdinfo) {
std::cerr << "Unknown command: " << ctx.command << std::endl; error << "Unknown command: " << ctx.command << std::endl;
return 1; return 1;
} }
if (info->requires_config && !gConfig().is_config_set()) { if (cmdinfo->requires_config && !gConfig().is_config_set()) {
std::cerr << "Valid dropshell configuration required for command: " << ctx.command << std::endl; error << "Valid dropshell configuration required for command: " << ctx.command << std::endl;
std::cerr << "Please run 'dropshell edit' to set up the dropshell configuration." << std::endl; info << "Please run 'dropshell edit' to set up the dropshell configuration." << std::endl;
return 1; return 1;
} }
if (info->requires_install && !gConfig().is_agent_installed()) { if (cmdinfo->requires_install && !gConfig().is_agent_installed()) {
std::cerr << "Dropshell agent not installed for command: " << ctx.command << std::endl; error << "Dropshell agent not installed for command: " << ctx.command << std::endl;
std::cerr << "Please run 'dropshell install' to install the local dropshell agent." << std::endl; info << "Please run 'dropshell install' to install the local dropshell agent." << std::endl;
return 1; return 1;
} }
int arg_count = ctx.args.size(); int arg_count = ctx.args.size();
if (arg_count < info->min_args || (info->max_args != -1 && arg_count > info->max_args)) { if (arg_count < cmdinfo->min_args || (cmdinfo->max_args != -1 && arg_count > cmdinfo->max_args)) {
std::cerr << "Invalid number of arguments for command: " << ctx.command << std::endl; error << "Invalid number of arguments for command: " << ctx.command << std::endl;
std::cerr << "(" << ctx.args.size() << " args provided, " << ctx.command << " requires " << (info->min_args) << " to " << (info->max_args) << " args)" << std::endl; debug << "(" << ctx.args.size() << " args provided, " << ctx.command << " requires " << (cmdinfo->min_args) << " to " << (cmdinfo->max_args) << " args)" << std::endl;
std::cerr << "Usage: " << std::endl; info << "Usage: " << std::endl;
std::cerr << " "; info << " ";
print_left_aligned(info->help_usage,30); info << left_align(cmdinfo->help_usage,30);
std::cout << info->help_description << std::endl; info << cmdinfo->help_description << std::endl;
return 1; return 1;
} }
return info->handler(ctx); return cmdinfo->handler(ctx);
} }
catch (const std::exception& e) { catch (const std::exception& e) {
@ -116,13 +116,6 @@ bool getCLIServices(const std::string & arg2, const std::string & arg3,
return true; return true;
} }
void printversion() {
maketitle("DropShell version " + VERSION);
std::cout << "Release date: " << RELEASE_DATE << std::endl;
std::cout << "Author: " << AUTHOR << std::endl;
std::cout << "License: " << LICENSE << std::endl;
}
auto command_match = [](const std::string& cmd_list, int argc, char* argv[]) -> bool { auto command_match = [](const std::string& cmd_list, int argc, char* argv[]) -> bool {
std::istringstream iss(cmd_list); std::istringstream iss(cmd_list);
std::string cmd_item; std::string cmd_item;

View File

@ -91,7 +91,6 @@ namespace fs = std::filesystem;
namespace dropshell { namespace dropshell {
static const std::string magic_string = "-_-";
service_runner::service_runner(const std::string& server_name, const std::string& service_name) : service_runner::service_runner(const std::string& server_name, const std::string& service_name) :
mServerEnv(server_name), mServer(server_name), mService(service_name), mValid(false) mServerEnv(server_name), mServer(server_name), mService(service_name), mValid(false)
@ -122,12 +121,12 @@ bool service_runner::nuke(bool silent)
std::string remote_service_path = remotepath::service(mServer, mService); std::string remote_service_path = remotepath::service(mServer, mService);
std::cout << "Service " << mService << " successfully nuked from " << mServer << std::endl; info << "Service " << mService << " successfully nuked from " << mServer << std::endl;
if (!silent) { if (!silent) {
std::cout << "There's nothing left on the remote server." << std::endl; info << "There's nothing left on the remote server." << std::endl;
std::cout << "You can remove the local files with:" << std::endl; info << "You can remove the local files with:" << std::endl;
std::cout << " rm -rf " << localpath::service(mServer,mService) << std::endl; info << " rm -rf " << localpath::service(mServer,mService) << std::endl;
} }
return true; return true;
} }
@ -136,19 +135,19 @@ bool service_runner::fullnuke()
{ {
if (!nuke(true)) if (!nuke(true))
{ {
std::cerr << "Warning: Nuke script failed, aborting fullnuke!" << std::endl; warning << "Nuke script failed, aborting." << std::endl;
return false; return false;
} }
std::string local_service_path = mServiceInfo.local_service_path; std::string local_service_path = mServiceInfo.local_service_path;
if (local_service_path.empty() || !fs::exists(local_service_path)) { if (local_service_path.empty() || !fs::exists(local_service_path)) {
std::cerr << "Error: Service directory not found: " << local_service_path << std::endl; error << "Service directory not found: " << local_service_path << std::endl;
return false; return false;
} }
std::string rm_cmd = "rm -rf " + quote(local_service_path); std::string rm_cmd = "rm -rf " + quote(local_service_path);
if (!execute_local_command("", rm_cmd, {}, nullptr, cMode::Silent)) { if (!execute_local_command("", rm_cmd, {}, nullptr, cMode::Silent)) {
std::cerr << "Failed to remove service directory" << std::endl; error << "Failed to remove service directory" << std::endl;
return false; return false;
} }
@ -298,7 +297,7 @@ bool service_runner::restore(std::string backup_file, bool silent)
} }
// split the backup filename into parts based on the magic string // split the backup filename into parts based on the magic string
std::vector<std::string> parts = dropshell::split(backup_file, magic_string); std::vector<std::string> parts = dropshell::split(backup_file, "-_-");
if (parts.size() != 4) { if (parts.size() != 4) {
std::cerr << "Error: Backup file format is incompatible, - in one of the names?" << std::endl; std::cerr << "Error: Backup file format is incompatible, - in one of the names?" << std::endl;
return false; return false;
@ -383,12 +382,6 @@ bool service_runner::restore(std::string backup_file, bool silent)
} }
bool name_breaks_backups(std::string name)
{
// if name contains -_-, return true
return name.find("-_-") != std::string::npos;
}
// backup the service over ssh, using the credentials from server.env (via server_env.hpp) // backup the service over ssh, using the credentials from server.env (via server_env.hpp)
// 1. run backup.sh on the server // 1. run backup.sh on the server
// 2. create a backup file with format server-service-datetime.tgz // 2. create a backup file with format server-service-datetime.tgz
@ -452,17 +445,18 @@ bool service_runner::backup(bool silent) {
std::stringstream datetime; std::stringstream datetime;
datetime << std::put_time(std::localtime(&time), "%Y-%m-%d_%H-%M-%S"); datetime << std::put_time(std::localtime(&time), "%Y-%m-%d_%H-%M-%S");
if (name_breaks_backups(mServer)) {std::cerr << "Error: Server name contains invalid character sequence ( -_- ) that would break backup naming scheme" << std::endl; return 1;}
if (name_breaks_backups(mService)) {std::cerr << "Error: Service name contains invalid character sequence ( -_- ) that would break backup naming scheme" << std::endl; return 1;}
if (name_breaks_backups(service_info.template_name)) {std::cerr << "Error: Service template name contains invalid character sequence ( -_- ) that would break backup naming scheme" << std::endl; return 1;}
// Construct backup filename // Construct backup filename
std::string backup_filename = mServer + magic_string + service_info.template_name + magic_string + mService + magic_string + datetime.str() + ".tgz"; shared_commands::cBackupFileName backup_filename_construction(mServer, mService, service_info.template_name);
if (!backup_filename_construction.is_valid()) {
std::cerr << "Invalid backup filename" << std::endl;
return false;
}
std::string backup_filename = backup_filename_construction.get_filename();
std::string remote_backup_file_path = remote_backups_dir + "/" + backup_filename; std::string remote_backup_file_path = remote_backups_dir + "/" + backup_filename;
std::string local_backup_file_path = (std::filesystem::path(local_backups_dir) / backup_filename).string(); std::string local_backup_file_path = (std::filesystem::path(local_backups_dir) / backup_filename).string();
// assert that the backup filename is valid - -_- appears exactly 3 times in local_backup_file_path. // assert that the backup filename is valid - -_- appears exactly 3 times in local_backup_file_path.
ASSERT(3 == count_substring(magic_string, local_backup_file_path), "Invalid backup filename"); ASSERT(3 == count_substring("-_-", local_backup_file_path), "Invalid backup filename");
{ // Run backup script { // Run backup script
shared_commands::cRemoteTempFolder remote_temp_folder(mServerEnv); shared_commands::cRemoteTempFolder remote_temp_folder(mServerEnv);
@ -501,7 +495,7 @@ std::string service_runner::get_latest_backup_file(const std::string& server, co
} }
// Build the expected prefix for backup files // Build the expected prefix for backup files
std::string prefix = server + magic_string + info.template_name + magic_string + service + magic_string; std::string prefix = server + "-_-" + info.template_name + "-_-" + service + "-_-";
std::string latest_file; std::string latest_file;
std::string latest_datetime; std::string latest_datetime;

View File

@ -47,7 +47,7 @@ std::vector<LocalServiceInfo> get_server_services_info(const std::string& server
if (!service.local_service_path.empty()) if (!service.local_service_path.empty())
services.push_back(service); services.push_back(service);
else else
std::cerr << "Warning: Failed to get service info for " << dirname << " on server " << server_name << std::endl; warning << "Failed to get service info for " << dirname << " on server " << server_name << std::endl;
} }
} // end of for } // end of for
} }
@ -188,7 +188,7 @@ bool get_all_service_env_vars(const std::string &server_name, const std::string
all_env_vars.merge(env_vars); all_env_vars.merge(env_vars);
} }
else else
std::cout << "Warning: Expected environment file not found: " << file << std::endl; warning << "Expected environment file not found: " << file << std::endl;
}; };
// Load environment files // Load environment files
@ -198,11 +198,10 @@ bool get_all_service_env_vars(const std::string &server_name, const std::string
// determine template name. // determine template name.
auto it = all_env_vars.find("TEMPLATE"); auto it = all_env_vars.find("TEMPLATE");
if (it == all_env_vars.end()) { if (it == all_env_vars.end()) {
std::cerr << std::endl << std::endl; error << "TEMPLATE variable not defined in service " << service_name << " on server " << server_name << std::endl;
std::cerr << "Error: TEMPLATE variable not defined in service " << service_name << " on server " << server_name << std::endl; info << "The TEMPLATE variable is required to determine the template name." << std::endl;
std::cerr << "The TEMPLATE variable is required to determine the template name." << std::endl; info << "Please check the service.env file and the .template_info.env file in:" << std::endl;
std::cerr << "Please check the service.env file and the .template_info.env file in:" << std::endl; info << " " << localpath::service(server_name, service_name) << std::endl << std::endl;
std::cerr << " " << localpath::service(server_name, service_name) << std::endl << std::endl;
return false; return false;
} }
template_info tinfo = gTemplateManager().get_template_info(it->second); template_info tinfo = gTemplateManager().get_template_info(it->second);

View File

@ -1,10 +1,13 @@
#include "directories.hpp" #include "directories.hpp"
#include "config.hpp" #include "config.hpp"
#include "server_env_manager.hpp" #include "server_env_manager.hpp"
#include "output.hpp"
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <filesystem> #include <filesystem>
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace dropshell { namespace dropshell {
@ -78,7 +81,7 @@ namespace localpath {
std::filesystem::path homedir_path(homedir); std::filesystem::path homedir_path(homedir);
return fs::canonical(homedir_path).string(); return fs::canonical(homedir_path).string();
} }
std::cerr << "Warning: Couldn't determine user directory" << std::endl; warning << "Couldn't determine user directory" << std::endl;
return std::string(); return std::string();
} }
} // namespace localpath } // namespace localpath

View File

@ -11,7 +11,8 @@ namespace dropshell
constexpr const char *GREY = "\033[90m"; constexpr const char *GREY = "\033[90m";
constexpr const char *RESET = "\033[0m"; constexpr const char *RESET = "\033[0m";
constexpr const char *DEBUG_COLOUR = "\033[36m"; // Cyan constexpr const char *DEBUG_COLOUR = "\033[36m"; // Cyan
constexpr const char *INFO_COLOUR = "\033[32m"; // Green // constexpr const char *INFO_COLOUR = "\033[32m"; // Green
constexpr const char *INFO_COLOUR = "\033[37m"; // White
constexpr const char *WARNING_COLOUR = "\033[33m"; // Yellow constexpr const char *WARNING_COLOUR = "\033[33m"; // Yellow
constexpr const char *ERROR_COLOUR = "\033[31m"; // Red constexpr const char *ERROR_COLOUR = "\033[31m"; // Red
@ -77,6 +78,9 @@ namespace dropshell
std::ostream &warning = warning_stream; std::ostream &warning = warning_stream;
std::ostream &error = error_stream; std::ostream &error = error_stream;
std::ostream &rawout = std::cout;
std::ostream &rawerr = std::cerr;
std::ostream &colourstream(sColour colour) std::ostream &colourstream(sColour colour)
{ {
switch (colour) switch (colour)

View File

@ -56,6 +56,9 @@ extern std::ostream& info;
extern std::ostream& warning; extern std::ostream& warning;
extern std::ostream& error; extern std::ostream& error;
extern std::ostream& rawout;
extern std::ostream& rawerr;
// Enum for colours // Enum for colours
enum class sColour { enum class sColour {
RESET, RESET,

View File

@ -9,6 +9,8 @@
#include <iostream> #include <iostream>
#include <map> #include <map>
#include "output.hpp"
enum kTextColors { enum kTextColors {
kTextColor_Default, kTextColor_Default,
kTextColor_Red, kTextColor_Red,
@ -32,7 +34,7 @@ const std::map<std::string, coloredText> kReplacements = {
{":tick:", {"+", kTextColor_Green}}, {":tick:", {"+", kTextColor_Green}},
{":cross:", {"x", kTextColor_Red}}, {":cross:", {"x", kTextColor_Red}},
{":warning:", {"!", kTextColor_Yellow}}, {":warning:", {"!", kTextColor_Yellow}},
{":info:", {"i", kTextColor_Blue}}, {":dropshell::info:", {"i", kTextColor_Blue}},
{":check:", {"+", kTextColor_Green}}, {":check:", {"+", kTextColor_Green}},
{":x:", {"x", kTextColor_Red}}, {":x:", {"x", kTextColor_Red}},
{":error:", {"!", kTextColor_Red}}, {":error:", {"!", kTextColor_Red}},
@ -115,12 +117,12 @@ std::string width_print_centered(std::string str,int width, std::string rowcolor
oss << rowcolor << std::string(lpad, ' ') << process_cell(str, rowcolor) << oss << rowcolor << std::string(lpad, ' ') << process_cell(str, rowcolor) <<
std::string(rpad, ' ') << "\033[0m"; std::string(rpad, ' ') << "\033[0m";
// std::cout << "str = "<<str <<std::endl; // dropshell::info << "str = "<<str <<std::endl;
// std::cout << "width = "<<width <<std::endl; // dropshell::info << "width = "<<width <<std::endl;
// std::cout << "padding = "<<padding <<std::endl; // dropshell::info << "padding = "<<padding <<std::endl;
// std::cout << "get_visible_length(str) = "<<get_visible_length(str) <<std::endl; // dropshell::info << "get_visible_length(str) = "<<get_visible_length(str) <<std::endl;
// std::cout << "get_codepoints(str) = "<<get_codepoints(str) <<std::endl; // dropshell::info << "get_codepoints(str) = "<<get_codepoints(str) <<std::endl;
// std::cout << "oss.str() = ["<<oss.str() <<"]"<<std::endl; // dropshell::info << "oss.str() = ["<<oss.str() <<"]"<<std::endl;
return oss.str(); return oss.str();
} }
@ -195,98 +197,105 @@ void tableprint::print() {
// Print title if it exists // Print title if it exists
if (!title.empty()) { if (!title.empty()) {
std::cout << "\033[90m"; // Dark grey color for borders dropshell::info << "\033[90m"; // Dark grey color for borders
std::cout << "+"; dropshell::info << "+";
for (size_t i = 0; i < rows[0].size(); ++i) { for (size_t i = 0; i < rows[0].size(); ++i) {
std::cout << std::string(col_widths[i] + 2, '-'); dropshell::info << std::string(col_widths[i] + 2, '-');
if (i < rows[0].size() - 1) std::cout << "-"; if (i < rows[0].size() - 1) dropshell::info << "-";
} }
std::cout << "+" << std::endl; dropshell::info << "+" << std::endl;
std::cout << "|"; // White color for title dropshell::info << "\033[90m"; // Dark grey color for borders
dropshell::info << "|"; // White color for title
size_t title_width = 0; size_t title_width = 0;
for (size_t width : col_widths) { for (size_t width : col_widths) {
title_width += width + 2; // +2 for padding title_width += width + 2; // +2 for padding
} }
title_width += col_widths.size() - 1; // Add space for vertical borders title_width += col_widths.size() - 1; // Add space for vertical borders
std::cout << width_print_centered(title,title_width,"\033[1;37m"); dropshell::info << width_print_centered(title,title_width,"\033[1;37m");
std::cout << "\033[90m|" << std::endl; dropshell::info << "\033[90m|" << std::endl;
// Use └─┴─┘ for bottom of title box to connect with table // Use └─┴─┘ for bottom of title box to connect with table
std::cout << "+"; dropshell::info << "\033[90m"; // Dark grey color for borders
dropshell::info << "+";
for (size_t i = 0; i < rows[0].size(); ++i) { for (size_t i = 0; i < rows[0].size(); ++i) {
std::cout << std::string(col_widths[i] + 2, '-'); dropshell::info << std::string(col_widths[i] + 2, '-');
if (i < rows[0].size() - 1) std::cout << "-"; if (i < rows[0].size() - 1) dropshell::info << "-";
} }
std::cout << "+" << std::endl; dropshell::info << "+" << std::endl;
} else { } else {
// Print top border if no title // Print top border if no title
std::cout << "\033[90m"; // Dark grey color for borders dropshell::info << "\033[90m"; // Dark grey color for borders
std::cout << "+"; dropshell::info << "+";
for (size_t i = 0; i < rows[0].size(); ++i) { for (size_t i = 0; i < rows[0].size(); ++i) {
std::cout << std::string(col_widths[i] + 2, '-'); dropshell::info << std::string(col_widths[i] + 2, '-');
if (i < rows[0].size() - 1) std::cout << "+"; if (i < rows[0].size() - 1) dropshell::info << "+";
} }
std::cout << "+" << std::endl; dropshell::info << "+" << std::endl;
} }
// Print header // Print header
std::cout << "|"; dropshell::info << "\033[90m"; // Dark grey color for borders
dropshell::info << "|";
for (size_t i = 0; i < rows[0].size(); ++i) { for (size_t i = 0; i < rows[0].size(); ++i) {
std::cout << width_print_centered(rows[0][i],col_widths[i]+2,"\033[1;36m"); dropshell::info << width_print_centered(rows[0][i],col_widths[i]+2,"\033[1;36m");
if (i < rows[0].size() - 1) { if (i < rows[0].size() - 1) {
std::cout << "\033[90m|\033[1;36m"; // Border color then back to cyan dropshell::info << "\033[90m|\033[1;36m"; // Border color then back to cyan
} else { } else {
std::cout << "\033[90m|"; // Just border color for last column dropshell::info << "\033[90m|"; // Just border color for last column
} }
} }
std::cout << std::endl; dropshell::info << std::endl;
// Print header separator // Print header separator
if (!mCompact) { if (!mCompact) {
std::cout << "+"; dropshell::info << "\033[90m"; // Dark grey color for borders
dropshell::info << "+";
for (size_t i = 0; i < rows[0].size(); ++i) { for (size_t i = 0; i < rows[0].size(); ++i) {
for (size_t j = 0; j < col_widths[i] + 2; ++j) { for (size_t j = 0; j < col_widths[i] + 2; ++j) {
std::cout << "-"; dropshell::info << "-";
} }
if (i < rows[0].size() - 1) std::cout << "+"; if (i < rows[0].size() - 1) dropshell::info << "+";
} }
std::cout << "+" << std::endl; dropshell::info << "+" << std::endl;
} }
// Print rows // Print rows
for (size_t row_idx = 1; row_idx < rows.size(); ++row_idx) { for (size_t row_idx = 1; row_idx < rows.size(); ++row_idx) {
const auto& row = rows[row_idx]; const auto& row = rows[row_idx];
std::cout << "|"; dropshell::info << "\033[90m"; // Dark grey color for borders
dropshell::info << "|";
for (size_t i = 0; i < row.size(); ++i) { for (size_t i = 0; i < row.size(); ++i) {
// Set the appropriate color for the row // Set the appropriate color for the row
std::string rowcolor = (row_idx % 2 == 1) ? "\033[38;5;142m" : "\033[38;5;250m"; std::string rowcolor = (row_idx % 2 == 1) ? "\033[38;5;142m" : "\033[38;5;250m";
std::cout << width_print_left(row[i],col_widths[i]+2,rowcolor); dropshell::info << width_print_left(row[i],col_widths[i]+2,rowcolor);
std::cout << "\033[90m" << "|"; dropshell::info << "\033[90m" << "|";
} }
std::cout << std::endl; dropshell::info << std::endl;
// Print row separator if not the last row // Print row separator if not the last row
if (row_idx < rows.size() - 1 && !mCompact) { if (row_idx < rows.size() - 1 && !mCompact) {
std::cout << "+"; dropshell::info << "\033[90m"; // Dark grey color for borders
dropshell::info << "+";
for (size_t i = 0; i < rows[0].size(); ++i) { for (size_t i = 0; i < rows[0].size(); ++i) {
for (size_t j = 0; j < col_widths[i] + 2; ++j) { for (size_t j = 0; j < col_widths[i] + 2; ++j) {
std::cout << "-"; dropshell::info << "-";
} }
if (i < rows[0].size() - 1) std::cout << "+"; if (i < rows[0].size() - 1) dropshell::info << "+";
} }
std::cout << "+" << std::endl; dropshell::info << "+" << std::endl;
} }
} }
// Print bottom border // Print bottom border
std::cout << "+"; dropshell::info << "\033[90m"; // Dark grey color for borders
dropshell::info << "+";
for (size_t i = 0; i < rows[0].size(); ++i) { for (size_t i = 0; i < rows[0].size(); ++i) {
for (size_t j = 0; j < col_widths[i] + 2; ++j) { for (size_t j = 0; j < col_widths[i] + 2; ++j) {
std::cout << "-"; dropshell::info << "-";
} }
if (i < rows[0].size() - 1) std::cout << "+"; if (i < rows[0].size() - 1) dropshell::info << "+";
} }
std::cout << "+" << "\033[0m" << std::endl; // Reset color dropshell::info << "+" << "\033[0m" << std::endl; // Reset color
} }

View File

@ -10,6 +10,16 @@
namespace dropshell { namespace dropshell {
std::string magic_string() {
return "-_-";
}
bool has_magic_string(std::string name)
{
return name.find(magic_string()) != std::string::npos;
}
void maketitle(const std::string& title, sColour colour) { void maketitle(const std::string& title, sColour colour) {
colourstream(colour) << std::string(title.length() + 4, '-') << std::endl; colourstream(colour) << std::string(title.length() + 4, '-') << std::endl;
colourstream(colour) << "| " << title << " |" << std::endl; colourstream(colour) << "| " << title << " |" << std::endl;
@ -334,20 +344,6 @@ std::string safearg(int argc, char *argv[], int index)
return argv[index]; return argv[index];
} }
void print_left_aligned(const std::string & str, int width) {
std::cout << left_align(str, width);
}
void print_centered(const std::string & str, int width) {
std::cout << center_align(str, width);
}
void print_right_aligned(const std::string & str, int width) {
std::cout << right_align(str, width);
}
std::string left_align(const std::string & str, int width) { std::string left_align(const std::string & str, int width) {
if (static_cast<int>(str.size()) >= width) if (static_cast<int>(str.size()) >= width)
return str; return str;

View File

@ -16,6 +16,8 @@ void maketitle(const std::string& title, sColour colour=sColour::INFO);
bool replace_line_in_file(const std::string& file_path, const std::string& search_string, const std::string& replacement_line); bool replace_line_in_file(const std::string& file_path, const std::string& search_string, const std::string& replacement_line);
std::string magic_string();
bool has_magic_string(std::string name);
// utility functions // utility functions
std::string trim(std::string str); std::string trim(std::string str);
@ -47,10 +49,6 @@ int die(const std::string & msg);
std::string safearg(int argc, char *argv[], int index); std::string safearg(int argc, char *argv[], int index);
std::string safearg(const std::vector<std::string> & args, int index); std::string safearg(const std::vector<std::string> & args, int index);
void print_left_aligned(const std::string & str, int width);
void print_centered(const std::string & str, int width);
void print_right_aligned(const std::string & str, int width);
std::string left_align(const std::string & str, int width); std::string left_align(const std::string & str, int width);
std::string right_align(const std::string & str, int width); std::string right_align(const std::string & str, int width);
std::string center_align(const std::string & str, int width); std::string center_align(const std::string & str, int width);