/
dispatch.c
4373 lines (3854 loc) · 104 KB
/
dispatch.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* dispatcher module
*
* Copyright (C) 2004-2006 FhG Fokus
* Copyright (C) 2005 Voice-System.ro
* Copyright (C) 2015 Daniel-Constantin Mierla (asipto.com)
*
* This file is part of Kamailio, a free SIP server.
*
* Kamailio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version
*
* Kamailio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*! \file
* \ingroup dispatcher
* \brief Dispatcher :: Dispatch
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <math.h>
#include "../../core/ut.h"
#include "../../core/trim.h"
#include "../../core/dprint.h"
#include "../../core/action.h"
#include "../../core/route.h"
#include "../../core/dset.h"
#include "../../core/mem/shm_mem.h"
#include "../../core/parser/parse_uri.h"
#include "../../core/parser/parse_from.h"
#include "../../core/parser/parse_param.h"
#include "../../core/xavp.h"
#include "../../core/parser/digest/digest.h"
#include "../../core/resolve.h"
#include "../../core/lvalue.h"
#include "../../modules/tm/tm_load.h"
#include "../../lib/srdb1/db.h"
#include "../../lib/srdb1/db_res.h"
#include "../../core/str.h"
#include "../../core/script_cb.h"
#include "../../core/kemi.h"
#include "../../core/fmsg.h"
#include "ds_ht.h"
#include "api.h"
#include "dispatch.h"
#define DS_TABLE_VERSION 1
#define DS_TABLE_VERSION2 2
#define DS_TABLE_VERSION3 3
#define DS_TABLE_VERSION4 4
#define DS_ALG_HASHCALLID 0
#define DS_ALG_HASHFROMURI 1
#define DS_ALG_HASHTOURI 2
#define DS_ALG_HASHRURI 3
#define DS_ALG_ROUNDROBIN 4
#define DS_ALG_HASHAUTHUSER 5
#define DS_ALG_RANDOM 6
#define DS_ALG_HASHPV 7
#define DS_ALG_SERIAL 8
#define DS_ALG_WEIGHT 9
#define DS_ALG_CALLLOAD 10
#define DS_ALG_RELWEIGHT 11
#define DS_ALG_PARALLEL 12
#define DS_ALG_LATENCY 13
#define DS_HN_SIZE 256
#define DS_MATCHED_ADDR 1
#define DS_MATCHED_PORT (1 << 1)
#define DS_MATCHED_PROTO (1 << 2)
#define DS_MATCHED_SOCK (1 << 3)
/* increment call load */
#define DS_LOAD_INC(dgrp, didx) \
do { \
lock_get(&(dgrp)->lock); \
(dgrp)->dlist[didx].dload++; \
lock_release(&(dgrp)->lock); \
} while(0)
/* decrement call load */
#define DS_LOAD_DEC(dgrp, didx) \
do { \
lock_get(&(dgrp)->lock); \
if(likely((dgrp)->dlist[didx].dload > 0)) { \
(dgrp)->dlist[didx].dload--; \
} \
lock_release(&(dgrp)->lock); \
} while(0)
static int _ds_table_version = DS_TABLE_VERSION;
static ds_ht_t *_dsht_load = NULL;
static int *_ds_ping_active = NULL;
extern int ds_force_dst;
extern str ds_event_callback;
extern int ds_ping_latency_stats;
extern int ds_retain_latency_stats;
extern float ds_latency_estimator_alpha;
extern int ds_attrs_none;
extern param_t *ds_db_extra_attrs_list;
extern int ds_load_mode;
extern uint32_t ds_dns_mode;
extern int ds_dns_ttl;
static db_func_t ds_dbf;
static db1_con_t *ds_db_handle = NULL;
static ds_set_t **ds_lists = NULL;
static int *ds_list_nr = NULL;
static int *ds_crt_idx = NULL;
static int *ds_next_idx = NULL;
static ds_set_t *ds_strictest_node = NULL;
static int ds_strictest_idx;
static int ds_strictness;
#define _ds_list (ds_lists[*ds_crt_idx])
#define _ds_list_nr (*ds_list_nr)
static void ds_run_route(
struct sip_msg *msg, str *uri, char *route, ds_rctx_t *rctx);
void shuffle_uint100array(unsigned int *arr);
int ds_reinit_rweight_on_state_change(
int old_state, int new_state, ds_set_t *dset);
/**
*
*/
int ds_ping_active_init(void)
{
if(_ds_ping_active != NULL)
return 0;
_ds_ping_active = (int *)shm_malloc(sizeof(int));
if(_ds_ping_active == NULL) {
SHM_MEM_ERROR;
return -1;
}
*_ds_ping_active = 1;
return 0;
}
/**
*
*/
int ds_ping_active_get(void)
{
if(_ds_ping_active == NULL)
return -1;
return *_ds_ping_active;
}
/**
*
*/
int ds_ping_active_set(int v)
{
if(_ds_ping_active == NULL)
return -1;
*_ds_ping_active = v;
return 0;
}
/**
*
*/
int ds_hash_load_init(unsigned int htsize, int expire, int initexpire)
{
if(_dsht_load != NULL)
return 0;
_dsht_load = ds_ht_init(htsize, expire, initexpire);
if(_dsht_load == NULL)
return -1;
return 0;
}
/**
*
*/
int ds_hash_load_destroy(void)
{
if(_dsht_load == NULL)
return -1;
ds_ht_destroy(_dsht_load);
_dsht_load = NULL;
return 0;
}
/**
* Recursivly iterate over ds_set and execute callback
*/
void ds_iter_set(ds_set_t *node,
void (*ds_action_cb)(ds_set_t *node, int i, void *arg),
void *ds_action_arg)
{
int i;
if(!node)
return;
for(i = 0; i < 2; ++i)
ds_iter_set(node->next[i], ds_action_cb, ds_action_arg);
for(i = 0; i < node->nr; i++) {
ds_action_cb(node, i, ds_action_arg);
}
return;
}
void ds_log_dst_cb(ds_set_t *node, int i, void *arg)
{
LM_DBG("dst>> %d %.*s %d %d (%.*s,%d,%d,%d)\n", node->id,
node->dlist[i].uri.len, node->dlist[i].uri.s, node->dlist[i].flags,
node->dlist[i].priority, node->dlist[i].attrs.duid.len,
node->dlist[i].attrs.duid.s, node->dlist[i].attrs.maxload,
node->dlist[i].attrs.weight, node->dlist[i].attrs.rweight);
}
/**
* Recursivly print ds_set
*/
void ds_log_set(ds_set_t *node)
{
ds_iter_set(node, &ds_log_dst_cb, NULL);
return;
}
/**
*
*/
int ds_log_sets(void)
{
if(_ds_list == NULL)
return -1;
ds_log_set(_ds_list);
return 0;
}
/**
*
*/
int ds_init_data(void)
{
int *p;
ds_lists = (ds_set_t **)shm_malloc(2 * sizeof(ds_set_t *));
if(!ds_lists) {
SHM_MEM_ERROR;
return -1;
}
memset(ds_lists, 0, 2 * sizeof(ds_set_t *));
p = (int *)shm_malloc(3 * sizeof(int));
if(!p) {
shm_free(ds_lists);
SHM_MEM_ERROR;
return -1;
}
memset(p, 0, 3 * sizeof(int));
ds_crt_idx = p;
ds_next_idx = p + 1;
ds_list_nr = p + 2;
*ds_crt_idx = *ds_next_idx = 0;
return 0;
}
/**
*
*/
int ds_set_attrs(ds_dest_t *dest, str *vattrs)
{
param_t *params_list = NULL;
param_hooks_t phooks;
param_t *pit = NULL;
str param;
int tmp_ival = 0;
str sattrs;
if(vattrs == NULL || vattrs->len <= 0) {
if(ds_attrs_none == 0) {
return 0;
}
sattrs.s = "none=yes";
sattrs.len = 8;
} else {
sattrs = *vattrs;
}
if(sattrs.s[sattrs.len - 1] == ';')
sattrs.len--;
/* clone in shm */
dest->attrs.body.s = (char *)shm_malloc(sattrs.len + 1);
if(dest->attrs.body.s == NULL) {
SHM_MEM_ERROR;
return -1;
}
memcpy(dest->attrs.body.s, sattrs.s, sattrs.len);
dest->attrs.body.s[sattrs.len] = '\0';
dest->attrs.body.len = sattrs.len;
param = dest->attrs.body;
if(parse_params(¶m, CLASS_ANY, &phooks, ¶ms_list) < 0)
return -1;
for(pit = params_list; pit; pit = pit->next) {
if(pit->name.len == 4 && strncasecmp(pit->name.s, "duid", 4) == 0) {
dest->attrs.duid = pit->body;
} else if(pit->name.len == 2
&& strncasecmp(pit->name.s, "cc", 2) == 0) {
str2sint(&pit->body, &dest->attrs.congestion_control);
} else if(pit->name.len == 6
&& strncasecmp(pit->name.s, "weight", 6) == 0) {
tmp_ival = 0;
str2sint(&pit->body, &tmp_ival);
if(tmp_ival >= 1 && tmp_ival <= 100) {
dest->attrs.weight = tmp_ival;
} else {
dest->attrs.weight = 0;
LM_ERR("weight %d not in 1-100 range - ignoring destination\n",
tmp_ival);
}
} else if(pit->name.len == 7
&& strncasecmp(pit->name.s, "latency", 7) == 0) {
int initial_latency = 0;
if(str2sint(&pit->body, &initial_latency) == 0)
latency_stats_init(
&dest->latency_stats, initial_latency, 10000);
} else if(pit->name.len == 7
&& strncasecmp(pit->name.s, "maxload", 7) == 0) {
str2sint(&pit->body, &dest->attrs.maxload);
} else if(pit->name.len == 6
&& strncasecmp(pit->name.s, "socket", 6) == 0) {
dest->attrs.socket = pit->body;
} else if(pit->name.len == 8
&& strncasecmp(pit->name.s, "sockname", 8) == 0) {
dest->attrs.sockname = pit->body;
} else if(pit->name.len == 7
&& strncasecmp(pit->name.s, "rweight", 7) == 0) {
tmp_ival = 0;
str2sint(&pit->body, &tmp_ival);
if(tmp_ival >= 1 && tmp_ival <= 100) {
dest->attrs.rweight = tmp_ival;
} else {
dest->attrs.rweight = 0;
LM_WARN("rweight %d not in 1-100 range - ignoring\n", tmp_ival);
}
} else if(pit->name.len == 9
&& strncasecmp(pit->name.s, "ping_from", 9) == 0) {
dest->attrs.ping_from = pit->body;
} else if(pit->name.len == 7
&& strncasecmp(pit->name.s, "obproxy", 7) == 0) {
dest->attrs.obproxy = pit->body;
}
}
if(params_list)
free_params(params_list);
return 0;
}
/**
*
*/
ds_dest_t *pack_dest(str iuri, int flags, int priority, str *attrs, int dload)
{
ds_dest_t *dp = NULL;
/* For DNS-Lookups */
char hn[DS_HN_SIZE];
char ub[512];
struct hostent *he;
struct sip_uri puri;
str host;
int port, proto;
char c = 0;
str uri;
unsigned short sport = 0;
char sproto = PROTO_NONE;
uri = iuri;
/* check uri */
if(parse_uri(uri.s, uri.len, &puri) != 0) {
if(iuri.len > 4 && strncmp(iuri.s, "sip:", 4) != 0 && iuri.len < 500) {
memcpy(ub, "sip:", 4);
memcpy(ub + 4, iuri.s, iuri.len);
ub[iuri.len + 4] = '\0';
uri.s = ub;
uri.len = iuri.len + 4;
if(parse_uri(uri.s, uri.len, &puri) != 0) {
LM_ERR("bad uri [%.*s]\n", iuri.len, iuri.s);
goto err;
} else {
LM_INFO("uri without sip scheme - fixing it: %.*s\n", iuri.len,
iuri.s);
}
} else {
LM_ERR("bad uri [%.*s]\n", iuri.len, iuri.s);
goto err;
}
}
if(puri.host.len > (DS_HN_SIZE - 2)) {
LM_ERR("hostname in uri is too long [%.*s]\n", uri.len, uri.s);
goto err;
}
/* skip IPv6 references if IPv6 lookups are disabled */
if(default_core_cfg.dns_try_ipv6 == 0 && puri.host.s[0] == '['
&& puri.host.s[puri.host.len - 1] == ']') {
LM_DBG("skipping IPv6 record %.*s\n", puri.host.len, puri.host.s);
return NULL;
}
/* store uri */
dp = (ds_dest_t *)shm_malloc(sizeof(ds_dest_t));
if(dp == NULL) {
SHM_MEM_ERROR;
goto err;
}
memset(dp, 0, sizeof(ds_dest_t));
dp->uri.s = (char *)shm_malloc((uri.len + 1) * sizeof(char));
if(dp->uri.s == NULL) {
SHM_MEM_ERROR;
goto err;
}
strncpy(dp->uri.s, uri.s, uri.len);
dp->uri.s[uri.len] = '\0';
dp->uri.len = uri.len;
dp->flags = flags;
dp->priority = priority;
dp->dload = dload;
if(ds_set_attrs(dp, attrs) < 0) {
LM_ERR("cannot set attributes!\n");
goto err;
}
/* set send socket by name or address */
if(dp->attrs.sockname.s && dp->attrs.sockname.len > 0) {
dp->sock = ksr_get_socket_by_name(&dp->attrs.sockname);
if(dp->sock == 0) {
LM_ERR("non-local socket name <%.*s>\n", dp->attrs.sockname.len,
dp->attrs.sockname.s);
goto err;
}
} else if(dp->attrs.socket.s && dp->attrs.socket.len > 0) {
/* parse_phostport(...) expects 0-terminated string
* - after socket parameter is either ';' or '\0' */
STR_VTOZ(dp->attrs.socket.s[dp->attrs.socket.len], c);
if(parse_phostport(
dp->attrs.socket.s, &host.s, &host.len, &port, &proto)
!= 0) {
LM_ERR("bad socket <%.*s>\n", dp->attrs.socket.len,
dp->attrs.socket.s);
STR_ZTOV(dp->attrs.socket.s[dp->attrs.socket.len], c);
goto err;
}
STR_ZTOV(dp->attrs.socket.s[dp->attrs.socket.len], c);
dp->sock = grep_sock_info(&host, (unsigned short)port, proto);
if(dp->sock == 0) {
LM_ERR("non-local socket <%.*s>\n", dp->attrs.socket.len,
dp->attrs.socket.s);
goto err;
}
} else if(ds_default_sockinfo) {
dp->sock = ds_default_sockinfo;
}
dp->host.s = dp->uri.s + (puri.host.s - uri.s);
dp->host.len = puri.host.len;
/* Copy the port out of the URI */
dp->port = puri.port_no;
/* Copy the proto out of the URI */
dp->proto = puri.proto;
/* Do a DNS-Lookup for the Host-Name, if not disabled via dst flags */
if(dp->flags & DS_NODNSARES_DST) {
dp->irmode |= DS_IRMODE_NOIPADDR;
} else if(ds_dns_mode & (DS_DNS_MODE_INIT | DS_DNS_MODE_TIMER)) {
dns_set_local_ttl(ds_dns_ttl);
if(ds_dns_mode & DS_DNS_MODE_QSRV) {
sport = dp->port;
sproto = (char)dp->proto;
he = sip_resolvehost(&dp->host, &sport, &sproto);
if(he != 0) {
if(sport != 0) {
dp->port = sport;
}
if(sproto != PROTO_NONE) {
dp->proto = sproto;
}
}
} else {
/* The Hostname needs to be \0 terminated for resolvehost, so we
* make a copy here. */
strncpy(hn, puri.host.s, puri.host.len);
hn[puri.host.len] = '\0';
he = resolvehost(hn);
}
dns_set_local_ttl(0);
if(he == 0) {
LM_ERR("could not resolve %.*s (missing no-probing flag?!?)\n",
puri.host.len, puri.host.s);
goto err;
} else {
/* Store hostent in the dispatcher structure */
hostent2ip_addr(&dp->ip_address, he, 0);
}
}
return dp;
err:
if(dp != NULL) {
if(dp->uri.s != NULL)
shm_free(dp->uri.s);
if(dp->attrs.body.s != NULL)
shm_free(dp->attrs.body.s);
shm_free(dp);
}
return NULL;
}
/**
*
*/
int add_dest2list(int id, str uri, int flags, int priority, str *attrs,
int list_idx, int *setn, int dload, ds_latency_stats_t *latency_stats)
{
ds_dest_t *dp = NULL;
ds_set_t *sp = NULL;
ds_dest_t *dp0 = NULL;
ds_dest_t *dp1 = NULL;
dp = pack_dest(uri, flags, priority, attrs, dload);
if(!dp)
goto err;
if(latency_stats != NULL) {
dp->latency_stats.stdev = latency_stats->stdev;
dp->latency_stats.m2 = latency_stats->m2;
dp->latency_stats.max = latency_stats->max;
dp->latency_stats.min = latency_stats->min;
dp->latency_stats.average = latency_stats->average;
dp->latency_stats.estimate = latency_stats->estimate;
dp->latency_stats.count = latency_stats->count;
dp->latency_stats.timeout = latency_stats->timeout;
}
sp = ds_avl_insert(&ds_lists[list_idx], id, setn);
if(!sp) {
LM_ERR("no more memory.\n");
goto err;
}
sp->nr++;
if(sp->dlist == NULL) {
sp->dlist = dp;
} else {
dp1 = NULL;
dp0 = sp->dlist;
/* highest priority last -> reindex will copy backwards */
while(dp0) {
if(dp0->priority > dp->priority)
break;
dp1 = dp0;
dp0 = dp0->next;
}
if(dp1 == NULL) {
dp->next = sp->dlist;
sp->dlist = dp;
} else {
dp->next = dp1->next;
dp1->next = dp;
}
}
LM_DBG("dest [%d/%d] <%.*s>\n", sp->id, sp->nr, dp->uri.len, dp->uri.s);
return 0;
err:
if(dp != NULL) {
if(dp->uri.s != NULL)
shm_free(dp->uri.s);
if(dp->attrs.body.s != NULL)
shm_free(dp->attrs.body.s);
shm_free(dp);
}
return -1;
}
/* for internal usage; arr must be arr[100] */
void shuffle_uint100array(unsigned int *arr)
{
int k;
int j;
unsigned int t;
if(arr == NULL)
return;
for(j = 0; j < 100; j++) {
k = j + (kam_rand() % (100 - j));
t = arr[j];
arr[j] = arr[k];
arr[k] = t;
}
}
/**
* Initialize the relative weight distribution for a destination set
* - fill the array of 0..99 elements where to keep the index of the
* destination address to be used. The Nth call will use
* the address with the index at possition N%100
*/
int dp_init_relative_weights(ds_set_t *dset)
{
int j;
int k;
int t;
int *ds_dests_flags = NULL;
int *ds_dests_rweights = NULL;
int current_slice;
int rw_sum;
unsigned int last_insert;
if(dset == NULL || dset->dlist == NULL || dset->nr < 2)
return -1;
/* local copy to avoid synchronization problems */
ds_dests_flags = pkg_malloc(sizeof(int) * dset->nr);
if(ds_dests_flags == NULL) {
PKG_MEM_ERROR;
return -1;
}
ds_dests_rweights = pkg_malloc(sizeof(int) * dset->nr);
if(ds_dests_rweights == NULL) {
PKG_MEM_ERROR;
pkg_free(ds_dests_flags);
return -1;
}
/* needed to sync the rwlist access */
lock_get(&dset->lock);
rw_sum = 0;
/* find the sum of relative weights */
for(j = 0; j < dset->nr; j++) {
ds_dests_flags[j] = dset->dlist[j].flags;
ds_dests_rweights[j] = dset->dlist[j].attrs.rweight;
if(ds_skip_dst(ds_dests_flags[j]))
continue;
rw_sum += ds_dests_rweights[j];
}
if(rw_sum == 0)
goto ret;
/* fill the array based on the relative weight of each destination */
t = 0;
for(j = 0; j < dset->nr; j++) {
if(ds_skip_dst(ds_dests_flags[j]))
continue;
current_slice = ds_dests_rweights[j] * 100 / rw_sum; /* truncate here */
LM_DBG("rw_sum[%d][%d][%d]\n", j, rw_sum, current_slice);
for(k = 0; k < current_slice; k++) {
dset->rwlist[t] = (unsigned int)j;
t++;
}
}
/* if the array was not completely filled (i.e., the sum of rweights is
* less than 100 due to truncated), then use last address to fill the rest */
last_insert = t > 0 ? dset->rwlist[t - 1] : (unsigned int)(dset->nr - 1);
if(t < 100) {
LM_INFO("extra rweight %d for last active destination in group %d\n",
(100 - t), dset->id);
}
for(j = t; j < 100; j++)
dset->rwlist[j] = last_insert;
/* shuffle the content of the array in order to mix the selection
* of the addresses (e.g., if first address has weight=20, avoid
* sending first 20 calls to it, but ensure that within a 100 calls,
* 20 go to first address */
shuffle_uint100array(dset->rwlist);
goto ret;
ret:
lock_release(&dset->lock);
pkg_free(ds_dests_flags);
pkg_free(ds_dests_rweights);
return 0;
}
/**
* Initialize the weight distribution for a destination set
* - fill the array of 0..99 elements where to keep the index of the
* destination address to be used. The Nth call will use
* the address with the index at possition N%100
*/
int dp_init_weights(ds_set_t *dset)
{
int j;
int k;
int t;
if(dset == NULL || dset->dlist == NULL)
return -1;
/* is weight set for dst list? (first address must have weight!=0) */
if(dset->dlist[0].attrs.weight == 0)
return 0;
/* first fill the array based on the weight of each destination
* - the weight is the percentage (e.g., if weight=20, the afferent
* address gets its index 20 times in the array)
* - if the sum of weights is more than 100, the addresses over the
* limit are ignored */
t = 0;
for(j = 0; j < dset->nr; j++) {
for(k = 0; k < dset->dlist[j].attrs.weight; k++) {
if(t >= 100)
goto randomize;
dset->wlist[t] = (unsigned int)j;
t++;
}
}
/* if the array was not completely filled (i.e., the sum of weights is
* less than 100), then use last address to fill the rest */
if(t < 100) {
LM_INFO("extra weight %d for last destination in group %d\n", (100 - t),
dset->id);
}
for(; t < 100; t++)
dset->wlist[t] = (unsigned int)(dset->nr - 1);
randomize:
/* shuffle the content of the array in order to mix the selection
* of the addresses (e.g., if first address has weight=20, avoid
* sending first 20 calls to it, but ensure that within a 100 calls,
* 20 go to first address */
shuffle_uint100array(dset->wlist);
return 0;
}
/*! \brief compact destinations from sets for fast access */
int reindex_dests(ds_set_t *node)
{
int i = 0;
int j = 0;
if(!node)
return 0;
for(; i < 2; ++i) {
int rc = reindex_dests(node->next[i]);
if(rc != 0)
return rc;
}
ds_dest_t *dp = NULL, *dp0 = NULL;
dp0 = (ds_dest_t *)shm_malloc(node->nr * sizeof(ds_dest_t));
if(dp0 == NULL) {
SHM_MEM_ERROR;
goto err1;
}
memset(dp0, 0, node->nr * sizeof(ds_dest_t));
/* copy from the old pointer to destination, and then free it */
for(j = node->nr - 1; j >= 0 && node->dlist != NULL; j--) {
memcpy(&dp0[j], node->dlist, sizeof(ds_dest_t));
if(j == node->nr - 1)
dp0[j].next = NULL;
else
dp0[j].next = &dp0[j + 1];
dp = node->dlist;
node->dlist = dp->next;
shm_free(dp);
dp = NULL;
}
node->dlist = dp0;
dp_init_weights(node);
dp_init_relative_weights(node);
return 0;
err1:
return -1;
}
/*! \brief load groups of destinations from file */
int ds_load_list(char *lfile)
{
char line[1024], *p;
FILE *f = NULL;
int id, setn, flags, priority;
str uri;
str attrs;
ds_latency_stats_t *latency_stats;
if((*ds_crt_idx) != (*ds_next_idx)) {
LM_WARN("load command already generated, aborting reload...\n");
return 0;
}
if(lfile == NULL || strlen(lfile) <= 0) {
LM_ERR("bad list file\n");
return -1;
}
f = fopen(lfile, "r");
if(f == NULL) {
LM_ERR("can't open list file [%s]\n", lfile);
return -1;
}
id = setn = flags = priority = 0;
*ds_next_idx = (*ds_crt_idx + 1) % 2;
ds_avl_destroy(&ds_lists[*ds_next_idx]);
p = fgets(line, 1024, f);
while(p) {
/* eat all white spaces */
while(*p && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n'))
p++;
if(*p == '\0' || *p == '#')
goto next_line;
/* get set id */
id = 0;
while(*p >= '0' && *p <= '9') {
id = id * 10 + (*p - '0');
p++;
}
/* eat all white spaces */
while(*p && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n'))
p++;
if(*p == '\0' || *p == '#') {
LM_ERR("bad line [%s]\n", line);
goto error;
}
/* get uri */
uri.s = p;
while(*p && *p != ' ' && *p != '\t' && *p != '\r' && *p != '\n'
&& *p != '#')
p++;
uri.len = p - uri.s;
/* eat all white spaces */
while(*p && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n'))
p++;
/* get flags */
flags = 0;
priority = 0;
attrs.s = 0;
attrs.len = 0;
if(*p == '\0' || *p == '#')
goto add_destination; /* no flags given */
while(*p >= '0' && *p <= '9') {
flags = flags * 10 + (*p - '0');
p++;
}
/* eat all white spaces */
while(*p && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n'))
p++;
/* get priority */
if(*p == '\0' || *p == '#')
goto add_destination; /* no priority given */
while(*p >= '0' && *p <= '9') {
priority = priority * 10 + (*p - '0');
p++;
}
/* eat all white spaces */
while(*p && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n'))
p++;
if(*p == '\0' || *p == '#')
goto add_destination; /* no attrs given */
/* get attributes */
attrs.s = p;
while(*p && *p != ' ' && *p != '\t' && *p != '\r' && *p != '\n')
p++;
attrs.len = p - attrs.s;
add_destination:
latency_stats = NULL;
if(ds_ping_latency_stats && ds_retain_latency_stats) {
latency_stats = latency_stats_find(id, &uri);
}
if(add_dest2list(id, uri, flags, priority, &attrs, *ds_next_idx, &setn,
0, latency_stats)
!= 0) {
LM_WARN("unable to add destination %.*s to set %d -- skipping\n",
uri.len, uri.s, id);
if(ds_load_mode == 1) {
goto error;
}
}
next_line:
p = fgets(line, 1024, f);
}
if(reindex_dests(ds_lists[*ds_next_idx]) != 0) {
LM_ERR("error on reindex\n");
goto error;
}
fclose(f);
f = NULL;
/* Update list - should it be sync'ed? */
_ds_list_nr = setn;
*ds_crt_idx = *ds_next_idx;
LM_DBG("found [%d] dest sets\n", _ds_list_nr);
ds_log_sets();
return 0;
error:
if(f != NULL)
fclose(f);
ds_avl_destroy(&ds_lists[*ds_next_idx]);
*ds_next_idx = *ds_crt_idx;
return -1;
}
/**
*
*/
int ds_connect_db(void)
{
if(ds_db_url.s == NULL)
return -1;
if((ds_db_handle = ds_dbf.init(&ds_db_url)) == 0) {
LM_ERR("cannot initialize db connection\n");
return -1;
}
return 0;
}
/**
*
*/
void ds_disconnect_db(void)
{
if(ds_db_handle) {
ds_dbf.close(ds_db_handle);
ds_db_handle = 0;
}
}
/*! \brief Initialize and verify DB stuff*/
int ds_init_db(void)
{