Currently job artifacts in CI/CD pipelines on LRZ GitLab never expire. Starting from Wed 26.1.2022 the default expiration time will be 30 days (GitLab default). Currently existing artifacts in already completed jobs will not be affected by the change. The latest artifacts for all jobs in the latest successful pipelines will be kept. More information: https://gitlab.lrz.de/help/user/admin_area/settings/continuous_integration.html#default-artifacts-expiration

simplemqttserverthread.cpp 15.2 KB
Newer Older
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
//================================================================================
// Name        : simplemqttserverthread.cpp
// Author      : Axel Auweter
// Copyright   : Leibniz Supercomputing Centre
// Description : Implementation of classes for running MQTT server threads
//================================================================================

//================================================================================
// This file is part of DCDB (DataCenter DataBase)
// Copyright (C) 2011-2016 Leibniz Supercomputing Centre
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//================================================================================
26
27

#include "simplemqttserver.h"
28
#include "abrt.h"
29
30

using namespace std;
31
using namespace boost::system;
32
33
34
35
36

#ifdef SimpleMQTTVerbose
static boost::mutex coutMtx;
#endif

37
38
static boost::mutex launchMtx;

39
40
41
42
43
44
45
46
47
SimpleMQTTServerThread::SimpleMQTTServerThread()
{
  /*
   * Start the thread at the 'launch' function. The 'launch'
   * function will take care of calling the child-specific
   * 'run' function which contains the thread's main loop.
   *
   * Special care must be taken not to call the run function
   * before the child has gone through its constructor. Thus,
48
49
50
51
52
53
54
55
56
57
58
59
   * we lock a mutex (launchMtx) that will cause the 'launch'
   * function to  wait until the mutex is released by the
   * child's constructor.
   *
   * A second mutex (cleanupMtx) is held to allow others to
   * wait for a thread to return from its child-specific
   * 'run' function. This is necessary for cases where the
   * child class has local objects that can only be destroyed
   * after the 'run' function has finished (to avoid access
   * to these objects in the 'run'function after destroying
   * them). In such cases, the child class destructor can try
   * to obtain the mutex in the destructor.
60
   */
61
62
  launchMtx.lock();
  cleanupMtx.lock();
63
64
65
66

  terminate = false;
  if (pthread_create(&t, NULL, launch, this) != 0) {
      cout << "Error creating new MQTT server thread.\n";
67
      abrt(EXIT_FAILURE, INTERR);
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
  }

#ifdef SimpleMQTTVerbose
  coutMtx.lock();
  cout << "Started Thread (" << t << ") of class (" << this << ")...\n";
  coutMtx.unlock();
#endif
}

SimpleMQTTServerThread::~SimpleMQTTServerThread()
{
  /*
   * Terminate the thread and join it to ensure proper
   * thread termination before the class is destroyed.
   */
  terminate = true;
  if (pthread_join(t, NULL) != 0) {
      cout << "Error joining thread.\n";
86
      abrt(EXIT_FAILURE, INTERR);
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
  }

#ifdef SimpleMQTTVerbose
  coutMtx.lock();
  cout << "Terminated Thread (" << t << ") of class (" << this << ")...\n";
  coutMtx.unlock();
#endif
}

void* SimpleMQTTServerThread::launch(void *selfPtr)
{
#ifdef SimpleMQTTVerbose
  coutMtx.lock();
  cout << "Running launcher for class (" << selfPtr << ")...\n";
  coutMtx.unlock();
#endif

  /*
   * The following lines guard the run function to be called
   * before the constructor of the child class has finished.
   * The lock is released at the end of the child's constructor.
   */
109
110
  launchMtx.lock();
  launchMtx.unlock();
111
112
113
114
115
116

  /*
   * Call the child's run function...
   */
  ((SimpleMQTTServerThread*)selfPtr)->run();

117
118
119
120
121
  /*
   * The thread will terminate. Unlock the cleanupMtx...
   */
  ((SimpleMQTTServerThread*)selfPtr)->cleanupMtx.unlock();

122
123
124
  return NULL;
}

