Merge pull request #11 from QuasarApp/simpleRefactoring

Simple refactoring
This commit is contained in:
Andrei Yankovich 2021-04-28 18:46:23 +03:00 committed by GitHub
commit 8462ee2978
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 249 additions and 100 deletions

View File

@ -9,17 +9,24 @@
QString Patronum::IController::errorToString(Patronum::ControllerError error) const {
switch (error) {
case Patronum::ControllerError::ServiceUnavailable: return "Service is unavailable. Try send start comand or restart the service manually.";
case Patronum::ControllerError::ServiceUnavailable:
return QObject::tr("Service is unavailable. Try send start comand or restart the service manually.");
case Patronum::ControllerError::InvalidPackage: return "Invalid package received";
case Patronum::ControllerError::InvalidPackage:
return QObject::tr("Invalid package received");
case Patronum::ControllerError::WrongCommand: return "Library unsupported command received";
case Patronum::ControllerError::WrongCommand:
return QObject::tr("Library unsupported command received");
case Patronum::ControllerError::SystemError: return "Internal error of the work of the Patronum library."
" Contact the developers and provide them with an error report."
" https://github.com/QuasarApp/Patronum/issues";
case Patronum::ControllerError::SystemError:
return QObject::tr("Internal error of the work of the Patronum library."
" Contact the developers and provide them with an error report."
" https://github.com/QuasarApp/Patronum/issues");
case Patronum::ControllerError::TimeOutError:
return QObject::tr("Timeout error. service unavailable or not started.");
default:
return "Unknown error";
return QObject::tr("Unknown error");
}
}

View File

@ -28,12 +28,16 @@ enum class ControllerError {
InvalidPackage,
/// Library unsupported command received.
WrongCommand,
/// Timeout error. service unavailable or not started.
TimeOutError,
/// Internal error of the work of the Patronum library. Contact the developers and provide them with an error report. https://github.com/QuasarApp/Patronum/issues
SystemError
};
/**
* @brief The IController class
* @brief The IController class This is base interface for the handling network events.
*
*/
class PATRONUM_LIBRARYSHARED_EXPORT IController
{
@ -43,14 +47,36 @@ public:
/**
* @brief errorToString This method convert the ControllerError to QString.
* @param error - Error id.
* @param error This is error id.
* @return return text of error.
*/
QString errorToString(ControllerError error) const;
/**
* @brief handleFeatures This method should be handle all Command::Features resuests.
* This method will invoked when controller receive commands list for execute (features) from controller or terminal.
* @param features This is list of the requests (@a features)
*/
virtual void handleFeatures(const QList<Feature>& features) = 0;
virtual void handleResponce(const QVariantMap& feature) = 0;
virtual void handleError(ControllerError) = 0;
/**
* @brief handleResponce This method should be handle all responces of the service.
* This method will invoked when controller receive responce from service.
* @param responce This is responce message.
*/
virtual void handleResponce(const QVariantMap& responce) = 0;
/**
* @brief handleError This method shold be handle all error messages.
* This method will invoked when a controlee receive a error responce from a service.
* @param errorCode This is code of a error.
*/
virtual void handleError(ControllerError errorCode) = 0;
/**
* @brief finished This method ivoked when controler received Command::CloseConnection from the server.
*/
virtual void finished() = 0;
};
}

View File

@ -26,14 +26,14 @@ public:
/**
* @brief handleReceiveData This method get all received commnads and process its.
* For each command will invoke the handleReceive method.
* @param data
* For each command will invoke the IService::handleReceive method.
* @param data This is array of the incomming requests (commands)
*/
virtual void handleReceiveData(const QSet<Feature>& data) = 0;
/**
* @brief handleReceive This method invoked when service receive a request from terminal.
* Override this method for work service.
* Override this method for work your service.
* @param data This is input data.
* @return This method should be return true if the @a data command is supported and processed successful.
* IF you return false then a negative message will be sent to a terminal app.
@ -41,7 +41,8 @@ public:
virtual bool handleReceive(const Feature &data) = 0;
/**
* @brief supportedFeatures Override this method for add your features for the service.
* @brief supportedFeatures This method should be return the list of the supported fetures.
* Override this method for add your features for the service.
* @return should be return a set of supported features.
*/
virtual QSet<Feature> supportedFeatures() = 0;

View File

