File: worker.cpp

package info (click to toggle)
tntnet 3.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,488 kB
  • sloc: cpp: 16,636; javascript: 8,109; ansic: 2,189; makefile: 861; sh: 317; xml: 258; perl: 159; sql: 14
file content (543 lines) | stat: -rw-r--r-- 16,762 bytes parent folder | download
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/*
 * Copyright (C) 2003-2005 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * As a special exception, you may use this file as part of a free
 * software library without restriction. Specifically, if other files
 * instantiate templates or use macros or inline functions from this
 * file, or you compile this file and link it with other files to
 * produce an executable, this file does not by itself cause the
 * resulting executable to be covered by the GNU General Public
 * License. This exception does not however invalidate any other
 * reasons why the executable file might be covered by the GNU Library
 * General Public License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */


#include "tnt/worker.h"
#include "tnt/dispatcher.h"
#include "tnt/job.h"
#include <tnt/httprequest.h>
#include <tnt/httpreply.h>
#include <tnt/httperror.h>
#include <tnt/http.h>
#include <tnt/poller.h>
#include <tnt/tntconfig.h>
#include <cxxtools/log.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/poll.h>
#include <cxxtools/dlloader.h>
#include <cxxtools/ioerror.h>
#include <cxxtools/net/tcpserver.h>
#include <pthread.h>
#include <string.h>

#include <atomic>
#include "config.h"

log_define("tntnet.worker")

namespace
{
  static const char stateStarting[]          = "0 starting";
  static const char stateWaitingForJob[]     = "1 waiting for job";
  static const char stateParsing[]           = "2 parsing request";
  static const char statePostParsing[]       = "3 post parsing";
  static const char stateDispatch[]          = "4 dispatch";
  static const char stateProcessingRequest[] = "5 processing request";
  static const char stateFlush[]             = "6 flush";
  static const char stateSendReply[]         = "7 send reply";
  static const char stateSendError[]         = "8 send error";
  static const char stateStopping[]          = "9 stopping";
}

namespace tnt
{
  cxxtools::Mutex Worker::_mutex;
  Worker::workers_type Worker::_workers;
  Comploader Worker::_comploader;

  Worker::Worker(TntnetImpl& app)
    : _application(app),
      _threadId(0),
      _state(stateStarting),
      _lastWaitTime(0)
  {
    cxxtools::MutexLock lock(_mutex);
    _workers.insert(this);
  }

  void Worker::run()
  {
    _threadId = pthread_self();
    Jobqueue& queue = _application.getQueue();
    log_debug("start thread " << _threadId);
    while (queue.getWaitThreadCount() < _application.getMinThreads())
    {
      _state = stateWaitingForJob;
      Jobqueue::JobPtr j = queue.get();
      if (TntnetImpl::shouldStop())
      {
        // put job back to queue to wake up next worker if any left
        queue.put(j);
        break;
      }

      try
      {
        std::iostream& socket = j->getStream();
        if (TntnetImpl::shouldStop())
          break;

        bool keepAlive;
        do
        {
          time(&_lastWaitTime);

          keepAlive = false;
          _state = stateParsing;
          try
          {
            j->getParser().parse(socket);
            _state = statePostParsing;

            if (socket.eof())
              log_debug("eof");
            else if (j->getParser().failed())
            {
              _state = stateSendError;
              log_warn("bad request");
              tnt::HttpReply errorReply(socket);
              errorReply.setVersion(1, 0);
              errorReply.setContentType("text/html");
              errorReply.setKeepAliveCounter(0);
              errorReply.out() << "<html><body><h1>Error</h1><p>bad request</p></body></html>\n";
              errorReply.sendReply(400, "Bad Request");
              logRequest(j->getRequest(), errorReply, 400);
            }
            else if (socket.fail())
              log_debug("socket failed");
            else
            {
              j->getRequest().doPostParse();

              j->setWrite();
              keepAlive = processRequest(j->getRequest(), socket,
                j->decrementKeepAliveCounter());

              if (keepAlive)
              {
                j->setRead();
                j->clear();

                if (!socket.rdbuf()->in_avail())
                {
                  if (queue.getWaitThreadCount() == 0
                    && !queue.empty())
                  {
                    // if there is something to do and no threads waiting, we take
                    // the next job just to improve responsiveness.
                    log_debug("put job back into queue");
                    queue.put(j, true);
                    keepAlive = false;
                  }
                  else
                  {
                    struct pollfd fd;
                    fd.fd = j->getFd();
                    fd.events = POLLIN;
                    if (::poll(&fd, 1, TntConfig::it().socketReadTimeout) == 0)
                    {
                      log_debug("pass job to poll-thread");
                      _application.getPoller().addIdleJob(j);
                      keepAlive = false;
                    }
                  }
                }
              }
            }
          }
          catch (const HttpError& e)
          {
            keepAlive = false;
            _state = stateSendError;
            log_warn("http-Error: " << e.what());
            HttpReply errorReply(socket);
            errorReply.setVersion(1, 0);
            errorReply.setKeepAliveCounter(0);
            for (HttpMessage::header_type::const_iterator it = e.header_begin();
                 it != e.header_end(); ++it)
              errorReply.setHeader(it->first, it->second);

            errorReply.out() << e.getBody() << '\n';
            errorReply.sendReply(e.getErrcode(), e.getErrmsg());
            logRequest(j->getRequest(), errorReply, e.getErrcode());
          }
        } while (keepAlive);
      }
      catch (const cxxtools::IOTimeout& e)
      {
        log_debug("IOTimeout");
        _application.getPoller().addIdleJob(j);
      }
      catch (const cxxtools::net::AcceptTerminated&)
      {
        log_debug("listener terminated");
        break;
      }
      catch (const std::exception& e)
      {
        log_warn("unexpected exception: " << e.what());
      }
    }

    time(&_lastWaitTime);

    _state = stateStopping;

    cxxtools::MutexLock lock(_mutex);
    _workers.erase(this);

    log_debug("end worker thread " << _threadId << " - " << _workers.size()
      << " threads left - " << _application.getQueue().getWaitThreadCount()
      << " waiting threads");
  }

