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>
49 #include "users_impl.h"
50 #include "admins_impl.h"
51 #include "tariffs_impl.h"
53 #include "traffcounter.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"
61 #include "store_loader.h"
63 #include "eventloop.h"
69 #define MAIN_DEBUG (1)
73 #define START_FILE "/._ST_ART_ED_"
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;
83 //-----------------------------------------------------------------------------
84 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
86 return lhs.GetStartPosition() < rhs.GetStartPosition();
88 //-----------------------------------------------------------------------------
89 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
91 return lhs.GetStopPosition() > rhs.GetStopPosition();
93 //-----------------------------------------------------------------------------
97 STG_STOPPER() { nonstop = true; }
98 bool GetStatus() const { return nonstop; };
100 void Stop(const char * __file__, int __line__)
102 void Stop(const char *, int)
106 printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
113 //-----------------------------------------------------------------------------
115 //-----------------------------------------------------------------------------
116 static void StartTimer()
118 STG_LOGGER & WriteServLog = GetStgLogger();
122 WriteServLog("Cannot start timer. Fatal.");
123 //printfd(__FILE__, "Cannot start timer. Fatal.\n");
128 WriteServLog("Timer thread started successfully.");
129 //printfd(__FILE__, "Timer thread started successfully.\n");
132 //-----------------------------------------------------------------------------
137 //-----------------------------------------------------------------------------
138 void CatchTERM(int sig)
141 *Function Name:CatchINT
142 *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
143 *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
146 STG_LOGGER & WriteServLog = GetStgLogger();
147 WriteServLog("Shutting down... %d", sig);
150 nonstop.Stop(__FILE__, __LINE__);
152 struct sigaction newsa, oldsa;
155 sigemptyset(&sigmask);
156 sigaddset(&sigmask, SIGTERM);
157 newsa.sa_handler = SIG_IGN;
158 newsa.sa_mask = sigmask;
160 sigaction(SIGTERM, &newsa, &oldsa);
162 sigemptyset(&sigmask);
163 sigaddset(&sigmask, SIGINT);
164 newsa.sa_handler = SIG_IGN;
165 newsa.sa_mask = sigmask;
167 sigaction(SIGINT, &newsa, &oldsa);
169 //-----------------------------------------------------------------------------
172 STG_LOGGER & WriteServLog = GetStgLogger();
173 WriteServLog("Broken pipe!");
175 //-----------------------------------------------------------------------------
178 needRulesReloading = true;
180 //-----------------------------------------------------------------------------
185 childPid = waitpid(-1, &status, WNOHANG);
187 set<pid_t>::iterator pid;
188 pid = executersPid.find(childPid);
189 if (pid != executersPid.end())
191 executersPid.erase(pid);
192 if (executersPid.empty() && nonstop.GetStatus())
194 nonstop.Stop(__FILE__, __LINE__);
197 if (childPid == stgChildPid)
202 /*//-----------------------------------------------------------------------------
203 void CatchSEGV(int, siginfo_t *, void *)
206 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
207 FILE * f = fopen(fileName, "wt");
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);
215 switch (sinfo->si_code)
218 fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
222 fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
229 fprintf(f, "addr:\t 0x%.8X\n",
230 (unsigned int)sinfo->si_addr);
233 //asm("movl %eip, eip");
234 if (dladdr((void*)CatchCHLD, &dlinfo))
236 fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
240 fprintf(f, "Cannot find SEGV point\n");
246 struct sigaction segv_action, segv_action_old;
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;
253 sigaction(SIGSEGV, &segv_action, &segv_action_old);
255 //-----------------------------------------------------------------------------
256 static void SetSignalHandlers()
258 struct sigaction newsa, oldsa;
261 sigemptyset(&sigmask);
262 sigaddset(&sigmask, SIGTERM);
263 newsa.sa_handler = CatchTERM;
264 newsa.sa_mask = sigmask;
266 sigaction(SIGTERM, &newsa, &oldsa);
268 sigemptyset(&sigmask);
269 sigaddset(&sigmask, SIGUSR1);
270 newsa.sa_handler = CatchUSR1;
271 newsa.sa_mask = sigmask;
273 sigaction(SIGUSR1, &newsa, &oldsa);
275 sigemptyset(&sigmask);
276 sigaddset(&sigmask, SIGINT);
277 newsa.sa_handler = CatchTERM;
278 newsa.sa_mask = sigmask;
280 sigaction(SIGINT, &newsa, &oldsa);
282 sigemptyset(&sigmask);
283 sigaddset(&sigmask, SIGPIPE);
284 newsa.sa_handler = CatchPIPE;
285 newsa.sa_mask = sigmask;
287 sigaction(SIGPIPE, &newsa, &oldsa);
289 sigemptyset(&sigmask);
290 sigaddset(&sigmask, SIGHUP);
291 newsa.sa_handler = CatchHUP;
292 newsa.sa_mask = sigmask;
294 sigaction(SIGHUP, &newsa, &oldsa);
296 sigemptyset(&sigmask);
297 sigaddset(&sigmask, SIGCHLD);
298 newsa.sa_handler = CatchCHLD;
299 newsa.sa_mask = sigmask;
301 sigaction(SIGCHLD, &newsa, &oldsa);
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);*/
311 //-----------------------------------------------------------------------------
312 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS * settings)
314 STG_LOGGER & WriteServLog = GetStgLogger();
316 if (*msgID == -11) // If msgID == -11 - first call. Create queue
318 for (int i = 0; i < 2; i++)
320 //WriteServLog("Creating queue with key=%d ...", msgKey);
321 *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
325 *msgID = msgget(msgKey, 0);
328 WriteServLog("Message queue not created.");
333 msgctl(*msgID, IPC_RMID, NULL);
334 //printfd(__FILE__, "Queue removed!");
339 WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
345 pid_t executerPid = fork();
350 WriteServLog("Fork error!");
359 Executer(msgKey, *msgID, executerPid, procName);
362 default: // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
363 if (executersPid.empty()) {
364 Executer(msgKey, *msgID, executerPid, NULL);
366 executersPid.insert(executerPid);
370 //-----------------------------------------------------------------------------
372 int ForkAndWait(const string & confDir)
374 int ForkAndWait(const string &)
378 stgChildPid = fork();
379 string startFile = confDir + START_FILE;
380 unlink(startFile.c_str());
395 default: // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
396 for (int i = 0; i < 120 * 5; i++)
398 if (access(startFile.c_str(), F_OK) == 0)
400 //printf("Fork successfull. Exit.\n");
401 unlink(startFile.c_str());
407 unlink(startFile.c_str());
412 unlink(startFile.c_str());
419 //-----------------------------------------------------------------------------
422 set<pid_t>::iterator pid;
423 pid = executersPid.begin();
424 while (pid != executersPid.end())
426 printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
431 //-----------------------------------------------------------------------------
432 int main(int argc, char * argv[])
436 Initialization order:
449 - Set signal nandlers
453 SETTINGS * settings = NULL;
454 STORE * dataStore = NULL;
455 TARIFFS * tariffs = NULL;
456 ADMINS * admins = NULL;
457 USERS * users = NULL;
458 TRAFFCOUNTER * traffCnt = NULL;
462 STG_LOGGER & WriteServLog = GetStgLogger();
463 WriteServLog.SetLogFileName("/var/log/stargazer.log");
466 vector<MODULE_SETTINGS> modSettings;
467 list<PLUGIN_RUNNER> modules;
469 list<PLUGIN_RUNNER>::iterator modIter;
473 printf("You must be root. Exit.\n");
478 settings = new SETTINGS(argv[1]);
480 settings = new SETTINGS();
482 if (settings->ReadSettings())
484 //printfd(__FILE__, "ReadSettings error.\n");
485 STG_LOGGER & WriteServLog = GetStgLogger();
487 if (settings->GetLogFileName() != "")
488 WriteServLog.SetLogFileName(settings->GetLogFileName());
490 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
495 string startFile(settings->GetConfDir() + START_FILE);
498 if (ForkAndWait(settings->GetConfDir()) < 0)
500 STG_LOGGER & WriteServLog = GetStgLogger();
501 WriteServLog("Fork error!");
505 STG_LOGGER & WriteServLog = GetStgLogger();
506 WriteServLog.SetLogFileName(settings->GetLogFileName());
507 WriteServLog("Stg v. %s", SERVER_VERSION);
509 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
511 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
514 STG_LOGGER & WriteServLog = GetStgLogger();
515 WriteServLog("Start Script Executer error!");
525 PIDFile pidFile(settings->GetPIDFileName());
529 if (!IsStgTimerRunning())
531 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
532 WriteServLog("Timer thread not started in 1 sec!");
535 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
537 STORE_LOADER storeLoader(*settings);
538 if (storeLoader.Load())
540 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
541 goto exitLblNotStarted;
546 WriteServLog("Event loop not started.");
547 goto exitLblNotStarted;
550 dataStore = storeLoader.GetStore();
551 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
553 tariffs = new TARIFFS_IMPL(dataStore);
554 admins = new ADMINS_IMPL(dataStore);
555 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
556 traffCnt = new TRAFFCOUNTER(users, tariffs, settings->GetRulesFileName());
557 traffCnt->SetMonitorDir(settings->GetMonitorDir());
559 modSettings = settings->GetModulesSettings();
561 for (unsigned i = 0; i < modSettings.size(); i++)
563 string modulePath = settings->GetModulesPath();
564 modulePath += "/mod_";
565 modulePath += modSettings[i].moduleName;
567 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
569 PLUGIN_RUNNER(modulePath,
580 modIter = modules.begin();
582 while (modIter != modules.end())
587 WriteServLog("Error: %s",
588 modIter->GetStrError().c_str());
589 goto exitLblNotStarted;
597 goto exitLblNotStarted;
599 WriteServLog("Users started successfully.");
601 if (traffCnt->Start())
603 goto exitLblNotStarted;
605 WriteServLog("Traffcounter started successfully.");
607 //Sort by start order
608 modules.sort(StartModCmp);
609 modIter = modules.begin();
611 while (modIter != modules.end())
613 if (modIter->Start())
615 WriteServLog("Error: %s",
616 modIter->GetStrError().c_str());
617 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
620 WriteServLog("Module: \'%s\'. Start successfull. %d", modIter->GetPlugin()->GetVersion().c_str(),
621 modIter->GetPlugin()->GetStartPosition());
629 * Note that an implementation in which nice returns the new nice value
630 * can legitimately return -1. To reliably detect an error, set
631 * errno to 0 before the call, and check its value when nice returns -1.
637 if (nice(-19) && errno) {
638 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
639 WriteServLog("nice failed: '%s'", strerror(errno));
642 WriteServLog("Stg started successfully.");
643 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
646 creat(startFile.c_str(), S_IRUSR);
649 while (nonstop.GetStatus())
651 if (needRulesReloading)
653 needRulesReloading = false;
656 modIter = modules.begin();
657 for (; modIter != modules.end(); ++modIter)
659 if (modIter->Reload())
661 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
662 modIter->GetStrError().c_str());
663 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
664 modIter->GetStrError().c_str());
673 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
675 //Sort by start order
676 modules.sort(StopModCmp);
677 modIter = modules.begin();
678 while (modIter != modules.end())
680 std::string name = modIter->GetFileName();
681 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
684 WriteServLog("Module \'%s\': Error: %s",
685 modIter->GetPlugin()->GetVersion().c_str(),
686 modIter->GetStrError().c_str());
687 printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
688 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
691 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
697 WriteServLog("Event loop not stopped.");
702 modIter = modules.begin();
703 while (modIter != modules.end())
705 std::string name = modIter->GetFileName();
706 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
707 if (modIter->Unload())
709 WriteServLog("Module \'%s\': Error: %s",
711 modIter->GetStrError().c_str());
712 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
720 WriteServLog("Traffcounter: Stop successfull.");
726 WriteServLog("Users: Stop successfull.");
730 int res = msgctl(msgID, IPC_RMID, NULL);
732 WriteServLog("Queue was not removed. id=%d", msgID);
734 WriteServLog("Queue removed successfully.");
736 /*struct sigaction newsa, oldsa;
738 sigemptyset(&sigmask);
739 sigaddset(&sigmask, SIGCHLD);
740 newsa.sa_handler = SIG_IGN;
741 newsa.sa_mask = sigmask;
743 sigaction(SIGCHLD, &newsa, &oldsa);*/
748 WriteServLog("StgTimer: Stop successfull.");
750 WriteServLog("Stg stopped successfully.");
752 WriteServLog("---------------------------------------------");
762 //-----------------------------------------------------------------------------