collectagent.cpp 17.4 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
#include <dcdb/version.h>
42

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

49
50
#include "sensorcache.h"

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

54
using namespace std;
55
56

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

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

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

80
81
82
83
84
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);
85
    std::ostringstream data;
86
    static httpServer_t::response_header headers[] = { { "Connection", "close" }, { "Content-Type", "text/plain" } };
87

88
89
    //try getting the latest value 
    try {
90
91
92
93
94
      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());

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

      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");
    }

120
121
122
123
  }
};


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

133
  uint64_t len;
134
135
136
  /*
   * Decode the message and put into the database.
   */
137
  if (msg->isPublish()) {
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
Alessio Netti's avatar
Alessio Netti committed
142
      if (strncmp(topic, DCDB_MAP, DCDB_MAP_LEN) == 0) {
143
          if ((len = msg->getPayloadLength()) == 0) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
144
              LOG(error) << "Empty topic-to-name mapping message received";
145
146
              return 1;
          }
147

148
149
150
151
152
153
          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
154
                  LOG(error) << "Invalid sensor topic : " << msg->getTopic();
155
156
                  return 1;
              case DCDB::SC_INVALIDPUBLICNAME:
Alessio Netti's avatar
Logging    
Alessio Netti committed
157
                  LOG(error) << "Invalid sensor public name: " << sensorName;
158
159
                  return 1;
              case DCDB::SC_INVALIDSESSION:
Alessio Netti's avatar
Logging    
Alessio Netti committed
160
                  LOG(error) << "Cannot reach sensor data store.";
161
162
163
164
165
166
167
168
169
170
171
                  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;
172
              payload->value = *((int64_t *) msg->getPayload());
173
174
              payload->timestamp = Messaging::calculateTimestamp();
              len = sizeof(uint64_t) * 2;
175
          }
176
177
178
179
180
181
              //...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
182
              LOG(error) << "Message malformed";
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
              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;
205
#endif
206
	      std::list<DCDB::SensorDataStoreReading> readings;
207
              for (uint64_t i = 0; i < len / sizeof(mqttPayload); i++) {
208
209
		  DCDB::SensorDataStoreReading r(sid, payload[i].timestamp, payload[i].value);
		  readings.push_back(r);
210
211
                  mySensorCache.storeSensor(sid, payload[i].timestamp, payload[i].value);
              }
212
	      mySensorDataStore->insertBatch(readings);
213
	      readingCtr+= readings.size();
214

215
              //mySensorCache.dump();
216
          }
217
#if 1
218
219
220
221
          else {
              cout << "Wrong topic format: " << msg->getTopic() << "\n";
              return 1;
          }
222
#endif
223
      }
224
  }
225
  return 0;
226
227
}

228
229
230



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

int main(int argc, char* const argv[]) {
263
    cout << "CollectAgent " << VERSION << " (libdcdb " << DCDB::Version::getVersion() << ")" << endl << endl;
264
265

  try{
266

267
268
269
270
271
272
273
274
      // 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
275
      const char* opts = "m:r:c:C:u:p:t:v:dDsh";
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291

      // 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
292
293
294
      DCDBLog::initLogging();
      auto cmdSink = DCDBLog::setupCmdLogger();

295
296
      Configuration config(argv[argc - 1]);
      if( !config.readGlobal() ) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
297
          LOG(fatal) << "Failed to read global configuration!";
298
299
300
301
          exit(EXIT_FAILURE);
      }

      globalCA_t& settings = config.getGlobal();
302

303
      /* Parse command line */
304
      std::string listenHost, cassandraHost, restApiHost;
305
      std::string listenPort, cassandraPort, restApiPort;
306
307
308

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

Alessio Netti's avatar
Logging    
Alessio Netti committed
355
356
357
358
359
      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);

360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
      /*
       * 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();

376
377
378
      /*
       * Parse hostnames for port specifications
       */
379
      listenHost = string(settings.mqttListenAddress);
380
381
382
383
384
      size_t pos = listenHost.find(":");
      if (pos != string::npos) {
        listenPort = listenHost.substr(pos+1);
        listenHost.erase(pos);
      } else {
385
        listenPort = LISTENPORT;
386
      }
387
388

      cassandraHost = string(settings.cassandraSettings.address);