125
126
127
128
129
130
131
132
133
134
135
void SimpleMQTTServerThread::yield()
{
  /*
   * Yield this thread's execution to give way to other threads.
   * This is being used in the SimpleMQTTServer to allow the
   * accept thread acquiring the fdsMtx lock. Otherwise, in
   * particular on single-CPU systems (or when the acceptThread
   * and the messageThread share a core), waiting connections
   * may have to wait a long time before the lock will be given
   * to the acceptThread.
   */
136
  boost::this_thread::yield();
137
138
}

139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
void SimpleMQTTServerAcceptThread::run()
{
#ifdef SimpleMQTTVerbose
  coutMtx.lock();
  cout << "Running SimpleMQTTServerAcceptThread for socket " << socket << "...\n";
  coutMtx.unlock();
#endif

  int newsock = -1;
  struct pollfd fd;

  while (!terminate) {
      /*
       * Wait for something to happen on the socket...
       */
      fd.fd = socket;
      fd.events = POLLIN | POLLPRI;
      fd.revents = 0;
      if(poll(&fd, 1, SimpleMQTTPollTimeout) > 0 && (fd.revents & (POLLIN | POLLPRI))) {

159
160
161
162
163
164
          /*
           * Find a free message thread to take over
           * the next incoming connection.
           */
          SimpleMQTTServerMessageThread *mt = NULL;
          for (boost::ptr_list<SimpleMQTTServerMessageThread>::iterator i = messageThreads.begin(); i != messageThreads.end(); i++) {
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
              if (i->hasCapacity()) {
                  mt = &*i;
#ifdef SimpleMQTTVerbose
  coutMtx.lock();
  cout << "Found a message thread with capacity: " << mt << "...\n";
  coutMtx.unlock();
#endif
              }
              else {
#ifdef SimpleMQTTVerbose
  coutMtx.lock();
  cout << "No capacity in message thread: " << mt << "...\n";
  coutMtx.unlock();
#endif
              }
180
          }
181

182
183
184
185
186
187
188
189
190
191
192
193
          /*
           * In case no free message thread was found,
           * try to create a new one as long as we do
           * not exceed the maximum.
           */
          if (!mt) {
              if (messageThreads.size() >= SimpleMQTTMaxThreadsPerSocket) {
                  cout << "Warning: socket " << socket << " cannot accept more connections.\n";
                  // FIXME: There must be nicer ways to handle such situations...
                  sleep(1);
                  continue;
              }
194
              messageThreads.push_back(new SimpleMQTTServerMessageThread(messageCallback));
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
              continue;
          }

          /*
           * Take the next incoming connection.
           */
#ifdef SimpleMQTTVerbose
          coutMtx.lock();
          cout << "Thread (" << this << ") waiting in accept()...\n";
          coutMtx.unlock();
#endif
          newsock = accept(socket, NULL, 0);
          if (newsock != -1) {
              int opt = fcntl(newsock, F_GETFL, 0);
              if (opt == -1 || fcntl(newsock, F_SETFL, opt | O_NONBLOCK)==-1) {
210
211
212
213
214
#ifdef SimpleMQTTVerbose
          coutMtx.lock();
          cout << "Setting socket to non-blocking in thread (" << this << ") failed for socket " << newsock << "...\n";
          coutMtx.unlock();
#endif
215
216
217
                  close(newsock);
              }
              else {
218
219
220
221
222
#ifdef SimpleMQTTVerbose
          coutMtx.lock();
          cout << "Successfully set socket " << newsock << " nonblocing in thread (" << this << ")...\n";
          coutMtx.unlock();
#endif
223
224
225
                  mt->assignConnection(newsock);
              }
          }
226
227
228
229
230
231
232
          else {
#ifdef SimpleMQTTVerbose
          coutMtx.lock();
          cout << "Accept() in thread (" << this << ") returned -1...\n";
          coutMtx.unlock();
#endif
          }
233
234
235
236
      }
  }
}

237
void SimpleMQTTServerAcceptThread::setMessageCallback(SimpleMQTTMessageCallback callback)
238
{
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
  /*
   * Set the function that will be called for each received
   * MQTT message and propagate to all message threads.
   */
  messageCallback = callback;
  for (boost::ptr_list<SimpleMQTTServerMessageThread>::iterator i = messageThreads.begin(); i != messageThreads.end(); i++) {
      (*i).setMessageCallback(callback);
  }
}

