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

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

37
#include <dcdb/connection.h>
38
39
#include <dcdb/sensordatastore.h>

40
#include "simplemqttserver.h"
41
#include "messaging.h"
42
#include "abrt.h"
43
#include "dcdbdaemon.h"
44

45
46
#include "sensorcache.h"

47
48
49
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

50
using namespace std;
51
52

int keepRunning;
53
bool statistics;
54
55
uint64_t msgCtr;
uint64_t pmsgCtr;
56
DCDB::SensorDataStore *mySensorDataStore;
57
DCDB::SensorCache mySensorCache;
58

59
/* Normal termination (SIGINT, CTRL+C) */
60
61
void sigHandler(int sig)
{
62
63
64
  keepRunning = 0;
}

65
66
67
68
69
70
/* Crash */
void abrtHandler(int sig)
{
  abrt(EXIT_FAILURE, SIGNAL);
}

71
72
73
74
75
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);
76
    std::ostringstream data;
77
    static httpServer_t::response_header headers[] = { { "Connection", "close" }, { "Content-Type", "text/plain" } };
78

79
80
    //try getting the latest value 
    try {
81
      uint64_t val = mySensorCache.getSensor(request.destination);
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

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

106
107
108
109
  }
};


110
111
112
113
114
void mqttCallback(SimpleMQTTMessage *msg)
{
  /*
   * Increment the msgCtr/vmsgCtr for statistics.
   */
115
  msgCtr++;
116
117
118
119
120
121
  if (msg->isPublish())
    pmsgCtr++;

  /*
   * Decode the message and put into the database.
   */
122
  if (msg->isPublish()) {
123
124
125
126
127
128
129
130
131

      uint64_t val;
      uint64_t ts;

      //In the 64 bit message case, the collect agent provides a timestamp
      if(msg->getPayloadLength()==sizeof(uint64_t)) {

          //printf("Providing timestamp...\n");
          val = *((uint64_t*)msg->getPayload());
132
          ts = Messaging::calculateTimestamp();
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
          //printf("Val = %" PRIu64 ", timestamp = %" PRIu64 "\n", val, ts);
      }

      //...otherwise it just retrieves it from the MQTT message payload.
      else if((msg->getPayloadLength()%sizeof(mqttPayload)==0) && (msg->getPayloadLength()>0)){

          //printf("Retrieving timestamp...\n");
          mqttPayload *payload = (mqttPayload*)msg->getPayload();

          val = payload->value; // payload[n].value
          ts = payload->timestamp;
          //printf("Val = %" PRIu64 ", timestamp = %" PRIu64 "\n", val, ts);
      }

      //...otherwise this message is malformed -> ignore...
      else {
          delete msg;
          return;
      }
152
153
154
155
156
157

      /*
       * Check if we can decode the message topic
       * into a valid SensorId. If successful, store
       * the record in the database.
       */
158
      DCDB::SensorId sid;
Axel Auweter's avatar
Axel Auweter committed
159
      if (sid.mqttTopicConvert(msg->getTopic())) {
160
#if 0
161
          cout << "Topic decode successful:"
162
163
164
165
166
167
168
169
170
171
172
173
              << "\nRaw: " << hex << setw(16) << setfill('0') << sid.raw[0] << " " << hex << setw(16) << setfill('0') << sid.raw[1]
              << "\ndatacenter_id: " << hex << ((sid.dl & 0xFF00000000000000) >> 56)
              << "\ncluster_id:    " << hex << ((sid.dl & 0x00FF000000000000) >> 48)
              << "\nrack_id:       " << hex << ((sid.dl & 0x0000FFFF00000000) >> 32)
              << "\nchassis_id:    " << hex << ((sid.dl & 0x00000000FF000000) >> 24)
              << "\nbic_id:        " << hex << ((sid.dl & 0x0000000000FF0000) >> 16)
              << "\nbmc_id:        " << hex << ((sid.dl & 0x000000000000FF00) >> 8)
              << "\nknc_id:        " << hex << ((sid.dl & 0x00000000000000FF))
              << "\ndevice_id:     " << hex << sid.dsid.device_id
              << "\nreserved:      " << hex << sid.dsid.rsvd
              << "\nsensor_number: " << hex << sid.dsid.sensor_number
              << "\n";
174
#endif
175
          mySensorDataStore->insert(&sid, ts, val);
176
          mySensorCache.storeSensor(sid, ts, val);
177
          //mySensorCache.dump();
178
      }
179
#if 1
180
181
182
183
      else {
          cout << "Wrong topic format: " << msg->getTopic() << "\n";
      }
#endif
184
  }
185
  delete msg;
186
187
}

188
189
190



191
192
193
194
/*
 * Print usage information
 */
void usage() {
195
  printf("Usage: collectagent [-D] [-s] [-l <host>] [-h <host>] [-t <ttl>]\n");
196
  printf("Collectagent will accept remote connections by listening to the\n");
197
198
  printf("specified listen address (-l <host>) at port 1883 (default MQTT port).\n");
  printf("It will also connect to cassandra to the specifiec addres (-h <host>).\n");
199
  printf("The default <host> is localhost/127.0.0.1.\n");
200
201
  printf("If the -t option is specified, data will be inserted with the specified\n");
  printf("TTL in seconds.\n");
202
203
  printf("If the -D option is specified, CollectAgent will run as daemon.\n");
  printf("With the -s option, CollectAgent will print message statistics.\n\n");
204
205
206
}