  bool Worker::processRequest(HttpRequest& request, std::iostream& socket,
         unsigned keepAliveCount)
  {
    // log message
    log_info("request " << request.getMethod_cstr() << ' ' << request.getQuery()
      << " from client " << request.getPeerIp() << " user-Agent \"" << request.getUserAgent()
      << "\" user \"" << request.getUsername() << '"');

    // create reply-object
    HttpReply reply(socket);
    reply.setVersion(request.getMajorVersion(), request.getMinorVersion());
    if (request.isMethodHEAD())
      reply.setHeadRequest();

#ifdef ENABLE_LOCALE
    reply.setLocale(request.getLocale());
#endif

    if (request.keepAlive())
      reply.setKeepAliveCounter(keepAliveCount);

    if (TntConfig::it().enableCompression)
      reply.setAcceptEncoding(request.getEncoding());

    // process request
    try
    {
      try
      {
        dispatch(request, reply);

        if (!request.keepAlive() || !reply.keepAlive())
          keepAliveCount = 0;

        if (keepAliveCount > 0)
          log_debug("keep alive");
        else
        {
          log_debug("no keep alive request/reply="
              << request.keepAlive() << '/' << reply.keepAlive());
        }
      }
      catch (const HttpError& e)
      {
        throw;
      }
      catch (const std::exception& e)
      {
        throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what());
      }
      catch (...)
      {
        log_error("unknown exception");
        throw HttpError(HTTP_INTERNAL_SERVER_ERROR, "unknown error");
      }
    }
    catch (const HttpError& e)
    {
      _state = stateSendError;
      log_warn("http-Error: " << e.what());
      HttpReply errorReply(socket);
      errorReply.setVersion(request.getMajorVersion(), request.getMinorVersion());
      if (request.keepAlive())
        errorReply.setKeepAliveCounter(keepAliveCount);
      else
        keepAliveCount = 0;
      for (HttpMessage::header_type::const_iterator it = e.header_begin();
           it != e.header_end(); ++it)
        errorReply.setHeader(it->first, it->second);

      errorReply.out() << e.getBody() << '\n';
      errorReply.sendReply(e.getErrcode(), e.getErrmsg());
      logRequest(request, errorReply, e.getErrcode());
    }

