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 $
27 /*#include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>*/
34 #include <sys/types.h>
36 /*#include <sys/stat.h>
47 #include "settings_impl.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_IMPL * 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 *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);
337 WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
343 pid_t executerPid = fork();
348 WriteServLog("Fork error!");
353 Executer(msgKey, *msgID, executerPid, procName);
357 if (executersPid.empty()) {
358 Executer(msgKey, *msgID, executerPid, NULL);
360 executersPid.insert(executerPid);
364 //-----------------------------------------------------------------------------
366 int ForkAndWait(const string & confDir)
368 int ForkAndWait(const string &)
372 stgChildPid = fork();
373 string startFile = confDir + START_FILE;
374 unlink(startFile.c_str());
389 for (int i = 0; i < 120 * 5; i++)
391 if (access(startFile.c_str(), F_OK) == 0)
393 unlink(startFile.c_str());
399 unlink(startFile.c_str());
404 unlink(startFile.c_str());
411 //-----------------------------------------------------------------------------
414 set<pid_t>::iterator pid;
415 pid = executersPid.begin();
416 while (pid != executersPid.end())
418 printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
423 //-----------------------------------------------------------------------------
424 int main(int argc, char * argv[])
428 Initialization order:
441 - Set signal nandlers
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;
454 STG_LOGGER & WriteServLog = GetStgLogger();
455 WriteServLog.SetLogFileName("/var/log/stargazer.log");
458 vector<MODULE_SETTINGS> modSettings;
459 list<PLUGIN_RUNNER> modules;
461 list<PLUGIN_RUNNER>::iterator modIter;
465 printf("You must be root. Exit.\n");
470 settings = new SETTINGS_IMPL(argv[1]);
472 settings = new SETTINGS_IMPL();
474 if (settings->ReadSettings())
476 STG_LOGGER & WriteServLog = GetStgLogger();
478 if (settings->GetLogFileName() != "")
479 WriteServLog.SetLogFileName(settings->GetLogFileName());
481 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
486 string startFile(settings->GetConfDir() + START_FILE);
489 if (ForkAndWait(settings->GetConfDir()) < 0)
491 STG_LOGGER & WriteServLog = GetStgLogger();
492 WriteServLog("Fork error!");
496 STG_LOGGER & WriteServLog = GetStgLogger();
497 WriteServLog.SetLogFileName(settings->GetLogFileName());
498 WriteServLog("Stg v. %s", SERVER_VERSION);
500 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
502 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
505 STG_LOGGER & WriteServLog = GetStgLogger();
506 WriteServLog("Start Script Executer error!");
516 PIDFile pidFile(settings->GetPIDFileName());
520 if (!IsStgTimerRunning())
522 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
523 WriteServLog("Timer thread not started in 1 sec!");
526 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
528 STORE_LOADER storeLoader(*settings);
529 if (storeLoader.Load())
531 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
532 goto exitLblNotStarted;
537 WriteServLog("Event loop not started.");
538 goto exitLblNotStarted;
541 dataStore = storeLoader.GetStore();
542 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
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());
550 modSettings = settings->GetModulesSettings();
552 for (size_t i = 0; i < modSettings.size(); i++)
554 string modulePath = settings->GetModulesPath();
555 modulePath += "/mod_";
556 modulePath += modSettings[i].moduleName;
558 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
560 PLUGIN_RUNNER(modulePath,
571 modIter = modules.begin();
573 while (modIter != modules.end())
578 WriteServLog("Error: %s",
579 modIter->GetStrError().c_str());
580 goto exitLblNotStarted;
588 goto exitLblNotStarted;
590 WriteServLog("Users started successfully.");
592 if (traffCnt->Start())
594 goto exitLblNotStarted;
596 WriteServLog("Traffcounter started successfully.");
598 //Sort by start order
599 modules.sort(StartModCmp);
600 modIter = modules.begin();
602 while (modIter != modules.end())
604 if (modIter->Start())
606 WriteServLog("Error: %s",
607 modIter->GetStrError().c_str());
608 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
611 WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
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.
627 if (nice(-19) && errno) {
628 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
629 WriteServLog("nice failed: '%s'", strerror(errno));
632 WriteServLog("Stg started successfully.");
633 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
636 creat(startFile.c_str(), S_IRUSR);
639 while (nonstop.GetStatus())
641 if (needRulesReloading)
643 needRulesReloading = false;
646 modIter = modules.begin();
647 for (; modIter != modules.end(); ++modIter)
649 if (modIter->Reload())
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());
663 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
665 //Sort by start order
666 modules.sort(StopModCmp);
667 modIter = modules.begin();
668 while (modIter != modules.end())
670 std::string name = modIter->GetFileName();
671 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
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());
681 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
687 WriteServLog("Event loop not stopped.");
692 modIter = modules.begin();
693 while (modIter != modules.end())
695 std::string name = modIter->GetFileName();
696 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
697 if (modIter->Unload())
699 WriteServLog("Module \'%s\': Error: %s",
701 modIter->GetStrError().c_str());
702 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
710 WriteServLog("Traffcounter: Stop successfull.");
716 WriteServLog("Users: Stop successfull.");
720 int res = msgctl(msgID, IPC_RMID, NULL);
722 WriteServLog("Queue was not removed. id=%d", msgID);
724 WriteServLog("Queue removed successfully.");
729 WriteServLog("StgTimer: Stop successfull.");
737 WriteServLog("Stg stopped successfully.");
738 WriteServLog("---------------------------------------------");
742 //-----------------------------------------------------------------------------