collectagent.cpp 34.8 KB
Newer Older
1
2
//================================================================================
// Name        : collectagent.cpp
3
// Author      : Axel Auweter
Micha Müller's avatar
Micha Müller committed
4
// Contact     : info@dcdb.it
5
// Copyright   : Leibniz Supercomputing Centre
6
// Description : Main code of the CollectAgent
7
8
9
10
//================================================================================

//================================================================================
// This file is part of DCDB (DataCenter DataBase)
11
// Copyright (C) 2011-2019 Leibniz Supercomputing Centre
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//
// 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.
//================================================================================
27

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * @defgroup ca Collect Agent
 *
 * @brief MQTT message broker in between pusher and storage backend.
 *
 * @details Collect Agent is a intermediary between one or multiple Pusher
 *          instances and one storage backend. It runs a reduced custom MQTT
 *          message server. Collect Agent receives data from Pusher
 *          via MQTT messages and stores them in the storage via libdcdb.
 */

/**
 * @file collectagent.cpp
 *
 * @brief Main function for the DCDB Collect Agent.
 *
 * @ingroup ca
 */

47
#include <cstdlib>
48
#include <signal.h>
49
50
#include <unistd.h>
#include <string>
51

52
#include <boost/date_time/posix_time/posix_time.hpp>
Micha Müller's avatar
Micha Müller committed
53
54
55
#include <boost/foreach.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
56

57
#include <dcdb/connection.h>
58
#include <dcdb/sensordatastore.h>
Alessio Netti's avatar
Alessio Netti committed
59
#include <dcdb/jobdatastore.h>
60
#include <dcdb/calievtdatastore.h>
61
#include <dcdb/sensorconfig.h>
62
#include <dcdb/version.h>
63
#include <dcdb/sensor.h>
64
#include "version.h"
65

66
#include "CARestAPI.h"
67
#include "configuration.h"
68
#include "simplemqttserver.h"
69
#include "messaging.h"
70
#include "abrt.h"
71
#include "dcdbdaemon.h"
72
#include "sensorcache.h"
73
74
#include "analyticscontroller.h"
#include "../analytics/includes/QueryEngine.h"
75

76
77
78
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

79
80
81
82
83
84
85
/**
 * Uncomment and recompile to activate CollectAgent's special benchmark mode.
 * In this mode, all received messages will be discarded and no data is stored
 * in the storage backend.
 */
//#define BENCHMARK_MODE

86
using namespace std;
87
88

int keepRunning;
Alessio Netti's avatar
Alessio Netti committed
89
int retCode = EXIT_SUCCESS;
90
bool statistics;
91
92
uint64_t msgCtr;
uint64_t pmsgCtr;
93
uint64_t readingCtr;
Alessio Netti's avatar
Alessio Netti committed
94
SensorCache mySensorCache;
95
AnalyticsController* analyticsController;
96
DCDB::Connection* dcdbConn;
97
DCDB::SensorDataStore *mySensorDataStore;
Alessio Netti's avatar
Alessio Netti committed
98
DCDB::JobDataStore *myJobDataStore;
99
DCDB::SensorConfig *mySensorConfig;
100
DCDB::CaliEvtDataStore *myCaliEvtDataStore;
101
MetadataStore *metadataStore;
Alessio Netti's avatar
Alessio Netti committed
102
CARestAPI* httpsServer = nullptr;
103
DCDB::SCError err;
104
QueryEngine& queryEngine = QueryEngine::getInstance();
105
logger_t lg;
106

107
bool jobQueryCallback(const string& jobId, const uint64_t startTs, const uint64_t endTs, vector<qeJobData>& buffer, const bool rel, const bool range) {
Alessio Netti's avatar
Alessio Netti committed
108
109
110
111
112
113
114
115
116
117
    std::list<JobData> tempList;
    JobData   tempData;
    qeJobData tempQeData;
    JDError err;
    if(range) {
        // Getting a list of jobs in the given time range
        uint64_t now = getTimestamp();
        uint64_t startTsInt = rel ? now - startTs : startTs;
        uint64_t endTsInt = rel ? now - endTs : endTs;
        DCDB::TimeStamp start(startTsInt), end(endTsInt);
118
        err = myJobDataStore->getJobsInIntervalRunning(tempList, start, end);
119
        if(err != JD_OK) return false;
Alessio Netti's avatar
Alessio Netti committed
120
121
122
    } else {
        // Getting a single job by id
        err = myJobDataStore->getJobById(tempData, jobId);
123
        if(err != JD_OK) return false;
Alessio Netti's avatar
Alessio Netti committed
124
125
126
127
128
129
130
131
132
        tempList.push_back(tempData);
    }
    
    for(auto& jd : tempList) {
        tempQeData.jobId = jd.jobId;
        tempQeData.userId = jd.userId;
        tempQeData.startTime = jd.startTime.getRaw();
        tempQeData.endTime = jd.endTime.getRaw();
        tempQeData.nodes = jd.nodes;
133
        buffer.push_back(tempQeData);
Alessio Netti's avatar
Alessio Netti committed
134
    }
135
    return true;
Alessio Netti's avatar
Alessio Netti committed
136
137
}

