]> git.stg.codes - stg.git/blob - projects/stargazer/main.cpp
Set services and corps to plugins
[stg.git] / projects / stargazer / main.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19  */
20
21  /*
22  $Revision: 1.124 $
23  $Date: 2010/10/04 20:19:12 $
24  $Author: faust $
25  */
26
27 #include <unistd.h>
28 #include <sys/ipc.h>
29 #include <sys/msg.h>
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <sys/stat.h> // S_IRUSR
33 #include <fcntl.h> // create
34
35 #include <csignal>
36 #include <cerrno>
37 #include <cstdio>
38 #include <cstdlib> // srandom, exit
39 #include <fstream>
40 #include <vector>
41 #include <set>
42 #include <list>
43
44 #include "stg/user.h"
45 #include "stg/common.h"
46 #include "stg/plugin.h"
47 #include "stg/logger.h"
48 #include "stg/scriptexecuter.h"
49 #include "stg/conffiles.h"
50 #include "stg/version.h"
51 #include "stg/pinger.h"
52 #include "stg_timer.h"
53 #include "settings_impl.h"
54 #include "users_impl.h"
55 #include "admins_impl.h"
56 #include "tariffs_impl.h"
57 #include "services_impl.h"
58 #include "corps_impl.h"
59 #include "traffcounter_impl.h"
60 #include "plugin_runner.h"
61 #include "store_loader.h"
62 #include "pidfile.h"
63 #include "eventloop.h"
64
65 using namespace std;
66 uint32_t        eip;
67
68 #ifdef DEBUG
69     #define MAIN_DEBUG (1)
70     #define NO_DAEMON  (1)
71 #endif
72
73 #define START_FILE "/._ST_ART_ED_"
74
75 static bool needRulesReloading = false;
76 static bool childExited = false;
77 //static pid_t executerPid;
78 set<pid_t> executersPid;
79 static pid_t stgChildPid;
80
81
82 //-----------------------------------------------------------------------------
83 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
84 {
85 return lhs.GetStartPosition() < rhs.GetStartPosition();
86 }
87 //-----------------------------------------------------------------------------
88 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
89 {
90 return lhs.GetStopPosition() > rhs.GetStopPosition();
91 }
92 //-----------------------------------------------------------------------------
93 class STG_STOPPER
94 {
95 public:
96     STG_STOPPER() { nonstop = true; }
97     bool    GetStatus() const { return nonstop; };
98     #ifdef NO_DAEMON
99     void    Stop(const char * __file__, int __line__)
100     #else
101     void    Stop(const char *, int)
102     #endif
103         {
104         #ifdef NO_DAEMON
105         printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
106         #endif
107         nonstop = false;
108         }
109 private:
110     bool nonstop;
111 };
112 //-----------------------------------------------------------------------------
113 STG_STOPPER nonstop;
114 //-----------------------------------------------------------------------------
115 static void StartTimer()
116 {
117 STG_LOGGER & WriteServLog = GetStgLogger();
118
119 if (RunStgTimer())
120     {
121     WriteServLog("Cannot start timer. Fatal.");
122     //printfd(__FILE__, "Cannot start timer. Fatal.\n");
123     exit(1);
124     }
125 else
126     {
127     WriteServLog("Timer thread started successfully.");
128     //printfd(__FILE__, "Timer thread started successfully.\n");
129     }
130 }
131 //-----------------------------------------------------------------------------
132 void CatchUSR1(int)
133 {
134
135 }
136 //-----------------------------------------------------------------------------
137 void CatchTERM(int sig)
138 {
139 /*
140  *Function Name:CatchINT
141  *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
142  *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
143  *Returns: îÉÞÅÇÏ
144  */
145 STG_LOGGER & WriteServLog = GetStgLogger();
146 WriteServLog("Shutting down... %d", sig);
147
148 //nonstop = false;
149 nonstop.Stop(__FILE__, __LINE__);
150
151 struct sigaction newsa, oldsa;
152 sigset_t sigmask;
153
154 sigemptyset(&sigmask);
155 sigaddset(&sigmask, SIGTERM);
156 newsa.sa_handler = SIG_IGN;
157 newsa.sa_mask = sigmask;
158 newsa.sa_flags = 0;
159 sigaction(SIGTERM, &newsa, &oldsa);
160
161 sigemptyset(&sigmask);
162 sigaddset(&sigmask, SIGINT);
163 newsa.sa_handler = SIG_IGN;
164 newsa.sa_mask = sigmask;
165 newsa.sa_flags = 0;
166 sigaction(SIGINT, &newsa, &oldsa);
167 }
168 //-----------------------------------------------------------------------------
169 void CatchPIPE(int)
170 {
171 STG_LOGGER & WriteServLog = GetStgLogger();
172 WriteServLog("Broken pipe!");
173 }
174 //-----------------------------------------------------------------------------
175 void CatchHUP(int)
176 {
177 needRulesReloading = true;
178 }
179 //-----------------------------------------------------------------------------
180 void CatchCHLD(int)
181 {
182 int status;
183 pid_t childPid;
184 childPid = waitpid(-1, &status, WNOHANG);
185
186 set<pid_t>::iterator pid;
187 pid = executersPid.find(childPid);
188 if (pid != executersPid.end())
189     {
190     executersPid.erase(pid);
191     if (executersPid.empty() && nonstop.GetStatus())
192         {
193         nonstop.Stop(__FILE__, __LINE__);
194         }
195     }
196 if (childPid == stgChildPid)
197     {
198     childExited = true;
199     }
200 }
201 /*//-----------------------------------------------------------------------------
202 void CatchSEGV(int, siginfo_t *, void *)
203 {
204 char fileName[50];
205 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
206 FILE * f = fopen(fileName, "wt");
207 if (f)
208     {
209     fprintf(f, "\nSignal info:\n~~~~~~~~~~~~\n");
210     fprintf(f, "numb:\t %d (%d)\n", sinfo->si_signo, sig);
211     fprintf(f, "errn:\t %d\n", sinfo->si_errno);
212     fprintf(f, "code:\t %d ", sinfo->si_code);
213
214     switch (sinfo->si_code)
215         {
216         case SEGV_MAPERR:
217             fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
218             break;
219
220         case SEGV_ACCERR:
221             fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
222             break;
223
224         default:
225             fprintf(f, "???\n");
226         }
227
228     fprintf(f, "addr:\t 0x%.8X\n",
229         (unsigned int)sinfo->si_addr);
230
231     Dl_info dlinfo;
232     //asm("movl %eip, eip");
233     if (dladdr((void*)CatchCHLD, &dlinfo))
234         {
235         fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
236         }
237     else
238         {
239         fprintf(f, "Cannot find SEGV point\n");
240         }
241
242     fclose(f);
243     }
244
245 struct sigaction segv_action, segv_action_old;
246
247 segv_action.sa_handler = SIG_DFL;
248 segv_action.sa_sigaction = NULL;
249 segv_action.sa_flags = SA_SIGINFO;
250 segv_action.sa_restorer = NULL;
251
252 sigaction(SIGSEGV, &segv_action, &segv_action_old);
253 }*/
254 //-----------------------------------------------------------------------------
255 static void SetSignalHandlers()
256 {
257 struct sigaction newsa, oldsa;
258 sigset_t sigmask;
259 ///////
260 sigemptyset(&sigmask);
261 sigaddset(&sigmask, SIGTERM);
262 newsa.sa_handler = CatchTERM;
263 newsa.sa_mask = sigmask;
264 newsa.sa_flags = 0;
265 sigaction(SIGTERM, &newsa, &oldsa);
266 ///////
267 sigemptyset(&sigmask);
268 sigaddset(&sigmask, SIGUSR1);
269 newsa.sa_handler = CatchUSR1;
270 newsa.sa_mask = sigmask;
271 newsa.sa_flags = 0;
272 sigaction(SIGUSR1, &newsa, &oldsa);
273 ///////
274 sigemptyset(&sigmask);
275 sigaddset(&sigmask, SIGINT);
276 newsa.sa_handler = CatchTERM;
277 newsa.sa_mask = sigmask;
278 newsa.sa_flags = 0;
279 sigaction(SIGINT, &newsa, &oldsa);
280 //////
281 sigemptyset(&sigmask);
282 sigaddset(&sigmask, SIGPIPE);
283 newsa.sa_handler = CatchPIPE;
284 newsa.sa_mask = sigmask;
285 newsa.sa_flags = 0;
286 sigaction(SIGPIPE, &newsa, &oldsa);
287 //////
288 sigemptyset(&sigmask);
289 sigaddset(&sigmask, SIGHUP);
290 newsa.sa_handler = CatchHUP;
291 newsa.sa_mask = sigmask;
292 newsa.sa_flags = 0;
293 sigaction(SIGHUP, &newsa, &oldsa);
294 //////
295 sigemptyset(&sigmask);
296 sigaddset(&sigmask, SIGCHLD);
297 newsa.sa_handler = CatchCHLD;
298 newsa.sa_mask = sigmask;
299 newsa.sa_flags = 0;
300 sigaction(SIGCHLD, &newsa, &oldsa);
301
302 /*newsa.sa_handler = NULL;
303 newsa.sa_sigaction = CatchSEGV;
304 newsa.sa_flags = SA_SIGINFO;
305 newsa.sa_restorer = NULL;
306 sigaction(SIGSEGV, &newsa, &oldsa);*/
307
308 return;
309 }
310 //-----------------------------------------------------------------------------
311 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
312 {
313 STG_LOGGER & WriteServLog = GetStgLogger();
314
315 if (*msgID == -11)   // If msgID == -11 - first call. Create queue
316     {
317     for (int i = 0; i < 2; i++)
318         {
319         *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
320
321         if (*msgID == -1)
322             {
323             *msgID = msgget(msgKey, 0);
324             if (*msgID == -1)
325                 {
326                 WriteServLog("Message queue not created.");
327                 return -1;
328                 }
329             else
330                 {
331                 msgctl(*msgID, IPC_RMID, NULL);
332                 }
333             }
334         else
335             {
336             WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
337             break;
338             }
339         }
340     }
341
342 pid_t executerPid = fork();
343
344 switch (executerPid)
345     {
346     case -1:
347         WriteServLog("Fork error!");
348         return -1;
349
350     case 0:
351         delete settings;
352         Executer(*msgID, executerPid, procName);
353         return 1;
354
355     default:
356         if (executersPid.empty()) {
357             Executer(*msgID, executerPid, NULL);
358         }
359         executersPid.insert(executerPid);
360     }
361 return 0;
362 }
363 //-----------------------------------------------------------------------------
364 #ifndef NO_DAEMON
365 int ForkAndWait(const string & confDir)
366 #else
367 int ForkAndWait(const string &)
368 #endif
369 {
370 #ifndef NO_DAEMON
371 stgChildPid = fork();
372 string startFile = confDir + START_FILE;
373 unlink(startFile.c_str());
374
375 switch (stgChildPid)
376     {
377     case -1:
378         return -1;
379         break;
380
381     case 0:
382         close(1);
383         close(2);
384         setsid();
385         break;
386
387     default:
388         struct timespec ts = {0, 200000000};
389         for (int i = 0; i < 120 * 5; i++)
390             {
391             if (access(startFile.c_str(), F_OK) == 0)
392                 {
393                 unlink(startFile.c_str());
394                 exit(0);
395                 }
396
397             if (childExited)
398                 {
399                 unlink(startFile.c_str());
400                 exit(1);
401                 }
402             nanosleep(&ts, NULL);
403             }
404         unlink(startFile.c_str());
405         exit(1);
406         break;
407     }
408 #endif
409 return 0;
410 }
411 //-----------------------------------------------------------------------------
412 void KillExecuters()
413 {
414 set<pid_t>::iterator pid;
415 pid = executersPid.begin();
416 while (pid != executersPid.end())
417     {
418     printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
419     kill(*pid, SIGUSR1);
420     ++pid;
421     }
422 }
423 //-----------------------------------------------------------------------------
424 int main(int argc, char * argv[])
425 {
426
427 /*
428   Initialization order:
429   - Logger
430   - Stg timer
431   - Settings
432   - Plugins
433   - Plugins settings
434   - Read Admins
435   - Read Tariffs
436   - Read Users
437   - Start Users
438   - Start Traffcounter
439   - Start Plugins
440   - Start pinger
441   - Set signal nandlers
442   - Fork and exit
443  * */
444
445 SETTINGS_IMPL * settings = NULL;
446 STORE * dataStore = NULL;
447 TARIFFS_IMPL * tariffs = NULL;
448 ADMINS_IMPL * admins = NULL;
449 USERS_IMPL * users = NULL;
450 TRAFFCOUNTER_IMPL * traffCnt = NULL;
451 SERVICES_IMPL * services = NULL;
452 CORPORATIONS_IMPL * corps = NULL;
453 int msgID = -11;
454
455     {
456     STG_LOGGER & WriteServLog = GetStgLogger();
457     WriteServLog.SetLogFileName("/var/log/stargazer.log");
458     }
459
460 vector<MODULE_SETTINGS> modSettings;
461 list<PLUGIN_RUNNER> modules;
462
463 list<PLUGIN_RUNNER>::iterator modIter;
464
465 if (getuid())
466     {
467     printf("You must be root. Exit.\n");
468     exit(1);
469     }
470
471 if (argc == 2)
472     settings = new SETTINGS_IMPL(argv[1]);
473 else
474     settings = new SETTINGS_IMPL();
475
476 if (settings->ReadSettings())
477     {
478     STG_LOGGER & WriteServLog = GetStgLogger();
479
480     if (settings->GetLogFileName() != "")
481         WriteServLog.SetLogFileName(settings->GetLogFileName());
482
483     WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
484     exit(1);
485     }
486
487 #ifndef NO_DAEMON
488 string startFile(settings->GetConfDir() + START_FILE);
489 #endif
490
491 if (ForkAndWait(settings->GetConfDir()) < 0)
492     {
493     STG_LOGGER & WriteServLog = GetStgLogger();
494     WriteServLog("Fork error!");
495     exit(1);
496     }
497
498 STG_LOGGER & WriteServLog = GetStgLogger();
499 WriteServLog.SetLogFileName(settings->GetLogFileName());
500 WriteServLog("Stg v. %s", SERVER_VERSION);
501
502 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
503     {
504     int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
505     if (ret < 0)
506         {
507         STG_LOGGER & WriteServLog = GetStgLogger();
508         WriteServLog("Start Script Executer error!");
509         return 1;
510         }
511     if (ret == 1)
512         {
513         // Stopping child
514         return 0;
515         }
516     }
517
518 PIDFile pidFile(settings->GetPIDFileName());
519
520 StartTimer();
521 WaitTimer();
522 if (!IsStgTimerRunning())
523     {
524     printfd(__FILE__, "Timer thread not started in 1 sec!\n");
525     WriteServLog("Timer thread not started in 1 sec!");
526     }
527
528 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
529
530 STORE_LOADER storeLoader(*settings);
531 if (storeLoader.Load())
532     {
533     WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
534     goto exitLblNotStarted;
535     }
536
537 if (loop.Start())
538     {
539     WriteServLog("Event loop not started.");
540     goto exitLblNotStarted;
541     }
542
543 dataStore = storeLoader.GetStore();
544 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
545
546 tariffs = new TARIFFS_IMPL(dataStore);
547 admins = new ADMINS_IMPL(dataStore);
548 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
549 traffCnt = new TRAFFCOUNTER_IMPL(users, settings->GetRulesFileName());
550 services = new SERVICES_IMPL(dataStore);
551 corps = new CORPORATIONS_IMPL(dataStore);
552 traffCnt->SetMonitorDir(settings->GetMonitorDir());
553
554 modSettings = settings->GetModulesSettings();
555
556 for (size_t i = 0; i < modSettings.size(); i++)
557     {
558     string modulePath = settings->GetModulesPath();
559     modulePath += "/mod_";
560     modulePath += modSettings[i].moduleName;
561     modulePath += ".so";
562     printfd(__FILE__, "Module: %s\n", modulePath.c_str());
563     modules.push_back(
564         PLUGIN_RUNNER(modulePath,
565                       modSettings[i],
566                       admins,
567                       tariffs,
568                       users,
569                       services,
570                       corps,
571                       traffCnt,
572                       dataStore,
573                       settings)
574         );
575     }
576
577 modIter = modules.begin();
578
579 while (modIter != modules.end())
580     {
581     //Loading modules
582     if (modIter->Load())
583         {
584         WriteServLog("Error: %s",
585                      modIter->GetStrError().c_str());
586         goto exitLblNotStarted;
587         }
588     ++modIter;
589     }
590
591 //Start section
592 if (users->Start())
593     {
594     goto exitLblNotStarted;
595     }
596 WriteServLog("Users started successfully.");
597
598 if (traffCnt->Start())
599     {
600     goto exitLblNotStarted;
601     }
602 WriteServLog("Traffcounter started successfully.");
603
604 //Sort by start order
605 modules.sort(StartModCmp);
606 modIter = modules.begin();
607
608 while (modIter != modules.end())
609     {
610     if (modIter->Start())
611         {
612         WriteServLog("Error: %s",
613                      modIter->GetStrError().c_str());
614         //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
615         goto exitLbl;
616         }
617     WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
618     ++modIter;
619     }
620 SetSignalHandlers();
621
622 srandom(stgTime);
623
624 /*
625  * Note that an implementation in which nice returns the new nice value
626  * can legitimately return -1.   To  reliably  detect  an  error,  set
627  * errno to 0 before the call, and check its value when nice returns -1.
628  *
629  *
630  * (c) man 2 nice
631  */
632 /*errno = 0;
633 if (nice(-19) && errno) {
634     printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
635     WriteServLog("nice failed: '%s'", strerror(errno));
636 }*/
637
638 WriteServLog("Stg started successfully.");
639 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
640
641 #ifndef NO_DAEMON
642 creat(startFile.c_str(), S_IRUSR);
643 #endif
644
645 while (nonstop.GetStatus())
646     {
647     if (needRulesReloading)
648         {
649         needRulesReloading = false;
650         traffCnt->Reload();
651
652         modIter = modules.begin();
653         for (; modIter != modules.end(); ++modIter)
654             {
655             if (modIter->Reload())
656                 {
657                 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
658                                                           modIter->GetStrError().c_str());
659                 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
660                                                                  modIter->GetStrError().c_str());
661                 }
662             }
663         }
664     stgUsleep(100000);
665     }
666
667 exitLbl:
668
669 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
670
671 //Sort by start order
672 modules.sort(StopModCmp);
673 modIter = modules.begin();
674 while (modIter != modules.end())
675     {
676     std::string name = modIter->GetFileName();
677     printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
678     if (modIter->Stop())
679         {
680         WriteServLog("Module \'%s\': Error: %s",
681                      modIter->GetPlugin()->GetVersion().c_str(),
682                      modIter->GetStrError().c_str());
683         printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
684         //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
685         //goto exitLbl;
686         }
687     WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
688     ++modIter;
689     }
690
691 if (loop.Stop())
692     {
693     WriteServLog("Event loop not stopped.");
694     }
695
696 exitLblNotStarted:
697
698 modIter = modules.begin();
699 while (modIter != modules.end())
700     {
701     std::string name = modIter->GetFileName();
702     printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
703     if (modIter->Unload())
704         {
705         WriteServLog("Module \'%s\': Error: %s",
706                      name.c_str(),
707                      modIter->GetStrError().c_str());
708         printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
709         }
710     ++modIter;
711     }
712
713 if (traffCnt)
714     {
715     traffCnt->Stop();
716     WriteServLog("Traffcounter: Stop successfull.");
717     }
718
719 if (users)
720     {
721     users->Stop();
722     WriteServLog("Users: Stop successfull.");
723     }
724
725 sleep(1);
726 int res = msgctl(msgID, IPC_RMID, NULL);
727 if (res)
728     WriteServLog("Queue was not removed. id=%d", msgID);
729 else
730     WriteServLog("Queue removed successfully.");
731
732 KillExecuters();
733
734 StopStgTimer();
735 WriteServLog("StgTimer: Stop successfull.");
736
737 delete corps;
738 delete services;
739 delete traffCnt;
740 delete users;
741 delete admins;
742 delete tariffs;
743 delete settings;
744
745 WriteServLog("Stg stopped successfully.");
746 WriteServLog("---------------------------------------------");
747
748 return 0;
749 }
750 //-----------------------------------------------------------------------------