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