1 // Copyright (C) 2006-2021 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"
32 #include "ObserverAsPlugin.hxx"
36 #include "KernelBasis.hxx"
37 #include "SALOME_Launcher.hxx"
38 #include "ServiceUnreachable.hxx"
39 #include "SALOME_NamingService_Wrapper.hxx"
40 #include "SALOME_NamingService.hxx"
41 #include "SALOME_ModuleCatalog.hh"
42 #include "Basics_Utils.hxx"
50 #if defined WIN32 || defined __APPLE__
55 using YACS::YACSLoader;
56 using namespace YACS::ENGINE;
60 // --- use of glibc argp interface for parsing unix-style arguments
62 const char *argp_program_version ="driver V0.1";
63 const char *argp_program_bug_address ="<nepal@nepal.edf.fr>";
64 static char doc[] ="driver -- a SALOME YACS graph executor";
65 static char args_doc[] = "graph.xml";
67 #if defined WIN32 || defined __APPLE__
69 static struct argp_option options[] =
71 {"display", 'd', "level", 0, "Display dot files: 0=never to 3=very often (default 0)"},
72 {"verbose", 'v', 0, 0, "Produce verbose output" },
73 {"stop-on-error", 's', 0, 0, "Stop on first error" },
74 {"dump-on-error", 'e', "file", OPTION_ARG_OPTIONAL, "Stop on first error and dump state"},
75 {"dump-final", 'f', "file", OPTION_ARG_OPTIONAL, "dump final state"},
76 {"dump", 'g', "nbsec", OPTION_ARG_OPTIONAL, "dump state"},
77 {"load-state", 'l', "file", 0, "Load State from a previous partial execution"},
78 {"save-xml-schema", 'x', "file", OPTION_ARG_OPTIONAL, "dump xml schema"},
79 {"shutdown", 't', "level", 0, "Shutdown the schema: 0=no shutdown to 3=full shutdown (default 1)"},
80 {"reset", 'r', "level", 0, "Reset the schema before execution: 0=nothing, 1=reset error nodes to ready state (default 0)"},
81 {"kill-port", 'k', "port", 0, "Kill Salome application running on the specified port if the driver process is killed (with SIGINT or SIGTERM)"},
82 {"init_port", 'i', "value", OPTION_ARG_OPTIONAL, "Initialisation value of a port, specified as bloc.node.port=value."},
101 std::list<std::string> init_ports;
110 #if defined WIN32 || defined __APPLE__
115 parse_opt (int key, char *arg, struct argp_state *state)
117 #if defined WIN32 || defined __APPLE__
119 // Get the input argument from argp_parse, which we
120 // know is a pointer to our arguments structure.
121 struct arguments *myArgs = (arguments*)state->input;
126 myArgs->display = atoi(arg);
129 myArgs->shutdown = atoi(arg);
132 myArgs->reset = atoi(arg);
143 myArgs->dumpErrorFile = arg;
145 myArgs->dumpErrorFile = (char *)"dumpErrorState.xml";
149 myArgs->finalDump = arg;
151 myArgs->finalDump = (char *)"finalDumpState.xml";
155 myArgs->dump = atoi(arg);
160 myArgs->loadState = arg;
164 myArgs->xmlSchema = arg;
166 myArgs->xmlSchema = (char *)"saveSchema.xml";
169 myArgs->killPort = atoi(arg);
173 myArgs->init_ports.push_back(std::string(arg));
177 if (state->arg_num >=1) // Too many arguments.
179 myArgs->args[state->arg_num] = arg;
183 if (state->arg_num < 1) // Not enough arguments.
188 return ARGP_ERR_UNKNOWN;
195 #if defined WIN32 || defined __APPLE__
197 static struct argp argp = { options, parse_opt, args_doc, doc };
200 void timer(std::string msg)
202 #if defined WIN32 || defined __APPLE__
205 gettimeofday(&tv,NULL);
206 long t=tv.tv_sec*1000+tv.tv_usec/1000;
208 gettimeofday(&tv,NULL);
209 std::cerr << msg << tv.tv_sec*1000+tv.tv_usec/1000-t0 << " ms" << std::endl;
214 static struct arguments myArgs;
216 void Handler(int theSigId)
221 //if requested save state
222 bool isFinalDump = (strlen(myArgs.finalDump) != 0);
225 YACS::ENGINE::VisitorSalomeSaveState vst(p);
226 vst.openFileDump(myArgs.finalDump);
230 //if requested shutdown schema
231 if(myArgs.shutdown < 999)
233 p->shutdown(myArgs.shutdown);
238 ostringstream command;
239 command << "killSalomeWithPort.py " << myArgs.killPort;
240 int status = system(command.str().c_str());
242 cerr << "Salome application on port " << myArgs.killPort << " is killed" << endl;
244 cerr << "Error: Can't kill Salome application on port " << myArgs.killPort << endl;
249 void * dumpState(void *arg)
251 thread_st *st = (thread_st*)arg;
252 YACS::StatesForNode state = p->getEffectiveState();
253 while((state != YACS::DONE) && (state != YACS::LOADFAILED) && (state != YACS::EXECFAILED) && (state != YACS::INTERNALERR) && (state != YACS::DISABLED) && (state != YACS::FAILED) && (state != YACS::ERROR)){
259 string cmd = "touch " + st->lockFile;
261 YACS::ENGINE::VisitorSalomeSaveState vst(p);
262 vst.openFileDump(st->dumpFile);
265 cmd = "rm -f " + st->lockFile;
267 state = p->getEffectiveState();
274 typedef void (*sighandler_t)(int);
275 sighandler_t setsig(int sig, sighandler_t handler)
277 struct sigaction context, ocontext;
278 context.sa_handler = handler;
279 sigemptyset(&context.sa_mask);
280 context.sa_flags = 0;
281 if (sigaction(sig, &context, &ocontext) == -1)
283 return ocontext.sa_handler;
287 bool parse_init_port(const std::string& input, std::string& node, std::string& port, std::string& value)
290 size_t pos_eq = input.find('=');
291 if(pos_eq == std::string::npos || pos_eq == input.size())
293 value = input.substr(pos_eq+1);
294 size_t pos_dot = input.rfind('.', pos_eq);
295 if(!pos_dot || pos_dot == std::string::npos || pos_dot >= pos_eq-1)
297 port = input.substr(pos_dot+1, pos_eq-pos_dot-1);
298 node = input.substr(0, pos_dot);
305 KERNEL::getLauncherSA();
308 int main (int argc, char* argv[])
315 myArgs.dumpErrorFile= (char *)"";
316 myArgs.finalDump = (char *)"";
318 myArgs.loadState = (char *)"";
319 myArgs.xmlSchema = (char *)"";
320 myArgs.shutdown = 10;
323 myArgs.init_ports.clear();
325 // Parse our arguments; every option seen by parse_opt will be reflected in arguments.
326 #if defined WIN32 || defined __APPLE__
328 argp_parse (&argp, argc, argv, 0, 0, &myArgs);
329 std::cerr << "graph = " << myArgs.args[0];
330 std::cerr << " options: display=" << myArgs.display;
331 std::cerr << " verbose="<<myArgs.verbose;
332 std::cerr << " stop-on-error=" << myArgs.stop;
333 std::cerr << " shutdown=" << myArgs.shutdown;
334 std::cerr << " reset=" << myArgs.reset;
336 std::cerr << " kill-port=" << myArgs.killPort;
338 std::cerr << " dumpErrorFile=" << myArgs.dumpErrorFile << std::endl;
340 std::cerr << std::endl;
341 std::list<std::string>::const_iterator it;
342 for(it=myArgs.init_ports.begin(); it != myArgs.init_ports.end(); it++)
344 std::cerr << (*it) << std::endl;
349 setsig(SIGINT,&Handler);
350 setsig(SIGTERM,&Handler);
356 long flags = RuntimeSALOME::UsePython + RuntimeSALOME::UseCorba + RuntimeSALOME::UseXml + \
357 RuntimeSALOME::UseCpp + RuntimeSALOME::UseSalome;
358 RuntimeSALOME::setRuntime(flags, argc, argv);
360 // Try to load the session catalog if it exists
363 YACS::ENGINE::RuntimeSALOME* runTime = YACS::ENGINE::getSALOMERuntime();
364 runTime->loadModulCatalog();
365 CORBA::ORB_ptr orb = runTime->getOrb();
368 SALOME_NamingService_Wrapper namingService(orb);
369 //SALOME_NamingService namingService(orb);
370 CORBA::Object_var obj = namingService.Resolve("/Kernel/ModulCatalog");
371 SALOME_ModuleCatalog::ModuleCatalog_var aModuleCatalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj);
372 if (! CORBA::is_nil(aModuleCatalog))
374 CORBA::String_var anIOR = orb->object_to_string( aModuleCatalog );
375 YACS::ENGINE::Catalog* aCatalog = runTime->loadCatalog( "session", anIOR.in() );
376 runTime->addCatalog(aCatalog);
380 catch(ServiceUnreachable& e)
382 //Naming service unreachable don't add catalog
390 timer("Elapsed time before load: ");
391 p=loader.load(myArgs.args[0]);
394 std::cerr << "The imported file is probably not a YACS schema file" << std::endl;
397 // Initialize the ports
398 for(std::list<std::string>::iterator it=myArgs.init_ports.begin(); it != myArgs.init_ports.end(); it++)
400 std::string node, port, value;
401 if(parse_init_port((*it), node, port, value))
403 std::cerr << "Initialization node=" << node
405 << " value=" << value << std::endl;
407 std::string init_state;
408 init_state = p->setInPortValue(node, port, value);
409 if(value.compare(init_state))
411 std::cerr << "Error on initialization:" << init_state << std::endl;
417 std::cerr << "Error on parsing initialization string:" << (*it) << std::endl;
422 //Get the parser logger
423 Logger* logger=p->getLogger("parser");
424 //Print errors logged if any
425 if(!logger->isEmpty())
427 std::cerr << "The imported file has errors" << std::endl;
428 std::cerr << logger->getStr() << std::endl;
430 //Don't execute if there are errors
431 if(logger->hasErrors())
435 std::string report=p->getErrorReport();
436 std::cerr << "The schema is not valid and can not be executed" << std::endl;
437 std::cerr << report << std::endl;
440 Runtime* r=YACS::ENGINE::getRuntime();
441 Dispatcher* disp=Dispatcher::getDispatcher();
447 timer("Elapsed time after load: ");
451 std::string report=p->getErrorReport();
452 std::cerr << "The schema is not valid and can not be executed" << std::endl;
453 std::cerr << report << std::endl;
454 Runtime* r=YACS::ENGINE::getRuntime();
455 Dispatcher* disp=Dispatcher::getDispatcher();
461 timer("Elapsed time after validation: ");
464 LinkInfo info(LinkInfo::ALL_DONT_STOP);
465 p->checkConsistency(info);
466 if(info.areWarningsOrErrors())
468 std::cerr << "The schema is not consistent and can not be executed" << std::endl;
469 std::cerr << info.getGlobalRepr() << std::endl;
470 Runtime* r=YACS::ENGINE::getRuntime();
471 Dispatcher* disp=Dispatcher::getDispatcher();
477 timer("Elapsed time after check consistency: ");
480 bool isXmlSchema = (strlen(myArgs.xmlSchema) != 0);
483 YACS::ENGINE::VisitorSaveSalomeSchema vss(p);
484 vss.openFileSchema(myArgs.xmlSchema);
486 vss.closeFileSchema();
489 bool fromScratch = (strlen(myArgs.loadState) == 0);
494 stateParser* rootParser = new stateParser();
495 stateLoader myStateLoader(rootParser, p);
496 myStateLoader.parse(myArgs.loadState);
499 p->resetState(myArgs.reset);
505 if (strlen(myArgs.dumpErrorFile) >0)
506 executor.setStopOnError(true, myArgs.dumpErrorFile);
508 executor.setStopOnError(false, myArgs.dumpErrorFile);
512 std::ofstream f("toto");
517 bool isDump = (myArgs.dump != 0);
521 thread_st *st = new thread_st;
522 st->nbsec = myArgs.dump;
523 st->dumpFile = string("dumpState_") + myArgs.args[0];
524 string rootFile = st->dumpFile.substr(0,st->dumpFile.find("."));
525 st->lockFile = rootFile + ".lock";
526 pthread_create(&th,NULL,&dumpState,(void*)st);
528 YACS::ENGINE::LoadObserversPluginIfAny(p,&executor);
529 cerr << "+++++++++++++++++++ start calculation +++++++++++++++++++" << endl;
530 executor.RunW(p,myArgs.display, fromScratch);
531 cerr << "+++++++++++++++++++ end calculation +++++++++++++++++++" << endl;
532 cerr << "Proc state : " << Node::getStateName(p->getEffectiveState()) << endl;
533 timer("Elapsed time after execution: ");
535 // Return 0 if SCHEMA OK
536 // Return 1 for YACS ERROR (EXCEPTION NOT CATCHED)
537 // Return 2 for YACS SCHEMA ERROR/FAILED
538 int return_value = 0;
540 if(p->getEffectiveState() != YACS::DONE)
542 std::string report=p->getErrorReport();
543 std::cerr << "Execution has ended in error" << std::endl;
544 std::cerr << report << std::endl;
550 std::ofstream g("titi");
557 pthread_join(th,NULL);
560 bool isFinalDump = (strlen(myArgs.finalDump) != 0);
563 YACS::ENGINE::VisitorSalomeSaveState vst(p);
564 vst.openFileDump(myArgs.finalDump);
568 if(myArgs.shutdown < 999)
570 p->shutdown(myArgs.shutdown);
573 Runtime* r=YACS::ENGINE::getRuntime();
574 Dispatcher* disp=Dispatcher::getDispatcher();
578 YACS::ENGINE::UnLoadObserversPluginIfAny();
581 catch (YACS::Exception& e)
583 cerr << "Caught a YACS exception" << endl;
584 cerr << e.what() << endl;
585 Runtime* r=YACS::ENGINE::getRuntime();
586 Dispatcher* disp=Dispatcher::getDispatcher();
592 catch (const std::ios_base::failure&)
594 cerr << "Caught an io failure exception" << endl;
597 catch(CORBA::SystemException& ex)
599 cerr << "Caught a CORBA::SystemException.:" << __FILE__ << ":" << __LINE__ << ":" ;
602 CORBA::TypeCode_var tc = tmp.type();
603 const char *p = tc->name();
611 catch(omniORB::fatalException& fe)
613 cerr << "Caught omniORB::fatalException:" << endl;
614 cerr << " file: " << fe.file() << endl;
615 cerr << " line: " << fe.line() << endl;
616 cerr << " mesg: " << fe.errmsg() << endl;
621 cerr << "Caught unknown exception." << endl;