138
bool sensorGroupQueryCallback(const std::vector<string>& names, const uint64_t startTs, const uint64_t endTs, std::vector<reading_t>& buffer, const bool rel) {
139
140
141
    // Returning NULL if the query engine is being updated
    if(queryEngine.updating.load()) return false;
    ++queryEngine.access;
142
143
144
145
146
147
148
149
150
151
152
153
154
155
    
    std::list<DCDB::SensorId> topics;
    std::string topic;
    sensorCache_t& sensorMap = mySensorCache.getSensorMap();
    size_t successCtr = 0;
    for(const auto& name : names) {
        // Getting the topic of the queried sensor from the Navigator
        // If not found, we try to use the input name as topic
        try {
            topic = queryEngine.getNavigator()->getNodeTopic(name);
        } catch (const std::domain_error &e) { topic = name; }
        DCDB::SensorId sid;
        // Creating a SID to perform the query
        if (sid.mqttTopicConvert(topic)) {
156
157
158
159
160
161
            mySensorCache.wait();
            if (sensorMap.count(sid) > 0 && sensorMap[sid].getView(startTs, endTs, buffer, rel)) {
                // Data was found, can continue to next SID
                successCtr++;
            } else {
                // This happens only if no data was found in the local cache
162
163
                topics.push_back(sid);
            }
164
            mySensorCache.release();
165
        }
166
    }
167
168
169
170
171
172
173
174
175
176
177
178
179
    // If we are here then some sensors were not found in the cache - we need to fetch data from Cassandra
    if(!topics.empty()) {
        try {
            std::list <DCDB::SensorDataStoreReading> results;
            uint64_t now = getTimestamp();
            //Converting relative timestamps to absolute
            uint64_t startTsInt = rel ? now - startTs : startTs;
            uint64_t endTsInt = rel ? now - endTs : endTs;
            DCDB::TimeStamp start(startTsInt), end(endTsInt);
            uint16_t startWs=start.getWeekstamp(), endWs=end.getWeekstamp();
            // If timestamps are equal we perform a fuzzy query
            if(startTsInt == endTsInt) {
                topics.front().setRsvd(startWs);
180
                mySensorDataStore->fuzzyQuery(results, topics, start, 3600000000000, false);
181
182
183
184
185
            }
            // Else, we iterate over the weekstamps (if more than one) and perform range queries
            else {
                for(uint16_t currWs=startWs; currWs<=endWs; currWs++) {
                    topics.front().setRsvd(currWs);
186
                    mySensorDataStore->query(results, topics, start, end, DCDB::AGGREGATE_NONE, false);
187
188
189
190
191
192
193
194
195
196
197
198
                }
            }

            if (!results.empty()) {
                successCtr++;
                reading_t reading;
                for (const auto &r : results) {
                    reading.value = r.value;
                    reading.timestamp = r.timeStamp.getRaw();
                    buffer.push_back(reading);
                }
            }
199
        }
200
        catch (const std::exception &e) {}
201
    }
202
    
203
    --queryEngine.access;
204
205
206
207
208
209
210
211
212
    return successCtr>0;
}

bool sensorQueryCallback(const string& name, const uint64_t startTs, const uint64_t endTs, std::vector<reading_t>& buffer, const bool rel) {
    // Returning NULL if the query engine is being updated
    if(queryEngine.updating.load()) return false;
    std::vector<std::string> nameWrapper;
    nameWrapper.push_back(name);
    return sensorGroupQueryCallback(nameWrapper, startTs, endTs, buffer, rel);
213
214
}

215
216
217
218
219
220
221
222
223
224
225
bool metadataQueryCallback(const string& name, SensorMetadata& buffer) {
    // Returning NULL if the query engine is being updated
    if(queryEngine.updating.load()) return false;
    ++queryEngine.access;
    std::string topic=name;
    // Getting the topic of the queried sensor from the Navigator
    // If not found, we try to use the input name as topic
    try {
        topic = queryEngine.getNavigator()->getNodeTopic(name);
    } catch(const std::domain_error& e) {}
    
226
    bool local = false;
227
228
229
230
    metadataStore->wait();
    if(metadataStore->getMap().count(topic)) {
        buffer = metadataStore->get(topic);
        local = true;
231
    }
232
233
    metadataStore->release();
        
234
    if(!local) {
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
        // If we are here then the sensor was not found in the cache - we need to fetch data from Cassandra
        try {
            DCDB::PublicSensor publicSensor;
            if (mySensorConfig->getPublicSensorByName(publicSensor, topic.c_str()) != SC_OK) {
                --queryEngine.access;
                return false;
            }
            buffer = Configuration::publicSensorToMetadata(publicSensor);
        }
        catch (const std::exception &e) {
            --queryEngine.access;
            return false;
        }
    }
    --queryEngine.access;
    return true;
}

253
/* Normal termination (SIGINT, CTRL+C) */
254
255
void sigHandler(int sig)
{
Alessio Netti's avatar
Alessio Netti committed
256
  boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
Alessio Netti's avatar
Alessio Netti committed
257
  if( sig == SIGINT ) {
Alessio Netti's avatar
Alessio Netti committed
258
      LOG(fatal) << "Received SIGINT";
Alessio Netti's avatar
Alessio Netti committed
259
260
      retCode = EXIT_SUCCESS;
  } else if( sig == SIGTERM ) {
Alessio Netti's avatar
Alessio Netti committed
261
      LOG(fatal) << "Received SIGTERM";
Alessio Netti's avatar
Alessio Netti committed
262
263
264
265
266
      retCode = EXIT_SUCCESS;
  } else if( sig == SIGUSR1 ) {
      LOG(fatal) << "Received SIGUSR1 via REST API";
      retCode = !httpsServer ? EXIT_SUCCESS : httpsServer->getReturnCode();
  }
267
268
269
  keepRunning = 0;
}

