The expiration time for new job artifacts in CI/CD pipelines is now 30 days (GitLab default). Previously generated artifacts in already completed jobs will not be affected by the change. The latest artifacts for all jobs in the latest successful pipelines will be kept. More information: https://gitlab.lrz.de/help/user/admin_area/settings/continuous_integration.html#default-artifacts-expiration

query.cpp 14.8 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
	    default:
Alessio Netti's avatar
Alessio Netti committed
142
		break;
143
	}
144
145
	
	std::string unitStr;
146
	if(it->second.unit != DCDB::Unit_None) {
147
	    unitStr = DCDB::UnitConv::toString(it->second.unit);
148
	} else if (baseUnit != DCDB::Unit_None) {
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
	    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 << ")";
165
	}
166
    }
167
168
    std::cout << std::endl;
    
169
    int64_t prevReading=0;
170
    DCDB::TimeStamp prevT((uint64_t) 0);
171
172
    for (std::list<DCDB::SensorDataStoreReading>::iterator reading = results.begin(); reading != results.end(); reading++) {
	DCDB::TimeStamp ts = (*reading).timeStamp;
173
	
174
	/* Print the sensor's public name */
175
	std::cout << start->first.name << ",";
176
177
	
	/* Print the time stamp */
178
	if (useRawOutput) {
179
	    std::cout << ts.getRaw();
180
181
182
183
	} else {
	    if (useLocalTime) {
		ts.convertToLocal();
	    }
184
	    std::cout << ts.getString();
185
	}
186
	
187
	int64_t value, result;
188
189
	/* Print the sensor value */
	for (queryMap_t::iterator it=start; it!=stop; it++) {
190
191
192
193
194
195
	    DCDB::Unit unit;
	    if (it->second.unit != DCDB::Unit_None) {
		unit = it->second.unit;
	    } else {
		unit = baseUnit;
	    }
196
197
	    value = (*reading).value;
	    result = 0;
198
199
200
	    bool resultOk = false;
	    switch(it->second.operation) {
		case DCDB_OP_NONE:
201
		case DCDB_OP_WINTERMUTE:
202
203
204
205
206
207
208
209
210
		    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;
211
			}
212
213
214
215
		    }
		    break;
		case DCDB_OP_DELTAT:
		    if (scaleAndConvert(value, baseScalingFactor, it->second.scalingFactor, baseUnit, it->second.unit)) {
216
			if ((prevT > (uint64_t) 0) && (DCDB::delta(ts.getRaw(), prevT.getRaw(), &result) == DCDB::DCDB_OP_SUCCESS)) {
217
			    resultOk = true;
218
			}
219
220
221
222
223
224
225
		    }
		    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;
226
			}
227
228
229
230
231
232
233
		    }
		    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;
234
			}
235
236
237
238
239
240
241
		    }
		    break;}
		default:
		    break;
	    }
	    if (resultOk) {
		std::cout << "," << result;
242
243
244
245
	    } else {
		std::cout << ",";
	    }
	}
246
	prevReading = value;
247
	prevT = ts;
248
	std::cout << std::endl;
249
    }
250
251
}

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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();
275
    }
276
    
277
    queryCfg = { 1.0, DCDB::Unit_None, DCDB_OP_NONE, DCDB::AGGREGATE_NONE};
278
279
280
281
282
283
284
285
286
287
    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;
288
289
290
291
292
293
294
    } 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")) {
295
	queryCfg.aggregate = DCDB::AGGREGATE_SUM;
296
297
    } else if (boost::iequals(functName, "count")) {
	queryCfg.aggregate = DCDB::AGGREGATE_COUNT;
298
    } else {
299
300
	queryCfg.operation = DCDB_OP_WINTERMUTE;
	queryCfg.wintermuteOp = functName;
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    }
    
    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) {
316
317
318
    /* Initialize the SensorConfig interface */
    DCDB::SensorConfig sensorConfig(connection);
    
319
320
321
    /* 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;
322
323
	queryConfig_t queryCfg;
	parseSensorSpecification(*it, sensorName, queryCfg);
324
	if (queryCfg.operation != DCDB_OP_UNKNOWN) {
Michael Ott's avatar
Michael Ott committed
325
326
327
328
	    std::list <DCDB::PublicSensor> publicSensors;
	    sensorConfig.getPublicSensorsByWildcard(publicSensors, sensorName.c_str());
	    if (publicSensors.size() > 0) {
		for (auto sen: publicSensors) {
329
330
331
332
333
334
335
336
337
			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
338
339
340
341
342
343
		    queries.insert(std::pair<DCDB::PublicSensor, queryConfig_t>(sen, queryCfg));
		}
	    } else {
		DCDB::PublicSensor pS;
		pS.name = sensorName;
		pS.pattern = sensorName;
344
345
346
347
		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;
348
	    }
349
350
	}
    }
351
352
353
354
355
}

void DCDBQuery::prepareQuery(std::list<std::string> sensors, std::list<std::string> prefixes) {
    /* Initialize the SensorConfig interface */
    DCDB::SensorConfig sensorConfig(connection);
356
    
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    /* 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) {
373
374
375
376
377
378
379
380
381
382
				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));
383
384
385
386
387
		    }
		} else {
		    DCDB::PublicSensor pS;
		    pS.name = s;
		    pS.pattern = s;
388
389
390
391
392
			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;
		}
393
394
395
396
397
398
		}
	    }
	}
}

void DCDBQuery::execute() {
399
    std::string prevSensorName;
400
401
402
    auto q = queries.begin();
    while (q != queries.end()) {
	if (q->first.name != prevSensorName) {
403
404
	    prevSensorName = q->first.name;

405
	    // Find all queries for the same sensor
406
	    std::pair<queryMap_t::iterator, queryMap_t::iterator> range = queries.equal_range(q->first);
407
408
	    
	    /* Base scaling factor and unit of the public sensor */
409
410
	    baseUnit = DCDB::UnitConv::fromString(q->first.unit);
	    baseScalingFactor = q->first.scaling_factor;
411
412
	    
	    std::list<DCDB::SensorDataStoreReading> results;
413
	    DCDB::Sensor sensor(connection, q->first);
414
	    
415
416
	    // Query aggregates first
	    auto it=range.first;
417
	    while(it!=range.second) {
418
419
420
421
422
		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();
423
			// Remove the query from the list so it doesn't show up in the raw values below anymore
424
425
426
			if (it == range.first) {
			    range.first = std::next(it);
			}
427
428
429
			if (it == q) {
			    q = std::next(q);
			}
430
431
432
433
			it = queries.erase(it);
			continue;
		    }
		}
434
435
436
		if (it != range.second) {
		    it++;
		}
437
438
439
	    }

	    // Query raw values next
440
	    for (auto it=range.first; it!=range.second; it++) {
441
442
443
444
445
446
447
448
449
		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();
	    }
450
	}
451
452
453
	if (q != queries.end()) {
	    q++;
	}
454
    }
455
456
457
458
459
460
461
462
463
464
465
466
}

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);
467
    
468
469
470
471
472
473
474
475
    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
476
477
}

Axel Auweter's avatar
Axel Auweter committed
478
DCDBQuery::DCDBQuery()
Axel Auweter's avatar
Axel Auweter committed
479
{
Axel Auweter's avatar
Axel Auweter committed
480
  connection = nullptr;
481
  useLocalTime = true;
Axel Auweter's avatar
Axel Auweter committed
482
  useRawOutput = false;
Axel Auweter's avatar
Axel Auweter committed
483
}