dropshell/source/src/servers.cpp
Your Name ddc57173cb
Some checks failed
Dropshell Test / Build_and_Test (push) Failing after 11s
.
2025-05-24 19:27:48 +12:00

453 lines
16 KiB
C++

#include "utils/directories.hpp"
#include "utils/utils.hpp"
#include "servers.hpp"
#include "services.hpp"
#include "templates.hpp"
#include "utils/utils.hpp"
#include "utils/execute.hpp"
#include "output.hpp"
#include <libassert/assert.hpp>
#include "config.hpp"
#include <iostream>
#include <memory>
#include <filesystem>
#include <fstream>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>
#include <wordexp.h> // For potential shell-like expansion if needed
namespace dropshell
{
ServerConfig::ServerConfig(const std::string &server_name) : mValid(false), mServerName(server_name)
{
if (server_name.empty())
return;
std::string server_json_path = localfile::server_json(server_name);
// Check if file exists
if (!std::filesystem::exists(server_json_path))
{
std::cerr << "Server environment file not found: " + server_json_path << " for server " << server_name << std::endl;
return;
}
try
{
// Use envmanager to handle the environment file
nlohmann::json server_env_json = nlohmann::json::parse(std::ifstream(server_json_path));
if (server_env_json.empty())
{
error << "Failed to parse server environment file at "<< server_json_path << std::endl;
info << "The returned json was empty." << std::endl;
return;
}
// get the variables from the json, converting everything to strings.
for (const auto &var : server_env_json.items())
{
std::string value;
if (var.value().is_string())
value = var.value();
else if (var.value().is_number_integer())
value = std::to_string(var.value().get<int>());
else if (var.value().is_boolean())
value = var.value() ? "true" : "false";
else
value = var.value().dump();
mVariables[var.key()] = replace_with_environment_variables_like_bash(value);
}
// Verify required variables exist
for (const auto &var : {"SSH_HOST", "SSH_PORT", "SSH_USERS"})
{
if (mVariables.find(var) == mVariables.end())
{
// Print the variables identified in the file
info << "Variables identified in the file:" << std::endl;
for (const auto &v : mVariables)
{
info << " " << v.first << std::endl;
}
throw std::runtime_error("Missing required variable: " + std::string(var));
}
}
// Parse users array
if (!server_env_json.contains("SSH_USERS") || !server_env_json["SSH_USERS"].is_array())
{
error << "SSH_USERS array not found or invalid in server configuration" << std::endl;
return;
}
for (const auto &user_json : server_env_json["SSH_USERS"])
{
UserConfig user;
user.user = user_json["USER"].get<std::string>();
user.dir = user_json["DIR"].get<std::string>();
mUsers.push_back(user);
}
if (mUsers.empty())
{
error << "No users defined in server configuration " << server_json_path << std::endl;
return;
}
mValid = true;
}
catch (const std::exception &e)
{
error << "Failed to parse " << server_json_path << std::endl;
error << "Error: " << e.what() << std::endl;
mValid = false;
}
}
std::string ServerConfig::get_SSH_HOST() const
{
return get_variable("SSH_HOST");
}
std::string ServerConfig::get_SSH_PORT() const
{
return get_variable("SSH_PORT");
}
std::vector<UserConfig> ServerConfig::get_users() const
{
return mUsers;
}
std::string ServerConfig::get_user_dir(const std::string &user) const
{
for (const auto &u : mUsers)
{
if (u.user == user)
{
return u.dir;
}
}
return "";
}
std::string ServerConfig::get_server_name() const
{
return mServerName;
}
std::string ServerConfig::get_user_for_service(const std::string &service) const
{
return dropshell::get_user_for_service(mServerName, service);
}
std::string get_user_for_service(const std::string &server, const std::string &service)
{
auto services_info = get_server_services_info(server);
auto it = std::find_if(services_info.begin(), services_info.end(),
[&service](const LocalServiceInfo &si)
{ return si.service_name == service; });
if (it != services_info.end() && SIvalid(*it))
return it->user;
return "";
}
sSSHInfo ServerConfig::get_SSH_INFO(std::string user) const
{
ASSERT(!user.empty(), "User is empty, cannot get SSH info.");
// Find user in mUsers vector
auto it = std::find_if(mUsers.begin(), mUsers.end(),
[&user](const UserConfig &u)
{ return u.user == user; });
ASSERT(it != mUsers.end(), ("User " + user + " not found in server environment."));
return sSSHInfo(get_SSH_HOST(), it->user, get_SSH_PORT(), get_server_name(), it->dir);
}
bool ServerConfig::hasRootUser() const
{
auto it = std::find_if(mUsers.begin(), mUsers.end(),[](const UserConfig &u)
{ return u.user == "root"; });
return it != mUsers.end();
}
bool ServerConfig::hasDocker() const
{
return get_variable("HAS_DOCKER") == "true";
}
bool ServerConfig::hasRootDocker() const
{
return get_variable("DOCKER_ROOTLESS") == "false";
}
bool ServerConfig::hasUser(const std::string &user) const
{
auto it = std::find_if(mUsers.begin(), mUsers.end(),
[&user](const UserConfig &u)
{ return u.user == user; });
return it != mUsers.end();
}
bool ServerConfig::check_remote_dir_exists(const std::string &dir_path, std::string user) const
{
sCommand scommand("", "test -d " + quote(dir_path), {});
return execute_ssh_command(get_SSH_INFO(user), scommand, cMode::Silent);
}
bool ServerConfig::check_remote_file_exists(const std::string &file_path, std::string user) const
{
sCommand scommand("", "test -f " + quote(file_path), {});
return execute_ssh_command(get_SSH_INFO(user), scommand, cMode::Silent);
}
bool ServerConfig::check_remote_items_exist(const std::vector<std::string> &file_paths, std::string user) const
{
// convert file_paths to a single string, separated by spaces
std::string file_paths_str;
std::string file_names_str;
for (const auto &file_path : file_paths)
{
file_paths_str += quote(file_path) + " ";
file_names_str += std::filesystem::path(file_path).filename().string() + " ";
}
// check if all items in the vector exist on the remote server, in a single command.
sCommand scommand("", "for item in " + file_paths_str + "; do test -f $item; done", {});
sSSHInfo sshinfo = get_SSH_INFO(user);
bool okay = execute_ssh_command(sshinfo, scommand, cMode::Silent);
if (!okay)
{
std::cerr << "Error: Required items not found on remote server: " << file_names_str << std::endl;
return false;
}
return true;
}
bool ServerConfig::remove_remote_dir(
const std::string &dir_path, bool silent, std::string user) const
{
std::filesystem::path path(dir_path);
std::filesystem::path parent_path = path.parent_path();
std::string target_dir = path.filename().string();
if (parent_path.empty())
parent_path = "/";
if (target_dir.empty())
return false;
if (!silent)
std::cout << "Removing remote directory " << target_dir << " in " << parent_path << " on " << mServerName << std::endl;
std::string remote_cmd =
"docker run --rm -v " + quote(parent_path.string()) + ":/parent " +
" alpine rm -rf \"/parent/" + target_dir + "\"";
// if (!silent)
// std::cout << "Running command: " << remote_cmd << std::endl;
sCommand scommand("", remote_cmd, {});
cMode mode = (silent ? cMode::Silent : cMode::Defaults);
sSSHInfo sshinfo = get_SSH_INFO(user);
return execute_ssh_command(sshinfo, scommand, mode);
}
bool ServerConfig::run_remote_template_command(
const std::string &service_name,
const std::string &command,
std::vector<std::string> args,
bool silent,
std::map<std::string, std::string> extra_env_vars) const
{
std::string user = get_user_for_service(service_name);
auto scommand = construct_standard_template_run_cmd(service_name, command, args, silent);
if (!scommand.has_value())
return false;
// add the extra env vars to the command
for (const auto &[key, value] : extra_env_vars)
scommand->add_env_var(key, value);
if (scommand->get_command_to_run().empty())
return false;
cMode mode = (command == "ssh") ? (cMode::Interactive) : (silent ? cMode::Silent : cMode::Defaults);
return execute_ssh_command(get_SSH_INFO(user), scommand.value(), mode);
}
bool ServerConfig::run_remote_template_command_and_capture_output(
const std::string &service_name,
const std::string &command,
std::vector<std::string> args,
std::string &output,
bool silent,
std::map<std::string, std::string> extra_env_vars) const
{
std::string user = get_user_for_service(service_name);
auto scommand = construct_standard_template_run_cmd(service_name, command, args, false);
if (!scommand.has_value())
return false;
// add the extra env vars to the command
for (const auto &[key, value] : extra_env_vars)
scommand->add_env_var(key, value);
return execute_ssh_command(get_SSH_INFO(user), scommand.value(), cMode::Defaults, &output);
}
std::string ServerConfig::get_variable(const std::string &name) const
{
auto it = mVariables.find(name);
if (it == mVariables.end())
{
return "";
}
return it->second;
}
std::optional<sCommand> ServerConfig::construct_standard_template_run_cmd(const std::string &service_name, const std::string &command, const std::vector<std::string> args, const bool silent) const
{
if (command.empty())
return std::nullopt;
std::string user = get_user_for_service(service_name);
std::string remote_service_template_path = remotepath(mServerName, user).service_template(service_name);
std::string script_path = remote_service_template_path + "/" + command + ".sh";
std::map<std::string, std::string> env_vars;
if (!get_all_service_env_vars(mServerName, service_name, env_vars))
{
std::cerr << "Error: Failed to get all service env vars for " << service_name << std::endl;
return std::nullopt;
}
std::string argstr = "";
for (const auto &arg : args)
{
argstr += " " + quote(dequote(trim(arg)));
}
sCommand sc(
remote_service_template_path,
quote(script_path) + argstr + (silent ? " > /dev/null 2>&1" : ""),
env_vars);
if (sc.empty())
{
std::cerr << "Error: Failed to construct command for " << service_name << " " << command << std::endl;
return std::nullopt;
}
return sc;
}
std::vector<ServerConfig> get_configured_servers()
{
std::vector<ServerConfig> servers;
std::vector<std::string> lsdp = gConfig().get_local_server_definition_paths();
if (lsdp.empty())
return servers;
for (auto servers_dir : lsdp)
{
if (!servers_dir.empty() && std::filesystem::exists(servers_dir))
{
for (const auto &entry : std::filesystem::directory_iterator(servers_dir))
{
if (std::filesystem::is_directory(entry))
{
std::string server_name = entry.path().filename().string();
if (server_name.empty() || server_name[0] == '.' || server_name[0] == '_')
continue;
ServerConfig env(server_name);
if (!env.is_valid())
{
std::cerr << "Error: Invalid server environment file: " << entry.path().string() << std::endl;
continue;
}
servers.push_back(env);
}
}
}
}
return servers;
}
bool create_server(const std::string &server_name)
{
// 1. check if server name already exists
std::string server_existing_dir = localpath::server(server_name);
if (!server_existing_dir.empty())
{
error << "Error: Server name already exists: " << server_name << std::endl;
info << "Current server path: " << server_existing_dir << std::endl;
return false;
}
// 2. create a new directory in the user config directory
auto lsdp = gConfig().get_local_server_definition_paths();
if (lsdp.empty() || lsdp[0].empty())
{
error << "Error: Local server definition path not found" << std::endl;
info << "Run 'dropshell edit' to configure DropShell" << std::endl;
return false;
}
std::string server_dir = lsdp[0] + "/" + server_name;
std::filesystem::create_directory(server_dir);
// 3. create a template server.env file in the server directory
std::string user = getenv("USER");
std::string server_env_path = server_dir + "/" + filenames::server_json;
std::ofstream server_env_file(server_env_path);
server_env_file << "{" << std::endl;
server_env_file << " \"SSH_HOST\": \"" << server_name << "\"," << std::endl;
server_env_file << " \"SSH_PORT\": " << 22 << "," << std::endl;
server_env_file << " \"SSH_USERS\": [" << std::endl;
server_env_file << " {" << std::endl;
server_env_file << " \"USER\": \"" << user << "\"," << std::endl;
server_env_file << " \"DIR\": \"" << "/home/" + user << "/.dropshell\"" << std::endl;
server_env_file << " }" << std::endl;
server_env_file << " ]" << std::endl;
server_env_file << "}" << std::endl;
server_env_file.close();
std::cout << "Server created successfully: " << server_name << std::endl;
std::cout << "Please complete the installation:" << std::endl;
std::cout << "1) edit the server configuration: dropshell edit " << server_name << std::endl;
std::cout << "2) install the server: dropshell install " << server_name << std::endl;
std::cout << std::endl;
return true;
}
void get_all_used_commands(std::set<std::string> &commands)
{
std::vector<ServerConfig> servers = get_configured_servers();
for (const auto &server : servers)
{
auto services = get_server_services_info(server.get_server_name());
for (const auto &service : services)
commands.merge(get_used_commands(server.get_server_name(), service.service_name));
}
}
bool server_exists(const std::string &server_name)
{
std::string server_existing_dir = localpath::server(server_name);
if (server_existing_dir.empty())
return false;
if (std::filesystem::exists(server_existing_dir));
return true;
return false;
}
} // namespace dropshell