270
271
272
273
274
275
/* Crash */
void abrtHandler(int sig)
{
  abrt(EXIT_FAILURE, SIGNAL);
}

276
int mqttCallback(SimpleMQTTMessage *msg)
277
278
279
280
{
  /*
   * Increment the msgCtr/vmsgCtr for statistics.
   */
281
  msgCtr++;
282
283
284
  if (msg->isPublish())
    pmsgCtr++;

285
286
#ifndef BENCHMARK_MODE

287
  uint64_t len;
288
289
290
  /*
   * Decode the message and put into the database.
   */
291
  if (msg->isPublish()) {
292
      const char *topic = msg->getTopic().c_str();
293
      // We check whether the topic includes the /DCDB_MAP/ keyword, indicating that the payload will contain the
294
295
      // sensor's name. In that case, we set the mappingMessage flag to true, and filter the keyword out of the prefix
      // We use strncmp as it is the most efficient way to do it
Alessio Netti's avatar
Alessio Netti committed
296
      if (strncmp(topic, DCDB_MAP, DCDB_MAP_LEN) == 0) {
297
          if ((len = msg->getPayloadLength()) == 0) {
298
              LOG(error) << "Empty sensor publish message received!";
299
300
              return 1;
          }
301

302
          string payload((char *) msg->getPayload(), len);
303
304
305
306
307
308
309
310
311
          //If the topic includes the extended /DCDB_MAP/METADATA/ keyword, we assume a JSON metadata packet is encoded
          if(strncmp(topic, DCDB_MET, DCDB_MET_LEN) == 0) {
              SensorMetadata sm;
              try {
                  sm.parseJSON(payload);
              } catch (const std::exception &e) {
                  LOG(error) << "Invalid metadata packed received!";
                  return 1;
              }
312
              if(sm.isValid()) {
313
                  err = mySensorConfig->publishSensor(sm);
314
315
                  metadataStore->store(*sm.getPattern(), sm);
              }
316
317
          } else {
              err = mySensorConfig->publishSensor(payload.c_str(), topic + DCDB_MAP_LEN);
318
          }
319
320
321
322

          // PublishSensor does most of the error checking for us
          switch (err) {
              case DCDB::SC_INVALIDPATTERN:
Alessio Netti's avatar
Logging    
Alessio Netti committed
323
                  LOG(error) << "Invalid sensor topic : " << msg->getTopic();
324
325
                  return 1;
              case DCDB::SC_INVALIDPUBLICNAME:
326
                  LOG(error) << "Invalid sensor public name.";
327
328
                  return 1;
              case DCDB::SC_INVALIDSESSION:
Alessio Netti's avatar
Logging    
Alessio Netti committed
329
                  LOG(error) << "Cannot reach sensor data store.";
330
331
332
333
                  return 1;
              default:
                  break;
          }
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
      } else if (strncmp(topic, DCDB_CALIEVT, DCDB_CALIEVT_LEN) == 0) {
          /*
           * Special message case. This message contains a Caliper Event data
           * string that is encoded in the MQTT topic. Its payload consists of
           * usual timestamp-value pairs.
           * Data from this messages will be stored in a separate table managed
           * by CaliEvtDataStore class.
           */
          std::string topicStr(msg->getTopic());
          mqttPayload buf, *payload;

          len = msg->getPayloadLength();
          //TODO support case that no timestamp is given?
          //retrieve timestamp and value from the payload
          if ((len % sizeof(mqttPayload) == 0) && (len > 0)) {
              payload = (mqttPayload *) msg->getPayload();
          } else {
              //this message is malformed -> ignore
              LOG(error) << "Message malformed";
              return 1;
          }

          /*
           * Decode message topic in actual sensor topic and string data.
           * "/:/" is used as delimiter between topic and data.
           */
          topicStr.erase(0, DCDB_CALIEVT_LEN);
          size_t pos = topicStr.find("/:/");
          if (pos == std::string::npos) {
              // topic is malformed -> ignore
              LOG(error) << "CaliEvt topic malformed";
              return 1;
          }
          const std::string data(topicStr, pos+3);
          topicStr.erase(pos);

          /*
           * We use the same MQTT-topic/SensorId infrastructure as actual sensor
           * data readings to sort related events.
           * Check if we can decode the event topic into a valid SensorId. If
           * successful, store the record in the database.
           */
          DCDB::SensorId sid;
          if (sid.mqttTopicConvert(topicStr)) {
378
              //std::list<DCDB::CaliEvtData> events;
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
              DCDB::CaliEvtData e;
              e.eventId   = sid;
              e.event     = data;
              for (uint64_t i = 0; i < len / sizeof(mqttPayload); i++) {
                  e.timeStamp = payload[i].timestamp;

                  /**
                   * We want an exhaustive list of all events ordered by their
                   * time of occurrence. Payload values should always be
                   * one. Other values currently indicate a malformed message.
                   *
                   * In the future, the value field could be used to aggregate
                   * multiple equal events that occurred in the same plugin
                   * read cycle.
                   */
                  if(payload[i].value != 1) {
                      LOG(error) << "CaliEvt message malformed. Value != 1";
                      return 1;
                  }

399
400
                  myCaliEvtDataStore->insert(e, metadataStore->getTTL(topicStr));
                  //events.push_back(e);
401
              }
402
              //myCaliEvtDataStore->insertBatch(events, metadataStore->getTTL(topicStr));
403
404
405
          } else {
              LOG(error) << "Topic could not be converted to SID";
          }
Micha Müller's avatar
Micha Müller committed
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
      } else if (strncmp(topic, DCDB_JOBDATA, DCDB_JOBDATA_LEN) == 0) {
	      /**
           * This message contains Slurm job data in JSON format. We need to
           * parse the payload and store it within the JobDataStore.
           */
	      if ((len = msg->getPayloadLength()) == 0) {
		      LOG(error) << "Empty job data message received!";
		      return 1;
	      }

	      //parse JSON into JobData object
	      string        payload((char *)msg->getPayload(), len);
	      DCDB::JobData jd;
	      try {
		      boost::property_tree::iptree config;
		      std::istringstream           str(payload);
		      boost::property_tree::read_json(str, config);
		      BOOST_FOREACH (boost::property_tree::iptree::value_type &val, config) {
			      if (boost::iequals(val.first, "jobid")) {
				      jd.jobId = val.second.data();
			      } else if (boost::iequals(val.first, "userid")) {
				      jd.userId = val.second.data();
			      } else if (boost::iequals(val.first, "starttime")) {
				      jd.startTime = DCDB::TimeStamp((uint64_t)stoull(val.second.data()));
			      } else if (boost::iequals(val.first, "endtime")) {
				      jd.endTime = DCDB::TimeStamp((uint64_t)stoull(val.second.data()));
			      } else if (boost::iequals(val.first, "nodes")) {
				      BOOST_FOREACH (boost::property_tree::iptree::value_type &node, val.second) {
					      jd.nodes.push_back(node.second.data());
				      }
			      }
		      }
	      } catch (const std::exception &e) {
		      LOG(error) << "Invalid job data packet received!";
		      return 1;
	      }

#ifdef DEBUG
	      LOG(debug) << "JobId  = " << jd.jobId;
	      LOG(debug) << "UserId = " << jd.userId;
	      LOG(debug) << "Start  = " << jd.startTime.getString();
	      LOG(debug) << "End    = " << jd.endTime.getString();
	      LOG(debug) << "Nodes: ";
	      for (const auto &n : jd.nodes) {
		      LOG(debug) << "    " << n;
	      }
#endif

	      //store JobData into Storage Backend
	      if (jd.endTime == DCDB::TimeStamp((uint64_t)0)) {
		      //starting job data
		      if (myJobDataStore->insertJob(jd) != DCDB::JD_OK) {
			      LOG(error) << "Job data insert failed!";
			      return 1;
		      }
	      } else {
		      //ending job data
		      DCDB::JobData tmp;
		      if (myJobDataStore->getJobById(tmp, jd.jobId) != DCDB::JD_OK) {
			      LOG(error) << "Could not retrieve job to be updated!";
			      return 1;
		      }

		      if (myJobDataStore->updateEndtime(tmp.jobId, tmp.startTime, jd.endTime) != DCDB::JD_OK) {
			      LOG(error) << "Could not update end time of job!";
			      return 1;
		      }
	      }
474
      } else {
Micha Müller's avatar
Micha Müller committed
475
	      mqttPayload buf, *payload;
476

Micha Müller's avatar
Micha Müller committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
	      len = msg->getPayloadLength();
	      //In the 64 bit message case, the collect agent provides a timestamp
	      if (len == sizeof(uint64_t)) {
		      payload = &buf;
		      payload->value = *((int64_t *)msg->getPayload());
		      payload->timestamp = Messaging::calculateTimestamp();
		      len = sizeof(uint64_t) * 2;
	      }
	      //...otherwise it just retrieves it from the MQTT message payload.
	      else if ((len % sizeof(mqttPayload) == 0) && (len > 0)) {
		      payload = (mqttPayload *)msg->getPayload();
	      }
	      //...otherwise this message is malformed -> ignore...
	      else {
		      LOG(error) << "Message malformed";
		      return 1;
	      }
494

Micha Müller's avatar
Micha Müller committed
495
	      /*
496
497
498
499
           * Check if we can decode the message topic
           * into a valid SensorId. If successful, store
           * the record in the database.
           */
Micha Müller's avatar
Micha Müller committed
500
501
	      DCDB::SensorId sid;
	      if (sid.mqttTopicConvert(msg->getTopic())) {
502
503
504
505
506
507
508
509
510
511
512
513
#if 0
              cout << "Topic decode successful:" << endl
                  << "  Raw:            " << hex << setw(16) << setfill('0') << sid.getRaw()[0] << hex << setw(16) << setfill('0') << sid.getRaw()[1] << endl
                  << "  DeviceLocation: " << hex << setw(16) << setfill('0') << sid.getDeviceLocation() << endl
                  << "  device_id:      " << hex << setw(8) << setfill('0') << sid.getDeviceSensorId().device_id << endl
                  << "  sensor_number:  " << hex << setw(4) << setfill('0') << sid.getDeviceSensorId().sensor_number << endl << dec;

              cout << "Payload ("  << len/sizeof(mqttPayload) << " messages):"<< endl;
              for (uint64_t i=0; i<len/sizeof(mqttPayload); i++) {
                cout << "  " << i << ": ts=" << payload[i].timestamp << " val=" << payload[i].value << endl;
              }
              cout << endl;
514
#endif
515
	      std::list<DCDB::SensorDataStoreReading> readings;
Alessio Netti's avatar
Alessio Netti committed
516
517
518
519
520
521
          for (uint64_t i = 0; i < len / sizeof(mqttPayload); i++) {
              DCDB::SensorDataStoreReading r(sid, payload[i].timestamp, payload[i].value);
              readings.push_back(r);
              mySensorCache.storeSensor(sid, payload[i].timestamp, payload[i].value);
          }
          mySensorCache.getSensorMap()[sid].updateBatchSize(uint64_t(len / sizeof(mqttPayload)));
522
	      mySensorDataStore->insertBatch(readings, metadataStore->getTTL(msg->getTopic()));
523
	      readingCtr+= readings.size();
524

525
              //mySensorCache.dump();
526
527
          } else {
              LOG(error) << "Message with empty topic received";
528
          }
529
      }
530
  }
531
#endif
532
  return 0;
533
534
}

