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_impl.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 struct timespec ts = {0, 200000000};
390 for (int i = 0; i < 120 * 5; i++)
392 if (access(startFile.c_str(), F_OK) == 0)
394 unlink(startFile.c_str());
400 unlink(startFile.c_str());
403 nanosleep(&ts, NULL);
405 unlink(startFile.c_str());
412 //-----------------------------------------------------------------------------
415 set<pid_t>::iterator pid;
416 pid = executersPid.begin();
417 while (pid != executersPid.end())
419 printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
424 //-----------------------------------------------------------------------------
425 int main(int argc, char * argv[])
429 Initialization order:
442 - Set signal nandlers
446 SETTINGS_IMPL * settings = NULL;
447 STORE * dataStore = NULL;
448 TARIFFS_IMPL * tariffs = NULL;
449 ADMINS_IMPL * admins = NULL;
450 USERS_IMPL * users = NULL;
451 TRAFFCOUNTER_IMPL * traffCnt = NULL;
455 STG_LOGGER & WriteServLog = GetStgLogger();
456 WriteServLog.SetLogFileName("/var/log/stargazer.log");
459 vector<MODULE_SETTINGS> modSettings;
460 list<PLUGIN_RUNNER> modules;
462 list<PLUGIN_RUNNER>::iterator modIter;
466 printf("You must be root. Exit.\n");
471 settings = new SETTINGS_IMPL(argv[1]);
473 settings = new SETTINGS_IMPL();
475 if (settings->ReadSettings())
477 STG_LOGGER & WriteServLog = GetStgLogger();
479 if (settings->GetLogFileName() != "")
480 WriteServLog.SetLogFileName(settings->GetLogFileName());
482 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
487 string startFile(settings->GetConfDir() + START_FILE);
490 if (ForkAndWait(settings->GetConfDir()) < 0)
492 STG_LOGGER & WriteServLog = GetStgLogger();
493 WriteServLog("Fork error!");
497 STG_LOGGER & WriteServLog = GetStgLogger();
498 WriteServLog.SetLogFileName(settings->GetLogFileName());
499 WriteServLog("Stg v. %s", SERVER_VERSION);
501 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
503 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
506 STG_LOGGER & WriteServLog = GetStgLogger();
507 WriteServLog("Start Script Executer error!");
517 PIDFile pidFile(settings->GetPIDFileName());
521 if (!IsStgTimerRunning())
523 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
524 WriteServLog("Timer thread not started in 1 sec!");
527 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
529 STORE_LOADER storeLoader(*settings);
530 if (storeLoader.Load())
532 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
533 goto exitLblNotStarted;
538 WriteServLog("Event loop not started.");
539 goto exitLblNotStarted;
542 dataStore = storeLoader.GetStore();
543 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
545 tariffs = new TARIFFS_IMPL(dataStore);
546 admins = new ADMINS_IMPL(dataStore);
547 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
548 traffCnt = new TRAFFCOUNTER_IMPL(users, tariffs, settings->GetRulesFileName());
549 traffCnt->SetMonitorDir(settings->GetMonitorDir());
551 modSettings = settings->GetModulesSettings();
553 for (size_t i = 0; i < modSettings.size(); i++)
555 string modulePath = settings->GetModulesPath();
556 modulePath += "/mod_";
557 modulePath += modSettings[i].moduleName;
559 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
561 PLUGIN_RUNNER(modulePath,
572 modIter = modules.begin();
574 while (modIter != modules.end())
579 WriteServLog("Error: %s",
580 modIter->GetStrError().c_str());
581 goto exitLblNotStarted;
589 goto exitLblNotStarted;
591 WriteServLog("Users started successfully.");
593 if (traffCnt->Start())
595 goto exitLblNotStarted;
597 WriteServLog("Traffcounter started successfully.");
599 //Sort by start order
600 modules.sort(StartModCmp);
601 modIter = modules.begin();
603 while (modIter != modules.end())
605 if (modIter->Start())
607 WriteServLog("Error: %s",
608 modIter->GetStrError().c_str());
609 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
612 WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
620 * Note that an implementation in which nice returns the new nice value
621 * can legitimately return -1. To reliably detect an error, set
622 * errno to 0 before the call, and check its value when nice returns -1.
628 if (nice(-19) && errno) {
629 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
630 WriteServLog("nice failed: '%s'", strerror(errno));
633 WriteServLog("Stg started successfully.");
634 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
637 creat(startFile.c_str(), S_IRUSR);
640 while (nonstop.GetStatus())
642 if (needRulesReloading)
644 needRulesReloading = false;
647 modIter = modules.begin();
648 for (; modIter != modules.end(); ++modIter)
650 if (modIter->Reload())
652 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
653 modIter->GetStrError().c_str());
654 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
655 modIter->GetStrError().c_str());
664 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
666 //Sort by start order
667 modules.sort(StopModCmp);
668 modIter = modules.begin();
669 while (modIter != modules.end())
671 std::string name = modIter->GetFileName();
672 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
675 WriteServLog("Module \'%s\': Error: %s",
676 modIter->GetPlugin()->GetVersion().c_str(),
677 modIter->GetStrError().c_str());
678 printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
679 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
682 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
688 WriteServLog("Event loop not stopped.");
693 modIter = modules.begin();
694 while (modIter != modules.end())
696 std::string name = modIter->GetFileName();
697 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
698 if (modIter->Unload())
700 WriteServLog("Module \'%s\': Error: %s",
702 modIter->GetStrError().c_str());
703 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
711 WriteServLog("Traffcounter: Stop successfull.");
717 WriteServLog("Users: Stop successfull.");
721 int res = msgctl(msgID, IPC_RMID, NULL);
723 WriteServLog("Queue was not removed. id=%d", msgID);
725 WriteServLog("Queue removed successfully.");
730 WriteServLog("StgTimer: Stop successfull.");
738 WriteServLog("Stg stopped successfully.");
739 WriteServLog("---------------------------------------------");
743 //-----------------------------------------------------------------------------