Blame view

src/InternLib/ProcessStandard.cc 15.7 KB
fbe3c2bb   Benjamin Renard   First commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
45
46
47
48
49
50
51
52
53
54
55
/*
 * ProcessStandard.cc
 *
 *  Created on: Oct 31, 2012
 *      Author: f.casimir
 */


#include <stdlib.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>


#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <limits.h>

#include <boost/shared_ptr.hpp>
#include <boost/algorithm/string.hpp>

#include "DicError.hh"

#include "Helper.hh"

#include "Parameter.hh"
#include "Operation.hh"
#include "ParamData.hh"
#include "DataTypeMath.hh"
#include "ServicesServer.hh"
#include "DataWriter.hh"
#include "ParameterManager.hh"

#include "ProcessStandard.hh"

using namespace std;
using namespace boost;
using namespace log4cxx;


namespace AMDA {
namespace Parameters {


ProcessStandard::ProcessStandard(Parameter & parameter) :
		MultiParamProcess_CRTP<ProcessStandard>(parameter),
				_fct(""),
				_symboleName("processFct"),
				_handle(NULL),
				_processInit(NULL),
0614f36d   Benjamin Renard   Check compilation...
56
				_compilVersion(NULL),
fbe3c2bb   Benjamin Renard   First commit
57
58
59
60
61
62
63
64
65
66
67
68
69
				_accesDirect(false),
				_alreadyParsed(false),
				  _propertiesList("app.properties"),
				  _timeOfSoFile(0) {
				_servicesServer = ServicesServer::getInstance();
}



ProcessStandard::ProcessStandard(const ProcessStandard & pProcess, Parameter &parameter) :
		MultiParamProcess_CRTP<ProcessStandard>(pProcess,parameter),
				_fct(pProcess._fct),
				_symboleName(pProcess._symboleName),
a9f0f983   Benjamin Renard   Fix copy construc...
70
				_handle(pProcess._handle),
fbe3c2bb   Benjamin Renard   First commit
71
				_processInit(pProcess._processInit),
a9f0f983   Benjamin Renard   Fix copy construc...
72
				_compilVersion(pProcess._compilVersion),
fbe3c2bb   Benjamin Renard   First commit
73
74
				_accesDirect(pProcess._accesDirect),
				_alreadyParsed(pProcess._alreadyParsed),
a9f0f983   Benjamin Renard   Fix copy construc...
75
76
77
78
				_propertiesList(pProcess._propertiesList),
				_timeOfSoFile(pProcess._timeOfSoFile) {
	_servicesServer = ServicesServer::getInstance();
	establishConnection();
fbe3c2bb   Benjamin Renard   First commit
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
}

ProcessStandard::~ProcessStandard() {
	this->_paramData.reset();
	delete _operation; _operation = NULL;
	closeDynamicLib(); //Attention au mémoire allouer par cette lib
}

void ProcessStandard::establishConnection() {
	if ( ! _expression.empty()) {
		parse();
		MultiParamProcess::establishConnection();
	}
}

TimeStamp ProcessStandard::init() {
a9f0f983   Benjamin Renard   Fix copy construc...
95
96
97
98
99
	_fileNameRoot = _parameter.getId();
	size_t index = _fileNameRoot.find('/');
	if(index != string::npos) {
		_fileNameRoot.at(index) = '_';
	}
854a7fcf   Benjamin Renard   First implementat...
100
101
102
103
104
105
106
107
108
109
110
111
112
113

	std::string soDir;
	if (isUserProcess() && !_propertiesList["app.process.userlib"].empty()) {
		soDir = _propertiesList["app.process.userlib"];
	}
	else {
		soDir = _propertiesList["app.process.lib"];
	}

	if (soDir.empty() || (AMDA::Helpers::Helper::mkdir(soDir.c_str()) != 0)) {
		BOOST_THROW_EXCEPTION(Process_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg(std::string("ProcessStandard::init - Cannot create detination lib dir")));
	}

	_fileNameSO = soDir + "/" + _fileNameRoot + ".so";
fbe3c2bb   Benjamin Renard   First commit
114
115
116
117
118
119
120

	TimeStamp time = MultiParamProcess::init();
	if(mustGenerated(time)) {
		generateCppfile();
		time = generateSoFile();
	}
	loadDynamicLib();
0614f36d   Benjamin Renard   Check compilation...
121
122
123
124
125
126
	if ((_compilVersion == NULL) || ((*_compilVersion)() != PROCESS_STANDARD_COMPIL_VERSION)) {
		closeDynamicLib();
		generateCppfile();
		time = generateSoFile();
		loadDynamicLib();
	}
fbe3c2bb   Benjamin Renard   First commit
127
128
129
130
	// Create Operation && ParamData
	(*_processInit)(this);
	_paramData->setMinSampling(_minSampling);

aa8a8e5f   Benjamin Renard   Auto compute gap ...
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
	ParameterManager& lParameterManager = _parameter.getParameterManager();
	double minGapSize = NAN;

	for (auto param : _paramNameList) {
		ParameterSPtr& parameter = param.second.first;
		double crtGapSize = lParameterManager.getComputedGapSize(parameter->getGapThreshold(),parameter->getDataWriterTemplate()->getMinSampling());
		if (isNAN(minGapSize) || (crtGapSize < minGapSize))
			minGapSize = crtGapSize;
	}

	if (!isNAN(minGapSize)) {
		double computedGapThreshold = minGapSize / _minSampling;
		_parameter.setGapThreshold(computedGapThreshold);
	}

fbe3c2bb   Benjamin Renard   First commit
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
	return time;

}

double ProcessStandard::getMinSampling()
{
	if ( ! _expression.empty())
		parse();
	return MultiParamProcess_CRTP::getMinSampling();
}

#define MIN(a,b) (((a) < (b)) ? (a) :(b) )


void ProcessStandard::parse() {
	if (_alreadyParsed)
		return;

	ParameterManager& lParameterManager = _parameter.getParameterManager();

	_parser.process(_expression);
	const Parser::ListParameterName& lParameterNameList = _parser.getListParameterName();

	// Temporary Parameter creation
	const Parser::ListProcessName& processNameList = _parser.getListProcessName();
	Parser::ListProcessName::const_iterator lProcessIt = processNameList.begin();
	for (;lProcessIt!=processNameList.end();++lProcessIt) {
		ParameterSPtr lParameter;
		if ( lParameterManager.addParameter(&_parameter,lProcessIt->first,lParameter)) {
			Process* lProcess = _servicesServer->getProcess(lProcessIt->second.name,*lParameter.get());
			if ( lProcess) {
				lProcess->setExpression(lProcessIt->second.expression);
				lProcess->setAttributList(lProcessIt->second.attribut);
854a7fcf   Benjamin Renard   First implementat...
179
				lProcess->setIsUserProcess(isUserProcess());
fbe3c2bb   Benjamin Renard   First commit
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
				boost::shared_ptr<DataWriter> dataWriter = boost::shared_ptr<DataWriter>(static_cast<DataWriter *>(lProcess));
				lParameter->setDataWriter(dataWriter);
				_paramNameList[lProcessIt->first].first = lParameterManager.getParameter(lProcessIt->first);
			} else {
				stringstream lError;  lError << "Process: '" << lProcessIt->second.name << "' not found";
				LOG4CXX_ERROR(_logger, lError.str());
			    BOOST_THROW_EXCEPTION(Process_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg(lError.str()));
			}
		} else {
			_paramNameList[lProcessIt->first].first = lParameterManager.getParameter(lProcessIt->first);
		}
	}

	for (Parser::ListParameterName::const_iterator it = lParameterNameList.begin(); it != lParameterNameList.end(); ++it) {
		ParameterSPtr lParameter = lParameterManager.getParameter(*it);
		if (lParameter.get()) {
			_paramNameList[*it].first = lParameter;
			// Here we have a broken link in parameter chaining so create link.
			// Child is already creating before linking it to its parent parameter.
			_parameter.addParameter(lParameter);
		} else {
			LOG4CXX_ERROR(_logger, "parse of expression: \""<<_expression << "\" are impossible!");
	    	BOOST_THROW_EXCEPTION(Process_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg(std::string("Error to parse expression: ")+_expression));
		}
	}

	_alreadyParsed = true;
}

bool ProcessStandard::findInclude(std::string name, std::string &path, std::vector<std::string> &listSo)  {
	path = this->_propertiesList["app.plugin"] + "/" + name;
	bool find = false;
	if (AMDA::Helpers::Helper::getMatchFiles(path.c_str(), listSo, ".*.(so|a)$") == 0) {
		find = true;
	}
	return find;
}



bool ProcessStandard::mustGenerated(TimeStamp timeDepend) {
	bool recompile = false;
0614f36d   Benjamin Renard   Check compilation...
222

fbe3c2bb   Benjamin Renard   First commit
223
224
225
226
227
	if(_timeOfSoFile == 0) {
		if(_signatureTrigger != "") {
			// _signatureTrigger must be a name of xml parameter file
			timeDepend = std::max(TimeStamp(AMDA::Helpers::Helper::dateOfFile(_signatureTrigger.c_str())), timeDepend) ;
		}
fbe3c2bb   Benjamin Renard   First commit
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
		for(Parser::ListFctName::iterator it =  _parser.getListFctName().begin(); it != _parser.getListFctName().end(); ++it) {
			std::string path;
			SoList listLib;
			if(findInclude(*it, path, listLib)) {
				string includePath = path +"/" + *it;
				timeDepend = std::max(timeDepend, TimeStamp(AMDA::Helpers::Helper::dateOfFile((includePath + ".hh").c_str())));
				_streamIncludeFile << "#include \""<< *it <<".hh\" "; _streamIncludeFile << endl;
				_PluginList[path] = listLib;
			}
		}
		//return 0 if file not exist
		 _timeOfSoFile = AMDA::Helpers::Helper::dateOfFile(_fileNameSO.c_str());
		 recompile = (_timeOfSoFile <=  timeDepend);
	}

	return recompile;
}


