2 #include <sys/socket.h>
17 #include "stg/common.h"
23 using STG::SMUX_SETTINGS;
28 bool SPrefixLess(const Sensors::value_type & a,
29 const Sensors::value_type & b)
31 return a.first.PrefixLess(b.first);
36 extern "C" STG::Plugin* GetPlugin()
42 SMUX_SETTINGS::SMUX_SETTINGS()
47 int SMUX_SETTINGS::ParseSettings(const ModuleSettings & s)
53 auto pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
54 if (pvi == s.moduleParams.end() || pvi->value.empty())
56 errorStr = "Parameter \'Port\' not found.";
57 printfd(__FILE__, "Parameter 'Port' not found\n");
60 if (ParseIntInRange(pvi->value[0], 2, 65535, &p) != 0)
62 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
63 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
66 port = static_cast<uint16_t>(p);
68 pv.param = "Password";
69 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
70 if (pvi == s.moduleParams.end() || pvi->value.empty())
72 errorStr = "Parameter \'Password\' not found.";
73 printfd(__FILE__, "Parameter 'Password' not found\n");
78 password = pvi->value[0];
82 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
83 if (pvi == s.moduleParams.end() || pvi->value.empty())
85 errorStr = "Parameter \'Server\' not found.";
86 printfd(__FILE__, "Parameter 'Server' not found\n");
89 ip = inet_strington(pvi->value[0]);
99 corporations(nullptr),
100 traffcounter(nullptr),
102 needReconnect(false),
106 logger(PluginLogger::get("smux"))
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;
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;
120 for (auto& kv : sensors)
122 for (auto& kv : tables)
124 printfd(__FILE__, "SMUX::~SMUX()\n");
127 int SMUX::ParseSettings()
129 return smuxSettings.ParseSettings(settings);
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");
142 needReconnect = true;
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);
158 sensors[OID(".1.3.6.1.4.1.38313.1.2.1")] = new TotalTariffsSensor(*tariffs);
160 sensors[OID(".1.3.6.1.4.1.38313.1.3.1")] = new TotalAdminsSensor(*admins);
162 sensors[OID(".1.3.6.1.4.1.38313.1.4.1")] = new TotalServicesSensor(*services);
164 sensors[OID(".1.3.6.1.4.1.38313.1.5.1")] = new TotalCorporationsSensor(*corporations);
166 sensors[OID(".1.3.6.1.4.1.38313.1.6.1")] = new TotalRulesSensor(*traffcounter);
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);
175 auto it = sensors.begin();
176 while (it != sensors.end())
178 printfd(__FILE__, "%s = %s\n",
179 it->first.ToString().c_str(),
180 it->second->ToString().c_str());
185 if (!m_thread.joinable())
186 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
193 printfd(__FILE__, "SMUX::Stop() - Before\n");
194 m_thread.request_stop();
198 //5 seconds to thread stops itself
199 for (int i = 0; i < 25 && !stopped; i++)
201 struct timespec ts = {0, 200000000};
202 nanosleep(&ts, nullptr);
213 for (auto& kv : sensors)
215 for (auto& kv : tables)
218 tables.erase(tables.begin(), tables.end());
219 sensors.erase(sensors.begin(), sensors.end());
228 printfd(__FILE__, "SMUX::Stop() - After\n");
232 int SMUX::Reload(const ModuleSettings & /*ms*/)
240 printfd(__FILE__, "SMUX reconnected succesfully.\n");
241 logger("Reconnected successfully.");
246 void SMUX::Run(std::stop_token token)
249 if (!SendOpenPDU(sock))
250 needReconnect = true;
251 if (!SendRReqPDU(sock))
252 needReconnect = true;
255 while (!token.stop_requested())
257 if (WaitPackets(sock) && !needReconnect)
259 auto* pdus = RecvSMUXPDUs(sock);
263 ASN_STRUCT_FREE(asn_DEF_SMUX_PDUs, pdus);
265 else if (!token.stop_requested())
268 else if (!token.stop_requested() && needReconnect)
270 if (token.stop_requested())
277 bool SMUX::PrepareNet()
279 sock = socket(AF_INET, SOCK_STREAM, 0);
283 errorStr = "Cannot create socket.";
284 logger("Cannot create a socket: %s", strerror(errno));
285 printfd(__FILE__, "Cannot create socket\n");
289 struct sockaddr_in addr;
291 addr.sin_family = AF_INET;
292 addr.sin_port = htons(smuxSettings.GetPort());
293 addr.sin_addr.s_addr = smuxSettings.GetIP();
295 if (connect(sock, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)) != 0)
297 errorStr = "Cannot connect.";
298 logger("Cannot connect the socket: %s", strerror(errno));
299 printfd(__FILE__, "Cannot connect. Message: '%s'\n", strerror(errno));
306 bool SMUX::Reconnect()
308 if (needReconnect && difftime(time(nullptr), lastReconnectTry) < reconnectTimeout)
311 time(&lastReconnectTry);
315 if (SendOpenPDU(sock))
316 if (SendRReqPDU(sock))
318 reconnectTimeout = 1;
319 needReconnect = false;
320 logger("Connected successfully");
321 printfd(__FILE__, "Connected successfully\n");
326 if (reconnectTimeout < 60)
327 reconnectTimeout *= 2;
329 needReconnect = true;
333 bool SMUX::DispatchPDUs(const SMUX_PDUs_t * pdus)
335 auto it = smuxHandlers.find(pdus->present);
336 if (it != smuxHandlers.end())
337 return (this->*(it->second))(pdus);
341 switch (pdus->present)
343 case SMUX_PDUs_PR_NOTHING:
344 printfd(__FILE__, "PDUs: nothing\n");
346 case SMUX_PDUs_PR_open:
347 printfd(__FILE__, "PDUs: open\n");
349 case SMUX_PDUs_PR_registerRequest:
350 printfd(__FILE__, "PDUs: registerRequest\n");
353 printfd(__FILE__, "PDUs: undefined\n");
355 asn_fprint(stderr, &asn_DEF_SMUX_PDUs, pdus);
361 bool SMUX::UpdateTables()
365 auto it = tables.begin();
366 while (it != tables.end())
370 it->second->UpdateSensors(newSensors);
372 catch (const std::runtime_error & ex)
375 "SMUX::UpdateTables - failed to update table '%s': '%s'\n",
376 it->first.c_str(), ex.what());
384 auto sit = newSensors.begin();
385 while (sit != newSensors.end())
394 while (it != tables.end())
396 auto res = std::equal_range(sensors.begin(),
398 std::pair<OID, Sensor *>(OID(it->first), nullptr),
400 auto sit = res.first;
401 while (sit != res.second)
406 sensors.erase(res.first, res.second);
410 sensors.insert(newSensors.begin(), newSensors.end());
415 void SMUX::SetNotifier(UserPtr userPtr)
417 m_conns.emplace_back(
419 userPtr->GetProperties().tariffName.afterChange([this](const auto&, const auto&){ UpdateTables(); })
423 void SMUX::UnsetNotifier(UserPtr userPtr)
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(); }),
430 void SMUX::SetNotifiers()
432 int h = users->OpenSearch();
433 assert(h && "USERS::OpenSearch is always correct");
436 while (users->SearchNext(h, &u) == 0)
439 users->CloseSearch(h);
441 m_onAddUserConn = users->onAdd([this](auto user){
445 m_onDelUserConn = users->onDel([this](auto user){
450 auto updateTables = [this](const TariffData&){ UpdateTables(); };
451 m_onAddTariffConn = tariffs->onAdd(updateTables);
452 m_onDelTariffConn = tariffs->onDel(updateTables);
455 void SMUX::ResetNotifiers()
457 m_onAddTariffConn.disconnect();
458 m_onDelTariffConn.disconnect();
460 m_onAddUserConn.disconnect();
461 m_onDelUserConn.disconnect();