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"
35 #include "KernelBasis.hxx"
36 #include "SALOME_Launcher.hxx"
37 #include "ServiceUnreachable.hxx"
38 #include "SALOME_NamingService_Wrapper.hxx"
39 #include "SALOME_ModuleCatalog.hh"
40 #include "Basics_Utils.hxx"
48 #if defined WIN32 || defined __APPLE__
53 using YACS::YACSLoader;
54 using namespace YACS::ENGINE;
58 // --- use of glibc argp interface for parsing unix-style arguments
60 const char *argp_program_version ="driver V0.1";
61 const char *argp_program_bug_address ="<nepal@nepal.edf.fr>";
62 static char doc[] ="driver -- a SALOME YACS graph executor";
63 static char args_doc[] = "graph.xml";
65 #if defined WIN32 || defined __APPLE__
67 static struct argp_option options[] =
69 {"display", 'd', "level", 0, "Display dot files: 0=never to 3=very often (default 0)"},
70 {"verbose", 'v', 0, 0, "Produce verbose output" },
71 {"stop-on-error", 's', 0, 0, "Stop on first error" },
72 {"dump-on-error", 'e', "file", OPTION_ARG_OPTIONAL, "Stop on first error and dump state"},
73 {"dump-final", 'f', "file", OPTION_ARG_OPTIONAL, "dump final state"},
74 {"dump", 'g', "nbsec", OPTION_ARG_OPTIONAL, "dump state"},
75 {"load-state", 'l', "file", 0, "Load State from a previous partial execution"},
76 {"save-xml-schema", 'x', "file", OPTION_ARG_OPTIONAL, "dump xml schema"},
77 {"shutdown", 't', "level", 0, "Shutdown the schema: 0=no shutdown to 3=full shutdown (default 1)"},
78 {"reset", 'r', "level", 0, "Reset the schema before execution: 0=nothing, 1=reset error nodes to ready state (default 0)"},
79 {"kill-port", 'k', "port", 0, "Kill Salome application running on the specified port if the driver process is killed (with SIGINT or SIGTERM)"},
80 {"init_port", 'i', "value", OPTION_ARG_OPTIONAL, "Initialisation value of a port, specified as bloc.node.port=value."},
99 std::list<std::string> init_ports;
108 #if defined WIN32 || defined __APPLE__
113 parse_opt (int key, char *arg, struct argp_state *state)
115 #if defined WIN32 || defined __APPLE__
117 // Get the input argument from argp_parse, which we
118 // know is a pointer to our arguments structure.
119 struct arguments *myArgs = (arguments*)state->input;
124 myArgs->display = atoi(arg);
127 myArgs->shutdown = atoi(arg);
130 myArgs->reset = atoi(arg);
141 myArgs->dumpErrorFile = arg;
143 myArgs->dumpErrorFile = (char *)"dumpErrorState.xml";
147 myArgs->finalDump = arg;
149 myArgs->finalDump = (char *)"finalDumpState.xml";
153 myArgs->dump = atoi(arg);
158 myArgs->loadState = arg;
162 myArgs->xmlSchema = arg;
164 myArgs->xmlSchema = (char *)"saveSchema.xml";
167 myArgs->killPort = atoi(arg);
171 myArgs->init_ports.push_back(std::string(arg));
175 if (state->arg_num >=1) // Too many arguments.
177 myArgs->args[state->arg_num] = arg;
181 if (state->arg_num < 1) // Not enough arguments.
186 return ARGP_ERR_UNKNOWN;
193 #if defined WIN32 || defined __APPLE__
195 static struct argp argp = { options, parse_opt, args_doc, doc };
198 void timer(std::string msg)
200 #if defined WIN32 || defined __APPLE__
203 gettimeofday(&tv,NULL);
204 long t=tv.tv_sec*1000+tv.tv_usec/1000;
206 gettimeofday(&tv,NULL);
207 std::cerr << msg << tv.tv_sec*1000+tv.tv_usec/1000-t0 << " ms" << std::endl;
212 static struct arguments myArgs;
214 void Handler(int theSigId)
219 //if requested save state
220 bool isFinalDump = (strlen(myArgs.finalDump) != 0);
223 YACS::ENGINE::VisitorSalomeSaveState vst(p);
224 vst.openFileDump(myArgs.finalDump);
228 //if requested shutdown schema
229 if(myArgs.shutdown < 999)
231 p->shutdown(myArgs.shutdown);
236 ostringstream command;
237 command << "killSalomeWithPort.py " << myArgs.killPort;
238 int status = system(command.str().c_str());
240 cerr << "Salome application on port " << myArgs.killPort << " is killed" << endl;
242 cerr << "Error: Can't kill Salome application on port " << myArgs.killPort << endl;
247 void * dumpState(void *arg)
249 thread_st *st = (thread_st*)arg;
250 YACS::StatesForNode state = p->getEffectiveState();
251 while((state != YACS::DONE) && (state != YACS::LOADFAILED) && (state != YACS::EXECFAILED) && (state != YACS::INTERNALERR) && (state != YACS::DISABLED) && (state != YACS::FAILED) && (state != YACS::ERROR)){
257 string cmd = "touch " + st->lockFile;
259 YACS::ENGINE::VisitorSalomeSaveState vst(p);
260 vst.openFileDump(st->dumpFile);
263 cmd = "rm -f " + st->lockFile;
265 state = p->getEffectiveState();
272 typedef void (*sighandler_t)(int);
273 sighandler_t setsig(int sig, sighandler_t handler)
275 struct sigaction context, ocontext;
276 context.sa_handler = handler;
277 sigemptyset(&context.sa_mask);
278 context.sa_flags = 0;
279 if (sigaction(sig, &context, &ocontext) == -1)
281 return ocontext.sa_handler;
285 bool parse_init_port(const std::string& input, std::string& node, std::string& port, std::string& value)
288 size_t pos_eq = input.find('=');
289 if(pos_eq == std::string::npos || pos_eq == input.size())
291 value = input.substr(pos_eq+1);
292 size_t pos_dot = input.rfind('.', pos_eq);
293 if(!pos_dot || pos_dot == std::string::npos || pos_dot >= pos_eq-1)
295 port = input.substr(pos_dot+1, pos_eq-pos_dot-1);
296 node = input.substr(0, pos_dot);
303 KERNEL::getLauncherSA();
306 int main (int argc, char* argv[])
313 myArgs.dumpErrorFile= (char *)"";
314 myArgs.finalDump = (char *)"";
316 myArgs.loadState = (char *)"";
317 myArgs.xmlSchema = (char *)"";
321 myArgs.init_ports.clear();
323 // Parse our arguments; every option seen by parse_opt will be reflected in arguments.
324 #if defined WIN32 || defined __APPLE__
326 argp_parse (&argp, argc, argv, 0, 0, &myArgs);
327 std::cerr << "graph = " << myArgs.args[0];
328 std::cerr << " options: display=" << myArgs.display;
329 std::cerr << " verbose="<<myArgs.verbose;
330 std::cerr << " stop-on-error=" << myArgs.stop;
331 std::cerr << " shutdown=" << myArgs.shutdown;
332 std::cerr << " reset=" << myArgs.reset;
334 std::cerr << " kill-port=" << myArgs.killPort;
336 std::cerr << " dumpErrorFile=" << myArgs.dumpErrorFile << std::endl;
338 std::cerr << std::endl;
339 std::list<std::string>::const_iterator it;
340 for(it=myArgs.init_ports.begin(); it != myArgs.init_ports.end(); it++)
342 std::cerr << (*it) << std::endl;
347 setsig(SIGINT,&Handler);
348 setsig(SIGTERM,&Handler);
354 long flags = RuntimeSALOME::UsePython + RuntimeSALOME::UseCorba + RuntimeSALOME::UseXml + \
355 RuntimeSALOME::UseCpp + RuntimeSALOME::UseSalome;
356 RuntimeSALOME::setRuntime(flags, argc, argv);
358 // Try to load the session catalog if it exists
361 YACS::ENGINE::RuntimeSALOME* runTime = YACS::ENGINE::getSALOMERuntime();
362 CORBA::ORB_ptr orb = runTime->getOrb();
365 SALOME_NamingService_Wrapper namingService(orb);
366 CORBA::Object_var obj = namingService.Resolve("/Kernel/ModulCatalog");
367 SALOME_ModuleCatalog::ModuleCatalog_var aModuleCatalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj);
368 if (! CORBA::is_nil(aModuleCatalog))
370 CORBA::String_var anIOR = orb->object_to_string( aModuleCatalog );
371 YACS::ENGINE::Catalog* aCatalog = runTime->loadCatalog( "session", anIOR.in() );
372 runTime->addCatalog(aCatalog);
376 catch(ServiceUnreachable& e)
378 //Naming service unreachable don't add catalog
386 timer("Elapsed time before load: ");
387 p=loader.load(myArgs.args[0]);
390 std::cerr << "The imported file is probably not a YACS schema file" << std::endl;
393 // Initialize the ports
394 for(std::list<std::string>::iterator it=myArgs.init_ports.begin(); it != myArgs.init_ports.end(); it++)
396 std::string node, port, value;
397 if(parse_init_port((*it), node, port, value))
399 std::cerr << "Initialization node=" << node
401 << " value=" << value << std::endl;
403 std::string init_state;
404 init_state = p->setInPortValue(node, port, value);
405 if(value.compare(init_state))
407 std::cerr << "Error on initialization:" << init_state << std::endl;
413 std::cerr << "Error on parsing initialization string:" << (*it) << std::endl;
418 //Get the parser logger
419 Logger* logger=p->getLogger("parser");
420 //Print errors logged if any
421 if(!logger->isEmpty())
423 std::cerr << "The imported file has errors" << std::endl;
424 std::cerr << logger->getStr() << std::endl;
426 //Don't execute if there are errors
427 if(logger->hasErrors())
431 std::string report=p->getErrorReport();
432 std::cerr << "The schema is not valid and can not be executed" << std::endl;
433 std::cerr << report << std::endl;
436 Runtime* r=YACS::ENGINE::getRuntime();
437 Dispatcher* disp=Dispatcher::getDispatcher();
443 timer("Elapsed time after load: ");
447 std::string report=p->getErrorReport();
448 std::cerr << "The schema is not valid and can not be executed" << std::endl;
449 std::cerr << report << std::endl;
450 Runtime* r=YACS::ENGINE::getRuntime();
451 Dispatcher* disp=Dispatcher::getDispatcher();
457 timer("Elapsed time after validation: ");
460 LinkInfo info(LinkInfo::ALL_DONT_STOP);
461 p->checkConsistency(info);
462 if(info.areWarningsOrErrors())
464 std::cerr << "The schema is not consistent and can not be executed" << std::endl;
465 std::cerr << info.getGlobalRepr() << std::endl;
466 Runtime* r=YACS::ENGINE::getRuntime();
467 Dispatcher* disp=Dispatcher::getDispatcher();
473 timer("Elapsed time after check consistency: ");
476 bool isXmlSchema = (strlen(myArgs.xmlSchema) != 0);
479 YACS::ENGINE::VisitorSaveSalomeSchema vss(p);
480 vss.openFileSchema(myArgs.xmlSchema);
482 vss.closeFileSchema();
485 bool fromScratch = (strlen(myArgs.loadState) == 0);
490 stateParser* rootParser = new stateParser();
491 stateLoader myStateLoader(rootParser, p);
492 myStateLoader.parse(myArgs.loadState);
495 p->resetState(myArgs.reset);
501 if (strlen(myArgs.dumpErrorFile) >0)
502 executor.setStopOnError(true, myArgs.dumpErrorFile);
504 executor.setStopOnError(false, myArgs.dumpErrorFile);
508 std::ofstream f("toto");
513 bool isDump = (myArgs.dump != 0);
517 thread_st *st = new thread_st;
518 st->nbsec = myArgs.dump;
519 st->dumpFile = string("dumpState_") + myArgs.args[0];
520 string rootFile = st->dumpFile.substr(0,st->dumpFile.find("."));
521 st->lockFile = rootFile + ".lock";
522 pthread_create(&th,NULL,&dumpState,(void*)st);
524 YACS::ENGINE::LoadObserversPluginIfAny(p,&executor);
525 cerr << "+++++++++++++++++++ start calculation +++++++++++++++++++" << endl;
526 executor.RunW(p,myArgs.display, fromScratch);
527 cerr << "+++++++++++++++++++ end calculation +++++++++++++++++++" << endl;
528 cerr << "Proc state : " << Node::getStateName(p->getEffectiveState()) << endl;
529 timer("Elapsed time after execution: ");
531 // Return 0 if SCHEMA OK
532 // Return 1 for YACS ERROR (EXCEPTION NOT CATCHED)
533 // Return 2 for YACS SCHEMA ERROR/FAILED
534 int return_value = 0;
536 if(p->getEffectiveState() != YACS::DONE)
538 std::string report=p->getErrorReport();
539 std::cerr << "Execution has ended in error" << std::endl;
540 std::cerr << report << std::endl;
546 std::ofstream g("titi");
553 pthread_join(th,NULL);
556 bool isFinalDump = (strlen(myArgs.finalDump) != 0);
559 YACS::ENGINE::VisitorSalomeSaveState vst(p);
560 vst.openFileDump(myArgs.finalDump);
564 if(myArgs.shutdown < 999)
566 p->shutdown(myArgs.shutdown);
569 Runtime* r=YACS::ENGINE::getRuntime();
570 Dispatcher* disp=Dispatcher::getDispatcher();
574 YACS::ENGINE::UnLoadObserversPluginIfAny();
577 catch (YACS::Exception& e)
579 cerr << "Caught a YACS exception" << endl;
580 cerr << e.what() << endl;
581 Runtime* r=YACS::ENGINE::getRuntime();
582 Dispatcher* disp=Dispatcher::getDispatcher();
588 catch (const std::ios_base::failure&)
590 cerr << "Caught an io failure exception" << endl;
593 catch(CORBA::SystemException& ex)
595 cerr << "Caught a CORBA::SystemException.:" << __FILE__ << ":" << __LINE__ << ":" ;
598 CORBA::TypeCode_var tc = tmp.type();
599 const char *p = tc->name();
607 catch(omniORB::fatalException& fe)
609 cerr << "Caught omniORB::fatalException:" << endl;
610 cerr << " file: " << fe.file() << endl;
611 cerr << " line: " << fe.line() << endl;
612 cerr << " mesg: " << fe.errmsg() << endl;
617 cerr << "Caught unknown exception." << endl;