389
390
391
392
393
      pos = cassandraHost.find(":");
      if (pos != string::npos) {
        cassandraPort = cassandraHost.substr(pos+1);
        cassandraHost.erase(pos);
      } else {
394
        cassandraPort = CASSANDRAPORT;
395
      }
396
397

      restApiHost = string(settings.restListenAddress);
398
399
400
401
402
      pos = restApiHost.find(":");
      if (pos != string::npos) {
        restApiPort = restApiHost.substr(pos+1);
        restApiHost.erase(pos);
      } else {
403
        restApiPort = RESTAPIPORT;
404
405
      }

406
407
      // Setting the size of the sensor cache
      mySensorCache.setMaxHistory(settings.cacheInterval * 1000000000);
408

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

Axel Auweter's avatar
Axel Auweter committed
412
      if (!dcdbConn->connect()) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
413
          LOG(fatal) << "Cannot connect to Cassandra!";
414
415
416
417
418
419
          exit(EXIT_FAILURE);
      }

      /*
       * Legacy behavior: Initialize the DCDB schema in Cassandra.
       */
Axel Auweter's avatar
Axel Auweter committed
420
      dcdbConn->initSchema();
421
422
423
424

      /*
       * Allocate the SensorDataStore.
       */
425
      mySensorDataStore = new DCDB::SensorDataStore(dcdbConn);
426
      mySensorConfig = new DCDB::SensorConfig(dcdbConn);
427
428
429

      /*
       * Set TTL for data store inserts if TTL > 0.
430
       */
431
432
      if (settings.cassandraSettings.ttl > 0)
        mySensorDataStore->setTTL(settings.cassandraSettings.ttl);
433

434
435
436
      /*
       * Start the MQTT Message Server.
       */
437
      SimpleMQTTServer ms(listenHost, listenPort, settings.messageThreads, settings.messageSlots);
438
      
439
440
441
      ms.setMessageCallback(mqttCallback);
      ms.start();

Alessio Netti's avatar
Logging    
Alessio Netti committed
442
      LOG(info) << "MQTT Server running...";
443
      
444
445
446
447
448
449
450
451
452
453
454
455
      /*
       * 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
456
      LOG(info) <<  "HTTP Server running...";
457

458
459
460
461
462
463
      /*
       * Run (hopefully) forever...
       */
      keepRunning = 1;
      timeval start, end;
      double elapsed;
464
465
466
      msgCtr = 0;
      pmsgCtr = 0;
      readingCtr = 0;
467

468
      LOG(info) << "Collect Agent running...";
469
470
      while(keepRunning) {
          gettimeofday(&start, NULL);
471
          sleep(60);
472
473
474
475
          /* 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;
476
          float publish = msgCtr?(pmsgCtr*100.0)/msgCtr:0;
477
          if (settings.statistics) {
478
              LOG(info) << "Performance: " << (readingCtr/elapsed)*1000.0 << " inserts/s, " << (msgCtr/elapsed)*1000.0 << " messages/s (" << publish << "% PUBLISH)";
479
          }
480
          msgCtr = 0;
481
          pmsgCtr = 0;
482
	  readingCtr = 0;
483
484
      }

Alessio Netti's avatar
Logging    
Alessio Netti committed
485
      LOG(info) << "Stopping...";
486
487

      ms.stop();
Alessio Netti's avatar
Logging    
Alessio Netti committed
488
      LOG(info) << "MQTT Server stopped...";
489
490
      httpServer.stop();
      httpThread.join();
Alessio Netti's avatar
Logging    
Alessio Netti committed
491
      LOG(info) << "HTTP Server stopped...";
492
      delete mySensorDataStore;
493
      delete mySensorConfig;
Axel Auweter's avatar
Axel Auweter committed
494
495
      dcdbConn->disconnect();
      delete dcdbConn;
Alessio Netti's avatar
Logging    
Alessio Netti committed
496
      LOG(info) << "Collect Agent closed. Bye bye...";
497
  }
498
  catch (const exception& e) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
499
      LOG(fatal) << "Exception: " << e.what();
500
      abrt(EXIT_FAILURE, INTERR);
501
502
  }

503
  return EXIT_SUCCESS;
504
}
505
506