CollectAgent.cpp 8.34 KB
Newer Older
1
2
3
4
5
6
7
8
//============================================================================
// Name        : CollectAgent.cpp
// Author      : Axel Auweter
// Version     :
// Copyright   : Leibniz Supercomputing Centre
// Description : As of now this is some rudimentary bad code to talk to the DB
//============================================================================

9
10
11
12
#include <cstdio>
#include <cstdlib>

#include <sstream>
13
14
15

#include <sys/socket.h>
#include <netinet/in.h>
16
#include <signal.h>
17
18
#include <sys/time.h>

19

20
21
22
23
24
25
26
#include <thrift/Thrift.h>
#include <thrift/transport/TTransport.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TSocket.h>
#include <thrift/protocol/TProtocol.h>
#include <thrift/protocol/TBinaryProtocol.h>

27
#include "cassandra/Cassandra.h"
28

29
30
#include "mosquitto.h"

31
32
33
34
35
using namespace apache::thrift;
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
using namespace org::apache::cassandra;

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
CassandraClient *myClient;

int keepRunning;
int msgCtr;

void sigHandler(int sig) {
  keepRunning = 0;
}

void mqttOnMessage(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) {
  msgCtr++;
  try {
      CqlResult res;
      std::string query;
      std::stringstream datestr, sidstr;
      time_t t = time(NULL);
      struct tm *now = localtime(&t);

      datestr << "'" << (now->tm_year + 1900) << "-" << (now->tm_mon + 1)
            << "-" << (now->tm_mday) << " " << (now->tm_hour) << ":"
            << (now->tm_min) << ":" << (now->tm_sec) << "'";
      sidstr << msgCtr;

      query = "INSERT INTO sensordata (sid, ts, value) VALUES ( " + sidstr.str() + ", " + datestr.str() + ", 3.141 );";
      myClient->execute_cql3_query(res, query, Compression::NONE, ConsistencyLevel::ONE);
  }
  catch(TTransportException te){
      printf("TP Exception: %s  [%d]\n", te.what(), te.getType());
  }catch(InvalidRequestException ire){
      printf("IRE Exception: %s  [%s]\n", ire.what(), ire.why.c_str());
  }catch(NotFoundException nfe){
      printf("NF Exception: %s\n", nfe.what());
  }
}


