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