2.12.2021, 9:00 - 11:00: Due to updates GitLab may be unavailable for some minutes between 09:00 and 11:00.

query.cpp 15.3 KB
Newer Older
Axel Auweter's avatar
Axel Auweter committed
1
2
//================================================================================
// Name        : query.cpp
3
// Author      : Axel Auweter, Daniele Tafani
Micha Müller's avatar
Micha Müller committed
4
// Contact     : info@dcdb.it
Axel Auweter's avatar
Axel Auweter committed
5
6
7
8
9
10
// Copyright   : Leibniz Supercomputing Centre
// Description : Implementation of query class of dcdbquery
//================================================================================

//================================================================================
// This file is part of DCDB (DataCenter DataBase)
11
// Copyright (C) 2011-2019 Leibniz Supercomputing Centre
Axel Auweter's avatar
Axel Auweter committed
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.
//================================================================================
Axel Auweter's avatar
Axel Auweter committed
27
28
29
30
31
32
33

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

#include <cstdlib>
34
#include <cinttypes>
Axel Auweter's avatar
Axel Auweter committed
35

36
#include <boost/algorithm/string.hpp>
37
#include <boost/regex.hpp>
38
39

#include "dcdbendian.h"
Axel Auweter's avatar
Axel Auweter committed
40
#include "query.h"
Daniele Tafani's avatar
Daniele Tafani committed
41
#include "dcdb/sensoroperations.h"
42
43
#include <dcdb/jobdatastore.h>

Axel Auweter's avatar
Axel Auweter committed
44

Axel Auweter's avatar
Axel Auweter committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
void DCDBQuery::setLocalTimeEnabled(bool enable) {
  useLocalTime = enable;
}

bool DCDBQuery::getLocalTimeEnabled() {
  return useLocalTime;
}

void DCDBQuery::setRawOutputEnabled(bool enable) {
  useRawOutput = enable;
}

bool DCDBQuery::getRawOutputEnabled() {
  return useRawOutput;
}

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
int DCDBQuery::connect(const char* hostname) {
    if (connection != nullptr) {
	return 0;
    }
    connection = new DCDB::Connection();
    connection->setHostname(hostname);
    if (!connection->connect()) {
	std::cout << "Cannot connect to database." << std::endl;
	return 1;
    }
    return 0;
}

void DCDBQuery::disconnect() {
    connection->disconnect();
    delete connection;
    connection = nullptr;
}

80
81
82
83
bool scaleAndConvert(int64_t &value, double baseScalingFactor, double scalingFactor, DCDB::Unit baseUnit, DCDB::Unit unit) {
    if(scalingFactor != 1.0 || baseScalingFactor != 1.0) {
	if( DCDB::scale(&value, scalingFactor, baseScalingFactor) == DCDB::DCDB_OP_OVERFLOW)
	    return false;
84
85
    }
    
86
87
88
89
90
91
92
93
94
    /* Convert the unit if requested */
    if ((unit != DCDB::Unit_None) && (unit != baseUnit)) {
	if (!DCDB::UnitConv::convert(value, baseUnit, unit)) {
	    std::cerr << "Warning, cannot convert units ("
	    << DCDB::UnitConv::toString(baseUnit) << " -> "
	    << DCDB::UnitConv::toString(unit) << ")"
	    << std::endl;
	    return false;
	}
95
    }
96
97
98
99
100
101
102
103
104
105
	    
    return true;
}

