add KeepAlive, Status and Buffered Reads

This commit is contained in:
Syping 2023-08-09 20:58:21 +02:00
parent 529a4a8be9
commit 95db23458f
6 changed files with 106 additions and 36 deletions

View file

@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.5) cmake_minimum_required(VERSION 3.5)
project(smsub LANGUAGES CXX) project(smsub LANGUAGES CXX VERSION 0.7)
set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_INCLUDE_CURRENT_DIR ON)

View file

@ -22,8 +22,8 @@
#include "smsub.h" #include "smsub.h"
#include <QDebug> #include <QDebug>
SMSubProcess::SMSubProcess(const QString &executable, const QStringList &arguments, const QString &workingDirectory, const int &termTimeout) : SMSubProcess::SMSubProcess(const QString &executable, const QStringList &arguments, const QString &workingDirectory, const int &termTimeout, const bool &keepAlive) :
termTimeout(termTimeout) termTimeout(termTimeout), keepAlive(keepAlive)
{ {
// Set process executable, arguments and working directory // Set process executable, arguments and working directory
process.setProgram(executable); process.setProgram(executable);
@ -41,26 +41,31 @@ SMSubProcess::SMSubProcess(const QString &executable, const QStringList &argumen
QObject::connect(&process, &QProcess::errorOccurred, this, &SMSubProcess::processError); QObject::connect(&process, &QProcess::errorOccurred, this, &SMSubProcess::processError);
QObject::connect(&process, &QProcess::started, this, [=]() { QObject::connect(&process, &QProcess::started, this, [=]() {
QTextStream(stderr) << "Subprocess started!" << smsub_endl; QTextStream(stderr) << "Subprocess started!" << smsub_endl;
emit statusUpdated(true);
}); });
QObject::connect(&process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [=](int exitCode) { QObject::connect(&process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [=](int exitCode) {
QTextStream(stderr) << "Subprocess exited!" << smsub_endl; QTextStream(stderr) << "Subprocess exited!" << smsub_endl;
// Exit with the same exit code as the process // Exit with the same exit code as the process
emit processStopped(); emit statusUpdated(false);
QCoreApplication::exit(exitCode); if (!keepAlive)
QCoreApplication::exit(exitCode);
}); });
} }
void SMSubProcess::start()
{
process.start(QIODevice::ReadWrite);
}
void SMSubProcess::readyRead() void SMSubProcess::readyRead()
{ {
#ifdef SMSUB_IODEBUG #ifdef SMSUB_IODEBUG
QTextStream(stderr) << "Subprocess I/O RR!" << smsub_endl; QTextStream(stderr) << "Subprocess I/O RR!" << smsub_endl;
#endif #endif
// Read process output and emit event // Read process output and emit event
#ifdef SMSUB_BUFFERED_READS
#ifdef SMSUB_IODEBUG
QTextStream(stderr) << "Subprocess I/O W!" << smsub_endl;
#endif
const QByteArray readData = process.read(1024);
if (!readData.isEmpty())
emit outputWritten(readData);
#else
while (process.canReadLine()) { while (process.canReadLine()) {
#ifdef SMSUB_IODEBUG #ifdef SMSUB_IODEBUG
QTextStream(stderr) << "Subprocess I/O WL!" << smsub_endl; QTextStream(stderr) << "Subprocess I/O WL!" << smsub_endl;
@ -68,6 +73,7 @@ void SMSubProcess::readyRead()
const QByteArray readData = process.readLine().trimmed(); const QByteArray readData = process.readLine().trimmed();
emit outputWritten(readData + '\n'); emit outputWritten(readData + '\n');
} }
#endif
} }
void SMSubProcess::processError(QProcess::ProcessError error) void SMSubProcess::processError(QProcess::ProcessError error)
@ -75,11 +81,13 @@ void SMSubProcess::processError(QProcess::ProcessError error)
// Handle process errors // Handle process errors
if (Q_LIKELY(error == QProcess::FailedToStart)) { if (Q_LIKELY(error == QProcess::FailedToStart)) {
QTextStream(stderr) << "Process failed to start!" << smsub_endl; QTextStream(stderr) << "Process failed to start!" << smsub_endl;
QCoreApplication::exit(1); if (!keepAlive)
QCoreApplication::exit(1);
} }
else if (error == QProcess::UnknownError) { else if (error == QProcess::UnknownError) {
QTextStream(stderr) << "Unknown error occurred!" << smsub_endl; QTextStream(stderr) << "Unknown error occurred!" << smsub_endl;
QCoreApplication::exit(1); if (!keepAlive)
QCoreApplication::exit(1);
} }
} }
@ -94,20 +102,25 @@ void SMSubProcess::aboutToQuit()
} }
} }
void SMSubProcess::killProcess() void SMSubProcess::startProcess()
{ {
// Kill process as requested // Start process as requested
if (process.state() == QProcess::Running) { if (process.state() == QProcess::NotRunning)
process.kill(); process.start(QIODevice::ReadWrite);
}
} }
void SMSubProcess::stopProcess() void SMSubProcess::stopProcess()
{ {
// Terminate process as requested // Terminate process as requested
if (process.state() == QProcess::Running) { if (process.state() == QProcess::Running)
process.terminate(); process.terminate();
} }
void SMSubProcess::killProcess()
{
// Kill process as requested
if (process.state() == QProcess::Running)
process.kill();
} }
void SMSubProcess::writeInput(const QByteArray &input) void SMSubProcess::writeInput(const QByteArray &input)
@ -116,5 +129,6 @@ void SMSubProcess::writeInput(const QByteArray &input)
QTextStream(stderr) << "Subprocess I/O IN!" << smsub_endl; QTextStream(stderr) << "Subprocess I/O IN!" << smsub_endl;
#endif #endif
// Write input from Unix/IPC socket to process // Write input from Unix/IPC socket to process
process.write(input); if (process.state() == QProcess::Running)
process.write(input);
} }

