]> git.stg.codes - stg.git/blob - projects/stargazer/main.cpp
Moved plugin-related things into a separate file.
[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 #include "store_loader.h"
22 #include "plugin_mgr.h"
23 #include "plugin_runner.h"
24 #include "users_impl.h"
25 #include "admins_impl.h"
26 #include "tariffs_impl.h"
27 #include "services_impl.h"
28 #include "corps_impl.h"
29 #include "traffcounter_impl.h"
30 #include "settings_impl.h"
31 #include "pidfile.h"
32 #include "eventloop.h"
33 #include "stg_timer.h"
34
35 #include "stg/user.h"
36 #include "stg/common.h"
37 #include "stg/plugin.h"
38 #include "stg/logger.h"
39 #include "stg/scriptexecuter.h"
40 #include "stg/version.h"
41
42 #include <fstream>
43 #include <vector>
44 #include <set>
45 #include <csignal>
46 #include <cerrno>
47 #include <cstdio>
48 #include <cstdlib> // srandom, exit
49
50 #include <unistd.h>
51 #include <sys/ipc.h>
52 #include <sys/msg.h>
53 #include <sys/types.h>
54 #include <sys/wait.h>
55 #include <sys/stat.h> // S_IRUSR
56 #include <fcntl.h> // create
57
58 #ifdef DEBUG
59     #define NO_DAEMON  (1)
60 #endif
61
62 #define START_FILE "/._ST_ART_ED_"
63
64 namespace
65 {
66 std::set<pid_t> executersPid;
67
68 void StartTimer();
69 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings);
70 int ForkAndWait(const std::string & confDir);
71 void KillExecuters();
72
73 //-----------------------------------------------------------------------------
74 void StartTimer()
75 {
76 STG_LOGGER & WriteServLog = GetStgLogger();
77
78 if (RunStgTimer())
79     {
80     WriteServLog("Cannot start timer. Fatal.");
81     //printfd(__FILE__, "Cannot start timer. Fatal.\n");
82     exit(1);
83     }
84 else
85     {
86     WriteServLog("Timer thread started successfully.");
87     //printfd(__FILE__, "Timer thread started successfully.\n");
88     }
89 }
90 //-----------------------------------------------------------------------------
91 #if defined(LINUX) || defined(DARWIN)
92 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
93 #else
94 int StartScriptExecuter(char *, int msgKey, int * msgID, SETTINGS_IMPL * settings)
95 #endif
96 {
97 STG_LOGGER & WriteServLog = GetStgLogger();
98
99 if (*msgID == -11)   // If msgID == -11 - first call. Create queue
100     {
101     for (int i = 0; i < 2; i++)
102         {
103         *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
104
105         if (*msgID == -1)
106             {
107             *msgID = msgget(msgKey, 0);
108             if (*msgID == -1)
109                 {
110                 WriteServLog("Message queue not created.");
111                 return -1;
112                 }
113             else
114                 {
115                 msgctl(*msgID, IPC_RMID, NULL);
116                 }
117             }
118         else
119             {
120             WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
121             break;
122             }
123         }
124     }
125
126 pid_t executerPid = fork();
127
128 switch (executerPid)
129     {
130     case -1:
131         WriteServLog("Fork error!");
132         return -1;
133
134     case 0:
135         delete settings;
136 #if defined(LINUX) || defined(DARWIN)
137         Executer(*msgID, executerPid, procName);
138 #else
139         Executer(*msgID, executerPid);
140 #endif
141         return 1;
142
143     default:
144         if (executersPid.empty()) {
145 #if defined(LINUX) || defined(DARWIN)
146             Executer(*msgID, executerPid, NULL);
147 #else
148             Executer(*msgID, executerPid);
149 #endif
150         }
151         executersPid.insert(executerPid);
152     }
153 return 0;
154 }
155 //-----------------------------------------------------------------------------
156 #ifndef NO_DAEMON
157 int ForkAndWait(const std::string & confDir)
158 #else
159 int ForkAndWait(const std::string &)
160 #endif
161 {
162 #ifndef NO_DAEMON
163 pid_t childPid = fork();
164 std::string startFile = confDir + START_FILE;
165 unlink(startFile.c_str());
166
167 switch (childPid)
168     {
169     case -1:
170         return -1;
171         break;
172
173     case 0:
174         close(1);
175         close(2);
176         setsid();
177         break;
178
179     default:
180         struct timespec ts = {0, 200000000};
181         for (int i = 0; i < 120 * 5; i++)
182             {
183             if (access(startFile.c_str(), F_OK) == 0)
184                 {
185                 unlink(startFile.c_str());
186                 exit(0);
187                 }
188
189             nanosleep(&ts, NULL);
190             }
191         unlink(startFile.c_str());
192         exit(1);
193         break;
194     }
195 #endif
196 return 0;
197 }
198 //-----------------------------------------------------------------------------
199 void KillExecuters()
200 {
201 std::set<pid_t>::iterator pid;
202 pid = executersPid.begin();
203 while (pid != executersPid.end())
204     {
205     printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
206     kill(*pid, SIGUSR1);
207     ++pid;
208     }
209 }
210 //-----------------------------------------------------------------------------
211 } // namespace anonymous
212 //-----------------------------------------------------------------------------
213 int main(int argc, char * argv[])
214 {
215 SETTINGS_IMPL * settings = NULL;
216 int msgID = -11;
217
218 GetStgLogger().SetLogFileName("/var/log/stargazer.log");
219
220 if (getuid())
221     {
222     printf("You must be root. Exit.\n");
223     return 1;
224     }
225
226 if (argc == 2)
227     settings = new SETTINGS_IMPL(argv[1]);
228 else
229     settings = new SETTINGS_IMPL();
230
231 if (settings->ReadSettings())
232     {
233     STG_LOGGER & WriteServLog = GetStgLogger();
234
235     if (settings->GetLogFileName() != "")
236         WriteServLog.SetLogFileName(settings->GetLogFileName());
237
238     WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
239     return -1;
240     }
241
242 #ifndef NO_DAEMON
243 std::string startFile(settings->GetConfDir() + START_FILE);
244 #endif
245
246 if (ForkAndWait(settings->GetConfDir()) < 0)
247     {
248     STG_LOGGER & WriteServLog = GetStgLogger();
249     WriteServLog("Fork error!");
250     return -1;
251     }
252
253 STG_LOGGER & WriteServLog = GetStgLogger();
254 WriteServLog.SetLogFileName(settings->GetLogFileName());
255 WriteServLog("Stg v. %s", SERVER_VERSION);
256
257 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
258     {
259     int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
260     if (ret < 0)
261         {
262         STG_LOGGER & WriteServLog = GetStgLogger();
263         WriteServLog("Start Script Executer error!");
264         return -1;
265         }
266     if (ret == 1)
267         {
268         // Stopping child
269         return 0;
270         }
271     }
272
273 PIDFile pidFile(settings->GetPIDFileName());
274
275 sigset_t signalSet;
276 sigfillset(&signalSet);
277 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
278
279 StartTimer();
280 WaitTimer();
281 if (!IsStgTimerRunning())
282     {
283     printfd(__FILE__, "Timer thread not started in 1 sec!\n");
284     WriteServLog("Timer thread not started in 1 sec!");
285     return -1;
286     }
287
288 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
289
290 STORE_LOADER storeLoader(*settings);
291 if (storeLoader.Load())
292     {
293     printfd(__FILE__, "Storage plugin: '%s'\n", storeLoader.GetStrError().c_str());
294     WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
295     return -1;
296     }
297
298 if (loop.Start())
299     {
300     printfd(__FILE__, "Event loop not started.\n");
301     WriteServLog("Event loop not started.");
302     return -1;
303     }
304
305 STORE & store(storeLoader.GetStore());
306 WriteServLog("Storage plugin: %s. Loading successfull.", store.GetVersion().c_str());
307
308 ADMINS_IMPL admins(&store);
309 TARIFFS_IMPL tariffs(&store);
310 SERVICES_IMPL services(&store);
311 CORPORATIONS_IMPL corps(&store);
312 USERS_IMPL users(settings, &store, &tariffs, services, admins.GetSysAdmin());
313 TRAFFCOUNTER_IMPL traffCnt(&users, settings->GetRulesFileName());
314 traffCnt.SetMonitorDir(settings->GetMonitorDir());
315
316 if (users.Start())
317     return -1;
318
319 WriteServLog("Users started successfully.");
320
321 if (traffCnt.Start())
322     return -1;
323
324 WriteServLog("Traffcounter started successfully.");
325
326 STG::PluginManager manager(*settings, store, admins, tariffs, services, corps, users, traffCnt);
327
328 srandom(static_cast<unsigned int>(stgTime));
329
330 WriteServLog("Stg started successfully.");
331 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
332
333 #ifndef NO_DAEMON
334 creat(startFile.c_str(), S_IRUSR);
335 #endif
336
337 while (true)
338     {
339     sigfillset(&signalSet);
340     int sig = 0;
341     sigwait(&signalSet, &sig);
342     bool stop = false;
343     int status;
344     pid_t childPid;
345     std::set<pid_t>::iterator it;
346     switch (sig)
347         {
348         case SIGHUP:
349             traffCnt.Reload();
350             manager.reload();
351             break;
352         case SIGTERM:
353             stop = true;
354             break;
355         case SIGINT:
356             stop = true;
357             break;
358         case SIGPIPE:
359             WriteServLog("Broken pipe!");
360             break;
361         case SIGCHLD:
362             childPid = waitpid(-1, &status, WNOHANG);
363
364             it = executersPid.find(childPid);
365             if (it != executersPid.end())
366                 {
367                 executersPid.erase(it);
368                 if (executersPid.empty())
369                     stop = true;
370                 }
371             break;
372         default:
373             WriteServLog("Ignore signal %d", sig);
374             break;
375         }
376     if (stop)
377         break;
378     }
379
380 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
381
382 if (loop.Stop())
383     WriteServLog("Event loop not stopped.");
384
385 if (!traffCnt.Stop())
386     WriteServLog("Traffcounter: Stop successfull.");
387
388 if (!users.Stop())
389     WriteServLog("Users: Stop successfull.");
390
391 sleep(1);
392 int res = msgctl(msgID, IPC_RMID, NULL);
393 if (res)
394     WriteServLog("Queue was not removed. id=%d", msgID);
395 else
396     WriteServLog("Queue removed successfully.");
397
398 KillExecuters();
399
400 StopStgTimer();
401 WriteServLog("StgTimer: Stop successfull.");
402
403 delete settings;
404
405 WriteServLog("Stg stopped successfully.");
406 WriteServLog("---------------------------------------------");
407
408 return 0;
409 }
410 //-----------------------------------------------------------------------------