SimpleMQTTServerAcceptThread::SimpleMQTTServerAcceptThread(int listenSock, SimpleMQTTMessageCallback callback)
{
  /*
   * Assign socket and message callback.
   */
254
  socket = listenSock;
255
  messageCallback = callback;
256
257
258
259
260

  /*
   * Release the lock to indicate that the constructor has
   * finished. This causes the launcher to call the run function.
   */
261
  launchMtx.unlock();
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
}

SimpleMQTTServerAcceptThread::~SimpleMQTTServerAcceptThread()
{
}

void SimpleMQTTServerMessageThread::run()
{
#ifdef SimpleMQTTVerbose
  coutMtx.lock();
  cout << "Running SimpleMQTTServerMessageThread (" << this << ")...\n";
  coutMtx.unlock();
#endif

  int numfds = -1;
277
  char inbuf[SimpleMQTTReadBufferSize];
278
279
280
281
282

  while (!terminate) {
      /*
       * Check for activity on our sockets...
       */
283
      fdsMtx.lock();
284
      numfds = poll(fds, SimpleMQTTConnectionsPerThread, SimpleMQTTPollTimeout);
285
      fdsMtx.unlock();
286

287
288
289
290
291
292
293
294
      /*
       * Allow other threads to run (avoid instantaneous
       * re-acquisition of the fdsMtx lock in the next
       * iteration while connections are pending in the
       * acceptThread).
       */
      yield();

295
      if (numfds == -1)
296
          throw new boost::system::system_error(errno, boost::system::system_category(), "Error in poll().");
297
298
299
300
301
302

      /*
       * Apparently, there is work to do...
       */
      if (numfds > 0) {
          for (int connectionId=0; connectionId<SimpleMQTTConnectionsPerThread; connectionId++) {
303
304
305
306
307
308
309
              if (fds[connectionId].fd != -1) {
#ifdef SimpleMQTTVerbose
                  coutMtx.lock();
                  cout << "fd(" << fds[connectionId].fd << ") revents: " << hex << fds[connectionId].revents << "\n";
                  coutMtx.unlock();
#endif

310
                  if (fds[connectionId].revents & POLLIN) {
311
312
313
314
315
316
317
                      char* readPtr;
                      ssize_t rbytes, lbytes, bytes;

                      rbytes = read(fds[connectionId].fd, inbuf, SimpleMQTTReadBufferSize);

                      readPtr = inbuf;
                      lbytes = rbytes;
318
319

                      /*
320
                       * If read() returns 0, the connection was closed on the
321
322
                       * remote side. In this case, release it from our list.
                       */
323
                      if (rbytes == 0) {
324
325
                          releaseConnection(connectionId);
                      }
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

                      while (lbytes > 0) {
                          /*
                           * Allocate new message if there is none.
                           */
                          if (!msg[connectionId]) {
                              msg[connectionId] = new SimpleMQTTMessage();
                              if (!msg[connectionId]) {
                                  cout << "Warning: Out of memory! Discarding network input!\n";
                                  continue;
                              }
#ifdef SimpleMQTTVerbose
                              coutMtx.lock();
                              cout << "Allocated new SimpleMQTTMessage (" << msg[connectionId] << ")...\n";
                              coutMtx.unlock();
#endif
                          }

                          /*
                           * Append received data to message.
                           */
                          bytes = msg[connectionId]->appendRawData(readPtr, lbytes);
                          readPtr += bytes;
                          lbytes -= bytes;

                          /*
                           * Check if message is complete.
                           */
                          if (msg[connectionId]->complete()) {
                              /*
356
357
358
359
                               * Forward message upstream!
                               * If there is a callback function, it is responsible
                               * for freeing the message using delete. Otherwise, we
                               * have to take care of this, here.
360
361
362
363
364
365
                               */
#ifdef SimpleMQTTVerbose
                              coutMtx.lock();
                              cout << "Completed receiving SimpleMQTTMessage (" << msg[connectionId] << ")...\n";
                              coutMtx.unlock();
#endif
366
367
368
369
370
371
                              if (messageCallback) {
                                  messageCallback(msg[connectionId]);
                              }
                              else {
                                  delete msg[connectionId];
                              }
372
373
374
                              msg[connectionId] = NULL;
                          }
                      }
375
376
377
378
379
380
381
382
383
                  }
              }
          }
      }
  }
}

