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