-
-
Notifications
You must be signed in to change notification settings - Fork 226
/
Copy pathtactionthread.cpp
255 lines (207 loc) · 6.65 KB
/
tactionthread.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/* Copyright (c) 2010-2019, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include "tfcore.h"
#include "thttpsocket.h"
#include "tsessionmanager.h"
#include "tsystemglobal.h"
#include "twebsocket.h"
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QEventLoop>
#include <TActionThread>
#include <TAppSettings>
#include <TApplicationServerBase>
#include <THttpRequest>
#include <TSession>
#include <TWebApplication>
#include <atomic>
constexpr int RECV_BUF_SIZE = 8 * 1024;
namespace {
std::atomic<int> threadCounter(0);
}
int TActionThread::threadCount()
{
return threadCounter.load();
}
bool TActionThread::waitForAllDone(int msec)
{
int cnt;
QElapsedTimer time;
time.start();
while ((cnt = threadCount()) > 0) {
if (time.elapsed() > msec) {
break;
}
Tf::msleep(5);
qApp->processEvents();
}
tSystemDebug("waitForAllDone : remaining:{}", cnt);
return cnt == 0;
}
/*!
\class TActionThread
\brief The TActionThread class provides a thread context.
*/
TActionThread::TActionThread(int socket, int maxThreads) :
QThread(),
TActionContext(),
_maxThreads(maxThreads)
{
TActionContext::socketDesc = socket;
_readBuffer.reserve(RECV_BUF_SIZE);
}
TActionThread::~TActionThread()
{
if (_httpSocket) {
_httpSocket->deleteLater();
}
if (TActionContext::socketDesc > 0) {
tf_close_socket(TActionContext::socketDesc);
}
}
void TActionThread::setSocketDescriptor(qintptr socket)
{
if (TActionContext::socketDesc > 0) {
tSystemWarn("Socket still open : {} [{}:{}]", TActionContext::socketDesc, __FILE__, __LINE__);
tf_close_socket(TActionContext::socketDesc);
}
TActionContext::socketDesc = socket;
}
void TActionThread::run()
{
class Counter {
std::atomic<int> &_num;
public:
Counter(std::atomic<int> &n) :
_num(n) { _num++; }
~Counter() { _num--; }
};
Counter counter(threadCounter);
QEventLoop eventLoop;
_httpSocket = new THttpSocket(_readBuffer, this);
if (TActionContext::socketDesc > 0) {
_httpSocket->setSocketDescriptor(TActionContext::socketDesc, QAbstractSocket::ConnectedState);
}
TActionContext::socketDesc = 0;
TDatabaseContext::setCurrentDatabaseContext(this);
try {
for (;;) {
QList<THttpRequest> requests = readRequest(_httpSocket);
tSystemDebug("HTTP request count: {}", (qint64)requests.count());
if (requests.isEmpty()) {
break;
}
// WebSocket?
QByteArray connectionHeader = requests[0].header().rawHeader(QByteArrayLiteral("Connection")).toLower();
if (Q_UNLIKELY(connectionHeader.contains("upgrade"))) {
QByteArray upgradeHeader = requests[0].header().rawHeader(QByteArrayLiteral("Upgrade")).toLower();
tSystemDebug("Upgrade: {}", (const char*)upgradeHeader.data());
if (upgradeHeader == "websocket") {
// Switch to WebSocket
if (!handshakeForWebSocket(requests[0].header())) {
goto socket_error;
}
}
goto socket_cleanup;
}
for (auto &req : requests) {
TActionContext::execute(req);
}
if (keepAliveTimeout() == 0) {
break;
}
if (threadCount() >= _maxThreads && _maxThreads > 0) {
// Do not keep-alive
break;
}
if (_httpSocket->state() != QAbstractSocket::ConnectedState) {
goto receive_end;
}
}
} catch (ClientErrorException &e) {
Tf::warn("Caught ClientErrorException: status code:{}", e.statusCode());
tSystemWarn("Caught ClientErrorException: status code:{}", e.statusCode());
THttpResponseHeader header;
TActionContext::writeResponse(e.statusCode(), header);
} catch (std::exception &e) {
Tf::error("Caught Exception: {}", e.what());
tSystemError("Caught Exception: {}", e.what());
THttpResponseHeader header;
TActionContext::writeResponse(Tf::InternalServerError, header);
}
receive_end:
closeSocket(); // disconnect
socket_cleanup:
// For cleanup
while (eventLoop.processEvents()) {
}
socket_error:
TActionContext::socketDesc = 0;
TActionContext::release();
TDatabaseContext::setCurrentDatabaseContext(nullptr);
_httpSocket->deleteLater();
_httpSocket = nullptr;
}
void TActionThread::emitError(int socketError)
{
emit error(socketError);
}
QList<THttpRequest> TActionThread::readRequest(THttpSocket *socket)
{
QList<THttpRequest> reqs;
for (;;) {
if (socket->waitForReadyReadRequest(500)) {
reqs = socket->read();
if (!reqs.isEmpty()) {
return reqs;
} else {
break;
}
}
if (Q_UNLIKELY(socket->state() != QAbstractSocket::ConnectedState)) {
break;
}
// Check idle timeout
if (Q_UNLIKELY(keepAliveTimeout() > 0 && socket->idleTime() >= keepAliveTimeout())) {
tSystemWarn("Reading a socket timed out after {} seconds. Descriptor:{}", keepAliveTimeout(), (int)socket->socketDescriptor());
break;
}
}
socket->abort();
return QList<THttpRequest>();
}
int64_t TActionThread::writeResponse(THttpResponseHeader &header, QIODevice *body)
{
if (keepAliveTimeout() > 0) {
header.setRawHeader(QByteArrayLiteral("Connection"), QByteArrayLiteral("Keep-Alive"));
}
return _httpSocket->write(static_cast<THttpHeader *>(&header), body);
}
void TActionThread::closeSocket()
{
_httpSocket->abort();
}
bool TActionThread::handshakeForWebSocket(const THttpRequestHeader &header)
{
if (!TWebSocket::searchEndpoint(header)) {
return false;
}
// Switch to WebSocket
int sd = TApplicationServerBase::duplicateSocket(_httpSocket->socketDescriptor());
TWebSocket *ws = new TWebSocket(sd, _httpSocket->peerAddress(), header);
connect(ws, SIGNAL(disconnected()), ws, SLOT(deleteLater()));
ws->moveToThread(Tf::app()->thread());
// WebSocket opening
TSession session;
QByteArray sessionId = header.cookie(TSession::sessionName());
if (!sessionId.isEmpty()) {
// Finds a session
session = TSessionManager::instance().findSession(sessionId);
}
ws->startWorkerForOpening(session);
return true;
}