535
536
537



538
539
540
541
/*
 * Print usage information
 */
void usage() {
542
543
544
545
546
  /*
             1         2         3         4         5         6         7         8
   012345678901234567890123456789012345678901234567890123456789012345678901234567890
   */
  cout << "Usage:" << endl;
547
  cout << "  collectagent [-d] [-s] [-x] [-a] [-m<host>] [-c<host>] [-u<username>] [-p<password>] [-t<ttl>] [-v<verbosity>] <config>" << endl;
548
549
550
551
  cout << "  collectagent -h" << endl;
  cout << endl;
  
  cout << "Options:" << endl;
552
553
  cout << "  -m<host>      MQTT listen address     [default: " << DEFAULT_LISTENHOST << ":" << DEFAULT_LISTENPORT << "]" << endl;
  cout << "  -c<host>      Cassandra host          [default: " << DEFAULT_CASSANDRAHOST << ":" << DEFAULT_CASSANDRAPORT << "]" << endl;
Michael Ott's avatar
Michael Ott committed
554
555
  cout << "  -u<username>  Cassandra username      [default: none]" << endl;
  cout << "  -p<password>  Cassandra password      [default: none]" << endl;
556
557
  cout << "  -t<ttl>       Cassandra insert TTL    [default: " << DEFAULT_CASSANDRATTL << "]" << endl;
  cout << "  -v<level>     Set verbosity of output [default: " << DEFAULT_LOGLEVEL << "]" << endl
Alessio Netti's avatar
Logging    
Alessio Netti committed
558
       << "                Can be a number between 5 (all) and 0 (fatal)." << endl;
559
  cout << endl;
Michael Ott's avatar
Michael Ott committed
560
  cout << "  -d            Daemonize" << endl;
561
  cout << "  -s            Print message stats" <<endl;
562
  cout << "  -x            Parse and print the config but do not actually start collectagent" << endl;
563
  cout << "  -a			   Enable sensor auto-publish" << endl;
Michael Ott's avatar
Michael Ott committed
564
  cout << "  -h            This help page" << endl;
565
  cout << endl;
566
567
568
}