void DCDBQuery::genOutput(std::list<DCDB::SensorDataStoreReading> &results, queryMap_t::iterator start, queryMap_t::iterator stop) {
    /* Print Header */
    std::cout << "Sensor,Time";
    for (queryMap_t::iterator it=start; it!=stop; it++) {
	switch(it->second.operation) {
	    case DCDB_OP_NONE:
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
	    case DCDB_OP_WINTERMUTE: {
		switch(it->second.aggregate) {
		    case DCDB::AGGREGATE_MIN:
			std::cout << ",min";
			break;
		    case DCDB::AGGREGATE_MAX:
			std::cout << ",max";
			break;
		    case DCDB::AGGREGATE_AVG:
			std::cout << ",avg";
			break;
		    case DCDB::AGGREGATE_SUM:
			std::cout << ",sum";
			break;
		    case DCDB::AGGREGATE_COUNT:
			std::cout << ",count";
			break;
		    default:
			std::cout << ",Value";
			break;
		}
127
		break;
128
	    }
129
130
131
132
133
134
135
136
137
138
139
140
	    case DCDB_OP_DELTA:
		std::cout << ",Delta";
		break;
	    case DCDB_OP_DELTAT:
		std::cout << ",Delta_t";
		break;
	    case DCDB_OP_DERIVATIVE:
		std::cout << ",Derivative";
		break;
	    case DCDB_OP_INTEGRAL:
		std::cout << ",Integral";
		break;
141
142
143
	    case DCDB_OP_RATE:
		std::cout << ",Rate";
		break;
144
	    default:
Alessio Netti's avatar
Alessio Netti committed
145
		break;
146
	}
147
148
	
	std::string unitStr;
149
	if(it->second.unit != DCDB::Unit_None) {
150
	    unitStr = DCDB::UnitConv::toString(it->second.unit);
151
	} else if (baseUnit != DCDB::Unit_None) {
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
	    unitStr = DCDB::UnitConv::toString(baseUnit);
	}
	if (it->second.operation == DCDB_OP_DERIVATIVE) {
	    if ((unitStr.back() == 's') || (unitStr.back() == 'h')) {
		unitStr.pop_back();
	    } else if (unitStr.back() == 'J') {
		unitStr.pop_back();
		unitStr.append("W");
	    }
	} else if (it->second.operation == DCDB_OP_INTEGRAL) {
	    if (unitStr.back() == 'W') {
		unitStr.append("s");
	    }
	}
	if (unitStr.size() > 0) {
	    std::cout << " (" << unitStr << ")";
168
	}
169
    }
170
171
    std::cout << std::endl;
    
172
    int64_t prevReading=0;
173
    DCDB::TimeStamp prevT((uint64_t) 0);
174
175
    for (std::list<DCDB::SensorDataStoreReading>::iterator reading = results.begin(); reading != results.end(); reading++) {
	DCDB::TimeStamp ts = (*reading).timeStamp;
176
	
177
	/* Print the sensor's public name */
178
	std::cout << start->first.name << ",";
179
180
	
	/* Print the time stamp */
181
	if (useRawOutput) {
182
	    std::cout << ts.getRaw();
183
184
185
186
	} else {
	    if (useLocalTime) {
		ts.convertToLocal();
	    }
187
	    std::cout << ts.getString();
188
	}
189
	
190
	int64_t value, result;
191
192
	/* Print the sensor value */
	for (queryMap_t::iterator it=start; it!=stop; it++) {
193
194
195
196
197
198
	    DCDB::Unit unit;
	    if (it->second.unit != DCDB::Unit_None) {
		unit = it->second.unit;
	    } else {
		unit = baseUnit;
	    }
199
200
	    value = (*reading).value;
	    result = 0;
201
202
203
	    bool resultOk = false;
	    switch(it->second.operation) {
		case DCDB_OP_NONE:
204
		case DCDB_OP_WINTERMUTE:
205
206
207
208
209
210
211
212
213
		    if (scaleAndConvert(value, baseScalingFactor, it->second.scalingFactor, baseUnit, it->second.unit)) {
			result = value;
			resultOk = true;
		    }
		    break;
		case DCDB_OP_DELTA:
		    if (scaleAndConvert(value, baseScalingFactor, it->second.scalingFactor, baseUnit, it->second.unit)) {
			if ((prevT > (uint64_t) 0) && (DCDB::delta(value, prevReading, &result) == DCDB::DCDB_OP_SUCCESS)) {
			    resultOk = true;
214
			}
215
216
217
218
		    }
		    break;
		case DCDB_OP_DELTAT:
		    if (scaleAndConvert(value, baseScalingFactor, it->second.scalingFactor, baseUnit, it->second.unit)) {
219
			if ((prevT > (uint64_t) 0) && (DCDB::delta(ts.getRaw(), prevT.getRaw(), &result) == DCDB::DCDB_OP_SUCCESS)) {
220
			    resultOk = true;
221
			}
222
223
224
225
226
227
228
		    }
		    break;
		case DCDB_OP_DERIVATIVE: {
		    int64_t prevValue = prevReading;
		    if (scaleAndConvert(value, baseScalingFactor, it->second.scalingFactor, baseUnit, it->second.unit) && scaleAndConvert(prevValue, baseScalingFactor, it->second.scalingFactor, baseUnit, it->second.unit)) {
			if( (prevT > (uint64_t) 0) && DCDB::derivative(value, prevValue, ts.getRaw(), prevT.getRaw(), &result, unit) == DCDB::DCDB_OP_SUCCESS) {
			    resultOk = true;
229
			}
230
231
232
233
234
235
236
		    }
		    break;}
		case DCDB_OP_INTEGRAL: {
		    int64_t prevValue = prevReading;
		    if (scaleAndConvert(prevValue, baseScalingFactor, it->second.scalingFactor, baseUnit, it->second.unit)) {
			if( (prevT > (uint64_t) 0) && DCDB::integral(prevValue, ts.getRaw(), prevT.getRaw(), &result, unit) == DCDB::DCDB_OP_SUCCESS) {
			    resultOk = true;
237
			}
238
239
		    }
		    break;}
240
241
242
243
244
245
246
247
		case DCDB_OP_RATE: {
		    int64_t prevValue = prevReading;
		    if (scaleAndConvert(value, baseScalingFactor, it->second.scalingFactor, baseUnit, it->second.unit)) {
			if( (prevT > (uint64_t) 0) && DCDB::rate(value, ts.getRaw(), prevT.getRaw(), &result) == DCDB::DCDB_OP_SUCCESS) {
			    resultOk = true;
			}
		    }
		    break;}
248
249
250
251
252
		default:
		    break;
	    }
	    if (resultOk) {
		std::cout << "," << result;
253
254
255
256
	    } else {
		std::cout << ",";
	    }
	}
257
	prevReading = value;
258
	prevT = ts;
259
	std::cout << std::endl;
260
    }
261
262
}

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
void DCDBQuery::setInterval(DCDB::TimeStamp start, DCDB::TimeStamp end) {
    start_ts = start;
    end_ts = end;
}

