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.
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.
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
18 * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
23 $Date: 2010/10/04 20:19:12 $
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
52 #include "traffcounter.h"
53 #include "base_plugin.h"
54 #include "stg_logger.h"
55 #include "stg_timer.h"
56 #include "plugin_runner.h"
57 #include "script_executer.h"
58 #include "conffiles.h"
60 #include "store_loader.h"
62 #include "eventloop.h"
68 #define MAIN_DEBUG (1)
72 #define START_FILE "/._ST_ART_ED_"
74 static bool needRulesReloading = false;
75 static bool childExited = false;
76 //static pid_t executerPid;
77 set<pid_t> executersPid;
78 static pid_t stgChildPid;
82 //-----------------------------------------------------------------------------
83 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
85 return lhs.GetStartPosition() < rhs.GetStartPosition();
87 //-----------------------------------------------------------------------------
88 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
90 return lhs.GetStopPosition() > rhs.GetStopPosition();
92 //-----------------------------------------------------------------------------
96 STG_STOPPER() { nonstop = true; }
97 bool GetStatus() const { return nonstop; };
99 void Stop(const char * __file__, int __line__)
101 void Stop(const char *, int)
105 printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
112 //-----------------------------------------------------------------------------
114 //-----------------------------------------------------------------------------
115 static void StartTimer()
117 STG_LOGGER & WriteServLog = GetStgLogger();
121 WriteServLog("Cannot start timer. Fatal.");
122 //printfd(__FILE__, "Cannot start timer. Fatal.\n");
127 WriteServLog("Timer thread started successfully.");
128 //printfd(__FILE__, "Timer thread started successfully.\n");
131 //-----------------------------------------------------------------------------
136 //-----------------------------------------------------------------------------
137 void CatchTERM(int sig)
140 *Function Name:CatchINT
141 *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
142 *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
145 STG_LOGGER & WriteServLog = GetStgLogger();
146 WriteServLog("Shutting down... %d", sig);
149 nonstop.Stop(__FILE__, __LINE__);
151 struct sigaction newsa, oldsa;
154 sigemptyset(&sigmask);
155 sigaddset(&sigmask, SIGTERM);
156 newsa.sa_handler = SIG_IGN;
157 newsa.sa_mask = sigmask;
159 sigaction(SIGTERM, &newsa, &oldsa);
161 sigemptyset(&sigmask);
162 sigaddset(&sigmask, SIGINT);
163 newsa.sa_handler = SIG_IGN;
164 newsa.sa_mask = sigmask;
166 sigaction(SIGINT, &newsa, &oldsa);
168 //-----------------------------------------------------------------------------
171 STG_LOGGER & WriteServLog = GetStgLogger();
172 WriteServLog("Broken pipe!");
174 //-----------------------------------------------------------------------------
177 needRulesReloading = true;
179 //-----------------------------------------------------------------------------
184 childPid = waitpid(-1, &status, WNOHANG);
186 set<pid_t>::iterator pid;
187 pid = executersPid.find(childPid);
188 if (pid != executersPid.end())
190 executersPid.erase(pid);
191 if (executersPid.empty() && nonstop.GetStatus())
193 nonstop.Stop(__FILE__, __LINE__);
196 if (childPid == stgChildPid)
201 /*//-----------------------------------------------------------------------------
202 void CatchSEGV(int, siginfo_t *, void *)
205 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
206 FILE * f = fopen(fileName, "wt");
209 fprintf(f, "\nSignal info:\n~~~~~~~~~~~~\n");
210 fprintf(f, "numb:\t %d (%d)\n", sinfo->si_signo, sig);
211 fprintf(f, "errn:\t %d\n", sinfo->si_errno);
212 fprintf(f, "code:\t %d ", sinfo->si_code);
214 switch (sinfo->si_code)
217 fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
221 fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
228 fprintf(f, "addr:\t 0x%.8X\n",
229 (unsigned int)sinfo->si_addr);
232 //asm("movl %eip, eip");
233 if (dladdr((void*)CatchCHLD, &dlinfo))
235 fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
239 fprintf(f, "Cannot find SEGV point\n");
245 struct sigaction segv_action, segv_action_old;
247 segv_action.sa_handler = SIG_DFL;
248 segv_action.sa_sigaction = NULL;
249 segv_action.sa_flags = SA_SIGINFO;
250 segv_action.sa_restorer = NULL;
252 sigaction(SIGSEGV, &segv_action, &segv_action_old);
254 //-----------------------------------------------------------------------------
255 static void SetSignalHandlers()
257 struct sigaction newsa, oldsa;
260 sigemptyset(&sigmask);
261 sigaddset(&sigmask, SIGTERM);
262 newsa.sa_handler = CatchTERM;
263 newsa.sa_mask = sigmask;
265 sigaction(SIGTERM, &newsa, &oldsa);
267 sigemptyset(&sigmask);
268 sigaddset(&sigmask, SIGUSR1);
269 newsa.sa_handler = CatchUSR1;
270 newsa.sa_mask = sigmask;
272 sigaction(SIGUSR1, &newsa, &oldsa);
274 sigemptyset(&sigmask);
275 sigaddset(&sigmask, SIGINT);
276 newsa.sa_handler = CatchTERM;
277 newsa.sa_mask = sigmask;
279 sigaction(SIGINT, &newsa, &oldsa);
281 sigemptyset(&sigmask);
282 sigaddset(&sigmask, SIGPIPE);
283 newsa.sa_handler = CatchPIPE;
284 newsa.sa_mask = sigmask;
286 sigaction(SIGPIPE, &newsa, &oldsa);
288 sigemptyset(&sigmask);
289 sigaddset(&sigmask, SIGHUP);
290 newsa.sa_handler = CatchHUP;
291 newsa.sa_mask = sigmask;
293 sigaction(SIGHUP, &newsa, &oldsa);
295 sigemptyset(&sigmask);
296 sigaddset(&sigmask, SIGCHLD);
297 newsa.sa_handler = CatchCHLD;
298 newsa.sa_mask = sigmask;
300 sigaction(SIGCHLD, &newsa, &oldsa);
302 /*newsa.sa_handler = NULL;
303 newsa.sa_sigaction = CatchSEGV;
304 newsa.sa_flags = SA_SIGINFO;
305 newsa.sa_restorer = NULL;
306 sigaction(SIGSEGV, &newsa, &oldsa);*/
310 //-----------------------------------------------------------------------------
311 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS * settings)
313 STG_LOGGER & WriteServLog = GetStgLogger();
315 if (*msgID == -11) // If msgID == -11 - first call. Create queue
317 for (int i = 0; i < 2; i++)
319 //WriteServLog("Creating queue with key=%d ...", msgKey);
320 *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
324 *msgID = msgget(msgKey, 0);
327 WriteServLog("Message queue not created.");
332 msgctl(*msgID, IPC_RMID, NULL);
333 //printfd(__FILE__, "Queue removed!");
338 WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
344 pid_t executerPid = fork();
349 WriteServLog("Fork error!");
358 Executer(msgKey, *msgID, executerPid, procName);
361 default: // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
362 if (executersPid.empty()) {
363 Executer(msgKey, *msgID, executerPid, NULL);
365 executersPid.insert(executerPid);
369 //-----------------------------------------------------------------------------
371 int ForkAndWait(const string & confDir)
373 int ForkAndWait(const string &)
377 stgChildPid = fork();
378 string startFile = confDir + START_FILE;
379 unlink(startFile.c_str());
394 default: // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
395 for (int i = 0; i < 120 * 5; i++)
397 if (access(startFile.c_str(), F_OK) == 0)
399 //printf("Fork successfull. Exit.\n");
400 unlink(startFile.c_str());
406 unlink(startFile.c_str());
411 unlink(startFile.c_str());
418 //-----------------------------------------------------------------------------
421 set<pid_t>::iterator pid;
422 pid = executersPid.begin();
423 while (pid != executersPid.end())
425 printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
430 //-----------------------------------------------------------------------------
431 int main(int argc, char * argv[])
435 Initialization order:
448 - Set signal nandlers
452 SETTINGS * settings = NULL;
453 BASE_STORE * dataStore = NULL;
454 TARIFFS * tariffs = NULL;
455 ADMINS * admins = NULL;
456 USERS * users = NULL;
457 TRAFFCOUNTER * traffCnt = NULL;
461 STG_LOGGER & WriteServLog = GetStgLogger();
462 WriteServLog.SetLogFileName("/var/log/stargazer.log");
465 vector<MODULE_SETTINGS> modSettings;
466 list<PLUGIN_RUNNER> modules;
468 list<PLUGIN_RUNNER>::iterator modIter;
472 printf("You must be root. Exit.\n");
477 settings = new SETTINGS(argv[1]);
479 settings = new SETTINGS();
481 if (settings->ReadSettings())
483 //printfd(__FILE__, "ReadSettings error.\n");
484 STG_LOGGER & WriteServLog = GetStgLogger();
486 if (settings->GetLogFileName() != "")
487 WriteServLog.SetLogFileName(settings->GetLogFileName());
489 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
494 string startFile(settings->GetConfDir() + START_FILE);
497 if (ForkAndWait(settings->GetConfDir()) < 0)
499 STG_LOGGER & WriteServLog = GetStgLogger();
500 WriteServLog("Fork error!");
504 STG_LOGGER & WriteServLog = GetStgLogger();
505 WriteServLog.SetLogFileName(settings->GetLogFileName());
506 WriteServLog("Stg v. %s", SERVER_VERSION);
508 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
510 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
513 STG_LOGGER & WriteServLog = GetStgLogger();
514 WriteServLog("Start Script Executer error!");
524 PIDFile pidFile(settings->GetPIDFileName());
528 if (!IsStgTimerRunning())
530 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
531 WriteServLog("Timer thread not started in 1 sec!");
534 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
536 STORE_LOADER storeLoader(*settings);
537 if (storeLoader.Load())
539 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
540 goto exitLblNotStarted;
545 WriteServLog("Event loop not started.");
546 goto exitLblNotStarted;
549 dataStore = storeLoader.GetStore();
550 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
552 tariffs = new TARIFFS(dataStore);
553 admins = new ADMINS(dataStore);
554 users = new USERS(settings, dataStore, tariffs, admins->GetSysAdmin());
555 traffCnt = new TRAFFCOUNTER(users, tariffs, settings->GetRulesFileName());
556 traffCnt->SetMonitorDir(settings->GetMonitorDir());
558 modSettings = settings->GetModulesSettings();
560 for (unsigned i = 0; i < modSettings.size(); i++)
562 string modulePath = settings->GetModulesPath();
563 modulePath += "/mod_";
564 modulePath += modSettings[i].moduleName;
566 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
568 PLUGIN_RUNNER(modulePath,
579 modIter = modules.begin();
581 while (modIter != modules.end())
586 WriteServLog("Error: %s",
587 modIter->GetStrError().c_str());
588 goto exitLblNotStarted;
596 goto exitLblNotStarted;
598 WriteServLog("Users started successfully.");
600 if (traffCnt->Start())
602 goto exitLblNotStarted;
604 WriteServLog("Traffcounter started successfully.");
606 //Sort by start order
607 modules.sort(StartModCmp);
608 modIter = modules.begin();
610 while (modIter != modules.end())
612 if (modIter->Start())
614 WriteServLog("Error: %s",
615 modIter->GetStrError().c_str());
616 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
619 WriteServLog("Module: \'%s\'. Start successfull. %d", modIter->GetPlugin()->GetVersion().c_str(),
620 modIter->GetPlugin()->GetStartPosition());
628 * Note that an implementation in which nice returns the new nice value
629 * can legitimately return -1. To reliably detect an error, set
630 * errno to 0 before the call, and check its value when nice returns -1.
636 if (nice(-19) && errno) {
637 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
638 WriteServLog("nice failed: '%s'", strerror(errno));
641 WriteServLog("Stg started successfully.");
642 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
645 creat(startFile.c_str(), S_IRUSR);
648 while (nonstop.GetStatus())
650 if (needRulesReloading)
652 needRulesReloading = false;
655 modIter = modules.begin();
656 for (; modIter != modules.end(); ++modIter)
658 if (modIter->Reload())
660 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
661 modIter->GetStrError().c_str());
662 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
663 modIter->GetStrError().c_str());
672 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
674 //Sort by start order
675 modules.sort(StopModCmp);
676 modIter = modules.begin();
677 while (modIter != modules.end())
679 std::string name = modIter->GetFileName();
680 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
683 WriteServLog("Module \'%s\': Error: %s",
684 modIter->GetPlugin()->GetVersion().c_str(),
685 modIter->GetStrError().c_str());
686 printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
687 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
690 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
696 WriteServLog("Event loop not stopped.");
701 modIter = modules.begin();
702 while (modIter != modules.end())
704 std::string name = modIter->GetFileName();
705 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
706 if (modIter->Unload())
708 WriteServLog("Module \'%s\': Error: %s",
710 modIter->GetStrError().c_str());
711 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
719 WriteServLog("Traffcounter: Stop successfull.");
725 WriteServLog("Users: Stop successfull.");
729 int res = msgctl(msgID, IPC_RMID, NULL);
731 WriteServLog("Queue was not removed. id=%d", msgID);
733 WriteServLog("Queue removed successfully.");
735 /*struct sigaction newsa, oldsa;
737 sigemptyset(&sigmask);
738 sigaddset(&sigmask, SIGCHLD);
739 newsa.sa_handler = SIG_IGN;
740 newsa.sa_mask = sigmask;
742 sigaction(SIGCHLD, &newsa, &oldsa);*/
747 WriteServLog("StgTimer: Stop successfull.");
749 WriteServLog("Stg stopped successfully.");
751 WriteServLog("---------------------------------------------");
761 //-----------------------------------------------------------------------------