collectagent.cpp 12 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
      mqttPayload buf, *payload;
      uint64_t len;
131

132
      len = msg->getPayloadLength();
133
      //In the 64 bit message case, the collect agent provides a timestamp
134
135
136
137
      if (len == sizeof(uint64_t)) {
        payload = &buf;
        payload->value = *((uint64_t*)msg->getPayload());
        payload->timestamp = Messaging::calculateTimestamp();
138
        len = sizeof(uint64_t) * 2;
139
140
      }
      //...otherwise it just retrieves it from the MQTT message payload.
141
142
      else if((len%sizeof(mqttPayload)==0) && (len>0)){
          payload = (mqttPayload*)msg->getPayload();
143
144
145
146
147
148
      }
      //...otherwise this message is malformed -> ignore...
      else {
          delete msg;
          return;
      }
149
150
151
152
153
154

      /*
       * Check if we can decode the message topic
       * into a valid SensorId. If successful, store
       * the record in the database.
       */
155
      DCDB::SensorId sid;
Axel Auweter's avatar
Axel Auweter committed
156
      if (sid.mqttTopicConvert(msg->getTopic())) {
157
#if 0
158
          cout << "Topic decode successful:"
159
160
161
162
163
164
165
166
167
168
169
170
              << "\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";
171
#endif
172
173
174
175
          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);
          }
176
          //mySensorCache.dump();
177
      }
178
#if 1
179
180
181
182
      else {
          cout << "Wrong topic format: " << msg->getTopic() << "\n";
      }
#endif
183
  }
184
  delete msg;
185
186
}

187
188
189



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

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

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

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

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


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

Axel Auweter's avatar
Axel Auweter committed
288
      if (!dcdbConn->connect()) {
289
290
291
292
293
294
295
          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
296
      dcdbConn->initSchema();
297
298
299
300

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

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

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

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

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

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

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

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

381
  return EXIT_SUCCESS;
382
}
383
384