View file

@ -26,17 +26,18 @@ class SMSubProcess : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
SMSubProcess(const QString &executable, const QStringList &arguments, const QString& workingDirectory, const int &termTimeout = 60000); SMSubProcess(const QString &executable, const QStringList &arguments, const QString &workingDirectory, const int &termTimeout = 60000, const bool &keepAlive = false);
void start();
private: private:
QProcess process; QProcess process;
int termTimeout; int termTimeout;
bool keepAlive;
public slots: public slots:
void aboutToQuit(); void aboutToQuit();
void killProcess(); void startProcess();
void stopProcess(); void stopProcess();
void killProcess();
void writeInput(const QByteArray &input); void writeInput(const QByteArray &input);
private slots: private slots:
@ -45,8 +46,7 @@ private slots:
signals: signals:
void outputWritten(const QByteArray &output); void outputWritten(const QByteArray &output);
void processStopped(); void statusUpdated(const bool status);
}; };
#endif // SMSUBPROCESS_H #endif // SMSUBPROCESS_H

View file

@ -32,6 +32,7 @@ SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &soc
type = ServerType::Local; type = ServerType::Local;
server = localServer; server = localServer;
status = false;
} }
SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &serverName, const quint16 &port) : serverSettings(serverSettings) SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &serverName, const quint16 &port) : serverSettings(serverSettings)
@ -43,6 +44,7 @@ SMSubServer::SMSubServer(SMSubServerSettings *serverSettings, const QString &ser
type = ServerType::WebSocket; type = ServerType::WebSocket;
server = webSocketServer; server = webSocketServer;
status = false;
} }
bool SMSubServer::isListening() bool SMSubServer::isListening()
@ -122,14 +124,30 @@ bool SMSubServer::messageReceived(QObject *socket, const QByteArray &message)
sendMessage(socket, "Permission denied!\n"); sendMessage(socket, "Permission denied!\n");
} }
} }
else if (message.startsWith("kill")) { else if (message.startsWith("status")) {
emit killRequested(); if (status) {
debugOutput(socket, "Killing server!"); sendMessage(socket, "Status: on\n");
}
else {
sendMessage(socket, "Status: off\n");
}
}
else if (message.startsWith("start")) {
emit startRequested();
debugOutput(socket, "Starting server!");
} }
else if (message.startsWith("stop")) { else if (message.startsWith("stop")) {
emit stopRequested(); emit stopRequested();
debugOutput(socket, "Stopping server!"); debugOutput(socket, "Stopping server!");
} }
else if (message.startsWith("kill")) {
emit killRequested();
debugOutput(socket, "Killing server!");
}
else if (message.startsWith("quit")) {
QTimer::singleShot(0, qApp, &QCoreApplication::quit);
debugOutput(socket, "Qutting smsub!");
}
else if (message.startsWith("wl")) { else if (message.startsWith("wl")) {
const QByteArray writeData = message.mid(3); const QByteArray writeData = message.mid(3);
emit inputWritten(writeData + '\n'); emit inputWritten(writeData + '\n');
@ -254,3 +272,8 @@ void SMSubServer::registerToken(const QString &token)
tokens.removeAll(token); tokens.removeAll(token);
}); });
} }
void SMSubServer::statusUpdated(const bool status_)
{
status = status_;
}

View file

