collectagent.cpp 17 KB
Newer Older
1
2
//================================================================================
// Name        : collectagent.cpp
3
4
// Author      : Axel Auweter
// Copyright   : Leibniz Supercomputing Centre
5
// Description : Main code of the CollectAgent
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//================================================================================

//================================================================================
// 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
28
#include <boost/network/protocol/http/server.hpp>
#include <boost/network/utils/thread_pool.hpp>
29
#include <boost/network/uri.hpp>
30
#include <iostream>
31
#include <cstdlib>
32
#include <signal.h>
33
34
#include <unistd.h>
#include <string>
35

36
#include <boost/date_time/posix_time/posix_time.hpp>
37

38
#include <dcdb/connection.h>
39
#include <dcdb/sensordatastore.h>
40
#include <dcdb/sensorconfig.h>
41

42
#include "configuration.h"
43
#include "simplemqttserver.h"
44
#include "messaging.h"
45
#include "abrt.h"
46
#include "dcdbdaemon.h"
47

48
49
#include "sensorcache.h"

50
51
52
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

53
using namespace std;
54
55

int keepRunning;
56
bool statistics;
57
58
uint64_t msgCtr;
uint64_t pmsgCtr;
59
DCDB::Connection* dcdbConn;
60
DCDB::SensorDataStore *mySensorDataStore;
61
DCDB::SensorConfig *mySensorConfig;
62
DCDB::SensorCache mySensorCache;
63
DCDB::SCError err;
Alessio Netti's avatar
Logging    
Alessio Netti committed
64
DCDBLog::logger_t lg;
65

66
/* Normal termination (SIGINT, CTRL+C) */
67
68
void sigHandler(int sig)
{
69
70
71
  keepRunning = 0;
}

72
73
74
75
76
77
/* Crash */
void abrtHandler(int sig)
{
  abrt(EXIT_FAILURE, SIGNAL);
}

78
79
80
81
82
struct httpHandler_t;
typedef boost::network::http::server<httpHandler_t> httpServer_t;
struct httpHandler_t {
  void operator()(httpServer_t::request const &request, httpServer_t::connection_ptr connection) {
    httpServer_t::string_type ip = source(request);
83
    std::ostringstream data;
84
    static httpServer_t::response_header headers[] = { { "Connection", "close" }, { "Content-Type", "text/plain" } };
85

86
87
    //try getting the latest value 
    try {
88
89
90
91
92
      boost::network::uri::uri uri("http://localhost"+request.destination);
      std::map<std::string, std::string> queries;
      boost::network::uri::query_map(uri, queries);
      int avg = atoi(queries.find("avg")->second.c_str());

93
      int64_t val = mySensorCache.getSensor(uri.path(), (uint64_t) avg);
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

      data << val << "\n";
      //data << "Sid : " << sid.toString() << ", Value: " << val << "." << std::endl;

      connection->set_status(httpServer_t::connection::ok);
      connection->set_headers(boost::make_iterator_range(headers, headers + 2));
      connection->write(data.str());

    }

    catch (const std::invalid_argument& e) {
      connection->set_status(httpServer_t::connection::not_found);
      connection->set_headers(boost::make_iterator_range(headers, headers + 2));
      connection->write("Error: Sensor id not found.\n");
    } catch (const std::out_of_range &e) {
      connection->set_status(httpServer_t::connection::no_content);
      connection->set_headers(boost::make_iterator_range(headers, headers + 2));
      connection->write("Error: Sensor unavailable.\n");
    } catch (const std::exception& e) {
      connection->set_status(httpServer_t::connection::internal_server_error);
      connection->set_headers(boost::make_iterator_range(headers, headers + 2));
      connection->write("Server error.\n");
    }

118
119
120
121
  }
};


