]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/other/smux/smux.cpp
Block all signals in threads other than main
[stg.git] / projects / stargazer / plugins / other / smux / smux.cpp
1 #include <sys/types.h>
2 #include <sys/socket.h>
3 #include <arpa/inet.h>
4
5 #include <cstring>
6 #include <cerrno>
7 #include <ctime>
8 #include <csignal>
9 #include <cassert>
10
11 #include <vector>
12 #include <algorithm>
13 #include <iterator>
14 #include <stdexcept>
15 #include <utility>
16
17 #include "stg/common.h"
18 #include "stg/plugin_creator.h"
19
20 #include "smux.h"
21 #include "utils.h"
22
23 PLUGIN_CREATOR<SMUX> smc;
24
25 PLUGIN * GetPlugin()
26 {
27 return smc.GetPlugin();
28 }
29
30 bool SPrefixLess(const Sensors::value_type & a,
31                  const Sensors::value_type & b)
32 {
33 return a.first.PrefixLess(b.first);
34 }
35
36 SMUX_SETTINGS::SMUX_SETTINGS()
37     : errorStr(),
38       ip(0),
39       port(0),
40       password()
41 {}
42
43 int SMUX_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
44 {
45 PARAM_VALUE pv;
46 std::vector<PARAM_VALUE>::const_iterator pvi;
47 int p;
48
49 pv.param = "Port";
50 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
51 if (pvi == s.moduleParams.end())
52     {
53     errorStr = "Parameter \'Port\' not found.";
54     printfd(__FILE__, "Parameter 'Port' not found\n");
55     return -1;
56     }
57 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
58     {
59     errorStr = "Cannot parse parameter \'Port\': " + errorStr;
60     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
61     return -1;
62     }
63 port = p;
64
65 pv.param = "Password";
66 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
67 if (pvi == s.moduleParams.end())
68     {
69     errorStr = "Parameter \'Password\' not found.";
70     printfd(__FILE__, "Parameter 'Password' not found\n");
71     password = "";
72     }
73 else
74     {
75     password = pvi->value[0];
76     }
77
78 pv.param = "Server";
79 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
80 if (pvi == s.moduleParams.end())
81     {
82     errorStr = "Parameter \'Server\' not found.";
83     printfd(__FILE__, "Parameter 'Server' not found\n");
84     return -1;
85     }
86 ip = inet_strington(pvi->value[0]);
87
88 return 0;
89 }
90
91 SMUX::SMUX()
92     : PLUGIN(),
93       users(NULL),
94       tariffs(NULL),
95       admins(NULL),
96       services(NULL),
97       corporations(NULL),
98       traffcounter(NULL),
99       errorStr(),
100       smuxSettings(),
101       settings(),
102       thread(),
103       mutex(),
104       running(false),
105       stopped(true),
106       sock(-1),
107       smuxHandlers(),
108       pdusHandlers(),
109       sensors(),
110       tables(),
111       notifiers(),
112       addUserNotifier(*this),
113       delUserNotifier(*this),
114       addDelTariffNotifier(*this)
115 {
116 pthread_mutex_init(&mutex, NULL);
117
118 smuxHandlers[SMUX_PDUs_PR_close] = &SMUX::CloseHandler;
119 smuxHandlers[SMUX_PDUs_PR_registerResponse] = &SMUX::RegisterResponseHandler;
120 smuxHandlers[SMUX_PDUs_PR_pdus] = &SMUX::PDUsRequestHandler;
121 smuxHandlers[SMUX_PDUs_PR_commitOrRollback] = &SMUX::CommitOrRollbackHandler;
122
123 pdusHandlers[PDUs_PR_get_request] = &SMUX::GetRequestHandler;
124 pdusHandlers[PDUs_PR_get_next_request] = &SMUX::GetNextRequestHandler;
125 pdusHandlers[PDUs_PR_set_request] = &SMUX::SetRequestHandler;
126 }
127
128 SMUX::~SMUX()
129 {
130     {
131     Sensors::iterator it;
132     for (it = sensors.begin(); it != sensors.end(); ++it)
133         delete it->second;
134     }
135     {
136     Tables::iterator it;
137     for (it = tables.begin(); it != tables.end(); ++it)
138         delete it->second;
139     }
140 printfd(__FILE__, "SMUX::~SMUX()\n");
141 pthread_mutex_destroy(&mutex);
142 }
143
144 int SMUX::ParseSettings()
145 {
146 return smuxSettings.ParseSettings(settings);
147 }
148
149 int SMUX::Start()
150 {
151 assert(users != NULL && "users must not be NULL");
152 assert(tariffs != NULL && "tariffs must not be NULL");
153 assert(admins != NULL && "admins must not be NULL");
154 assert(services != NULL && "services must not be NULL");
155 assert(corporations != NULL && "corporations must not be NULL");
156 assert(traffcounter != NULL && "traffcounter must not be NULL");
157
158 if (PrepareNet())
159     return -1;
160
161 // Users
162 sensors[OID(".1.3.6.1.4.1.38313.1.1.1")] = new TotalUsersSensor(*users);
163 sensors[OID(".1.3.6.1.4.1.38313.1.1.2")] = new ConnectedUsersSensor(*users);
164 sensors[OID(".1.3.6.1.4.1.38313.1.1.3")] = new AuthorizedUsersSensor(*users);
165 sensors[OID(".1.3.6.1.4.1.38313.1.1.4")] = new AlwaysOnlineUsersSensor(*users);
166 sensors[OID(".1.3.6.1.4.1.38313.1.1.5")] = new NoCashUsersSensor(*users);
167 sensors[OID(".1.3.6.1.4.1.38313.1.1.6")] = new DisabledDetailStatsUsersSensor(*users);
168 sensors[OID(".1.3.6.1.4.1.38313.1.1.7")] = new DisabledUsersSensor(*users);
169 sensors[OID(".1.3.6.1.4.1.38313.1.1.8")] = new PassiveUsersSensor(*users);
170 sensors[OID(".1.3.6.1.4.1.38313.1.1.9")] = new CreditUsersSensor(*users);
171 sensors[OID(".1.3.6.1.4.1.38313.1.1.10")] = new FreeMbUsersSensor(*users);
172 sensors[OID(".1.3.6.1.4.1.38313.1.1.11")] = new TariffChangeUsersSensor(*users);
173 // Tariffs
174 sensors[OID(".1.3.6.1.4.1.38313.1.2.1")] = new TotalTariffsSensor(*tariffs);
175 // Admins
176 sensors[OID(".1.3.6.1.4.1.38313.1.3.1")] = new TotalAdminsSensor(*admins);
177 // Services
178 sensors[OID(".1.3.6.1.4.1.38313.1.4.1")] = new TotalServicesSensor(*services);
179 // Corporations
180 sensors[OID(".1.3.6.1.4.1.38313.1.5.1")] = new TotalCorporationsSensor(*corporations);
181 // Traffcounter
182 sensors[OID(".1.3.6.1.4.1.38313.1.6.1")] = new TotalRulesSensor(*traffcounter);
183
184 // Table data
185 tables[".1.3.6.1.4.1.38313.1.2.2"] = new TariffUsersTable(".1.3.6.1.4.1.38313.1.2.2", *tariffs, *users);
186
187 UpdateTables();
188 SetNotifiers();
189
190 #ifdef SMUX_DEBUG
191 Sensors::const_iterator it(sensors.begin());
192 while (it != sensors.end())
193     {
194     printfd(__FILE__, "%s = %s\n",
195             it->first.ToString().c_str(),
196             it->second->ToString().c_str());
197     ++it;
198     }
199 #endif
200
201 if (!running)
202     {
203     if (pthread_create(&thread, NULL, Runner, this))
204         {
205         errorStr = "Cannot create thread.";
206         printfd(__FILE__, "Cannot create thread\n");
207         return -1;
208         }
209     }
210
211 return 0;
212 }
213
214 int SMUX::Stop()
215 {
216 printfd(__FILE__, "SMUX::Stop() - Before\n");
217 running = false;
218
219 if (!stopped)
220     {
221     //5 seconds to thread stops itself
222     for (int i = 0; i < 25 && !stopped; i++)
223         {
224         struct timespec ts = {0, 200000000};
225         nanosleep(&ts, NULL);
226         }
227
228     //after 5 seconds waiting thread still running. now killing it
229     if (!stopped)
230         {
231         printfd(__FILE__, "SMUX::Stop() - failed to stop thread, killing it\n");
232         if (pthread_kill(thread, SIGINT))
233             {
234             errorStr = "Cannot kill thread.";
235             printfd(__FILE__, "SMUX::Stop() - Cannot kill thread\n");
236             return -1;
237             }
238         printfd(__FILE__, "SMUX::Stop() -  killed Run\n");
239         }
240     }
241
242 pthread_join(thread, NULL);
243
244 ResetNotifiers();
245
246     {
247     Tables::iterator it;
248     for (it = tables.begin(); it != tables.end(); ++it)
249         delete it->second;
250     }
251     {
252     Sensors::iterator it;
253     for (it = sensors.begin(); it != sensors.end(); ++it)
254         delete it->second;
255     }
256
257 tables.erase(tables.begin(), tables.end());
258 sensors.erase(sensors.begin(), sensors.end());
259
260 close(sock);
261
262 printfd(__FILE__, "SMUX::Stop() - After\n");
263 return 0;
264 }
265
266 int SMUX::Reload()
267 {
268 if (Stop())
269     return -1;
270 if (Start())
271     return -1;
272 return 0;
273 }
274
275 void * SMUX::Runner(void * d)
276 {
277 sigset_t signalSet;
278 sigfillset(&signalSet);
279 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
280
281 SMUX * smux = static_cast<SMUX *>(d);
282
283 smux->Run();
284
285 return NULL;
286 }
287
288 void SMUX::Run()
289 {
290 stopped = true;
291 if (!SendOpenPDU(sock))
292     return;
293 if (!SendRReqPDU(sock))
294     return;
295 running = true;
296 stopped = false;
297
298 while(running)
299     {
300     if (WaitPackets(sock))
301         {
302         SMUX_PDUs_t * pdus = RecvSMUXPDUs(sock);
303         if (pdus)
304             {
305             DispatchPDUs(pdus);
306             ASN_STRUCT_FREE(asn_DEF_SMUX_PDUs, pdus);
307             }
308         }
309     if (!running)
310         break;
311     }
312 SendClosePDU(sock);
313 stopped = true;
314 }
315
316 bool SMUX::PrepareNet()
317 {
318 sock = socket(AF_INET, SOCK_STREAM, 0);
319
320 if (sock < 0)
321     {
322     errorStr = "Cannot create socket.";
323     printfd(__FILE__, "Cannot create socket\n");
324     return true;
325     }
326
327 struct sockaddr_in addr;
328
329 addr.sin_family = AF_INET;
330 addr.sin_port = htons(smuxSettings.GetPort());
331 addr.sin_addr.s_addr = smuxSettings.GetIP();
332
333 if (connect(sock, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)))
334     {
335     errorStr = "Cannot connect.";
336     printfd(__FILE__, "Cannot connect. Message: '%s'\n", strerror(errno));
337     return true;
338     }
339
340 return false;
341 }
342
343 bool SMUX::DispatchPDUs(const SMUX_PDUs_t * pdus)
344 {
345 SMUXHandlers::iterator it;
346 it = smuxHandlers.find(pdus->present);
347 if (it != smuxHandlers.end())
348     {
349     return (this->*(it->second))(pdus);
350     }
351 else
352     {
353 #ifdef SMUX_DEBUG
354     switch (pdus->present)
355         {
356         case SMUX_PDUs_PR_NOTHING:
357             printfd(__FILE__, "PDUs: nothing\n");
358             break;
359         case SMUX_PDUs_PR_open:
360             printfd(__FILE__, "PDUs: open\n");
361             break;
362         case SMUX_PDUs_PR_registerRequest:
363             printfd(__FILE__, "PDUs: registerRequest\n");
364             break;
365         default:
366             printfd(__FILE__, "PDUs: undefined\n");
367         }
368     asn_fprint(stderr, &asn_DEF_SMUX_PDUs, pdus);
369 #endif
370     }
371 return false;
372 }
373
374 bool SMUX::UpdateTables()
375 {
376 Sensors newSensors;
377 bool done = true;
378 Tables::iterator it(tables.begin());
379 while (it != tables.end())
380     {
381     try
382         {
383         it->second->UpdateSensors(newSensors);
384         }
385     catch (const std::runtime_error & ex)
386         {
387         printfd(__FILE__,
388                 "SMUX::UpdateTables - failed to update table '%s': '%s'\n",
389                 it->first.c_str(), ex.what());
390         done = false;
391         break;
392         }
393     ++it;
394     }
395 if (!done)
396     {
397     Sensors::iterator it(newSensors.begin());
398     while (it != newSensors.end())
399         {
400         delete it->second;
401         ++it;
402         }
403     return false;
404     }
405
406 it = tables.begin();
407 while (it != tables.end())
408     {
409     std::pair<Sensors::iterator, Sensors::iterator> res;
410     res = std::equal_range(sensors.begin(),
411                            sensors.end(),
412                            std::pair<OID, Sensor *>(OID(it->first), NULL),
413                            SPrefixLess);
414     Sensors::iterator sit(res.first);
415     while (sit != res.second)
416         {
417         delete sit->second;
418         ++sit;
419         }
420     sensors.erase(res.first, res.second);
421     ++it;
422     }
423
424 sensors.insert(newSensors.begin(), newSensors.end());
425
426 return true;
427 }
428
429 void SMUX::SetNotifier(USER_PTR userPtr)
430 {
431 notifiers.push_back(CHG_AFTER_NOTIFIER(*this, userPtr));
432 userPtr->GetProperty().tariffName.AddAfterNotifier(&notifiers.back());
433 }
434
435 void SMUX::UnsetNotifier(USER_PTR userPtr)
436 {
437 std::list<CHG_AFTER_NOTIFIER>::iterator it = notifiers.begin();
438 while (it != notifiers.end())
439     {
440     if (it->GetUserPtr() == userPtr)
441         {
442         userPtr->GetProperty().tariffName.DelAfterNotifier(&(*it));
443         notifiers.erase(it);
444         break;
445         }
446     ++it;
447     }
448 }
449
450 void SMUX::SetNotifiers()
451 {
452 int h = users->OpenSearch();
453 assert(h && "USERS::OpenSearch is always correct");
454
455 USER_PTR u;
456 while (!users->SearchNext(h, &u))
457     SetNotifier(u);
458
459 users->CloseSearch(h);
460
461 users->AddNotifierUserAdd(&addUserNotifier);
462 users->AddNotifierUserDel(&delUserNotifier);
463
464 tariffs->AddNotifierAdd(&addDelTariffNotifier);
465 tariffs->AddNotifierDel(&addDelTariffNotifier);
466 }
467
468 void SMUX::ResetNotifiers()
469 {
470 tariffs->DelNotifierDel(&addDelTariffNotifier);
471 tariffs->DelNotifierAdd(&addDelTariffNotifier);
472
473 users->DelNotifierUserDel(&delUserNotifier);
474 users->DelNotifierUserAdd(&addUserNotifier);
475
476 std::list<CHG_AFTER_NOTIFIER>::iterator it = notifiers.begin();
477 while (it != notifiers.end())
478     {
479     it->GetUserPtr()->GetProperty().tariffName.DelAfterNotifier(&(*it));
480     ++it;
481     }
482 }
483
484 void CHG_AFTER_NOTIFIER::Notify(const std::string &, const std::string &)
485 {
486 smux.UpdateTables();
487 }