]> git.stg.codes - stg.git/blob - projects/stargazer/main.cpp
code correction: removal spaces
[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     if (settings->GetLogFileName() != "")
268         WriteServLog.SetLogFileName(settings->GetLogFileName());
269     WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
270     exit(1);
271     }
272     /*************************************************************************************************/
273     printfd(__FILE__, "--- Script params dump ---\n");
274     std::vector<std::string>::const_iterator it(settings->GetScriptParams().begin());
275     while (it != settings->GetScriptParams().end())
276         {
277         printfd(__FILE__, "%s\n", it->c_str());
278         ++it;
279         }
280     printfd(__FILE__, "--- End dump ---\n"); 
281     /*************************************************************************************************/
282 #ifndef NO_DAEMON
283 std::string startFile(settings->GetConfDir() + START_FILE);
284 #endif
285
286 if (ForkAndWait(settings->GetConfDir()) < 0)
287     {
288     STG_LOGGER & WriteServLog = GetStgLogger();
289     WriteServLog("Fork error!");
290     exit(1);
291     }
292
293 STG_LOGGER & WriteServLog = GetStgLogger();
294 WriteServLog.SetLogFileName(settings->GetLogFileName());
295 WriteServLog("Stg v. %s", SERVER_VERSION);
296
297 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
298     {
299     int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
300     if (ret < 0)
301         {
302         STG_LOGGER & WriteServLog = GetStgLogger();
303         WriteServLog("Start Script Executer error!");
304         return 1;
305         }
306     if (ret == 1)
307         {
308         // Stopping child
309         return 0;
310         }
311     }
312
313 PIDFile pidFile(settings->GetPIDFileName());
314
315 sigset_t signalSet;
316 sigfillset(&signalSet);
317 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
318
319 StartTimer();
320 WaitTimer();
321 if (!IsStgTimerRunning())
322     {
323     printfd(__FILE__, "Timer thread not started in 1 sec!\n");
324     WriteServLog("Timer thread not started in 1 sec!");
325     }
326
327 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
328
329 STORE_LOADER storeLoader(*settings);
330 if (storeLoader.Load())
331     {
332     WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
333     goto exitLblNotStarted;
334     }
335
336 if (loop.Start())
337     {
338     WriteServLog("Event loop not started.");
339     goto exitLblNotStarted;
340     }
341
342 dataStore = storeLoader.GetStore();
343 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
344
345 tariffs = new TARIFFS_IMPL(dataStore);
346 admins = new ADMINS_IMPL(dataStore);
347 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
348 traffCnt = new TRAFFCOUNTER_IMPL(users, settings->GetRulesFileName());
349 services = new SERVICES_IMPL(dataStore);
350 corps = new CORPORATIONS_IMPL(dataStore);
351 traffCnt->SetMonitorDir(settings->GetMonitorDir());
352
353 modSettings = settings->GetModulesSettings();
354
355 for (size_t i = 0; i < modSettings.size(); i++)
356     {
357     std::string modulePath = settings->GetModulesPath();
358     modulePath += "/mod_";
359     modulePath += modSettings[i].moduleName;
360     modulePath += ".so";
361     printfd(__FILE__, "Module: %s\n", modulePath.c_str());
362     modules.push_back(
363         PLUGIN_RUNNER(modulePath,
364                       modSettings[i],
365                       admins,
366                       tariffs,
367                       users,
368                       services,
369                       corps,
370                       traffCnt,
371                       dataStore,
372                       settings)
373         );
374     }
375
376 modIter = modules.begin();
377
378 while (modIter != modules.end())
379     {
380     if (modIter->Load())
381         {
382         WriteServLog("Error loading module '%s': %s",
383                      modIter->GetPlugin()->GetVersion().c_str(),
384                      modIter->GetStrError().c_str());
385         goto exitLblNotStarted;
386         }
387     ++modIter;
388     }
389
390 if (users->Start())
391     {
392     goto exitLblNotStarted;
393     }
394 WriteServLog("Users started successfully.");
395
396 if (traffCnt->Start())
397     {
398     goto exitLblNotStarted;
399     }
400 WriteServLog("Traffcounter started successfully.");
401
402 //Sort by start order
403 modules.sort(StartModCmp);
404 modIter = modules.begin();
405
406 while (modIter != modules.end())
407     {
408     if (modIter->Start())
409         {
410         WriteServLog("Error starting module '%s': %s",
411                      modIter->GetPlugin()->GetVersion().c_str(),
412                      modIter->GetStrError().c_str());
413         goto exitLbl;
414         }
415     WriteServLog("Module: '%s'. Start successfull.", modIter->GetPlugin()->GetVersion().c_str());
416     ++modIter;
417     }
418
419 srandom(static_cast<unsigned int>(stgTime));
420
421 WriteServLog("Stg started successfully.");
422 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
423
424 #ifndef NO_DAEMON
425 creat(startFile.c_str(), S_IRUSR);
426 #endif
427
428 while (true)
429     {
430     sigfillset(&signalSet);
431     int sig = 0;
432     sigwait(&signalSet, &sig);
433     bool stop = false;
434     int status;
435     pid_t childPid;
436     std::set<pid_t>::iterator it;
437     switch (sig)
438         {
439         case SIGHUP:
440             traffCnt->Reload();
441             modIter = modules.begin();
442             for (; modIter != modules.end(); ++modIter)
443                 {
444                 if (modIter->Reload())
445                     {
446                     WriteServLog("Error reloading module '%s': '%s'", modIter->GetPlugin()->GetVersion().c_str(),
447                                                               modIter->GetStrError().c_str());
448                     printfd(__FILE__, "Error reloading module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(),
449                                                                      modIter->GetStrError().c_str());
450                     }
451                 }
452             break;
453         case SIGTERM:
454             stop = true;
455             break;
456         case SIGINT:
457             stop = true;
458             break;
459         case SIGPIPE:
460             WriteServLog("Broken pipe!");
461             break;
462         case SIGCHLD:
463             childPid = waitpid(-1, &status, WNOHANG);
464
465             it = executersPid.find(childPid);
466             if (it != executersPid.end())
467                 {
468                 executersPid.erase(it);
469                 if (executersPid.empty())
470                     stop = true;
471                 }
472             break;
473         default:
474             WriteServLog("Ignore signel %d", sig);
475             break;
476         }
477     if (stop)
478         break;
479     }
480
481 exitLbl:
482
483 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
484
485 //Sort by start order
486 modules.sort(StopModCmp);
487 modIter = modules.begin();
488 while (modIter != modules.end())
489     {
490     std::string name = modIter->GetFileName();
491     printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
492     if (modIter->Stop())
493         {
494         WriteServLog("Error stopping module '%s': %s",
495                      modIter->GetPlugin()->GetVersion().c_str(),
496                      modIter->GetStrError().c_str());
497         printfd(__FILE__, "Error stopping module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str());
498         }
499     else
500         {
501         WriteServLog("Module: '%s'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
502         }
503     ++modIter;
504     }
505
506 if (loop.Stop())
507     {
508     WriteServLog("Event loop not stopped.");
509     }
510
511 exitLblNotStarted:
512
513 modIter = modules.begin();
514 while (modIter != modules.end())
515     {
516     std::string name = modIter->GetFileName();
517     if (modIter->IsRunning())
518         {
519         printfd(__FILE__, "Passing module '%s' `cause it's still running\n", name.c_str());
520         }
521     else
522         {
523         printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
524         if (modIter->Unload())
525             {
526             WriteServLog("Error unloading module '%s': '%s'",
527                          modIter->GetPlugin()->GetVersion().c_str(),
528                          modIter->GetStrError().c_str());
529             printfd(__FILE__, "Error unloading module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str());
530             }
531         }
532     ++modIter;
533     }
534
535 if (traffCnt)
536     {
537     traffCnt->Stop();
538     WriteServLog("Traffcounter: Stop successfull.");
539     }
540
541 if (users)
542     {
543     users->Stop();
544     WriteServLog("Users: Stop successfull.");
545     }
546
547 sleep(1);
548 int res = msgctl(msgID, IPC_RMID, NULL);
549 if (res)
550     WriteServLog("Queue was not removed. id=%d", msgID);
551 else
552     WriteServLog("Queue removed successfully.");
553
554 KillExecuters();
555
556 StopStgTimer();
557 WriteServLog("StgTimer: Stop successfull.");
558
559 delete corps;
560 delete services;
561 delete traffCnt;
562 delete users;
563 delete admins;
564 delete tariffs;
565 delete settings;
566
567 WriteServLog("Stg stopped successfully.");
568 WriteServLog("---------------------------------------------");
569
570 return 0;
571 }
572 //-----------------------------------------------------------------------------