72
73
74
75
76
77
78
79
80
81
82
83
int main(void) {
  boost::shared_ptr<TSocket> sock;
  boost::shared_ptr<TTransport> tr;
  boost::shared_ptr<TProtocol> prot;

  std::string clusterName;

  sock = boost::shared_ptr<TSocket>(new TSocket("localhost", 9160));
  tr = boost::shared_ptr<TFramedTransport>(new TFramedTransport(sock));
  prot = boost::shared_ptr<TBinaryProtocol>(new TBinaryProtocol(tr));

  try {
84
      myClient = new CassandraClient(prot);
85
      tr->open();
86
87
88

    start:
      myClient->describe_cluster_name(clusterName);
89
90
      printf("Cluster name: %s\n", clusterName.c_str());

91
92

      int dcdbKeyspace = -1;
93
94
      printf("Keyspaces:\n");
      std::vector<KsDef> keySpaces;
95
      myClient->describe_keyspaces(keySpaces);
96
      for (unsigned int i=0; i<keySpaces.size(); i++) {
97
          printf("   [%d]: %s\n", i, keySpaces[i].name.c_str());
98
99
100
          if(keySpaces[i].name == "dcdb") {
              dcdbKeyspace = i;
          }
101
102
103
      }

      CqlResult res;
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
      std::string query;

      if (dcdbKeyspace<0) {
          printf("Creating dcdb keyspace...\n");
          query = "CREATE KEYSPACE dcdb WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '1'};";
          printf("Sending CQL statement: %s", query.c_str());
          myClient->execute_cql3_query(res, query, Compression::NONE, ConsistencyLevel::ONE);
          printf("  --> Success!\n");
          printf("Starting over...\n\n");
          goto start;
      }
      else {
          printf("Using existing keyspace dcdb...\n");
      }

      query = "USE dcdb;";
      printf("Sending CQL statement: %s", query.c_str());
      myClient->execute_cql3_query(res, query, Compression::NONE, ConsistencyLevel::ONE);
      printf("  --> Success!\n");

      int sensordataCf = -1;
      printf("Column families in dcdb:\n");
126
      for (unsigned int i=0; i<keySpaces[dcdbKeyspace].cf_defs.size(); i++) {
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
          printf("   [%d]: %s\n", i, keySpaces[dcdbKeyspace].cf_defs[i].name.c_str());
          if (keySpaces[dcdbKeyspace].cf_defs[i].name == "sensordata") {
              sensordataCf = i;
          }
      }

      if (sensordataCf<0) {
          printf("Creating sensordata column familiy...\n");
          query = "CREATE TABLE sensordata ( sid int, ts timestamp, value float, PRIMARY KEY (sid, ts)) WITH COMPACT STORAGE;";
          printf("Sending CQL statement: %s", query.c_str());
          myClient->execute_cql3_query(res, query, Compression::NONE, ConsistencyLevel::ONE);
          printf("  --> Success!\n");
          printf("Starting over...\n\n");
          goto start;
      }
      else {
          printf("Using existing sensordata column familiy.\n");
      }

      /* Should have the keyspace and the column familiy in the system now, subscribe to local mqtt broker */
      int mosqMajor, mosqMinor, mosqRevision;
      mosquitto_lib_version(&mosqMajor, &mosqMinor, &mosqRevision);
      printf("Initializing Mosquitto Library Version %d.%d.%d\n", mosqMajor, mosqMinor, mosqRevision);
      mosquitto_lib_init();

      /* Init mosquitto struct */
      struct mosquitto* mosq;
      mosq = mosquitto_new("CollectAgent", false, NULL);
      if (!mosq) {
          perror(NULL);
          exit(EXIT_FAILURE);
      }

      /* Connect to the broker */
      printf("Connecting to broker...");
      fflush(stdout);
      if (mosquitto_connect(mosq, "localhost", 1883, 1000) != MOSQ_ERR_SUCCESS) {
          perror("\nCould not connect to host");
          exit(EXIT_FAILURE);
      }
      printf(" Done.\n");

      /* Catch SIGINT signals */
      signal(SIGINT, sigHandler);

      /* Subscribe to anything */
      printf("Subscribing to anything on the broker (Pattern #)...");
      fflush(stdout);
      if (mosquitto_subscribe(mosq, NULL, "#", 0) != MOSQ_ERR_SUCCESS) {
          perror("\nCould not subscribe");
          exit(EXIT_FAILURE);
      }
      printf(" Done.\n");

      /* Set the callback for mosquitto */
      printf("Configuring message callback...");
      fflush(stdout);
      mosquitto_message_callback_set(mosq, mqttOnMessage);
      printf(" Done.\n");

      /* Here comes the main loop */
      printf("Starting mqtt loop thread...");
      fflush(stdout);
      if (mosquitto_loop_start(mosq) != MOSQ_ERR_SUCCESS) {
          perror("\nCould not start mosquitto thread");
          exit(EXIT_FAILURE);
      }
      printf(" Done.\n");

      keepRunning = 1;
      timeval start, end;
      double elapsed;

      while(keepRunning) {
          gettimeofday(&start, NULL);
          sleep(10);
          /* 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;
          printf("Message rate: %f messages/second\n", (msgCtr/elapsed)*1000.0);
          msgCtr = 0;
      }

      printf("Cleaning up...");

      /* Stop the mosquitto loop */
      mosquitto_loop_stop(mosq, true);
      mosquitto_disconnect(mosq);

      /* Disconnect from Cassandra */
      tr->close();

220
221
      printf(" Done.\n");

222
#if 0
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
      int resB = 0;
      while (resB < keySpaces[0].cf_defs.size()) {
          query = "SELECT * FROM " + keySpaces[0].cf_defs[resB].name + ";";
          printf("Sending CQL statement: %s...", query.c_str());
          myClient.execute_cql3_query(res, query, Compression::NONE, ConsistencyLevel::ONE);
          printf(" Done.\nResult:\n");
          int resC = 0;
          while (resC < res.rows.size()) {
              int resD = 0;
              while (resD < res.rows[resC].columns.size()) {
                  printf("%s [%lu]:", res.rows[resC].columns[resD].name.c_str(),
                      res.rows[resC].columns[resD].value.length());
                  int resE = 0;
                  while (resE < res.rows[resC].columns[resD].value.length()) {
                      printf(" %02x", res.rows[resC].columns[resD].value.c_str()[resE] & 0xff);
                      resE++;
                  }
                  printf("\n");
                  resD++;
              }
              resC++;
          }
          resB++;
      }
247
#endif
248
249
250
251
252
253
254
255
256
257
  }
  catch(TTransportException te){
      printf("TP Exception: %s  [%d]\n", te.what(), te.getType());
  }catch(InvalidRequestException ire){
      printf("IRE Exception: %s  [%s]\n", ire.what(), ire.why.c_str());
  }catch(NotFoundException nfe){
      printf("NF Exception: %s\n", nfe.what());
  }
  return EXIT_SUCCESS;
}