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