-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmediator.c
489 lines (409 loc) · 14.9 KB
/
mediator.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <systemd/sd-daemon.h>
#include "mediator.h"
#include "config.h"
#include "daemonizer.h"
#include "medmysql.h"
#include "medredis.h"
#include "cdr.h"
#include "records.h"
sig_atomic_t mediator_shutdown = 0;
int mediator_lockfd = -1;
uint64_t mediator_count = 0;
static time_t next_intermediate_run = 0;
GHashTable *med_peer_ip_table = NULL;
GHashTable *med_peer_host_table = NULL;
GHashTable *med_peer_id_table = NULL;
GHashTable *med_uuid_cache = NULL;
GHashTable *med_call_stat_info_table = NULL;
GHashTable *med_cdr_tag_table = NULL;
static void med_free_cache_entry(void *p)
{
med_cache_entry_t *e = p;
g_free(e->str_value);
g_slice_free1(sizeof(*e), e);
}
void med_entry_free(void *p) {
med_entry_t *e = p;
g_free(e->callid);
g_free(e->dst_leg);
g_free(e->src_leg);
g_free(e->acc_ref);
json_object_put(e->dst_leg_json);
json_object_put(e->src_leg_json);
g_slice_free1(sizeof(*e), e);
}
/**********************************************************************/
static void mediator_create_caches(void)
{
med_uuid_cache = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, med_free_cache_entry);
}
static int mediator_load_maps(void)
{
med_peer_ip_table = g_hash_table_new_full(g_str_hash, g_str_equal, free, free);
med_peer_host_table = g_hash_table_new_full(g_str_hash, g_str_equal, free, free);
med_peer_id_table = g_hash_table_new_full(g_str_hash, g_str_equal, free, free);
med_cdr_tag_table = g_hash_table_new_full(g_str_hash, g_str_equal, free, NULL);
if(medmysql_load_maps(med_peer_ip_table, med_peer_host_table, med_peer_id_table))
return -1;
if (medmysql_load_db_ids())
return -1;
if (medmysql_load_cdr_tag_ids(med_cdr_tag_table))
return -1;
return 0;
}
/**********************************************************************/
static void mediator_print_mapentry(gpointer key, gpointer value, gpointer d __attribute__((unused)))
{
L_DEBUG("\t'%s' -> %s", (char*)key, (char*)value);
}
/**********************************************************************/
static void mediator_destroy_caches(void)
{
g_hash_table_destroy(med_uuid_cache);
med_uuid_cache = NULL;
}
static void mediator_cleanup_caches(void)
{
medmysql_cache_cleanup(med_uuid_cache);
}
static void mediator_destroy_maps(void)
{
if(med_peer_ip_table)
g_hash_table_destroy(med_peer_ip_table);
if(med_peer_host_table)
g_hash_table_destroy(med_peer_host_table);
if(med_peer_id_table)
g_hash_table_destroy(med_peer_id_table);
if(med_call_stat_info_table)
g_hash_table_destroy(med_call_stat_info_table);
if(med_cdr_tag_table)
g_hash_table_destroy(med_cdr_tag_table);
med_peer_ip_table = NULL;
med_peer_host_table = NULL;
med_peer_id_table = NULL;
med_call_stat_info_table = NULL;
med_cdr_tag_table = NULL;
}
/**********************************************************************/
static void mediator_print_maps(void)
{
L_DEBUG("Peer IP map:");
g_hash_table_foreach(med_peer_ip_table, mediator_print_mapentry, NULL);
L_DEBUG("Peer host map:");
g_hash_table_foreach(med_peer_host_table, mediator_print_mapentry, NULL);
L_DEBUG("Peer ID map:");
g_hash_table_foreach(med_peer_id_table, mediator_print_mapentry, NULL);
L_DEBUG("TAGS map:");
g_hash_table_foreach(med_cdr_tag_table, mediator_print_mapentry, NULL);
}
/**********************************************************************/
static void mediator_unlock(void)
{
L_DEBUG("Unlocking mediator.");
if(mediator_lockfd != -1)
{
flock(mediator_lockfd, LOCK_UN);
}
}
/**********************************************************************/
static void mediator_exit(void)
{
mediator_unlock();
config_cleanup();
closelog();
}
/**********************************************************************/
static void mediator_signal(int signal)
{
if(signal == SIGTERM || signal == SIGINT)
mediator_shutdown = 1;
}
/**********************************************************************/
static int mediator_lock(void)
{
struct stat sb;
mediator_lockfd = open(MEDIATOR_LOCK_FILE, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR);
if(mediator_lockfd == -1)
{
L_CRITICAL("Error creating lock file: %s", strerror(errno));
return -1;
}
if(flock(mediator_lockfd, LOCK_EX|LOCK_NB) == -1)
{
L_CRITICAL("Error locking lock file: %s", strerror(errno));
return -1;
}
if (fstat(mediator_lockfd, &sb)) {
L_CRITICAL("Error getting file stats for lock file: %m");
return -1;
}
if (sb.st_size) {
L_CRITICAL("Non-empty lock file '%s' detected, refusing to start. Examine its contents to learn about the cause, and then delete it to clear the error", MEDIATOR_LOCK_FILE);
return -1;
}
return 0;
}
/**********************************************************************/
static uint64_t mediator_calc_runtime(struct timeval *tv_start, struct timeval *tv_stop)
{
return ((uint64_t)((tv_stop->tv_sec * 1000000 + tv_stop->tv_usec) -
(tv_start->tv_sec * 1000000 + tv_start->tv_usec)));
}
/**********************************************************************/
int main(int argc, char **argv)
{
GQueue mysql_callids = G_QUEUE_INIT;
GQueue redis_callids = G_QUEUE_INIT;
GQueue acc_records = G_QUEUE_INIT;
uint64_t cdr_count, last_count;
int maprefresh;
struct medmysql_batches *batches;
struct timeval loop_tv_start, loop_tv_stop;
uint64_t loop_runtime;
#ifdef WITH_TIME_CALC
struct timeval tv_start, tv_stop;
uint64_t runtime;
#endif
gboolean success;
openlog(MEDIATOR_SYSLOG_NAME, LOG_PID|LOG_NDELAY, LOG_DAEMON);
atexit(mediator_exit);
signal(SIGCHLD, SIG_IGN);
signal(SIGTERM, mediator_signal);
signal(SIGINT, mediator_signal);
if (config_parse(argc, argv) == -1)
{
return -1;
}
L_NOTICE("Starting mediator\n");
L_DEBUG("Locking process.");
if(mediator_lock() != 0)
{
return -1;
}
if(config_daemonize)
{
L_DEBUG("Daemonizing process.");
if(daemonize() != 0)
{
return -1;
}
}
L_DEBUG("Writing pid file.");
if(write_pid(config_pid_path) != 0)
{
return -1;
}
if (config_maintenance) {
L_INFO("Maintenance mode active, going to sleep");
sd_notify(0, "READY=1\n");
while (!mediator_shutdown)
sleep(1);
exit(0);
}
L_INFO("ACC acc database host='%s', port='%d', user='%s', name='%s'",
config_med_host, config_med_port, config_med_user, config_med_db);
L_INFO("CDR acc database host='%s', port='%d', user='%s', name='%s'",
config_cdr_host, config_cdr_port, config_cdr_user, config_cdr_db);
L_INFO("PROV database host='%s', port='%d', user='%s', name='%s'",
config_prov_host, config_prov_port, config_prov_user, config_prov_db);
L_INFO("STATS database host='%s', port='%d', user='%s', name='%s'",
config_stats_host, config_stats_port, config_stats_user, config_stats_db);
L_INFO("REDIS database host='%s', port='%d', pass='%s', id='%d'",
config_redis_host, config_redis_port,
config_redis_pass ? config_redis_pass : "<none>",
config_redis_db);
L_DEBUG("Setting up mysql connections.");
if(medmysql_init() != 0)
{
return -1;
}
L_DEBUG("Setting up redis connections.");
if(medredis_init() != 0)
{
return -1;
}
L_NOTICE("Up and running, daemonized=%d, pid-path='%s', interval=%d",
config_daemonize, config_pid_path, config_interval);
sd_notify(0, "READY=1\n");
maprefresh = 0;
batches = malloc(sizeof(*batches));
if (!batches) {
L_ERROR("Out of memory allocating batches");
return -1;
}
mediator_create_caches();
while(!mediator_shutdown)
{
L_DEBUG("Starting mediation loop\n");
gettimeofday(&loop_tv_start, NULL);
if(maprefresh == 0)
{
mediator_destroy_maps();
if(mediator_load_maps() != 0)
{
break;
}
mediator_cleanup_caches();
maprefresh = 10;
}
--maprefresh;
if (0)
mediator_print_maps();
// process intermediate CDRs this round?
int do_intermediate = 0;
if (config_intermediate_interval > 0) {
if (loop_tv_start.tv_sec >= next_intermediate_run) {
L_DEBUG("Processing intermediate CDRs in this iteration\n");
do_intermediate = 1;
if (next_intermediate_run == 0)
next_intermediate_run = loop_tv_start.tv_sec;
next_intermediate_run += config_intermediate_interval;
}
}
g_queue_clear_full(&mysql_callids, g_free);
g_queue_clear_full(&redis_callids, g_free);
g_queue_clear_full(&acc_records, med_entry_free);
cdr_count = 0;
last_count = mediator_count;
success = medmysql_fetch_callids(&mysql_callids);
if(!success) {
L_ERROR("Failed to fetch callids from MySQL\n");
break;
}
success = medredis_fetch_callids(&redis_callids);
if (!success) {
L_ERROR("Failed to fetch callids from Redis\n");
break;
}
if (!mysql_callids.length && !redis_callids.length) {
L_DEBUG("No callids found, going idle\n");
goto idle;
}
if (medmysql_batch_start(batches)) {
L_ERROR("Failed to start MySQL batches\n");
break;
}
//////////////// mysql handling //////////////////
L_DEBUG("Processing %u mysql accounting record group(s).", mysql_callids.length);
for(GList *l = mysql_callids.head; l && !mediator_shutdown; l = l->next)
{
char *mysql_callid = l->data;
#ifdef WITH_TIME_CALC
gettimeofday(&tv_start, NULL);
#endif
int ret = medmysql_fetch_records(mysql_callid, &acc_records, 1, records_no_refer_bleg_bye, NULL);
if (ret < 0)
goto out;
int must_sort = (ret > 0);
ret = medredis_fetch_records(mysql_callid, &acc_records, records_no_refer_bleg_bye, NULL);
if (ret > 0)
must_sort = 1;
if (must_sort)
{
// only re-sort if records from Redis were added, as MySQL already does the sorting
records_sort(&acc_records);
}
int are_records_complete = records_complete(&acc_records);
if (!are_records_complete && !do_intermediate)
{
L_DEBUG("Found incomplete call with cid '%s', skipping...\n", mysql_callid);
g_queue_clear_full(&acc_records, med_entry_free);
continue;
}
if(cdr_process_records(&acc_records, &cdr_count, batches, do_intermediate) != 0)
goto out;
g_queue_clear_full(&acc_records, med_entry_free);
mediator_count += cdr_count;
#ifdef WITH_TIME_CALC
gettimeofday(&tv_stop, NULL);
runtime = mediator_calc_runtime(&tv_start, &tv_stop);
L_INFO("Runtime for mysql record group was %"PRIu64" us.", runtime);
L_INFO("CDR creation rate for mysql record group was %f CDR/sec", (double)mysql_callids.length/runtime * 1000000);
#endif
}
//////////////// redis handling //////////////////
L_DEBUG("Processing %u redis accounting record group(s).", redis_callids.length);
for(GList *l = redis_callids.head; l && !mediator_shutdown; l = l->next)
{
char *redis_callid = l->data;
#ifdef WITH_TIME_CALC
gettimeofday(&tv_start, NULL);
#endif
if(medredis_fetch_records(redis_callid, &acc_records, records_no_refer_bleg_bye, NULL) < 0)
goto out;
medmysql_fetch_records(redis_callid, &acc_records, 0, records_no_refer_bleg_bye, NULL);
// always sort records from Redis, regardless of whether records from MySQL were merged
records_sort(&acc_records);
int are_records_complete = records_complete(&acc_records);
if (!are_records_complete && !do_intermediate)
{
L_DEBUG("Found incomplete call with cid '%s', skipping...\n", redis_callid);
g_queue_clear_full(&acc_records, med_entry_free);
continue;
}
L_DEBUG("process cdr with cid '%s' and %u records\n", redis_callid, acc_records.length);
if (acc_records.length) {
if(cdr_process_records(&acc_records, &cdr_count, batches, do_intermediate) != 0) {
g_queue_clear_full(&acc_records, med_entry_free);
goto out;
}
g_queue_clear_full(&acc_records, med_entry_free);
mediator_count += cdr_count;
}
#ifdef WITH_TIME_CALC
gettimeofday(&tv_stop, NULL);
runtime = mediator_calc_runtime(&tv_start, &tv_stop);
L_INFO("Runtime for redis record group was %"PRIu64" us.", runtime);
L_INFO("CDR creation rate for redis record group was %f CDR/sec", (double)redis_callids.length/runtime * 1000000);
#endif
}
//////////////// end //////////////////
if (medmysql_batch_end(batches))
break;
if (medredis_batch_end())
break;
gettimeofday(&loop_tv_stop, NULL);
loop_runtime = mediator_calc_runtime(&loop_tv_start, &loop_tv_stop);
L_INFO("Runtime for loop processing %u callids and generating %"PRIu64" CDRs was %"PRIu64" us.",
mysql_callids.length + redis_callids.length, mediator_count - last_count, loop_runtime);
L_INFO("Total CDR creation rate %f CDR/sec", (double)(mediator_count - last_count)/loop_runtime * 1000000);
idle:
if(mediator_count > last_count)
{
L_DEBUG("Overall %"PRIu64" CDRs created so far.", mediator_count);
sleep(3);
}
else
{
/* sleep if no cdrs have been created */
sleep(config_interval);
}
}
out:
L_INFO("Shutting down.");
sd_notify(0, "STOPPING=1\n");
g_queue_clear_full(&acc_records, med_entry_free);
g_queue_clear_full(&mysql_callids, g_free);
g_queue_clear_full(&redis_callids, g_free);
mediator_destroy_maps();
mediator_destroy_caches();
medmysql_cleanup();
medredis_cleanup();
free(batches);
L_INFO("Successfully shut down.");
return 0;
}
void critical(const char *msg) {
write(mediator_lockfd, msg, strlen(msg));
write(mediator_lockfd, "\n", 1);
}