collectagent.cpp 11.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
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
std::string listenHost, cassandraHost, ttl;
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
77
78
79
80
81
82
83
84
85
86
87
88
89
namespace http = boost::network::http;

/*<< Defines the server. >>*/
struct http_handler;
typedef http::server<http_handler> server;

/*<< Defines the request handler.  It's a class that defines two
     functions, `operator()` and `log()` >>*/
struct http_handler {
	
	/*<< This is the function that handles the incoming request. >>*/
    void operator()(server::request const &request, server::connection_ptr connection) {
    server::string_type ip = source(request);
    
    DCDB::SensorId sid;
    sid.mqttTopicConvert(request.destination);
    std::ostringstream data;
    
90
    static server::response_header headers[] = {{"Connection", "close"}, {"Content-Type", "text/plain"}};
91
92
93
94
95
    //try getting the latest value 
    try {
		
		uint64_t val = mySensorCache.getSensor(sid);
		
96
		data << val << "\n";
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
		//data << "Sid : " << sid.toString() << ", Value: " << val << "." << std::endl;
    
		connection->set_status(server::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(server::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(server::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(server::connection::internal_server_error);
		connection->set_headers(boost::make_iterator_range(headers, headers + 2));
		connection->write("Server error.\n");
	}
    
  }
};


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

  /*
   * Decode the message and put into the database.
   */
137
  if (msg->isPublish()) {
138
139
140
141
142
143
144
145
146

      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());
147
          ts = Messaging::calculateTimestamp();
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
          //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;
      }
167
168
169
170
171
172

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

203
204
205



206
207
208
209
/*
 * Print usage information
 */
void usage() {
210
  printf("Usage: collectagent [-D] [-s] [-l <host>] [-h <host>] [-t <ttl>]\n");
211
  printf("Collectagent will accept remote connections by listening to the\n");
212
213
  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");
214
  printf("The default <host> is localhost/127.0.0.1.\n");
215
216
  printf("If the -t option is specified, data will be inserted with the specified\n");
  printf("TTL in seconds.\n");
217
218
  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");
219
220
221
}

int main(int argc, char* const argv[]) {
222
223

  try{
224
      /*
225
       * Catch SIGINT signals to allow for proper server shutdowns.
226
       */
227
      signal(SIGINT, sigHandler);
228

229
230
231
232
233
234
235
      /*
       * Catch critical signals to allow for backtraces
       */
      signal(SIGABRT, abrtHandler);
      signal(SIGSEGV, abrtHandler);
      signal(SIGTERM, abrtHandler);

236
      /* Parse command line */
237
      int ret;
238
239
      listenHost="localhost";
      cassandraHost="127.0.0.1";
240
      ttl="0";
241
242
      statistics = false;
      while ((ret=getopt(argc, argv, "h:l:t:Ds?"))!=-1) {
243
          switch(ret) {
244
              case 'h':
245
246
247
248
                  cassandraHost = optarg;
                  break;
              case 'l':
                  listenHost = optarg;
249
                  break;
250
251
252
              case 't':
                  ttl = optarg;
                  break;
253
              case 'D':
254
                  dcdbdaemon();
255
                  break;
256
257
258
              case 's':
                  statistics = true;
                  break;
259
260
261
262
              case '?':
              default:
                  usage();
                  exit(EXIT_FAILURE);
263
264
265
          }
      }

266
      /*
267
268
       * Allocate and initialize connection to Cassandra.
       */
Axel Auweter's avatar
Axel Auweter committed
269
      std::string sdHost = cassandraHost;
270
271
      DCDB::Connection* dcdbConn;
      dcdbConn = new DCDB::Connection(sdHost, 9042);
272

Axel Auweter's avatar
Axel Auweter committed
273
      if (!dcdbConn->connect()) {
274
275
276
277
278
279
280
          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
281
      dcdbConn->initSchema();
282
283
284
285

      /*
       * Allocate the SensorDataStore.
       */
286
      mySensorDataStore = new DCDB::SensorDataStore(dcdbConn);
287
288
289

      /*
       * Set TTL for data store inserts if TTL > 0.
290
       */
291
292
293
294
295
296
      uint64_t ttlInt;
      std::istringstream ttlParser(ttl);
      if (!(ttlParser >> ttlInt)) {
          std::cout << "Invalid TTL!" << std::endl;
          exit(EXIT_FAILURE);
      }
297
298
299
      if (ttlInt) {
        mySensorDataStore->setTTL(ttlInt);
      }
300

301
302
303
      /*
       * Start the MQTT Message Server.
       */
304
      SimpleMQTTServer ms(listenHost,"1883");
305
      
306
307
308
      ms.setMessageCallback(mqttCallback);
      ms.start();

309
310
311
312
313
314
315
316
      cout << "MQTT Server running..." << std::endl;
      std::thread t1;
      
	  /*<< Creates the request handler. >>*/
	  http_handler handler;

	  /*<< Creates the server. >>*/		
	  server::options options(handler);
317
	  options.reuse_address(true);
318
319
320
321
322
323
324
325

	  options.thread_pool(std::make_shared<boost::network::utils::thread_pool>());
	  server server_(options.address("127.0.0.1").port("8080"));
		
	  /*<< Runs the server. >>*/
	  t1 = std::thread([&server_] { server_.run(); });
  
	  cout << "HTTP Server running..." << std::endl;
326
327
328
329
330
331
      /*
       * Run (hopefully) forever...
       */
      keepRunning = 1;
      timeval start, end;
      double elapsed;
332
333
      
      cout << "Collect Agent running..." << std::endl;
334

335
336
      while(keepRunning) {
          gettimeofday(&start, NULL);
337
          sleep(60);
338
339
340
341
          /* 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;
342
          float publish = msgCtr?(pmsgCtr*100.0)/msgCtr:0;
343
344
345
          if (statistics) {
              cout << "Message rate: " << (msgCtr/elapsed)*1000.0 << " messages/second (" << publish << "% PUBLISH)\n";
          }
346
          msgCtr = 0;
347
          pmsgCtr = 0;
348
349
      }

350
      cout << "Stopping...\n";
351
352

      ms.stop();
353
354
355
356
      cout << "MQTT Server stopped..." << std::endl;
      server_.stop();
      t1.join();
      cout << "HTTP Server stopped..." << std::endl;
357
      delete mySensorDataStore;
Axel Auweter's avatar
Axel Auweter committed
358
359
      dcdbConn->disconnect();
      delete dcdbConn;
360
      cout << "Collect Agent closed. Bye bye..." << std::endl;
361
  }
362
363
  catch (const exception& e) {
      cout << "Exception: " << e.what() << "\n";
364
      abrt(EXIT_FAILURE, INTERR);
365
366
  }

367
  return EXIT_SUCCESS;
368
}
369
370