Salome HOME
81919420e534e45f76d3fa0eea952709d3665d95
[modules/yacs.git] / src / yacsloader / driver.cxx
1 // Copyright (C) 2006-2021  CEA/DEN, EDF R&D
2 //
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.
7 //
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.
12 //
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
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "yacsconfig.h"
21 #include "RuntimeSALOME.hxx"
22 #include "Proc.hxx"
23 #include "Logger.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"
33
34 #ifdef SALOME_KERNEL
35
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"
43 #endif
44
45 #include <iostream>
46 #include <fstream>
47 #include <signal.h>
48 #include <list>
49
50 #if defined WIN32 || defined __APPLE__
51 #else
52 #include <argp.h>
53 #endif
54
55 using YACS::YACSLoader;
56 using namespace YACS::ENGINE;
57 using namespace std;
58
59
60 // --- use of glibc argp interface for parsing unix-style arguments
61
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";
66
67 #if defined WIN32 || defined __APPLE__
68 #else
69 static struct argp_option options[] =
70   {
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."},
83     { 0 }
84   };
85 #endif
86
87 struct arguments
88 {
89   char *args[1];
90   int display;
91   int verbose;
92   int stop;
93   char *dumpErrorFile;
94   char *finalDump;
95   int dump;
96   char *xmlSchema;
97   char *loadState;
98   int shutdown;
99   int reset;
100   int killPort;
101   std::list<std::string> init_ports;
102 };
103
104 typedef struct {
105   int nbsec;
106   string dumpFile;
107   string lockFile;
108 } thread_st;
109
110 #if defined WIN32 || defined __APPLE__
111 static int
112 #else
113 static error_t
114 #endif
115 parse_opt (int key, char *arg, struct argp_state *state)
116 {
117 #if defined WIN32 || defined __APPLE__
118 #else
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;
122   
123   switch (key)
124     {
125     case 'd':
126       myArgs->display = atoi(arg);
127       break;
128     case 't':
129       myArgs->shutdown = atoi(arg);
130       break;
131     case 'r':
132       myArgs->reset = atoi(arg);
133       break;
134     case 'v':
135       myArgs->verbose = 1;
136       break;
137     case 's':
138       myArgs->stop = 1;
139       break;
140     case 'e':
141       myArgs->stop = 1;
142       if (arg)
143         myArgs->dumpErrorFile = arg;
144       else
145         myArgs->dumpErrorFile = (char *)"dumpErrorState.xml";
146       break;
147     case 'f':
148       if (arg)
149         myArgs->finalDump = arg;
150       else
151         myArgs->finalDump = (char *)"finalDumpState.xml";
152       break;      
153     case 'g':
154       if (arg)
155         myArgs->dump = atoi(arg);
156       else
157         myArgs->dump = 60;
158       break;      
159     case 'l':
160       myArgs->loadState = arg;
161       break;
162     case 'x':
163       if (arg)
164         myArgs->xmlSchema = arg;
165       else
166         myArgs->xmlSchema = (char *)"saveSchema.xml";
167       break;      
168     case 'k':
169       myArgs->killPort = atoi(arg);
170       break;
171     case 'i':
172       if (arg)
173         myArgs->init_ports.push_back(std::string(arg));
174       break;
175
176     case ARGP_KEY_ARG:
177       if (state->arg_num >=1) // Too many arguments.
178         argp_usage (state);
179       myArgs->args[state->arg_num] = arg;
180       break;
181       
182     case ARGP_KEY_END:
183       if (state->arg_num < 1) // Not enough arguments.
184         argp_usage (state);
185       break;
186      
187     default:
188       return ARGP_ERR_UNKNOWN;
189     }
190 #endif
191   return 0;
192 }
193
194 // Our argp parser.
195 #if defined WIN32 || defined __APPLE__
196 #else
197 static struct argp argp = { options, parse_opt, args_doc, doc };
198 #endif
199
200 void timer(std::string msg)
201 {
202 #if defined WIN32 || defined __APPLE__
203 #else
204   struct timeval tv;
205   gettimeofday(&tv,NULL);
206   long t=tv.tv_sec*1000+tv.tv_usec/1000;
207   static long t0=t;
208   gettimeofday(&tv,NULL);
209   std::cerr << msg << tv.tv_sec*1000+tv.tv_usec/1000-t0 << " ms" << std::endl;
210 #endif
211 }
212
213 Proc* p=0;
214 static struct arguments myArgs;
215
216 void Handler(int theSigId)
217 {
218   if(p)
219     {
220       p->cleanNodes();
221       //if requested save state
222       bool isFinalDump = (strlen(myArgs.finalDump) != 0);
223       if (isFinalDump)
224         {
225           YACS::ENGINE::VisitorSalomeSaveState vst(p);
226           vst.openFileDump(myArgs.finalDump);
227           p->accept(&vst);
228           vst.closeFileDump();
229         }
230       //if requested shutdown schema
231       if(myArgs.shutdown < 999)
232         {
233           p->shutdown(myArgs.shutdown);
234         }
235     }
236   if (myArgs.killPort)
237     {
238       ostringstream command;
239       command << "killSalomeWithPort.py " << myArgs.killPort;
240       int status = system(command.str().c_str());
241       if (status == 0)
242         cerr << "Salome application on port " << myArgs.killPort << " is killed" << endl;
243       else
244         cerr << "Error: Can't kill Salome application on port " << myArgs.killPort << endl;
245     }
246   _exit(1);
247 }
248
249 void * dumpState(void *arg)
250 {
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)){
254 #ifdef WIN32
255     Sleep(st->nbsec);
256 #else 
257     sleep(st->nbsec);
258 #endif
259     string cmd = "touch " + st->lockFile;
260     system(cmd.c_str());
261     YACS::ENGINE::VisitorSalomeSaveState vst(p);
262     vst.openFileDump(st->dumpFile);
263     p->accept(&vst);
264     vst.closeFileDump();
265     cmd = "rm -f " + st->lockFile;
266     system(cmd.c_str());
267     state = p->getEffectiveState();
268   }
269   delete st;
270   return NULL;
271 }
272
273 #ifndef WIN32
274 typedef void (*sighandler_t)(int);
275 sighandler_t setsig(int sig, sighandler_t handler)
276 {
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)
282     return SIG_ERR;
283   return ocontext.sa_handler;
284 }
285 #endif
286
287 bool parse_init_port(const std::string& input, std::string& node, std::string& port, std::string& value)
288 {
289   bool ok = true;
290   size_t pos_eq = input.find('=');
291   if(pos_eq == std::string::npos || pos_eq == input.size())
292     return false;
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)
296     return false;
297   port = input.substr(pos_dot+1, pos_eq-pos_dot-1);
298   node = input.substr(0, pos_dot);
299   return true;
300 }
301
302 void InitializeSSL()
303 {
304   setSSLMode(true);
305   KERNEL::getLauncherSA();
306 }
307
308 int main (int argc, char* argv[])
309 {
310      
311   // Default values.
312   myArgs.display = 0;
313   myArgs.verbose = 0;
314   myArgs.stop = 0;
315   myArgs.dumpErrorFile= (char *)"";
316   myArgs.finalDump = (char *)"";
317   myArgs.dump = 0;
318   myArgs.loadState = (char *)"";
319   myArgs.xmlSchema = (char *)"";
320   myArgs.shutdown = 1;
321   myArgs.reset = 0;
322   myArgs.killPort = 0;
323   myArgs.init_ports.clear();
324
325   // Parse our arguments; every option seen by parse_opt will be reflected in arguments.
326 #if defined WIN32 || defined __APPLE__
327 #else
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;
335   if (myArgs.killPort)
336     std::cerr << " kill-port=" << myArgs.killPort;
337   if (myArgs.stop)
338     std::cerr << " dumpErrorFile=" << myArgs.dumpErrorFile << std::endl;
339   else
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++)
343   {
344     std::cerr << (*it) << std::endl;
345   }
346 #endif
347
348 #ifndef WIN32
349   setsig(SIGINT,&Handler);
350   setsig(SIGTERM,&Handler);
351 #endif
352
353   InitializeSSL();
354
355   timer("Starting ");
356   long flags = RuntimeSALOME::UsePython + RuntimeSALOME::UseCorba + RuntimeSALOME::UseXml + \
357                RuntimeSALOME::UseCpp + RuntimeSALOME::UseSalome;
358   RuntimeSALOME::setRuntime(flags, argc, argv);
359
360   // Try to load the session catalog if it exists
361   try
362     {
363       YACS::ENGINE::RuntimeSALOME* runTime = YACS::ENGINE::getSALOMERuntime();
364       CORBA::ORB_ptr orb = runTime->getOrb();
365       if (orb)
366         {
367           SALOME_NamingService_Wrapper namingService(orb);
368           //SALOME_NamingService namingService(orb);
369           CORBA::Object_var obj = namingService.Resolve("/Kernel/ModulCatalog");
370           SALOME_ModuleCatalog::ModuleCatalog_var aModuleCatalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj);
371           if (! CORBA::is_nil(aModuleCatalog))
372             {
373               CORBA::String_var anIOR = orb->object_to_string( aModuleCatalog );
374               YACS::ENGINE::Catalog* aCatalog = runTime->loadCatalog( "session", anIOR.in() );
375               runTime->addCatalog(aCatalog);
376             }
377         }
378     }
379   catch(ServiceUnreachable& e)
380     {
381       //Naming service unreachable don't add catalog
382     }
383
384   YACSLoader loader;
385   Executor executor;
386
387   try
388     {
389       timer("Elapsed time before load: ");
390       p=loader.load(myArgs.args[0]);
391       if(p==0)
392         {
393           std::cerr << "The imported file is probably not a YACS schema file" << std::endl;
394           return 1;
395         }
396       // Initialize the ports
397       for(std::list<std::string>::iterator it=myArgs.init_ports.begin(); it != myArgs.init_ports.end(); it++)
398       {
399         std::string node, port, value;
400         if(parse_init_port((*it), node, port, value))
401         {
402           std::cerr << "Initialization node=" << node
403                     << " port=" << port
404                     << " value=" << value << std::endl;
405
406           std::string init_state;
407           init_state = p->setInPortValue(node, port, value);
408           if(value.compare(init_state))
409           {
410             std::cerr << "Error on initialization:" << init_state << std::endl;
411             return 1;
412           }
413         }
414         else
415         {
416           std::cerr << "Error on parsing initialization string:" << (*it) << std::endl;
417           return 1;
418         }
419       }
420       
421       //Get the parser logger
422       Logger* logger=p->getLogger("parser");
423       //Print errors logged if any
424       if(!logger->isEmpty())
425         {
426           std::cerr << "The imported file has errors" << std::endl;
427           std::cerr << logger->getStr() << std::endl;
428         }
429       //Don't execute if there are errors
430       if(logger->hasErrors())
431         {
432           if(!p->isValid())
433             {
434               std::string report=p->getErrorReport();
435               std::cerr << "The schema is not valid and can not be executed" << std::endl;
436               std::cerr << report << std::endl;
437             }
438           delete p;
439           Runtime* r=YACS::ENGINE::getRuntime();
440           Dispatcher* disp=Dispatcher::getDispatcher();
441           r->fini();
442           delete r;
443           delete disp;
444           return 1;
445         }
446       timer("Elapsed time after load: ");
447
448       if(!p->isValid())
449         {
450           std::string report=p->getErrorReport();
451           std::cerr << "The schema is not valid and can not be executed" << std::endl;
452           std::cerr << report << std::endl;
453           Runtime* r=YACS::ENGINE::getRuntime();
454           Dispatcher* disp=Dispatcher::getDispatcher();
455           r->fini();
456           delete r;
457           delete disp;
458           return 1;
459         }
460       timer("Elapsed time after validation: ");
461
462       // Check consistency
463       LinkInfo info(LinkInfo::ALL_DONT_STOP);
464       p->checkConsistency(info);
465       if(info.areWarningsOrErrors())
466         {
467           std::cerr << "The schema is not consistent and can not be executed" << std::endl;
468           std::cerr << info.getGlobalRepr() << std::endl;
469           Runtime* r=YACS::ENGINE::getRuntime();
470           Dispatcher* disp=Dispatcher::getDispatcher();
471           r->fini();
472           delete r;
473           delete disp;
474           return 1;
475         }
476       timer("Elapsed time after check consistency: ");
477
478       //execution
479       bool isXmlSchema = (strlen(myArgs.xmlSchema) != 0);
480       if (isXmlSchema)
481       {
482         YACS::ENGINE::VisitorSaveSalomeSchema vss(p);
483         vss.openFileSchema(myArgs.xmlSchema);
484         p->accept(&vss);
485         vss.closeFileSchema();
486       }
487
488       bool fromScratch = (strlen(myArgs.loadState) == 0);
489       if (!fromScratch)
490         {
491           p->init();
492           p->exUpdateState();
493           stateParser* rootParser = new stateParser();
494           stateLoader myStateLoader(rootParser, p);
495           myStateLoader.parse(myArgs.loadState);
496           if(myArgs.reset>0)
497             {
498               p->resetState(myArgs.reset);
499               p->exUpdateState();
500             }
501         }
502
503       if (myArgs.stop)
504         if (strlen(myArgs.dumpErrorFile) >0)
505           executor.setStopOnError(true, myArgs.dumpErrorFile);
506         else
507           executor.setStopOnError(false, myArgs.dumpErrorFile);
508
509       if(myArgs.display>0)
510         {
511           std::ofstream f("toto");
512           p->writeDot(f);
513           f.close();
514         }
515
516       bool isDump = (myArgs.dump != 0);
517       pthread_t th;
518       if (isDump)
519         {
520           thread_st *st = new thread_st;
521           st->nbsec = myArgs.dump;
522           st->dumpFile = string("dumpState_") + myArgs.args[0];
523           string rootFile = st->dumpFile.substr(0,st->dumpFile.find("."));
524           st->lockFile = rootFile + ".lock";
525           pthread_create(&th,NULL,&dumpState,(void*)st);
526         }
527       YACS::ENGINE::LoadObserversPluginIfAny(p,&executor);
528       cerr << "+++++++++++++++++++ start calculation +++++++++++++++++++" << endl;
529       executor.RunW(p,myArgs.display, fromScratch);
530       cerr << "+++++++++++++++++++  end calculation  +++++++++++++++++++" << endl;
531       cerr << "Proc state : " << Node::getStateName(p->getEffectiveState()) << endl;
532       timer("Elapsed time after execution: ");
533
534       // Return 0 if SCHEMA OK
535       // Return 1 for YACS ERROR (EXCEPTION NOT CATCHED)
536       // Return 2 for YACS SCHEMA ERROR/FAILED
537       int return_value = 0;
538
539       if(p->getEffectiveState() != YACS::DONE)
540         {
541           std::string report=p->getErrorReport();
542           std::cerr << "Execution has ended in error" << std::endl;
543           std::cerr << report << std::endl;
544           return_value = 2;
545         }
546
547       if(myArgs.display>0)
548         {
549           std::ofstream g("titi");
550           p->writeDot(g);
551           g.close();
552         }
553
554       if (isDump)
555         {
556           pthread_join(th,NULL);
557         }
558
559       bool isFinalDump = (strlen(myArgs.finalDump) != 0);
560       if (isFinalDump)
561         {
562           YACS::ENGINE::VisitorSalomeSaveState vst(p);
563           vst.openFileDump(myArgs.finalDump);
564           p->accept(&vst);
565           vst.closeFileDump();
566         }
567       if(myArgs.shutdown < 999)
568         {
569           p->shutdown(myArgs.shutdown);
570         }
571       delete p;
572       Runtime* r=YACS::ENGINE::getRuntime();
573       Dispatcher* disp=Dispatcher::getDispatcher();
574       r->fini();
575       delete r;
576       delete disp;
577       YACS::ENGINE::UnLoadObserversPluginIfAny();
578       return return_value;
579     }
580   catch (YACS::Exception& e)
581     {
582       cerr << "Caught a YACS exception" << endl;
583       cerr << e.what() << endl;
584       Runtime* r=YACS::ENGINE::getRuntime();
585       Dispatcher* disp=Dispatcher::getDispatcher();
586       r->fini();
587       delete r;
588       delete disp;
589       return 1;
590     }
591   catch (const std::ios_base::failure&)
592     {
593       cerr << "Caught an io failure exception" << endl;
594       return 1;
595     }
596   catch(CORBA::SystemException& ex) 
597     {
598       cerr << "Caught a CORBA::SystemException.:" << __FILE__ << ":" << __LINE__ << ":" ;
599       CORBA::Any tmp;
600       tmp <<= ex;
601       CORBA::TypeCode_var tc = tmp.type();
602       const char *p = tc->name();
603       if ( *p != '\0' ) 
604         cerr <<p;
605       else  
606         cerr  << tc->id();
607       cerr << endl;
608       return 1;
609     }
610   catch(omniORB::fatalException& fe) 
611     {
612       cerr << "Caught omniORB::fatalException:" << endl;
613       cerr << "  file: " << fe.file() << endl;
614       cerr << "  line: " << fe.line() << endl;
615       cerr << "  mesg: " << fe.errmsg() << endl;
616       return 1;
617     }
618   catch(...) 
619     {
620       cerr << "Caught unknown exception." << endl;
621       return 1;
622     }
623 }
624