]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/other/smux/smux.cpp
Start replacing notifiers with subscriptions.
[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
19 #include "smux.h"
20 #include "utils.h"
21
22 namespace
23 {
24
25 bool SPrefixLess(const Sensors::value_type & a,
26                  const Sensors::value_type & b)
27 {
28 return a.first.PrefixLess(b.first);
29 }
30
31 }
32
33 extern "C" STG::Plugin* GetPlugin()
34 {
35     static SMUX plugin;
36     return &plugin;
37 }
38
39 SMUX_SETTINGS::SMUX_SETTINGS()
40     : ip(0),
41       port(0)
42 {}
43
44 int SMUX_SETTINGS::ParseSettings(const STG::ModuleSettings & s)
45 {
46 STG::ParamValue pv;
47 int p;
48
49 pv.param = "Port";
50 auto pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
51 if (pvi == s.moduleParams.end() || pvi->value.empty())
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) != 0)
58     {
59     errorStr = "Cannot parse parameter \'Port\': " + errorStr;
60     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
61     return -1;
62     }
63 port = static_cast<uint16_t>(p);
64
65 pv.param = "Password";
66 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
67 if (pvi == s.moduleParams.end() || pvi->value.empty())
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() || pvi->value.empty())
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     : users(nullptr),
93       tariffs(nullptr),
94       admins(nullptr),
95       services(nullptr),
96       corporations(nullptr),
97       traffcounter(nullptr),
98       stopped(true),
99       needReconnect(false),
100       lastReconnectTry(0),
101       reconnectTimeout(1),
102       sock(-1),
103       addDelTariffNotifier(*this),
104       logger(STG::PluginLogger::get("smux"))
105 {
106 smuxHandlers[SMUX_PDUs_PR_close] = &SMUX::CloseHandler;
107 smuxHandlers[SMUX_PDUs_PR_registerResponse] = &SMUX::RegisterResponseHandler;
108 smuxHandlers[SMUX_PDUs_PR_pdus] = &SMUX::PDUsRequestHandler;
109 smuxHandlers[SMUX_PDUs_PR_commitOrRollback] = &SMUX::CommitOrRollbackHandler;
110
111 pdusHandlers[PDUs_PR_get_request] = &SMUX::GetRequestHandler;
112 pdusHandlers[PDUs_PR_get_next_request] = &SMUX::GetNextRequestHandler;
113 pdusHandlers[PDUs_PR_set_request] = &SMUX::SetRequestHandler;
114 }
115
116 SMUX::~SMUX()
117 {
118     for (auto& kv : sensors)
119         delete kv.second;
120     for (auto& kv : tables)
121         delete kv.second;
122     printfd(__FILE__, "SMUX::~SMUX()\n");
123 }
124
125 int SMUX::ParseSettings()
126 {
127 return smuxSettings.ParseSettings(settings);
128 }
129
130 int SMUX::Start()
131 {
132 assert(users != nullptr && "users must not be NULL");
133 assert(tariffs != nullptr && "tariffs must not be NULL");
134 assert(admins != nullptr && "admins must not be NULL");
135 assert(services != nullptr && "services must not be NULL");
136 assert(corporations != nullptr && "corporations must not be NULL");
137 assert(traffcounter != nullptr && "traffcounter must not be NULL");
138
139 if (PrepareNet())
140     needReconnect = true;
141
142 // Users
143 sensors[OID(".1.3.6.1.4.1.38313.1.1.1")] = new TotalUsersSensor(*users);
144 sensors[OID(".1.3.6.1.4.1.38313.1.1.2")] = new ConnectedUsersSensor(*users);
145 sensors[OID(".1.3.6.1.4.1.38313.1.1.3")] = new AuthorizedUsersSensor(*users);
146 sensors[OID(".1.3.6.1.4.1.38313.1.1.4")] = new AlwaysOnlineUsersSensor(*users);
147 sensors[OID(".1.3.6.1.4.1.38313.1.1.5")] = new NoCashUsersSensor(*users);
148 sensors[OID(".1.3.6.1.4.1.38313.1.1.6")] = new DisabledDetailStatsUsersSensor(*users);
149 sensors[OID(".1.3.6.1.4.1.38313.1.1.7")] = new DisabledUsersSensor(*users);
150 sensors[OID(".1.3.6.1.4.1.38313.1.1.8")] = new PassiveUsersSensor(*users);
151 sensors[OID(".1.3.6.1.4.1.38313.1.1.9")] = new CreditUsersSensor(*users);
152 sensors[OID(".1.3.6.1.4.1.38313.1.1.10")] = new FreeMbUsersSensor(*users);
153 sensors[OID(".1.3.6.1.4.1.38313.1.1.11")] = new TariffChangeUsersSensor(*users);
154 sensors[OID(".1.3.6.1.4.1.38313.1.1.12")] = new ActiveUsersSensor(*users);
155 // Tariffs
156 sensors[OID(".1.3.6.1.4.1.38313.1.2.1")] = new TotalTariffsSensor(*tariffs);
157 // Admins
158 sensors[OID(".1.3.6.1.4.1.38313.1.3.1")] = new TotalAdminsSensor(*admins);
159 // Services
160 sensors[OID(".1.3.6.1.4.1.38313.1.4.1")] = new TotalServicesSensor(*services);
161 // Corporations
162 sensors[OID(".1.3.6.1.4.1.38313.1.5.1")] = new TotalCorporationsSensor(*corporations);
163 // Traffcounter
164 sensors[OID(".1.3.6.1.4.1.38313.1.6.1")] = new TotalRulesSensor(*traffcounter);
165
166 // Table data
167 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);
168
169 UpdateTables();
170 SetNotifiers();
171
172 #ifdef SMUX_DEBUG
173 auto it = sensors.begin();
174 while (it != sensors.end())
175     {
176     printfd(__FILE__, "%s = %s\n",
177             it->first.ToString().c_str(),
178             it->second->ToString().c_str());
179     ++it;
180     }
181 #endif
182
183 if (!m_thread.joinable())
184     m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
185
186 return 0;
187 }
188
189 int SMUX::Stop()
190 {
191 printfd(__FILE__, "SMUX::Stop() - Before\n");
192 m_thread.request_stop();
193
194 if (!stopped)
195     {
196     //5 seconds to thread stops itself
197     for (int i = 0; i < 25 && !stopped; i++)
198         {
199         struct timespec ts = {0, 200000000};
200         nanosleep(&ts, nullptr);
201         }
202     }
203
204 if (!stopped)
205     m_thread.detach();
206 else
207     m_thread.join();
208
209 ResetNotifiers();
210
211 for (auto& kv : sensors)
212     delete kv.second;
213 for (auto& kv : tables)
214     delete kv.second;
215
216 tables.erase(tables.begin(), tables.end());
217 sensors.erase(sensors.begin(), sensors.end());
218
219 close(sock);
220
221 if (!stopped)
222     {
223     return -1;
224     }
225
226 printfd(__FILE__, "SMUX::Stop() - After\n");
227 return 0;
228 }
229
230 int SMUX::Reload(const STG::ModuleSettings & /*ms*/)
231 {
232 if (Stop() != 0)
233     return -1;
234 if (Start() != 0)
235     return -1;
236 if (!needReconnect)
237     {
238     printfd(__FILE__, "SMUX reconnected succesfully.\n");
239     logger("Reconnected successfully.");
240     }
241 return 0;
242 }
243
244 void SMUX::Run(std::stop_token token)
245 {
246 stopped = true;
247 if (!SendOpenPDU(sock))
248     needReconnect = true;
249 if (!SendRReqPDU(sock))
250     needReconnect = true;
251 stopped = false;
252
253 while (!token.stop_requested())
254     {
255     if (WaitPackets(sock) && !needReconnect)
256         {
257         auto* pdus = RecvSMUXPDUs(sock);
258         if (pdus != nullptr)
259             {
260             DispatchPDUs(pdus);
261             ASN_STRUCT_FREE(asn_DEF_SMUX_PDUs, pdus);
262             }
263         else if (!token.stop_requested())
264             Reconnect();
265         }
266     else if (!token.stop_requested() && needReconnect)
267         Reconnect();
268     if (token.stop_requested())
269         break;
270     }
271 SendClosePDU(sock);
272 stopped = true;
273 }
274
275 bool SMUX::PrepareNet()
276 {
277 sock = socket(AF_INET, SOCK_STREAM, 0);
278
279 if (sock < 0)
280     {
281     errorStr = "Cannot create socket.";
282     logger("Cannot create a socket: %s", strerror(errno));
283     printfd(__FILE__, "Cannot create socket\n");
284     return true;
285     }
286
287 struct sockaddr_in addr;
288
289 addr.sin_family = AF_INET;
290 addr.sin_port = htons(smuxSettings.GetPort());
291 addr.sin_addr.s_addr = smuxSettings.GetIP();
292
293 if (connect(sock, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)) != 0)
294     {
295     errorStr = "Cannot connect.";
296     logger("Cannot connect the socket: %s", strerror(errno));
297     printfd(__FILE__, "Cannot connect. Message: '%s'\n", strerror(errno));
298     return true;
299     }
300
301 return false;
302 }
303
304 bool SMUX::Reconnect()
305 {
306 if (needReconnect && difftime(time(nullptr), lastReconnectTry) < reconnectTimeout)
307     return true;
308
309 time(&lastReconnectTry);
310 SendClosePDU(sock);
311 close(sock);
312 if (!PrepareNet())
313     if (SendOpenPDU(sock))
314         if (SendRReqPDU(sock))
315             {
316             reconnectTimeout = 1;
317             needReconnect = false;
318             logger("Connected successfully");
319             printfd(__FILE__, "Connected successfully\n");
320             return false;
321             }
322
323 if (needReconnect)
324     if (reconnectTimeout < 60)
325         reconnectTimeout *= 2;
326
327 needReconnect = true;
328 return true;
329 }
330
331 bool SMUX::DispatchPDUs(const SMUX_PDUs_t * pdus)
332 {
333 auto it = smuxHandlers.find(pdus->present);
334 if (it != smuxHandlers.end())
335     return (this->*(it->second))(pdus);
336 #ifdef SMUX_DEBUG
337 else
338     {
339     switch (pdus->present)
340         {
341         case SMUX_PDUs_PR_NOTHING:
342             printfd(__FILE__, "PDUs: nothing\n");
343             break;
344         case SMUX_PDUs_PR_open:
345             printfd(__FILE__, "PDUs: open\n");
346             break;
347         case SMUX_PDUs_PR_registerRequest:
348             printfd(__FILE__, "PDUs: registerRequest\n");
349             break;
350         default:
351             printfd(__FILE__, "PDUs: undefined\n");
352         }
353     asn_fprint(stderr, &asn_DEF_SMUX_PDUs, pdus);
354     }
355 #endif
356 return false;
357 }
358
359 bool SMUX::UpdateTables()
360 {
361 Sensors newSensors;
362 bool done = true;
363 auto it = tables.begin();
364 while (it != tables.end())
365     {
366     try
367         {
368         it->second->UpdateSensors(newSensors);
369         }
370     catch (const std::runtime_error & ex)
371         {
372         printfd(__FILE__,
373                 "SMUX::UpdateTables - failed to update table '%s': '%s'\n",
374                 it->first.c_str(), ex.what());
375         done = false;
376         break;
377         }
378     ++it;
379     }
380 if (!done)
381     {
382     auto sit = newSensors.begin();
383     while (sit != newSensors.end())
384         {
385         delete sit->second;
386         ++sit;
387         }
388     return false;
389     }
390
391 it = tables.begin();
392 while (it != tables.end())
393     {
394     auto res = std::equal_range(sensors.begin(),
395                                 sensors.end(),
396                                 std::pair<OID, Sensor *>(OID(it->first), nullptr),
397                                 SPrefixLess);
398     auto sit = res.first;
399     while (sit != res.second)
400         {
401         delete sit->second;
402         ++sit;
403         }
404     sensors.erase(res.first, res.second);
405     ++it;
406     }
407
408 sensors.insert(newSensors.begin(), newSensors.end());
409
410 return true;
411 }
412
413 void SMUX::SetNotifier(UserPtr userPtr)
414 {
415 notifiers.emplace_back(*this, userPtr);
416 userPtr->GetProperties().tariffName.AddAfterNotifier(&notifiers.back());
417 }
418
419 void SMUX::UnsetNotifier(UserPtr userPtr)
420 {
421 auto it = notifiers.begin();
422 while (it != notifiers.end())
423     {
424     if (it->GetUserPtr() == userPtr)
425         {
426         userPtr->GetProperties().tariffName.DelAfterNotifier(&(*it));
427         notifiers.erase(it);
428         break;
429         }
430     ++it;
431     }
432 }
433
434 void SMUX::SetNotifiers()
435 {
436 int h = users->OpenSearch();
437 assert(h && "USERS::OpenSearch is always correct");
438
439 UserPtr u;
440 while (users->SearchNext(h, &u) == 0)
441     SetNotifier(u);
442
443 users->CloseSearch(h);
444
445 m_onAddUserConn = users->onUserAdd([this](auto user){
446     SetNotifier(user);
447     UpdateTables();
448 });
449 m_onDelUserConn = users->onUserDel([this](auto user){
450     UnsetNotifier(user);
451     UpdateTables();
452 });
453
454 tariffs->AddNotifierAdd(&addDelTariffNotifier);
455 tariffs->AddNotifierDel(&addDelTariffNotifier);
456 }
457
458 void SMUX::ResetNotifiers()
459 {
460 tariffs->DelNotifierDel(&addDelTariffNotifier);
461 tariffs->DelNotifierAdd(&addDelTariffNotifier);
462
463 m_onAddUserConn.disconnect();
464 m_onDelUserConn.disconnect();
465
466 auto it = notifiers.begin();
467 while (it != notifiers.end())
468     {
469     it->GetUserPtr()->GetProperties().tariffName.DelAfterNotifier(&(*it));
470     ++it;
471     }
472 notifiers.clear();
473 }