Blame view

src/Parameters/ParameterManager.cc 15 KB
fbe3c2bb   Benjamin Renard   First commit
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * ParamterManager.cc
 *
 *  Created on: 15 oct. 2012
 *      Author: AKKA IS
 */


#include <iostream>
#include <sstream>
#include <boost/thread/future.hpp>
#include <boost/thread/thread.hpp>
#include <boost/functional/hash.hpp>
78249cd2   Benjamin Renard   Fix special chara...
14
#include <boost/algorithm/string/replace.hpp>
fbe3c2bb   Benjamin Renard   First commit
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

#include "DicError.hh"

#include "ParameterManager.hh"

#include "DicError.hh"
#include "Parameter.hh"
#include "FileConfigurator.hh"
#include "ParamOutput.hh"
#include "Process.hh"
#include "ServicesServer.hh"

//#include "TimeTableCatalogFactory.hh"

using namespace std;
using namespace TimeTableCatalog;

namespace AMDA {
namespace Parameters {

log4cxx::LoggerPtr ParameterManager::_logger(
		log4cxx::Logger::getLogger("AMDA-Kernel.ParameterManager"));

/*
 * @brief Mutex used to protect multi-thread access to CDF lib (CDF lib is not thread-safe!)
 * This mutex is a part of the ParameterManager to be shared between by FileWriterCDF (DownloadOutput plugin)
 * and class and FileReaderCDF (ParamGetLocalFile)
 */
boost::mutex ParameterManager::mutexCDFLib;

5ddc9ffe   Benjamin Renard   NetCDF file reade...
45
46
47
48
49
50
51
/*
 * @brief Mutex used to protect multi-thread access to NetCDF lib (NetCDF lib is not thread-safe!)
 * This mutex is a part of the ParameterManager to be shared between by FileWriterNetCDF (DownloadOutput plugin)
 * and class and FileReaderNetCDF (ParamGetLocalFile)
 */
boost::mutex ParameterManager::mutexNetCDFLib;

fbe3c2bb   Benjamin Renard   First commit
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#define DEFAULT_GAP_THRESHOLD_VALUE 5

ParameterManager::ParameterManager() :
		_timeIntervalList(new TimeIntervalList),
		_defaultGapThreshold(DEFAULT_GAP_THRESHOLD_VALUE) {
}

ParameterManager::~ParameterManager() {
}

void ParameterManager::createParameter(const std::string& nameParam) {
	CfgContext ctx;
	ctx.push<ParameterManager*>(this);
	ctx.push<ServicesServer*>(ServicesServer::getInstance());
	try {
		ServicesServer::getInstance()->getConfigurator()->proceed(
				nameParam.c_str(), ctx);
	} catch (AMDA::AMDA_exception & e) {
		e << AMDA::errno_code(AMDA_INFORMATION_PARAM_ERR);
		throw;
	}
}

bool ParameterManager::addParameter(Parameter* pParentParameter,
		const std::string& pIDParam, ParameterSPtr& pParamResult) {
	bool result = false;
78249cd2   Benjamin Renard   Fix special chara...
78
79
80
81
	std::string fixedParamId = pIDParam;
        applyParamIdCorrection(fixedParamId);
	ParameterSPtr param = findParamInParameterList(pIDParam);
	if (param == nullptr) {
fbe3c2bb   Benjamin Renard   First commit
82
		pParamResult = ParameterSPtr(new Parameter(*this, pIDParam));
78249cd2   Benjamin Renard   Fix special chara...
83
		addParamInParameterList(pParamResult);
fbe3c2bb   Benjamin Renard   First commit
84
85
		result = true;
	} else {
78249cd2   Benjamin Renard   Fix special chara...
86
		pParamResult = param;
fbe3c2bb   Benjamin Renard   First commit
87
88
89
90
	}
	if (pParentParameter) {
		pParentParameter->addParameter(pParamResult);
		pParamResult->setGapThreshold(pParentParameter->getGapThreshold());
e8fa18b6   Benjamin Renard   Add the possibili...
91
92
		for (auto info : pParentParameter->getInfoList())
			pParamResult->setInfoValues(info.first,info.second);
fbe3c2bb   Benjamin Renard   First commit
93
94
95
96
	}
	return result;
}

78249cd2   Benjamin Renard   Fix special chara...
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
void ParameterManager::addParamInParameterList(ParameterSPtr& pParam) {
	ParameterSPtr param = findParamInParameterList(pParam->getId());
	if (param != nullptr) {
		return;
	}
	std::string fixedParamId = pParam->getId();
	applyParamIdCorrection(fixedParamId);
	LOG4CXX_DEBUG(_logger, "Add Parameter " << pParam->getId())
	_parameterList[fixedParamId] = pParam;
}

ParameterSPtr ParameterManager::findParamInParameterList(const std::string& paramId) {
	std::string fixedParamId = paramId;
	applyParamIdCorrection(fixedParamId);
	ParameterList::iterator it = _parameterList.find(fixedParamId);
	if (it != _parameterList.end()) {
		return _parameterList[fixedParamId];
	}
	return ParameterSPtr();
}

fbe3c2bb   Benjamin Renard   First commit
118
119
120
121
122
123
void ParameterManager::applyParamIdCorrection(std::string& paramId)
{
	//Some characters are used to apply an operation, a process, etc... in an expression
	//These characters can't be used for a parmId
	//=> replace "-", "+", "*", "/", "^", "(", ")", "[", "]", "{", "}","&","|",
	//"$" by "_"
78249cd2   Benjamin Renard   Fix special chara...
124
125
126
127
	std::vector<std::string> charList = {
		"-", "+", "*", "/", "^",
		"(", ")", "[", "]", "{", "}",
		"&", "|", "$", ".", ",", "#",
fbe3c2bb   Benjamin Renard   First commit
128
129
	};

78249cd2   Benjamin Renard   Fix special chara...
130
131
132
133
134
135
136
137
	std::string replaceBy;
	for (auto c : charList) {
		replaceBy = "";
		replaceBy += "_";
		replaceBy += std::to_string((int)(c[0]));
		replaceBy += "_";
		paramId = boost::replace_all_copy(paramId, c, replaceBy);
	}
fbe3c2bb   Benjamin Renard   First commit
138
139
140
141
142
143
144
}

ParameterSPtr& ParameterManager::checkIfIsANeededParameter(ParameterSPtr& pParam) {
	Process* lProcess = dynamic_cast<Process*>(pParam->getDataWriterTemplate().get());
	if ( lProcess && lProcess->isEmptyExpression() ){
		ParameterSPtr temp = *pParam->getParameterList().begin();
		pParam->delegateOtherTaskTo(temp);
78249cd2   Benjamin Renard   Fix special chara...
145
146
		std::string fixedParamId = pParam->getId();
		_parameterList[fixedParamId] = temp;
fbe3c2bb   Benjamin Renard   First commit
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
		pParam=temp;
	}
	return pParam;
}

ParameterSPtr ParameterManager::getSampledParameter(const std::string& pIDParam,
		const std::string &samplingMode, float samplingValue, float gapThreshold)
{
	ParameterSPtr lParameter;
	if (samplingMode == "") {
		lParameter = getParameter(pIDParam);
	} else {
		//Compute a ResmapledParameter name
	    boost::hash<std::string> string_hash;
		stringstream lIdent;
		stringstream lBuffer;
		lBuffer << samplingMode << "_" << samplingValue << "_" << gapThreshold;
		lIdent << pIDParam << "_" << string_hash(lBuffer.str());
5fc489c5   Benjamin Renard   Add resampling in...
165
		LOG4CXX_DEBUG(_logger, "Resampled Parameter to found or create: " << lIdent.str() << " - samplingValue = " << samplingValue << ", gapThreshold = " << gapThreshold);
fbe3c2bb   Benjamin Renard   First commit
166
		// Search if already exist
78249cd2   Benjamin Renard   Fix special chara...
167
168
		lParameter = findParamInParameterList(lIdent.str());
		if (lParameter != nullptr) {
fbe3c2bb   Benjamin Renard   First commit
169
			LOG4CXX_DEBUG(_logger, "Resampled Parameter: " << lIdent.str() << " founded");
78249cd2   Benjamin Renard   Fix special chara...
170
			lParameter = checkIfIsANeededParameter(lParameter);
fbe3c2bb   Benjamin Renard   First commit
171
172
173
174
		} else {
			// create Parameter with ProcessRempling on $pIDParam
			LOG4CXX_DEBUG(_logger, "Resampled Parameter: " << lIdent.str() << " creation");
			lParameter = ParameterSPtr(new Parameter(*this, lIdent.str()));
e8fa18b6   Benjamin Renard   Add the possibili...
175
176
			for (auto info : getParameter(pIDParam)->getInfoList())
				lParameter->setInfoValues(info.first,info.second);
fbe3c2bb   Benjamin Renard   First commit
177
178
179
180
181
182
183
184
185
186
187
188
			//lParameter->setXmlId(getParameter(pIDParam)->getXmlId());
			Process* lProcess = NULL;
			if (samplingMode == "classic") {
				lProcess = ServicesServer::getInstance()->getProcess("sampling_classic",*lParameter.get());
			} else {
				lProcess = ServicesServer::getInstance()->getProcess("sampling_simple",*lParameter.get());
			}
			if (lProcess) {
				lBuffer.str(""); lBuffer << samplingValue;
				lProcess->getAttributList().push_back(lBuffer.str());
				lBuffer.str(""); lBuffer << gapThreshold;
				lProcess->getAttributList().push_back(lBuffer.str());
78249cd2   Benjamin Renard   Fix special chara...
189
190
191
				std::string fixedParamId = pIDParam;
				applyParamIdCorrection(fixedParamId);
				lBuffer.str("");  lBuffer << "$" << fixedParamId;
fbe3c2bb   Benjamin Renard   First commit
192
193
194
195
196
197
				lProcess->setExpression(lBuffer.str());
				DataWriterSPtr lDataWriter(lProcess);
				lParameter->setDataWriter(lDataWriter);
			} else {
				BOOST_THROW_EXCEPTION(ParameterManager_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg(std::string("Cannot found resampling process for: ")+pIDParam));
			}
78249cd2   Benjamin Renard   Fix special chara...
198
			addParamInParameterList(lParameter);
fbe3c2bb   Benjamin Renard   First commit
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
		}
	}
	if (!lParameter.get()) {
    	BOOST_THROW_EXCEPTION(ParameterManager_exception() << AMDA::errno_code(AMDA_PARAM_NOT_FOUND_ERR) << AMDA::ex_msg(std::string("Cannot reach parameter: ")+ pIDParam));
	}
	return lParameter;
}

ParameterSPtr ParameterManager::getSampledParameterUnderRefParam(const std::string& pIDParam, const std::string& pIDRefParam)
{
	//make a name for the resampled parameter
	boost::hash<std::string> string_hash;
	stringstream lIdent;
	stringstream lBuffer;
	lBuffer << "sampling_under_refparam";
	lBuffer << "_" << pIDRefParam;
	lIdent << pIDParam << "_" << string_hash(lBuffer.str());
	LOG4CXX_DEBUG(_logger, "Resampled Parameter under reference parameter to found or create: " << lIdent.str());
	// Search if already exist
	ParameterSPtr lParameter;
	ParameterSPtr lrefParameter;

	lrefParameter = getParameter(pIDRefParam);

	if (lrefParameter == nullptr)
	{
    	BOOST_THROW_EXCEPTION(ParameterManager_exception() << AMDA::errno_code(AMDA_PARAM_NOT_FOUND_ERR) << AMDA::ex_msg(std::string("Cannot reach reference parameter: ")+ pIDRefParam));
	}

78249cd2   Benjamin Renard   Fix special chara...
228
229
	lParameter = findParamInParameterList(lIdent.str());
	if (lParameter != nullptr) {
fbe3c2bb   Benjamin Renard   First commit
230
		LOG4CXX_DEBUG(_logger, "Resampled Parameter under reference parameter : " << lIdent.str() << " founded");
78249cd2   Benjamin Renard   Fix special chara...
231
		lParameter = checkIfIsANeededParameter(lParameter);
fbe3c2bb   Benjamin Renard   First commit
232
233
234
235
	} else {
		// create Parameter with ProcessRempling on $pIDParam
		LOG4CXX_DEBUG(_logger, "Resampled Parameter under reference parameter : " << lIdent.str() << " creation");
		lParameter = ParameterSPtr(new Parameter(*this, lIdent.str()));
e8fa18b6   Benjamin Renard   Add the possibili...
236
237
		for (auto info : lrefParameter->getInfoList())
			lParameter->setInfoValues(info.first,info.second);
fbe3c2bb   Benjamin Renard   First commit
238
239
240
241
242
		//lParameter->setXmlId(getParameter(pIDParam)->getXmlId());
		Process* lProcess = NULL;
		lProcess = ServicesServer::getInstance()->getProcess("sampling_under_refparam",*lParameter.get());
		if (lProcess)
		{
78249cd2   Benjamin Renard   Fix special chara...
243
244
245
			std::string fixedParamId = pIDParam;
			applyParamIdCorrection(fixedParamId);
			lBuffer.str("");  lBuffer << "$" << fixedParamId;
fbe3c2bb   Benjamin Renard   First commit
246
247
248
249
250
251
252
253
			lProcess->setExpression(lBuffer.str());
			lProcess->setReferenceParameter(lrefParameter);
			DataWriterSPtr lDataWriter(lProcess);
			lParameter->setDataWriter(lDataWriter);

		} else {
			BOOST_THROW_EXCEPTION(ParameterManager_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg(std::string("Cannot found resampling process for: ")+pIDParam));
		}
78249cd2   Benjamin Renard   Fix special chara...
254
		addParamInParameterList(lParameter);
fbe3c2bb   Benjamin Renard   First commit
255
256
257
258
259
260
261
262
	}

	if (!lParameter.get()) {
	    	BOOST_THROW_EXCEPTION(ParameterManager_exception() << AMDA::errno_code(AMDA_PARAM_NOT_FOUND_ERR) << AMDA::ex_msg(std::string("Cannot reach parameter: ")+ pIDParam));
		}
	return lParameter;
}

aa8a8e5f   Benjamin Renard   Auto compute gap ...
263
ParameterSPtr ParameterManager::getParameterFromExpression(const std::string& pExpression, double gapThreshold)
fbe3c2bb   Benjamin Renard   First commit
264
265
266
267
{
	boost::hash<std::string> string_hash;
	std::stringstream lIdent;
	lIdent << string_hash(pExpression);
aa8a8e5f   Benjamin Renard   Auto compute gap ...
268
269
270
271
	if (!isNAN(gapThreshold)) {
		lIdent << "_";
		lIdent << gapThreshold;
	}
fbe3c2bb   Benjamin Renard   First commit
272
273
274
275

	ParameterSPtr lParameter;
	ParameterSPtr lparentParameter;

78249cd2   Benjamin Renard   Fix special chara...
276
	lParameter = findParamInParameterList(lIdent.str());
fbe3c2bb   Benjamin Renard   First commit
277
	//check if the parameter already exist
78249cd2   Benjamin Renard   Fix special chara...
278
	if (lParameter != nullptr) {
fbe3c2bb   Benjamin Renard   First commit
279
		LOG4CXX_DEBUG(_logger, "Parameter from expression : " << lIdent.str() << " founded");
78249cd2   Benjamin Renard   Fix special chara...
280
		lParameter = checkIfIsANeededParameter(lParameter);
fbe3c2bb   Benjamin Renard   First commit
281
282
283
284
285
286
287
288
289
290
291
	} else {
		// create Parameter
		LOG4CXX_DEBUG(_logger, "Parameter from expression : " << lIdent.str() << " creation");
		lParameter = ParameterSPtr(new Parameter(*this, lIdent.str()));
		Process* lProcess = NULL;
		//create a standard process
		lProcess = ServicesServer::getInstance()->getProcess("standard",*lParameter.get());
		if (lProcess)
		{
			//set expression and create the data writer
			lProcess->setExpression(pExpression);
aa8a8e5f   Benjamin Renard   Auto compute gap ...
292
293
			if (!isNAN(gapThreshold))
				lProcess->setGapThreshold(gapThreshold);
fbe3c2bb   Benjamin Renard   First commit
294
295
			DataWriterSPtr lDataWriter(lProcess);
			lParameter->setDataWriter(lDataWriter);
78249cd2   Benjamin Renard   Fix special chara...
296
			addParamInParameterList(lParameter);
fbe3c2bb   Benjamin Renard   First commit
297
298
299
300
301
302
303
304
305
306
307
308
309
310
		} else {
			stringstream lError;  lError << "Process: 'standard' not found";
			LOG4CXX_ERROR(_logger, lError.str());
			BOOST_THROW_EXCEPTION(ParameterManager_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg(lError.str()));
		}
	}

	if (!lParameter.get()) {
		BOOST_THROW_EXCEPTION(ParameterManager_exception() << AMDA::errno_code(AMDA_PARAM_NOT_FOUND_ERR) << AMDA::ex_msg(std::string("Cannot reach parameter: ")+ lIdent.str()));
	}
	return lParameter;
}

ParameterSPtr ParameterManager::getParameter(const std::string& pIDParam) {
78249cd2   Benjamin Renard   Fix special chara...
311
	ParameterSPtr lParameter = findParamInParameterList(pIDParam);
fbe3c2bb   Benjamin Renard   First commit
312

78249cd2   Benjamin Renard   Fix special chara...
313
314
	if (lParameter != nullptr) {
		lParameter = checkIfIsANeededParameter(lParameter);
fbe3c2bb   Benjamin Renard   First commit
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
	} else {
		LOG4CXX_ERROR(_logger, "parameter '" << pIDParam << "' not exist");
    	BOOST_THROW_EXCEPTION(ParameterManager_exception() << AMDA::errno_code(AMDA_PARAM_NOT_FOUND_ERR) << AMDA::ex_msg(std::string("Cannot reach parameter: ")+ pIDParam));
	}

	return lParameter;
}

void ParameterManager::execute(string workingPath) {
	int error=0;
	int result = AMDA_EXIT_OK;
	int lNbTraitement =  _paramOutputList.size();

	for (ParamOutputList::iterator it = _paramOutputList.begin(); it != _paramOutputList.end(); ++it) {
		bool lAsError = false;
		try {
			(*it)->setWorkPath(workingPath);
			(*it)->establishConnection();
		} catch (AMDA::AMDA_exception & e) {
			LOG4CXX_ERROR( _logger, "Error resume: " << traitException(result,e));
			lAsError=true;
		} catch (...) {
			lAsError=true;
		}
		if (lAsError) {
			++error;
			_paramOutputList.erase(it--);
		}
	}
/*
	// Read time table file.
	if (!_timeTablePath.empty()) {
		readTimeTable(workingPath + "/" + _timeTablePath);
	}
*/
	for (ParamOutputList::iterator it = _paramOutputList.begin(); it != _paramOutputList.end(); ++it) {
		bool lAsError = false;
		try {
			LOG4CXX_DEBUG(_logger, "Give TimeInterval list to method");
			(*it)->init(getInputIntervals());
		} catch (AMDA::AMDA_exception & e) {
			LOG4CXX_ERROR( _logger, "Error resume: " << traitException(result,e));
			lAsError = true;
		} catch (...) {
			lAsError = true;
		}
		if (lAsError) {
			++error;
			_paramOutputList.erase(it--);
		}
	}

	boost::thread_group lThGroup;

	 typedef std::vector<boost::shared_future<void> > ParamOutputResultList;
	 ParamOutputResultList resultList;
	 for ( ParamOutputList::iterator it = _paramOutputList.begin(); it != _paramOutputList.end(); ++it) {
		 boost::packaged_task<void> pt(boost::bind(&ParamOutput::process, *it));
		 boost::shared_future<void> future(pt.get_future());
		 resultList.push_back(future);
		 lThGroup.add_thread(new boost::thread(boost::move(pt)));
	}

	 boost::wait_for_all(resultList.begin(), resultList.end());
	 lThGroup.join_all();

	 _parameterList.clear();

	for (ParamOutputResultList::iterator it = resultList.begin();it != resultList.end(); ++it) {
		try {
			it->get();
		} catch (AMDA::AMDA_exception & e) {
			LOG4CXX_ERROR( _logger,	"Error resume: " << traitException(result,e));
			++error;
		} catch (...) {
			result = AMDA_ERROR_UNKNOWN;
		}
	}

	// Attempt to terminate each param output.
	for(ParamOutputList::iterator it = _paramOutputList.begin(); it != _paramOutputList.end(); ++it) {
		try {
			(*it)->terminate();
		} catch (...) {
			// Nothing to do
		}
	}

	if ( error != 0) {
		if ( lNbTraitement == 1) {
			BOOST_THROW_EXCEPTION( AMDA::AMDA_exception() << AMDA::errno_code(result));
		} else {
			BOOST_THROW_EXCEPTION( AMDA::AMDA_exception() << AMDA::errno_code(AMDA_PARAM_SOME_ERR));
		}
	}

 }

