]> git.stg.codes - stg.git/blob - projects/stargazer/main.cpp
Empty lines removed from the end of the main.cpp from stargazer project
[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 <stdio.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
32 #include <unistd.h>
33 #include <sys/ipc.h>
34 #include <sys/msg.h>
35 #include <sys/stat.h>
36 #include <sys/wait.h>
37 #include <dlfcn.h>
38 #include <fcntl.h>
39
40 #include <csignal>
41 #include <cerrno>
42 #include <fstream>
43 #include <vector>
44 #include <set>
45 #include <list>
46
47 #include "settings.h"
48 #include "user.h"
49 #include "users.h"
50 #include "admins.h"
51 #include "common.h"
52 #include "traffcounter.h"
53 #include "base_plugin.h"
54 #include "stg_logger.h"
55 #include "stg_timer.h"
56 #include "plugin_runner.h"
57 #include "script_executer.h"
58 #include "conffiles.h"
59 #include "version.h"
60 #include "store_loader.h"
61 #include "pidfile.h"
62 #include "eventloop.h"
63
64 using namespace std;
65 uint32_t        eip;
66
67 #ifdef DEBUG
68     #define MAIN_DEBUG (1)
69     #define NO_DAEMON  (1)
70 #endif
71
72 #define START_FILE "/._ST_ART_ED_"
73
74 static bool needRulesReloading = false;
75 static bool childExited = false;
76 //static pid_t executerPid;
77 set<pid_t> executersPid;
78 static pid_t stgChildPid;
79
80 #include "pinger.h"
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 * 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         //WriteServLog("Creating queue with key=%d ...", msgKey);
320         *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
321
322         if (*msgID == -1)
323             {
324             *msgID = msgget(msgKey, 0);
325             if (*msgID == -1)
326                 {
327                 WriteServLog("Message queue not created.");
328                 return -1;
329                 }
330             else
331                 {
332                 msgctl(*msgID, IPC_RMID, NULL);
333                 //printfd(__FILE__, "Queue removed!");
334                 }
335             }
336         else
337             {
338             WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
339             break;
340             }
341         }
342     }
343
344 pid_t executerPid = fork();
345
346 switch (executerPid)
347     {
348     case -1:    // ìÁÖÁ
349         WriteServLog("Fork error!");
350         return -1;
351
352     case 0:     // ðÏÔÏÍÏË
353         //close(0);
354         //close(1);
355         //close(2);
356         //setsid();
357         delete settings;
358         Executer(msgKey, *msgID, executerPid, procName);
359         return 1;
360
361     default:    // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
362         if (executersPid.empty()) {
363             Executer(msgKey, *msgID, executerPid, NULL);
364         }
365         executersPid.insert(executerPid);
366     }
367 return 0;
368 }
369 //-----------------------------------------------------------------------------
370 #ifndef NO_DAEMON
371 int ForkAndWait(const string & confDir)
372 #else
373 int ForkAndWait(const string &)
374 #endif
375 {
376 #ifndef NO_DAEMON
377 stgChildPid = fork();
378 string startFile = confDir + START_FILE;
379 unlink(startFile.c_str());
380
381 switch (stgChildPid)
382     {
383     case -1:    // ìÁÖÁ
384         return -1;
385         break;
386
387     case 0:     // ðÏÔÏÍÏË
388         //close(0);
389         close(1);
390         close(2);
391         setsid();
392         break;
393
394     default:    // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
395         for (int i = 0; i < 120 * 5; i++)
396             {
397             if (access(startFile.c_str(), F_OK) == 0)
398                 {
399                 //printf("Fork successfull. Exit.\n");
400                 unlink(startFile.c_str());
401                 exit(0);
402                 }
403
404             if (childExited)
405                 {
406                 unlink(startFile.c_str());
407                 exit(1);
408                 }
409             usleep(200000);
410             }
411         unlink(startFile.c_str());
412         exit(1);
413         break;
414     }
415 #endif
416 return 0;
417 }
418 //-----------------------------------------------------------------------------
419 void KillExecuters()
420 {
421 set<pid_t>::iterator pid;
422 pid = executersPid.begin();
423 while (pid != executersPid.end())
424     {
425     printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
426     kill(*pid, SIGUSR1);
427     ++pid;
428     }
429 }
430 //-----------------------------------------------------------------------------
431 int main(int argc, char * argv[])
432 {
433
434 /*
435   Initialization order:
436   - Logger
437   - Stg timer
438   - Settings
439   - Plugins
440   - Plugins settings
441   - Read Admins
442   - Read Tariffs
443   - Read Users
444   - Start Users
445   - Start Traffcounter
446   - Start Plugins
447   - Start pinger
448   - Set signal nandlers
449   - Fork and exit
450  * */
451
452 SETTINGS * settings = NULL;
453 BASE_STORE * dataStore = NULL;
454 TARIFFS * tariffs = NULL;
455 ADMINS * admins = NULL;
456 USERS * users = NULL;
457 TRAFFCOUNTER * traffCnt = NULL;
458 int msgID = -11;
459
460     {
461     STG_LOGGER & WriteServLog = GetStgLogger();
462     WriteServLog.SetLogFileName("/var/log/stargazer.log");
463     }
464
465 vector<MODULE_SETTINGS> modSettings;
466 list<PLUGIN_RUNNER> modules;
467
468 list<PLUGIN_RUNNER>::iterator modIter;
469
470 if (getuid())
471     {
472     printf("You must be root. Exit.\n");
473     exit(1);
474     }
475
476 if (argc == 2)
477     settings = new SETTINGS(argv[1]);
478 else
479     settings = new SETTINGS();
480
481 if (settings->ReadSettings())
482     {
483     //printfd(__FILE__, "ReadSettings error.\n");
484     STG_LOGGER & WriteServLog = GetStgLogger();
485
486     if (settings->GetLogFileName() != "")
487         WriteServLog.SetLogFileName(settings->GetLogFileName());
488
489     WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
490     exit(1);
491     }
492
493 #ifndef NO_DAEMON
494 string startFile(settings->GetConfDir() + START_FILE);
495 #endif
496
497 if (ForkAndWait(settings->GetConfDir()) < 0)
498     {
499     STG_LOGGER & WriteServLog = GetStgLogger();
500     WriteServLog("Fork error!");
501     exit(1);
502     }
503
504 STG_LOGGER & WriteServLog = GetStgLogger();
505 WriteServLog.SetLogFileName(settings->GetLogFileName());
506 WriteServLog("Stg v. %s", SERVER_VERSION);
507
508 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
509     {
510     int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
511     if (ret < 0)
512         {
513         STG_LOGGER & WriteServLog = GetStgLogger();
514         WriteServLog("Start Script Executer error!");
515         return 1;
516         }
517     if (ret == 1)
518         {
519         // Stopping child
520         return 0;
521         }
522     }
523
524 PIDFile pidFile(settings->GetPIDFileName());
525
526 StartTimer();
527 WaitTimer();
528 if (!IsStgTimerRunning())
529     {
530     printfd(__FILE__, "Timer thread not started in 1 sec!\n");
531     WriteServLog("Timer thread not started in 1 sec!");
532     }
533
534 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
535
536 STORE_LOADER storeLoader(*settings);
537 if (storeLoader.Load())
538     {
539     WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
540     goto exitLblNotStarted;
541     }
542
543 if (loop.Start())
544     {
545     WriteServLog("Event loop not started.");
546     goto exitLblNotStarted;
547     }
548
549 dataStore = storeLoader.GetStore();
550 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
551
552 tariffs = new TARIFFS(dataStore);
553 admins = new ADMINS(dataStore);
554 users = new USERS(settings, dataStore, tariffs, admins->GetSysAdmin());
555 traffCnt = new TRAFFCOUNTER(users, tariffs, settings->GetRulesFileName());
556 traffCnt->SetMonitorDir(settings->GetMonitorDir());
557
558 modSettings = settings->GetModulesSettings();
559
560 for (unsigned i = 0; i < modSettings.size(); i++)
561     {
562     string modulePath = settings->GetModulesPath();
563     modulePath += "/mod_";
564     modulePath += modSettings[i].moduleName;
565     modulePath += ".so";
566     printfd(__FILE__, "Module: %s\n", modulePath.c_str());
567     modules.push_back(
568         PLUGIN_RUNNER(modulePath,
569                       modSettings[i],
570                       admins,
571                       tariffs,
572                       users,
573                       traffCnt,
574                       dataStore,
575                       settings)
576         );
577     }
578
579 modIter = modules.begin();
580
581 while (modIter != modules.end())
582     {
583     //Loading modules
584     if (modIter->Load())
585         {
586         WriteServLog("Error: %s",
587                      modIter->GetStrError().c_str());
588         goto exitLblNotStarted;
589         }
590     ++modIter;
591     }
592
593 //Start section
594 if (users->Start())
595     {
596     goto exitLblNotStarted;
597     }
598 WriteServLog("Users started successfully.");
599
600 if (traffCnt->Start())
601     {
602     goto exitLblNotStarted;
603     }
604 WriteServLog("Traffcounter started successfully.");
605
606 //Sort by start order
607 modules.sort(StartModCmp);
608 modIter = modules.begin();
609
610 while (modIter != modules.end())
611     {
612     if (modIter->Start())
613         {
614         WriteServLog("Error: %s",
615                      modIter->GetStrError().c_str());
616         //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
617         goto exitLbl;
618         }
619     WriteServLog("Module: \'%s\'. Start successfull. %d", modIter->GetPlugin()->GetVersion().c_str(),
620         modIter->GetPlugin()->GetStartPosition());
621     ++modIter;
622     }
623 SetSignalHandlers();
624
625 srandom(stgTime);
626
627 /*
628  * Note that an implementation in which nice returns the new nice value
629  * can legitimately return -1.   To  reliably  detect  an  error,  set
630  * errno to 0 before the call, and check its value when nice returns -1.
631  *
632  *
633  * (c) man 2 nice
634  */
635 errno = 0;
636 if (nice(-19) && errno) {
637     printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
638     WriteServLog("nice failed: '%s'", strerror(errno));
639 }
640
641 WriteServLog("Stg started successfully.");
642 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
643
644 #ifndef NO_DAEMON
645 creat(startFile.c_str(), S_IRUSR);
646 #endif
647
648 while (nonstop.GetStatus())
649     {
650     if (needRulesReloading)
651         {
652         needRulesReloading = false;
653         traffCnt->Reload();
654
655         modIter = modules.begin();
656         for (; modIter != modules.end(); ++modIter)
657             {
658             if (modIter->Reload())
659                 {
660                 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
661                                                           modIter->GetStrError().c_str());
662                 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
663                                                                  modIter->GetStrError().c_str());
664                 }
665             }
666         }
667     stgUsleep(100000);
668     }
669
670 exitLbl:
671
672 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
673
674 //Sort by start order
675 modules.sort(StopModCmp);
676 modIter = modules.begin();
677 while (modIter != modules.end())
678     {
679     std::string name = modIter->GetFileName();
680     printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
681     if (modIter->Stop())
682         {
683         WriteServLog("Module \'%s\': Error: %s",
684                      modIter->GetPlugin()->GetVersion().c_str(),
685                      modIter->GetStrError().c_str());
686         printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
687         //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
688         //goto exitLbl;
689         }
690     WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
691     ++modIter;
692     }
693
694 if (loop.Stop())
695     {
696     WriteServLog("Event loop not stopped.");
697     }
698
699 exitLblNotStarted:
700
701 modIter = modules.begin();
702 while (modIter != modules.end())
703     {
704     std::string name = modIter->GetFileName();
705     printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
706     if (modIter->Unload())
707         {
708         WriteServLog("Module \'%s\': Error: %s",
709                      name.c_str(),
710                      modIter->GetStrError().c_str());
711         printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
712         }
713     ++modIter;
714     }
715
716 if (traffCnt)
717     {
718     traffCnt->Stop();
719     WriteServLog("Traffcounter: Stop successfull.");
720     }
721
722 if (users)
723     {
724     users->Stop();
725     WriteServLog("Users: Stop successfull.");
726     }
727
728 sleep(1);
729 int res = msgctl(msgID, IPC_RMID, NULL);
730 if (res)
731     WriteServLog("Queue was not removed. id=%d", msgID);
732 else
733     WriteServLog("Queue removed successfully.");
734
735 /*struct sigaction newsa, oldsa;
736 sigset_t sigmask;
737 sigemptyset(&sigmask);
738 sigaddset(&sigmask, SIGCHLD);
739 newsa.sa_handler = SIG_IGN;
740 newsa.sa_mask = sigmask;
741 newsa.sa_flags = 0;
742 sigaction(SIGCHLD, &newsa, &oldsa);*/
743
744 KillExecuters();
745
746 StopStgTimer();
747 WriteServLog("StgTimer: Stop successfull.");
748
749 WriteServLog("Stg stopped successfully.");
750 sleep(1);
751 WriteServLog("---------------------------------------------");
752
753 delete traffCnt;
754 delete users;
755 delete admins;
756 delete tariffs;
757 delete settings;
758
759 return 0;
760 }
761 //-----------------------------------------------------------------------------