void DCDBQuery::parseSensorSpecification(const std::string sensor, std::string& sensorName, queryConfig_t& queryCfg) {
    
    std::string s = sensor;
    /* Check for function first */
    boost::regex functRegex("^([^\\(\\)]+)\\(([^\\(\\)]+)\\)$", boost::regex::extended);
    boost::smatch match;
    std::string functName;
    if(boost::regex_search(s, match, functRegex)) {
	functName = match[1].str();
	s = match[2].str();
    }
    
    /* Split into sensor name and potential modifier, i.e. unit conversion or scaling factor */
    boost::regex sensorRegex("([^\\@]+)\\@?([^\\@]*)", boost::regex::extended);
    std::string modifierStr;
    if(boost::regex_search(s, match, sensorRegex)) {
	sensorName = match[1].str();
	modifierStr = match[2].str();
286
    }
287
    
288
    queryCfg = { 1.0, DCDB::Unit_None, DCDB_OP_NONE, DCDB::AGGREGATE_NONE};
289
290
291
292
293
294
295
296
297
298
    if (functName.length() == 0) {
	queryCfg.operation = DCDB_OP_NONE;
    } else if (boost::iequals(functName, "delta")) {
	queryCfg.operation = DCDB_OP_DELTA;
    } else if (boost::iequals(functName, "delta_t")) {
	queryCfg.operation = DCDB_OP_DELTAT;
    } else if (boost::iequals(functName, "derivative")) {
	queryCfg.operation = DCDB_OP_DERIVATIVE;
    } else if (boost::iequals(functName, "integral")) {
	queryCfg.operation = DCDB_OP_INTEGRAL;
299
300
    } else if (boost::iequals(functName, "rate")) {
	queryCfg.operation = DCDB_OP_RATE;
301
302
303
304
305
306
307
    } else if (boost::iequals(functName, "min")) {
	queryCfg.aggregate = DCDB::AGGREGATE_MIN;
    } else if (boost::iequals(functName, "max")) {
	queryCfg.aggregate = DCDB::AGGREGATE_MAX;
    } else if (boost::iequals(functName, "avg")) {
	queryCfg.aggregate = DCDB::AGGREGATE_AVG;
    } else if (boost::iequals(functName, "sum")) {
308
	queryCfg.aggregate = DCDB::AGGREGATE_SUM;
309
310
    } else if (boost::iequals(functName, "count")) {
	queryCfg.aggregate = DCDB::AGGREGATE_COUNT;
311
    } else {
312
313
	queryCfg.operation = DCDB_OP_WINTERMUTE;
	queryCfg.wintermuteOp = functName;
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    }
    
    if (queryCfg.operation != DCDB_OP_UNKNOWN) {
	if (modifierStr.length() > 0) {
	    boost::regex e("[0-9]*\\.?[0-9]*", boost::regex::extended);
	    if (boost::regex_match(modifierStr, e)) {
		queryCfg.scalingFactor = atof(modifierStr.c_str());
	    } else {
		queryCfg.unit = DCDB::UnitConv::fromString(modifierStr);
	    }
	}
    }
}

