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