1 // Copyright (C) 2006-2016 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include "yacsconfig.h"
21 #include "RuntimeSALOME.hxx"
24 #include "Exception.hxx"
25 #include "Executor.hxx"
26 #include "parsers.hxx"
27 #include "VisitorSalomeSaveState.hxx"
28 #include "VisitorSaveSalomeSchema.hxx"
29 #include "LoadState.hxx"
30 #include "Dispatcher.hxx"
31 #include "LinkInfo.hxx"
34 #include "SALOME_NamingService.hxx"
35 #include "SALOME_ModuleCatalog.hh"
36 #include "Basics_Utils.hxx"
44 #if defined WIN32 || defined __APPLE__
49 using YACS::YACSLoader;
50 using namespace YACS::ENGINE;
54 // --- use of glibc argp interface for parsing unix-style arguments
56 const char *argp_program_version ="driver V0.1";
57 const char *argp_program_bug_address ="<nepal@nepal.edf.fr>";
58 static char doc[] ="driver -- a SALOME YACS graph executor";
59 static char args_doc[] = "graph.xml";
61 #if defined WIN32 || defined __APPLE__
63 static struct argp_option options[] =
65 {"display", 'd', "level", 0, "Display dot files: 0=never to 3=very often (default 0)"},
66 {"verbose", 'v', 0, 0, "Produce verbose output" },
67 {"stop-on-error", 's', 0, 0, "Stop on first error" },
68 {"dump-on-error", 'e', "file", OPTION_ARG_OPTIONAL, "Stop on first error and dump state"},
69 {"dump-final", 'f', "file", OPTION_ARG_OPTIONAL, "dump final state"},
70 {"dump", 'g', "nbsec", OPTION_ARG_OPTIONAL, "dump state"},
71 {"load-state", 'l', "file", 0, "Load State from a previous partial execution"},
72 {"save-xml-schema", 'x', "file", OPTION_ARG_OPTIONAL, "dump xml schema"},
73 {"shutdown", 't', "level", 0, "Shutdown the schema: 0=no shutdown to 3=full shutdown (default 1)"},
74 {"reset", 'r', "level", 0, "Reset the schema before execution: 0=nothing, 1=reset error nodes to ready state (default 0)"},
75 {"kill-port", 'k', "port", 0, "Kill Salome application running on the specified port if the driver process is killed (with SIGINT or SIGTERM)"},
76 {"init_port", 'i', "value", OPTION_ARG_OPTIONAL, "Initialisation value of a port, specified as bloc.node.port=value."},
95 std::list<std::string> init_ports;
109 std::string LoadedDriverPluginLibrary;
110 void *HandleOnLoadedPlugin=0;
111 void (*DefineCustomObservers)(YACS::ENGINE::Dispatcher *, YACS::ENGINE::ComposedNode *, YACS::ENGINE::Executor *)=0;
112 void (*CleanUpObservers) ()=0;
114 void LoadObserversPluginIfAny(YACS::ENGINE::ComposedNode *rootNode, YACS::ENGINE::Executor *executor)
116 static const char SYMBOLE_NAME_1[]="DefineCustomObservers";
117 static const char SYMBOLE_NAME_2[]="CleanUpObservers";
119 Dispatcher *disp(Dispatcher::getDispatcher());
121 throw YACS::Exception("Internal error ! No dispatcher !");
122 char *yacsDriverPluginPath(getenv("YACS_DRIVER_PLUGIN_PATH"));
123 if(!yacsDriverPluginPath)
125 void *handle(dlopen(yacsDriverPluginPath, RTLD_LAZY | RTLD_GLOBAL));
128 std::string message(dlerror());
129 std::ostringstream oss; oss << "Error during load of \"" << yacsDriverPluginPath << "\" defined by the YACS_DRIVER_PLUGIN_PATH env var : " << message;
130 throw YACS::Exception(oss.str());
132 DefineCustomObservers=(void (*)(YACS::ENGINE::Dispatcher *, YACS::ENGINE::ComposedNode *, YACS::ENGINE::Executor *))(dlsym(handle,SYMBOLE_NAME_1));
133 if(!DefineCustomObservers)
135 std::ostringstream oss; oss << "Error during load of \"" << yacsDriverPluginPath << "\" ! Library has been correctly loaded but symbol " << SYMBOLE_NAME_1 << " does not exists !";
136 throw YACS::Exception(oss.str());
138 CleanUpObservers=(void (*)())(dlsym(handle,SYMBOLE_NAME_2));
139 if(!CleanUpObservers)
141 std::ostringstream oss; oss << "Error during load of \"" << yacsDriverPluginPath << "\" ! Library has been correctly loaded but symbol " << SYMBOLE_NAME_2 << " does not exists !";
142 throw YACS::Exception(oss.str());
144 HandleOnLoadedPlugin=handle;
145 DefineCustomObservers(disp,rootNode,executor);
149 void UnLoadObserversPluginIfAny()
152 if(HandleOnLoadedPlugin)
155 dlclose(HandleOnLoadedPlugin);
160 #if defined WIN32 || defined __APPLE__
165 parse_opt (int key, char *arg, struct argp_state *state)
167 #if defined WIN32 || defined __APPLE__
169 // Get the input argument from argp_parse, which we
170 // know is a pointer to our arguments structure.
171 struct arguments *myArgs = (arguments*)state->input;
176 myArgs->display = atoi(arg);
179 myArgs->shutdown = atoi(arg);
182 myArgs->reset = atoi(arg);
193 myArgs->dumpErrorFile = arg;
195 myArgs->dumpErrorFile = (char *)"dumpErrorState.xml";
199 myArgs->finalDump = arg;
201 myArgs->finalDump = (char *)"finalDumpState.xml";
205 myArgs->dump = atoi(arg);
210 myArgs->loadState = arg;
214 myArgs->xmlSchema = arg;
216 myArgs->xmlSchema = (char *)"saveSchema.xml";
219 myArgs->killPort = atoi(arg);
223 myArgs->init_ports.push_back(std::string(arg));
227 if (state->arg_num >=1) // Too many arguments.
229 myArgs->args[state->arg_num] = arg;
233 if (state->arg_num < 1) // Not enough arguments.
238 return ARGP_ERR_UNKNOWN;
245 #if defined WIN32 || defined __APPLE__
247 static struct argp argp = { options, parse_opt, args_doc, doc };
250 void timer(std::string msg)
252 #if defined WIN32 || defined __APPLE__
255 gettimeofday(&tv,NULL);
256 long t=tv.tv_sec*1000+tv.tv_usec/1000;
258 gettimeofday(&tv,NULL);
259 std::cerr << msg << tv.tv_sec*1000+tv.tv_usec/1000-t0 << " ms" << std::endl;
264 static struct arguments myArgs;
266 void Handler(int theSigId)
271 //if requested save state
272 bool isFinalDump = (strlen(myArgs.finalDump) != 0);
275 YACS::ENGINE::VisitorSalomeSaveState vst(p);
276 vst.openFileDump(myArgs.finalDump);
280 //if requested shutdown schema
281 if(myArgs.shutdown < 999)
283 p->shutdown(myArgs.shutdown);
288 ostringstream command;
289 command << "killSalomeWithPort.py " << myArgs.killPort;
290 int status = system(command.str().c_str());
292 cerr << "Salome application on port " << myArgs.killPort << " is killed" << endl;
294 cerr << "Error: Can't kill Salome application on port " << myArgs.killPort << endl;
299 void * dumpState(void *arg)
301 thread_st *st = (thread_st*)arg;
302 YACS::StatesForNode state = p->getEffectiveState();
303 while((state != YACS::DONE) && (state != YACS::LOADFAILED) && (state != YACS::EXECFAILED) && (state != YACS::INTERNALERR) && (state != YACS::DISABLED) && (state != YACS::FAILED) && (state != YACS::ERROR)){
309 string cmd = "touch " + st->lockFile;
311 YACS::ENGINE::VisitorSalomeSaveState vst(p);
312 vst.openFileDump(st->dumpFile);
315 cmd = "rm -f " + st->lockFile;
317 state = p->getEffectiveState();
324 typedef void (*sighandler_t)(int);
325 sighandler_t setsig(int sig, sighandler_t handler)
327 struct sigaction context, ocontext;
328 context.sa_handler = handler;
329 sigemptyset(&context.sa_mask);
330 context.sa_flags = 0;
331 if (sigaction(sig, &context, &ocontext) == -1)
333 return ocontext.sa_handler;
337 bool parse_init_port(const std::string& input, std::string& node, std::string& port, std::string& value)
340 size_t pos_eq = input.find('=');
341 if(pos_eq == std::string::npos || pos_eq == input.size())
343 value = input.substr(pos_eq+1);
344 size_t pos_dot = input.rfind('.', pos_eq);
345 if(!pos_dot || pos_dot == std::string::npos || pos_dot >= pos_eq-1)
347 port = input.substr(pos_dot+1, pos_eq-pos_dot-1);
348 node = input.substr(0, pos_dot);
352 int main (int argc, char* argv[])
359 myArgs.dumpErrorFile= (char *)"";
360 myArgs.finalDump = (char *)"";
362 myArgs.loadState = (char *)"";
363 myArgs.xmlSchema = (char *)"";
367 myArgs.init_ports.clear();
369 // Parse our arguments; every option seen by parse_opt will be reflected in arguments.
370 #if defined WIN32 || defined __APPLE__
372 argp_parse (&argp, argc, argv, 0, 0, &myArgs);
373 std::cerr << "graph = " << myArgs.args[0];
374 std::cerr << " options: display=" << myArgs.display;
375 std::cerr << " verbose="<<myArgs.verbose;
376 std::cerr << " stop-on-error=" << myArgs.stop;
377 std::cerr << " shutdown=" << myArgs.shutdown;
378 std::cerr << " reset=" << myArgs.reset;
380 std::cerr << " kill-port=" << myArgs.killPort;
382 std::cerr << " dumpErrorFile=" << myArgs.dumpErrorFile << std::endl;
384 std::cerr << std::endl;
385 std::list<std::string>::const_iterator it;
386 for(it=myArgs.init_ports.begin(); it != myArgs.init_ports.end(); it++)
388 std::cerr << (*it) << std::endl;
393 setsig(SIGINT,&Handler);
394 setsig(SIGTERM,&Handler);
398 long flags = RuntimeSALOME::UsePython + RuntimeSALOME::UseCorba + RuntimeSALOME::UseXml + \
399 RuntimeSALOME::UseCpp + RuntimeSALOME::UseSalome;
400 RuntimeSALOME::setRuntime(flags, argc, argv);
402 // Try to load the session catalog if it exists
405 YACS::ENGINE::RuntimeSALOME* runTime = YACS::ENGINE::getSALOMERuntime();
406 CORBA::ORB_ptr orb = runTime->getOrb();
409 SALOME_NamingService namingService(orb);
410 CORBA::Object_var obj = namingService.Resolve("/Kernel/ModulCatalog");
411 SALOME_ModuleCatalog::ModuleCatalog_var aModuleCatalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj);
412 if (! CORBA::is_nil(aModuleCatalog))
414 CORBA::String_var anIOR = orb->object_to_string( aModuleCatalog );
415 YACS::ENGINE::Catalog* aCatalog = runTime->loadCatalog( "session", anIOR.in() );
416 runTime->addCatalog(aCatalog);
420 catch(ServiceUnreachable& e)
422 //Naming service unreachable don't add catalog
430 timer("Elapsed time before load: ");
431 p=loader.load(myArgs.args[0]);
434 std::cerr << "The imported file is probably not a YACS schema file" << std::endl;
437 // Initialize the ports
438 for(std::list<std::string>::iterator it=myArgs.init_ports.begin(); it != myArgs.init_ports.end(); it++)
440 std::string node, port, value;
441 if(parse_init_port((*it), node, port, value))
443 std::cerr << "Initialization node=" << node
445 << " value=" << value << std::endl;
447 std::string init_state;
448 init_state = p->setInPortValue(node, port, value);
449 if(value.compare(init_state))
451 std::cerr << "Error on initialization:" << init_state << std::endl;
457 std::cerr << "Error on parsing initialization string:" << (*it) << std::endl;
462 //Get the parser logger
463 Logger* logger=p->getLogger("parser");
464 //Print errors logged if any
465 if(!logger->isEmpty())
467 std::cerr << "The imported file has errors" << std::endl;
468 std::cerr << logger->getStr() << std::endl;
470 //Don't execute if there are errors
471 if(logger->hasErrors())
475 std::string report=p->getErrorReport();
476 std::cerr << "The schema is not valid and can not be executed" << std::endl;
477 std::cerr << report << std::endl;
480 Runtime* r=YACS::ENGINE::getRuntime();
481 Dispatcher* disp=Dispatcher::getDispatcher();
487 timer("Elapsed time after load: ");
491 std::string report=p->getErrorReport();
492 std::cerr << "The schema is not valid and can not be executed" << std::endl;
493 std::cerr << report << std::endl;
494 Runtime* r=YACS::ENGINE::getRuntime();
495 Dispatcher* disp=Dispatcher::getDispatcher();
501 timer("Elapsed time after validation: ");
504 LinkInfo info(LinkInfo::ALL_DONT_STOP);
505 p->checkConsistency(info);
506 if(info.areWarningsOrErrors())
508 std::cerr << "The schema is not consistent and can not be executed" << std::endl;
509 std::cerr << info.getGlobalRepr() << std::endl;
510 Runtime* r=YACS::ENGINE::getRuntime();
511 Dispatcher* disp=Dispatcher::getDispatcher();
517 timer("Elapsed time after check consistency: ");
520 bool isXmlSchema = (strlen(myArgs.xmlSchema) != 0);
523 YACS::ENGINE::VisitorSaveSalomeSchema vss(p);
524 vss.openFileSchema(myArgs.xmlSchema);
526 vss.closeFileSchema();
529 bool fromScratch = (strlen(myArgs.loadState) == 0);
534 stateParser* rootParser = new stateParser();
535 stateLoader myStateLoader(rootParser, p);
536 myStateLoader.parse(myArgs.loadState);
539 p->resetState(myArgs.reset);
545 if (strlen(myArgs.dumpErrorFile) >0)
546 executor.setStopOnError(true, myArgs.dumpErrorFile);
548 executor.setStopOnError(false, myArgs.dumpErrorFile);
552 std::ofstream f("toto");
557 bool isDump = (myArgs.dump != 0);
561 thread_st *st = new thread_st;
562 st->nbsec = myArgs.dump;
563 st->dumpFile = string("dumpState_") + myArgs.args[0];
564 string rootFile = st->dumpFile.substr(0,st->dumpFile.find("."));
565 st->lockFile = rootFile + ".lock";
566 pthread_create(&th,NULL,&dumpState,(void*)st);
568 LoadObserversPluginIfAny(p,&executor);
569 cerr << "+++++++++++++++++++ start calculation +++++++++++++++++++" << endl;
570 executor.RunW(p,myArgs.display, fromScratch);
571 cerr << "+++++++++++++++++++ end calculation +++++++++++++++++++" << endl;
572 cerr << "Proc state : " << Node::getStateName(p->getEffectiveState()) << endl;
573 timer("Elapsed time after execution: ");
575 // Return 0 if SCHEMA OK
576 // Return 1 for YACS ERROR (EXCEPTION NOT CATCHED)
577 // Return 2 for YACS SCHEMA ERROR/FAILED
578 int return_value = 0;
580 if(p->getEffectiveState() != YACS::DONE)
582 std::string report=p->getErrorReport();
583 std::cerr << "Execution has ended in error" << std::endl;
584 std::cerr << report << std::endl;
590 std::ofstream g("titi");
597 pthread_join(th,NULL);
600 bool isFinalDump = (strlen(myArgs.finalDump) != 0);
603 YACS::ENGINE::VisitorSalomeSaveState vst(p);
604 vst.openFileDump(myArgs.finalDump);
608 if(myArgs.shutdown < 999)
610 p->shutdown(myArgs.shutdown);
613 Runtime* r=YACS::ENGINE::getRuntime();
614 Dispatcher* disp=Dispatcher::getDispatcher();
618 UnLoadObserversPluginIfAny();
621 catch (YACS::Exception& e)
623 cerr << "Caught a YACS exception" << endl;
624 cerr << e.what() << endl;
625 Runtime* r=YACS::ENGINE::getRuntime();
626 Dispatcher* disp=Dispatcher::getDispatcher();
632 catch (const std::ios_base::failure&)
634 cerr << "Caught an io failure exception" << endl;
637 catch(CORBA::SystemException& ex)
639 cerr << "Caught a CORBA::SystemException.:" << __FILE__ << ":" << __LINE__ << ":" ;
642 CORBA::TypeCode_var tc = tmp.type();
643 const char *p = tc->name();
651 catch(omniORB::fatalException& fe)
653 cerr << "Caught omniORB::fatalException:" << endl;
654 cerr << " file: " << fe.file() << endl;
655 cerr << " line: " << fe.line() << endl;
656 cerr << " mesg: " << fe.errmsg() << endl;
661 cerr << "Caught unknown exception." << endl;