122
int mqttCallback(SimpleMQTTMessage *msg)
123
124
125
126
{
  /*
   * Increment the msgCtr/vmsgCtr for statistics.
   */
127
  msgCtr++;
128
129
130
  if (msg->isPublish())
    pmsgCtr++;

131
  uint64_t len;
132
133
134
  /*
   * Decode the message and put into the database.
   */
135
  if (msg->isPublish()) {
136
137
138
139
140
141
      const char *topic = msg->getTopic().c_str();
      // We check whether the topic includes the \DCDB_MAP\ keyword, indicating that the payload will contain the
      // sensor's name. In that case, we set the mappingMessage flag to true, and filter the keyword out of the prefix
      // We use strncmp as it is the most efficient way to do it
      if (strlen(topic) > DCDB_MAP_LEN && strncmp(topic, DCDB_MAP, DCDB_MAP_LEN) == 0) {
          if ((len = msg->getPayloadLength()) == 0) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
142
              LOG(error) << "Empty topic-to-name mapping message received";
143
144
              return 1;
          }
145

146
147
148
149
150
151
          string sensorName((char *) msg->getPayload(), len);
          err = mySensorConfig->publishSensor(sensorName.c_str(), topic + DCDB_MAP_LEN);

          // PublishSensor does most of the error checking for us
          switch (err) {
              case DCDB::SC_INVALIDPATTERN:
Alessio Netti's avatar
Logging    
Alessio Netti committed
152
                  LOG(error) << "Invalid sensor topic : " << msg->getTopic();
153
154
                  return 1;
              case DCDB::SC_INVALIDPUBLICNAME:
Alessio Netti's avatar
Logging    
Alessio Netti committed
155
                  LOG(error) << "Invalid sensor public name: " << sensorName;
156
157
                  return 1;
              case DCDB::SC_INVALIDSESSION:
Alessio Netti's avatar
Logging    
Alessio Netti committed
158
                  LOG(error) << "Cannot reach sensor data store.";
159
160
161
162
163
164
165
166
167
168
169
                  return 1;
              default:
                  break;
          }
      } else {
          mqttPayload buf, *payload;

          len = msg->getPayloadLength();
          //In the 64 bit message case, the collect agent provides a timestamp
          if (len == sizeof(uint64_t)) {
              payload = &buf;
170
              payload->value = *((int64_t *) msg->getPayload());
171
172
              payload->timestamp = Messaging::calculateTimestamp();
              len = sizeof(uint64_t) * 2;
173
          }
174
175
176
177
178
179
              //...otherwise it just retrieves it from the MQTT message payload.
          else if ((len % sizeof(mqttPayload) == 0) && (len > 0)) {
              payload = (mqttPayload *) msg->getPayload();
          }
              //...otherwise this message is malformed -> ignore...
          else {
Alessio Netti's avatar
Logging    
Alessio Netti committed
180
              LOG(error) << "Message malformed";
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
              return 1;
          }

          /*
           * Check if we can decode the message topic
           * into a valid SensorId. If successful, store
           * the record in the database.
           */
          DCDB::SensorId sid;
          if (sid.mqttTopicConvert(msg->getTopic())) {
#if 0
              cout << "Topic decode successful:" << endl
                  << "  Raw:            " << hex << setw(16) << setfill('0') << sid.getRaw()[0] << hex << setw(16) << setfill('0') << sid.getRaw()[1] << endl
                  << "  DeviceLocation: " << hex << setw(16) << setfill('0') << sid.getDeviceLocation() << endl
                  << "  device_id:      " << hex << setw(8) << setfill('0') << sid.getDeviceSensorId().device_id << endl
                  << "  sensor_number:  " << hex << setw(4) << setfill('0') << sid.getDeviceSensorId().sensor_number << endl << dec;

              cout << "Payload ("  << len/sizeof(mqttPayload) << " messages):"<< endl;
              for (uint64_t i=0; i<len/sizeof(mqttPayload); i++) {
                cout << "  " << i << ": ts=" << payload[i].timestamp << " val=" << payload[i].value << endl;
              }
              cout << endl;
203
#endif
204
205
206
              for (uint64_t i = 0; i < len / sizeof(mqttPayload); i++) {
                  mySensorDataStore->insert(&sid, payload[i].timestamp, payload[i].value);
                  mySensorCache.storeSensor(sid, payload[i].timestamp, payload[i].value);
207

208
209
              }
              //mySensorCache.dump();
210
          }
211
#if 1
212
213
214
215
          else {
              cout << "Wrong topic format: " << msg->getTopic() << "\n";
              return 1;
          }
216
#endif
217
      }
218
  }
