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 "traffcounter_impl.h"
58 #include "plugin_runner.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;
80 //-----------------------------------------------------------------------------
81 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
83 return lhs.GetStartPosition() < rhs.GetStartPosition();
85 //-----------------------------------------------------------------------------
86 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
88 return lhs.GetStopPosition() > rhs.GetStopPosition();
90 //-----------------------------------------------------------------------------
94 STG_STOPPER() { nonstop = true; }
95 bool GetStatus() const { return nonstop; };
97 void Stop(const char * __file__, int __line__)
99 void Stop(const char *, int)
103 printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
110 //-----------------------------------------------------------------------------
112 //-----------------------------------------------------------------------------
113 static void StartTimer()
115 STG_LOGGER & WriteServLog = GetStgLogger();
119 WriteServLog("Cannot start timer. Fatal.");
120 //printfd(__FILE__, "Cannot start timer. Fatal.\n");
125 WriteServLog("Timer thread started successfully.");
126 //printfd(__FILE__, "Timer thread started successfully.\n");
129 //-----------------------------------------------------------------------------
134 //-----------------------------------------------------------------------------
135 void CatchTERM(int sig)
138 *Function Name:CatchINT
139 *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
140 *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
143 STG_LOGGER & WriteServLog = GetStgLogger();
144 WriteServLog("Shutting down... %d", sig);
147 nonstop.Stop(__FILE__, __LINE__);
149 struct sigaction newsa, oldsa;
152 sigemptyset(&sigmask);
153 sigaddset(&sigmask, SIGTERM);
154 newsa.sa_handler = SIG_IGN;
155 newsa.sa_mask = sigmask;
157 sigaction(SIGTERM, &newsa, &oldsa);
159 sigemptyset(&sigmask);
160 sigaddset(&sigmask, SIGINT);
161 newsa.sa_handler = SIG_IGN;
162 newsa.sa_mask = sigmask;
164 sigaction(SIGINT, &newsa, &oldsa);
166 //-----------------------------------------------------------------------------
169 STG_LOGGER & WriteServLog = GetStgLogger();
170 WriteServLog("Broken pipe!");
172 //-----------------------------------------------------------------------------
175 needRulesReloading = true;
177 //-----------------------------------------------------------------------------
182 childPid = waitpid(-1, &status, WNOHANG);
184 set<pid_t>::iterator pid;
185 pid = executersPid.find(childPid);
186 if (pid != executersPid.end())
188 executersPid.erase(pid);
189 if (executersPid.empty() && nonstop.GetStatus())
191 nonstop.Stop(__FILE__, __LINE__);
194 if (childPid == stgChildPid)
199 /*//-----------------------------------------------------------------------------
200 void CatchSEGV(int, siginfo_t *, void *)
203 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
204 FILE * f = fopen(fileName, "wt");
207 fprintf(f, "\nSignal info:\n~~~~~~~~~~~~\n");
208 fprintf(f, "numb:\t %d (%d)\n", sinfo->si_signo, sig);
209 fprintf(f, "errn:\t %d\n", sinfo->si_errno);
210 fprintf(f, "code:\t %d ", sinfo->si_code);
212 switch (sinfo->si_code)
215 fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
219 fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
226 fprintf(f, "addr:\t 0x%.8X\n",
227 (unsigned int)sinfo->si_addr);
230 //asm("movl %eip, eip");
231 if (dladdr((void*)CatchCHLD, &dlinfo))
233 fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
237 fprintf(f, "Cannot find SEGV point\n");
243 struct sigaction segv_action, segv_action_old;
245 segv_action.sa_handler = SIG_DFL;
246 segv_action.sa_sigaction = NULL;
247 segv_action.sa_flags = SA_SIGINFO;
248 segv_action.sa_restorer = NULL;
250 sigaction(SIGSEGV, &segv_action, &segv_action_old);
252 //-----------------------------------------------------------------------------
253 static void SetSignalHandlers()
255 struct sigaction newsa, oldsa;
258 sigemptyset(&sigmask);
259 sigaddset(&sigmask, SIGTERM);
260 newsa.sa_handler = CatchTERM;
261 newsa.sa_mask = sigmask;
263 sigaction(SIGTERM, &newsa, &oldsa);
265 sigemptyset(&sigmask);
266 sigaddset(&sigmask, SIGUSR1);
267 newsa.sa_handler = CatchUSR1;
268 newsa.sa_mask = sigmask;
270 sigaction(SIGUSR1, &newsa, &oldsa);
272 sigemptyset(&sigmask);
273 sigaddset(&sigmask, SIGINT);
274 newsa.sa_handler = CatchTERM;
275 newsa.sa_mask = sigmask;
277 sigaction(SIGINT, &newsa, &oldsa);
279 sigemptyset(&sigmask);
280 sigaddset(&sigmask, SIGPIPE);
281 newsa.sa_handler = CatchPIPE;
282 newsa.sa_mask = sigmask;
284 sigaction(SIGPIPE, &newsa, &oldsa);
286 sigemptyset(&sigmask);
287 sigaddset(&sigmask, SIGHUP);
288 newsa.sa_handler = CatchHUP;
289 newsa.sa_mask = sigmask;
291 sigaction(SIGHUP, &newsa, &oldsa);
293 sigemptyset(&sigmask);
294 sigaddset(&sigmask, SIGCHLD);
295 newsa.sa_handler = CatchCHLD;
296 newsa.sa_mask = sigmask;
298 sigaction(SIGCHLD, &newsa, &oldsa);
300 /*newsa.sa_handler = NULL;
301 newsa.sa_sigaction = CatchSEGV;
302 newsa.sa_flags = SA_SIGINFO;
303 newsa.sa_restorer = NULL;
304 sigaction(SIGSEGV, &newsa, &oldsa);*/
308 //-----------------------------------------------------------------------------
309 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
311 STG_LOGGER & WriteServLog = GetStgLogger();
313 if (*msgID == -11) // If msgID == -11 - first call. Create queue
315 for (int i = 0; i < 2; i++)
317 *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
321 *msgID = msgget(msgKey, 0);
324 WriteServLog("Message queue not created.");
329 msgctl(*msgID, IPC_RMID, NULL);
334 WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
340 pid_t executerPid = fork();
345 WriteServLog("Fork error!");
350 Executer(msgKey, *msgID, executerPid, procName);
354 if (executersPid.empty()) {
355 Executer(msgKey, *msgID, executerPid, NULL);
357 executersPid.insert(executerPid);
361 //-----------------------------------------------------------------------------
363 int ForkAndWait(const string & confDir)
365 int ForkAndWait(const string &)
369 stgChildPid = fork();
370 string startFile = confDir + START_FILE;
371 unlink(startFile.c_str());
386 struct timespec ts = {0, 200000000};
387 for (int i = 0; i < 120 * 5; i++)
389 if (access(startFile.c_str(), F_OK) == 0)
391 unlink(startFile.c_str());
397 unlink(startFile.c_str());
400 nanosleep(&ts, NULL);
402 unlink(startFile.c_str());
409 //-----------------------------------------------------------------------------
412 set<pid_t>::iterator pid;
413 pid = executersPid.begin();
414 while (pid != executersPid.end())
416 printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
421 //-----------------------------------------------------------------------------
422 int main(int argc, char * argv[])
426 Initialization order:
439 - Set signal nandlers
443 SETTINGS_IMPL * settings = NULL;
444 STORE * dataStore = NULL;
445 TARIFFS_IMPL * tariffs = NULL;
446 ADMINS_IMPL * admins = NULL;
447 USERS_IMPL * users = NULL;
448 TRAFFCOUNTER_IMPL * traffCnt = NULL;
452 STG_LOGGER & WriteServLog = GetStgLogger();
453 WriteServLog.SetLogFileName("/var/log/stargazer.log");
456 vector<MODULE_SETTINGS> modSettings;
457 list<PLUGIN_RUNNER> modules;
459 list<PLUGIN_RUNNER>::iterator modIter;
463 printf("You must be root. Exit.\n");
468 settings = new SETTINGS_IMPL(argv[1]);
470 settings = new SETTINGS_IMPL();
472 if (settings->ReadSettings())
474 STG_LOGGER & WriteServLog = GetStgLogger();
476 if (settings->GetLogFileName() != "")
477 WriteServLog.SetLogFileName(settings->GetLogFileName());
479 WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
484 string startFile(settings->GetConfDir() + START_FILE);
487 if (ForkAndWait(settings->GetConfDir()) < 0)
489 STG_LOGGER & WriteServLog = GetStgLogger();
490 WriteServLog("Fork error!");
494 STG_LOGGER & WriteServLog = GetStgLogger();
495 WriteServLog.SetLogFileName(settings->GetLogFileName());
496 WriteServLog("Stg v. %s", SERVER_VERSION);
498 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
500 int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
503 STG_LOGGER & WriteServLog = GetStgLogger();
504 WriteServLog("Start Script Executer error!");
514 PIDFile pidFile(settings->GetPIDFileName());
518 if (!IsStgTimerRunning())
520 printfd(__FILE__, "Timer thread not started in 1 sec!\n");
521 WriteServLog("Timer thread not started in 1 sec!");
524 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
526 STORE_LOADER storeLoader(*settings);
527 if (storeLoader.Load())
529 WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
530 goto exitLblNotStarted;
535 WriteServLog("Event loop not started.");
536 goto exitLblNotStarted;
539 dataStore = storeLoader.GetStore();
540 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
542 tariffs = new TARIFFS_IMPL(dataStore);
543 admins = new ADMINS_IMPL(dataStore);
544 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
545 traffCnt = new TRAFFCOUNTER_IMPL(users, settings->GetRulesFileName());
546 traffCnt->SetMonitorDir(settings->GetMonitorDir());
548 modSettings = settings->GetModulesSettings();
550 for (size_t i = 0; i < modSettings.size(); i++)
552 string modulePath = settings->GetModulesPath();
553 modulePath += "/mod_";
554 modulePath += modSettings[i].moduleName;
556 printfd(__FILE__, "Module: %s\n", modulePath.c_str());
558 PLUGIN_RUNNER(modulePath,
569 modIter = modules.begin();
571 while (modIter != modules.end())
576 WriteServLog("Error: %s",
577 modIter->GetStrError().c_str());
578 goto exitLblNotStarted;
586 goto exitLblNotStarted;
588 WriteServLog("Users started successfully.");
590 if (traffCnt->Start())
592 goto exitLblNotStarted;
594 WriteServLog("Traffcounter started successfully.");
596 //Sort by start order
597 modules.sort(StartModCmp);
598 modIter = modules.begin();
600 while (modIter != modules.end())
602 if (modIter->Start())
604 WriteServLog("Error: %s",
605 modIter->GetStrError().c_str());
606 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
609 WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
617 * Note that an implementation in which nice returns the new nice value
618 * can legitimately return -1. To reliably detect an error, set
619 * errno to 0 before the call, and check its value when nice returns -1.
625 if (nice(-19) && errno) {
626 printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
627 WriteServLog("nice failed: '%s'", strerror(errno));
630 WriteServLog("Stg started successfully.");
631 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
634 creat(startFile.c_str(), S_IRUSR);
637 while (nonstop.GetStatus())
639 if (needRulesReloading)
641 needRulesReloading = false;
644 modIter = modules.begin();
645 for (; modIter != modules.end(); ++modIter)
647 if (modIter->Reload())
649 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
650 modIter->GetStrError().c_str());
651 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
652 modIter->GetStrError().c_str());
661 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
663 //Sort by start order
664 modules.sort(StopModCmp);
665 modIter = modules.begin();
666 while (modIter != modules.end())
668 std::string name = modIter->GetFileName();
669 printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
672 WriteServLog("Module \'%s\': Error: %s",
673 modIter->GetPlugin()->GetVersion().c_str(),
674 modIter->GetStrError().c_str());
675 printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
676 //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
679 WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
685 WriteServLog("Event loop not stopped.");
690 modIter = modules.begin();
691 while (modIter != modules.end())
693 std::string name = modIter->GetFileName();
694 printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
695 if (modIter->Unload())
697 WriteServLog("Module \'%s\': Error: %s",
699 modIter->GetStrError().c_str());
700 printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
708 WriteServLog("Traffcounter: Stop successfull.");
714 WriteServLog("Users: Stop successfull.");
718 int res = msgctl(msgID, IPC_RMID, NULL);
720 WriteServLog("Queue was not removed. id=%d", msgID);
722 WriteServLog("Queue removed successfully.");
727 WriteServLog("StgTimer: Stop successfull.");
735 WriteServLog("Stg stopped successfully.");
736 WriteServLog("---------------------------------------------");
740 //-----------------------------------------------------------------------------