	TimeIntervalListSPtr ParameterManager::getInputIntervals() {
		return _timeIntervalList;
	}

897858c8   Benjamin Renard   Support multi TT ...
417
418
	void ParameterManager::addInputInterval(double pStartTime, double pStopTime, int pIndex, std::string& pttPath, std::string& pttName, int pttTotalIntervals)  {
		_timeIntervalList->push_back(TimeInterval(pStartTime, pStopTime, pIndex, pttPath, pttName, pttTotalIntervals));
fbe3c2bb   Benjamin Renard   First commit
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
	}

	void ParameterManager::addInputInterval(const TimeInterval& pTimeInterval) {
		_timeIntervalList->push_back(pTimeInterval);
	}

	void ParameterManager::addInputIntervalDataList(const int pIndex, const std::string& pDataKey, const std::vector<std::string>& dataList)
	{
		_timeIntervalDataList[pIndex][pDataKey] = dataList;
	}

	std::vector<std::string>& ParameterManager::getInputIntervalDataList(const int pIndex, const std::string& pDataKey)
	{
		return _timeIntervalDataList[pIndex][pDataKey];
	}

	/**
	 * get the computed gap size
	 */
	double ParameterManager::getComputedGapSize(double gapThreshold, double minSampling)
	{
		return gapThreshold * minSampling;
	}

} /* namespace Parameters */
} /* namespace AMDA */