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>
32 #include <sys/stat.h> // S_IRUSR
33 #include <fcntl.h> // create
44 #include "stg/common.h"
45 #include "stg/plugin.h"
46 #include "stg/logger.h"
47 #include "stg/scriptexecuter.h"
48 #include "stg/conffiles.h"
49 #include "stg/version.h"
50 #include "stg/pinger.h"
51 #include "stg_timer.h"
52 #include "settings_impl.h"
53 #include "users_impl.h"
54 #include "admins_impl.h"
55 #include "tariffs_impl.h"
56 #include "traffcounter_impl.h"
57 #include "plugin_runner.h"
58 #include "store_loader.h"
60 #include "eventloop.h"
66 #define MAIN_DEBUG (1)
70 #define START_FILE "/._ST_ART_ED_"
72 static bool needRulesReloading = false;
73 static bool childExited = false;
74 //static pid_t executerPid;
75 set<pid_t> executersPid;
76 static pid_t stgChildPid;
79 //-----------------------------------------------------------------------------
80 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
82 return lhs.GetStartPosition() < rhs.GetStartPosition();
84 //-----------------------------------------------------------------------------
85 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
87 return lhs.GetStopPosition() > rhs.GetStopPosition();
89 //-----------------------------------------------------------------------------
93 STG_STOPPER() { nonstop = true; }
94 bool GetStatus() const { return nonstop; };
96 void Stop(const char * __file__, int __line__)
98 void Stop(const char *, int)
102 printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
109 //-----------------------------------------------------------------------------
111 //-----------------------------------------------------------------------------
112 static void StartTimer()
114 STG_LOGGER & WriteServLog = GetStgLogger();
118 WriteServLog("Cannot start timer. Fatal.");
119 //printfd(__FILE__, "Cannot start timer. Fatal.\n");
124 WriteServLog("Timer thread started successfully.");
125 //printfd(__FILE__, "Timer thread started successfully.\n");
128 //-----------------------------------------------------------------------------
133 //-----------------------------------------------------------------------------
134 void CatchTERM(int sig)
137 *Function Name:CatchINT
138 *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
139 *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
142 STG_LOGGER & WriteServLog = GetStgLogger();
143 WriteServLog("Shutting down... %d", sig);
146 nonstop.Stop(__FILE__, __LINE__);
148 struct sigaction newsa, oldsa;
151 sigemptyset(&sigmask);
152 sigaddset(&sigmask, SIGTERM);
153 newsa.sa_handler = SIG_IGN;
154 newsa.sa_mask = sigmask;
156 sigaction(SIGTERM, &newsa, &oldsa);
158 sigemptyset(&sigmask);
159 sigaddset(&sigmask, SIGINT);
160 newsa.sa_handler = SIG_IGN;
161 newsa.sa_mask = sigmask;
163 sigaction(SIGINT, &newsa, &oldsa);
165 //-----------------------------------------------------------------------------
168 STG_LOGGER & WriteServLog = GetStgLogger();
169 WriteServLog("Broken pipe!");
171 //-----------------------------------------------------------------------------
174 needRulesReloading = true;
176 //-----------------------------------------------------------------------------
181 childPid = waitpid(-1, &status, WNOHANG);
183 set<pid_t>::iterator pid;
184 pid = executersPid.find(childPid);
185 if (pid != executersPid.end())
187 executersPid.erase(pid);
188 if (executersPid.empty() && nonstop.GetStatus())
190 nonstop.Stop(__FILE__, __LINE__);
193 if (childPid == stgChildPid)
198 /*//-----------------------------------------------------------------------------
199 void CatchSEGV(int, siginfo_t *, void *)
202 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
203 FILE * f = fopen(fileName, "wt");
206 fprintf(f, "\nSignal info:\n~~~~~~~~~~~~\n");
207 fprintf(f, "numb:\t %d (%d)\n", sinfo->si_signo, sig);
208 fprintf(f, "errn:\t %d\n", sinfo->si_errno);
209 fprintf(f, "code:\t %d ", sinfo->si_code);
211 switch (sinfo->si_code)
214 fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
218 fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
225 fprintf(f, "addr:\t 0x%.8X\n",
226 (unsigned int)sinfo->si_addr);
229 //asm("movl %eip, eip");
230 if (dladdr((void*)CatchCHLD, &dlinfo))
232 fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
236 fprintf(f, "Cannot find SEGV point\n");
242 struct sigaction segv_action, segv_action_old;
244 segv_action.sa_handler = SIG_DFL;
245 segv_action.sa_sigaction = NULL;
246 segv_action.sa_flags = SA_SIGINFO;
247 segv_action.sa_restorer = NULL;
249 sigaction(SIGSEGV, &segv_action, &segv_action_old);
251 //-----------------------------------------------------------------------------
252 static void SetSignalHandlers()
254 struct sigaction newsa, oldsa;
257 sigemptyset(&sigmask);
258 sigaddset(&sigmask, SIGTERM);
259 newsa.sa_handler = CatchTERM;
260 newsa.sa_mask = sigmask;
262 sigaction(SIGTERM, &newsa, &oldsa);
264 sigemptyset(&sigmask);
265 sigaddset(&sigmask, SIGUSR1);
266 newsa.sa_handler = CatchUSR1;
267 newsa.sa_mask = sigmask;
269 sigaction(SIGUSR1, &newsa, &oldsa);
271 sigemptyset(&sigmask);
272 sigaddset(&sigmask, SIGINT);
273 newsa.sa_handler = CatchTERM;
274 newsa.sa_mask = sigmask;
276 sigaction(SIGINT, &newsa, &oldsa);
278 sigemptyset(&sigmask);
279 sigaddset(&sigmask, SIGPIPE);
280 newsa.sa_handler = CatchPIPE;
281 newsa.sa_mask = sigmask;
283 sigaction(SIGPIPE, &newsa, &oldsa);
285 sigemptyset(&sigmask);
286 sigaddset(&sigmask, SIGHUP);
287 newsa.sa_handler = CatchHUP;
288 newsa.sa_mask = sigmask;
290 sigaction(SIGHUP, &newsa, &oldsa);
292 sigemptyset(&sigmask);
293 sigaddset(&sigmask, SIGCHLD);
294 newsa.sa_handler = CatchCHLD;
295 newsa.sa_mask = sigmask;
297 sigaction(SIGCHLD, &newsa, &oldsa);
299 /*newsa.sa_handler = NULL;
300 newsa.sa_sigaction = CatchSEGV;
301 newsa.sa_flags = SA_SIGINFO;
302 newsa.sa_restorer = NULL;
303 sigaction(SIGSEGV, &newsa, &oldsa);*/
307 //-----------------------------------------------------------------------------
308 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
310 STG_LOGGER & WriteServLog = GetStgLogger();
312 if (*msgID == -11) // If msgID == -11 - first call. Create queue
314 for (int i = 0; i < 2; i++)
316 *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
320 *msgID = msgget(msgKey, 0);
323 WriteServLog("Message queue not created.");
328 msgctl(*msgID, IPC_RMID, NULL);
333 WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
339 pid_t executerPid = fork();
344 WriteServLog("Fork error!");
349 Executer(msgKey, *msgID, executerPid, procName);
353 if (executersPid.empty()) {
354 Executer(msgKey, *msgID, executerPid, NULL);
356 executersPid.insert(executerPid);
360 //-----------------------------------------------------------------------------
362 int ForkAndWait(const string & confDir)
364 int ForkAndWait(const string &)
368 stgChildPid = fork();
369 string startFile = confDir + START_FILE;
370 unlink(startFile.c_str());
385 struct timespec ts = {0, 200000000};
386 for (int i = 0; i < 120 * 5; i++)
388 if (access(startFile.c_str(), F_OK) == 0)
390 unlink(startFile.c_str());
396 unlink(startFile.c_str());
399 nanosleep(&ts, NULL);
401 unlink(startFile.c_str());
408 //-----------------------------------------------------------------------------
411 set<pid_t>::iterator pid;
412 pid = executersPid.begin();
413 while (pid != executersPid.end())
415 printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
420 //-----------------------------------------------------------------------------
421 int main(int argc, char * argv[])
425 Initialization order:
438 - Set signal nandlers
442 SETTINGS_IMPL * settings = NULL;
443 STORE * dataStore = NULL;
444 TARIFFS_IMPL * tariffs = NULL;
445 ADMINS_IMPL * admins = NULL;
446 USERS_IMPL * users = NULL;
447 TRAFFCOUNTER_IMPL * traffCnt = NULL;
451 STG_LOGGER & WriteServLog = GetStgLogger();
452 WriteServLog.SetLogFileName("/var/log/stargazer.log");
455 vector<MODULE_SETTINGS> modSettings;
456 list<PLUGIN_RUNNER> modules;
458 list<PLUGIN_RUNNER>::iterator modIter;
462 printf("You must be root. Exit.\n");
467 settings = new SETTINGS_IMPL(argv[1]);
469 settings = new SETTINGS_IMPL();
471 if (settings->ReadSettings())
473 STG_LOGGER & WriteServLog = GetStgLogger();
475 if (settings->GetLogFileName() != "")
476 WriteServLog.SetLogFileName(settings->GetLogFileName());
478 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
483 string startFile(settings->GetConfDir() + START_FILE);
486 if (ForkAndWait(settings->GetConfDir()) < 0)
488 STG_LOGGER & WriteServLog = GetStgLogger();
489 WriteServLog("Fork error!");
493 STG_LOGGER & WriteServLog = GetStgLogger();
494 WriteServLog.SetLogFileName(settings->GetLogFileName());
495 WriteServLog("Stg v. %s", SERVER_VERSION);
497 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
499 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
502 STG_LOGGER & WriteServLog = GetStgLogger();
503 WriteServLog("Start Script Executer error!");
513 PIDFile pidFile(settings->GetPIDFileName());
517 if (!IsStgTimerRunning())
519 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
520 WriteServLog("Timer thread not started in 1 sec!");
523 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
525 STORE_LOADER storeLoader(*settings);
526 if (storeLoader.Load())
528 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
529 goto exitLblNotStarted;
534 WriteServLog("Event loop not started.");
535 goto exitLblNotStarted;
538 dataStore = storeLoader.GetStore();
539 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
541 tariffs = new TARIFFS_IMPL(dataStore);
542 admins = new ADMINS_IMPL(dataStore);
543 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
544 traffCnt = new TRAFFCOUNTER_IMPL(users, settings->GetRulesFileName());
545 traffCnt->SetMonitorDir(settings->GetMonitorDir());
547 modSettings = settings->GetModulesSettings();
549 for (size_t i = 0; i < modSettings.size(); i++)
551 string modulePath = settings->GetModulesPath();
552 modulePath += "/mod_";
553 modulePath += modSettings[i].moduleName;
555 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
557 PLUGIN_RUNNER(modulePath,
568 modIter = modules.begin();
570 while (modIter != modules.end())
575 WriteServLog("Error: %s",
576 modIter->GetStrError().c_str());
577 goto exitLblNotStarted;
585 goto exitLblNotStarted;
587 WriteServLog("Users started successfully.");
589 if (traffCnt->Start())
591 goto exitLblNotStarted;
593 WriteServLog("Traffcounter started successfully.");
595 //Sort by start order
596 modules.sort(StartModCmp);
597 modIter = modules.begin();
599 while (modIter != modules.end())
601 if (modIter->Start())
603 WriteServLog("Error: %s",
604 modIter->GetStrError().c_str());
605 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
608 WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
616 * Note that an implementation in which nice returns the new nice value
617 * can legitimately return -1. To reliably detect an error, set
618 * errno to 0 before the call, and check its value when nice returns -1.
624 if (nice(-19) && errno) {
625 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
626 WriteServLog("nice failed: '%s'", strerror(errno));
629 WriteServLog("Stg started successfully.");
630 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
633 creat(startFile.c_str(), S_IRUSR);
636 while (nonstop.GetStatus())
638 if (needRulesReloading)
640 needRulesReloading = false;
643 modIter = modules.begin();
644 for (; modIter != modules.end(); ++modIter)
646 if (modIter->Reload())
648 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
649 modIter->GetStrError().c_str());
650 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
651 modIter->GetStrError().c_str());
660 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
662 //Sort by start order
663 modules.sort(StopModCmp);
664 modIter = modules.begin();
665 while (modIter != modules.end())
667 std::string name = modIter->GetFileName();
668 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
671 WriteServLog("Module \'%s\': Error: %s",
672 modIter->GetPlugin()->GetVersion().c_str(),
673 modIter->GetStrError().c_str());
674 printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
675 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
678 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
684 WriteServLog("Event loop not stopped.");
689 modIter = modules.begin();
690 while (modIter != modules.end())
692 std::string name = modIter->GetFileName();
693 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
694 if (modIter->Unload())
696 WriteServLog("Module \'%s\': Error: %s",
698 modIter->GetStrError().c_str());
699 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
707 WriteServLog("Traffcounter: Stop successfull.");
713 WriteServLog("Users: Stop successfull.");
717 int res = msgctl(msgID, IPC_RMID, NULL);
719 WriteServLog("Queue was not removed. id=%d", msgID);
721 WriteServLog("Queue removed successfully.");
726 WriteServLog("StgTimer: Stop successfull.");
734 WriteServLog("Stg stopped successfully.");
735 WriteServLog("---------------------------------------------");
739 //-----------------------------------------------------------------------------