]> git.stg.codes - stg.git/blob - projects/stargazer/main.cpp
Fix compilation issues after splitting SETTINGS into interface and
[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         for (int i = 0; i < 120 * 5; i++)
390             {
391             if (access(startFile.c_str(), F_OK) == 0)
392                 {
393                 unlink(startFile.c_str());
394                 exit(0);
395                 }
396
397             if (childExited)
398                 {
399                 unlink(startFile.c_str());
400                 exit(1);
401                 }
402             usleep(200000);
403             }
404         unlink(startFile.c_str());
405         exit(1);
406         break;
407     }
408 #endif
409 return 0;
410 }
411 //-----------------------------------------------------------------------------
412 void KillExecuters()
413 {
414 set<pid_t>::iterator pid;
415 pid = executersPid.begin();
416 while (pid != executersPid.end())
417     {
418     printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
419     kill(*pid, SIGUSR1);
420     ++pid;
421     }
422 }
423 //-----------------------------------------------------------------------------
424 int main(int argc, char * argv[])
425 {
426
427 /*
428   Initialization order:
429   - Logger
430   - Stg timer
431   - Settings
432   - Plugins
433   - Plugins settings
434   - Read Admins
435   - Read Tariffs
436   - Read Users
437   - Start Users
438   - Start Traffcounter
439   - Start Plugins
440   - Start pinger
441   - Set signal nandlers
442   - Fork and exit
443  * */
444
445 SETTINGS_IMPL * settings = NULL;
446 STORE * dataStore = NULL;
447 TARIFFS_IMPL * tariffs = NULL;
448 ADMINS_IMPL * admins = NULL;
449 USERS_IMPL * users = NULL;
450 TRAFFCOUNTER * traffCnt = NULL;
451 int msgID = -11;
452
453     {
454     STG_LOGGER & WriteServLog = GetStgLogger();
455     WriteServLog.SetLogFileName("/var/log/stargazer.log");
456     }
457
458 vector<MODULE_SETTINGS> modSettings;
459 list<PLUGIN_RUNNER> modules;
460
461 list<PLUGIN_RUNNER>::iterator modIter;
462
463 if (getuid())
464     {
465     printf("You must be root. Exit.\n");
466     exit(1);
467     }
468
469 if (argc == 2)
470     settings = new SETTINGS_IMPL(argv[1]);
471 else
472     settings = new SETTINGS_IMPL();
473
474 if (settings->ReadSettings())
475     {
476     STG_LOGGER & WriteServLog = GetStgLogger();
477
478     if (settings->GetLogFileName() != "")
479         WriteServLog.SetLogFileName(settings->GetLogFileName());
480
481     WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
482     exit(1);
483     }
484
485 #ifndef NO_DAEMON
486 string startFile(settings->GetConfDir() + START_FILE);
487 #endif
488
489 if (ForkAndWait(settings->GetConfDir()) < 0)
490     {
491     STG_LOGGER & WriteServLog = GetStgLogger();
492     WriteServLog("Fork error!");
493     exit(1);
494     }
495
496 STG_LOGGER & WriteServLog = GetStgLogger();
497 WriteServLog.SetLogFileName(settings->GetLogFileName());
498 WriteServLog("Stg v. %s", SERVER_VERSION);
499
500 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
501     {
502     int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
503     if (ret < 0)
504         {
505         STG_LOGGER & WriteServLog = GetStgLogger();
506         WriteServLog("Start Script Executer error!");
507         return 1;
508         }
509     if (ret == 1)
510         {
511         // Stopping child
512         return 0;
513         }
514     }
515
516 PIDFile pidFile(settings->GetPIDFileName());
517
518 StartTimer();
519 WaitTimer();
520 if (!IsStgTimerRunning())
521     {
522     printfd(__FILE__, "Timer thread not started in 1 sec!\n");
523     WriteServLog("Timer thread not started in 1 sec!");
524     }
525
526 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
527
528 STORE_LOADER storeLoader(*settings);
529 if (storeLoader.Load())
530     {
531     WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
532     goto exitLblNotStarted;
533     }
534
535 if (loop.Start())
536     {
537     WriteServLog("Event loop not started.");
538     goto exitLblNotStarted;
539     }
540
541 dataStore = storeLoader.GetStore();
542 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
543
544 tariffs = new TARIFFS_IMPL(dataStore);
545 admins = new ADMINS_IMPL(dataStore);
546 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
547 traffCnt = new TRAFFCOUNTER(users, tariffs, settings->GetRulesFileName());
548 traffCnt->SetMonitorDir(settings->GetMonitorDir());
549
550 modSettings = settings->GetModulesSettings();
551
552 for (size_t i = 0; i < modSettings.size(); i++)
553     {
554     string modulePath = settings->GetModulesPath();
555     modulePath += "/mod_";
556     modulePath += modSettings[i].moduleName;
557     modulePath += ".so";
558     printfd(__FILE__, "Module: %s\n", modulePath.c_str());
559     modules.push_back(
560         PLUGIN_RUNNER(modulePath,
561                       modSettings[i],
562                       admins,
563                       tariffs,
564                       users,
565                       traffCnt,
566                       dataStore,
567                       settings)
568         );
569     }
570
571 modIter = modules.begin();
572
573 while (modIter != modules.end())
574     {
575     //Loading modules
576     if (modIter->Load())
577         {
578         WriteServLog("Error: %s",
579                      modIter->GetStrError().c_str());
580         goto exitLblNotStarted;
581         }
582     ++modIter;
583     }
584
585 //Start section
586 if (users->Start())
587     {
588     goto exitLblNotStarted;
589     }
590 WriteServLog("Users started successfully.");
591
592 if (traffCnt->Start())
593     {
594     goto exitLblNotStarted;
595     }
596 WriteServLog("Traffcounter started successfully.");
597
598 //Sort by start order
599 modules.sort(StartModCmp);
600 modIter = modules.begin();
601
602 while (modIter != modules.end())
603     {
604     if (modIter->Start())
605         {
606         WriteServLog("Error: %s",
607                      modIter->GetStrError().c_str());
608         //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
609         goto exitLbl;
610         }
611     WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
612     ++modIter;
613     }
614 SetSignalHandlers();
615
616 srandom(stgTime);
617
618 /*
619  * Note that an implementation in which nice returns the new nice value
620  * can legitimately return -1.   To  reliably  detect  an  error,  set
621  * errno to 0 before the call, and check its value when nice returns -1.
622  *
623  *
624  * (c) man 2 nice
625  */
626 errno = 0;
627 if (nice(-19) && errno) {
628     printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
629     WriteServLog("nice failed: '%s'", strerror(errno));
630 }
631
632 WriteServLog("Stg started successfully.");
633 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
634
635 #ifndef NO_DAEMON
636 creat(startFile.c_str(), S_IRUSR);
637 #endif
638
639 while (nonstop.GetStatus())
640     {
641     if (needRulesReloading)
642         {
643         needRulesReloading = false;
644         traffCnt->Reload();
645
646         modIter = modules.begin();
647         for (; modIter != modules.end(); ++modIter)
648             {
649             if (modIter->Reload())
650                 {
651                 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
652                                                           modIter->GetStrError().c_str());
653                 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
654                                                                  modIter->GetStrError().c_str());
655                 }
656             }
657         }
658     stgUsleep(100000);
659     }
660
661 exitLbl:
662
663 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
664
665 //Sort by start order
666 modules.sort(StopModCmp);
667 modIter = modules.begin();
668 while (modIter != modules.end())
669     {
670     std::string name = modIter->GetFileName();
671     printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
672     if (modIter->Stop())
673         {
674         WriteServLog("Module \'%s\': Error: %s",
675                      modIter->GetPlugin()->GetVersion().c_str(),
676                      modIter->GetStrError().c_str());
677         printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
678         //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
679         //goto exitLbl;
680         }
681     WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
682     ++modIter;
683     }
684
685 if (loop.Stop())
686     {
687     WriteServLog("Event loop not stopped.");
688     }
689
690 exitLblNotStarted:
691
692 modIter = modules.begin();
693 while (modIter != modules.end())
694     {
695     std::string name = modIter->GetFileName();
696     printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
697     if (modIter->Unload())
698         {
699         WriteServLog("Module \'%s\': Error: %s",
700                      name.c_str(),
701                      modIter->GetStrError().c_str());
702         printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
703         }
704     ++modIter;
705     }
706
707 if (traffCnt)
708     {
709     traffCnt->Stop();
710     WriteServLog("Traffcounter: Stop successfull.");
711     }
712
713 if (users)
714     {
715     users->Stop();
716     WriteServLog("Users: Stop successfull.");
717     }
718
719 sleep(1);
720 int res = msgctl(msgID, IPC_RMID, NULL);
721 if (res)
722     WriteServLog("Queue was not removed. id=%d", msgID);
723 else
724     WriteServLog("Queue removed successfully.");
725
726 KillExecuters();
727
728 StopStgTimer();
729 WriteServLog("StgTimer: Stop successfull.");
730
731 delete traffCnt;
732 delete users;
733 delete admins;
734 delete tariffs;
735 delete settings;
736
737 WriteServLog("Stg stopped successfully.");
738 WriteServLog("---------------------------------------------");
739
740 return 0;
741 }
742 //-----------------------------------------------------------------------------