5#include "localserver.h"
7#include "protocolfastcgi.h"
8#include "protocolhttp.h"
9#include "protocolhttp2.h"
11#include "serverengine.h"
13#include "tcpserverbalancer.h"
18# include "windowsfork.h"
22# include "../EventLoopEPoll/eventdispatcher_epoll.h"
23# include "systemdnotify.h"
28#include <QCommandLineParser>
29#include <QCoreApplication>
31#include <QLoggingCategory>
32#include <QMetaProperty>
33#include <QPluginLoader>
35#include <QSocketNotifier>
40Q_LOGGING_CATEGORY(CUTELYST_SERVER,
"cutelyst.server", QtWarningMsg)
47 , d_ptr(new ServerPrivate(this))
51 if (!qEnvironmentVariableIsSet(
"QT_MESSAGE_PATTERN")) {
52 if (qEnvironmentVariableIsSet(
"JOURNAL_STREAM")) {
54 qSetMessagePattern(u
"%{category}[%{type}] %{message}"_s);
56 qSetMessagePattern(u
"%{pid}:%{threadid} %{category}[%{type}] %{message}"_s);
61 if (!qEnvironmentVariableIsSet(
"CUTELYST_QT_EVENT_LOOP")) {
62 qCInfo(CUTELYST_SERVER) <<
"Trying to install EPoll event loop";
67 auto cleanUp = [
this]() {
70 d->protoHTTP =
nullptr;
73 d->protoHTTP2 =
nullptr;
76 d->protoFCGI =
nullptr;
79 d->mainEngine =
nullptr;
81 qDeleteAll(d->servers);
92 std::cout <<
"Cutelyst-Server terminated" <<
'\n';
103 qtTrId(
"cutelystd-cli-desc"));
112 qtTrId(
"cutelystd-opt-ini-desc"),
115 qtTrId(
"cutelystd-opt-value-file"));
123 qtTrId(
"cutelystd-opt-json-desc"),
124 qtTrId(
"cutelystd-opt-value-file"));
131 qtTrId(
"cutelystd-opt-chdir-desc"),
134 qtTrId(
"cutelystd-opt-value-directory"));
141 qtTrId(
"cutelystd-opt-chdir2-desc"),
142 qtTrId(
"cutelystd-opt-value-directory"));
149 qtTrId(
"cutelystd-opt-lazy-desc"));
155 qtTrId(
"cutelystd-opt-application-desc"),
156 qtTrId(
"cutelystd-opt-value-file"));
163 qtTrId(
"cutelystd-opt-threads-desc"),
166 qtTrId(
"cutelystd-opt-threads-value"));
174 qtTrId(
"cutelystd-opt-processes-desc"),
177 qtTrId(
"cutelystd-opt-processes-value"));
184 qtTrId(
"cutelystd-opt-master-desc"));
190 qtTrId(
"cutelystd-opt-listen-desc"),
193 qtTrId(
"cutelystd-opt-value-size"));
199 qtTrId(
"cutelystd-opt-buffer-size-desc"),
202 qtTrId(
"cutelystd-opt-value-bytes"));
211 qtTrId(
"cutelystd-opt-post-buffering-desc"),
212 qtTrId(
"cutelystd-opt-value-bytes"));
216 u
"post-buffering-bufsize"_s,
219 qtTrId(
"cutelystd-opt-post-buffering-bufsize-desc"),
220 qtTrId(
"cutelystd-opt-value-bytes"));
221 parser.
addOption(postBufferingBufsizeOpt);
226 qtTrId(
"cutelystd-opt-http-socket-desc"),
229 qtTrId(
"cutelystd-opt-value-address"));
233 {u
"http2-socket"_s, u
"h2"_s},
236 qtTrId(
"cutelystd-opt-http2-socket-desc"),
237 qtTrId(
"cutelystd-opt-value-address"));
243 qtTrId(
"cutelystd-opt-http2-header-table-size-desc"),
244 qtTrId(
"cutelystd-opt-value-size"));
245 parser.
addOption(http2HeaderTableSizeOpt);
250 qtTrId(
"cutelystd-opt-upgrade-h2c-desc"));
256 qtTrId(
"cutelystd-opt-https-h2-desc"));
262 qtTrId(
"cutelystd-opt-https-socket-desc"),
264 qtTrId(
"cutelystd-opt-value-httpsaddress"));
271 qtTrId(
"cutelystd-opt-fastcgi-socket-desc"),
272 qtTrId(
"cutelystd-opt-value-address"));
279 qtTrId(
"cutelystd-opt-socket-access-desc"),
282 qtTrId(
"cutelystd-opt-socket-access-value"));
288 qtTrId(
"cutelystd-opt-socket-timeout-desc"),
291 qtTrId(
"cutelystd-opt-socket-timeout-value"));
300 qtTrId(
"cutelystd-opt-static-map-desc"),
303 qtTrId(
"cutelystd-opt-value-static-map"));
310 qtTrId(
"cutelystd-opt-static-map2-desc"),
313 qtTrId(
"cutelystd-opt-value-static-map"));
320 qtTrId(
"cutelystd-opt-auto-restart-desc"));
328 qtTrId(
"cutelystd-opt-touch-reload-desc"),
329 qtTrId(
"cutelystd-opt-value-file"));
335 qtTrId(
"cutelystd-opt-tcp-nodelay-desc"));
341 qtTrId(
"cutelystd-opt-so-keepalive-desc"));
348 qtTrId(
"cutelystd-opt-socket-sndbuf-desc"),
349 qtTrId(
"cutelystd-opt-value-bytes"));
356 qtTrId(
"cutelystd-opt-socket-rcvbuf-desc"),
357 qtTrId(
"cutelystd-opt-value-bytes"));
364 qtTrId(
"cutelystd-opt-websocket-max-size-desc"),
367 qtTrId(
"cutelystd-opt-websocket-max-size-value"));
373 qtTrId(
"cutelystd-opt-pidfile-desc"),
376 qtTrId(
"cutelystd-opt-value-pidfile"));
382 qtTrId(
"cutelystd-opt-pidfile2-desc"),
383 qtTrId(
"cutelystd-opt-value-pidfile"));
390 qtTrId(
"cutelystd-opt-stop-desc"),
391 qtTrId(
"cutelystd-opt-value-pidfile"));
397 qtTrId(
"cutelystd-opt-uid-desc"),
400 qtTrId(
"cutelystd-opt-uid-value"));
406 qtTrId(
"cutelystd-opt-gid-desc"),
409 qtTrId(
"cutelystd-opt-gid-value"));
415 qtTrId(
"cutelystd-opt-no-init-groups-desc"));
421 qtTrId(
"cutelystd-opt-chown-socket-desc"),
424 qtTrId(
"cutelystd-opt-chown-socket-value"));
430 qtTrId(
"cutelystd-opt-umask-desc"),
433 qtTrId(
"cutelystd-opt-umask-value"));
440 qtTrId(
"cutelystd-opt-cpu-affinity-desc"),
443 qtTrId(
"cutelystd-opt-cpu-affinity-value"));
451 qtTrId(
"cutelystd-opt-reuse-port-desc"));
456 u
"experimental-thread-balancer"_s,
459 qtTrId(
"cutelystd-opt-experimental-thread-balancer-desc"));
465 qtTrId(
"cutelystd-opt-using-frontend-proxy-desc"));
471 setIni(parser.
values(iniOpt));
473 setJson(parser.
values(jsonOpt));
475 if (parser.
isSet(chdirOpt)) {
476 setChdir(parser.
value(chdirOpt));
479 if (parser.
isSet(chdir2Opt)) {
480 setChdir2(parser.
value(chdir2Opt));
483 if (parser.
isSet(threadsOpt)) {
484 setThreads(parser.
value(threadsOpt));
487 if (parser.
isSet(socketAccessOpt)) {
488 setSocketAccess(parser.
value(socketAccessOpt));
491 if (parser.
isSet(socketTimeoutOpt)) {
493 auto size = parser.
value(socketTimeoutOpt).
toInt(&ok);
494 setSocketTimeout(size);
495 if (!ok || size < 0) {
500 if (parser.
isSet(pidfileOpt)) {
501 setPidfile(parser.
value(pidfileOpt));
504 if (parser.
isSet(pidfile2Opt)) {
505 setPidfile2(parser.
value(pidfile2Opt));
509 if (parser.
isSet(stopOpt)) {
510 UnixFork::stopSERVER(parser.
value(stopOpt));
513 if (parser.
isSet(processesOpt)) {
514 setProcesses(parser.
value(processesOpt));
517 if (parser.
isSet(uidOpt)) {
518 setUid(parser.
value(uidOpt));
521 if (parser.
isSet(gidOpt)) {
522 setGid(parser.
value(gidOpt));
525 if (parser.
isSet(noInitgroupsOpt)) {
526 setNoInitgroups(
true);
529 if (parser.
isSet(chownSocketOpt)) {
530 setChownSocket(parser.
value(chownSocketOpt));
533 if (parser.
isSet(umaskOpt)) {
534 setUmask(parser.
value(umaskOpt));
537 if (parser.
isSet(cpuAffinityOpt)) {
539 auto value = parser.
value(cpuAffinityOpt).
toInt(&ok);
540 setCpuAffinity(value);
541 if (!ok || value < 0) {
548 if (parser.
isSet(reusePortOpt)) {
553 if (parser.
isSet(lazyOpt)) {
557 if (parser.
isSet(listenQueueOpt)) {
559 auto size = parser.
value(listenQueueOpt).
toInt(&ok);
560 setListenQueue(size);
561 if (!ok || size < 1) {
566 if (parser.
isSet(bufferSizeOpt)) {
568 auto size = parser.
value(bufferSizeOpt).
toInt(&ok);
570 if (!ok || size < 1) {
575 if (parser.
isSet(postBufferingOpt)) {
578 setPostBuffering(size);
579 if (!ok || size < 1) {
584 if (parser.
isSet(postBufferingBufsizeOpt)) {
587 setPostBufferingBufsize(size);
588 if (!ok || size < 1) {
593 if (parser.
isSet(applicationOpt)) {
594 setApplication(parser.
value(applicationOpt));
597 if (parser.
isSet(masterOpt)) {
601 if (parser.
isSet(autoReloadOpt)) {
605 if (parser.
isSet(tcpNoDelay)) {
609 if (parser.
isSet(soKeepAlive)) {
610 setSoKeepalive(
true);
613 if (parser.
isSet(upgradeH2cOpt)) {
617 if (parser.
isSet(httpsH2Opt)) {
621 if (parser.
isSet(socketSndbufOpt)) {
623 auto size = parser.
value(socketSndbufOpt).
toInt(&ok);
624 setSocketSndbuf(size);
625 if (!ok || size < 1) {
630 if (parser.
isSet(socketRcvbufOpt)) {
632 auto size = parser.
value(socketRcvbufOpt).
toInt(&ok);
633 setSocketRcvbuf(size);
634 if (!ok || size < 1) {
639 if (parser.
isSet(wsMaxSize)) {
641 auto size = parser.
value(wsMaxSize).
toInt(&ok);
642 setWebsocketMaxSize(size);
643 if (!ok || size < 1) {
648 if (parser.
isSet(http2HeaderTableSizeOpt)) {
650 auto size = parser.
value(http2HeaderTableSizeOpt).
toUInt(&ok);
651 setHttp2HeaderTableSize(size);
652 if (!ok || size < 1) {
657 if (parser.
isSet(frontendProxy)) {
658 setUsingFrontendProxy(
true);
661 setHttpSocket(httpSocket() + parser.
values(httpSocketOpt));
663 setHttp2Socket(http2Socket() + parser.
values(http2SocketOpt));
665 setHttpsSocket(httpsSocket() + parser.
values(httpsSocketOpt));
667 setFastcgiSocket(fastcgiSocket() + parser.
values(fastcgiSocketOpt));
669 setStaticMap(staticMap() + parser.
values(staticMapOpt));
671 setStaticMap2(staticMap2() + parser.
values(staticMap2Opt));
673 setTouchReload(touchReload() + parser.
values(touchReloadOpt));
675 d->threadBalancer = parser.
isSet(threadBalancerOpt);
681 std::cout <<
"Cutelyst-Server starting" <<
'\n';
683 if (!qEnvironmentVariableIsSet(
"CUTELYST_SERVER_IGNORE_MASTER") && !d->master) {
685 <<
"*** WARNING: you are running Cutelyst-Server without its master process manager ***"
690 if (d->processes == -1 && d->threads == -1) {
691 d->processes = UnixFork::idealProcessCount();
692 d->threads = UnixFork::idealThreadCount() / d->processes;
693 }
else if (d->processes == -1) {
694 d->processes = UnixFork::idealThreadCount();
695 }
else if (d->threads == -1) {
696 d->threads = UnixFork::idealThreadCount();
699 if (d->processes == 0 && d->master) {
702 d->genericFork =
new UnixFork(d->processes, qMax(d->threads, 1), !d->userEventLoop,
this);
704 if (d->processes == -1) {
707 if (d->threads == -1) {
718 if (d->master && d->lazy) {
719 if (d->autoReload && !d->application.isEmpty()) {
720 d->touchReload.append(d->application);
722 d->genericFork->setTouchReload(d->touchReload);
726 if (d->master && !d->genericFork->continueMaster(&ret)) {
731 if (systemdNotify::is_systemd_notify_available()) {
733 sd->setWatchdog(
true, systemdNotify::sd_watchdog_enabled(
true));
735 sd->sendStatus(qApp->applicationName().toLatin1() +
" is ready");
738 connect(d, &ServerPrivate::postForked, sd, [sd] { sd->setWatchdog(
false); });
739 qInfo(CUTELYST_SERVER) <<
"systemd notify detected";
747 if (!d->listenTcpSockets()) {
754 if (!d->writePidFile(d->pidfile)) {
760 bool isListeningLocalSockets =
false;
761 if (!d->chownSocket.isEmpty()) {
762 if (!d->listenLocalSockets()) {
767 isListeningLocalSockets =
true;
770 if (!d->umask.isEmpty() && !UnixFork::setUmask(d->umask.toLatin1())) {
774 if (!UnixFork::setGidUid(d->gid, d->uid, d->noInitgroups)) {
780 if (!isListeningLocalSockets) {
782 d->listenLocalSockets();
788 if (!d->listenTcpSockets()) {
794 if (d->servers.empty()) {
795 std::cout <<
"Please specify a socket to listen to" <<
'\n';
801 d->writePidFile(d->pidfile2);
803 if (!d->chdir.isEmpty()) {
804 std::cout <<
"Changing directory to: " << d->chdir.toLatin1().constData() <<
'\n';
815 if (!d->setupApplication()) {
822 if (d->userEventLoop) {
827 ret = d->genericFork->exec(d->lazy, d->master);
845 d->userEventLoop =
true;
850 qputenv(
"CUTELYST_SERVER_IGNORE_MASTER", QByteArrayLiteral(
"1"));
852 if (
exec(app) == 0) {
862 if (d->userEventLoop) {
867ServerPrivate::~ServerPrivate()
874bool ServerPrivate::listenTcpSockets()
876 if (httpSockets.isEmpty() && httpsSockets.isEmpty() && http2Sockets.isEmpty() &&
877 fastcgiSockets.isEmpty()) {
883 bool httpOk = std::ranges::all_of(httpSockets, [
this](
const auto &socket) {
884 return listenTcp(socket, getHttpProto(),
false);
891 bool httpsOk = std::ranges::all_of(httpsSockets, [
this](
const auto &socket) {
892 return listenTcp(socket, getHttpProto(),
true);
899 bool http2Ok = std::ranges::all_of(http2Sockets, [
this](
const auto &socket) {
900 return listenTcp(socket, getHttp2Proto(),
false);
907 bool allOk = std::ranges::all_of(fastcgiSockets, [
this](
const QString &socket) {
908 return listenTcp(socket, getFastCgiProto(),
false);
914bool ServerPrivate::listenTcp(
const QString &line,
Protocol *protocol,
bool secure)
921 server->setBalancer(threadBalancer);
922 ret = server->listen(line, protocol, secure);
924 if (ret && server->socketDescriptor()) {
925 auto qEnum = Protocol::staticMetaObject.enumerator(0);
926 std::cout << qEnum.valueToKey(
static_cast<int>(protocol->type())) <<
" socket "
928 <<
" bound to TCP address " << server->serverName().constData() <<
" fd "
930 servers.emplace_back(server);
937bool ServerPrivate::listenLocalSockets()
946 std::vector<int> fds = systemdNotify::listenFds();
949 if (server->listen(fd)) {
950 const QString name = server->serverName();
951 const QString fullName = server->fullServerName();
955 protocol = getHttpProto();
957 protocol = getHttp2Proto();
959 protocol = getFastCgiProto();
961 std::cerr <<
"systemd activated socket does not match any configured socket"
965 server->setProtocol(protocol);
966 server->pauseAccepting();
968 auto qEnum = Protocol::staticMetaObject.enumerator(0);
969 std::cout << qEnum.valueToKey(
static_cast<int>(protocol->type())) <<
" socket "
971 <<
" bound to LOCAL address " << qPrintable(fullName) <<
" fd "
973 servers.push_back(server);
975 std::cerr <<
"Failed to listen on activated LOCAL FD: "
977 << qPrintable(server->errorString()) <<
'\n';
984 const auto httpConst = http;
985 for (
const auto &socket : httpConst) {
986 ret |= listenLocal(socket, getHttpProto());
989 const auto http2Const = http2;
990 for (
const auto &socket : http2Const) {
991 ret |= listenLocal(socket, getHttp2Proto());
994 const auto fastcgiConst = fastcgi;
995 for (
const auto &socket : fastcgiConst) {
996 ret |= listenLocal(socket, getFastCgiProto());
1002bool ServerPrivate::listenLocal(
const QString &line,
Protocol *protocol)
1009 server->setProtocol(protocol);
1010 if (!socketAccess.isEmpty()) {
1012 if (socketAccess.contains(u
'u')) {
1016 if (socketAccess.contains(u
'g')) {
1020 if (socketAccess.contains(u
'o')) {
1023 server->setSocketOptions(options);
1027 server->setListenBacklogSize(listenQueue);
1028 ret = server->listen(line);
1029 server->pauseAccepting();
1031 if (!ret || !server->socket()) {
1032 std::cerr <<
"Failed to listen on LOCAL: " << qPrintable(line) <<
" : "
1033 << qPrintable(server->errorString()) <<
'\n';
1038 if (!chownSocket.isEmpty()) {
1039 UnixFork::chownSocket(line, chownSocket);
1042 auto qEnum = Protocol::staticMetaObject.enumerator(0);
1043 std::cout << qEnum.valueToKey(
static_cast<int>(protocol->type())) <<
" socket "
1045 <<
" bound to LOCAL address " << qPrintable(line) <<
" fd "
1047 servers.push_back(server);
1053void Server::setApplication(
const QString &application)
1058 if (loader.fileName().isEmpty()) {
1063 d->application = loader.fileName();
1071 return d->application;
1074void Server::setThreads(
const QString &threads)
1088 if (d->threads == -1) {
1094void Server::setProcesses(
const QString &process)
1101 d->processes = process.
toInt();
1110 if (d->processes == -1) {
1116void Server::setChdir(
const QString &chdir)
1129void Server::setHttpSocket(
const QStringList &httpSocket)
1132 d->httpSockets = httpSocket;
1139 return d->httpSockets;
1142void Server::setHttp2Socket(
const QStringList &http2Socket)
1145 d->http2Sockets = http2Socket;
1152 return d->http2Sockets;
1155void Server::setHttp2HeaderTableSize(quint32 headerTableSize)
1158 d->http2HeaderTableSize = headerTableSize;
1162quint32 Server::http2HeaderTableSize()
const
1165 return d->http2HeaderTableSize;
1168void Server::setUpgradeH2c(
bool enable)
1171 d->upgradeH2c = enable;
1175bool Server::upgradeH2c()
const
1178 return d->upgradeH2c;
1181void Server::setHttpsH2(
bool enable)
1184 d->httpsH2 = enable;
1188bool Server::httpsH2()
const
1194void Server::setHttpsSocket(
const QStringList &httpsSocket)
1197 d->httpsSockets = httpsSocket;
1204 return d->httpsSockets;
1207void Server::setFastcgiSocket(
const QStringList &fastcgiSocket)
1210 d->fastcgiSockets = fastcgiSocket;
1217 return d->fastcgiSockets;
1220void Server::setSocketAccess(
const QString &socketAccess)
1223 d->socketAccess = socketAccess;
1227QString Server::socketAccess()
const
1230 return d->socketAccess;
1233void Server::setSocketTimeout(
int timeout)
1236 d->socketTimeout = timeout;
1240int Server::socketTimeout()
const
1243 return d->socketTimeout;
1246void Server::setChdir2(
const QString &chdir2)
1262 d->ini.append(files);
1263 d->ini.removeDuplicates();
1266 for (
const QString &file : files) {
1267 if (!d->configLoaded.contains(file)) {
1268 auto fileToLoad = std::make_pair(file, ServerPrivate::ConfigFormat::Ini);
1269 if (!d->configToLoad.contains(fileToLoad)) {
1270 qCDebug(CUTELYST_SERVER) <<
"Enqueue INI config file:" << file;
1271 d->configToLoad.enqueue(fileToLoad);
1288 d->json.append(files);
1289 d->json.removeDuplicates();
1292 for (
const QString &file : files) {
1293 if (!d->configLoaded.contains(file)) {
1294 auto fileToLoad = std::make_pair(file, ServerPrivate::ConfigFormat::Json);
1295 if (!d->configToLoad.contains(fileToLoad)) {
1296 qCDebug(CUTELYST_SERVER) <<
"Enqueue JSON config file:" << file;
1297 d->configToLoad.enqueue(fileToLoad);
1311void Server::setStaticMap(
const QStringList &staticMap)
1314 d->staticMaps = staticMap;
1321 return d->staticMaps;
1324void Server::setStaticMap2(
const QStringList &staticMap)
1327 d->staticMaps2 = staticMap;
1334 return d->staticMaps2;
1337void Server::setMaster(
bool enable)
1340 if (!qEnvironmentVariableIsSet(
"CUTELYST_SERVER_IGNORE_MASTER")) {
1352void Server::setAutoReload(
bool enable)
1356 d->autoReload =
true;
1361bool Server::autoReload()
const
1364 return d->autoReload;
1367void Server::setTouchReload(
const QStringList &files)
1370 d->touchReload = files;
1377 return d->touchReload;
1380void Server::setListenQueue(
int size)
1383 d->listenQueue = size;
1387int Server::listenQueue()
const
1390 return d->listenQueue;
1393void Server::setBufferSize(
int size)
1397 qCWarning(CUTELYST_SERVER) <<
"Buffer size must be at least 4096 bytes, ignoring";
1400 d->bufferSize = size;
1404int Server::bufferSize()
const
1407 return d->bufferSize;
1410void Server::setPostBuffering(qint64 size)
1413 d->postBuffering = size;
1417qint64 Server::postBuffering()
const
1420 return d->postBuffering;
1423void Server::setPostBufferingBufsize(qint64 size)
1427 qCWarning(CUTELYST_SERVER) <<
"Post buffer size must be at least 4096 bytes, ignoring";
1430 d->postBufferingBufsize = size;
1434qint64 Server::postBufferingBufsize()
const
1437 return d->postBufferingBufsize;
1440void Server::setTcpNodelay(
bool enable)
1443 d->tcpNodelay = enable;
1447bool Server::tcpNodelay()
const
1450 return d->tcpNodelay;
1453void Server::setSoKeepalive(
bool enable)
1456 d->soKeepalive = enable;
1460bool Server::soKeepalive()
const
1463 return d->soKeepalive;
1466void Server::setSocketSndbuf(
int value)
1469 d->socketSendBuf = value;
1473int Server::socketSndbuf()
const
1476 return d->socketSendBuf;
1479void Server::setSocketRcvbuf(
int value)
1482 d->socketReceiveBuf = value;
1486int Server::socketRcvbuf()
const
1489 return d->socketReceiveBuf;
1492void Server::setWebsocketMaxSize(
int value)
1495 d->websocketMaxSize = value * 1024;
1499int Server::websocketMaxSize()
const
1502 return d->websocketMaxSize / 1024;
1505void Server::setPidfile(
const QString &file)
1518void Server::setPidfile2(
const QString &file)
1531void Server::setUid(
const QString &uid)
1546void Server::setGid(
const QString &gid)
1561void Server::setNoInitgroups(
bool enable)
1565 d->noInitgroups = enable;
1570bool Server::noInitgroups()
const
1573 return d->noInitgroups;
1576void Server::setChownSocket(
const QString &chownSocket)
1580 d->chownSocket = chownSocket;
1585QString Server::chownSocket()
const
1588 return d->chownSocket;
1591void Server::setUmask(
const QString &value)
1606void Server::setCpuAffinity(
int value)
1610 d->cpuAffinity = value;
1615int Server::cpuAffinity()
const
1618 return d->cpuAffinity;
1621void Server::setReusePort(
bool enable)
1625 d->reusePort = enable;
1632bool Server::reusePort()
const
1635 return d->reusePort;
1638void Server::setLazy(
bool enable)
1651void Server::setUsingFrontendProxy(
bool enable)
1654 d->usingFrontendProxy = enable;
1658bool Server::usingFrontendProxy()
const
1661 return d->usingFrontendProxy;
1670bool ServerPrivate::setupApplication()
1677 std::cout <<
"Loading application: " << application.
toLatin1().
constData() <<
'\n';
1680 if (!loader.load()) {
1681 qCCritical(CUTELYST_SERVER) <<
"Could not load application:" << loader.errorString();
1685 QObject *instance = loader.instance();
1687 qCCritical(CUTELYST_SERVER) <<
"Could not get a QObject instance: %s\n"
1688 << loader.errorString();
1692 localApp = qobject_cast<Cutelyst::Application *>(instance);
1694 qCCritical(CUTELYST_SERVER)
1695 <<
"Could not cast Cutelyst::Application from instance: %s\n"
1696 << loader.errorString();
1707 if (!chdir2.isEmpty()) {
1708 std::cout <<
"Changing directory2 to: " << chdir2.toLatin1().constData() <<
'\n';
1717 mainEngine = createEngine(localApp, 0);
1718 for (
int i = 1; i < threads; ++i) {
1719 if (createEngine(localApp, i)) {
1720 ++workersNotRunning;
1724 mainEngine = createEngine(localApp, 0);
1725 workersNotRunning = 1;
1729 std::cerr <<
"Application failed to init, cheaping..." <<
'\n';
1736void ServerPrivate::engineShutdown(
ServerEngine *engine)
1738 const auto engineThread = engine->
thread();
1741 auto [first, last] = std::ranges::remove(engines, engine);
1742 engines.erase(first, last);
1743 checkEngineShutdown();
1745 engineThread->quit();
1747 auto [first, last] = std::ranges::remove(engines, engine);
1748 engines.erase(first, last);
1751 checkEngineShutdown();
1754void ServerPrivate::checkEngineShutdown()
1756 if (engines.empty()) {
1757 if (userEventLoop) {
1759 Q_EMIT q->stopped();
1766void ServerPrivate::workerStarted()
1771 if (--workersNotRunning == 0) {
1776bool ServerPrivate::postFork(
int workerId)
1781 if (!setupApplication()) {
1782 Q_EMIT q->errorOccured(qtTrId(
"cutelystd-err-fail-setup-app"));
1787 if (engines.size() > 1) {
1788 qCDebug(CUTELYST_SERVER) <<
"Starting threads";
1793 if (thread != qApp->thread()) {
1795 if (!qEnvironmentVariableIsSet(
"CUTELYST_QT_EVENT_LOOP")) {
1805 Q_EMIT postForked(workerId);
1813 qApp->processEvents();
1819bool ServerPrivate::writePidFile(
const QString &filename)
1825 QFile file(filename);
1827 std::cerr <<
"Failed write pid file " << qPrintable(filename) <<
'\n';
1831 std::cout <<
"Writing pidfile to " << qPrintable(filename) <<
'\n';
1842 if (workerCore > 0) {
1845 qFatal(
"*** FATAL *** Could not create a NEW instance of your Cutelyst::Application, "
1846 "make sure your constructor has Q_INVOKABLE macro or disable threaded mode.");
1850 auto engine =
new ServerEngine(app, workerCore, opt, q);
1855 &ServerEngine::shutdownCompleted,
1857 &ServerPrivate::engineShutdown,
1863 engine->setServers(servers);
1864 if (!engine->
init()) {
1865 std::cerr <<
"Application failed to init(), cheaping core: " << workerCore <<
'\n';
1870 engines.push_back(engine);
1873 if (workerCore > 0) {
1878 auto thread =
new QThread(
this);
1887void ServerPrivate::loadConfig()
1889 if (loadingConfig) {
1893 loadingConfig =
true;
1895 if (configToLoad.isEmpty()) {
1896 loadingConfig =
false;
1900 auto fileToLoad = configToLoad.dequeue();
1902 if (fileToLoad.first.isEmpty()) {
1903 qCWarning(CUTELYST_SERVER) <<
"Can not load config from empty config file name";
1904 loadingConfig =
false;
1908 if (configLoaded.contains(fileToLoad.first)) {
1909 loadingConfig =
false;
1913 configLoaded.append(fileToLoad.first);
1915 QVariantMap loadedConfig;
1916 switch (fileToLoad.second) {
1917 case ConfigFormat::Ini:
1918 qCInfo(CUTELYST_SERVER) <<
"Loading INI configuratin:" << fileToLoad.first;
1921 case ConfigFormat::Json:
1922 qCInfo(CUTELYST_SERVER) <<
"Loading JSON configuration:" << fileToLoad.first;
1927 for (
const auto &[key, value] : std::as_const(loadedConfig).asKeyValueRange()) {
1928 if (config.contains(key)) {
1929 QVariantMap currentMap = config.value(key).toMap();
1930 const QVariantMap loadedMap = value.toMap();
1931 for (
const auto &[mapKey, mapValue] : loadedMap.asKeyValueRange()) {
1932 currentMap.insert(mapKey, mapValue);
1934 config.insert(key, currentMap);
1936 config.insert(key, value);
1940 QVariantMap sessionConfig = loadedConfig.value(u
"server"_s).toMap();
1942 applyConfig(sessionConfig);
1944 opt.insert(sessionConfig);
1946 loadingConfig =
false;
1948 if (!configToLoad.empty()) {
1953void ServerPrivate::applyConfig(
const QVariantMap &config)
1957 for (
const auto &[key, value] : config.asKeyValueRange()) {
1967 if (prop.
userType() == value.userType()) {
1970 prop.
write(q, currentValues + value.toStringList());
1972 prop.
write(q, value);
1978 prop.
write(q, value);
1983Protocol *ServerPrivate::getHttpProto()
2005Protocol *ServerPrivate::getFastCgiProto()
2014#include "moc_server.cpp"
2015#include "moc_server_p.cpp"
The Cutelyst application.
static QVariantMap loadJsonConfig(const QString &filename)
void setConfig(const QVariantMap &config)
static QVariantMap loadIniConfig(const QString &filename)
virtual bool init() override
void errorOccured(const QString &error)
bool start(Cutelyst::Application *app=nullptr)
int exec(Cutelyst::Application *app=nullptr)
void parseCommandLine(const QStringList &args)
Server(QObject *parent=nullptr)
QVariantMap config() const noexcept
The Cutelyst namespace holds all public Cutelyst API.
const char * constData() const const
QByteArray number(double n, char format, int precision)
QCommandLineOption addHelpOption()
bool addOption(const QCommandLineOption &option)
QCommandLineOption addVersionOption()
bool isSet(const QCommandLineOption &option) const const
void process(const QCoreApplication &app)
void setApplicationDescription(const QString &description)
void showHelp(int exitCode)
QString value(const QCommandLineOption &option) const const
QStringList values(const QCommandLineOption &option) const const
void addLibraryPath(const QString &path)
void setEventDispatcher(QAbstractEventDispatcher *eventDispatcher)
bool setCurrent(const QString &path)
bool removeOne(const AT &t)
bool removeServer(const QString &name)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void moveToThread(QThread *targetThread)
void setParent(QObject *parent)
QThread * thread() const const
int compare(QLatin1StringView s1, const QString &s2, Qt::CaseSensitivity cs)
QString fromLatin1(QByteArrayView str)
bool isEmpty() const const
QString number(double n, char format, int precision)
QString & replace(QChar before, QChar after, Qt::CaseSensitivity cs)
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
int toInt(bool *ok, int base) const const
QByteArray toLatin1() const const
qlonglong toLongLong(bool *ok, int base) const const
uint toUInt(bool *ok, int base) const const
QFuture< ArgsType< Signal > > connect(Sender *sender, Signal signal)
QThread * currentThread()
void setEventDispatcher(QAbstractEventDispatcher *eventDispatcher)
void start(QThread::Priority priority)
QStringList toStringList() const const