void DCDBQuery::prepareQuery(std::list<std::string> sensors) {
329
330
331
    /* Initialize the SensorConfig interface */
    DCDB::SensorConfig sensorConfig(connection);
    
332
333
334
    /* Iterate over list of sensors requested by the user */
    for (std::list<std::string>::iterator it = sensors.begin(); it != sensors.end(); it++) {
	std::string sensorName;
335
336
	queryConfig_t queryCfg;
	parseSensorSpecification(*it, sensorName, queryCfg);
337
	if (queryCfg.operation != DCDB_OP_UNKNOWN) {
Michael Ott's avatar
Michael Ott committed
338
339
340
341
	    std::list <DCDB::PublicSensor> publicSensors;
	    sensorConfig.getPublicSensorsByWildcard(publicSensors, sensorName.c_str());
	    if (publicSensors.size() > 0) {
		for (auto sen: publicSensors) {
342
343
344
345
346
347
348
349
350
			if(queryCfg.operation == DCDB_OP_WINTERMUTE) {
				if(sen.operations.find(queryCfg.wintermuteOp) != sen.operations.end()) {
					sen.name = sen.name + queryCfg.wintermuteOp;
					sen.pattern = sen.pattern + queryCfg.wintermuteOp;
				} else {
					std::cerr << "Unknown sensor operation: " << queryCfg.wintermuteOp << std::endl;
					continue;
				}
			}
Michael Ott's avatar
Michael Ott committed
351
352
353
354
355
356
		    queries.insert(std::pair<DCDB::PublicSensor, queryConfig_t>(sen, queryCfg));
		}
	    } else {
		DCDB::PublicSensor pS;
		pS.name = sensorName;
		pS.pattern = sensorName;
357
358
359
360
		if(queryCfg.operation != DCDB_OP_WINTERMUTE)
			queries.insert(std::pair<DCDB::PublicSensor, queryConfig_t>(pS, queryCfg));
		else
			std::cerr << "Unknown sensor operation: " << queryCfg.wintermuteOp << std::endl;
361
	    }
362
363
	}
    }
364
365
366
367
368
}

void DCDBQuery::prepareQuery(std::list<std::string> sensors, std::list<std::string> prefixes) {
    /* Initialize the SensorConfig interface */
    DCDB::SensorConfig sensorConfig(connection);
369
    
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
    /* Iterate over list of sensors requested by the user */
    for (std::list<std::string>::iterator it = sensors.begin(); it != sensors.end(); it++) {
	std::string sensorName;
	queryConfig_t queryCfg;
	parseSensorSpecification(*it, sensorName, queryCfg);
	for (auto p: prefixes) {
	    std::string s = p;
	    if (s.back() != '/') {
		s.push_back('/');
	    }
	    s.append(sensorName);
	    if (queryCfg.operation != DCDB_OP_UNKNOWN) {
		std::list <DCDB::PublicSensor> publicSensors;
		sensorConfig.getPublicSensorsByWildcard(publicSensors, s.c_str());
		if (publicSensors.size() > 0) {
		    for (auto sen: publicSensors) {
386
387
388
389
390
391
392
393
394
395
				if(queryCfg.operation == DCDB_OP_WINTERMUTE) {
					if(sen.operations.find(queryCfg.wintermuteOp) != sen.operations.end()) {
						sen.name = sen.name + queryCfg.wintermuteOp;
						sen.pattern = sen.pattern + queryCfg.wintermuteOp;
					} else {
						std::cerr << "Unknown sensor operation: " << queryCfg.wintermuteOp << std::endl;
						continue;
					}
				}
				queries.insert(std::pair<DCDB::PublicSensor, queryConfig_t>(sen, queryCfg));
396
397
398
399
400
		    }
		} else {
		    DCDB::PublicSensor pS;
		    pS.name = s;
		    pS.pattern = s;
401
402
403
404
405
			if(queryCfg.operation != DCDB_OP_WINTERMUTE)
				queries.insert(std::pair<DCDB::PublicSensor, queryConfig_t>(pS, queryCfg));
			else
				std::cerr << "Unknown sensor operation: " << queryCfg.wintermuteOp << std::endl;
		}
406
407
408
409
410
411
		}
	    }
	}
}

