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 $
30 #include <sys/types.h>
41 #include "settings_impl.h"
43 #include "users_impl.h"
44 #include "admins_impl.h"
45 #include "tariffs_impl.h"
47 #include "traffcounter_impl.h"
49 #include "stg_logger.h"
50 #include "stg_timer.h"
51 #include "plugin_runner.h"
52 #include "script_executer.h"
53 #include "conffiles.h"
55 #include "store_loader.h"
57 #include "eventloop.h"
63 #define MAIN_DEBUG (1)
67 #define START_FILE "/._ST_ART_ED_"
69 static bool needRulesReloading = false;
70 static bool childExited = false;
71 //static pid_t executerPid;
72 set<pid_t> executersPid;
73 static pid_t stgChildPid;
77 //-----------------------------------------------------------------------------
78 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
80 return lhs.GetStartPosition() < rhs.GetStartPosition();
82 //-----------------------------------------------------------------------------
83 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
85 return lhs.GetStopPosition() > rhs.GetStopPosition();
87 //-----------------------------------------------------------------------------
91 STG_STOPPER() { nonstop = true; }
92 bool GetStatus() const { return nonstop; };
94 void Stop(const char * __file__, int __line__)
96 void Stop(const char *, int)
100 printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
107 //-----------------------------------------------------------------------------
109 //-----------------------------------------------------------------------------
110 static void StartTimer()
112 STG_LOGGER & WriteServLog = GetStgLogger();
116 WriteServLog("Cannot start timer. Fatal.");
117 //printfd(__FILE__, "Cannot start timer. Fatal.\n");
122 WriteServLog("Timer thread started successfully.");
123 //printfd(__FILE__, "Timer thread started successfully.\n");
126 //-----------------------------------------------------------------------------
131 //-----------------------------------------------------------------------------
132 void CatchTERM(int sig)
135 *Function Name:CatchINT
136 *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
137 *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
140 STG_LOGGER & WriteServLog = GetStgLogger();
141 WriteServLog("Shutting down... %d", sig);
144 nonstop.Stop(__FILE__, __LINE__);
146 struct sigaction newsa, oldsa;
149 sigemptyset(&sigmask);
150 sigaddset(&sigmask, SIGTERM);
151 newsa.sa_handler = SIG_IGN;
152 newsa.sa_mask = sigmask;
154 sigaction(SIGTERM, &newsa, &oldsa);
156 sigemptyset(&sigmask);
157 sigaddset(&sigmask, SIGINT);
158 newsa.sa_handler = SIG_IGN;
159 newsa.sa_mask = sigmask;
161 sigaction(SIGINT, &newsa, &oldsa);
163 //-----------------------------------------------------------------------------
166 STG_LOGGER & WriteServLog = GetStgLogger();
167 WriteServLog("Broken pipe!");
169 //-----------------------------------------------------------------------------
172 needRulesReloading = true;
174 //-----------------------------------------------------------------------------
179 childPid = waitpid(-1, &status, WNOHANG);
181 set<pid_t>::iterator pid;
182 pid = executersPid.find(childPid);
183 if (pid != executersPid.end())
185 executersPid.erase(pid);
186 if (executersPid.empty() && nonstop.GetStatus())
188 nonstop.Stop(__FILE__, __LINE__);
191 if (childPid == stgChildPid)
196 /*//-----------------------------------------------------------------------------
197 void CatchSEGV(int, siginfo_t *, void *)
200 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
201 FILE * f = fopen(fileName, "wt");
204 fprintf(f, "\nSignal info:\n~~~~~~~~~~~~\n");
205 fprintf(f, "numb:\t %d (%d)\n", sinfo->si_signo, sig);
206 fprintf(f, "errn:\t %d\n", sinfo->si_errno);
207 fprintf(f, "code:\t %d ", sinfo->si_code);
209 switch (sinfo->si_code)
212 fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
216 fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
223 fprintf(f, "addr:\t 0x%.8X\n",
224 (unsigned int)sinfo->si_addr);
227 //asm("movl %eip, eip");
228 if (dladdr((void*)CatchCHLD, &dlinfo))
230 fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
234 fprintf(f, "Cannot find SEGV point\n");
240 struct sigaction segv_action, segv_action_old;
242 segv_action.sa_handler = SIG_DFL;
243 segv_action.sa_sigaction = NULL;
244 segv_action.sa_flags = SA_SIGINFO;
245 segv_action.sa_restorer = NULL;
247 sigaction(SIGSEGV, &segv_action, &segv_action_old);
249 //-----------------------------------------------------------------------------
250 static void SetSignalHandlers()
252 struct sigaction newsa, oldsa;
255 sigemptyset(&sigmask);
256 sigaddset(&sigmask, SIGTERM);
257 newsa.sa_handler = CatchTERM;
258 newsa.sa_mask = sigmask;
260 sigaction(SIGTERM, &newsa, &oldsa);
262 sigemptyset(&sigmask);
263 sigaddset(&sigmask, SIGUSR1);
264 newsa.sa_handler = CatchUSR1;
265 newsa.sa_mask = sigmask;
267 sigaction(SIGUSR1, &newsa, &oldsa);
269 sigemptyset(&sigmask);
270 sigaddset(&sigmask, SIGINT);
271 newsa.sa_handler = CatchTERM;
272 newsa.sa_mask = sigmask;
274 sigaction(SIGINT, &newsa, &oldsa);
276 sigemptyset(&sigmask);
277 sigaddset(&sigmask, SIGPIPE);
278 newsa.sa_handler = CatchPIPE;
279 newsa.sa_mask = sigmask;
281 sigaction(SIGPIPE, &newsa, &oldsa);
283 sigemptyset(&sigmask);
284 sigaddset(&sigmask, SIGHUP);
285 newsa.sa_handler = CatchHUP;
286 newsa.sa_mask = sigmask;
288 sigaction(SIGHUP, &newsa, &oldsa);
290 sigemptyset(&sigmask);
291 sigaddset(&sigmask, SIGCHLD);
292 newsa.sa_handler = CatchCHLD;
293 newsa.sa_mask = sigmask;
295 sigaction(SIGCHLD, &newsa, &oldsa);
297 /*newsa.sa_handler = NULL;
298 newsa.sa_sigaction = CatchSEGV;
299 newsa.sa_flags = SA_SIGINFO;
300 newsa.sa_restorer = NULL;
301 sigaction(SIGSEGV, &newsa, &oldsa);*/
305 //-----------------------------------------------------------------------------
306 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
308 STG_LOGGER & WriteServLog = GetStgLogger();
310 if (*msgID == -11) // If msgID == -11 - first call. Create queue
312 for (int i = 0; i < 2; i++)
314 *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
318 *msgID = msgget(msgKey, 0);
321 WriteServLog("Message queue not created.");
326 msgctl(*msgID, IPC_RMID, NULL);
331 WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
337 pid_t executerPid = fork();
342 WriteServLog("Fork error!");
347 Executer(msgKey, *msgID, executerPid, procName);
351 if (executersPid.empty()) {
352 Executer(msgKey, *msgID, executerPid, NULL);
354 executersPid.insert(executerPid);
358 //-----------------------------------------------------------------------------
360 int ForkAndWait(const string & confDir)
362 int ForkAndWait(const string &)
366 stgChildPid = fork();
367 string startFile = confDir + START_FILE;
368 unlink(startFile.c_str());
383 struct timespec ts = {0, 200000000};
384 for (int i = 0; i < 120 * 5; i++)
386 if (access(startFile.c_str(), F_OK) == 0)
388 unlink(startFile.c_str());
394 unlink(startFile.c_str());
397 nanosleep(&ts, NULL);
399 unlink(startFile.c_str());
406 //-----------------------------------------------------------------------------
409 set<pid_t>::iterator pid;
410 pid = executersPid.begin();
411 while (pid != executersPid.end())
413 printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
418 //-----------------------------------------------------------------------------
419 int main(int argc, char * argv[])
423 Initialization order:
436 - Set signal nandlers
440 SETTINGS_IMPL * settings = NULL;
441 STORE * dataStore = NULL;
442 TARIFFS_IMPL * tariffs = NULL;
443 ADMINS_IMPL * admins = NULL;
444 USERS_IMPL * users = NULL;
445 TRAFFCOUNTER_IMPL * traffCnt = NULL;
449 STG_LOGGER & WriteServLog = GetStgLogger();
450 WriteServLog.SetLogFileName("/var/log/stargazer.log");
453 vector<MODULE_SETTINGS> modSettings;
454 list<PLUGIN_RUNNER> modules;
456 list<PLUGIN_RUNNER>::iterator modIter;
460 printf("You must be root. Exit.\n");
465 settings = new SETTINGS_IMPL(argv[1]);
467 settings = new SETTINGS_IMPL();
469 if (settings->ReadSettings())
471 STG_LOGGER & WriteServLog = GetStgLogger();
473 if (settings->GetLogFileName() != "")
474 WriteServLog.SetLogFileName(settings->GetLogFileName());
476 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
481 string startFile(settings->GetConfDir() + START_FILE);
484 if (ForkAndWait(settings->GetConfDir()) < 0)
486 STG_LOGGER & WriteServLog = GetStgLogger();
487 WriteServLog("Fork error!");
491 STG_LOGGER & WriteServLog = GetStgLogger();
492 WriteServLog.SetLogFileName(settings->GetLogFileName());
493 WriteServLog("Stg v. %s", SERVER_VERSION);
495 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
497 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
500 STG_LOGGER & WriteServLog = GetStgLogger();
501 WriteServLog("Start Script Executer error!");
511 PIDFile pidFile(settings->GetPIDFileName());
515 if (!IsStgTimerRunning())
517 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
518 WriteServLog("Timer thread not started in 1 sec!");
521 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
523 STORE_LOADER storeLoader(*settings);
524 if (storeLoader.Load())
526 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
527 goto exitLblNotStarted;
532 WriteServLog("Event loop not started.");
533 goto exitLblNotStarted;
536 dataStore = storeLoader.GetStore();
537 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
539 tariffs = new TARIFFS_IMPL(dataStore);
540 admins = new ADMINS_IMPL(dataStore);
541 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
542 traffCnt = new TRAFFCOUNTER_IMPL(users, tariffs, settings->GetRulesFileName());
543 traffCnt->SetMonitorDir(settings->GetMonitorDir());
545 modSettings = settings->GetModulesSettings();
547 for (size_t i = 0; i < modSettings.size(); i++)
549 string modulePath = settings->GetModulesPath();
550 modulePath += "/mod_";
551 modulePath += modSettings[i].moduleName;
553 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
555 PLUGIN_RUNNER(modulePath,
566 modIter = modules.begin();
568 while (modIter != modules.end())
573 WriteServLog("Error: %s",
574 modIter->GetStrError().c_str());
575 goto exitLblNotStarted;
583 goto exitLblNotStarted;
585 WriteServLog("Users started successfully.");
587 if (traffCnt->Start())
589 goto exitLblNotStarted;
591 WriteServLog("Traffcounter started successfully.");
593 //Sort by start order
594 modules.sort(StartModCmp);
595 modIter = modules.begin();
597 while (modIter != modules.end())
599 if (modIter->Start())
601 WriteServLog("Error: %s",
602 modIter->GetStrError().c_str());
603 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
606 WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
614 * Note that an implementation in which nice returns the new nice value
615 * can legitimately return -1. To reliably detect an error, set
616 * errno to 0 before the call, and check its value when nice returns -1.
622 if (nice(-19) && errno) {
623 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
624 WriteServLog("nice failed: '%s'", strerror(errno));
627 WriteServLog("Stg started successfully.");
628 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
631 creat(startFile.c_str(), S_IRUSR);
634 while (nonstop.GetStatus())
636 if (needRulesReloading)
638 needRulesReloading = false;
641 modIter = modules.begin();
642 for (; modIter != modules.end(); ++modIter)
644 if (modIter->Reload())
646 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
647 modIter->GetStrError().c_str());
648 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
649 modIter->GetStrError().c_str());
658 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
660 //Sort by start order
661 modules.sort(StopModCmp);
662 modIter = modules.begin();
663 while (modIter != modules.end())
665 std::string name = modIter->GetFileName();
666 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
669 WriteServLog("Module \'%s\': Error: %s",
670 modIter->GetPlugin()->GetVersion().c_str(),
671 modIter->GetStrError().c_str());
672 printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
673 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
676 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
682 WriteServLog("Event loop not stopped.");
687 modIter = modules.begin();
688 while (modIter != modules.end())
690 std::string name = modIter->GetFileName();
691 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
692 if (modIter->Unload())
694 WriteServLog("Module \'%s\': Error: %s",
696 modIter->GetStrError().c_str());
697 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
705 WriteServLog("Traffcounter: Stop successfull.");
711 WriteServLog("Users: Stop successfull.");
715 int res = msgctl(msgID, IPC_RMID, NULL);
717 WriteServLog("Queue was not removed. id=%d", msgID);
719 WriteServLog("Queue removed successfully.");
724 WriteServLog("StgTimer: Stop successfull.");
732 WriteServLog("Stg stopped successfully.");
733 WriteServLog("---------------------------------------------");
737 //-----------------------------------------------------------------------------