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