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>
42 #include "settings_impl.h"
44 #include "users_impl.h"
45 #include "admins_impl.h"
46 #include "tariffs_impl.h"
48 #include "traffcounter_impl.h"
50 #include "stg_logger.h"
51 #include "stg_timer.h"
52 #include "plugin_runner.h"
53 #include "script_executer.h"
54 #include "conffiles.h"
56 #include "store_loader.h"
58 #include "eventloop.h"
64 #define MAIN_DEBUG (1)
68 #define START_FILE "/._ST_ART_ED_"
70 static bool needRulesReloading = false;
71 static bool childExited = false;
72 //static pid_t executerPid;
73 set<pid_t> executersPid;
74 static pid_t stgChildPid;
78 //-----------------------------------------------------------------------------
79 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
81 return lhs.GetStartPosition() < rhs.GetStartPosition();
83 //-----------------------------------------------------------------------------
84 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
86 return lhs.GetStopPosition() > rhs.GetStopPosition();
88 //-----------------------------------------------------------------------------
92 STG_STOPPER() { nonstop = true; }
93 bool GetStatus() const { return nonstop; };
95 void Stop(const char * __file__, int __line__)
97 void Stop(const char *, int)
101 printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
108 //-----------------------------------------------------------------------------
110 //-----------------------------------------------------------------------------
111 static void StartTimer()
113 STG_LOGGER & WriteServLog = GetStgLogger();
117 WriteServLog("Cannot start timer. Fatal.");
118 //printfd(__FILE__, "Cannot start timer. Fatal.\n");
123 WriteServLog("Timer thread started successfully.");
124 //printfd(__FILE__, "Timer thread started successfully.\n");
127 //-----------------------------------------------------------------------------
132 //-----------------------------------------------------------------------------
133 void CatchTERM(int sig)
136 *Function Name:CatchINT
137 *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
138 *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
141 STG_LOGGER & WriteServLog = GetStgLogger();
142 WriteServLog("Shutting down... %d", sig);
145 nonstop.Stop(__FILE__, __LINE__);
147 struct sigaction newsa, oldsa;
150 sigemptyset(&sigmask);
151 sigaddset(&sigmask, SIGTERM);
152 newsa.sa_handler = SIG_IGN;
153 newsa.sa_mask = sigmask;
155 sigaction(SIGTERM, &newsa, &oldsa);
157 sigemptyset(&sigmask);
158 sigaddset(&sigmask, SIGINT);
159 newsa.sa_handler = SIG_IGN;
160 newsa.sa_mask = sigmask;
162 sigaction(SIGINT, &newsa, &oldsa);
164 //-----------------------------------------------------------------------------
167 STG_LOGGER & WriteServLog = GetStgLogger();
168 WriteServLog("Broken pipe!");
170 //-----------------------------------------------------------------------------
173 needRulesReloading = true;
175 //-----------------------------------------------------------------------------
180 childPid = waitpid(-1, &status, WNOHANG);
182 set<pid_t>::iterator pid;
183 pid = executersPid.find(childPid);
184 if (pid != executersPid.end())
186 executersPid.erase(pid);
187 if (executersPid.empty() && nonstop.GetStatus())
189 nonstop.Stop(__FILE__, __LINE__);
192 if (childPid == stgChildPid)
197 /*//-----------------------------------------------------------------------------
198 void CatchSEGV(int, siginfo_t *, void *)
201 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
202 FILE * f = fopen(fileName, "wt");
205 fprintf(f, "\nSignal info:\n~~~~~~~~~~~~\n");
206 fprintf(f, "numb:\t %d (%d)\n", sinfo->si_signo, sig);
207 fprintf(f, "errn:\t %d\n", sinfo->si_errno);
208 fprintf(f, "code:\t %d ", sinfo->si_code);
210 switch (sinfo->si_code)
213 fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
217 fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
224 fprintf(f, "addr:\t 0x%.8X\n",
225 (unsigned int)sinfo->si_addr);
228 //asm("movl %eip, eip");
229 if (dladdr((void*)CatchCHLD, &dlinfo))
231 fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
235 fprintf(f, "Cannot find SEGV point\n");
241 struct sigaction segv_action, segv_action_old;
243 segv_action.sa_handler = SIG_DFL;
244 segv_action.sa_sigaction = NULL;
245 segv_action.sa_flags = SA_SIGINFO;
246 segv_action.sa_restorer = NULL;
248 sigaction(SIGSEGV, &segv_action, &segv_action_old);
250 //-----------------------------------------------------------------------------
251 static void SetSignalHandlers()
253 struct sigaction newsa, oldsa;
256 sigemptyset(&sigmask);
257 sigaddset(&sigmask, SIGTERM);
258 newsa.sa_handler = CatchTERM;
259 newsa.sa_mask = sigmask;
261 sigaction(SIGTERM, &newsa, &oldsa);
263 sigemptyset(&sigmask);
264 sigaddset(&sigmask, SIGUSR1);
265 newsa.sa_handler = CatchUSR1;
266 newsa.sa_mask = sigmask;
268 sigaction(SIGUSR1, &newsa, &oldsa);
270 sigemptyset(&sigmask);
271 sigaddset(&sigmask, SIGINT);
272 newsa.sa_handler = CatchTERM;
273 newsa.sa_mask = sigmask;
275 sigaction(SIGINT, &newsa, &oldsa);
277 sigemptyset(&sigmask);
278 sigaddset(&sigmask, SIGPIPE);
279 newsa.sa_handler = CatchPIPE;
280 newsa.sa_mask = sigmask;
282 sigaction(SIGPIPE, &newsa, &oldsa);
284 sigemptyset(&sigmask);
285 sigaddset(&sigmask, SIGHUP);
286 newsa.sa_handler = CatchHUP;
287 newsa.sa_mask = sigmask;
289 sigaction(SIGHUP, &newsa, &oldsa);
291 sigemptyset(&sigmask);
292 sigaddset(&sigmask, SIGCHLD);
293 newsa.sa_handler = CatchCHLD;
294 newsa.sa_mask = sigmask;
296 sigaction(SIGCHLD, &newsa, &oldsa);
298 /*newsa.sa_handler = NULL;
299 newsa.sa_sigaction = CatchSEGV;
300 newsa.sa_flags = SA_SIGINFO;
301 newsa.sa_restorer = NULL;
302 sigaction(SIGSEGV, &newsa, &oldsa);*/
306 //-----------------------------------------------------------------------------
307 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
309 STG_LOGGER & WriteServLog = GetStgLogger();
311 if (*msgID == -11) // If msgID == -11 - first call. Create queue
313 for (int i = 0; i < 2; i++)
315 *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
319 *msgID = msgget(msgKey, 0);
322 WriteServLog("Message queue not created.");
327 msgctl(*msgID, IPC_RMID, NULL);
332 WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
338 pid_t executerPid = fork();
343 WriteServLog("Fork error!");
348 Executer(msgKey, *msgID, executerPid, procName);
352 if (executersPid.empty()) {
353 Executer(msgKey, *msgID, executerPid, NULL);
355 executersPid.insert(executerPid);
359 //-----------------------------------------------------------------------------
361 int ForkAndWait(const string & confDir)
363 int ForkAndWait(const string &)
367 stgChildPid = fork();
368 string startFile = confDir + START_FILE;
369 unlink(startFile.c_str());
384 struct timespec ts = {0, 200000000};
385 for (int i = 0; i < 120 * 5; i++)
387 if (access(startFile.c_str(), F_OK) == 0)
389 unlink(startFile.c_str());
395 unlink(startFile.c_str());
398 nanosleep(&ts, NULL);
400 unlink(startFile.c_str());
407 //-----------------------------------------------------------------------------
410 set<pid_t>::iterator pid;
411 pid = executersPid.begin();
412 while (pid != executersPid.end())
414 printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
419 //-----------------------------------------------------------------------------
420 int main(int argc, char * argv[])
424 Initialization order:
437 - Set signal nandlers
441 SETTINGS_IMPL * settings = NULL;
442 STORE * dataStore = NULL;
443 TARIFFS_IMPL * tariffs = NULL;
444 ADMINS_IMPL * admins = NULL;
445 USERS_IMPL * users = NULL;
446 TRAFFCOUNTER_IMPL * traffCnt = NULL;
450 STG_LOGGER & WriteServLog = GetStgLogger();
451 WriteServLog.SetLogFileName("/var/log/stargazer.log");
454 vector<MODULE_SETTINGS> modSettings;
455 list<PLUGIN_RUNNER> modules;
457 list<PLUGIN_RUNNER>::iterator modIter;
461 printf("You must be root. Exit.\n");
466 settings = new SETTINGS_IMPL(argv[1]);
468 settings = new SETTINGS_IMPL();
470 if (settings->ReadSettings())
472 STG_LOGGER & WriteServLog = GetStgLogger();
474 if (settings->GetLogFileName() != "")
475 WriteServLog.SetLogFileName(settings->GetLogFileName());
477 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
482 string startFile(settings->GetConfDir() + START_FILE);
485 if (ForkAndWait(settings->GetConfDir()) < 0)
487 STG_LOGGER & WriteServLog = GetStgLogger();
488 WriteServLog("Fork error!");
492 STG_LOGGER & WriteServLog = GetStgLogger();
493 WriteServLog.SetLogFileName(settings->GetLogFileName());
494 WriteServLog("Stg v. %s", SERVER_VERSION);
496 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
498 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
501 STG_LOGGER & WriteServLog = GetStgLogger();
502 WriteServLog("Start Script Executer error!");
512 PIDFile pidFile(settings->GetPIDFileName());
516 if (!IsStgTimerRunning())
518 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
519 WriteServLog("Timer thread not started in 1 sec!");
522 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
524 STORE_LOADER storeLoader(*settings);
525 if (storeLoader.Load())
527 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
528 goto exitLblNotStarted;
533 WriteServLog("Event loop not started.");
534 goto exitLblNotStarted;
537 dataStore = storeLoader.GetStore();
538 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
540 tariffs = new TARIFFS_IMPL(dataStore);
541 admins = new ADMINS_IMPL(dataStore);
542 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
543 traffCnt = new TRAFFCOUNTER_IMPL(users, tariffs, settings->GetRulesFileName());
544 traffCnt->SetMonitorDir(settings->GetMonitorDir());
546 modSettings = settings->GetModulesSettings();
548 for (size_t i = 0; i < modSettings.size(); i++)
550 string modulePath = settings->GetModulesPath();
551 modulePath += "/mod_";
552 modulePath += modSettings[i].moduleName;
554 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
556 PLUGIN_RUNNER(modulePath,
567 modIter = modules.begin();
569 while (modIter != modules.end())
574 WriteServLog("Error: %s",
575 modIter->GetStrError().c_str());
576 goto exitLblNotStarted;
584 goto exitLblNotStarted;
586 WriteServLog("Users started successfully.");
588 if (traffCnt->Start())
590 goto exitLblNotStarted;
592 WriteServLog("Traffcounter started successfully.");
594 //Sort by start order
595 modules.sort(StartModCmp);
596 modIter = modules.begin();
598 while (modIter != modules.end())
600 if (modIter->Start())
602 WriteServLog("Error: %s",
603 modIter->GetStrError().c_str());
604 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
607 WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
615 * Note that an implementation in which nice returns the new nice value
616 * can legitimately return -1. To reliably detect an error, set
617 * errno to 0 before the call, and check its value when nice returns -1.
623 if (nice(-19) && errno) {
624 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
625 WriteServLog("nice failed: '%s'", strerror(errno));
628 WriteServLog("Stg started successfully.");
629 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
632 creat(startFile.c_str(), S_IRUSR);
635 while (nonstop.GetStatus())
637 if (needRulesReloading)
639 needRulesReloading = false;
642 modIter = modules.begin();
643 for (; modIter != modules.end(); ++modIter)
645 if (modIter->Reload())
647 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
648 modIter->GetStrError().c_str());
649 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
650 modIter->GetStrError().c_str());
659 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
661 //Sort by start order
662 modules.sort(StopModCmp);
663 modIter = modules.begin();
664 while (modIter != modules.end())
666 std::string name = modIter->GetFileName();
667 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
670 WriteServLog("Module \'%s\': Error: %s",
671 modIter->GetPlugin()->GetVersion().c_str(),
672 modIter->GetStrError().c_str());
673 printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
674 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
677 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
683 WriteServLog("Event loop not stopped.");
688 modIter = modules.begin();
689 while (modIter != modules.end())
691 std::string name = modIter->GetFileName();
692 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
693 if (modIter->Unload())
695 WriteServLog("Module \'%s\': Error: %s",
697 modIter->GetStrError().c_str());
698 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
706 WriteServLog("Traffcounter: Stop successfull.");
712 WriteServLog("Users: Stop successfull.");
716 int res = msgctl(msgID, IPC_RMID, NULL);
718 WriteServLog("Queue was not removed. id=%d", msgID);
720 WriteServLog("Queue removed successfully.");
725 WriteServLog("StgTimer: Stop successfull.");
733 WriteServLog("Stg stopped successfully.");
734 WriteServLog("---------------------------------------------");
738 //-----------------------------------------------------------------------------