219
  return 0;
220
221
}

222
223
224



225
226
227
228
/*
 * Print usage information
 */
void usage() {
229
  globalCA_t& defaults = Configuration("").getGlobal();
230
231
232
233
234
  /*
             1         2         3         4         5         6         7         8
   012345678901234567890123456789012345678901234567890123456789012345678901234567890
   */
  cout << "Usage:" << endl;
Alessio Netti's avatar
Logging    
Alessio Netti committed
235
  cout << "  collectagent [-m<host>] [-r<host>] [-c<host>] [-C<interval>] [-u<username>] [-p<password>] [-t<ttl>] [-v<verbosity>] [-d] [-s] <path/to/configfiles/>" << endl;
236
237
238
239
  cout << "  collectagent -h" << endl;
  cout << endl;
  
  cout << "Options:" << endl;
240
241
242
243
  cout << "  -m<host>      MQTT listen address     [default: " << defaults.mqttListenAddress << "]" << endl;
  cout << "  -r<host>      REST API listen address [default: " << defaults.restListenAddress << "]" << endl;
  cout << "  -c<host>      Cassandra host          [default: " << defaults.cassandraSettings.address << "]" << endl;
  cout << "  -C<interval>  Cache interval in [s]   [default: " << defaults.cacheInterval << "]" << endl;
Michael Ott's avatar
Michael Ott committed
244
245
  cout << "  -u<username>  Cassandra username      [default: none]" << endl;
  cout << "  -p<password>  Cassandra password      [default: none]" << endl;
246
  cout << "  -t<ttl>       Cassandra insert TTL    [default: " << defaults.cassandraSettings.ttl << "]" << endl;
Alessio Netti's avatar
Logging    
Alessio Netti committed
247
248
  cout << "  -v<level>     Set verbosity of output [default: " << defaults.logLevelCmd << "]" << endl
       << "                Can be a number between 5 (all) and 0 (fatal)." << endl;
249
  cout << endl;
Michael Ott's avatar
Michael Ott committed
250
  cout << "  -d            Daemonize" << endl;
251
  cout << "  -s            Print message stats" <<endl;
Michael Ott's avatar
Michael Ott committed
252
  cout << "  -h            This help page" << endl;
253
  cout << endl;
254
255
256
}

