File: tntnetimpl.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 (311 lines) | stat: -rw-r--r-- 9,010 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
/*
 * Copyright (C) 2015 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 "tntnetimpl.h"
#include "tnt/worker.h"
#include "tnt/listener.h"
#include "tnt/http.h"
#include "tnt/httpreply.h"
#include "tnt/sessionscope.h"
#include "tnt/tntconfig.h"
#include "tnt/util.h"

#include <cxxtools/net/tcpstream.h>
#include <cxxtools/systemerror.h>
#include <cxxtools/log.h>

#include <unistd.h>
#include <signal.h>

#include <config.h>

log_define("tntnet.tntnet.impl")

namespace tnt
{
  namespace
  {
    void configureDispatcher(Dispatcher& dis)
    {
      const TntConfig::MappingsType& mappings = TntConfig::it().mappings;
      for (TntConfig::MappingsType::const_iterator it = mappings.begin(); it != mappings.end(); ++it)
      {
        Maptarget ci(it->target);
        if (!it->pathinfo.empty())
          ci.setPathInfo(it->pathinfo);
        ci.setHttpReturn(it->httpreturn);
        ci.setArgs(it->args);
        dis.addUrlMapEntry(it->vhost, it->url, it->method, it->ssl, ci);
      }
    }

    typedef std::set<TntnetImpl*> TntnetInstancesType;
    cxxtools::Mutex allTntnetInstancesMutex;
    TntnetInstancesType allRunningTntnetInstances;

  }

  ////////////////////////////////////////////////////////////////////////
  // Tntnet
  //
  TntnetImpl::TntnetImpl()
    : _minthreads(TntConfig::it().minThreads),
      _maxthreads(TntConfig::it().maxThreads),
      _pollerthread(cxxtools::callable(_poller, &Poller::run)),
      _poller(_queue)
  { }

  bool TntnetImpl::_stop = false;
  cxxtools::Mutex TntnetImpl::_timeStopMutex;
  cxxtools::Condition TntnetImpl::_timerStopCondition;

  TntnetImpl::listeners_type TntnetImpl::_allListeners;

  void TntnetImpl::init(Tntnet& app, const TntConfig& config)
  {
    TntConfig::it() = config;

    log_init(config.logConfiguration);

    _minthreads = config.minThreads;
    _maxthreads = config.maxThreads;

    _queue.setCapacity(config.queueSize);

    for (TntConfig::EnvironmentType::const_iterator it = config.environment.begin(); it != config.environment.end(); ++it)
    {
      std::string name = it->first;
      std::string value = it->second;
#ifdef HAVE_SETENV
      log_debug("setenv " << name << "=\"" << value << '"');
      ::setenv(name.c_str(), value.c_str(), 1);
#else
      char* env = new char[name.size() + value.size() + 2];
      name.copy(env, name.size());
      env[name.size()] = '=';
      value.copy(env + name.size() + 1, value.size());
      env[name.size() + value.size() + 1] = '\0';

      log_debug("putenv(" << env << ')');
      ::putenv(env);
#endif
    }

    configureDispatcher(_dispatcher);

    // initialize listeners
    for (TntConfig::ListenersType::const_iterator it = config.listeners.begin(); it != config.listeners.end(); ++it)
    {
      listen(app, it->ip, it->port);
    }

    for (TntConfig::SslListenersType::const_iterator it = config.ssllisteners.begin(); it != config.ssllisteners.end(); ++it)
    {
      sslListen(app, it->ip, it->port, it->certificate, it->key, it->sslVerifyLevel, it->sslCa);
    }
  }

  void TntnetImpl::listen(Tntnet& app, const std::string& ip, unsigned short int port)
  {
    log_debug("listen on ip " << ip << " port " << port);
    Listener* listener = new Listener(app, ip, port, _queue);
    _listeners.insert(listener);
    _allListeners.insert(listener);
  }

  void TntnetImpl::sslListen(Tntnet& app,
                     const std::string& ipaddr, unsigned short int port,
                     const std::string& certificateFile, const std::string& keyFile,
                     int sslVerifyLevel, const std::string& sslCa)
  {
    log_debug("listen on ip " << ipaddr << " port " << port << " (ssl)");
    Listener* listener = new Listener(app, ipaddr, port, _queue, certificateFile, keyFile, sslVerifyLevel, sslCa);
    _listeners.insert(listener);
    _allListeners.insert(listener);
  }

  void TntnetImpl::run()
  {
    log_debug("worker-process");

    _stop = false;

    if (_listeners.empty())
      throwRuntimeError("no listeners defined");

    log_debug(_listeners.size() << " listeners");

    if (_listeners.size() >= _minthreads)
    {
      log_warn("at least one more worker than listeners needed - set MinThreads to "
        << _listeners.size() + 1);
      _minthreads = _listeners.size() + 1;
    }

    if (_maxthreads < _minthreads)
    {
      log_warn("MaxThreads < MinThreads - set MaxThreads = MinThreads = " << _minthreads);
      _maxthreads = _minthreads;
    }

    // initialize worker-process

    // SIGPIPE must be ignored
    struct sigaction sa;
    sa.sa_handler = SIG_IGN;
    sa.sa_flags = 0;
    if (sigaction(SIGPIPE, &sa, 0) == -1)
        cxxtools::throwSystemError("sigaction");

    // create worker-threads
    log_info("create " << _minthreads << " worker threads");
    for (unsigned i = 0; i < _minthreads; ++i)
    {
      log_debug("create worker " << i);
      Worker* s = new Worker(*this);
      s->create();
    }

    // create poller-thread
    log_debug("start poller thread");
    _pollerthread.start();

    log_debug("start timer thread");
    cxxtools::AttachedThread timerThread(cxxtools::callable(*this, &TntnetImpl::timerTask));
    timerThread.start();

    {
      cxxtools::MutexLock lock(allTntnetInstancesMutex);
      allRunningTntnetInstances.insert(this);
    }

    // mainloop
    cxxtools::Mutex mutex;
    while (!_stop)
    {
      {
        cxxtools::MutexLock lock(mutex);
        _queue.noWaitThreads.wait(lock);
      }

      if (_stop)
        break;

      if (Worker::getCountThreads() < _maxthreads)
      {
        log_info("create workerthread");
        Worker* s = new Worker(*this);
        s->create();
      }
      else
        log_info("max worker-threadcount " << _maxthreads << " reached");

      if (TntConfig::it().threadStartDelay > 0)
        usleep(TntConfig::it().threadStartDelay.totalUSecs());
    }

    log_info("stopping TntnetImpl");

    {
      cxxtools::MutexLock lock(allTntnetInstancesMutex);
      allRunningTntnetInstances.erase(this);
    }

    log_info("stop listener");
    for (listeners_type::iterator it = _listeners.begin(); it != _listeners.end(); ++it)
      (*it)->terminate();

    log_info("stop poller thread");
    _poller.doStop();
    _pollerthread.join();

    log_info("stop timer thread");
    timerThread.join();

    if (Worker::getCountThreads() > 0)
    {
      log_info("wait for " << Worker::getCountThreads() << " worker threads to stop");
      while (Worker::getCountThreads() > 0)
      {
        log_debug("wait for worker threads to stop; " << Worker::getCountThreads() << " left");
        usleep(100);
      }
    }

    log_debug("destroy listener");
    for (listeners_type::iterator it = _listeners.begin(); it != _listeners.end(); ++it)
      delete *it;
    _listeners.clear();

    HttpReply::postRunCleanup();
    HttpRequest::postRunCleanup();

    log_info("all threads stopped");
  }

  void TntnetImpl::setMinThreads(unsigned n)
  {
    if (_listeners.size() >= n)
    {
      log_warn("at least one more worker than listeners needed - set MinThreads to "
        << _listeners.size() + 1);
      _minthreads = _listeners.size() + 1;
    }
    else
      _minthreads = n;

  }

  void TntnetImpl::timerTask()
  {
    log_debug("timer thread");

    while (true)
    {
      {
        cxxtools::MutexLock timeStopLock(_timeStopMutex);
        if (_stop || _timerStopCondition.wait(timeStopLock, TntConfig::it().timerSleep))
          break;
      }

      getScopemanager().checkSessionTimeout();
      Worker::timer();
    }

    _queue.noWaitThreads.signal();
    _minthreads = _maxthreads = 0;
  }

  void TntnetImpl::shutdown()
  {
    _stop = true;
    _timerStopCondition.broadcast();
  }
}