]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/other/smux/smux.cpp
Log errors from plugins to server log.
[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       logger(GetPluginLogger(GetStgLogger(), "smux"))
116 {
117 pthread_mutex_init(&mutex, NULL);
118
119 smuxHandlers[SMUX_PDUs_PR_close] = &SMUX::CloseHandler;
120 smuxHandlers[SMUX_PDUs_PR_registerResponse] = &SMUX::RegisterResponseHandler;
121 smuxHandlers[SMUX_PDUs_PR_pdus] = &SMUX::PDUsRequestHandler;
122 smuxHandlers[SMUX_PDUs_PR_commitOrRollback] = &SMUX::CommitOrRollbackHandler;
123
124 pdusHandlers[PDUs_PR_get_request] = &SMUX::GetRequestHandler;
125 pdusHandlers[PDUs_PR_get_next_request] = &SMUX::GetNextRequestHandler;
126 pdusHandlers[PDUs_PR_set_request] = &SMUX::SetRequestHandler;
127 }
128
129 SMUX::~SMUX()
130 {
131     {
132     Sensors::iterator it;
133     for (it = sensors.begin(); it != sensors.end(); ++it)
134         delete it->second;
135     }
136     {
137     Tables::iterator it;
138     for (it = tables.begin(); it != tables.end(); ++it)
139         delete it->second;
140     }
141 printfd(__FILE__, "SMUX::~SMUX()\n");
142 pthread_mutex_destroy(&mutex);
143 }
144
145 int SMUX::ParseSettings()
146 {
147 return smuxSettings.ParseSettings(settings);
148 }
149
150 int SMUX::Start()
151 {
152 assert(users != NULL && "users must not be NULL");
153 assert(tariffs != NULL && "tariffs must not be NULL");
154 assert(admins != NULL && "admins must not be NULL");
155 assert(services != NULL && "services must not be NULL");
156 assert(corporations != NULL && "corporations must not be NULL");
157 assert(traffcounter != NULL && "traffcounter must not be NULL");
158
159 if (PrepareNet())
160     return -1;
161
162 // Users
163 sensors[OID(".1.3.6.1.4.1.38313.1.1.1")] = new TotalUsersSensor(*users);
164 sensors[OID(".1.3.6.1.4.1.38313.1.1.2")] = new ConnectedUsersSensor(*users);
165 sensors[OID(".1.3.6.1.4.1.38313.1.1.3")] = new AuthorizedUsersSensor(*users);
166 sensors[OID(".1.3.6.1.4.1.38313.1.1.4")] = new AlwaysOnlineUsersSensor(*users);
167 sensors[OID(".1.3.6.1.4.1.38313.1.1.5")] = new NoCashUsersSensor(*users);
168 sensors[OID(".1.3.6.1.4.1.38313.1.1.6")] = new DisabledDetailStatsUsersSensor(*users);
169 sensors[OID(".1.3.6.1.4.1.38313.1.1.7")] = new DisabledUsersSensor(*users);
170 sensors[OID(".1.3.6.1.4.1.38313.1.1.8")] = new PassiveUsersSensor(*users);
171 sensors[OID(".1.3.6.1.4.1.38313.1.1.9")] = new CreditUsersSensor(*users);
172 sensors[OID(".1.3.6.1.4.1.38313.1.1.10")] = new FreeMbUsersSensor(*users);
173 sensors[OID(".1.3.6.1.4.1.38313.1.1.11")] = new TariffChangeUsersSensor(*users);
174 sensors[OID(".1.3.6.1.4.1.38313.1.1.12")] = new ActiveUsersSensor(*users);
175 // Tariffs
176 sensors[OID(".1.3.6.1.4.1.38313.1.2.1")] = new TotalTariffsSensor(*tariffs);
177 // Admins
178 sensors[OID(".1.3.6.1.4.1.38313.1.3.1")] = new TotalAdminsSensor(*admins);
179 // Services
180 sensors[OID(".1.3.6.1.4.1.38313.1.4.1")] = new TotalServicesSensor(*services);
181 // Corporations
182 sensors[OID(".1.3.6.1.4.1.38313.1.5.1")] = new TotalCorporationsSensor(*corporations);
183 // Traffcounter
184 sensors[OID(".1.3.6.1.4.1.38313.1.6.1")] = new TotalRulesSensor(*traffcounter);
185
186 // Table data
187 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);
188
189 UpdateTables();
190 SetNotifiers();
191
192 #ifdef SMUX_DEBUG
193 Sensors::const_iterator it(sensors.begin());
194 while (it != sensors.end())
195     {
196     printfd(__FILE__, "%s = %s\n",
197             it->first.ToString().c_str(),
198             it->second->ToString().c_str());
199     ++it;
200     }
201 #endif
202
203 if (!running)
204     {
205     if (pthread_create(&thread, NULL, Runner, this))
206         {
207         errorStr = "Cannot create thread.";
208         logger("Cannot create thread.");
209         printfd(__FILE__, "Cannot create thread\n");
210         return -1;
211         }
212     }
213
214 return 0;
215 }
216
217 int SMUX::Stop()
218 {
219 printfd(__FILE__, "SMUX::Stop() - Before\n");
220 running = false;
221
222 if (!stopped)
223     {
224     //5 seconds to thread stops itself
225     for (int i = 0; i < 25 && !stopped; i++)
226         {
227         struct timespec ts = {0, 200000000};
228         nanosleep(&ts, NULL);
229         }
230     }
231
232 if (stopped)
233     pthread_join(thread, NULL);
234
235 ResetNotifiers();
236
237     {
238     Tables::iterator it;
239     for (it = tables.begin(); it != tables.end(); ++it)
240         delete it->second;
241     }
242     {
243     Sensors::iterator it;
244     for (it = sensors.begin(); it != sensors.end(); ++it)
245         delete it->second;
246     }
247
248 tables.erase(tables.begin(), tables.end());
249 sensors.erase(sensors.begin(), sensors.end());
250
251 close(sock);
252
253 if (!stopped)
254     {
255     running = true;
256     return -1;
257     }
258
259 printfd(__FILE__, "SMUX::Stop() - After\n");
260 return 0;
261 }
262
263 int SMUX::Reload()
264 {
265 if (Stop())
266     return -1;
267 if (Start())
268     return -1;
269 return 0;
270 }
271
272 void * SMUX::Runner(void * d)
273 {
274 sigset_t signalSet;
275 sigfillset(&signalSet);
276 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
277
278 SMUX * smux = static_cast<SMUX *>(d);
279
280 smux->Run();
281
282 return NULL;
283 }
284
285 void SMUX::Run()
286 {
287 stopped = true;
288 if (!SendOpenPDU(sock))
289     return;
290 if (!SendRReqPDU(sock))
291     return;
292 running = true;
293 stopped = false;
294
295 while(running)
296     {
297     if (WaitPackets(sock))
298         {
299         SMUX_PDUs_t * pdus = RecvSMUXPDUs(sock);
300         if (pdus)
301             {
302             DispatchPDUs(pdus);
303             ASN_STRUCT_FREE(asn_DEF_SMUX_PDUs, pdus);
304             }
305         }
306     if (!running)
307         break;
308     }
309 SendClosePDU(sock);
310 stopped = true;
311 }
312
313 bool SMUX::PrepareNet()
314 {
315 sock = socket(AF_INET, SOCK_STREAM, 0);
316
317 if (sock < 0)
318     {
319     errorStr = "Cannot create socket.";
320     logger("Cannot create a socket: %s", strerror(errno));
321     printfd(__FILE__, "Cannot create socket\n");
322     return true;
323     }
324
325 struct sockaddr_in addr;
326
327 addr.sin_family = AF_INET;
328 addr.sin_port = htons(smuxSettings.GetPort());
329 addr.sin_addr.s_addr = smuxSettings.GetIP();
330
331 if (connect(sock, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)))
332     {
333     errorStr = "Cannot connect.";
334     logger("Cannot connect the socket: %s", strerror(errno));
335     printfd(__FILE__, "Cannot connect. Message: '%s'\n", strerror(errno));
336     return true;
337     }
338
339 return false;
340 }
341
342 bool SMUX::DispatchPDUs(const SMUX_PDUs_t * pdus)
343 {
344 SMUXHandlers::iterator it(smuxHandlers.find(pdus->present));
345 if (it != smuxHandlers.end())
346     {
347     return (this->*(it->second))(pdus);
348     }
349 #ifdef SMUX_DEBUG
350 else
351     {
352     switch (pdus->present)
353         {
354         case SMUX_PDUs_PR_NOTHING:
355             printfd(__FILE__, "PDUs: nothing\n");
356             break;
357         case SMUX_PDUs_PR_open:
358             printfd(__FILE__, "PDUs: open\n");
359             break;
360         case SMUX_PDUs_PR_registerRequest:
361             printfd(__FILE__, "PDUs: registerRequest\n");
362             break;
363         default:
364             printfd(__FILE__, "PDUs: undefined\n");
365         }
366     asn_fprint(stderr, &asn_DEF_SMUX_PDUs, pdus);
367     }
368 #endif
369 return false;
370 }
371
372 bool SMUX::UpdateTables()
373 {
374 Sensors newSensors;
375 bool done = true;
376 Tables::iterator it(tables.begin());
377 while (it != tables.end())
378     {
379     try
380         {
381         it->second->UpdateSensors(newSensors);
382         }
383     catch (const std::runtime_error & ex)
384         {
385         printfd(__FILE__,
386                 "SMUX::UpdateTables - failed to update table '%s': '%s'\n",
387                 it->first.c_str(), ex.what());
388         done = false;
389         break;
390         }
391     ++it;
392     }
393 if (!done)
394     {
395     Sensors::iterator it(newSensors.begin());
396     while (it != newSensors.end())
397         {
398         delete it->second;
399         ++it;
400         }
401     return false;
402     }
403
404 it = tables.begin();
405 while (it != tables.end())
406     {
407     std::pair<Sensors::iterator, Sensors::iterator> res;
408     res = std::equal_range(sensors.begin(),
409                            sensors.end(),
410                            std::pair<OID, Sensor *>(OID(it->first), NULL),
411                            SPrefixLess);
412     Sensors::iterator sit(res.first);
413     while (sit != res.second)
414         {
415         delete sit->second;
416         ++sit;
417         }
418     sensors.erase(res.first, res.second);
419     ++it;
420     }
421
422 sensors.insert(newSensors.begin(), newSensors.end());
423
424 return true;
425 }
426
427 void SMUX::SetNotifier(USER_PTR userPtr)
428 {
429 notifiers.push_back(CHG_AFTER_NOTIFIER(*this, userPtr));
430 userPtr->GetProperty().tariffName.AddAfterNotifier(&notifiers.back());
431 }
432
433 void SMUX::UnsetNotifier(USER_PTR userPtr)
434 {
435 std::list<CHG_AFTER_NOTIFIER>::iterator it = notifiers.begin();
436 while (it != notifiers.end())
437     {
438     if (it->GetUserPtr() == userPtr)
439         {
440         userPtr->GetProperty().tariffName.DelAfterNotifier(&(*it));
441         notifiers.erase(it);
442         break;
443         }
444     ++it;
445     }
446 }
447
448 void SMUX::SetNotifiers()
449 {
450 int h = users->OpenSearch();
451 assert(h && "USERS::OpenSearch is always correct");
452
453 USER_PTR u;
454 while (!users->SearchNext(h, &u))
455     SetNotifier(u);
456
457 users->CloseSearch(h);
458
459 users->AddNotifierUserAdd(&addUserNotifier);
460 users->AddNotifierUserDel(&delUserNotifier);
461
462 tariffs->AddNotifierAdd(&addDelTariffNotifier);
463 tariffs->AddNotifierDel(&addDelTariffNotifier);
464 }
465
466 void SMUX::ResetNotifiers()
467 {
468 tariffs->DelNotifierDel(&addDelTariffNotifier);
469 tariffs->DelNotifierAdd(&addDelTariffNotifier);
470
471 users->DelNotifierUserDel(&delUserNotifier);
472 users->DelNotifierUserAdd(&addUserNotifier);
473
474 std::list<CHG_AFTER_NOTIFIER>::iterator it(notifiers.begin());
475 while (it != notifiers.end())
476     {
477     it->GetUserPtr()->GetProperty().tariffName.DelAfterNotifier(&(*it));
478     ++it;
479     }
480 notifiers.clear();
481 }