Skip to content

Commit

Permalink
feat: Implement self-restart functionality for the agent
Browse files Browse the repository at this point in the history
  • Loading branch information
lchico committed Dec 20, 2024
1 parent 1eb2738 commit 7ec7f08
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 32 deletions.
27 changes: 3 additions & 24 deletions packages/debs/SPECS/wazuh-agent/debian/prerm
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,9 @@ case "$1" in
elif ${BINARY_DIR}wazuh-agent --status 2>/dev/null | grep "is running" > /dev/null 2>&1; then
pid=$(ps -ef | grep "${BINARY_DIR}wazuh-agent" | grep -v grep | awk '{print $2}')
if [ -n "$pid" ]; then
kill -SIGTERM "$pid" 2>/dev/null
kill -15 "$pid" 2>/dev/null
fi
fi

# # Process: wazuh-agent
# if pgrep -f "wazuh-agent" > /dev/null 2>&1; then
# kill -15 $(pgrep -f "wazuh-agent") > /dev/null 2>&1
# fi

# if pgrep -f "wazuh-agent" > /dev/null 2>&1; then
# kill -9 $(pgrep -f "wazuh-agent") > /dev/null 2>&1
# fi
;;

remove)
Expand All @@ -38,10 +29,9 @@ case "$1" in
elif ${BINARY_DIR}wazuh-agent --status 2>/dev/null | grep "is running" > /dev/null 2>&1; then
pid=$(ps -ef | grep "${BINARY_DIR}wazuh-agent" | grep -v grep | awk '{print $2}')
if [ -n "$pid" ]; then
kill -SIGTERM "$pid" 2>/dev/null
kill -15 "$pid" 2>/dev/null
fi
fi

;;

failed-upgrade)
Expand All @@ -52,20 +42,9 @@ case "$1" in
elif ${BINARY_DIR}wazuh-agent --status 2>/dev/null | grep "is running" > /dev/null 2>&1; then
pid=$(ps -ef | grep "${BINARY_DIR}wazuh-agent" | grep -v grep | awk '{print $2}')
if [ -n "$pid" ]; then
kill -SIGTERM "$pid" 2>/dev/null
kill -15 "$pid" 2>/dev/null
fi
fi

# if [ -f ${INSTALLATION_WAZUH_DIR}/bin/wazuh-agent ]; then
# # pkill wazuh-agent
# if pgrep -f "wazuh-agent" > /dev/null 2>&1; then
# kill -15 $(pgrep -f "wazuh-agent") > /dev/null 2>&1
# fi

# if pgrep -f "wazuh-agent" > /dev/null 2>&1; then
# kill -9 $(pgrep -f "wazuh-agent") > /dev/null 2>&1
# fi
# fi
;;

