lcpex rewrite - alpha

This commit is contained in:
phanes committed 2023-02-15 18:44:21 -05:00
1 parent bb85754dc0
commit 7ed6e13fa5
82 files changed
+4510 -2592

No files matched your search

+230
View File
@@ -0,0 +1,230 @@
/*
Rex - A configuration management and workflow automation tool that
compiles and runs in minimal environments.
© SILO GROUP and Chris Punches, 2020.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "Suite.h"
/**
* @class SuiteException
* @brief Exception thrown when a Suite tries to access a contained Unit's value that is not present in the Unit.
*
* This exception is thrown when a Suite object tries to access a value in a contained Unit object that is not present in the Unit. The error message is stored in the `msg_` member variable and can be retrieved with the `what` method.
*/
class SuiteException: public std::exception
{
public:
/**
* @brief Constructor for SuiteException class (C-style string).
*
* @param message C-style string error message. The string contents are copied upon construction. The caller is responsible for deleting the char*.
*/
explicit SuiteException(const char* message):
msg_(message)
{
}
/**
* @brief Constructor for SuiteException class (C++ STL string).
*
* @param message The error message.
*/
explicit SuiteException(const std::string& message):
msg_(message)
{}
/**
* @brief Destructor for SuiteException class.
*
* Virtual to allow for subclassing.
*/
virtual ~SuiteException() throw (){}
/**
* @brief Get the error message.
*
* @return A pointer to a const char*. The underlying memory is in the possession of the Exception object. Callers should not attempt to free the memory.
*/
virtual const char* what() const throw (){
return msg_.c_str();
}
protected:
/// Error message.
std::string msg_;
};
/**
* @brief Constructor for Suite class.
*
* The Suite class is simply a managed container for a Unit vector.
* Once instantiated, all methods will require either a JSON file or string to be loaded as deserialized Unit types
* before being called or will simply throw an exception.
* From the high level, a Suite contains the full definitions of all potential Units to execute defined in the Unit
* definition files that it is loading. It is meant to be used in such a way that as the application iterates through
* the Task objects contained by the application Plan, it will iterate through the appplication's Suite, which contains
* the definition of all available Tasks. In this manner, defining units and executing units are split into separate
* human processes to allow modularly developed profiles of test suites. As inferred, Unit is expected to be one of
* the two types that are only instantiated once per application run, though it is designed to be used more than once
* if the implementor so desires.
*/
Suite::Suite( int LOG_LEVEL ): JSON_Loader( LOG_LEVEL ), slog( LOG_LEVEL, "_suite" )
{
this->LOG_LEVEL;
}
/**
* @brief Get the list of unit files in a directory
*
* This function retrieves all the files with a ".units" extension in the specified directory.
*
* @param[out] files The list of unit files
* @param[in] path The path of the directory to search
*
* @return None
*/
void Suite::get_units_from_dir( std::vector<std::string> * files, std::string path )
{
// TODO: this whole method probably needs rewritten
DIR* dirFile = opendir( path.c_str() );
if ( dirFile )
{
std::string entry;
struct dirent* hFile;
errno = 0;
while (( hFile = readdir( dirFile )) != NULL )
{
if ( !strcmp( hFile->d_name, "." ))
{
continue;
}
if ( !strcmp( hFile->d_name, ".." ))
{
continue;
}
// hidden files
if ( hFile->d_name[0] == '.' )
{
continue;
}
// dirFile.name is the name of the file. Do whatever string comparison
// you want here. Something like:
if ( strstr( hFile->d_name, ".units" ))
{
std::string full_path = path + hFile->d_name;
files->push_back( full_path );
}
}
closedir( dirFile );
} else {
this->slog.log( E_DEBUG, "File not found: " + path );
}
}
/**
* @brief Load units from a file or directory
*
* This function loads units from a file or directory containing unit files.
* The unit files must be in JSON format.
*
* @param[in] units_path The path to the file or directory containing unit files
*
* @return None
*/
void Suite::load_units_file( std::string units_path )
{
std::vector<std::string> unit_files;
if ( is_dir( units_path ) )
{
// we have a directory path. find all files ending in *.units and load them into a vector<std::string>
get_units_from_dir( &unit_files, units_path );
}
if ( is_file( units_path ) )
{
unit_files.push_back( units_path );
}
this->slog.log( E_INFO, "Unit files found: " + std::to_string( unit_files.size() ) );
for ( int i = 0; i < unit_files.size(); i++ )
{
// will use json_root buffer on each run to append to this->units vector as valid units are found.
this->load_json_file( unit_files[i] );
// staging buffer
Json::Value jbuff;
// fill the jbuff staging buffer with a json::value object in the supplied units_path
if ( this->get_serialized( jbuff, "units" ) == 0)
{
this->json_root = jbuff;
}
// iterate through the json::value members that have been loaded. append to this->units vector
// buffer for units to append:
Unit tmp_U = Unit( this->LOG_LEVEL );
for ( int index = 0; index < this->json_root.size(); index++ )
{
// assemble the unit from json_root using the built-in value operator
tmp_U.load_root( this->json_root[ index ] );
if ( tmp_U.get_active() ) {
// append to this->units
this->units.push_back( tmp_U );
this->slog.log( E_INFO, "Added unit \"" + tmp_U.get_name() + "\" to Suite.");
}
}
}
}
/**
* @brief Returns a contained Unit identified by the `provided_name` attribute.
*
* @param result The unit type that receives the unit's value.
* @param provided_name The name of the unit being fetched.
*
* @throws SuiteException if the unit with the specified name is not found.
*/
void Suite::get_unit(Unit & result, std::string provided_name)
{
bool foundMatch = false;
for ( int i = 0; i < this->units.size(); i++ )
{
std::string unit_name = this->units[i].get_name();
if ( unit_name == provided_name )
{
result = this->units[i];
foundMatch = true;
break;
}
}
if (! foundMatch )
{
this->slog.log( E_FATAL, "Unit name \"" + provided_name + "\" was referenced but not defined!" );
throw SuiteException( "Undefined unit referenced." );
}
}
+85
View File
@@ -0,0 +1,85 @@
/*
Rex - A configuration management and workflow automation tool that
compiles and runs in minimal environments.
© SILO GROUP and Chris Punches, 2020.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef REX_SUITE_H
#define REX_SUITE_H
#include <vector>
#include "../json_support/JSON.h"
#include "../logger/Logger.h"
#include "Unit.h"
#include "../misc/helpers.h"
#include <string.h>
#include <syslog.h>
#include <sys/stat.h>
#include <dirent.h>
/**
* @class Suite
* @brief Loads unit definition files and provides access to the unit definitions.
*
* The Suite class extends the JSON_Loader class and loads unit definition files. It stores the valid unit definitions
* in the `units` vector. The `get_unit` method can be used to retrieve a specific unit by name. The `load_units_file`
* method is used to load a unit definition file and add valid unit definitions to the `units` vector. The
* `get_units_from_dir` method is used to get a list of unit definition files from a directory. The `LOG_LEVEL` and
* `slog` member variables are used to control logging.
*/
class Suite: public JSON_Loader
{
protected:
/// storage for the definitions we are amassing from the unit definition files
std::vector<Unit> units;
public:
/**
* @brief Constructor for Suite class.
*
* @param LOG_LEVEL The logging level to use.
*/
Suite( int LOG_LEVEL );
/**
* @brief Load a unit definitions file and add valid unit definitions to `units` vector.
*
* @param filename The path to the unit definitions file.
*/
void load_units_file( std::string filename );
/**
* @brief Retrieve a unit by name.
*
* @param result The Unit object that will be set to the unit with the provided name.
* @param provided_name The name of the unit to retrieve.
*/
void get_unit(Unit & result, std::string provided_name);
private:
/**
* @brief Get a list of unit definition files from a directory.
*
* @param files A pointer to a vector of strings that will be set to the list of unit definition files.
* @param path The path to the directory containing the unit definition files.
*/
void get_units_from_dir( std::vector<std::string> * files, std::string path );
private:
/// The logging level to use.
int LOG_LEVEL;
/// A logger for logging messages.
Logger slog;
};
#endif //REX_SUITE_H
+420
View File
@@ -0,0 +1,420 @@
/*
Rex - A configuration management and workflow automation tool that
compiles and runs in minimal environments.
© SILO GROUP and Chris Punches, 2020.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "Unit.h"
/**
* @class UnitException
* @brief Exception class for Unit related errors.
*
* This class provides an exception type for Unit related errors.
*/
class UnitException: public std::exception
{
public:
/**
* @brief Constructor for UnitException (C strings).
*
* @param message C-style string error message. The string contents are copied upon construction.
* Responsibility for deleting the char* lies with the caller.
*/
explicit UnitException(const char* message): msg_(message) {}
/**
* @brief Constructor for UnitException (C++ STL strings).
*
* @param message The error message.
*/
explicit UnitException(const std::string& message): msg_(message) {}
/**
* @brief Destructor for UnitException.
*
* Virtual to allow for subclassing.
*/
virtual ~UnitException() throw (){}
/**
* @brief Returns a pointer to the (constant) error description.
*
* @return A pointer to a const char*. The underlying memory is in posession of the Exception object.
* Callers must not attempt to free the memory.
*/
virtual const char* what() const throw () { return msg_.c_str(); }
protected:
/**
* @brief Error message.
*/
std::string msg_;
};
/**
* @class Unit
* @brief Definition of an automation task.
*
* The Unit is a definition of an automation task. Each Unit has:
* - name, used for identification and retrieval.
* - target, which is the filepath of an executable to trigger.
* - output, which is the desired output of the execution of target to STDOUT in determinations of success or failure
* (in addition to 0|non-0 exit code). If the output is set to look for "0" then it uses the exit code.
* - rectifier, which is the path to an executable in the event of a non-0 exit code or a failure to get the desired
* output.
* - required, which is used as a flag to halt or continue if rectifier does not heal the system in such a way that
* target can run successfully.
* - rectify, which is used as a flag to determine if the rectifier runs.
*
* @param LOG_LEVEL The log level to be used.
*/
Unit::Unit( int LOG_LEVEL ): JSON_Loader( LOG_LEVEL ), slog( LOG_LEVEL, "_unit_" )
{
this->LOG_LEVEL;
}
/**
* @brief Unit::load_root - Takes a JSON::Value and assigns the members to the Unit being populated.
*
* @param loader_root - The JSON::Value object to use to populate unit from. Usually supplied as the Suite's buffer
* member.
* @return - Boolean representation of success or failure.
*/
int Unit::load_root(Json::Value loader_root)
{
// TODO this needs reworked to have errmsg actually end up as a null return from json::value.get()
std::string errmsg = "SOMETHING WENT TERRIBLY WRONG IN PARSING";
// TODO this pattern is 'working but broken'. need to use a datastructure for required members and iterate
// do NOT replace this with a switch case pattern
if ( loader_root.isMember("name") )
{ this->name = loader_root.get("name", errmsg).asString(); } else
throw UnitException("No 'name' attribute specified when loading a unit.");
if ( loader_root.isMember("target") )
{ this->target = loader_root.get("target", errmsg).asString(); } else
throw UnitException("No 'target' attribute specified when loading a unit.");
if ( loader_root.isMember("is_shell_command") )
{ this->is_shell_command = loader_root.get("is_shell_command", errmsg).asBool(); } else
throw UnitException("No 'is_shell_command' attribute specified when loading a unit.");
if ( loader_root.isMember("shell_definition") )
{ this->shell_definition = loader_root.get("shell_definition", errmsg).asString(); } else
throw UnitException("No 'shell_definition' attribute specified when loading a unit.");
if ( loader_root.isMember("force_pty") )
{ this->force_pty = loader_root.get("force_pty", errmsg).asBool(); } else
throw UnitException("No 'force_pty' attribute specified when loading a unit.");
if ( loader_root.isMember("set_working_directory") )
{ this->set_working_directory = loader_root.get("set_working_directory", errmsg).asBool(); } else
throw UnitException("No 'set_working_directory' attribute specified when loading a unit.");
if ( loader_root.isMember("rectify") )
{ this->rectify = loader_root.get("rectify", errmsg).asBool(); } else
throw UnitException("No 'rectify' boolean attribute specified when loading a unit.");
if ( loader_root.isMember("rectifier") )
{ this->rectifier = loader_root.get("rectifier", errmsg).asString(); } else
throw UnitException("No 'rectifier' executable attribute specified when loading a unit.");
if ( loader_root.isMember("active") )
{ this->active = loader_root.get("active", errmsg).asBool(); } else
throw UnitException("No 'active' attribute specified when loading a unit.");
if ( loader_root.isMember("required") )
{ this->required = loader_root.get("required", errmsg).asBool(); } else
throw UnitException("No 'required' attribute specified when loading a unit.");
if ( loader_root.isMember("set_user_context") )
{ this->set_user_context = loader_root.get("set_user_context", errmsg).asBool(); } else
throw UnitException("No 'set_user_context' attribute specified when loading a unit.");
// TODO functionize this
int uid = getuid();
struct passwd * upw;
std::string errmsg_user;
// if no user field is specified then default to the currently executing user
if ( ( upw = getpwuid(uid) ) == nullptr )
{
throw UnitException( "Could not retrieve current user." );
} else {
errmsg_user = upw->pw_name;
}
// -TODO
if ( loader_root.isMember( "user" ) )
{ this->user = loader_root.get( "user", errmsg_user ).asString(); } else this->user = errmsg_user;
// TODO functionalize this
// get the current context gid as a backup value
int gid = getgid();
// declare the grp object to pull the name from once populated
struct group * grp;
// storage for backup value once retrieved
std::string errmsg_group;
// get the backup value and store it to errmsg_group
if ( ( grp = getgrgid( gid ) ) == nullptr )
{
throw UnitException("Could not retrieve current group");
} else {
errmsg_group = grp->gr_name;
}
if ( loader_root.isMember( "group" ) )
{ this->group = loader_root.get( "group", errmsg_group ).asString(); } else this->group = grp->gr_name;
if ( loader_root.isMember("supply_environment") )
{
this->supply_environment = loader_root.get("supply_environment", errmsg).asBool();
} else {
throw UnitException("No 'supply_environment' attribute specified when loading a unit.");
}
if ( loader_root.isMember("environment") )
{
this->env_vars_file = loader_root.get("environment", errmsg).asString();
} else {
throw UnitException("No 'environment' attribute specified when loading a unit.");
}
this->populated = true;
return 0;
}
/**
* @brief Retrieves the name of the unit.
*
* @return The name of the unit.
*
* @throws UnitException if the unit has not been populated.
*/
std::string Unit::get_name()
{
if ( ! this->populated ) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->name;
}
/**
* @brief Retrieves the target of the unit.
*
* @return The target of the unit.
*
* @throws UnitException if the unit has not been populated.
*/
std::string Unit::get_target()
{
if ( ! this->populated ) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->target;
}
/**
* @brief Retrieves whether the unit is a shell command.
*
* @return True if the unit is a shell command, false otherwise.
*
* @throws UnitException if the unit has not been populated.
*/
bool Unit::get_is_shell_command()
{
if (!this->populated) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->is_shell_command;
}
/**
* @brief Retrieves the shell definition of the unit.
*
* @return The shell definition of the unit.
*
* @throws UnitException if the unit has not been populated.
*/
std::string Unit::get_shell_definition() {
if (!this->populated) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->shell_definition;
}
/**
* @brief Retrieves whether the unit requires a PTY.
*
* @return True if the unit requires a PTY, false otherwise.
*
* @throws UnitException if the unit has not been populated.
*/
bool Unit::get_force_pty() {
if (!this->populated) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->force_pty;
}
/**
* @brief Retrieves whether the working directory should be set for the unit.
*
* @return True if the working directory should be set, false otherwise.
*
* @throws UnitException if the unit has not been populated.
*/
bool Unit::get_set_working_directory() {
if (!this->populated) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->set_working_directory;
}
/**
* @brief Retrieves the working directory of the unit.
*
* @return The working directory of the unit.
*
* @throws UnitException if the unit has not been populated.
*/
std::string Unit::get_working_directory() {
if (!this->populated) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->working_directory;
}
/**
* @brief Retrieves the rectification status of the unit.
*
* @return The rectification status of the unit.
*
* @throws UnitException if the unit has not been populated.
*/
bool Unit::get_rectify() {
if (!this->populated) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->rectify;
}
/**
* @brief Retrieves the rectifier of the unit.
*
* @return The rectifier of the unit.
*
* @throws UnitException if the unit has not been populated.
*/
std::string Unit::get_rectifier()
{
if ( ! this->populated ) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->rectifier;
}
/**
* @brief Retrieves the armed status of the unit.
*
* @return The armed status of the unit.
*
* @throws UnitException if the unit has not been populated.
*/
bool Unit::get_active()
{
if ( ! this->populated ) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->active;
}
/**
* @brief Retrieves the requirement status of the unit.
*
* @return The requirement status of the unit.
*
* @throws UnitException if the unit has not been populated.
*/
bool Unit::get_required()
{
if ( ! this->populated ) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->required;
}
/**
* @brief Retrieves whether the user context should be set for the unit.
*
* @return True if the user context should be set, false otherwise.
*
* @throws UnitException if the unit has not been populated.
*/
bool Unit::get_set_user_context() {
if (!this->populated) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->set_user_context;
}
/**
* @brief Retrieves the user context for the unit.
*
* @return The string value of the user name.
*
* @throws UnitException if the unit has not been populated.
*/
std::string Unit::get_user()
{
if ( ! this->populated ) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->user;
}
/**
* @brief Retrieves the group context for the unit.
*
* @return The string value of the group name.
*
* @throws UnitException if the unit has not been populated.
*/
std::string Unit::get_group()
{
if ( ! this->populated ) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->group;
}
/**
* @brief Retrieves whether the environment should be supplied to the unit.
*
* @return True if the environment should be supplied, false otherwise.
*
* @throws UnitException if the unit has not been populated.
*/
bool Unit::get_supply_environment() {
if (!this->populated) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->supply_environment;
}
/**
* @brief Retrieves the environment file for the unit.
*
* @return The environment file for the unit.
*
* @throws UnitException if the unit has not been populated.
*/
std::string Unit::get_environment_file()
{
if ( ! this->populated ) { throw UnitException("Attempted to access an unpopulated unit."); }
return this->env_vars_file;
}
+124
View File
@@ -0,0 +1,124 @@
/*
Rex - A configuration management and workflow automation tool that
compiles and runs in minimal environments.
© SILO GROUP and Chris Punches, 2020.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef REX_UNIT_H
#define REX_UNIT_H
#include <string>
#include "../json_support/JSON.h"
#include "../logger/Logger.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdexcept>
#include <pwd.h>
#include <grp.h>
/*
* Unit is a type that represents a safely deserialized JSON object which defines what actions are taken as rex
* iterates through it's Tasks in it's given Plan. They only define the behaviour on execution, while the tasks define
* which Units are executed and in what order (and which Units a given Task depends on.
*/
class Unit: JSON_Loader
{
private:
// the name of the test
std::string name;
// the path of the executable this test executes when run
std::string target;
// bool to indicate if the target is a shell command or not
bool is_shell_command;
// the shell profile to use defined in the shell definitions file
std::string shell_definition;
// bool to indicate if the target should be run in a pty
bool force_pty;
// bool to indicate if the working directory should be set for this execution
bool set_working_directory;
// the working directory to set for this execution
std::string working_directory;
// indicator of whether the rectifier executable should be run on test failures.
// if rectifier exits on non-zero return code, it should be trigger the behaviour indicated by required
bool rectify;
// the path of the executable this test runs when the target executable fails to produce output or a 0 exit code.
std::string rectifier;
// an indicator of whether the test is active or not
// this is used as a way to give definers a way to force executors to edit arbitrary fields or prevent
// execution of potentially dangerous or intrusive tests
bool active;
// an indicator of whether or not this test is required to pass.
// intended to be used as a flag to halt execution of further tests on failure
bool required;
// an indicator of whether or not the user context should be set for this execution
bool set_user_context;
// user to run process as.
// not intended for protected accounts, handle your own security
std::string user;
// group to run process as.
// not intended for protected accounts, handle your own security
std::string group;
// an indicator of whether or not the environment should be set for this execution
// REQUIRES this->is_shell_command == true
bool supply_environment;
// the path to a file containing environment variables or functions to be set for this execution
std::string env_vars_file;
public:
Unit( int LOG_LEVEL );
// loads a serialized jason::value object as a unit
int load_root( Json::Value loader_root );
// getters
std::string get_name();
std::string get_target();
bool get_is_shell_command();
std::string get_shell_definition();
bool get_force_pty();
bool get_set_working_directory();
std::string get_working_directory();
bool get_rectify();
std::string get_rectifier();
bool get_active();
bool get_required();
bool get_set_user_context();
std::string get_user();
std::string get_group();
bool get_supply_environment();
std::string get_environment_file();
private:
int LOG_LEVEL;
Logger slog;
};
#endif //REX_UNIT_H