	void ProcessStandard::generateCppfile() {

		LOG4CXX_INFO(_logger, "generation of compilation expression: " << _parser.getFormulaCc())

	size_t bufSize = _propertiesList["app.process.src"].size() + _fileNameRoot.size()  + 8;
	char  *buf = new char[bufSize];
	strcpy(buf,  (_propertiesList["app.process.src"] + "/" + _fileNameRoot).c_str());
	strcat(buf, "XXXXXX");
	 _workingDiretory = mkdtemp(buf);
	 delete[] buf;
	_fileNameC =_workingDiretory + "/" + _fileNameRoot + ".cc";

	fstream fileC(_fileNameC.c_str(), ios_base::out);

	fileC << " /*  File generated by AMDA */  " << endl;
	// Include
	fileC << "#include \"Operation.hh\" " << endl;
	fileC << "#include \"ServicesServer.hh\" " << endl;
	fileC << "#include \"Parameter.hh\"" << endl;
	fileC << "#include \"ParamData.hh\"" << endl;
	fileC << "#include \"DataTypeMath.hh\"" << endl;
	fileC << "#include \"ProcessStandard.hh\"" << endl;
	fileC << endl;
	fileC << "#include \"TimeInterval.hh\"" << endl;
	fileC << endl;
95430126   Benjamin Renard   Add constants def...
272
273
	fileC << "#include \"AMDA_constants.hh\"" << endl;
	fileC << endl;
fbe3c2bb   Benjamin Renard   First commit
274
275
276
277
278
279
280
	fileC << endl;
	fileC.flush();

	fileC << _streamIncludeFile.str();
	fileC << endl;
	fileC << endl;

0614f36d   Benjamin Renard   Check compilation...
281
282
283
	fileC << "#define PROCESS_STANDARD_COMPIL_VERSION " << PROCESS_STANDARD_COMPIL_VERSION << endl;
	fileC << endl;
	fileC << endl;
fbe3c2bb   Benjamin Renard   First commit
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298

	for (ParameterList::iterator it = _paramNameList.begin(); it != _paramNameList.end(); ++it) {
		ParamDataSPtr p = it->second.first->getParamData(this);
		string lParamTypeName = " _T_" + boost::to_upper_copy(it->first) ;
		string  lElementTypeName = lParamTypeName + "_Element_Type";
		fileC << "typedef "<<  p->getElementType() << " " << lElementTypeName <<";"; fileC << endl;
		fileC << "typedef "<<  p->getParamDataType() << " " << lParamTypeName <<";"; fileC << endl;
	}
	fileC.flush();

	// Process Init Signature
	stringstream lProcessInit;
	lProcessInit << "void processInit(AMDA::Parameters::ProcessStandard *pProcess)";
	fileC << "extern \"C\" " << lProcessInit.str() << ";" ;
	fileC		<< endl;
0614f36d   Benjamin Renard   Check compilation...
299
	fileC << "extern \"C\" int compilVersion();" << endl;
fbe3c2bb   Benjamin Renard   First commit
300
301
302
303
304
	fileC << endl;
	fileC << endl;

	//Declaration Calss
	fileC << "template <typename TParamData>" << endl;
78249cd2   Benjamin Renard   Fix special chara...
305
306
307
308
	ParameterManager& lParameterManager = this->_parameter.getParameterManager();
	std::string fixedParamId = this->_parameter.getId();
	lParameterManager.applyParamIdCorrection(fixedParamId);
	string lClassName =  "_Operation" + fixedParamId;
fbe3c2bb   Benjamin Renard   First commit
309
310
311
312
313
314
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
	fileC << "class " <<lClassName <<" : public AMDA::Parameters::Operation {"; fileC<< endl;
	fileC << "public:" << endl;
	fileC << endl;
	//Costructor
	fileC << lClassName <<"(AMDA::Parameters::ProcessStandard &pProcess) : AMDA::Parameters::Operation(pProcess), _processStandard(pProcess), _paramOutput(new TParamData())" << endl;
	fileC << "{" << endl;
	fileC << "	_paramDataOutput = _paramOutput;" << endl;
	for (ParameterList::iterator it = _paramNameList.begin(); it != _paramNameList.end(); ++it) {
		fileC <<"	" << it->first << " = dynamic_cast<_T_"<< boost::to_upper_copy(it->first)<< "*>( pProcess.getParameterList()[\""<< it->first << "\"].first->getParamData(&pProcess).get());"; fileC  << endl;
	}
	fileC << "}" << endl;
	fileC << endl;
	fileC.flush();

	//Destructor
	fileC << "virtual ~" <<lClassName<<"() {}"; fileC  << endl;
	fileC << endl;

	//Wirte methode
	fileC << "void  write(AMDA::Parameters::ParamDataIndexInfo &pParamDataIndexInfo) {" << endl;
	fileC << "	for (unsigned int index = pParamDataIndexInfo._startIndex; index < pParamDataIndexInfo._startIndex + pParamDataIndexInfo._nbDataToProcess; ++index) {" << endl;
	fileC << "		_paramOutput->pushTime(_processStandard.getParameterList().begin()->second.first->getParamData(&_process)->getTime(index));" << endl;
	fileC << "		_paramOutput->push("<< _parser.getFormulaCc() <<");"; fileC << endl;
	fileC << "	}" << endl;
	fileC << "}" << endl;
	fileC << endl;
	//attributs
	fileC << "AMDA::Parameters::ProcessStandard&  _processStandard;" << endl;
	fileC << "TParamData *_paramOutput;" << endl;
	fileC << "AMDA::Parameters::ParamDataIndexInfo _paramDataIndexInfo;" << endl;
	fileC.flush();

	for (ParameterList::iterator it = _paramNameList.begin(); it != _paramNameList.end(); ++it) {
		ParamDataSPtr p = it->second.first->getParamData(this);
		fileC << " _T_" + boost::to_upper_copy(it->first) <<" *" << it->first <<";"  << endl;
	}
	fileC << endl;
	//fin class
	fileC << "};" << endl;


	fileC << lProcessInit.str() << "{"<< endl;
22bc7b60   Benjamin Renard   Fix a bug with ex...
351
352
	fileC << "  typedef decltype(AMDA::Parameters::generate(" << _parser.getContructorCc() <<")) _Generated_Type;" << endl;
	fileC << "	pProcess->setOperation(new " << lClassName<<"<_Generated_Type>(*pProcess));" ; fileC  << endl;
fbe3c2bb   Benjamin Renard   First commit
353
354
355
356
	fileC << "	pProcess->getParamData().reset( pProcess->getOperation()->getParamOutput());" << endl;
	fileC << "}" << endl;
	fileC << endl;

0614f36d   Benjamin Renard   Check compilation...
357
358
359
360
361
	fileC << "int compilVersion() {"<< endl;
	fileC << "	return PROCESS_STANDARD_COMPIL_VERSION;"<< endl;
	fileC << "}" << endl;
	fileC << endl;

fbe3c2bb   Benjamin Renard   First commit
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
417
418
419
420
421
	fileC.close();

}

TimeStamp ProcessStandard::generateSoFile() {
	string pathInclude;
	string pathlib;

	string fileNameSOTmp = _workingDiretory + "/" + _fileNameRoot + ".so";

	for(PluginList::iterator it =_PluginList.begin() ; it != _PluginList.end(); ++it) {
		pathInclude += " -I" +it->first;
		pathlib += " -L"+it->first;
		pathlib += " -Wl,-rpath,"+it->first;

		for(SoList::iterator itlib =it->second.begin() ; itlib != it->second.end(); ++itlib) {
			//pathlib = string(pwd) + "/" + it->first + "/" + *itlib;
			string name = *itlib;
			unsigned int posLastPoint = name.rfind('.');
			string rootLib = itlib->substr(3, posLastPoint - 3);
			pathlib += " -l"+rootLib;
		}
	}
	string command = _propertiesList["app.process.CXX_COMPILER"]
		//+ "-DParameters_EXPORTS" +
		+ " " + _propertiesList["app.process.CMAKE_CXX_FLAGS"]
		+ " " + _propertiesList["app.process.INCLUDE"]
		+ " " + pathInclude
		+ " " + _propertiesList["app.process.LIB"]
		+ " " + pathlib
		+ " -shared -Wl,-soname," + fileNameSOTmp  + " -o "
		+ fileNameSOTmp + " " + _fileNameC;

	if(AMDA::Helpers::Helper::SystemCommand(command, _logger)) {
		BOOST_THROW_EXCEPTION(Process_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg(std::string("Error to parse expression: ")+_expression));
	}
	//move file
	int status = rename(fileNameSOTmp.c_str(), _fileNameSO.c_str());
	if(status != 0) {
		LOG4CXX_ERROR(_logger, "rename  of : " << fileNameSOTmp << " in " << _fileNameSO <<" End with an error " << WTERMSIG(status));
    	BOOST_THROW_EXCEPTION(Process_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg("rename  of : " + fileNameSOTmp + " in " + _fileNameSO + " End with an error "));
	}

	//if not Debug environment
	const char* lBuildType=getenv("BUILD_TYPE");
	if(lBuildType && strcmp(lBuildType, "Debug")) {
		status = unlink(_fileNameC.c_str());
		if(_workingDiretory != ".") {
			status += rmdir(_workingDiretory.c_str());
		}
		if(status != 0) {
				LOG4CXX_WARN(_logger, "Suppression of temporary files: " << _fileNameC  <<" End with an error " << WTERMSIG(status));
			}
	}

	return AMDA::Helpers::Helper::dateOfFile(_fileNameSO.c_str());
}

//std::string ProcessStandard::_env(getenv("LD_LIBRARY_PATH"));
void ProcessStandard::loadDynamicLib() {
fbe3c2bb   Benjamin Renard   First commit
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
    std::string lLib = _fileNameSO;
//    /*set LD_LIBRARY_PATH */
//    string lLD_LIBRARY_PATH = "LD_LIBRARY_PATH=";
//	for(PluginList::iterator it =_PluginList.begin() ; it != _PluginList.end(); ++it) {
//		lLD_LIBRARY_PATH += it->first + ":";
//	}
//    lLD_LIBRARY_PATH +=  _env;
//	LOG4CXX_INFO(_logger, "add in environment: " << lLD_LIBRARY_PATH);
//	putenv(const_cast<char *>( lLD_LIBRARY_PATH.c_str()));


    _handle = dlopen(lLib.c_str(), RTLD_LAZY);
    if (!_handle) {
    	LOG4CXX_ERROR(_logger,dlerror());
    	BOOST_THROW_EXCEPTION(Process_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg(std::string("Error to parse expression: ")+_expression));
    }

    dlerror();    /* Clear any existing error */
    *(void **) (&_processInit) = dlsym(_handle, "processInit");

a9f0f983   Benjamin Renard   Fix copy construc...
442
443
444
    char *error = dlerror();
    if (error != NULL)  {
    	LOG4CXX_ERROR(_logger,error);
fbe3c2bb   Benjamin Renard   First commit
445
446
447
    	BOOST_THROW_EXCEPTION(Process_exception() << AMDA::errno_code(AMDA_PROCESS_ERR) << AMDA::ex_msg(std::string("Error to parse expression: ")+_expression));
    }

0614f36d   Benjamin Renard   Check compilation...
448
449
    dlerror();    /* Clear any existing error */
    *(void **) (&_compilVersion) = dlsym(_handle, "compilVersion");
fbe3c2bb   Benjamin Renard   First commit
450

a9f0f983   Benjamin Renard   Fix copy construc...
451
452
453
    error = dlerror();
    if (error != NULL)  {
	LOG4CXX_WARN(_logger,error);
0614f36d   Benjamin Renard   Check compilation...
454
    }
fbe3c2bb   Benjamin Renard   First commit
455
456
457
458
459
460
461
462
463
464
}

void ProcessStandard::closeDynamicLib() {

    if(_handle) dlclose(_handle);

}

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