1 // Copyright (C) 2006-2022 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"
34 #include "KernelBasis.hxx"
35 #include "SALOME_Launcher.hxx"
36 #include "ServiceUnreachable.hxx"
37 #include "SALOME_NamingService_Wrapper.hxx"
38 #include "SALOME_NamingService.hxx"
39 #include "SALOME_ModuleCatalog.hh"
40 #include "SALOMESDS_DataServerManager.hxx"
41 #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 void shutdownServers()
308 // shutdown data server scopes
311 YACS::ENGINE::RuntimeSALOME* runTime = YACS::ENGINE::getSALOMERuntime();
312 runTime->loadModulCatalog();
313 CORBA::ORB_ptr orb = runTime->getOrb();
316 SALOME_NamingService_Wrapper namingService(orb);
317 CORBA::Object_var objDSM(namingService.Resolve(SALOMESDS::DataServerManager::NAME_IN_NS));
318 SALOME::DataServerManager_var dsm(SALOME::DataServerManager::_narrow(objDSM));
319 if ( !CORBA::is_nil(dsm) )
320 dsm->shutdownScopes();
323 catch(const CORBA::Exception& )
325 // ignore and continue
327 catch(ServiceUnreachable& e)
329 // ignore and continue
333 int main (int argc, char* argv[])
340 myArgs.dumpErrorFile= (char *)"";
341 myArgs.finalDump = (char *)"";
343 myArgs.loadState = (char *)"";
344 myArgs.xmlSchema = (char *)"";
345 myArgs.shutdown = 10;
348 myArgs.init_ports.clear();
350 // Parse our arguments; every option seen by parse_opt will be reflected in arguments.
351 #if defined WIN32 || defined __APPLE__
353 argp_parse (&argp, argc, argv, 0, 0, &myArgs);
354 std::cerr << "graph = " << myArgs.args[0];
355 std::cerr << " options: display=" << myArgs.display;
356 std::cerr << " verbose="<<myArgs.verbose;
357 std::cerr << " stop-on-error=" << myArgs.stop;
358 std::cerr << " shutdown=" << myArgs.shutdown;
359 std::cerr << " reset=" << myArgs.reset;
361 std::cerr << " kill-port=" << myArgs.killPort;
363 std::cerr << " dumpErrorFile=" << myArgs.dumpErrorFile << std::endl;
365 std::cerr << std::endl;
366 std::list<std::string>::const_iterator it;
367 for(it=myArgs.init_ports.begin(); it != myArgs.init_ports.end(); it++)
369 std::cerr << (*it) << std::endl;
374 setsig(SIGINT,&Handler);
375 setsig(SIGTERM,&Handler);
381 long flags = RuntimeSALOME::UsePython + RuntimeSALOME::UseCorba + RuntimeSALOME::UseXml + \
382 RuntimeSALOME::UseCpp + RuntimeSALOME::UseSalome;
383 RuntimeSALOME::setRuntime(flags, argc, argv);
385 // Try to load the session catalog if it exists
388 YACS::ENGINE::RuntimeSALOME* runTime = YACS::ENGINE::getSALOMERuntime();
389 runTime->loadModulCatalog();
390 CORBA::ORB_ptr orb = runTime->getOrb();
393 SALOME_NamingService_Wrapper namingService(orb);
394 CORBA::Object_var obj = namingService.Resolve("/Kernel/ModulCatalog");
395 SALOME_ModuleCatalog::ModuleCatalog_var aModuleCatalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj);
396 if (! CORBA::is_nil(aModuleCatalog))
398 CORBA::String_var anIOR = orb->object_to_string( aModuleCatalog );
399 YACS::ENGINE::Catalog* aCatalog = runTime->loadCatalog( "session", anIOR.in() );
400 runTime->addCatalog(aCatalog);
404 catch(ServiceUnreachable& e)
406 //Naming service unreachable don't add catalog
414 timer("Elapsed time before load: ");
415 p=loader.load(myArgs.args[0]);
418 std::cerr << "The imported file is probably not a YACS schema file" << std::endl;
421 // Initialize the ports
422 for(std::list<std::string>::iterator it=myArgs.init_ports.begin(); it != myArgs.init_ports.end(); it++)
424 std::string node, port, value;
425 if(parse_init_port((*it), node, port, value))
427 std::cerr << "Initialization node=" << node
429 << " value=" << value << std::endl;
431 std::string init_state;
432 init_state = p->setInPortValue(node, port, value);
433 if(value.compare(init_state))
435 std::cerr << "Error on initialization:" << init_state << std::endl;
441 std::cerr << "Error on parsing initialization string:" << (*it) << std::endl;
446 //Get the parser logger
447 Logger* logger=p->getLogger("parser");
448 //Print errors logged if any
449 if(!logger->isEmpty())
451 std::cerr << "The imported file has errors" << std::endl;
452 std::cerr << logger->getStr() << std::endl;
454 //Don't execute if there are errors
455 if(logger->hasErrors())
459 std::string report=p->getErrorReport();
460 std::cerr << "The schema is not valid and can not be executed" << std::endl;
461 std::cerr << report << std::endl;
464 Runtime* r=YACS::ENGINE::getRuntime();
465 Dispatcher* disp=Dispatcher::getDispatcher();
471 timer("Elapsed time after load: ");
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;
478 Runtime* r=YACS::ENGINE::getRuntime();
479 Dispatcher* disp=Dispatcher::getDispatcher();
485 timer("Elapsed time after validation: ");
488 LinkInfo info(LinkInfo::ALL_DONT_STOP);
489 p->checkConsistency(info);
490 if(info.areWarningsOrErrors())
492 std::cerr << "The schema is not consistent and can not be executed" << std::endl;
493 std::cerr << info.getGlobalRepr() << std::endl;
494 Runtime* r=YACS::ENGINE::getRuntime();
495 Dispatcher* disp=Dispatcher::getDispatcher();
501 timer("Elapsed time after check consistency: ");
504 bool isXmlSchema = (strlen(myArgs.xmlSchema) != 0);
507 YACS::ENGINE::VisitorSaveSalomeSchema vss(p);
508 vss.openFileSchema(myArgs.xmlSchema);
510 vss.closeFileSchema();
513 bool fromScratch = (strlen(myArgs.loadState) == 0);
518 stateParser* rootParser = new stateParser();
519 stateLoader myStateLoader(rootParser, p);
520 myStateLoader.parse(myArgs.loadState);
523 p->resetState(myArgs.reset);
530 if (strlen(myArgs.dumpErrorFile) >0)
531 executor.setStopOnError(true, myArgs.dumpErrorFile);
533 executor.setStopOnError(false, myArgs.dumpErrorFile);
537 std::ofstream f("toto");
542 bool isDump = (myArgs.dump != 0);
546 thread_st *st = new thread_st;
547 st->nbsec = myArgs.dump;
548 st->dumpFile = string("dumpState_") + myArgs.args[0];
549 string rootFile = st->dumpFile.substr(0,st->dumpFile.find("."));
550 st->lockFile = rootFile + ".lock";
551 pthread_create(&th,NULL,&dumpState,(void*)st);
553 YACS::ENGINE::LoadObserversPluginIfAny(p,&executor);
554 cerr << "+++++++++++++++++++ start calculation +++++++++++++++++++" << endl;
555 executor.RunW(p,myArgs.display, fromScratch);
556 cerr << "+++++++++++++++++++ end calculation +++++++++++++++++++" << endl;
557 cerr << "Proc state : " << Node::getStateName(p->getEffectiveState()) << endl;
558 timer("Elapsed time after execution: ");
560 // Return 0 if SCHEMA OK
561 // Return 1 for YACS ERROR (EXCEPTION NOT CATCHED)
562 // Return 2 for YACS SCHEMA ERROR/FAILED
563 int return_value = 0;
565 if(p->getEffectiveState() != YACS::DONE)
567 std::string report=p->getErrorReport();
568 std::cerr << "Execution has ended in error" << std::endl;
569 std::cerr << report << std::endl;
575 std::ofstream g("titi");
582 pthread_join(th,NULL);
585 bool isFinalDump = (strlen(myArgs.finalDump) != 0);
588 YACS::ENGINE::VisitorSalomeSaveState vst(p);
589 vst.openFileDump(myArgs.finalDump);
593 if(myArgs.shutdown < 999)
595 p->shutdown(myArgs.shutdown);
599 Runtime* r=YACS::ENGINE::getRuntime();
600 Dispatcher* disp=Dispatcher::getDispatcher();
604 YACS::ENGINE::UnLoadObserversPluginIfAny();
607 catch (YACS::Exception& e)
609 cerr << "Caught a YACS exception" << endl;
610 cerr << e.what() << endl;
611 Runtime* r=YACS::ENGINE::getRuntime();
612 Dispatcher* disp=Dispatcher::getDispatcher();
618 catch (const std::ios_base::failure&)
620 cerr << "Caught an io failure exception" << endl;
623 catch(CORBA::SystemException& ex)
625 cerr << "Caught a CORBA::SystemException.:" << __FILE__ << ":" << __LINE__ << ":" ;
628 CORBA::TypeCode_var tc = tmp.type();
629 const char *p = tc->name();
637 catch(omniORB::fatalException& fe)
639 cerr << "Caught omniORB::fatalException:" << endl;
640 cerr << " file: " << fe.file() << endl;
641 cerr << " line: " << fe.line() << endl;
642 cerr << " mesg: " << fe.errmsg() << endl;
647 cerr << "Caught unknown exception." << endl;