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