collectagent.cpp 12.2 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
40
#include <dcdb/sensordatastore.h>

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

46
47
#include "sensorcache.h"

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

51
using namespace std;
52
53

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

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

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

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

80
81
    //try getting the latest value 
    try {
82
83
84
85
86
87
      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());

      uint64_t val = mySensorCache.getSensor(uri.path(), (uint64_t) avg);
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

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

112
113
114
115
  }
};


116
117
118
119
120
void mqttCallback(SimpleMQTTMessage *msg)
{
  /*
   * Increment the msgCtr/vmsgCtr for statistics.
   */
121
  msgCtr++;
122
123
124
125
126
127
  if (msg->isPublish())
    pmsgCtr++;

  /*
   * Decode the message and put into the database.
   */
128
  if (msg->isPublish()) {
129
130
131
132
133
134
135
136
137

      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());
138
          ts = Messaging::calculateTimestamp();
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
          //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;
      }
158
159
160
161
162
163

      /*
       * Check if we can decode the message topic
       * into a valid SensorId. If successful, store
       * the record in the database.
       */
164
      DCDB::SensorId sid;
Axel Auweter's avatar
Axel Auweter committed
165
      if (sid.mqttTopicConvert(msg->getTopic())) {
166
#if 0
167
          cout << "Topic decode successful:"
168
169
170
171
172
173
174
175
176
177
178
179
              << "\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";
180
#endif
181
          mySensorDataStore->insert(&sid, ts, val);
182
          mySensorCache.storeSensor(sid, ts, val);
183
          //mySensorCache.dump();
184
      }
185
#if 1
186
187
188
189
      else {
          cout << "Wrong topic format: " << msg->getTopic() << "\n";
      }
#endif
190
  }
191
  delete msg;
192
193
}

194
195
196



197
198
199
200
/*
 * Print usage information
 */
void usage() {
201
  printf("Usage: collectagent [-D] [-s] [-l <host>] [-h <host>] [-t <ttl>]\n");
202
  printf("Collectagent will accept remote connections by listening to the\n");
203
204
  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");
205
  printf("The default <host> is localhost/127.0.0.1.\n");
206
207
  printf("If the -t option is specified, data will be inserted with the specified\n");
  printf("TTL in seconds.\n");
208
209
  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");
210
211
212
}

int main(int argc, char* const argv[]) {
213
214

  try{
215
      /*
216
       * Catch SIGINT signals to allow for proper server shutdowns.
217
       */
218
      signal(SIGINT, sigHandler);
219

220
221
222
223
224
225
226
      /*
       * Catch critical signals to allow for backtraces
       */
      signal(SIGABRT, abrtHandler);
      signal(SIGSEGV, abrtHandler);
      signal(SIGTERM, abrtHandler);

227
      /* Parse command line */
228
      int ret;
229
230
      std::string listenHost, cassandraHost, restApiHost, ttl;
      std::string listenPort, cassandraPort, restApiPort;
231
232
      listenHost="localhost";
      cassandraHost="127.0.0.1";
233
      restApiHost="0.0.0.0";
234
      ttl="0";
235
      statistics = false;
236
      while ((ret=getopt(argc, argv, "h:l:r:t:Ds?"))!=-1) {
237
          switch(ret) {
238
              case 'h':
239
240
241
242
                  cassandraHost = optarg;
                  break;
              case 'l':
                  listenHost = optarg;
243
                  break;
244
245
246
              case 'r':
                  restApiHost = optarg;
                  break;
247
248
249
              case 't':
                  ttl = optarg;
                  break;
250
              case 'D':
251
                  dcdbdaemon();
252
                  break;
253
254
255
              case 's':
                  statistics = true;
                  break;
256
257
258
259
              case '?':
              default:
                  usage();
                  exit(EXIT_FAILURE);
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
      /*
       * 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";
      }


289
      /*
290
291
       * Allocate and initialize connection to Cassandra.
       */
292
      DCDB::Connection* dcdbConn;
293
      dcdbConn = new DCDB::Connection(cassandraHost, atoi(cassandraPort.c_str()));
294

Axel Auweter's avatar
Axel Auweter committed
295
      if (!dcdbConn->connect()) {
296
297
298
299
300
301
302
          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
303
      dcdbConn->initSchema();
304
305
306
307

      /*
       * Allocate the SensorDataStore.
       */
308
      mySensorDataStore = new DCDB::SensorDataStore(dcdbConn);
309
310
311

      /*
       * Set TTL for data store inserts if TTL > 0.
312
       */
313
314
315
316
317
318
      uint64_t ttlInt;
      std::istringstream ttlParser(ttl);
      if (!(ttlParser >> ttlInt)) {
          std::cout << "Invalid TTL!" << std::endl;
          exit(EXIT_FAILURE);
      }
319
320
321
      if (ttlInt) {
        mySensorDataStore->setTTL(ttlInt);
      }
322

323
324
325
      /*
       * Start the MQTT Message Server.
       */
326
      SimpleMQTTServer ms(listenHost, listenPort);
327
      
328
329
330
      ms.setMessageCallback(mqttCallback);
      ms.start();

331
332
      cout << "MQTT Server running..." << std::endl;
      
333
334
335
336
337
338
339
340
341
342
343
344
345
346
      /*
       * 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;

347
348
349
350
351
352
      /*
       * Run (hopefully) forever...
       */
      keepRunning = 1;
      timeval start, end;
      double elapsed;
353
354
      
      cout << "Collect Agent running..." << std::endl;
355

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

371
      cout << "Stopping...\n";
372
373

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

388
  return EXIT_SUCCESS;
389
}
390
391