@ -12,6 +12,7 @@
#include <QVariantMap>
#include <quasarapp.h>
#include <QCoreApplication>
#include <QTimer>
namespace Patronum {
@ -33,15 +34,11 @@ bool Controller::send(int argc, char **argv) {
bool Controller::send() {
if (QuasarAppUtils::Params::isEndable("start")) {
return !d_ptr->start();
}
if (QuasarAppUtils::Params::isEndable("install")) {
if (QuasarAppUtils::Params::isEndable("install") || QuasarAppUtils::Params::isEndable("i")) {
return d_ptr->install();
}
if (QuasarAppUtils::Params::isEndable("uninstall")) {
if (QuasarAppUtils::Params::isEndable("uninstall") || QuasarAppUtils::Params::isEndable("u")) {
return d_ptr->uninstall();
}
@ -86,16 +83,43 @@ bool Controller::send() {
sendData.insert(Feature{val.key(), val.value()});
}
return d_ptr->sendCmd(sendData);
if (!d_ptr->sendCmd(sendData)) {
return false;
}
QTimer::singleShot(1000, nullptr, [this]() {
QuasarAppUtils::Params::log(errorToString(ControllerError::TimeOutError), QuasarAppUtils::Error);
QCoreApplication::exit(static_cast<int>(ControllerError::TimeOutError));
});
return true;
}
int Controller::startDetached() const {
return d_ptr->start();
}
bool Controller::waitForResponce(int msec) {
QuasarAppUtils::Help::Section Controller::help() const {
QuasarAppUtils::Help::Section help {
{QObject::tr("Options that available after start"), {
{"stop", QObject::tr("Stop a service")},
{"pause", QObject::tr("Pause a service")},
{"resume", QObject::tr("Resume a service")},
{"uninstall / u", QObject::tr("Uninstall a service")}
return d_ptr->waitForResponce(msec);
}
},
{QObject::tr("Options that available after instalation"),
{
{"uninstall / u", QObject::tr("Uninstall a service")},
{"start / s", QObject::tr("Start a service as a daemon")},
}
}
};
return help;
}
void Controller::handleError(ControllerError error) {
@ -125,7 +149,6 @@ void Controller::handleFeatures(const QList<Feature> &features) {
}
QuasarAppUtils::Help::print(options);
QCoreApplication::exit(0);
}
void Controller::handleResponce(const QVariantMap &responce) {
@ -136,6 +159,9 @@ void Controller::handleResponce(const QVariantMap &responce) {
}
QuasarAppUtils::Help::print(options);
}
void Controller::finished() {
QCoreApplication::exit(0);
}
@ -146,17 +172,7 @@ QList<Feature> Controller::features() {
void Controller::printDefaultHelp() const {
auto quasarappHelp = QuasarAppUtils::Params::getParamsHelp();
QuasarAppUtils::Help::Charters help{{"General options of this controller",{
{"start", QObject::tr("Start a service")},
{"stop", QObject::tr("Stop a service")},
{"pause", QObject::tr("Pause a service")},
{"resume", QObject::tr("Resume a service")},
{"install", QObject::tr("Install a service")},
{"uninstall", QObject::tr("Uninstall a service")}
}}};
QuasarAppUtils::Help::print(quasarappHelp.unite(help));
QuasarAppUtils::Help::print(quasarappHelp.unite(help()));
}
}

View File

@ -10,6 +10,7 @@
#include "Patronum_global.h"
#include <IPController.h>
#include "PFeature.h"
#include <quasarapp.h>
namespace Patronum {
@ -29,21 +30,23 @@ public:
/**
* @brief Controller - Base constructor.
* @param name - Name of you service.
* @param servicePath - Path to service executable. @note If servicePath argument well be empty then 'start' commnad not working
* @param servicePath - Path to service executable.
* @note If servicePath argument will set to empty then 'start' and install commands will not working
*/
Controller(const QString& name, const QString& servicePath = "");
~Controller() override;
/**
* @brief send - This method send request to service.
* @param argc - Count of arguments.
* @param argv - Arguments list.
* @brief send This method send request to service.
* @param argc This is count of arguments.
* @param argv This is arguments list.
* @return true if all sendet successful.
*/
bool send(int argc, char **argv);
/**
* @brief send - This method send request to service. @warning Invoke this method if you invoked QuasarAppUtils::Params::parse() before invoke this method else use send(int argc, char **argv).
* @brief send - This method send request to service.
* @warning Invoke this method if you invoked QuasarAppUtils::Params::parse() before invoke this method else use send(int argc, char **argv).
* @return true if all sendet successful.
*/
bool send();
@ -55,11 +58,10 @@ public:
int startDetached() const;
/**
* @brief waitForResponce - Wait for get a responce from servece.
* @param msec Timeout in msec.
* @return true if all seccussful.
* @brief help This method return help of the Controller.
* @return Available otions list.
*/
bool waitForResponce(int msec = 10000);
QuasarAppUtils::Help::Section help() const;
// IControler interface
protected:
@ -85,6 +87,13 @@ protected:
*/
void handleResponce(const QVariantMap &responce) override;
/**
* @brief finished This method invoked when controler receive from service the Command::CloseConnection command
* This implementation invoke he exit method of the QCoreApplication and finished application.
* If do not want to stop application after receive Command::CloseConnection then override this method.
*/
void finished() override;
/**
* @brief features - This method return current features of connected service.
* @note If Respond from service not received then return empty list.
@ -97,8 +106,6 @@ private:
ControllerPrivate *d_ptr = nullptr;
void printDefaultHelp() const;
};
}
#endif // CONTROLLER_H

View File

@ -94,23 +94,52 @@ Controller *ServiceBase::controller() {
return _controller;
_controller = new Controller(_serviceName,
QuasarAppUtils::Params::getCurrentExecutable());
QuasarAppUtils::Params::getCurrentExecutable());
return _controller;
}
void ServiceBase::printDefaultHelp() {
auto serviceHelp = controller()->help();
serviceHelp.unite(QuasarAppUtils::Params::getParamsHelp());
serviceHelp.unite({{QObject::tr("Options that available befor install"),{
{"start / s", QObject::tr("Start a service in console")},
{"daemon / d", QObject::tr("Start a service as a daemon")},
{"install / i", QObject::tr("Install a service")},
}}});
const auto features = supportedFeatures();
QuasarAppUtils::Help::Options optionsList;
for (const auto& cmd : features) {
optionsList.insert(cmd.cmd(), cmd.description());
}
serviceHelp.unite({{"Available commands of the service:", optionsList}});
QuasarAppUtils::Help::print(serviceHelp);
}
int ServiceBase::exec() {
if (!_core) {
createApplication();
}
bool fExec = QuasarAppUtils::Params::isEndable("exec") || QuasarAppUtils::Params::isDebugBuild();
if (!(QuasarAppUtils::Params::size() || fExec)) {
return controller()->startDetached();
if (!QuasarAppUtils::Params::size()) {
printDefaultHelp();
return 0;
}
if (fExec) {
bool fStart = QuasarAppUtils::Params::isEndable("start") || QuasarAppUtils::Params::isEndable("s");
bool fDaemon = QuasarAppUtils::Params::isEndable("daemon") || QuasarAppUtils::Params::isEndable("d");
if (fStart || fDaemon) {
if (fDaemon) {
return controller()->startDetached();
}
QTimer::singleShot(0, nullptr, [this](){
onStart();
d_ptr->listen();

View File

@ -35,7 +35,7 @@ public:
// IService interface
/**
* @brief exec
* @brief exec This is main method of the service. Use this like a QCoreApplication::exec.
* @return Result of work application.
*/
virtual int exec();
@ -108,6 +108,7 @@ protected:
QCoreApplication *_core = nullptr;
private:
void printDefaultHelp();
ServicePrivate *d_ptr = nullptr;
Controller *_controller = nullptr;

View File

@ -5,7 +5,7 @@ Description=Automatet generated service of %0
Type=forking
User=root
Group=root
ExecStart=%0
ExecStart=%0 start
ExecStop=%0 stop
[Install]

View File

@ -6,33 +6,42 @@
*/
#include "baseinstaller.h"
#include <QFile>
#include <QSettings>
#include <quasarapp.h>
namespace Patronum {
BaseInstaller::BaseInstaller(const QString &name):
Installer(name)
{
Installer(name) {
}
bool BaseInstaller::install(const QString &executable) {
if (!QFile::exists(executable)) {
QuasarAppUtils::Params::log(QObject::tr("The service executable file is not exists %0\n").arg(executable),
QuasarAppUtils::Error);
return false;
}
_executable = executable;
if (isInstalled()) {
QuasarAppUtils::Params::log(QString("the service %0 alredy installed \n").
QuasarAppUtils::Params::log(QObject::tr("the service %0 alredy installed \n").
arg(serviceName()),
QuasarAppUtils::Info);
return true;
}
return false;
savePath();
return true;
}
bool BaseInstaller::uninstall() {
if (!isInstalled()) {
QuasarAppUtils::Params::log(QString("the service %0 alredy uninstalled \n").
QuasarAppUtils::Params::log(QObject::tr("the service %0 alredy uninstalled \n").
arg(serviceName()),
QuasarAppUtils::Info);
return true;
@ -43,7 +52,7 @@ bool BaseInstaller::uninstall() {
bool BaseInstaller::enable() {
if (!isInstalled()) {
QuasarAppUtils::Params::log(QString("Cannot enabled the service %0 not installed, run install command befor enable. \n").
QuasarAppUtils::Params::log(QObject::tr("Cannot enabled the service %0 not installed, run install command befor enable. \n").
arg(serviceName()),
QuasarAppUtils::Info);
return false;
@ -54,7 +63,7 @@ bool BaseInstaller::enable() {
bool BaseInstaller::disable() {
if (!isInstalled()) {
QuasarAppUtils::Params::log(QString("Cannot disabled the service %0 not installed, run install command befor enable. \n").
QuasarAppUtils::Params::log(QObject::tr("Cannot disabled the service %0 not installed, run install command befor enable. \n").
arg(serviceName()),
QuasarAppUtils::Info);
return false;

View File

@ -10,6 +10,7 @@
#include "localsocket.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QFile>
#include <QProcess>
#include <quasarapp.h>
#include "package.h"
@ -63,7 +64,6 @@ bool ControllerPrivate::sendCmd(const QSet<Feature> &result) {
}
if (_socket->send(_parser->createPackage(Command::Feature, result))) {
_responce = false;
return true;
}
@ -73,12 +73,9 @@ bool ControllerPrivate::sendCmd(const QSet<Feature> &result) {
int ControllerPrivate::start() const {
QProcess proc;
proc.setProgram(_serviceExe);
if (_installer && _installer->isInstalled() && _installer->getExecutable().size()) {
proc.setProgram(_installer->getExecutable());
}
proc.setProgram(getExecutable());
proc.setArguments({"exec"});
proc.setArguments({"d"});
proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment());
proc.setProcessChannelMode(QProcess::SeparateChannels);
@ -104,7 +101,7 @@ bool ControllerPrivate::install() const {
return false;
}
if (!_installer->install(_serviceExe)) {
if (!_installer->install(getExecutable())) {
return false;
}
@ -126,7 +123,7 @@ bool ControllerPrivate::uninstall() const {
_controller->handleResponce({{"Result", "Uninstall service successful"}});
return _installer->uninstall();
return true;
}
bool ControllerPrivate::pause() {
@ -137,24 +134,6 @@ bool ControllerPrivate::resume() {
return sendCmd({Feature("resume")});
}
bool Patronum::ControllerPrivate::waitForResponce(int msec) {
if (!dynamic_cast<QCoreApplication*>(QCoreApplication::instance())) {
QuasarAppUtils::Params::log("Before run the waitForResponce method you need run a exec method of your QApplication class.",
QuasarAppUtils::Warning);
return false;
}
qint64 waitFor = QDateTime::currentMSecsSinceEpoch() + msec;
while (!_responce && QDateTime::currentMSecsSinceEpoch() < waitFor) {
QCoreApplication::processEvents();
}
QCoreApplication::processEvents();
return _responce;
}
QList<Feature> ControllerPrivate::features() const {
return _features;
}
@ -221,7 +200,7 @@ void ControllerPrivate::handleReceve(QByteArray data) {
}
case Command::CloseConnection: {
_responce = true;
_controller->finished();
break;
}
@ -249,4 +228,16 @@ void ControllerPrivate::handleReceve(QByteArray data) {
}
}
QString ControllerPrivate::getExecutable() const {
if (QFile::exists(_serviceExe)) {
return _serviceExe;
}
if (!_installer) {
return "";
}
return _installer->getExecutable();
}
}

View File

@ -33,8 +33,6 @@ public:
bool pause();
bool resume();
bool waitForResponce(int msec);
QList<Feature> features() const;
bool isConnected() const;
@ -44,18 +42,21 @@ public:
signals:
void sigListFeatures(QList<Feature>);
private slots:
void handleReceve(QByteArray data);
private:
QString getExecutable() const;
LocalSocket *_socket = nullptr;
IController *_controller = nullptr;
bool _responce = false;
QList<Feature> _features;
QString _serviceExe = "";
Installer *_installer = nullptr;
Parser * _parser;
private slots:
void handleReceve(QByteArray data);
};
}

View File

@ -12,7 +12,7 @@
#include <QProcess>
namespace Patronum {
const QString systemDPath = "/etc/systemd/system/";
#define SYSTEMD_PATH "/etc/systemd/system/"
InstallerSystemD::InstallerSystemD(const QString& name):
BaseInstaller(name) {
@ -106,7 +106,7 @@ bool InstallerSystemD::isInstalled() const {
}
QString InstallerSystemD::absaluteServicePath() const {
return systemDPath + serviceName() + ".service";
return SYSTEMD_PATH + serviceName() + ".service";
}
}

View File

@ -13,6 +13,39 @@
/**
* @brief The Patronum namespace - It is main name space of Patronum Library.
* The Patronum library support the two work mode
* 1. Single executable mode.
* 2. Service-terminal mode.
*
* ## Single executable mode
* In this case you have a service with single executable file. All service operations (instalation deinstalation, send commnad and another) will sends from the one executable.
*
* Fits one you need to start service executable as a daemon.
* @code{bash}
* myservice daemon
* @endcode
*
* For send any command to service use the service command.
*
* @code{bash}
* myservice myCommand
* @endcode
*
* ## Service-terminal mode.
* In this mode you create two executable file.
* 1. Service is Patronum::Service
* 2. Terminal is Patronum::Controller
*
* Fits one you need to start service executable as a daemon.
* @code{bash}
* myservice daemon
* @endcode
*
* For send any command to service use the terminal executable.
*
* @code{bash}
* terminal myCommand
* @endcode
*/
namespace Patronum {}
#endif // PATRONUM_H

View File

@ -61,7 +61,7 @@ public:
QList<Feature> supportedFeatures() {
QList<Feature> res;
Feature Ping = {"Ping", ""}
Feature Ping = {"Ping", "This is description of the ping command"}
return res << Ping;
}
};
@ -87,6 +87,8 @@ public:
};
int main(int argc, char **argv) {
QCoreApplication::setApplicationName("MyServiceName"); // <--
QCoreApplication::setOrganizationName("MyCompany"); // <--
QCoreApplcication app
MyControllerApp controller;
controller.send(argc, argv);

View File

@ -9,6 +9,14 @@ QVariantMap DefaultController::getResponce() {
return _receiveData;
}
bool DefaultController::isFinished() const {
return _finished;
}
void DefaultController::handleResponce(const QVariantMap &feature) {
_receiveData = feature;
}
void DefaultController::finished() {
_finished = true;
}

View File

@ -7,13 +7,15 @@ class DefaultController : public Patronum::Controller
public:
DefaultController();
QVariantMap getResponce();
bool isFinished() const;
protected:
void handleResponce(const QVariantMap &feature);
void finished();
private:
QVariantMap _receiveData;
bool _finished = false;
};

View File

@ -18,3 +18,12 @@ bool TestUtils::wait(const bool &forWait, int msec) {
return forWait;
}
bool TestUtils::wait(std::function<bool ()> forWait, int msec) {
auto curmsec = QDateTime::currentMSecsSinceEpoch() + msec;
while (curmsec > QDateTime::currentMSecsSinceEpoch() && !forWait()) {
QCoreApplication::processEvents();
}
QCoreApplication::processEvents();
return forWait();
}

View File

@ -8,6 +8,7 @@ class TestUtils
public:
TestUtils();
static bool wait(const bool &forWait, int msec);
static bool wait(std::function<bool ()> forWait, int msec);
};

View File

@ -39,6 +39,8 @@ testPatronum::testPatronum() {
}
void testPatronum::testPing() {
TestUtils utils;
const char* arg[] = {
"/",
"ping"
@ -46,11 +48,13 @@ void testPatronum::testPing() {
DefaultController cli;
QuasarAppUtils::Params::clearParsedData();
QVERIFY(cli.send(2 , const_cast<char**>(arg)));
QVERIFY(cli.waitForResponce(1000));
QVERIFY(utils.wait([&cli](){return cli.isFinished();}, 1000));
QVERIFY(cli.getResponce().value("Result") == "pong");
}
void testPatronum::testRandomCommad() {
TestUtils utils;
const char* arg[] = {
"/",
"fd"
@ -59,7 +63,7 @@ void testPatronum::testRandomCommad() {
QuasarAppUtils::Params::clearParsedData();
QVERIFY(cli.send(2 , const_cast<char**>(arg)));
QVERIFY(cli.waitForResponce(1000));
QVERIFY(utils.wait([&cli](){return cli.isFinished();}, 1000));
QVERIFY(cli.getResponce().contains("Error"));
}
@ -74,6 +78,8 @@ void testPatronum::connectTest() {
QCoreApplication::exit(0);
});
QuasarAppUtils::Params::parseParams({"s"});
QVERIFY(serv.exec() == 0);
}