bool SimpleMQTTServerMessageThread::hasCapacity()
{
384
  return numConnections < SimpleMQTTConnectionsPerThread;
385
386
387
388
389
390
391
392
393
394
}

void SimpleMQTTServerMessageThread::assignConnection(int newsock)
{
  /*
   * Find the first free slot in fds and assign connection.
   */
  fdsMtx.lock();
  for (int i=0; i<SimpleMQTTConnectionsPerThread; i++) {
      if (fds[i].fd == -1) {
395
          fds[i].events = POLLIN | POLLPRI | POLLHUP;
396
          fds[i].revents = 0;
Axel Auweter's avatar
Axel Auweter committed
397
          fds[i].fd = newsock;
398
399
400

          numConnections++;

401
402
403
404
405
406
#ifdef SimpleMQTTVerbose
          coutMtx.lock();
          cout << "Assigned connection  (" << this << ", " << i << ", " << fds[i].fd << ")...\n";
          coutMtx.unlock();
#endif

407
408
409
410
411
412
413
414
415
416
417
418
          break;
      }
  }
  fdsMtx.unlock();
}

void SimpleMQTTServerMessageThread::releaseConnection(int connectionId)
{
  /*
   * Close the connection an clean up.
   */
  fdsMtx.lock();
419
  shutdown(fds[connectionId].fd, SHUT_RDWR);
420
421
422
423
424
  close(fds[connectionId].fd);
  fds[connectionId].fd = -1;
  fds[connectionId].events = 0;
  fds[connectionId].revents = 0;

425
426
427
428
  /*
   * If the connection was closed while we were receiving
   * a message, delete the corresponding message object.
   */
429
430
431
432
433
  if(msg[connectionId]) {
    delete msg[connectionId];
    msg[connectionId] = NULL;
  }

434
435
  numConnections--;
  fdsMtx.unlock();
436
437
438
439
440
441

#ifdef SimpleMQTTVerbose
  coutMtx.lock();
  cout << "Released connection  (" << this << ", " << connectionId << ")...\n";
  coutMtx.unlock();
#endif
442
443
}

444
445
446
447
448
449
void SimpleMQTTServerMessageThread::setMessageCallback(SimpleMQTTMessageCallback callback)
{
  messageCallback = callback;
}

SimpleMQTTServerMessageThread::SimpleMQTTServerMessageThread(SimpleMQTTMessageCallback callback)
450
{
451
452
453
454
455
456
#ifdef SimpleMQTTVerbose
  coutMtx.lock();
  cout << "Created new MessageThread (" << (void*)this << ")\n";
  coutMtx.unlock();
#endif

457
458
459
460
461
462
  /*
   * Clear the fds array. Warning: This will only work when the
   * size of the fds array is determined at compile time.
   */
  memset(fds, -1, sizeof(fds));

Axel Auweter's avatar
Axel Auweter committed
463
464
465
466
467
468
  /*
   * Clear the msg array. Warning: This will only work when the
   * size of the msg array is determined at compile time.
   */
  memset(msg, 0, sizeof(msg));

469
  /*
470
471
   * Initialize the number of active connections to 0 and set
   * the messageCallback function.
472
473
   */
  numConnections = 0;
474
  messageCallback = callback;
475
476
477
478
479

  /*
   * Release the lock to indicate that the constructor has
   * finished. This causes the launcher to call the run function.
   */
480
  launchMtx.unlock();
481
482
483
484
}

SimpleMQTTServerMessageThread::~SimpleMQTTServerMessageThread()
{
485
486
487
488
489
490
491
492
493
494
495
  /*
   * When this destructor is called externally, we are likely
   * holding the fdsMtx mutex and waiting in poll().
   * Terminate the thread from here and acquire cleanupMtx to
   * ensure that the thread's 'run' function has terminated in
   * order to avoid fdsMtx to be accessed after destruction.
   */
  terminate = true;

  cleanupMtx.lock();
  cleanupMtx.unlock();
496
497
}