    return keepAliveCount > 0;
  }

  void Worker::logRequest(const HttpRequest& request, const HttpReply& reply, unsigned httpReturn)
  {
    static std::atomic<unsigned> waitCount(0);
    ++waitCount;

    std::ofstream& accessLog = _application._accessLog;

    if (!accessLog.is_open())
    {
      const std::string& fname = TntConfig::it().accessLog;
      if (fname.empty())
      {
        log_debug("accesLog setting is empty");
        return;
      }

      cxxtools::MutexLock lock(_application._accessLogMutex);

      if (!accessLog.is_open())
      {
        log_debug("access log is not open - open now");
        accessLog.open(fname.c_str(), std::ios::out | std::ios::app);
        if (accessLog.fail())
        {
          std::cerr << "failed to open access log \"" << fname << '"' << std::endl;
          TntConfig::it().accessLog.clear();
        }
      }
    }

    log_debug("log request to access log with return code " << httpReturn);

    static const std::string unknown("-");

    std::string user = request.getUsername();
    if (user.empty())
      user = unknown;

    std::string peerIp = request.getPeerIp();
    if (peerIp.empty())
      peerIp = unknown;

    std::string query = request.getQuery();
    if (query.empty())
      query = unknown;

    time_t t;
    ::time(&t);

    cxxtools::MutexLock lock(_application._accessLogMutex);

    // cache for timestamp of access log
    static time_t lastLogTime = 0;
    static char timebuf[40];

    if (t != lastLogTime)
    {
      struct tm tm;
      ::localtime_r(&t, &tm);
      strftime(timebuf, sizeof(timebuf), "%d/%b/%Y:%H:%M:%S %z", &tm);
      lastLogTime = t;
    }

    accessLog << peerIp
              << " - " << user << " [" << timebuf << "] \""
              << request.getMethod_cstr() << ' '
              << query << ' '
              << "HTTP/" << request.getMajorVersion() << '.' << request.getMinorVersion() << "\" "
              << httpReturn << ' ';
    std::string::size_type contentSize = reply.getContentSize();
    if (contentSize != 0)
      accessLog << contentSize;
    else
      accessLog << '-';
    accessLog << " \"" << request.getHeader(httpheader::referer, "-") << "\" \""
              << request.getHeader(httpheader::userAgent, "-") << "\"\n";
    if (--waitCount == 0)
      accessLog.flush();
  }

  void Worker::dispatch(HttpRequest& request, HttpReply& reply)
  {
    _state = stateDispatch;
    const std::string& url = request.getUrl();

    if (!HttpRequest::checkUrl(url))
    {
      log_info("illegal url <" << url << '>');
      throw HttpError(HTTP_BAD_REQUEST, "illegal url");
    }

    request.setThreadContext(this);

    Dispatcher::PosType pos(_application.getDispatcher(), request);
    while (true)
    {
      _state = stateDispatch;

      // pos.getNext() throws NotFoundException at end
      Maptarget ci = pos.getNext();
      try
      {
        Component* comp = 0;
        try
        {
          if (ci.libname == _application.getAppName())
          {
            // if the libname is the app name look first, if the component is
            // linked directly
            try
            {
              Compident cii = ci;
              cii.libname = std::string();
              comp = &_comploader.fetchComp(cii, _application.getDispatcher());
            }
            catch (const NotFoundException&)
            {
              // if the component is not found in the binary, fetchComp throws
              // NotFoundException and comp remains 0.
              // so we can ignore the exceptioni and just continue
            }
          }

          if (comp == 0)
            comp = &_comploader.fetchComp(ci, _application.getDispatcher());
        }
        catch (const NotFoundException& e)
        {
          log_debug("NotFoundException caught - url " << e.getUrl() << " try next mapping");
          continue;
        }

        request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url);
        request.setArgs(ci.getArgs());

        std::string appname = _application.getAppName().empty() ? ci.libname : _application.getAppName();

        _application.getScopemanager().preCall(request, appname);

        _state = stateProcessingRequest;
        unsigned http_return;
        const char* http_msg;
        std::string msg;
        try
        {
          http_return = comp->topCall(request, reply, request.getQueryParams());
          if (http_return == DEFAULT)
            http_return = ci.getHttpReturn();

          http_msg = HttpReturn::httpMessage(http_return);
        }
        catch (const HttpReturn& e)
        {
          http_return = e.getReturnCode();
          msg = e.getMessage();
          http_msg = msg.c_str();
        }

        if (http_return != DECLINED)
        {
          if (reply.isDirectMode())
          {
            log_info("request " << request.getMethod_cstr() << ' ' << request.getQuery() << " ready, returncode " << http_return << ' ' << http_msg);
            _state = stateFlush;
            reply.out().flush();
          }
          else
          {
            log_info_if(!reply.isChunkedEncoding(), "request " << request.getMethod_cstr() << ' ' << request.getQuery() << " ready, returncode " << http_return << ' ' << http_msg << " - ContentSize: " << reply.getContentSize());

            _application.getScopemanager().postCall(request, reply, appname);

            _state = stateSendReply;
            if (reply.sendReply(http_return, http_msg))
            {
              log_debug("reply sent");
            }
            else
            {
              reply.setKeepAliveCounter(0);
              log_warn("sending failed");
            }

            log_info_if(reply.isChunkedEncoding(), "request " << request.getMethod_cstr() << ' ' << request.getQuery() << " ready, returncode " << http_return << ' ' << http_msg << " - ContentSize: " << reply.chunkedBytesWritten() << " (chunked)");
          }

          logRequest(request, reply, http_return);

          return;
        }
        else
          log_debug("component " << ci << " returned DECLINED");
      }
      catch (const LibraryNotFound& e)
      {
        log_warn("library " << e.getLibname() << " not found");
      }
    }

    throw NotFoundException(request.getUrl());
  }

  void Worker::timer()
  {
    time_t currentTime;
    time(&currentTime);

    cxxtools::MutexLock lock(_mutex);
    for (workers_type::iterator it = _workers.begin(); it != _workers.end(); ++it)
    {
      (*it)->healthCheck(currentTime);
    }
  }

  void Worker::healthCheck(time_t currentTime)
  {
    if (_state == stateProcessingRequest
        && _lastWaitTime != 0
        && TntConfig::it().maxRequestTime > 0)
    {
      if (static_cast<unsigned>(currentTime - _lastWaitTime) > TntConfig::it().maxRequestTime)
      {
        log_fatal("requesttime " << TntConfig::it().maxRequestTime << " seconds in thread "
          << _threadId << " exceeded - exit process");
        log_info("current state: " << _state);
        ::_exit(111);
      }
    }
  }

  void Worker::touch()
    { time(&_lastWaitTime); }

  Scope& Worker::getScope()
    { return _threadScope; }

  Worker::workers_type::size_type Worker::getCountThreads()
  {
    cxxtools::MutexLock lock(_mutex);
    return _workers.size();
  }
}