@ -45,6 +45,7 @@ public:
public slots: public slots:
void writeOutput(const QByteArray &output); void writeOutput(const QByteArray &output);
void registerToken(const QString &token); void registerToken(const QString &token);
void statusUpdated(const bool status);
private slots: private slots:
void wsMessageReceived(const QByteArray &message); void wsMessageReceived(const QByteArray &message);
@ -61,12 +62,14 @@ private:
QVector<QString> tokens; QVector<QString> tokens;
ServerType type; ServerType type;
QObject *server; QObject *server;
bool status;
signals: signals:
void tokenRegistered(const QString &password); void tokenRegistered(const QString &password);
void inputWritten(const QByteArray &input); void inputWritten(const QByteArray &input);
void killRequested(); void startRequested();
void stopRequested(); void stopRequested();
void killRequested();
}; };
#endif // SMSUBSERVER_H #endif // SMSUBSERVER_H

View file

@ -134,13 +134,14 @@ int main(int argc, char *argv[])
{ {
QCoreApplication a(argc, argv); QCoreApplication a(argc, argv);
a.setApplicationName("Server Manager Subprocess"); a.setApplicationName("Server Manager Subprocess");
a.setApplicationVersion("0.6"); a.setApplicationVersion("0.7");
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
catchUnixSignals({SIGINT, SIGHUP, SIGQUIT, SIGTERM}); catchUnixSignals({SIGINT, SIGHUP, SIGQUIT, SIGTERM});
#endif #endif
bool rportSet = false; bool rportSet = false;
bool keepAlive = false;
bool timeoutSet = false; bool timeoutSet = false;
int termTimeout = 60000; int termTimeout = 60000;
quint16 rport; quint16 rport;
@ -151,6 +152,7 @@ int main(int argc, char *argv[])
QStringList argumentList; QStringList argumentList;
const QByteArray envEnvironmentMode = qgetenv("SMSUB_ENVIRONMENT_MODE"); const QByteArray envEnvironmentMode = qgetenv("SMSUB_ENVIRONMENT_MODE");
const QByteArray envKeepAlive = qgetenv("SMSUB_KEEPALIVE");
const QByteArray envManifest = qgetenv("SMSUB_JSON"); const QByteArray envManifest = qgetenv("SMSUB_JSON");
const QByteArray envExecutable = qgetenv("SMSUB_EXEC"); const QByteArray envExecutable = qgetenv("SMSUB_EXEC");
const QByteArray envArguments = qgetenv("SMSUB_ARGS"); const QByteArray envArguments = qgetenv("SMSUB_ARGS");
@ -160,7 +162,7 @@ int main(int argc, char *argv[])
const QByteArray envTimeout = qgetenv("SMSUB_TIMEOUT"); const QByteArray envTimeout = qgetenv("SMSUB_TIMEOUT");
const QByteArray envWorkDir = qgetenv("SMSUB_WORKDIR"); const QByteArray envWorkDir = qgetenv("SMSUB_WORKDIR");
if (envEnvironmentMode == "1" || envEnvironmentMode.toLower() == "true") { if (envEnvironmentMode == "1" || envEnvironmentMode.toLower() == "true" || envEnvironmentMode.toLower() == "yes") {
if (envExecutable.isEmpty() && envArguments.isEmpty()) { if (envExecutable.isEmpty() && envArguments.isEmpty()) {
QStringList arguments = a.arguments(); QStringList arguments = a.arguments();
arguments.removeFirst(); arguments.removeFirst();
@ -202,6 +204,12 @@ int main(int argc, char *argv[])
} }
} }
if (!envKeepAlive.isEmpty()) {
if (envKeepAlive == "1" || envKeepAlive.toLower() == "true" || envKeepAlive.toLower() == "yes") {
keepAlive = true;
}
}
if (!envWorkDir.isEmpty()) { if (!envWorkDir.isEmpty()) {
workingDirectory = QString::fromUtf8(envWorkDir); workingDirectory = QString::fromUtf8(envWorkDir);
} }
@ -334,6 +342,12 @@ int main(int argc, char *argv[])
executable = QString::fromUtf8(envExecutable); executable = QString::fromUtf8(envExecutable);
} }
if (!envKeepAlive.isEmpty()) {
if (envKeepAlive == "1" || envKeepAlive.toLower() == "true" || envKeepAlive.toLower() == "yes") {
keepAlive = true;
}
}
if (!envWorkDir.isEmpty()) { if (!envWorkDir.isEmpty()) {
workingDirectory = QString::fromUtf8(envWorkDir); workingDirectory = QString::fromUtf8(envWorkDir);
} }
@ -371,6 +385,16 @@ int main(int argc, char *argv[])
return 1; return 1;
} }
if (jsonObject.contains("KeepAlive")) {
const QJsonValue jsonKeepAlive = jsonObject.value("KeepAlive");
if (!jsonKeepAlive.isBool()) {
QTextStream(stderr) << "KeepAlive is not a bool in manifest, aborting!" << smsub_endl;
manifestFile.close();
return 1;
}
keepAlive = jsonKeepAlive.toBool();
}
if (jsonObject.contains("WorkingDirectory")) { if (jsonObject.contains("WorkingDirectory")) {
const QJsonValue jsonWorkingDirectory = jsonObject.value("WorkingDirectory"); const QJsonValue jsonWorkingDirectory = jsonObject.value("WorkingDirectory");
if (!jsonWorkingDirectory.isString()) { if (!jsonWorkingDirectory.isString()) {
@ -486,7 +510,7 @@ int main(int argc, char *argv[])
return 1; return 1;
} }
SMSubProcess subProcess(executable, argumentList, workingDirectory, termTimeout); SMSubProcess subProcess(executable, argumentList, workingDirectory, termTimeout, keepAlive);
SMSubServerSettings remoteSettings; SMSubServerSettings remoteSettings;
remoteSettings.canRegister = false; remoteSettings.canRegister = false;
@ -505,9 +529,11 @@ int main(int argc, char *argv[])
localSettings.canRegister = true; localSettings.canRegister = true;
QObject::connect(&subLocal, &SMSubServer::tokenRegistered, subRemote, &SMSubServer::registerToken); QObject::connect(&subLocal, &SMSubServer::tokenRegistered, subRemote, &SMSubServer::registerToken);
QObject::connect(&subProcess, &SMSubProcess::outputWritten, subRemote, &SMSubServer::writeOutput); QObject::connect(&subProcess, &SMSubProcess::outputWritten, subRemote, &SMSubServer::writeOutput);
QObject::connect(&subProcess, &SMSubProcess::statusUpdated, subRemote, &SMSubServer::statusUpdated);
QObject::connect(subRemote, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput); QObject::connect(subRemote, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(subRemote, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess); QObject::connect(subRemote, &SMSubServer::startRequested, &subProcess, &SMSubProcess::startProcess);
QObject::connect(subRemote, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess); QObject::connect(subRemote, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
QObject::connect(subRemote, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
} }
else if (rportSet) { else if (rportSet) {
SMSubServer *subRemote = new SMSubServer(&remoteSettings, QString(), rport); SMSubServer *subRemote = new SMSubServer(&remoteSettings, QString(), rport);
@ -518,21 +544,25 @@ int main(int argc, char *argv[])
localSettings.canRegister = true; localSettings.canRegister = true;
QObject::connect(&subLocal, &SMSubServer::tokenRegistered, subRemote, &SMSubServer::registerToken); QObject::connect(&subLocal, &SMSubServer::tokenRegistered, subRemote, &SMSubServer::registerToken);
QObject::connect(&subProcess, &SMSubProcess::outputWritten, subRemote, &SMSubServer::writeOutput); QObject::connect(&subProcess, &SMSubProcess::outputWritten, subRemote, &SMSubServer::writeOutput);
QObject::connect(&subProcess, &SMSubProcess::statusUpdated, subRemote, &SMSubServer::statusUpdated);
QObject::connect(subRemote, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput); QObject::connect(subRemote, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(subRemote, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess); QObject::connect(subRemote, &SMSubServer::startRequested, &subProcess, &SMSubProcess::startProcess);
QObject::connect(subRemote, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess); QObject::connect(subRemote, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
QObject::connect(subRemote, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
} }
else { else {
localSettings.canRegister = false; localSettings.canRegister = false;
} }
QObject::connect(&subProcess, &SMSubProcess::outputWritten, &subLocal, &SMSubServer::writeOutput); QObject::connect(&subProcess, &SMSubProcess::outputWritten, &subLocal, &SMSubServer::writeOutput);
QObject::connect(&subProcess, &SMSubProcess::statusUpdated, &subLocal, &SMSubServer::statusUpdated);
QObject::connect(&subLocal, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput); QObject::connect(&subLocal, &SMSubServer::inputWritten, &subProcess, &SMSubProcess::writeInput);
QObject::connect(&subLocal, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess); QObject::connect(&subLocal, &SMSubServer::startRequested, &subProcess, &SMSubProcess::startProcess);
QObject::connect(&subLocal, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess); QObject::connect(&subLocal, &SMSubServer::stopRequested, &subProcess, &SMSubProcess::stopProcess);
QObject::connect(&subLocal, &SMSubServer::killRequested, &subProcess, &SMSubProcess::killProcess);
QObject::connect(&a, &QCoreApplication::aboutToQuit, &subProcess, &SMSubProcess::aboutToQuit); QObject::connect(&a, &QCoreApplication::aboutToQuit, &subProcess, &SMSubProcess::aboutToQuit);
subProcess.start(); subProcess.startProcess();
QTextStream(stderr) << QString("SMSub Version %1 initialized!").arg(QCoreApplication::applicationVersion()) << smsub_endl; QTextStream(stderr) << QString("SMSub Version %1 initialized!").arg(QCoreApplication::applicationVersion()) << smsub_endl;