void DCDBQuery::execute() {
412
    std::string prevSensorName;
413
414
415
    auto q = queries.begin();
    while (q != queries.end()) {
	if (q->first.name != prevSensorName) {
416
417
	    prevSensorName = q->first.name;

418
	    // Find all queries for the same sensor
419
	    std::pair<queryMap_t::iterator, queryMap_t::iterator> range = queries.equal_range(q->first);
420
421
	    
	    /* Base scaling factor and unit of the public sensor */
422
423
	    baseUnit = DCDB::UnitConv::fromString(q->first.unit);
	    baseScalingFactor = q->first.scaling_factor;
424
425
	    
	    std::list<DCDB::SensorDataStoreReading> results;
426
	    DCDB::Sensor sensor(connection, q->first);
427
	    
428
429
	    // Query aggregates first
	    auto it=range.first;
430
	    while(it!=range.second) {
431
432
433
434
435
		if (it->second.aggregate != DCDB::AGGREGATE_NONE) {
		    sensor.query(results, start_ts, end_ts, it->second.aggregate);
		    if (results.size() > 0) {
			genOutput(results, it, std::next(it));
			results.clear();
436
			// Remove the query from the list so it doesn't show up in the raw values below anymore
437
438
439
			if (it == range.first) {
			    range.first = std::next(it);
			}
440
441
442
			if (it == q) {
			    q = std::next(q);
			}
443
444
445
446
			it = queries.erase(it);
			continue;
		    }
		}
447
448
449
		if (it != range.second) {
		    it++;
		}
450
451
452
	    }

	    // Query raw values next
453
	    for (auto it=range.first; it!=range.second; it++) {
454
455
456
457
458
459
460
461
462
		if (it->second.aggregate == DCDB::AGGREGATE_NONE) {
		    sensor.query(results, start_ts, end_ts, DCDB::AGGREGATE_NONE);
		    break;
		}
	    }
	    if (results.size() > 0) {
		genOutput(results, range.first, range.second);
		results.clear();
	    }
463
	}
464
465
466
	if (q != queries.end()) {
	    q++;
	}
467
    }
468
469
470
471
472
473
474
475
476
477
478
479
}

void DCDBQuery::doQuery(std::list<std::string> sensors, DCDB::TimeStamp start, DCDB::TimeStamp end) {
    setInterval(start, end);
    prepareQuery(sensors);
    execute();
}

void DCDBQuery::dojobQuery(std::list<std::string> sensors, std::string jobId) {
    DCDB::JobDataStore jobDataStore(connection);
    DCDB::JobData jobData;
    DCDB::JDError err = jobDataStore.getJobById(jobData, jobId);
480
    
481
482
483
484
485
486
487
488
    if (err == DCDB::JD_OK) {
	setInterval(jobData.startTime, jobData.endTime);
	prepareQuery(sensors, jobData.nodes);
	execute();
    } else {
	std::cerr << "Job not found: " << jobId << std::endl;
    }

Axel Auweter's avatar
Axel Auweter committed
489
490
}

Axel Auweter's avatar
Axel Auweter committed
491
DCDBQuery::DCDBQuery()
Axel Auweter's avatar
Axel Auweter committed
492
{
Axel Auweter's avatar
Axel Auweter committed
493
  connection = nullptr;
494
  useLocalTime = true;
Axel Auweter's avatar
Axel Auweter committed
495
  useRawOutput = false;
Axel Auweter's avatar
Axel Auweter committed
496
}