]> git.stg.codes - stg.git/blob - projects/stargazer/main.cpp
Massive refactoring.
[stg.git] / projects / stargazer / main.cpp
1 /*
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.
6  *
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.
11  *
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
15  */
16
17 /*
18  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19  */
20
21  /*
22  $Revision: 1.124 $
23  $Date: 2010/10/04 20:19:12 $
24  $Author: faust $
25  */
26
27 #include <unistd.h>
28 #include <sys/ipc.h>
29 #include <sys/msg.h>
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <sys/stat.h> // S_IRUSR
33 #include <fcntl.h> // create
34
35 #include <csignal>
36 #include <cerrno>
37 #include <cstdio>
38 #include <cstdlib> // srandom, exit
39 #include <fstream>
40 #include <vector>
41 #include <set>
42 #include <list>
43
44 #include "stg/user.h"
45 #include "stg/common.h"
46 #include "stg/plugin.h"
47 #include "stg/logger.h"
48 #include "stg/scriptexecuter.h"
49 #include "stg/version.h"
50 #include "stg_timer.h"
51 #include "settings_impl.h"
52 #include "users_impl.h"
53 #include "admins_impl.h"
54 #include "tariffs_impl.h"
55 #include "services_impl.h"
56 #include "corps_impl.h"
57 #include "traffcounter_impl.h"
58 #include "plugin_runner.h"
59 #include "store_loader.h"
60 #include "pidfile.h"
61 #include "eventloop.h"
62
63 #ifdef DEBUG
64     #define MAIN_DEBUG (1)
65     #define NO_DAEMON  (1)
66 #endif
67
68 #define START_FILE "/._ST_ART_ED_"
69
70 namespace
71 {
72 std::set<pid_t> executersPid;
73
74 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs);
75 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs);
76 void StartTimer();
77 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings);
78 int ForkAndWait(const std::string & confDir);
79 void KillExecuters();
80
81 //-----------------------------------------------------------------------------
82 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
83 {
84 return lhs.GetStartPosition() < rhs.GetStartPosition();
85 }
86 //-----------------------------------------------------------------------------
87 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
88 {
89 return lhs.GetStopPosition() > rhs.GetStopPosition();
90 }
91 //-----------------------------------------------------------------------------
92 void StartTimer()
93 {
94 STG_LOGGER & WriteServLog = GetStgLogger();
95
96 if (RunStgTimer())
97     {
98     WriteServLog("Cannot start timer. Fatal.");
99     //printfd(__FILE__, "Cannot start timer. Fatal.\n");
100     exit(1);
101     }
102 else
103     {
104     WriteServLog("Timer thread started successfully.");
105     //printfd(__FILE__, "Timer thread started successfully.\n");
106     }
107 }
108 //-----------------------------------------------------------------------------
109 #ifdef LINUX
110 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
111 #else
112 int StartScriptExecuter(char *, int msgKey, int * msgID, SETTINGS_IMPL * settings)
113 #endif
114 {
115 STG_LOGGER & WriteServLog = GetStgLogger();
116
117 if (*msgID == -11)   // If msgID == -11 - first call. Create queue
118     {
119     for (int i = 0; i < 2; i++)
120         {
121         *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
122
123         if (*msgID == -1)
124             {
125             *msgID = msgget(msgKey, 0);
126             if (*msgID == -1)
127                 {
128                 WriteServLog("Message queue not created.");
129                 return -1;
130                 }
131             else
132                 {
133                 msgctl(*msgID, IPC_RMID, NULL);
134                 }
135             }
136         else
137             {
138             WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
139             break;
140             }
141         }
142     }
143
144 pid_t executerPid = fork();
145
146 switch (executerPid)
147     {
148     case -1:
149         WriteServLog("Fork error!");
150         return -1;
151
152     case 0:
153         delete settings;
154 #ifdef LINUX
155         Executer(*msgID, executerPid, procName);
156 #else
157         Executer(*msgID, executerPid);
158 #endif
159         return 1;
160
161     default:
162         if (executersPid.empty()) {
163 #ifdef LINUX
164             Executer(*msgID, executerPid, NULL);
165 #else
166             Executer(*msgID, executerPid);
167 #endif
168         }
169         executersPid.insert(executerPid);
170     }
171 return 0;
172 }
173 //-----------------------------------------------------------------------------
174 #ifndef NO_DAEMON
175 int ForkAndWait(const std::string & confDir)
176 #else
177 int ForkAndWait(const std::string &)
178 #endif
179 {
180 #ifndef NO_DAEMON
181 pid_t childPid = fork();
182 std::string startFile = confDir + START_FILE;
183 unlink(startFile.c_str());
184
185 switch (childPid)
186     {
187     case -1:
188         return -1;
189         break;
190
191     case 0:
192         close(1);
193         close(2);
194         setsid();
195         break;
196
197     default:
198         struct timespec ts = {0, 200000000};
199         for (int i = 0; i < 120 * 5; i++)
200             {
201             if (access(startFile.c_str(), F_OK) == 0)
202                 {
203                 unlink(startFile.c_str());
204                 exit(0);
205                 }
206
207             nanosleep(&ts, NULL);
208             }
209         unlink(startFile.c_str());
210         exit(1);
211         break;
212     }
213 #endif
214 return 0;
215 }
216 //-----------------------------------------------------------------------------
217 void KillExecuters()
218 {
219 std::set<pid_t>::iterator pid;
220 pid = executersPid.begin();
221 while (pid != executersPid.end())
222     {
223     printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
224     kill(*pid, SIGUSR1);
225     ++pid;
226     }
227 }
228 //-----------------------------------------------------------------------------
229 } // namespace anonymous
230 //-----------------------------------------------------------------------------
231 int main(int argc, char * argv[])
232 {
233 SETTINGS_IMPL * settings = NULL;
234 STORE * dataStore = NULL;
235 TARIFFS_IMPL * tariffs = NULL;
236 ADMINS_IMPL * admins = NULL;
237 USERS_IMPL * users = NULL;
238 TRAFFCOUNTER_IMPL * traffCnt = NULL;
239 SERVICES_IMPL * services = NULL;
240 CORPORATIONS_IMPL * corps = NULL;
241 int msgID = -11;
242
243     {
244     STG_LOGGER & WriteServLog = GetStgLogger();
245     WriteServLog.SetLogFileName("/var/log/stargazer.log");
246     }
247
248 std::vector<MODULE_SETTINGS> modSettings;
249 std::list<PLUGIN_RUNNER> modules;
250
251 std::list<PLUGIN_RUNNER>::iterator modIter;
252
253 if (getuid())
254     {
255     printf("You must be root. Exit.\n");
256     exit(1);
257     }
258
259 if (argc == 2)
260     settings = new SETTINGS_IMPL(argv[1]);
261 else
262     settings = new SETTINGS_IMPL();
263
264 if (settings->ReadSettings())
265     {
266     STG_LOGGER & WriteServLog = GetStgLogger();
267
268     if (settings->GetLogFileName() != "")
269         WriteServLog.SetLogFileName(settings->GetLogFileName());
270
271     WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
272     exit(1);
273     }
274
275 #ifndef NO_DAEMON
276 std::string startFile(settings->GetConfDir() + START_FILE);
277 #endif
278
279 if (ForkAndWait(settings->GetConfDir()) < 0)
280     {
281     STG_LOGGER & WriteServLog = GetStgLogger();
282     WriteServLog("Fork error!");
283     exit(1);
284     }
285
286 STG_LOGGER & WriteServLog = GetStgLogger();
287 WriteServLog.SetLogFileName(settings->GetLogFileName());
288 WriteServLog("Stg v. %s", SERVER_VERSION);
289
290 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
291     {
292     int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
293     if (ret < 0)
294         {
295         STG_LOGGER & WriteServLog = GetStgLogger();
296         WriteServLog("Start Script Executer error!");
297         return 1;
298         }
299     if (ret == 1)
300         {
301         // Stopping child
302         return 0;
303         }
304     }
305
306 PIDFile pidFile(settings->GetPIDFileName());
307
308 sigset_t signalSet;
309 sigfillset(&signalSet);
310 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
311
312 StartTimer();
313 WaitTimer();
314 if (!IsStgTimerRunning())
315     {
316     printfd(__FILE__, "Timer thread not started in 1 sec!\n");
317     WriteServLog("Timer thread not started in 1 sec!");
318     }
319
320 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
321
322 STORE_LOADER storeLoader(*settings);
323 if (storeLoader.Load())
324     {
325     WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
326     goto exitLblNotStarted;
327     }
328
329 if (loop.Start())
330     {
331     WriteServLog("Event loop not started.");
332     goto exitLblNotStarted;
333     }
334
335 dataStore = storeLoader.GetStore();
336 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
337
338 tariffs = new TARIFFS_IMPL(dataStore);
339 admins = new ADMINS_IMPL(dataStore);
340 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
341 traffCnt = new TRAFFCOUNTER_IMPL(users, settings->GetRulesFileName());
342 services = new SERVICES_IMPL(dataStore);
343 corps = new CORPORATIONS_IMPL(dataStore);
344 traffCnt->SetMonitorDir(settings->GetMonitorDir());
345
346 modSettings = settings->GetModulesSettings();
347
348 for (size_t i = 0; i < modSettings.size(); i++)
349     {
350     std::string modulePath = settings->GetModulesPath();
351     modulePath += "/mod_";
352     modulePath += modSettings[i].moduleName;
353     modulePath += ".so";
354     printfd(__FILE__, "Module: %s\n", modulePath.c_str());
355     modules.push_back(
356         PLUGIN_RUNNER(modulePath,
357                       modSettings[i],
358                       admins,
359                       tariffs,
360                       users,
361                       services,
362                       corps,
363                       traffCnt,
364                       dataStore,
365                       settings)
366         );
367     }
368
369 modIter = modules.begin();
370
371 while (modIter != modules.end())
372     {
373     if (modIter->Load())
374         {
375         WriteServLog("Error loading module '%s': %s",
376                      modIter->GetPlugin()->GetVersion().c_str(),
377                      modIter->GetStrError().c_str());
378         goto exitLblNotStarted;
379         }
380     ++modIter;
381     }
382
383 if (users->Start())
384     {
385     goto exitLblNotStarted;
386     }
387 WriteServLog("Users started successfully.");
388
389 if (traffCnt->Start())
390     {
391     goto exitLblNotStarted;
392     }
393 WriteServLog("Traffcounter started successfully.");
394
395 //Sort by start order
396 modules.sort(StartModCmp);
397 modIter = modules.begin();
398
399 while (modIter != modules.end())
400     {
401     if (modIter->Start())
402         {
403         WriteServLog("Error starting module '%s': %s",
404                      modIter->GetPlugin()->GetVersion().c_str(),
405                      modIter->GetStrError().c_str());
406         goto exitLbl;
407         }
408     WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
409     ++modIter;
410     }
411
412 srandom(static_cast<unsigned int>(stgTime));
413
414 WriteServLog("Stg started successfully.");
415 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
416
417 #ifndef NO_DAEMON
418 creat(startFile.c_str(), S_IRUSR);
419 #endif
420
421 while (true)
422     {
423     sigfillset(&signalSet);
424     int sig = 0;
425     sigwait(&signalSet, &sig);
426     bool stop = false;
427     int status;
428     pid_t childPid;
429     std::set<pid_t>::iterator it;
430     switch (sig)
431         {
432         case SIGHUP:
433             traffCnt->Reload();
434             modIter = modules.begin();
435             for (; modIter != modules.end(); ++modIter)
436                 {
437                 if (modIter->Reload())
438                     {
439                     WriteServLog("Error reloading module '%s': '%s'", modIter->GetPlugin()->GetVersion().c_str(),
440                                                               modIter->GetStrError().c_str());
441                     printfd(__FILE__, "Error reloading module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(),
442                                                                      modIter->GetStrError().c_str());
443                     }
444                 }
445             break;
446         case SIGTERM:
447             stop = true;
448             break;
449         case SIGINT:
450             stop = true;
451             break;
452         case SIGPIPE:
453             WriteServLog("Broken pipe!");
454             break;
455         case SIGCHLD:
456             childPid = waitpid(-1, &status, WNOHANG);
457
458             it = executersPid.find(childPid);
459             if (it != executersPid.end())
460                 {
461                 executersPid.erase(it);
462                 if (executersPid.empty())
463                     stop = true;
464                 }
465             break;
466         default:
467             WriteServLog("Ignore signel %d", sig);
468             break;
469         }
470     if (stop)
471         break;
472     }
473
474 exitLbl:
475
476 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
477
478 //Sort by start order
479 modules.sort(StopModCmp);
480 modIter = modules.begin();
481 while (modIter != modules.end())
482     {
483     std::string name = modIter->GetFileName();
484     printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
485     if (modIter->Stop())
486         {
487         WriteServLog("Error stopping module '%s': %s",
488                      modIter->GetPlugin()->GetVersion().c_str(),
489                      modIter->GetStrError().c_str());
490         printfd(__FILE__, "Error stopping module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str());
491         }
492     else
493         {
494         WriteServLog("Module: '%s'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
495         }
496     ++modIter;
497     }
498
499 if (loop.Stop())
500     {
501     WriteServLog("Event loop not stopped.");
502     }
503
504 exitLblNotStarted:
505
506 modIter = modules.begin();
507 while (modIter != modules.end())
508     {
509     std::string name = modIter->GetFileName();
510     if (modIter->IsRunning())
511         {
512         printfd(__FILE__, "Passing module '%s' `cause it's still running\n", name.c_str());
513         }
514     else
515         {
516         printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
517         if (modIter->Unload())
518             {
519             WriteServLog("Error unloading module '%s': '%s'",
520                          modIter->GetPlugin()->GetVersion().c_str(),
521                          modIter->GetStrError().c_str());
522             printfd(__FILE__, "Error unloading module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str());
523             }
524         }
525     ++modIter;
526     }
527
528 if (traffCnt)
529     {
530     traffCnt->Stop();
531     WriteServLog("Traffcounter: Stop successfull.");
532     }
533
534 if (users)
535     {
536     users->Stop();
537     WriteServLog("Users: Stop successfull.");
538     }
539
540 sleep(1);
541 int res = msgctl(msgID, IPC_RMID, NULL);
542 if (res)
543     WriteServLog("Queue was not removed. id=%d", msgID);
544 else
545     WriteServLog("Queue removed successfully.");
546
547 KillExecuters();
548
549 StopStgTimer();
550 WriteServLog("StgTimer: Stop successfull.");
551
552 delete corps;
553 delete services;
554 delete traffCnt;
555 delete users;
556 delete admins;
557 delete tariffs;
558 delete settings;
559
560 WriteServLog("Stg stopped successfully.");
561 WriteServLog("---------------------------------------------");
562
563 return 0;
564 }
565 //-----------------------------------------------------------------------------