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>
32 #include <sys/stat.h> // S_IRUSR
33 #include <fcntl.h> // create
38 #include <cstdlib> // srandom, exit
45 #include "stg/common.h"
46 #include "stg/plugin.h"
47 #include "stg/logger.h"
48 #include "stg/scriptexecuter.h"
49 #include "stg/conffiles.h"
50 #include "stg/version.h"
51 #include "stg/pinger.h"
52 #include "stg_timer.h"
53 #include "settings_impl.h"
54 #include "users_impl.h"
55 #include "admins_impl.h"
56 #include "tariffs_impl.h"
57 #include "services_impl.h"
58 #include "corps_impl.h"
59 #include "traffcounter_impl.h"
60 #include "plugin_runner.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;
82 //-----------------------------------------------------------------------------
83 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
85 return lhs.GetStartPosition() < rhs.GetStartPosition();
87 //-----------------------------------------------------------------------------
88 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
90 return lhs.GetStopPosition() > rhs.GetStopPosition();
92 //-----------------------------------------------------------------------------
96 STG_STOPPER() : nonstop(true) {}
97 bool GetStatus() const { return nonstop; }
99 void Stop(const char * __file__, int __line__)
101 void Stop(const char *, int)
105 printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
112 //-----------------------------------------------------------------------------
114 //-----------------------------------------------------------------------------
115 static void StartTimer()
117 STG_LOGGER & WriteServLog = GetStgLogger();
121 WriteServLog("Cannot start timer. Fatal.");
122 //printfd(__FILE__, "Cannot start timer. Fatal.\n");
127 WriteServLog("Timer thread started successfully.");
128 //printfd(__FILE__, "Timer thread started successfully.\n");
131 //-----------------------------------------------------------------------------
136 //-----------------------------------------------------------------------------
137 void CatchTERM(int sig)
140 *Function Name:CatchINT
141 *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
142 *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
145 STG_LOGGER & WriteServLog = GetStgLogger();
146 WriteServLog("Shutting down... %d", sig);
149 nonstop.Stop(__FILE__, __LINE__);
151 struct sigaction newsa, oldsa;
154 sigemptyset(&sigmask);
155 sigaddset(&sigmask, SIGTERM);
156 newsa.sa_handler = SIG_IGN;
157 newsa.sa_mask = sigmask;
159 sigaction(SIGTERM, &newsa, &oldsa);
161 sigemptyset(&sigmask);
162 sigaddset(&sigmask, SIGINT);
163 newsa.sa_handler = SIG_IGN;
164 newsa.sa_mask = sigmask;
166 sigaction(SIGINT, &newsa, &oldsa);
168 //-----------------------------------------------------------------------------
171 STG_LOGGER & WriteServLog = GetStgLogger();
172 WriteServLog("Broken pipe!");
174 //-----------------------------------------------------------------------------
177 needRulesReloading = true;
179 //-----------------------------------------------------------------------------
184 childPid = waitpid(-1, &status, WNOHANG);
186 set<pid_t>::iterator pid;
187 pid = executersPid.find(childPid);
188 if (pid != executersPid.end())
190 executersPid.erase(pid);
191 if (executersPid.empty() && nonstop.GetStatus())
193 nonstop.Stop(__FILE__, __LINE__);
196 if (childPid == stgChildPid)
201 /*//-----------------------------------------------------------------------------
202 void CatchSEGV(int, siginfo_t *, void *)
205 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
206 FILE * f = fopen(fileName, "wt");
209 fprintf(f, "\nSignal info:\n~~~~~~~~~~~~\n");
210 fprintf(f, "numb:\t %d (%d)\n", sinfo->si_signo, sig);
211 fprintf(f, "errn:\t %d\n", sinfo->si_errno);
212 fprintf(f, "code:\t %d ", sinfo->si_code);
214 switch (sinfo->si_code)
217 fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
221 fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
228 fprintf(f, "addr:\t 0x%.8X\n",
229 (unsigned int)sinfo->si_addr);
232 //asm("movl %eip, eip");
233 if (dladdr((void*)CatchCHLD, &dlinfo))
235 fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
239 fprintf(f, "Cannot find SEGV point\n");
245 struct sigaction segv_action, segv_action_old;
247 segv_action.sa_handler = SIG_DFL;
248 segv_action.sa_sigaction = NULL;
249 segv_action.sa_flags = SA_SIGINFO;
250 segv_action.sa_restorer = NULL;
252 sigaction(SIGSEGV, &segv_action, &segv_action_old);
254 //-----------------------------------------------------------------------------
255 static void SetSignalHandlers()
257 struct sigaction newsa, oldsa;
260 sigemptyset(&sigmask);
261 sigaddset(&sigmask, SIGTERM);
262 newsa.sa_handler = CatchTERM;
263 newsa.sa_mask = sigmask;
265 sigaction(SIGTERM, &newsa, &oldsa);
267 sigemptyset(&sigmask);
268 sigaddset(&sigmask, SIGUSR1);
269 newsa.sa_handler = CatchUSR1;
270 newsa.sa_mask = sigmask;
272 sigaction(SIGUSR1, &newsa, &oldsa);
274 sigemptyset(&sigmask);
275 sigaddset(&sigmask, SIGINT);
276 newsa.sa_handler = CatchTERM;
277 newsa.sa_mask = sigmask;
279 sigaction(SIGINT, &newsa, &oldsa);
281 sigemptyset(&sigmask);
282 sigaddset(&sigmask, SIGPIPE);
283 newsa.sa_handler = CatchPIPE;
284 newsa.sa_mask = sigmask;
286 sigaction(SIGPIPE, &newsa, &oldsa);
288 sigemptyset(&sigmask);
289 sigaddset(&sigmask, SIGHUP);
290 newsa.sa_handler = CatchHUP;
291 newsa.sa_mask = sigmask;
293 sigaction(SIGHUP, &newsa, &oldsa);
295 sigemptyset(&sigmask);
296 sigaddset(&sigmask, SIGCHLD);
297 newsa.sa_handler = CatchCHLD;
298 newsa.sa_mask = sigmask;
300 sigaction(SIGCHLD, &newsa, &oldsa);
302 /*newsa.sa_handler = NULL;
303 newsa.sa_sigaction = CatchSEGV;
304 newsa.sa_flags = SA_SIGINFO;
305 newsa.sa_restorer = NULL;
306 sigaction(SIGSEGV, &newsa, &oldsa);*/
310 //-----------------------------------------------------------------------------
311 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
313 STG_LOGGER & WriteServLog = GetStgLogger();
315 if (*msgID == -11) // If msgID == -11 - first call. Create queue
317 for (int i = 0; i < 2; i++)
319 *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
323 *msgID = msgget(msgKey, 0);
326 WriteServLog("Message queue not created.");
331 msgctl(*msgID, IPC_RMID, NULL);
336 WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
342 pid_t executerPid = fork();
347 WriteServLog("Fork error!");
352 Executer(*msgID, executerPid, procName);
356 if (executersPid.empty()) {
357 Executer(*msgID, executerPid, NULL);
359 executersPid.insert(executerPid);
363 //-----------------------------------------------------------------------------
365 int ForkAndWait(const string & confDir)
367 int ForkAndWait(const string &)
371 stgChildPid = fork();
372 string startFile = confDir + START_FILE;
373 unlink(startFile.c_str());
388 struct timespec ts = {0, 200000000};
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());
402 nanosleep(&ts, NULL);
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_IMPL * traffCnt = NULL;
451 SERVICES_IMPL * services = NULL;
452 CORPORATIONS_IMPL * corps = NULL;
456 STG_LOGGER & WriteServLog = GetStgLogger();
457 WriteServLog.SetLogFileName("/var/log/stargazer.log");
460 vector<MODULE_SETTINGS> modSettings;
461 list<PLUGIN_RUNNER> modules;
463 list<PLUGIN_RUNNER>::iterator modIter;
467 printf("You must be root. Exit.\n");
472 settings = new SETTINGS_IMPL(argv[1]);
474 settings = new SETTINGS_IMPL();
476 if (settings->ReadSettings())
478 STG_LOGGER & WriteServLog = GetStgLogger();
480 if (settings->GetLogFileName() != "")
481 WriteServLog.SetLogFileName(settings->GetLogFileName());
483 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
488 string startFile(settings->GetConfDir() + START_FILE);
491 if (ForkAndWait(settings->GetConfDir()) < 0)
493 STG_LOGGER & WriteServLog = GetStgLogger();
494 WriteServLog("Fork error!");
498 STG_LOGGER & WriteServLog = GetStgLogger();
499 WriteServLog.SetLogFileName(settings->GetLogFileName());
500 WriteServLog("Stg v. %s", SERVER_VERSION);
502 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
504 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
507 STG_LOGGER & WriteServLog = GetStgLogger();
508 WriteServLog("Start Script Executer error!");
518 PIDFile pidFile(settings->GetPIDFileName());
522 if (!IsStgTimerRunning())
524 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
525 WriteServLog("Timer thread not started in 1 sec!");
528 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
530 STORE_LOADER storeLoader(*settings);
531 if (storeLoader.Load())
533 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
534 goto exitLblNotStarted;
539 WriteServLog("Event loop not started.");
540 goto exitLblNotStarted;
543 dataStore = storeLoader.GetStore();
544 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
546 tariffs = new TARIFFS_IMPL(dataStore);
547 admins = new ADMINS_IMPL(dataStore);
548 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
549 traffCnt = new TRAFFCOUNTER_IMPL(users, settings->GetRulesFileName());
550 services = new SERVICES_IMPL(dataStore);
551 corps = new CORPORATIONS_IMPL(dataStore);
552 traffCnt->SetMonitorDir(settings->GetMonitorDir());
554 modSettings = settings->GetModulesSettings();
556 for (size_t i = 0; i < modSettings.size(); i++)
558 string modulePath = settings->GetModulesPath();
559 modulePath += "/mod_";
560 modulePath += modSettings[i].moduleName;
562 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
564 PLUGIN_RUNNER(modulePath,
577 modIter = modules.begin();
579 while (modIter != modules.end())
584 WriteServLog("Error: %s",
585 modIter->GetStrError().c_str());
586 goto exitLblNotStarted;
594 goto exitLblNotStarted;
596 WriteServLog("Users started successfully.");
598 if (traffCnt->Start())
600 goto exitLblNotStarted;
602 WriteServLog("Traffcounter started successfully.");
604 //Sort by start order
605 modules.sort(StartModCmp);
606 modIter = modules.begin();
608 while (modIter != modules.end())
610 if (modIter->Start())
612 WriteServLog("Error: %s",
613 modIter->GetStrError().c_str());
614 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
617 WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
625 * Note that an implementation in which nice returns the new nice value
626 * can legitimately return -1. To reliably detect an error, set
627 * errno to 0 before the call, and check its value when nice returns -1.
633 if (nice(-19) && errno) {
634 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
635 WriteServLog("nice failed: '%s'", strerror(errno));
638 WriteServLog("Stg started successfully.");
639 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
642 creat(startFile.c_str(), S_IRUSR);
645 while (nonstop.GetStatus())
647 if (needRulesReloading)
649 needRulesReloading = false;
652 modIter = modules.begin();
653 for (; modIter != modules.end(); ++modIter)
655 if (modIter->Reload())
657 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
658 modIter->GetStrError().c_str());
659 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
660 modIter->GetStrError().c_str());
669 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
671 //Sort by start order
672 modules.sort(StopModCmp);
673 modIter = modules.begin();
674 while (modIter != modules.end())
676 std::string name = modIter->GetFileName();
677 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
680 WriteServLog("Module \'%s\': Error: %s",
681 modIter->GetPlugin()->GetVersion().c_str(),
682 modIter->GetStrError().c_str());
683 printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
684 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
687 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
693 WriteServLog("Event loop not stopped.");
698 modIter = modules.begin();
699 while (modIter != modules.end())
701 std::string name = modIter->GetFileName();
702 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
703 if (modIter->Unload())
705 WriteServLog("Module \'%s\': Error: %s",
707 modIter->GetStrError().c_str());
708 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
716 WriteServLog("Traffcounter: Stop successfull.");
722 WriteServLog("Users: Stop successfull.");
726 int res = msgctl(msgID, IPC_RMID, NULL);
728 WriteServLog("Queue was not removed. id=%d", msgID);
730 WriteServLog("Queue removed successfully.");
735 WriteServLog("StgTimer: Stop successfull.");
745 WriteServLog("Stg stopped successfully.");
746 WriteServLog("---------------------------------------------");
750 //-----------------------------------------------------------------------------