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