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]() {
71 d->protoHTTP =
nullptr;
74 d->protoHTTP2 =
nullptr;
77 d->protoFCGI =
nullptr;
79 qDeleteAll(d->engines);
81 d->mainEngine =
nullptr;
87 qDeleteAll(d->servers);
90 delete d->genericFork;
91 d->genericFork =
nullptr;
101 std::cout <<
"Cutelyst-Server terminated" <<
'\n';
112 qtTrId(
"cutelystd-cli-desc"));
121 qtTrId(
"cutelystd-opt-ini-desc"),
124 qtTrId(
"cutelystd-opt-value-file"));
132 qtTrId(
"cutelystd-opt-json-desc"),
133 qtTrId(
"cutelystd-opt-value-file"));
140 qtTrId(
"cutelystd-opt-chdir-desc"),
143 qtTrId(
"cutelystd-opt-value-directory"));
150 qtTrId(
"cutelystd-opt-chdir2-desc"),
151 qtTrId(
"cutelystd-opt-value-directory"));
158 qtTrId(
"cutelystd-opt-lazy-desc"));
164 qtTrId(
"cutelystd-opt-application-desc"),
165 qtTrId(
"cutelystd-opt-value-file"));
172 qtTrId(
"cutelystd-opt-threads-desc"),
175 qtTrId(
"cutelystd-opt-threads-value"));
183 qtTrId(
"cutelystd-opt-processes-desc"),
186 qtTrId(
"cutelystd-opt-processes-value"));
193 qtTrId(
"cutelystd-opt-master-desc"));
199 qtTrId(
"cutelystd-opt-listen-desc"),
202 qtTrId(
"cutelystd-opt-value-size"));
208 qtTrId(
"cutelystd-opt-buffer-size-desc"),
211 qtTrId(
"cutelystd-opt-value-bytes"));
220 qtTrId(
"cutelystd-opt-post-buffering-desc"),
221 qtTrId(
"cutelystd-opt-value-bytes"));
225 u
"post-buffering-bufsize"_s,
228 qtTrId(
"cutelystd-opt-post-buffering-bufsize-desc"),
229 qtTrId(
"cutelystd-opt-value-bytes"));
230 parser.
addOption(postBufferingBufsizeOpt);
235 qtTrId(
"cutelystd-opt-http-socket-desc"),
238 qtTrId(
"cutelystd-opt-value-address"));
242 {u
"http2-socket"_s, u
"h2"_s},
245 qtTrId(
"cutelystd-opt-http2-socket-desc"),
246 qtTrId(
"cutelystd-opt-value-address"));
252 qtTrId(
"cutelystd-opt-http2-header-table-size-desc"),
253 qtTrId(
"cutelystd-opt-value-size"));
254 parser.
addOption(http2HeaderTableSizeOpt);
259 qtTrId(
"cutelystd-opt-upgrade-h2c-desc"));
265 qtTrId(
"cutelystd-opt-https-h2-desc"));
271 qtTrId(
"cutelystd-opt-https-socket-desc"),
273 qtTrId(
"cutelystd-opt-value-httpsaddress"));
280 qtTrId(
"cutelystd-opt-fastcgi-socket-desc"),
281 qtTrId(
"cutelystd-opt-value-address"));
288 qtTrId(
"cutelystd-opt-socket-access-desc"),
291 qtTrId(
"cutelystd-opt-socket-access-value"));
297 qtTrId(
"cutelystd-opt-socket-timeout-desc"),
300 qtTrId(
"cutelystd-opt-socket-timeout-value"));
309 qtTrId(
"cutelystd-opt-static-map-desc"),
312 qtTrId(
"cutelystd-opt-value-static-map"));
319 qtTrId(
"cutelystd-opt-static-map2-desc"),
322 qtTrId(
"cutelystd-opt-value-static-map"));
329 qtTrId(
"cutelystd-opt-auto-restart-desc"));
337 qtTrId(
"cutelystd-opt-touch-reload-desc"),
338 qtTrId(
"cutelystd-opt-value-file"));
344 qtTrId(
"cutelystd-opt-tcp-nodelay-desc"));
350 qtTrId(
"cutelystd-opt-so-keepalive-desc"));
357 qtTrId(
"cutelystd-opt-socket-sndbuf-desc"),
358 qtTrId(
"cutelystd-opt-value-bytes"));
365 qtTrId(
"cutelystd-opt-socket-rcvbuf-desc"),
366 qtTrId(
"cutelystd-opt-value-bytes"));
373 qtTrId(
"cutelystd-opt-websocket-max-size-desc"),
376 qtTrId(
"cutelystd-opt-websocket-max-size-value"));
382 qtTrId(
"cutelystd-opt-pidfile-desc"),
385 qtTrId(
"cutelystd-opt-value-pidfile"));
391 qtTrId(
"cutelystd-opt-pidfile2-desc"),
392 qtTrId(
"cutelystd-opt-value-pidfile"));
399 qtTrId(
"cutelystd-opt-stop-desc"),
400 qtTrId(
"cutelystd-opt-value-pidfile"));
406 qtTrId(
"cutelystd-opt-uid-desc"),
409 qtTrId(
"cutelystd-opt-uid-value"));
415 qtTrId(
"cutelystd-opt-gid-desc"),
418 qtTrId(
"cutelystd-opt-gid-value"));
424 qtTrId(
"cutelystd-opt-no-init-groups-desc"));
430 qtTrId(
"cutelystd-opt-chown-socket-desc"),
433 qtTrId(
"cutelystd-opt-chown-socket-value"));
439 qtTrId(
"cutelystd-opt-umask-desc"),
442 qtTrId(
"cutelystd-opt-umask-value"));
449 qtTrId(
"cutelystd-opt-cpu-affinity-desc"),
452 qtTrId(
"cutelystd-opt-cpu-affinity-value"));
460 qtTrId(
"cutelystd-opt-reuse-port-desc"));
465 u
"experimental-thread-balancer"_s,
468 qtTrId(
"cutelystd-opt-experimental-thread-balancer-desc"));
474 qtTrId(
"cutelystd-opt-using-frontend-proxy-desc"));
480 setIni(parser.
values(iniOpt));
482 setJson(parser.
values(jsonOpt));
484 if (parser.
isSet(chdirOpt)) {
485 setChdir(parser.
value(chdirOpt));
488 if (parser.
isSet(chdir2Opt)) {
489 setChdir2(parser.
value(chdir2Opt));
492 if (parser.
isSet(threadsOpt)) {
493 setThreads(parser.
value(threadsOpt));
496 if (parser.
isSet(socketAccessOpt)) {
497 setSocketAccess(parser.
value(socketAccessOpt));
500 if (parser.
isSet(socketTimeoutOpt)) {
502 auto size = parser.
value(socketTimeoutOpt).
toInt(&ok);
503 setSocketTimeout(size);
504 if (!ok || size < 0) {
509 if (parser.
isSet(pidfileOpt)) {
510 setPidfile(parser.
value(pidfileOpt));
513 if (parser.
isSet(pidfile2Opt)) {
514 setPidfile2(parser.
value(pidfile2Opt));
518 if (parser.
isSet(stopOpt)) {
519 UnixFork::stopSERVER(parser.
value(stopOpt));
522 if (parser.
isSet(processesOpt)) {
523 setProcesses(parser.
value(processesOpt));
526 if (parser.
isSet(uidOpt)) {
527 setUid(parser.
value(uidOpt));
530 if (parser.
isSet(gidOpt)) {
531 setGid(parser.
value(gidOpt));
534 if (parser.
isSet(noInitgroupsOpt)) {
535 setNoInitgroups(
true);
538 if (parser.
isSet(chownSocketOpt)) {
539 setChownSocket(parser.
value(chownSocketOpt));
542 if (parser.
isSet(umaskOpt)) {
543 setUmask(parser.
value(umaskOpt));
546 if (parser.
isSet(cpuAffinityOpt)) {
548 auto value = parser.
value(cpuAffinityOpt).
toInt(&ok);
549 setCpuAffinity(value);
550 if (!ok || value < 0) {
557 if (parser.
isSet(reusePortOpt)) {
562 if (parser.
isSet(lazyOpt)) {
566 if (parser.
isSet(listenQueueOpt)) {
568 auto size = parser.
value(listenQueueOpt).
toInt(&ok);
569 setListenQueue(size);
570 if (!ok || size < 1) {
575 if (parser.
isSet(bufferSizeOpt)) {
577 auto size = parser.
value(bufferSizeOpt).
toInt(&ok);
579 if (!ok || size < 1) {
584 if (parser.
isSet(postBufferingOpt)) {
587 setPostBuffering(size);
588 if (!ok || size < 1) {
593 if (parser.
isSet(postBufferingBufsizeOpt)) {
596 setPostBufferingBufsize(size);
597 if (!ok || size < 1) {
602 if (parser.
isSet(applicationOpt)) {
603 setApplication(parser.
value(applicationOpt));
606 if (parser.
isSet(masterOpt)) {
610 if (parser.
isSet(autoReloadOpt)) {
614 if (parser.
isSet(tcpNoDelay)) {
618 if (parser.
isSet(soKeepAlive)) {
619 setSoKeepalive(
true);
622 if (parser.
isSet(upgradeH2cOpt)) {
626 if (parser.
isSet(httpsH2Opt)) {
630 if (parser.
isSet(socketSndbufOpt)) {
632 auto size = parser.
value(socketSndbufOpt).
toInt(&ok);
633 setSocketSndbuf(size);
634 if (!ok || size < 1) {
639 if (parser.
isSet(socketRcvbufOpt)) {
641 auto size = parser.
value(socketRcvbufOpt).
toInt(&ok);
642 setSocketRcvbuf(size);
643 if (!ok || size < 1) {
648 if (parser.
isSet(wsMaxSize)) {
650 auto size = parser.
value(wsMaxSize).
toInt(&ok);
651 setWebsocketMaxSize(size);
652 if (!ok || size < 1) {
657 if (parser.
isSet(http2HeaderTableSizeOpt)) {
659 auto size = parser.
value(http2HeaderTableSizeOpt).
toUInt(&ok);
660 setHttp2HeaderTableSize(size);
661 if (!ok || size < 1) {
666 if (parser.
isSet(frontendProxy)) {
667 setUsingFrontendProxy(
true);
670 setHttpSocket(httpSocket() + parser.
values(httpSocketOpt));
672 setHttp2Socket(http2Socket() + parser.
values(http2SocketOpt));
674 setHttpsSocket(httpsSocket() + parser.
values(httpsSocketOpt));
676 setFastcgiSocket(fastcgiSocket() + parser.
values(fastcgiSocketOpt));
678 setStaticMap(staticMap() + parser.
values(staticMapOpt));
680 setStaticMap2(staticMap2() + parser.
values(staticMap2Opt));
682 setTouchReload(touchReload() + parser.
values(touchReloadOpt));
684 d->threadBalancer = parser.
isSet(threadBalancerOpt);
690 std::cout <<
"Cutelyst-Server starting" <<
'\n';
692 if (!qEnvironmentVariableIsSet(
"CUTELYST_SERVER_IGNORE_MASTER") && !d->master) {
694 <<
"*** WARNING: you are running Cutelyst-Server without its master process manager ***"
699 if (d->processes == -1 && d->threads == -1) {
700 d->processes = UnixFork::idealProcessCount();
701 d->threads = UnixFork::idealThreadCount() / d->processes;
702 }
else if (d->processes == -1) {
703 d->processes = UnixFork::idealThreadCount();
704 }
else if (d->threads == -1) {
705 d->threads = UnixFork::idealThreadCount();
708 if (d->processes == 0 && d->master) {
711 delete d->genericFork;
712 d->genericFork =
new UnixFork(d->processes, qMax(d->threads, 1), !d->userEventLoop,
this);
714 if (d->processes == -1) {
717 if (d->threads == -1) {
720 delete d->genericFork;
729 if (d->master && d->lazy) {
730 if (d->autoReload && !d->application.isEmpty()) {
731 d->touchReload.append(d->application);
733 d->genericFork->setTouchReload(d->touchReload);
737 if (d->master && !d->genericFork->continueMaster(&ret)) {
742 if (systemdNotify::is_systemd_notify_available()) {
744 sd->setWatchdog(
true, systemdNotify::sd_watchdog_enabled(
true));
746 sd->sendStatus(qApp->applicationName().toLatin1() +
" is ready");
749 connect(d, &ServerPrivate::postForked, sd, [sd] { sd->setWatchdog(
false); });
750 qInfo(CUTELYST_SERVER) <<
"systemd notify detected";
758 if (!d->listenTcpSockets()) {
760 ? QStringLiteral(
"No specified sockets were able to be opened")
761 : d->lastListenError;
767 if (!d->writePidFile(d->pidfile)) {
773 bool isListeningLocalSockets =
false;
774 if (!d->chownSocket.isEmpty()) {
775 if (!d->listenLocalSockets()) {
780 isListeningLocalSockets =
true;
783 if (!d->umask.isEmpty() && !UnixFork::setUmask(d->umask.toLatin1())) {
787 if (!UnixFork::setGidUid(d->gid, d->uid, d->noInitgroups)) {
793 if (!isListeningLocalSockets) {
795 d->listenLocalSockets();
801 if (!d->listenTcpSockets()) {
803 ? QStringLiteral(
"No specified sockets were able to be opened")
804 : d->lastListenError;
810 if (d->servers.empty()) {
811 std::cout <<
"Please specify a socket to listen to" <<
'\n';
817 d->writePidFile(d->pidfile2);
819 if (!d->chdir.isEmpty()) {
820 std::cout <<
"Changing directory to: " << d->chdir.toLatin1().constData() <<
'\n';
831 if (!d->setupApplication()) {
838 if (d->userEventLoop) {
843 ret = d->genericFork->exec(d->lazy, d->master);
854 QStringLiteral(
"Server not fully stopped. Wait for shutdown to complete."));
861 d->userEventLoop =
true;
862 d->workersNotRunning = 1;
863 d->lastListenError.clear();
868 qputenv(
"CUTELYST_SERVER_IGNORE_MASTER", QByteArrayLiteral(
"1"));
870 if (
exec(app) == 0) {
880 if (d->userEventLoop) {
885ServerPrivate::~ServerPrivate()
892bool ServerPrivate::listenTcpSockets()
894 lastListenError.clear();
896 if (httpSockets.isEmpty() && httpsSockets.isEmpty() && http2Sockets.isEmpty() &&
897 fastcgiSockets.isEmpty()) {
903 bool httpOk = std::ranges::all_of(httpSockets, [
this](
const auto &socket) {
904 return listenTcp(socket, getHttpProto(),
false);
911 bool httpsOk = std::ranges::all_of(httpsSockets, [
this](
const auto &socket) {
912 return listenTcp(socket, getHttpProto(),
true);
919 bool http2Ok = std::ranges::all_of(http2Sockets, [
this](
const auto &socket) {
920 return listenTcp(socket, getHttp2Proto(),
false);
927 bool allOk = std::ranges::all_of(fastcgiSockets, [
this](
const QString &socket) {
928 return listenTcp(socket, getFastCgiProto(),
false);
934bool ServerPrivate::listenTcp(
const QString &line,
Protocol *protocol,
bool secure)
943 server->setBalancer(threadBalancer);
944 const bool ret = server->listen(line, protocol, secure);
946 if (!ret || !server->socketDescriptor()) {
948 server->bindError().
isEmpty() ? server->errorString() : server->bindError();
950 lastListenError = QStringLiteral(
"Failed to listen on %1: %2").arg(line, err);
953 QStringLiteral(
"Failed to listen on %1: no socket descriptor").arg(line);
955 qCWarning(CUTELYST_SERVER) << lastListenError;
960 auto qEnum = Protocol::staticMetaObject.enumerator(0);
961 std::cout << qEnum.valueToKey(
static_cast<int>(protocol->type())) <<
" socket "
963 <<
" bound to TCP address " << server->serverName().constData() <<
" fd "
965 servers.emplace_back(server);
969bool ServerPrivate::listenLocalSockets()
978 std::vector<int> fds = systemdNotify::listenFds();
981 if (server->listen(fd)) {
982 const QString name = server->serverName();
983 const QString fullName = server->fullServerName();
987 protocol = getHttpProto();
989 protocol = getHttp2Proto();
991 protocol = getFastCgiProto();
993 std::cerr <<
"systemd activated socket does not match any configured socket"
997 server->setProtocol(protocol);
998 server->pauseAccepting();
1000 auto qEnum = Protocol::staticMetaObject.enumerator(0);
1001 std::cout << qEnum.valueToKey(
static_cast<int>(protocol->type())) <<
" socket "
1003 <<
" bound to LOCAL address " << qPrintable(fullName) <<
" fd "
1005 servers.push_back(server);
1007 std::cerr <<
"Failed to listen on activated LOCAL FD: "
1009 << qPrintable(server->errorString()) <<
'\n';
1016 const auto httpConst = http;
1017 for (
const auto &socket : httpConst) {
1018 ret |= listenLocal(socket, getHttpProto());
1021 const auto http2Const = http2;
1022 for (
const auto &socket : http2Const) {
1023 ret |= listenLocal(socket, getHttp2Proto());
1026 const auto fastcgiConst = fastcgi;
1027 for (
const auto &socket : fastcgiConst) {
1028 ret |= listenLocal(socket, getFastCgiProto());
1034bool ServerPrivate::listenLocal(
const QString &line,
Protocol *protocol)
1041 server->setProtocol(protocol);
1042 if (!socketAccess.isEmpty()) {
1044 if (socketAccess.contains(u
'u')) {
1048 if (socketAccess.contains(u
'g')) {
1052 if (socketAccess.contains(u
'o')) {
1055 server->setSocketOptions(options);
1059 server->setListenBacklogSize(listenQueue);
1060 ret = server->listen(line);
1061 server->pauseAccepting();
1063 if (!ret || !server->socket()) {
1064 std::cerr <<
"Failed to listen on LOCAL: " << qPrintable(line) <<
" : "
1065 << qPrintable(server->errorString()) <<
'\n';
1070 if (!chownSocket.isEmpty()) {
1071 UnixFork::chownSocket(line, chownSocket);
1074 auto qEnum = Protocol::staticMetaObject.enumerator(0);
1075 std::cout << qEnum.valueToKey(
static_cast<int>(protocol->type())) <<
" socket "
1077 <<
" bound to LOCAL address " << qPrintable(line) <<
" fd "
1079 servers.push_back(server);
1085void Server::setApplication(
const QString &application)
1090 if (loader.fileName().isEmpty()) {
1095 d->application = loader.fileName();
1103 return d->application;
1106void Server::setThreads(
const QString &threads)
1120 if (d->threads == -1) {
1126void Server::setProcesses(
const QString &process)
1133 d->processes = process.
toInt();
1142 if (d->processes == -1) {
1148void Server::setChdir(
const QString &chdir)
1161void Server::setHttpSocket(
const QStringList &httpSocket)
1164 d->httpSockets = httpSocket;
1171 return d->httpSockets;
1174void Server::setHttp2Socket(
const QStringList &http2Socket)
1177 d->http2Sockets = http2Socket;
1184 return d->http2Sockets;
1187void Server::setHttp2HeaderTableSize(quint32 headerTableSize)
1190 d->http2HeaderTableSize = headerTableSize;
1194quint32 Server::http2HeaderTableSize()
const
1197 return d->http2HeaderTableSize;
1200void Server::setUpgradeH2c(
bool enable)
1203 d->upgradeH2c = enable;
1207bool Server::upgradeH2c()
const
1210 return d->upgradeH2c;
1213void Server::setHttpsH2(
bool enable)
1216 d->httpsH2 = enable;
1220bool Server::httpsH2()
const
1226void Server::setHttpsSocket(
const QStringList &httpsSocket)
1229 d->httpsSockets = httpsSocket;
1236 return d->httpsSockets;
1239void Server::setFastcgiSocket(
const QStringList &fastcgiSocket)
1242 d->fastcgiSockets = fastcgiSocket;
1249 return d->fastcgiSockets;
1252void Server::setSocketAccess(
const QString &socketAccess)
1255 d->socketAccess = socketAccess;
1259QString Server::socketAccess()
const
1262 return d->socketAccess;
1265void Server::setSocketTimeout(
int timeout)
1268 d->socketTimeout = timeout;
1272int Server::socketTimeout()
const
1275 return d->socketTimeout;
1278void Server::setChdir2(
const QString &chdir2)
1294 d->ini.append(files);
1295 d->ini.removeDuplicates();
1298 for (
const QString &file : files) {
1299 if (!d->configLoaded.contains(file)) {
1300 auto fileToLoad = std::make_pair(file, ServerPrivate::ConfigFormat::Ini);
1301 if (!d->configToLoad.contains(fileToLoad)) {
1302 qCDebug(CUTELYST_SERVER) <<
"Enqueue INI config file:" << file;
1303 d->configToLoad.enqueue(fileToLoad);
1320 d->json.append(files);
1321 d->json.removeDuplicates();
1324 for (
const QString &file : files) {
1325 if (!d->configLoaded.contains(file)) {
1326 auto fileToLoad = std::make_pair(file, ServerPrivate::ConfigFormat::Json);
1327 if (!d->configToLoad.contains(fileToLoad)) {
1328 qCDebug(CUTELYST_SERVER) <<
"Enqueue JSON config file:" << file;
1329 d->configToLoad.enqueue(fileToLoad);
1343void Server::setStaticMap(
const QStringList &staticMap)
1346 d->staticMaps = staticMap;
1353 return d->staticMaps;
1356void Server::setStaticMap2(
const QStringList &staticMap)
1359 d->staticMaps2 = staticMap;
1366 return d->staticMaps2;
1369void Server::setMaster(
bool enable)
1372 if (!qEnvironmentVariableIsSet(
"CUTELYST_SERVER_IGNORE_MASTER")) {
1384void Server::setAutoReload(
bool enable)
1388 d->autoReload =
true;
1393bool Server::autoReload()
const
1396 return d->autoReload;
1399void Server::setTouchReload(
const QStringList &files)
1402 d->touchReload = files;
1409 return d->touchReload;
1412void Server::setListenQueue(
int size)
1415 d->listenQueue = size;
1419int Server::listenQueue()
const
1422 return d->listenQueue;
1425void Server::setBufferSize(
int size)
1429 qCWarning(CUTELYST_SERVER) <<
"Buffer size must be at least 4096 bytes, ignoring";
1432 d->bufferSize = size;
1436int Server::bufferSize()
const
1439 return d->bufferSize;
1442void Server::setPostBuffering(qint64 size)
1445 d->postBuffering = size;
1449qint64 Server::postBuffering()
const
1452 return d->postBuffering;
1455void Server::setPostBufferingBufsize(qint64 size)
1459 qCWarning(CUTELYST_SERVER) <<
"Post buffer size must be at least 4096 bytes, ignoring";
1462 d->postBufferingBufsize = size;
1466qint64 Server::postBufferingBufsize()
const
1469 return d->postBufferingBufsize;
1472void Server::setTcpNodelay(
bool enable)
1475 d->tcpNodelay = enable;
1479bool Server::tcpNodelay()
const
1482 return d->tcpNodelay;
1485void Server::setSoKeepalive(
bool enable)
1488 d->soKeepalive = enable;
1492bool Server::soKeepalive()
const
1495 return d->soKeepalive;
1498void Server::setSocketSndbuf(
int value)
1501 d->socketSendBuf = value;
1505int Server::socketSndbuf()
const
1508 return d->socketSendBuf;
1511void Server::setSocketRcvbuf(
int value)
1514 d->socketReceiveBuf = value;
1518int Server::socketRcvbuf()
const
1521 return d->socketReceiveBuf;
1524void Server::setWebsocketMaxSize(
int value)
1527 d->websocketMaxSize = value * 1024;
1531int Server::websocketMaxSize()
const
1534 return d->websocketMaxSize / 1024;
1537void Server::setPidfile(
const QString &file)
1550void Server::setPidfile2(
const QString &file)
1563void Server::setUid(
const QString &uid)
1578void Server::setGid(
const QString &gid)
1593void Server::setNoInitgroups(
bool enable)
1597 d->noInitgroups = enable;
1602bool Server::noInitgroups()
const
1605 return d->noInitgroups;
1608void Server::setChownSocket(
const QString &chownSocket)
1612 d->chownSocket = chownSocket;
1617QString Server::chownSocket()
const
1620 return d->chownSocket;
1623void Server::setUmask(
const QString &value)
1638void Server::setCpuAffinity(
int value)
1642 d->cpuAffinity = value;
1647int Server::cpuAffinity()
const
1650 return d->cpuAffinity;
1653void Server::setReusePort(
bool enable)
1657 d->reusePort = enable;
1664bool Server::reusePort()
const
1667 return d->reusePort;
1670void Server::setLazy(
bool enable)
1683void Server::setUsingFrontendProxy(
bool enable)
1686 d->usingFrontendProxy = enable;
1690bool Server::usingFrontendProxy()
const
1693 return d->usingFrontendProxy;
1702bool ServerPrivate::setupApplication()
1708 if (userEventLoop) {
1709 qDeleteAll(engines);
1711 mainEngine =
nullptr;
1715 }
else if (!engines.empty() || mainEngine) {
1716 qDeleteAll(engines);
1718 mainEngine =
nullptr;
1722 std::cout <<
"Loading application: " << application.
toLatin1().
constData() <<
'\n';
1725 if (!loader.load()) {
1726 qCCritical(CUTELYST_SERVER) <<
"Could not load application:" << loader.errorString();
1730 QObject *instance = loader.instance();
1732 qCCritical(CUTELYST_SERVER) <<
"Could not get a QObject instance: %s\n"
1733 << loader.errorString();
1737 localApp = qobject_cast<Cutelyst::Application *>(instance);
1739 qCCritical(CUTELYST_SERVER)
1740 <<
"Could not cast Cutelyst::Application from instance: %s\n"
1741 << loader.errorString();
1752 if (!chdir2.isEmpty()) {
1753 std::cout <<
"Changing directory2 to: " << chdir2.toLatin1().constData() <<
'\n';
1762 mainEngine = createEngine(localApp, 0);
1763 for (
int i = 1; i < threads; ++i) {
1764 if (createEngine(localApp, i)) {
1765 ++workersNotRunning;
1769 mainEngine = createEngine(localApp, 0);
1770 workersNotRunning = 1;
1774 std::cerr <<
"Application failed to init, cheaping..." <<
'\n';
1781void ServerPrivate::engineShutdown(
ServerEngine *engine)
1783 if (mainEngine == engine) {
1784 mainEngine =
nullptr;
1787 const auto engineThread = engine->
thread();
1790 auto [first, last] = std::ranges::remove(engines, engine);
1791 engines.erase(first, last);
1792 if (userEventLoop) {
1795 checkEngineShutdown();
1797 engineThread->quit();
1801 auto [first, last] = std::ranges::remove(engines, engine);
1802 engines.erase(first, last);
1804 if (userEventLoop) {
1808 checkEngineShutdown();
1811void ServerPrivate::checkEngineShutdown()
1813 if (engines.empty()) {
1814 if (userEventLoop) {
1816 Q_EMIT q->stopped();
1823void ServerPrivate::workerStarted()
1828 if (--workersNotRunning == 0) {
1833bool ServerPrivate::postFork(
int workerId)
1838 if (!setupApplication()) {
1839 Q_EMIT q->errorOccured(qtTrId(
"cutelystd-err-fail-setup-app"));
1844 if (engines.size() > 1) {
1845 qCDebug(CUTELYST_SERVER) <<
"Starting threads";
1850 if (thread != qApp->thread()) {
1852 if (!qEnvironmentVariableIsSet(
"CUTELYST_QT_EVENT_LOOP")) {
1862 Q_EMIT postForked(workerId);
1870 qApp->processEvents();
1876bool ServerPrivate::writePidFile(
const QString &filename)
1882 QFile file(filename);
1884 std::cerr <<
"Failed write pid file " << qPrintable(filename) <<
'\n';
1888 std::cout <<
"Writing pidfile to " << qPrintable(filename) <<
'\n';
1899 if (workerCore > 0) {
1902 qFatal(
"*** FATAL *** Could not create a NEW instance of your Cutelyst::Application, "
1903 "make sure your constructor has Q_INVOKABLE macro or disable threaded mode.");
1907 auto engine =
new ServerEngine(app, workerCore, opt, q);
1911 connect(
this, &ServerPrivate::postForked, engine, &ServerEngine::postFork, forkConnection);
1913 &ServerEngine::shutdownCompleted,
1915 &ServerPrivate::engineShutdown,
1917 connect(engine, &ServerEngine::started,
this, &ServerPrivate::workerStarted, forkConnection);
1920 engine->setServers(servers);
1921 if (!engine->
init()) {
1922 std::cerr <<
"Application failed to init(), cheaping core: " << workerCore <<
'\n';
1927 engines.push_back(engine);
1930 if (workerCore > 0) {
1935 auto thread =
new QThread(
this);
1944void ServerPrivate::loadConfig()
1946 if (loadingConfig) {
1950 loadingConfig =
true;
1952 if (configToLoad.isEmpty()) {
1953 loadingConfig =
false;
1957 auto fileToLoad = configToLoad.dequeue();
1959 if (fileToLoad.first.isEmpty()) {
1960 qCWarning(CUTELYST_SERVER) <<
"Can not load config from empty config file name";
1961 loadingConfig =
false;
1965 if (configLoaded.contains(fileToLoad.first)) {
1966 loadingConfig =
false;
1970 configLoaded.append(fileToLoad.first);
1972 QVariantMap loadedConfig;
1973 switch (fileToLoad.second) {
1974 case ConfigFormat::Ini:
1975 qCInfo(CUTELYST_SERVER) <<
"Loading INI configuratin:" << fileToLoad.first;
1978 case ConfigFormat::Json:
1979 qCInfo(CUTELYST_SERVER) <<
"Loading JSON configuration:" << fileToLoad.first;
1984 for (
const auto &[key, value] : std::as_const(loadedConfig).asKeyValueRange()) {
1985 if (config.contains(key)) {
1986 QVariantMap currentMap = config.value(key).toMap();
1987 const QVariantMap loadedMap = value.toMap();
1988 for (
const auto &[mapKey, mapValue] : loadedMap.asKeyValueRange()) {
1989 currentMap.insert(mapKey, mapValue);
1991 config.insert(key, currentMap);
1993 config.insert(key, value);
1997 QVariantMap sessionConfig = loadedConfig.value(u
"server"_s).toMap();
1999 applyConfig(sessionConfig);
2001 opt.insert(sessionConfig);
2003 loadingConfig =
false;
2005 if (!configToLoad.empty()) {
2010void ServerPrivate::applyConfig(
const QVariantMap &config)
2014 for (
const auto &[key, value] : config.asKeyValueRange()) {
2024 if (prop.
userType() == value.userType()) {
2027 prop.
write(q, currentValues + value.toStringList());
2029 prop.
write(q, value);
2035 prop.
write(q, value);
2040Protocol *ServerPrivate::getHttpProto()
2062Protocol *ServerPrivate::getFastCgiProto()
2071#include "moc_server.cpp"
2072#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