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