int main(int argc, char* const argv[]) {
207
208

  try{
209
      /*
210
       * Catch SIGINT signals to allow for proper server shutdowns.
211
       */
212
      signal(SIGINT, sigHandler);
213

214
215
216
217
218
219
220
      /*
       * Catch critical signals to allow for backtraces
       */
      signal(SIGABRT, abrtHandler);
      signal(SIGSEGV, abrtHandler);
      signal(SIGTERM, abrtHandler);

221
      /* Parse command line */
222
      int ret;
223
224
      std::string listenHost, cassandraHost, restApiHost, ttl;
      std::string listenPort, cassandraPort, restApiPort;
225
226
      listenHost="localhost";
      cassandraHost="127.0.0.1";
227
      restApiHost="0.0.0.0";
228
      ttl="0";
229
      statistics = false;
230
      while ((ret=getopt(argc, argv, "h:l:r:t:Ds?"))!=-1) {
231
          switch(ret) {
232
              case 'h':
233
234
235
236
                  cassandraHost = optarg;
                  break;
              case 'l':
                  listenHost = optarg;
237
                  break;
238
239
240
              case 'r':
                  restApiHost = optarg;
                  break;
241
242
243
              case 't':
                  ttl = optarg;
                  break;
244
              case 'D':
245
                  dcdbdaemon();
246
                  break;
247
248
249
              case 's':
                  statistics = true;
                  break;
250
251
252
253
              case '?':
              default:
                  usage();
                  exit(EXIT_FAILURE);
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
      /*
       * Parse hostnames for port specifications
       */
      size_t pos = listenHost.find(":");
      if (pos != string::npos) {
        listenPort = listenHost.substr(pos+1);
        listenHost.erase(pos);
      } else {
        listenPort = "1883";
      }
      pos = cassandraHost.find(":");
      if (pos != string::npos) {
        cassandraPort = cassandraHost.substr(pos+1);
        cassandraHost.erase(pos);
      } else {
        cassandraPort = "9042";
      }
      pos = restApiHost.find(":");
      if (pos != string::npos) {
        restApiPort = restApiHost.substr(pos+1);
        restApiHost.erase(pos);
      } else {
        restApiPort = "8080";
      }


283
      /*
284
285
       * Allocate and initialize connection to Cassandra.
       */
286
      DCDB::Connection* dcdbConn;
287
      dcdbConn = new DCDB::Connection(cassandraHost, atoi(cassandraPort.c_str()));
288

Axel Auweter's avatar
Axel Auweter committed
289
      if (!dcdbConn->connect()) {
290
291
292
293
294
295
296
          std::cout << "Cannot connect to Cassandra!" << std::endl;
          exit(EXIT_FAILURE);
      }

      /*
       * Legacy behavior: Initialize the DCDB schema in Cassandra.
       */
Axel Auweter's avatar
Axel Auweter committed
297
      dcdbConn->initSchema();
298
299
300
301

      /*
       * Allocate the SensorDataStore.
       */
302
      mySensorDataStore = new DCDB::SensorDataStore(dcdbConn);
303
304
305

      /*
       * Set TTL for data store inserts if TTL > 0.
306
       */
307
308
309
310
311
312
      uint64_t ttlInt;
      std::istringstream ttlParser(ttl);
      if (!(ttlParser >> ttlInt)) {
          std::cout << "Invalid TTL!" << std::endl;
          exit(EXIT_FAILURE);
      }
313
314
315
      if (ttlInt) {
        mySensorDataStore->setTTL(ttlInt);
      }
316

317
318
319
      /*
       * Start the MQTT Message Server.
       */
320
      SimpleMQTTServer ms(listenHost, listenPort);
321
      
322
323
324
      ms.setMessageCallback(mqttCallback);
      ms.start();

325
326
      cout << "MQTT Server running..." << std::endl;
      
327
328
329
330
331
332
333
334
335
336
337
338
339
340
      /*
       * 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(); });

      cout << "HTTP Server running..." << std::endl;

341
342
343
344
345
346
      /*
       * Run (hopefully) forever...
       */
      keepRunning = 1;
      timeval start, end;
      double elapsed;
347
348
      
      cout << "Collect Agent running..." << std::endl;
349

350
351
      while(keepRunning) {
          gettimeofday(&start, NULL);
352
          sleep(60);
353
354
355
356
          /* 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;
357
          float publish = msgCtr?(pmsgCtr*100.0)/msgCtr:0;
358
359
360
          if (statistics) {
              cout << "Message rate: " << (msgCtr/elapsed)*1000.0 << " messages/second (" << publish << "% PUBLISH)\n";
          }
361
          msgCtr = 0;
362
          pmsgCtr = 0;
363
364
      }

365
      cout << "Stopping...\n";
366
367

      ms.stop();
368
      cout << "MQTT Server stopped..." << std::endl;
369
370
      httpServer.stop();
      httpThread.join();
371
      cout << "HTTP Server stopped..." << std::endl;
372
      delete mySensorDataStore;
Axel Auweter's avatar
Axel Auweter committed
373
374
      dcdbConn->disconnect();
      delete dcdbConn;
375
      cout << "Collect Agent closed. Bye bye..." << std::endl;
376
  }
377
378
  catch (const exception& e) {
      cout << "Exception: " << e.what() << "\n";
379
      abrt(EXIT_FAILURE, INTERR);
380
381
  }

382
  return EXIT_SUCCESS;
383
}
384
385