int main(int argc, char* const argv[]) {
257
258

  try{
259

260
261
262
263
264
265
266
267
      // Checking if path to config is supplied
      if (argc <= 1) {
          cout << "Please specify a path to the config-directory" << endl << endl;
          usage();
          exit(EXIT_FAILURE);
      }

      // Defining options
Alessio Netti's avatar
Logging    
Alessio Netti committed
268
      const char* opts = "m:r:c:C:u:p:t:v:dDsh";
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284

      // Same mechanism as in DCDBPusher - checking if help string is requested before loading config
      char ret;
      while ((ret = getopt(argc, argv, opts)) != -1) {
          switch (ret)
          {
              case 'h':
                  usage();
                  exit(EXIT_FAILURE);
                  break;
              default:
                  //do nothing (other options are read later on)
                  break;
          }
      }

Alessio Netti's avatar
Logging    
Alessio Netti committed
285
286
287
      DCDBLog::initLogging();
      auto cmdSink = DCDBLog::setupCmdLogger();

288
289
      Configuration config(argv[argc - 1]);
      if( !config.readGlobal() ) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
290
          LOG(fatal) << "Failed to read global configuration!";
291
292
293
294
          exit(EXIT_FAILURE);
      }

      globalCA_t& settings = config.getGlobal();
295

296
      /* Parse command line */
297
      std::string listenHost, cassandraHost, restApiHost;
298
      std::string listenPort, cassandraPort, restApiPort;
299
300
301

      optind = 1;
      while ((ret=getopt(argc, argv, opts))!=-1) {
302
          switch(ret) {
303
              case 'm':
304
                  settings.mqttListenAddress = optarg;
305
                  break;
306
              case 'r':
307
                  settings.restListenAddress = optarg;
308
                  break;
309
              case 'c':
310
311
312
313
                  settings.cassandraSettings.address = optarg;
                  break;
              case 'C':
                  settings.cacheInterval = stoul(optarg);
314
                  break;
Michael Ott's avatar
Michael Ott committed
315
              case 'u':
316
                  settings.cassandraSettings.username = optarg;
317
                  break;
Michael Ott's avatar
Michael Ott committed
318
              case 'p': {
319
320
                  settings.cassandraSettings.password = optarg;
                  // What does this do? Mask the password?
Michael Ott's avatar
Michael Ott committed
321
322
323
324
325
326
327
                  size_t pwdLen = strlen(optarg);
                  memset(optarg, 'x', (pwdLen >= 3) ? 3 : pwdLen);
                  if (pwdLen > 3) {
                      memset(optarg+3, 0, pwdLen-3);
                  }
                  break;
              }
328
              case 't':
329
                  settings.cassandraSettings.ttl = stoul(optarg);
330
                  break;
Alessio Netti's avatar
Logging    
Alessio Netti committed
331
332
333
              case 'v':
                  settings.logLevelCmd = DCDBLog::translateLogLevel(stoi(optarg));
                  break;
334
              case 'd':
335
              case 'D':
336
                  settings.daemonize = 1;
337
                  break;
338
              case 's':
339
                  settings.statistics = 1;
340
                  break;
341
              case 'h':
342
343
344
              default:
                  usage();
                  exit(EXIT_FAILURE);
345
346
347
          }
      }

Alessio Netti's avatar
Logging    
Alessio Netti committed
348
349
350
351
352
      auto fileSink = DCDBLog::setupFileLogger(settings.tempDir, std::string("collectagent"));
      //severity level may be overwritten (per option or config-file) --> set it according to globalSettings
      fileSink->set_filter(boost::log::trivial::severity >= settings.logLevelFile);
      cmdSink->set_filter(boost::log::trivial::severity >= settings.logLevelCmd);

353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
      /*
       * Catch SIGINT signals to allow for proper server shutdowns.
       */
      signal(SIGINT, sigHandler);

      /*
       * Catch critical signals to allow for backtraces
       */
      signal(SIGABRT, abrtHandler);
      signal(SIGSEGV, abrtHandler);
      signal(SIGTERM, abrtHandler);

      // Daemonizing the collectagent
      if(settings.daemonize)
          dcdbdaemon();

369
370
371
      /*
       * Parse hostnames for port specifications
       */
372
      listenHost = string(settings.mqttListenAddress);
373
374
375
376
377
      size_t pos = listenHost.find(":");
      if (pos != string::npos) {
        listenPort = listenHost.substr(pos+1);
        listenHost.erase(pos);
      } else {
378
        listenPort = LISTENPORT;
379
      }
380
381

      cassandraHost = string(settings.cassandraSettings.address);
382
383
384
385
386
      pos = cassandraHost.find(":");
      if (pos != string::npos) {
        cassandraPort = cassandraHost.substr(pos+1);
        cassandraHost.erase(pos);
      } else {
387
        cassandraPort = CASSANDRAPORT;
388
      }
389
390

      restApiHost = string(settings.restListenAddress);
391
392
393
394
395
      pos = restApiHost.find(":");
      if (pos != string::npos) {
        restApiPort = restApiHost.substr(pos+1);
        restApiHost.erase(pos);
      } else {
396
        restApiPort = RESTAPIPORT;
397
398
      }

399
400
      // Setting the size of the sensor cache
      mySensorCache.setMaxHistory(settings.cacheInterval * 1000000000);
401

402
403
      //Allocate and initialize connection to Cassandra.
      dcdbConn = new DCDB::Connection(cassandraHost, atoi(cassandraPort.c_str()), settings.cassandraSettings.username, settings.cassandraSettings.password);
404

Axel Auweter's avatar
Axel Auweter committed
405
      if (!dcdbConn->connect()) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
406
          LOG(fatal) << "Cannot connect to Cassandra!";
407
408
409
410
411
412
          exit(EXIT_FAILURE);
      }

      /*
       * Legacy behavior: Initialize the DCDB schema in Cassandra.
       */
