collectagent.cpp 8.57 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
#include "sensorcache.h"

44
45
46
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

47
using namespace std;
48
49

int keepRunning;
50
bool statistics;
51
52
uint64_t msgCtr;
uint64_t pmsgCtr;
53
DCDB::SensorDataStore *mySensorDataStore;
54
std::string listenHost, cassandraHost, ttl;
55
DCDB::SensorCache mySensorCache;
56

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

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

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

  /*
   * Decode the message and put into the database.
   */
81
  if (msg->isPublish()) {
82
83
84

      uint64_t val;
      uint64_t ts;
85
      uint64_t msgTs = Messaging::calculateTimestamp();
86
87
88
89
90
91

      //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());
92
          ts = msgTs;
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
          //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;
      }
112
113
114
115
116
117

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

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

int main(int argc, char* const argv[]) {
163
164

  try{
165
      /*
166
       * Catch SIGINT signals to allow for proper server shutdowns.
167
       */
168
      signal(SIGINT, sigHandler);
169

170
171
172
173
174
175
176
      /*
       * Catch critical signals to allow for backtraces
       */
      signal(SIGABRT, abrtHandler);
      signal(SIGSEGV, abrtHandler);
      signal(SIGTERM, abrtHandler);

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

207
      /*
208
209
       * Allocate and initialize connection to Cassandra.
       */
Axel Auweter's avatar
Axel Auweter committed
210
      std::string sdHost = cassandraHost;
211
212
      DCDB::Connection* dcdbConn;
      dcdbConn = new DCDB::Connection(sdHost, 9042);
213

Axel Auweter's avatar
Axel Auweter committed
214
      if (!dcdbConn->connect()) {
215
216
217
218
219
220
221
          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
222
      dcdbConn->initSchema();
223
224
225
226

      /*
       * Allocate the SensorDataStore.
       */
227
      mySensorDataStore = new DCDB::SensorDataStore(dcdbConn);
228
229
230

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

242
243
244
      /*
       * Start the MQTT Message Server.
       */
245
      SimpleMQTTServer ms(listenHost,"1883");
246
      
247
248
249
250
251
      ms.setMessageCallback(mqttCallback);
      ms.start();

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

252
253
254
255
256
257
258
      /*
       * Run (hopefully) forever...
       */
      keepRunning = 1;
      timeval start, end;
      double elapsed;

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

274
      cout << "Stopping...\n";
275
276

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

286
  return EXIT_SUCCESS;
287
}
288
289