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