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>
51 #include "traffcounter.h"
52 #include "base_plugin.h"
53 #include "stg_logger.h"
54 #include "stg_timer.h"
55 #include "plugin_runner.h"
56 #include "script_executer.h"
57 #include "conffiles.h"
59 #include "store_loader.h"
61 #include "eventloop.h"
67 #define MAIN_DEBUG (1)
71 #define START_FILE "/._ST_ART_ED_"
73 static bool needRulesReloading = false;
74 static bool childExited = false;
75 //static pid_t executerPid;
76 set<pid_t> executersPid;
77 static pid_t stgChildPid;
81 //-----------------------------------------------------------------------------
82 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
84 return lhs.GetStartPosition() < rhs.GetStartPosition();
86 //-----------------------------------------------------------------------------
87 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
89 return lhs.GetStopPosition() > rhs.GetStopPosition();
91 //-----------------------------------------------------------------------------
95 STG_STOPPER() { nonstop = true; }
96 bool GetStatus() { return nonstop; };
98 void Stop(const char * __file__, int __line__)
100 void Stop(const char *, int)
104 printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
111 //-----------------------------------------------------------------------------
113 //-----------------------------------------------------------------------------
114 static void StartTimer()
116 STG_LOGGER & WriteServLog = GetStgLogger();
120 WriteServLog("Cannot start timer. Fatal.");
121 //printfd(__FILE__, "Cannot start timer. Fatal.\n");
126 WriteServLog("Timer thread started successfully.");
127 //printfd(__FILE__, "Timer thread started successfully.\n");
130 //-----------------------------------------------------------------------------
133 /*STG_LOGGER & WriteServLog = GetStgLogger();
134 WriteServLog("CatchPROF");*/
136 //-----------------------------------------------------------------------------
141 //-----------------------------------------------------------------------------
142 void CatchTERM(int sig)
145 *Function Name:CatchINT
146 *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
147 *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
150 STG_LOGGER & WriteServLog = GetStgLogger();
151 WriteServLog("Shutting down... %d", sig);
154 nonstop.Stop(__FILE__, __LINE__);
156 struct sigaction newsa, oldsa;
159 sigemptyset(&sigmask);
160 sigaddset(&sigmask, SIGTERM);
161 newsa.sa_handler = SIG_IGN;
162 newsa.sa_mask = sigmask;
164 sigaction(SIGTERM, &newsa, &oldsa);
166 sigemptyset(&sigmask);
167 sigaddset(&sigmask, SIGINT);
168 newsa.sa_handler = SIG_IGN;
169 newsa.sa_mask = sigmask;
171 sigaction(SIGINT, &newsa, &oldsa);
173 //-----------------------------------------------------------------------------
176 STG_LOGGER & WriteServLog = GetStgLogger();
177 WriteServLog("Broken pipe!");
179 //-----------------------------------------------------------------------------
182 needRulesReloading = true;
184 //-----------------------------------------------------------------------------
189 childPid = waitpid(-1, &status, WNOHANG);
191 set<pid_t>::iterator pid;
192 pid = executersPid.find(childPid);
193 if (pid != executersPid.end())
195 executersPid.erase(pid);
196 if (executersPid.empty() && nonstop.GetStatus())
198 nonstop.Stop(__FILE__, __LINE__);
201 if (childPid == stgChildPid)
206 //-----------------------------------------------------------------------------
207 void CatchSEGV(int, siginfo_t *, void *)
210 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
211 FILE * f = fopen(fileName, "wt");
214 fprintf(f, "\nSignal info:\n~~~~~~~~~~~~\n");
215 fprintf(f, "numb:\t %d (%d)\n", sinfo->si_signo, sig);
216 fprintf(f, "errn:\t %d\n", sinfo->si_errno);
217 fprintf(f, "code:\t %d ", sinfo->si_code);
219 switch (sinfo->si_code)
222 fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
226 fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
233 fprintf(f, "addr:\t 0x%.8X\n",
234 (unsigned int)sinfo->si_addr);
237 //asm("movl %eip, eip");
238 if (dladdr((void*)CatchCHLD, &dlinfo))
240 fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
244 fprintf(f, "Cannot find SEGV point\n");
250 struct sigaction segv_action, segv_action_old;
252 segv_action.sa_handler = SIG_DFL;
253 segv_action.sa_sigaction = NULL;
254 segv_action.sa_flags = SA_SIGINFO;
255 segv_action.sa_restorer = NULL;
257 sigaction(SIGSEGV, &segv_action, &segv_action_old);*/
259 //-----------------------------------------------------------------------------
260 static void SetSignalHandlers()
262 struct sigaction newsa, oldsa;
265 sigemptyset(&sigmask);
266 sigaddset(&sigmask, SIGTERM);
267 newsa.sa_handler = CatchTERM;
268 newsa.sa_mask = sigmask;
270 sigaction(SIGTERM, &newsa, &oldsa);
272 sigemptyset(&sigmask);
273 sigaddset(&sigmask, SIGUSR1);
274 newsa.sa_handler = CatchUSR1;
275 newsa.sa_mask = sigmask;
277 sigaction(SIGUSR1, &newsa, &oldsa);
279 sigemptyset(&sigmask);
280 sigaddset(&sigmask, SIGINT);
281 newsa.sa_handler = CatchTERM;
282 newsa.sa_mask = sigmask;
284 sigaction(SIGINT, &newsa, &oldsa);
286 sigemptyset(&sigmask);
287 sigaddset(&sigmask, SIGPROF);
288 newsa.sa_handler = CatchPROF;
289 newsa.sa_mask = sigmask;
291 sigaction(SIGPROF, &newsa, &oldsa);*/
293 sigemptyset(&sigmask);
294 sigaddset(&sigmask, SIGPIPE);
295 newsa.sa_handler = CatchPIPE;
296 newsa.sa_mask = sigmask;
298 sigaction(SIGPIPE, &newsa, &oldsa);
300 sigemptyset(&sigmask);
301 sigaddset(&sigmask, SIGHUP);
302 newsa.sa_handler = CatchHUP;
303 newsa.sa_mask = sigmask;
305 sigaction(SIGHUP, &newsa, &oldsa);
307 sigemptyset(&sigmask);
308 sigaddset(&sigmask, SIGCHLD);
309 newsa.sa_handler = CatchCHLD;
310 newsa.sa_mask = sigmask;
312 sigaction(SIGCHLD, &newsa, &oldsa);
314 /*newsa.sa_handler = NULL;
315 newsa.sa_sigaction = CatchSEGV;
316 newsa.sa_flags = SA_SIGINFO;
317 newsa.sa_restorer = NULL;
318 sigaction(SIGSEGV, &newsa, &oldsa);*/
322 //-----------------------------------------------------------------------------
323 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS * settings)
325 STG_LOGGER & WriteServLog = GetStgLogger();
327 if (*msgID == -11) // If msgID == -11 - first call. Create queue
329 for (int i = 0; i < 2; i++)
331 //WriteServLog("Creating queue with key=%d ...", msgKey);
332 *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
336 *msgID = msgget(msgKey, 0);
339 WriteServLog("Message queue not created.");
344 msgctl(*msgID, IPC_RMID, NULL);
345 //printfd(__FILE__, "Queue removed!");
350 WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
356 pid_t executerPid = fork();
361 WriteServLog("Fork error!");
370 Executer(msgKey, *msgID, executerPid, procName);
373 default: // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
374 if (executersPid.empty()) {
375 Executer(msgKey, *msgID, executerPid, NULL);
377 executersPid.insert(executerPid);
381 //-----------------------------------------------------------------------------
383 int ForkAndWait(const string & confDir)
385 int ForkAndWait(const string &)
389 stgChildPid = fork();
390 string startFile = confDir + START_FILE;
391 unlink(startFile.c_str());
406 default: // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
407 for (int i = 0; i < 120 * 5; i++)
409 if (access(startFile.c_str(), F_OK) == 0)
411 //printf("Fork successfull. Exit.\n");
412 unlink(startFile.c_str());
418 unlink(startFile.c_str());
423 unlink(startFile.c_str());
430 //-----------------------------------------------------------------------------
433 set<pid_t>::iterator pid;
434 pid = executersPid.begin();
435 while (pid != executersPid.end())
437 printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
442 //-----------------------------------------------------------------------------
443 int main(int argc, char * argv[])
447 Initialization order:
460 - Set signal nandlers
464 SETTINGS * settings = NULL;
465 BASE_STORE * dataStore = NULL;
466 TARIFFS * tariffs = NULL;
467 ADMINS * admins = NULL;
468 USERS * users = NULL;
469 TRAFFCOUNTER * traffCnt = NULL;
473 STG_LOGGER & WriteServLog = GetStgLogger();
474 WriteServLog.SetLogFileName("/var/log/stargazer.log");
477 vector<MODULE_SETTINGS> modSettings;
478 list<PLUGIN_RUNNER> modules;
480 list<PLUGIN_RUNNER>::iterator modIter;
484 printf("You must be root. Exit.\n");
489 settings = new SETTINGS(argv[1]);
491 settings = new SETTINGS();
493 if (settings->ReadSettings())
495 //printfd(__FILE__, "ReadSettings error.\n");
496 STG_LOGGER & WriteServLog = GetStgLogger();
498 if (settings->GetLogFileName() != "")
499 WriteServLog.SetLogFileName(settings->GetLogFileName());
501 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
506 string startFile(settings->GetConfDir() + START_FILE);
509 //SetSignalHandlers();
510 if (ForkAndWait(settings->GetConfDir()) < 0)
512 STG_LOGGER & WriteServLog = GetStgLogger();
513 WriteServLog("Fork error!");
517 STG_LOGGER & WriteServLog = GetStgLogger();
518 WriteServLog.SetLogFileName(settings->GetLogFileName());
519 WriteServLog("Stg v. %s", SERVER_VERSION);
521 for (int i = 0; i < settings->GetExecutersNum(); i++)
523 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
526 STG_LOGGER & WriteServLog = GetStgLogger();
527 WriteServLog("Start Script Executer error!");
538 PIDFile pidFile(settings->GetPIDFileName());
542 if (!IsStgTimerRunning())
544 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
545 WriteServLog("Timer thread not started in 1 sec!");
548 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
550 STORE_LOADER storeLoader(*settings);
551 if (storeLoader.Load())
553 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
554 goto exitLblNotStarted;
559 WriteServLog("Event loop not started.");
560 goto exitLblNotStarted;
563 dataStore = storeLoader.GetStore();
564 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
566 tariffs = new TARIFFS(dataStore);
567 admins = new ADMINS(dataStore);
568 users = new USERS(settings, dataStore, tariffs, admins->GetSysAdmin());
569 traffCnt = new TRAFFCOUNTER(users, tariffs, settings->GetRulesFileName());
570 traffCnt->SetMonitorDir(settings->GetMonitorDir());
571 //tariffs->SetUsers(users);
573 modSettings = settings->GetModulesSettings();
575 for (unsigned i = 0; i < modSettings.size(); i++)
577 string modulePath = settings->GetModulesPath();
578 modulePath += "/mod_";
579 modulePath += modSettings[i].moduleName;
581 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
583 PLUGIN_RUNNER(modulePath,
594 modIter = modules.begin();
596 while (modIter != modules.end())
601 WriteServLog("Error: %s",
602 modIter->GetStrError().c_str());
603 goto exitLblNotStarted;
611 goto exitLblNotStarted;
613 WriteServLog("Users started successfully.");
615 if (traffCnt->Start())
617 goto exitLblNotStarted;
619 WriteServLog("Traffcounter started successfully.");
621 //Sort by start order
622 modules.sort(StartModCmp);
623 modIter = modules.begin();
625 while (modIter != modules.end())
627 if (modIter->Start())
629 WriteServLog("Error: %s",
630 modIter->GetStrError().c_str());
631 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
634 WriteServLog("Module: \'%s\'. Start successfull. %d", modIter->GetPlugin()->GetVersion().c_str(),
635 modIter->GetPlugin()->GetStartPosition());
643 * Note that an implementation in which nice returns the new nice value
644 * can legitimately return -1. To reliably detect an error, set
645 * errno to 0 before the call, and check its value when nice returns -1.
651 if (nice(-19) && errno) {
652 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
653 WriteServLog("nice failed: '%s'", strerror(errno));
656 WriteServLog("Stg started successfully.");
657 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
660 creat(startFile.c_str(), S_IRUSR);
665 while (nonstop.GetStatus())
667 if (needRulesReloading)
669 needRulesReloading = false;
672 modIter = modules.begin();
673 for (; modIter != modules.end(); ++modIter)
675 if (modIter->Reload())
677 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
678 modIter->GetStrError().c_str());
679 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
680 modIter->GetStrError().c_str());
689 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
691 //Sort by start order
692 modules.sort(StopModCmp);
693 modIter = modules.begin();
694 while (modIter != modules.end())
696 std::string name = modIter->GetFileName();
697 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
700 WriteServLog("Module \'%s\': Error: %s",
701 modIter->GetPlugin()->GetVersion().c_str(),
702 modIter->GetStrError().c_str());
703 printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
704 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
707 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
713 WriteServLog("Event loop not stopped.");
718 /*modIter = modules.begin();
719 while (modIter != modules.end())
721 std::string name = modIter->GetFileName();
722 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
723 if (modIter->Unload())
725 WriteServLog("Module \'%s\': Error: %s",
727 modIter->GetStrError().c_str());
728 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
736 WriteServLog("Traffcounter: Stop successfull.");
742 WriteServLog("Users: Stop successfull.");
746 int res = msgctl(msgID, IPC_RMID, NULL);
748 WriteServLog("Queue was not removed. id=%d", msgID);
750 WriteServLog("Queue removed successfully.");
752 /*struct sigaction newsa, oldsa;
754 sigemptyset(&sigmask);
755 sigaddset(&sigmask, SIGCHLD);
756 newsa.sa_handler = SIG_IGN;
757 newsa.sa_mask = sigmask;
759 sigaction(SIGCHLD, &newsa, &oldsa);*/
764 WriteServLog("StgTimer: Stop successfull.");
766 WriteServLog("Stg stopped successfully.");
768 WriteServLog("---------------------------------------------");
778 //-----------------------------------------------------------------------------