collectagent.cpp 7.2 KB
Newer Older
1
2
3
4
5
//============================================================================
// Name        : CollectAgent.cpp
// Author      : Axel Auweter
// Version     :
// Copyright   : Leibniz Supercomputing Centre
6
// Description : Main code of the CollectAgent
7
8
//============================================================================

9
#include <cstdlib>
10
#include <signal.h>
11
12
#include <unistd.h>
#include <string>
13

14
#include <boost/date_time/posix_time/posix_time.hpp>
15

16
#include <dcdb/connection.h>
17
18
#include <dcdb/sensordatastore.h>

19
#include "simplemqttserver.h"
20
#include "messaging.h"
21
#include "abrt.h"
22
#include "dcdbdaemon.h"
23

24
25
26
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

27
using namespace std;
28
29

int keepRunning;
30
31
uint64_t msgCtr;
uint64_t pmsgCtr;
32
SensorDataStore *mySensorDataStore;
33
std::string listenHost, cassandraHost, ttl;
34

35
/* Normal termination (SIGINT, CTRL+C) */
36
37
void sigHandler(int sig)
{
38
39
40
  keepRunning = 0;
}

41
42
43
44
45
46
/* Crash */
void abrtHandler(int sig)
{
  abrt(EXIT_FAILURE, SIGNAL);
}

47
48
49
50
51
void mqttCallback(SimpleMQTTMessage *msg)
{
  /*
   * Increment the msgCtr/vmsgCtr for statistics.
   */
52
  msgCtr++;
53
54
55
56
57
58
  if (msg->isPublish())
    pmsgCtr++;

  /*
   * Decode the message and put into the database.
   */
59
  if (msg->isPublish()) {
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

      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;
      }
89
90
91
92
93
94
95

      /*
       * Check if we can decode the message topic
       * into a valid SensorId. If successful, store
       * the record in the database.
       */
      SensorId sid;
Axel Auweter's avatar
Axel Auweter committed
96
      if (sid.mqttTopicConvert(msg->getTopic())) {
97
#if 0
98
          cout << "Topic decode successful:"
99
100
101
102
103
104
105
106
107
108
109
110
              << "\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";
111
#endif
112
          mySensorDataStore->insert(&sid, ts, val);
113
      }
114
#if 1
115
116
117
118
      else {
          cout << "Wrong topic format: " << msg->getTopic() << "\n";
      }
#endif
119
  }
120
  delete msg;
121
122
}

123
124
125
126
/*
 * Print usage information
 */
void usage() {
127
  printf("Usage: collectagent [-D] [-l <host>] [-h <host>] [-t <ttl>]\n");
128
  printf("Collectagent will accept remote connections by listening to the\n");
129
130
  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");
131
  printf("The default <host> is localhost/127.0.0.1.\n");
132
133
  printf("If the -t option is specified, data will be inserted with the specified\n");
  printf("TTL in seconds.\n");
134
  printf("If the -D option is specified, CollectAgent will run as daemon.\n\n");
135
136
137
}

int main(int argc, char* const argv[]) {
138
139

  try{
140
      /*
141
       * Catch SIGINT signals to allow for proper server shutdowns.
142
       */
143
      signal(SIGINT, sigHandler);
144

145
146
147
148
149
150
151
      /*
       * Catch critical signals to allow for backtraces
       */
      signal(SIGABRT, abrtHandler);
      signal(SIGSEGV, abrtHandler);
      signal(SIGTERM, abrtHandler);

152
      /* Parse command line */
153
      int ret;
154
155
      listenHost="localhost";
      cassandraHost="127.0.0.1";
156
157
      ttl="0";
      while ((ret=getopt(argc, argv, "h:l:t:D?"))!=-1) {
158
          switch(ret) {
159
              case 'h':
160
161
162
163
                  cassandraHost = optarg;
                  break;
              case 'l':
                  listenHost = optarg;
164
                  break;
165
166
167
              case 't':
                  ttl = optarg;
                  break;
168
              case 'D':
169
                  dcdbdaemon();
170
                  break;
171
172
173
174
              case '?':
              default:
                  usage();
                  exit(EXIT_FAILURE);
175
176
177
          }
      }

178
      /*
179
180
       * Allocate and initialize connection to Cassandra.
       */
Axel Auweter's avatar
Axel Auweter committed
181
182
183
      std::string sdHost = cassandraHost;
      DCDBConnection* dcdbConn;
      dcdbConn = new DCDBConnection(sdHost, 9042);
184

Axel Auweter's avatar
Axel Auweter committed
185
      if (!dcdbConn->connect()) {
186
187
188
189
190
191
192
          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
193
      dcdbConn->initSchema();
194
195
196
197

      /*
       * Allocate the SensorDataStore.
       */
Axel Auweter's avatar
Axel Auweter committed
198
      mySensorDataStore = new SensorDataStore(dcdbConn);
199
200
201

      /*
       * Set TTL for data store inserts if TTL > 0.
202
       */
203
204
205
206
207
208
      uint64_t ttlInt;
      std::istringstream ttlParser(ttl);
      if (!(ttlParser >> ttlInt)) {
          std::cout << "Invalid TTL!" << std::endl;
          exit(EXIT_FAILURE);
      }
209
210
211
      if (ttlInt) {
        mySensorDataStore->setTTL(ttlInt);
      }
212

213
214
215
      /*
       * Start the MQTT Message Server.
       */
216
      SimpleMQTTServer ms(listenHost,"1883");
217
      
218
219
220
221
222
      ms.setMessageCallback(mqttCallback);
      ms.start();

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

223
224
225
226
227
228
229
      /*
       * Run (hopefully) forever...
       */
      keepRunning = 1;
      timeval start, end;
      double elapsed;

230
231
      while(keepRunning) {
          gettimeofday(&start, NULL);
232
          sleep(60);
233
234
235
236
          /* 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;
237
238
          float publish = msgCtr?(pmsgCtr*100.0)/msgCtr:0;
          cout << "Message rate: " << (msgCtr/elapsed)*1000.0 << " messages/second (" << publish << "% PUBLISH)\n";
239
          msgCtr = 0;
240
          pmsgCtr = 0;
241
242
      }

243
      cout << "Stopping...\n";
244
245

      ms.stop();
246
      delete mySensorDataStore;
Axel Auweter's avatar
Axel Auweter committed
247
248
      dcdbConn->disconnect();
      delete dcdbConn;
249
  }
250
251
  catch (const exception& e) {
      cout << "Exception: " << e.what() << "\n";
252
      abrt(EXIT_FAILURE, INTERR);
253
254
  }

255
  return EXIT_SUCCESS;
256
}
257
258