Axel Auweter's avatar
Axel Auweter committed
413
      dcdbConn->initSchema();
414
415
416
417

      /*
       * Allocate the SensorDataStore.
       */
418
      mySensorDataStore = new DCDB::SensorDataStore(dcdbConn);
419
      mySensorConfig = new DCDB::SensorConfig(dcdbConn);
420
421
422

      /*
       * Set TTL for data store inserts if TTL > 0.
423
       */
424
425
      if (settings.cassandraSettings.ttl > 0)
        mySensorDataStore->setTTL(settings.cassandraSettings.ttl);
426

427
428
429
      /*
       * Start the MQTT Message Server.
       */
430
      SimpleMQTTServer ms(listenHost, listenPort, settings.messageThreads, settings.messageSlots);
431
      
432
433
434
      ms.setMessageCallback(mqttCallback);
      ms.start();

Alessio Netti's avatar
Logging    
Alessio Netti committed
435
      LOG(info) << "MQTT Server running...";
436
      
437
438
439
440
441
442
443
444
445
446
447
448
      /*
       * Start the HTTP Server for the REST API
       */
      std::thread httpThread;
      httpHandler_t httpHandler;
      httpServer_t::options httpOptions(httpHandler);

      httpOptions.reuse_address(true);
      httpOptions.thread_pool(std::make_shared<boost::network::utils::thread_pool>());
      httpServer_t httpServer(httpOptions.address(restApiHost).port(restApiPort));
      httpThread = std::thread([&httpServer] { httpServer.run(); });

Alessio Netti's avatar
Logging    
Alessio Netti committed
449
      LOG(info) <<  "HTTP Server running...";
450

451
452
453
454
455
456
      /*
       * Run (hopefully) forever...
       */
      keepRunning = 1;
      timeval start, end;
      double elapsed;
457
      
Alessio Netti's avatar
Logging    
Alessio Netti committed
458
      LOG(info) << "Collect Agent running...";
459

460
461
      while(keepRunning) {
          gettimeofday(&start, NULL);
462
          sleep(60);
463
464
465
466
          /* not really thread safe but will do the job */
          gettimeofday(&end, NULL);
          elapsed = (end.tv_sec - start.tv_sec) * 1000.0;
          elapsed += (end.tv_usec - start.tv_usec) / 1000.0;
467
          float publish = msgCtr?(pmsgCtr*100.0)/msgCtr:0;
468
          if (settings.statistics) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
469
              LOG(info) << "Message rate: " << (msgCtr/elapsed)*1000.0 << " messages/second (" << publish << "% PUBLISH)";
470
          }
471
          msgCtr = 0;
472
          pmsgCtr = 0;
473
474
      }

Alessio Netti's avatar
Logging    
Alessio Netti committed
475
      LOG(info) << "Stopping...";
476
477

      ms.stop();
Alessio Netti's avatar
Logging    
Alessio Netti committed
478
      LOG(info) << "MQTT Server stopped...";
479
480
      httpServer.stop();
      httpThread.join();
Alessio Netti's avatar
Logging    
Alessio Netti committed
481
      LOG(info) << "HTTP Server stopped...";
482
      delete mySensorDataStore;
483
      delete mySensorConfig;
Axel Auweter's avatar
Axel Auweter committed
484
485
      dcdbConn->disconnect();
      delete dcdbConn;
Alessio Netti's avatar
Logging    
Alessio Netti committed
486
      LOG(info) << "Collect Agent closed. Bye bye...";
487
  }
488
  catch (const exception& e) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
489
      LOG(fatal) << "Exception: " << e.what();
490
      abrt(EXIT_FAILURE, INTERR);
491
492
  }

493
  return EXIT_SUCCESS;
494
}
495
496