*)
Expand Down
1 change: 0 additions & 1 deletion src/agent/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ target_link_libraries(Agent
MultiTypeQueue
ModuleManager
ModuleCommand
CentralizedConfiguration
Boost::asio
sysinfo
PRIVATE
Expand Down
9 changes: 7 additions & 2 deletions src/agent/command_handler/include/command_handler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,13 @@ namespace command_handler
{
for (auto& cmd : *cmds)
{
cmd.ExecutionResult.ErrorCode = module_command::Status::FAILURE;
cmd.ExecutionResult.Message = "Agent stopped during execution";
if (cmd.Command == "restart") {
cmd.ExecutionResult.ErrorCode = module_command::Status::IN_PROGRESS;
cmd.ExecutionResult.Message = "Restarting Agent...";
} else {
cmd.ExecutionResult.ErrorCode = module_command::Status::FAILURE;
cmd.ExecutionResult.Message = "Agent stopped during execution";
}
ReportCommandResult(cmd);
m_commandStore.UpdateCommand(cmd);
}
Expand Down
2 changes: 1 addition & 1 deletion src/agent/command_handler/src/command_handler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace command_handler
{
const std::unordered_map<std::string, std::string> VALID_COMMANDS_MAP = {
{"set-group", "CentralizedConfiguration"}, {"update-group", "CentralizedConfiguration"}};
{"set-group", "CentralizedConfiguration"}, {"update-group", "CentralizedConfiguration"}, {"restart", "restart"}};

void CommandHandler::Stop()
{
Expand Down
9 changes: 9 additions & 0 deletions src/agent/include/agent.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ class Agent
/// This method stops all modules launched by moduleManager, and starts them again.
void ReloadModules();

/// @brief Checks if a restart is required
///
/// This method returns `true` if the agent needs to be restarted,
/// and `false` otherwise.
bool IsRestartRequired();

private:
/// @brief Task manager
TaskManager m_taskManager;
Expand Down Expand Up @@ -87,4 +93,7 @@ class Agent

/// @brief Agent thread count
size_t m_agentThreadCount;

/// @brief Define if the agent needs to be restarted after it ends.
bool requires_restart;
};
5 changes: 3 additions & 2 deletions src/agent/service/wazuh-agent.service
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ After=network.target network-online.target

[Service]
Type=simple

PIDFile=/var/run/wazuh-agent.lock
ExecStart=/usr/bin/env WAZUH_HOME/wazuh-agent
TimeoutStopSec=30s # Wait for 30 seconds before killing the service

KillSignal=SIGTERM

KillMode=process
KillMode=mixed

SendSIGKILL=no

Expand Down
17 changes: 16 additions & 1 deletion src/agent/src/agent.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
Agent::Agent(const std::string& configFilePath, std::unique_ptr<ISignalHandler> signalHandler)
: m_configurationParser(configFilePath.empty() ? std::make_shared<configuration::ConfigurationParser>()
: std::make_shared<configuration::ConfigurationParser>(
std::filesystem::path(configFilePath)))
std::filesystem::path(configFilePath)))
, m_dataPath(
m_configurationParser->GetConfig<std::string>("agent", "path.data").value_or(config::DEFAULT_DATA_PATH))
, m_messageQueue(std::make_shared<MultiTypeQueue>(
Expand All @@ -33,6 +33,7 @@ Agent::Agent(const std::string& configFilePath, std::unique_ptr<ISignalHandler>
m_configurationParser,
m_agentInfo.GetUUID())
, m_commandHandler(m_dataPath)
, requires_restart(false)
{
// Check if agent is registered
if (m_agentInfo.GetName().empty() || m_agentInfo.GetKey().empty() || m_agentInfo.GetUUID().empty())
Expand Down Expand Up @@ -101,6 +102,10 @@ void Agent::ReloadModules()
}
}

bool Agent::IsRestartRequired(){
return requires_restart;
}

void Agent::Run()
{
m_taskManager.Start(m_agentThreadCount);
Expand Down Expand Up @@ -158,6 +163,16 @@ void Agent::Run()
return m_centralizedConfiguration.ExecuteCommand(std::move(command), std::move(parameters));
},
m_messageQueue);
} else if (cmd.Module == "restart") {
requires_restart = true;
SignalHandler::HandleSignal(SIGTERM);
auto RestartExecuteCommand = []() -> boost::asio::awaitable<module_command::CommandExecutionResult> {
co_return module_command::CommandExecutionResult{
module_command::Status::IN_PROGRESS,
"Pending restart execution"
};
};
return RestartExecuteCommand();
}
return DispatchCommand(cmd, m_moduleManager.GetModule(cmd.Module), m_messageQueue);
}),
Expand Down
6 changes: 6 additions & 0 deletions src/agent/src/process_options_unix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

void StartAgent(const std::string& configFilePath)
{
bool is_restart_required = false;
unix_daemon::LockFileHandler lockFileHandler = unix_daemon::GenerateLockFile(configFilePath);

if (!lockFileHandler.isLockFileCreated())
Expand All @@ -27,13 +28,18 @@ void StartAgent(const std::string& configFilePath)
{
Agent agent(configFilePath);
agent.Run();
is_restart_required = agent.IsRestartRequired();
}
catch (const std::exception& e)
{
LogError("Exception thrown in wazuh-agent: {}", e.what());
}

lockFileHandler.removeLockFile();

if ( is_restart_required ){
LogInfo("## RESTARTING STARTED");
}
}

void StatusAgent(const std::string& configFilePath)
Expand Down
10 changes: 9 additions & 1 deletion src/agent/src/unix/unix_daemon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,16 @@ namespace unix_daemon
return false;
}

LogDebug("Lock file created: {}", filename);
// Write the PID to the lock file
const std::string pidStr = std::to_string(getpid()) + "\n";
if (write(fd, pidStr.c_str(), pidStr.size()) == -1)
{
LogError("Unable to write PID to lock file: {}. Error: {} ({})", filename.c_str(), errno, std::strerror(errno));
close(fd);
return false;
}

LogDebug("Lock file created: {}", filename);
return true;
}

Expand Down

0 comments on commit 7ec7f08

Please sign in to comment.