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