]> git.stg.codes - stg.git/blob - projects/stargazer/main.cpp
73786c4efd6c0cc46ba8aa805b9edaca0d9687cb
[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> executers;
67
68 void StartTimer();
69 int StartScriptExecuter(char * procName, int msgKey, int * msgID);
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)
93 #else
94 int StartScriptExecuter(char *, int msgKey, int * msgID)
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 pid = fork();
127
128 switch (pid)
129     {
130     case -1:
131         WriteServLog("Fork error!");
132         return -1;
133
134     case 0:
135 #if defined(LINUX) || defined(DARWIN)
136         Executer(*msgID, pid, procName);
137 #else
138         Executer(*msgID, pid);
139 #endif
140         return 1;
141
142     default:
143         if (executers.empty()) {
144 #if defined(LINUX) || defined(DARWIN)
145             Executer(*msgID, pid, NULL);
146 #else
147             Executer(*msgID, pid);
148 #endif
149         }
150         executers.insert(pid);
151     }
152 return 0;
153 }
154 //-----------------------------------------------------------------------------
155 #ifndef NO_DAEMON
156 int ForkAndWait(const std::string & confDir)
157 #else
158 int ForkAndWait(const std::string &)
159 #endif
160 {
161 #ifndef NO_DAEMON
162 pid_t pid = fork();
163 std::string startFile = confDir + START_FILE;
164 unlink(startFile.c_str());
165
166 switch (pid)
167     {
168     case -1:
169         return -1;
170         break;
171
172     case 0:
173         close(1);
174         close(2);
175         setsid();
176         break;
177
178     default:
179         struct timespec ts = {0, 200000000};
180         for (int i = 0; i < 120 * 5; i++)
181             {
182             if (access(startFile.c_str(), F_OK) == 0)
183                 {
184                 unlink(startFile.c_str());
185                 exit(0);
186                 }
187
188             nanosleep(&ts, NULL);
189             }
190         unlink(startFile.c_str());
191         exit(1);
192         break;
193     }
194 #endif
195 return 0;
196 }
197 //-----------------------------------------------------------------------------
198 void KillExecuters()
199 {
200 std::set<pid_t>::iterator pid(executers.begin());
201 while (pid != executers.end())
202     {
203     printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
204     kill(*pid, SIGUSR1);
205     ++pid;
206     }
207 }
208 //-----------------------------------------------------------------------------
209 } // namespace anonymous
210 //-----------------------------------------------------------------------------
211 int main(int argc, char * argv[])
212 {
213 int msgID = -11;
214
215 GetStgLogger().SetLogFileName("/var/log/stargazer.log");
216
217 if (getuid())
218     {
219     printf("You must be root. Exit.\n");
220     return 1;
221     }
222
223 SETTINGS_IMPL settings(argc == 2 ? argv[1] : "");
224
225 if (settings.ReadSettings())
226     {
227     STG_LOGGER & WriteServLog = GetStgLogger();
228
229     if (settings.GetLogFileName() != "")
230         WriteServLog.SetLogFileName(settings.GetLogFileName());
231
232     WriteServLog("ReadSettings error. %s", settings.GetStrError().c_str());
233     return -1;
234     }
235
236 #ifndef NO_DAEMON
237 std::string startFile(settings.GetConfDir() + START_FILE);
238 #endif
239
240 if (ForkAndWait(settings.GetConfDir()) < 0)
241     {
242     STG_LOGGER & WriteServLog = GetStgLogger();
243     WriteServLog("Fork error!");
244     return -1;
245     }
246
247 STG_LOGGER & WriteServLog = GetStgLogger();
248 WriteServLog.SetLogFileName(settings.GetLogFileName());
249 WriteServLog("Stg v. %s", SERVER_VERSION);
250
251 for (size_t i = 0; i < settings.GetExecutersNum(); i++)
252     {
253     int ret = StartScriptExecuter(argv[0], settings.GetExecMsgKey(), &msgID);
254     if (ret < 0)
255         {
256         STG_LOGGER & WriteServLog = GetStgLogger();
257         WriteServLog("Start Script Executer error!");
258         return -1;
259         }
260     if (ret == 1)
261         {
262         // Stopping child
263         return 0;
264         }
265     }
266
267 PIDFile pidFile(settings.GetPIDFileName());
268
269 sigset_t signalSet;
270 sigfillset(&signalSet);
271 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
272
273 StartTimer();
274 WaitTimer();
275 if (!IsStgTimerRunning())
276     {
277     printfd(__FILE__, "Timer thread not started in 1 sec!\n");
278     WriteServLog("Timer thread not started in 1 sec!");
279     return -1;
280     }
281
282 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
283
284 STORE_LOADER storeLoader(settings);
285 if (storeLoader.Load())
286     {
287     printfd(__FILE__, "Storage plugin: '%s'\n", storeLoader.GetStrError().c_str());
288     WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
289     return -1;
290     }
291
292 if (loop.Start())
293     {
294     printfd(__FILE__, "Event loop not started.\n");
295     WriteServLog("Event loop not started.");
296     return -1;
297     }
298
299 STORE & store(storeLoader.GetStore());
300 WriteServLog("Storage plugin: %s. Loading successfull.", store.GetVersion().c_str());
301
302 ADMINS_IMPL admins(&store);
303 TARIFFS_IMPL tariffs(&store);
304 SERVICES_IMPL services(&store);
305 CORPORATIONS_IMPL corps(&store);
306 USERS_IMPL users(&settings, &store, &tariffs, services, admins.GetSysAdmin());
307 TRAFFCOUNTER_IMPL traffCnt(&users, settings.GetRulesFileName());
308 traffCnt.SetMonitorDir(settings.GetMonitorDir());
309
310 if (users.Start())
311     return -1;
312
313 WriteServLog("Users started successfully.");
314
315 if (traffCnt.Start())
316     return -1;
317
318 WriteServLog("Traffcounter started successfully.");
319
320 STG::PluginManager manager(settings, store, admins, tariffs, services, corps, users, traffCnt);
321
322 srandom(static_cast<unsigned int>(stgTime));
323
324 WriteServLog("Stg started successfully.");
325 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
326
327 #ifndef NO_DAEMON
328 creat(startFile.c_str(), S_IRUSR);
329 #endif
330
331 bool running = true;
332 while (running)
333     {
334     sigfillset(&signalSet);
335     int sig = 0;
336     sigwait(&signalSet, &sig);
337     int status;
338     switch (sig)
339         {
340         case SIGHUP:
341             traffCnt.Reload();
342             manager.reload();
343             break;
344         case SIGTERM:
345             running = false;
346             break;
347         case SIGINT:
348             running = false;
349             break;
350         case SIGPIPE:
351             WriteServLog("Broken pipe!");
352             break;
353         case SIGCHLD:
354             executers.erase(waitpid(-1, &status, WNOHANG));
355             if (executers.empty())
356                 running = false;
357             break;
358         default:
359             WriteServLog("Ignore signal %d", sig);
360             break;
361         }
362     }
363
364 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
365
366 if (loop.Stop())
367     WriteServLog("Event loop not stopped.");
368
369 if (!traffCnt.Stop())
370     WriteServLog("Traffcounter: Stop successfull.");
371
372 if (!users.Stop())
373     WriteServLog("Users: Stop successfull.");
374
375 sleep(1);
376 int res = msgctl(msgID, IPC_RMID, NULL);
377 if (res)
378     WriteServLog("Queue was not removed. id=%d", msgID);
379 else
380     WriteServLog("Queue removed successfully.");
381
382 KillExecuters();
383
384 StopStgTimer();
385 WriteServLog("StgTimer: Stop successfull.");
386
387 WriteServLog("Stg stopped successfully.");
388 WriteServLog("---------------------------------------------");
389
390 return 0;
391 }
392 //-----------------------------------------------------------------------------