collectagent.cpp 8.43 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
#include <cstdlib>
28
#include <signal.h>
29
30
#include <unistd.h>
#include <string>
31

32
#include <boost/date_time/posix_time/posix_time.hpp>
33

34
#include <dcdb/connection.h>
35
36
#include <dcdb/sensordatastore.h>

37
#include "simplemqttserver.h"
38
#include "messaging.h"
39
#include "abrt.h"
40
#include "dcdbdaemon.h"
41

42
43
44
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

45
using namespace std;
46
47

int keepRunning;
48
bool statistics;
49
50
uint64_t msgCtr;
uint64_t pmsgCtr;
51
DCDB::SensorDataStore *mySensorDataStore;
52
std::string listenHost, cassandraHost, ttl;
53

54
/* Normal termination (SIGINT, CTRL+C) */
55
56
void sigHandler(int sig)
{
57
58
59
  keepRunning = 0;
}

60
61
62
63
64
65
/* Crash */
void abrtHandler(int sig)
{
  abrt(EXIT_FAILURE, SIGNAL);
}

66
67
68
69
70
void mqttCallback(SimpleMQTTMessage *msg)
{
  /*
   * Increment the msgCtr/vmsgCtr for statistics.
   */
71
  msgCtr++;
72
73
74
75
76
77
  if (msg->isPublish())
    pmsgCtr++;

  /*
   * Decode the message and put into the database.
   */
78
  if (msg->isPublish()) {
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

      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());
          ts = Messaging::calculateTimestamp();
          //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;
      }
108
109
110
111
112
113

      /*
       * Check if we can decode the message topic
       * into a valid SensorId. If successful, store
       * the record in the database.
       */
114
      DCDB::SensorId sid;
Axel Auweter's avatar
Axel Auweter committed
115
      if (sid.mqttTopicConvert(msg->getTopic())) {
116
#if 0
117
          cout << "Topic decode successful:"
118
119
120
121
122
123
124
125
126
127
128
129
              << "\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";
130
#endif
131
          mySensorDataStore->insert(&sid, ts, val);
132
      }
133
#if 1
134
135
136
137
      else {
          cout << "Wrong topic format: " << msg->getTopic() << "\n";
      }
#endif
138
  }
139
  delete msg;
140
141
}

142
143
144
145
/*
 * Print usage information
 */
void usage() {
146
  printf("Usage: collectagent [-D] [-s] [-l <host>] [-h <host>] [-t <ttl>]\n");
147
  printf("Collectagent will accept remote connections by listening to the\n");
148
149
  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");
150
  printf("The default <host> is localhost/127.0.0.1.\n");
151
152
  printf("If the -t option is specified, data will be inserted with the specified\n");
  printf("TTL in seconds.\n");
153
154
  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");
155
156
157
}

int main(int argc, char* const argv[]) {
158
159

  try{
160
      /*
161
       * Catch SIGINT signals to allow for proper server shutdowns.
162
       */
163
      signal(SIGINT, sigHandler);
164

165
166
167
168
169
170
171
      /*
       * Catch critical signals to allow for backtraces
       */
      signal(SIGABRT, abrtHandler);
      signal(SIGSEGV, abrtHandler);
      signal(SIGTERM, abrtHandler);

172
      /* Parse command line */
173
      int ret;
174
175
      listenHost="localhost";
      cassandraHost="127.0.0.1";
176
      ttl="0";
177
178
      statistics = false;
      while ((ret=getopt(argc, argv, "h:l:t:Ds?"))!=-1) {
179
          switch(ret) {
180
              case 'h':
181
182
183
184
                  cassandraHost = optarg;
                  break;
              case 'l':
                  listenHost = optarg;
185
                  break;
186
187
188
              case 't':
                  ttl = optarg;
                  break;
189
              case 'D':
190
                  dcdbdaemon();
191
                  break;
192
193
194
              case 's':
                  statistics = true;
                  break;
195
196
197
198
              case '?':
              default:
                  usage();
                  exit(EXIT_FAILURE);
199
200
201
          }
      }

202
      /*
203
204
       * Allocate and initialize connection to Cassandra.
       */
Axel Auweter's avatar
Axel Auweter committed
205
      std::string sdHost = cassandraHost;
206
207
      DCDB::Connection* dcdbConn;
      dcdbConn = new DCDB::Connection(sdHost, 9042);
208

Axel Auweter's avatar
Axel Auweter committed
209
      if (!dcdbConn->connect()) {
210
211
212
213
214
215
216
          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
217
      dcdbConn->initSchema();
218
219
220
221

      /*
       * Allocate the SensorDataStore.
       */
222
      mySensorDataStore = new DCDB::SensorDataStore(dcdbConn);
223
224
225

      /*
       * Set TTL for data store inserts if TTL > 0.
226
       */
227
228
229
230
231
232
      uint64_t ttlInt;
      std::istringstream ttlParser(ttl);
      if (!(ttlParser >> ttlInt)) {
          std::cout << "Invalid TTL!" << std::endl;
          exit(EXIT_FAILURE);
      }
233
234
235
      if (ttlInt) {
        mySensorDataStore->setTTL(ttlInt);
      }
236

237
238
239
      /*
       * Start the MQTT Message Server.
       */
240
      SimpleMQTTServer ms(listenHost,"1883");
241
      
242
243
244
245
246
      ms.setMessageCallback(mqttCallback);
      ms.start();

      cout << "Server running...\n";

247
248
249
250
251
252
253
      /*
       * Run (hopefully) forever...
       */
      keepRunning = 1;
      timeval start, end;
      double elapsed;

254
255
      while(keepRunning) {
          gettimeofday(&start, NULL);
256
          sleep(60);
257
258
259
260
          /* 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;
261
          float publish = msgCtr?(pmsgCtr*100.0)/msgCtr:0;
262
263
264
          if (statistics) {
              cout << "Message rate: " << (msgCtr/elapsed)*1000.0 << " messages/second (" << publish << "% PUBLISH)\n";
          }
265
          msgCtr = 0;
266
          pmsgCtr = 0;
267
268
      }

269
      cout << "Stopping...\n";
270
271

      ms.stop();
272
      delete mySensorDataStore;
Axel Auweter's avatar
Axel Auweter committed
273
274
      dcdbConn->disconnect();
      delete dcdbConn;
275
  }
276
277
  catch (const exception& e) {
      cout << "Exception: " << e.what() << "\n";
278
      abrt(EXIT_FAILURE, INTERR);
279
280
  }

281
  return EXIT_SUCCESS;
282
}
283
284