int main(int argc, char* const argv[]) {
569
    cout << "CollectAgent " << VERSION << " (libdcdb " << DCDB::Version::getVersion() << ")" << endl << endl;
570
571

  try{
572

573
574
      // Checking if path to config is supplied
      if (argc <= 1) {
575
          cout << "Please specify a path to the config-directory or a config-file" << endl << endl;
576
577
578
579
580
          usage();
          exit(EXIT_FAILURE);
      }

      // Defining options
581
      const char* opts = "m:r:c:C:u:p:t:v:dDsaxh";
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597

      // Same mechanism as in DCDBPusher - checking if help string is requested before loading config
      char ret;
      while ((ret = getopt(argc, argv, opts)) != -1) {
          switch (ret)
          {
              case 'h':
                  usage();
                  exit(EXIT_FAILURE);
                  break;
              default:
                  //do nothing (other options are read later on)
                  break;
          }
      }

598
599
      initLogging();
      auto cmdSink = setupCmdLogger();
Alessio Netti's avatar
Logging    
Alessio Netti committed
600

Alessio Netti's avatar
Alessio Netti committed
601
      Configuration config(argv[argc - 1], "collectagent.conf");
602
      config.readConfig();
603

Alessio Netti's avatar
Alessio Netti committed
604
605
606
607
      // References to shorten access to config parameters
      Configuration& settings = config;
      cassandra_t& cassandraSettings = config.cassandraSettings;
      pluginSettings_t& pluginSettings = config.pluginSettings;
Micha Mueller's avatar
Micha Mueller committed
608
      serverSettings_t& restAPISettings = config.restAPISettings;
Alessio Netti's avatar
Alessio Netti committed
609
      analyticsSettings_t& analyticsSettings = config.analyticsSettings;
Alessio Netti's avatar
Alessio Netti committed
610
      
611
612
      optind = 1;
      while ((ret=getopt(argc, argv, opts))!=-1) {
613
          switch(ret) {
614
              case 'a':
615
                  pluginSettings.autoPublish = true;
616
                  break;
617
              case 'm':
Alessio Netti's avatar
Alessio Netti committed
618
619
                  settings.mqttListenHost = parseNetworkHost(optarg);
                  settings.mqttListenPort = parseNetworkPort(optarg);
620
                  if(settings.mqttListenPort=="") settings.mqttListenPort = string(DEFAULT_LISTENPORT);
621
                  break;
622
              case 'c':
Alessio Netti's avatar
Alessio Netti committed
623
624
                  cassandraSettings.host = parseNetworkHost(optarg);
                  cassandraSettings.port = parseNetworkPort(optarg);
625
                  if(cassandraSettings.port=="") cassandraSettings.port = string(DEFAULT_CASSANDRAPORT);
626
                  break;
Michael Ott's avatar
Michael Ott committed
627
              case 'u':
Alessio Netti's avatar
Alessio Netti committed
628
                  cassandraSettings.username = optarg;
629
                  break;
Michael Ott's avatar
Michael Ott committed
630
              case 'p': {
Alessio Netti's avatar
Alessio Netti committed
631
                  cassandraSettings.password = optarg;
632
                  // What does this do? Mask the password?
Michael Ott's avatar
Michael Ott committed
633
634
635
636
637
638
639
                  size_t pwdLen = strlen(optarg);
                  memset(optarg, 'x', (pwdLen >= 3) ? 3 : pwdLen);
                  if (pwdLen > 3) {
                      memset(optarg+3, 0, pwdLen-3);
                  }
                  break;
              }
640
              case 't':
Alessio Netti's avatar
Alessio Netti committed
641
                  cassandraSettings.ttl = stoul(optarg);
642
                  break;
Alessio Netti's avatar
Logging    
Alessio Netti committed
643
              case 'v':
644
                  settings.logLevelCmd = stoi(optarg);
Alessio Netti's avatar
Logging    
Alessio Netti committed
645
                  break;
646
              case 'd':
647
              case 'D':
648
                  settings.daemonize = 1;
649
                  break;
650
              case 's':
651
                  settings.statistics = 1;
652
                  break;
653
              case 'x':
Alessio Netti's avatar
Alessio Netti committed
654
                  settings.validateConfig = true;
655
                  break;
656
              case 'h':
657
658
659
              default:
                  usage();
                  exit(EXIT_FAILURE);
660
661
662
          }
      }

663
664
      //set up logger to file
      if (settings.logLevelFile >= 0) {
Alessio Netti's avatar
Alessio Netti committed
665
	  auto fileSink = setupFileLogger(pluginSettings.tempdir, std::string("collectagent"));
666
667
668
	  fileSink->set_filter(boost::log::trivial::severity >= translateLogLevel(settings.logLevelFile));
      }
      
Alessio Netti's avatar
Logging    
Alessio Netti committed
669
      //severity level may be overwritten (per option or config-file) --> set it according to globalSettings
670
671
672
      if (settings.logLevelCmd >= 0) {
	  cmdSink->set_filter(boost::log::trivial::severity >= translateLogLevel(settings.logLevelCmd));
      }
Alessio Netti's avatar
Logging    
Alessio Netti committed
673

674
      /*
Alessio Netti's avatar
Alessio Netti committed
675
       * Catch SIGINT and SIGTERM signals to allow for proper server shutdowns.
676
677
       */
      signal(SIGINT, sigHandler);
Alessio Netti's avatar
Alessio Netti committed
678
      signal(SIGTERM, sigHandler);
Alessio Netti's avatar
Alessio Netti committed
679
      signal(SIGUSR1, sigHandler);
680
681
682
683
684
685
686
687
688
689

      /*
       * Catch critical signals to allow for backtraces
       */
      signal(SIGABRT, abrtHandler);
      signal(SIGSEGV, abrtHandler);

      // Daemonizing the collectagent
      if(settings.daemonize)
          dcdbdaemon();
Alessio Netti's avatar
Alessio Netti committed
690
      
691
      // Setting the size of the sensor cache
692
      // Conversion from milliseconds to nanoseconds
Alessio Netti's avatar
Alessio Netti committed
693
      mySensorCache.setMaxHistory(uint64_t(pluginSettings.cacheInterval) * 1000000);
694

695
      //Allocate and initialize connection to Cassandra.
Alessio Netti's avatar
Alessio Netti committed
696
697
      dcdbConn = new DCDB::Connection(cassandraSettings.host, atoi(cassandraSettings.port.c_str()), 
                                      cassandraSettings.username, cassandraSettings.password);
Alessio Netti's avatar
Alessio Netti committed
698
699
      dcdbConn->setNumThreadsIo(cassandraSettings.numThreadsIo);
      dcdbConn->setQueueSizeIo(cassandraSettings.queueSizeIo);
700
      uint32_t params[1] = {cassandraSettings.coreConnPerHost};
Alessio Netti's avatar
Alessio Netti committed
701
      dcdbConn->setBackendParams(params);
Alessio Netti's avatar
Alessio Netti committed
702
      
Axel Auweter's avatar
Axel Auweter committed
703
      if (!dcdbConn->connect()) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
704
          LOG(fatal) << "Cannot connect to Cassandra!";
705
706
707
708
709
710
          exit(EXIT_FAILURE);
      }

      /*
       * Legacy behavior: Initialize the DCDB schema in Cassandra.
       */
Axel Auweter's avatar
Axel Auweter committed
711
      dcdbConn->initSchema();
Alessio Netti's avatar
Alessio Netti committed
712
      
713
714
715
      /*
       * Allocate the SensorDataStore.
       */
716
      mySensorDataStore = new DCDB::SensorDataStore(dcdbConn);
717
      mySensorConfig = new DCDB::SensorConfig(dcdbConn);
Alessio Netti's avatar
Alessio Netti committed
718
      myJobDataStore = new DCDB::JobDataStore(dcdbConn);
719
      myCaliEvtDataStore = new DCDB::CaliEvtDataStore(dcdbConn);
720
721
722

      /*
       * Set TTL for data store inserts if TTL > 0.
723
       */
724
      if (cassandraSettings.ttl > 0) {
Alessio Netti's avatar
Alessio Netti committed
725
        mySensorDataStore->setTTL(cassandraSettings.ttl);
726
727
        myCaliEvtDataStore->setTTL(cassandraSettings.ttl);
      }
Alessio Netti's avatar
Alessio Netti committed
728
      mySensorDataStore->setDebugLog(cassandraSettings.debugLog);
729
      myCaliEvtDataStore->setDebugLog(cassandraSettings.debugLog);
730

731
732
733
      // Fetching public sensor information from the Cassandra datastore
      list<DCDB::PublicSensor> publicSensors;
      metadataStore = new MetadataStore();
734
735
      if(mySensorConfig->getPublicSensorsVerbose(publicSensors)!=SC_OK)
          LOG(error) << "Failed to retrieve public sensors. Metadata Store and Sensor Navigator will be empty.";
736
      SensorMetadata sBuf;
737
      for (const auto &s : publicSensors)
738
739
          if (!s.is_virtual) {
              sBuf = Configuration::publicSensorToMetadata(s);
740
741
              if(sBuf.isValid())
                  metadataStore->store(*sBuf.getPattern(), sBuf);
742
          }
743
          
744
745
      analyticsController = new AnalyticsController(mySensorConfig, mySensorDataStore);
      analyticsController->setCache(&mySensorCache);
746
      analyticsController->setMetadataStore(metadataStore);
Alessio Netti's avatar
Alessio Netti committed
747
      queryEngine.setFilter(analyticsSettings.filter);
Alessio Netti's avatar
Alessio Netti committed
748
      queryEngine.setJobFilter(analyticsSettings.jobFilter);
749
      queryEngine.setJobMatch(analyticsSettings.jobMatch);
Alessio Netti's avatar
Alessio Netti committed
750
      queryEngine.setSensorHierarchy(analyticsSettings.hierarchy);
751
      queryEngine.setQueryCallback(sensorQueryCallback);
752
      queryEngine.setGroupQueryCallback(sensorGroupQueryCallback);
753
      queryEngine.setMetadataQueryCallback(metadataQueryCallback);
Alessio Netti's avatar
Alessio Netti committed
754
      queryEngine.setJobQueryCallback(jobQueryCallback);
755
      if(!analyticsController->initialize(settings))
756
757
          return EXIT_FAILURE;
      
Alessio Netti's avatar
Alessio Netti committed
758
      LOG_LEVEL vLogLevel = settings.validateConfig ? LOG_LEVEL::info : LOG_LEVEL::debug;
759
760
761
762
      LOG_VAR(vLogLevel) << "-----  Configuration  -----";

      //print global settings in either case
      LOG(info) << "Global Settings:";
Alessio Netti's avatar
Alessio Netti committed
763
      LOG(info) << "    MQTT-listenAddress: " << settings.mqttListenHost << ":" << settings.mqttListenPort;
Alessio Netti's avatar
Alessio Netti committed
764
      LOG(info) << "    CacheInterval:      " << int(pluginSettings.cacheInterval/1000) << " [s]";
765
766
767
768
769
      LOG(info) << "    CleaningInterval:   " << settings.cleaningInterval << " [s]";
      LOG(info) << "    MessageThreads:     " << settings.messageThreads;
      LOG(info) << "    MessageSlots:       " << settings.messageSlots;
      LOG(info) << "    Daemonize:          " << (settings.daemonize ? "Enabled" : "Disabled");
      LOG(info) << "    Statistics:         " << (settings.statistics ? "Enabled" : "Disabled");
Alessio Netti's avatar
Alessio Netti committed
770
      LOG(info) << "    MQTT-prefix:        " << pluginSettings.mqttPrefix;
771
      LOG(info) << "    Auto-publish:       " << (pluginSettings.autoPublish ? "Enabled" : "Disabled");
Alessio Netti's avatar
Alessio Netti committed
772
773
      LOG(info) << "    Write-Dir:          " << pluginSettings.tempdir;
      LOG(info) << (settings.validateConfig ? "    Only validating config files." : "    ValidateConfig:     Disabled");
774

Alessio Netti's avatar
Alessio Netti committed
775
776
      LOG(info) << "Analytics Settings:";
      LOG(info) << "    Hierarchy:          " << (analyticsSettings.hierarchy!="" ? analyticsSettings.hierarchy : "none");
777
      LOG(info) << "    Filter:             " << (analyticsSettings.filter!="" ? analyticsSettings.filter : "none");
778
779
      LOG(info) << "    Job Filter:         " << (analyticsSettings.jobFilter != "" ? analyticsSettings.jobFilter : "none");
      LOG(info) << "    Job Match:          " << (analyticsSettings.jobMatch != "" ? analyticsSettings.jobMatch : "none");
Alessio Netti's avatar
Alessio Netti committed
780
      
781
      LOG(info) << "Cassandra Driver Settings:";
Alessio Netti's avatar
Alessio Netti committed
782
      LOG(info) << "    Address:            " << cassandraSettings.host << ":" << cassandraSettings.port;
Alessio Netti's avatar
Alessio Netti committed
783
784
785
786
787
      LOG(info) << "    TTL:                " << cassandraSettings.ttl;
      LOG(info) << "    NumThreadsIO:       " << cassandraSettings.numThreadsIo;
      LOG(info) << "    QueueSizeIO:        " << cassandraSettings.queueSizeIo;
      LOG(info) << "    CoreConnPerHost:    " << cassandraSettings.coreConnPerHost;
      LOG(info) << "    DebugLog:           " << (cassandraSettings.debugLog ? "Enabled" : "Disabled");
788
#ifdef SimpleMQTTVerbose
Alessio Netti's avatar
Alessio Netti committed
789
790
      LOG(info) << "    Username:           " << cassandraSettings.username;
	  LOG(info) << "    Password:           " << cassandraSettings.password;
791
792
793
794
#else
      LOG(info) << "    Username and password not printed.";
#endif

795
796
797
798
799
      if (restAPISettings.enabled) {
	  
	  LOG(info) << "RestAPI Settings:";
	  LOG(info) << "    REST Server: " << restAPISettings.host << ":" << restAPISettings.port;
	  LOG(info) << "    Certificate: " << restAPISettings.certificate;
Alessio Netti's avatar
Alessio Netti committed
800
	  LOG(info) << "    Private key file: " << restAPISettings.privateKey;
801
      }
802
803
      LOG_VAR(vLogLevel) << "-----  Analytics Configuration  -----";
      for(auto& p : analyticsController->getManager()->getPlugins()) {
804
          LOG_VAR(vLogLevel) << "Operator Plugin \"" << p.id << "\"";
805
806
807
808
          p.configurator->printConfig(vLogLevel);
      }
      LOG_VAR(vLogLevel) << "-----  End Configuration  -----";

Alessio Netti's avatar
Alessio Netti committed
809
      if (settings.validateConfig)
810
811
812
813
          return EXIT_SUCCESS;
      else
          analyticsController->start();

814
815
816
      /*
       * Start the MQTT Message Server.
       */
Alessio Netti's avatar
Alessio Netti committed
817
      SimpleMQTTServer ms(settings.mqttListenHost, settings.mqttListenPort, settings.messageThreads, settings.messageSlots);
818
      
819
820
821
      ms.setMessageCallback(mqttCallback);
      ms.start();

Alessio Netti's avatar
Logging    
Alessio Netti committed
822
      LOG(info) << "MQTT Server running...";
823
      
824
825
826
      /*
       * Start the HTTP Server for the REST API
       */
827
      if (restAPISettings.enabled) {
828
829
830
831
          httpsServer = new CARestAPI(restAPISettings, &mySensorCache, analyticsController);
          config.readRestAPIUsers(httpsServer);
          httpsServer->start();
          LOG(info) <<  "HTTP Server running...";
832
      }
833

834
835
836
837
838
839
      /*
       * Run (hopefully) forever...
       */
      keepRunning = 1;
      timeval start, end;
      double elapsed;
840
841
842
      msgCtr = 0;
      pmsgCtr = 0;
      readingCtr = 0;
843

Alessio Netti's avatar
Alessio Netti committed
844
845
846
      gettimeofday(&start, NULL);
      uint64_t lastCleanup = start.tv_sec;

847
      LOG(info) << "Collect Agent running...";
848
849
      while(keepRunning) {
          gettimeofday(&start, NULL);
Alessio Netti's avatar
Alessio Netti committed
850
851
852
853
854
855
856
          if(start.tv_sec - lastCleanup > settings.cleaningInterval) {
              uint64_t purged = mySensorCache.clean(settings.cleaningInterval * 1000000000);
              lastCleanup = start.tv_sec;
              if(purged > 0)
                  LOG(info) << "Cache: purged " << purged << " obsolete entries";
          }

857
          sleep(60);
858
859
860
861
          /* 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;
862
          float publish = msgCtr?(pmsgCtr*100.0)/msgCtr:0;
Alessio Netti's avatar
Alessio Netti committed
863
          if (settings.statistics && keepRunning) {
864
              LOG(info) << "Performance: " << (readingCtr/elapsed)*1000.0 << " inserts/s, " << (msgCtr/elapsed)*1000.0 << " messages/s (" << publish << "% PUBLISH)";
865
              LOG(info) << "Analytics Performance: " << (analyticsController->getReadingCtr()/elapsed)*1000.0 << " inserts/s ";
866
          }
867
          msgCtr = 0;
868
          pmsgCtr = 0;
869
	  readingCtr = 0;
870
871
      }

Alessio Netti's avatar
Logging    
Alessio Netti committed
872
      LOG(info) << "Stopping...";
873
      analyticsController->stop();
874
      ms.stop();
Alessio Netti's avatar
Logging    
Alessio Netti committed
875
      LOG(info) << "MQTT Server stopped...";
876
877
878
879
880
      if (restAPISettings.enabled) {
	  httpsServer->stop();
	  delete httpsServer;
	  LOG(info) << "HTTP Server stopped...";
      }
881
      delete mySensorDataStore;
Alessio Netti's avatar
Alessio Netti committed
882
      delete myJobDataStore;
883
      delete mySensorConfig;
884
      delete myCaliEvtDataStore;
Axel Auweter's avatar
Axel Auweter committed
885
886
      dcdbConn->disconnect();
      delete dcdbConn;
887
      delete metadataStore;
Alessio Netti's avatar
Logging    
Alessio Netti committed
888
      LOG(info) << "Collect Agent closed. Bye bye...";
889
  }
890
891
892
893
  catch (const std::runtime_error& e) {
      LOG(fatal) <<  e.what();
      return EXIT_FAILURE;
  }
894
  catch (const exception& e) {
Alessio Netti's avatar
Logging    
Alessio Netti committed
895
      LOG(fatal) << "Exception: " << e.what();
896
      abrt(EXIT_FAILURE, INTERR);
897
898
  }

Alessio Netti's avatar
Alessio Netti committed
899
  return retCode;
900
}
901
902