-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathres_config_mongodb.c
1497 lines (1348 loc) · 46 KB
/
res_config_mongodb.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
/*
* MongoDB configuration engine
*
* Copyright: (c) 2015-2016 KINOSHITA minoru
* License: GNU GENERAL PUBLIC LICENSE Version 2
*/
/*! \file
*
* \brief MongoDB configuration engine
*
* \author KINOSHITA minoru
*
* This is a realtime configuration engine for the MongoDB database
* \ingroup resources
*
* Depends on the MongoDB library - https://www.mongodb.org
*
*/
/*! \li \ref res_config_mongodb.c uses the configuration file \ref res_config_mongodb.conf
* \addtogroup configuration_file Configuration Files
*/
/*** MODULEINFO
<depend>res_mongodb</depend>
<depend>mongoc</depend>
<depend>bson</depend>
<support_level>extended</support_level>
***/
#include "asterisk.h"
#ifdef ASTERISK_REGISTER_FILE /* deprecated from 15.0.0 */
ASTERISK_REGISTER_FILE()
#endif
#include "asterisk/file.h"
#include "asterisk/channel.h"
#include "asterisk/pbx.h"
#include "asterisk/config.h"
#include "asterisk/module.h"
#include "asterisk/lock.h"
#include "asterisk/utils.h"
#include "asterisk/threadstorage.h"
#include "asterisk/res_mongodb.h"
#define HANDLE_ID_AS_OID 1
#define BSON_UTF8_VALIDATE(utf8,allow_null) \
bson_utf8_validate (utf8, (int) strlen (utf8), allow_null)
#define LOG_BSON_AS_JSON(level, fmt, bson, ...) { \
size_t length; \
char *str = bson_as_json(bson, &length); \
ast_log(level, fmt, str, ##__VA_ARGS__); \
bson_free(str); \
}
static const int MAXTOKENS = 3;
static const char NAME[] = "mongodb";
static const char CATEGORY[] = "config";
static const char CONFIG_FILE[] = "ast_mongo.conf";
static const char SERVERID[] = "serverid";
AST_MUTEX_DEFINE_STATIC(model_lock);
static mongoc_client_pool_t* dbpool = NULL;
static bson_t* models = NULL;
static bson_oid_t *serverid = NULL;
static void* apm_context = NULL;
static int apm_enabled = 0;
static int str_split(char* str, const char* delim, const char* tokens[] ) {
char* token;
char* saveptr;
int count = 0;
for(token = strtok_r(str, delim, &saveptr);
token && count < MAXTOKENS;
token = strtok_r(NULL, delim, &saveptr), count++)
{
tokens[count] = token;
}
return count;
}
static const char *key_mongo2asterisk(const char *key)
{
return strcmp(key, "_id") == 0 ? "id" : key;
}
static const char *key_asterisk2mongo(const char *key)
{
return strcmp(key, "id") == 0 ? "_id" : key;
}
/*!
* check if the specified string is integer
*
* \param[in] value
* \param[out] result
* \retval true if it's an integer
*/
static bool is_integer(const char* value, long long* result)
{
int len;
long long dummy;
long long* p = result ? result : &dummy;
if (sscanf(value, "%Ld%n", p, &len) == 0)
return false;
if (value[len] != '\0')
return false;
return true;
}
/*!
* check if the specified string is real number
*
* \param[in] value
* \param[out] result
* \retval true if it's a real number
*/
static bool is_real(const char* value, double* result)
{
int len;
double dummy;
double* p = result ? result : &dummy;
if (sscanf(value, "%lg%n", p, &len) == 0)
return false;
if (value[len] != '\0')
return false;
return true;
}
/*!
* check if the specified string is bool
*
* \param[in] value
* \param[out] result
* \retval true if it's a real number
*/
static bool is_bool(const char* value, bool* result) {
bool dummy;
bool* p = result ? result : &dummy;
if (strcmp(value, "true") == 0) {
*p = true;
return true;
}
if (strcmp(value, "false") == 0) {
*p = false;
return true;
}
return false;
}
/*!
* assume the specified src doesn't have any escaping letters for mongo such as \, ', ".
*
* \retval a pointer same as dst.
*/
static const char* strcopy(const char* src, char* dst, int size)
{
char* p = dst;
int escaping = 0;
int i;
for (i = 0; *src != '\0' && i < (size-1); ) {
int c = *src++;
if (escaping) {
*p++ = c;
++i;
escaping = 0;
}
else if (c == '%')
break;
else if (c == '\\')
escaping = 1;
else {
*p++ = c;
++i;
}
}
if (i == (size-1))
ast_log(LOG_WARNING, "size of dst is not enough.\n");
*p = '\0';
return (const char*)dst;
}
/*!
* \brief make a condition to query
* \param sql is pattern for sql
* \retval a bson to query as follows;
* sql patern generated bson to query
* ---------- --------------------------------------
* % { $exists: true, $not: { $size: 0} } }
* %patern% { $regex: "patern" }
* patern% { $regex: "^patern" }
* %patern { $regex: "patern$" }
* any other NULL
*/
static const bson_t* make_condition(const char* sql)
{
bson_t* condition = NULL;
char patern[1020];
char tmp[1024];
char head = *sql;
char tail = *(sql + strlen(sql) - 1);
if (strcmp(sql, "%") == 0) {
const char* json = "{ \"$exists\": true, \"$not\": {\"$size\": 0}}";
bson_error_t error;
condition = bson_new_from_json((const uint8_t*)json, -1, &error);
if (!condition)
ast_log(LOG_ERROR, "cannot generated condition from \"%s\", %d.%d:%s\n", json, error.domain, error.code, error.message);
}
else if (head == '%' && tail == '%') {
strcopy(sql+1, patern, sizeof(patern)-1);
snprintf(tmp, sizeof(tmp), "%s", patern);
condition = bson_new();
BSON_APPEND_UTF8(condition, "$regex", tmp);
}
else if (head == '%') {
strcopy(sql+1, patern, sizeof(patern)-1);
snprintf(tmp, sizeof(tmp), "%s$", patern);
condition = bson_new();
BSON_APPEND_UTF8(condition, "$regex", tmp);
}
else if (tail == '%') {
strcopy(sql, patern, sizeof(patern));
snprintf(tmp, sizeof(tmp), "^%s", patern);
condition = bson_new();
BSON_APPEND_UTF8(condition, "$regex", tmp);
}
else {
ast_log(LOG_WARNING, "not supported condition, \"%s\"\n", sql);
}
if (condition) {
// LOG_BSON_AS_JSON(LOG_DEBUG, "generated condition is \"%s\"\n", condition);
}
else
ast_log(LOG_WARNING, "no condition generated\n");
return (const bson_t*)condition;
}
/*!
* \brief make a query
* \param fields
* \param orderby
* \retval a bson object to query,
* \retval NULL if something wrong.
*/
static bson_t *make_query(const struct ast_variable *fields, const char *orderby)
{
bson_t *root = NULL;
bson_t *query = NULL;
bson_t *order = NULL;
do {
bool err;
query = serverid ? BCON_NEW(SERVERID, BCON_OID(serverid)) : bson_new();
order = orderby ? BCON_NEW(key_asterisk2mongo(orderby), BCON_DOUBLE(1)) : bson_new();
for(err = false; fields && !err; fields = fields->next) {
const bson_t *condition = NULL;
const char *tokens[MAXTOKENS];
char buf[1024];
int count;
long long ll_number;
if (strlen(fields->name) >= (sizeof(buf) - 1)) {
ast_log(LOG_WARNING, "too long key, \"%s\".\n", fields->name);
continue;
}
strcpy(buf, fields->name);
count = str_split(buf, " ", tokens);
err = true;
switch(count) {
case 1:
#ifdef HANDLE_ID_AS_OID
if ((strcmp(fields->name, "id") == 0)
&& bson_oid_is_valid(fields->value, strlen(fields->value))) {
bson_oid_t oid;
bson_oid_init_from_string(&oid, fields->value);
err = !BSON_APPEND_OID(query, "_id", &oid);
}
else
#endif
err = !BSON_APPEND_UTF8(query, key_asterisk2mongo(fields->name), fields->value);
break;
case 2:
if (!strcasecmp(tokens[1], "LIKE")) {
condition = make_condition(fields->value);
}
else if (!strcasecmp(tokens[1], "!=")) {
// {
// tokens[0]: {
// "$exists" : true,
// "$ne" : value
// }
// }
condition = BCON_NEW(
"$exists", BCON_BOOL(1),
"$ne", BCON_UTF8(fields->value)
);
}
else if (!strcasecmp(tokens[1], ">")) {
// {
// tokens[0]: {
// "$gt" : value
// }
// }
if (is_integer(fields->value, &ll_number))
condition = BCON_NEW("$gt", BCON_INT64(ll_number));
else
condition = BCON_NEW("$gt", BCON_UTF8(fields->value));
}
else if (!strcasecmp(tokens[1], "<=")) {
// {
// tokens[0]: {
// "$lte" : value
// }
// }
if (is_integer(fields->value, &ll_number))
condition = BCON_NEW("$lte", BCON_INT64(ll_number));
else
condition = BCON_NEW("$lte", BCON_UTF8(fields->value));
}
else {
ast_log(LOG_WARNING, "unexpected operator \"%s\" of \"%s\" \"%s\".\n", tokens[1], fields->name, fields->value);
break;
}
if (!condition) {
ast_log(LOG_ERROR, "something wrong.\n");
break;
}
err = !BSON_APPEND_DOCUMENT(query, key_asterisk2mongo(tokens[0]), condition);
break;
default:
ast_log(LOG_WARNING, "not handled, name=%s, value=%s.\n", fields->name, fields->value);
}
if (condition)
bson_destroy((bson_t*)condition);
else if (count > 1) {
ast_log(LOG_ERROR, "something wrong.\n");
break;
}
}
if (err) {
ast_log(LOG_ERROR, "something wrong.\n");
break;
}
root = BCON_NEW("$query", BCON_DOCUMENT(query),
"$orderby", BCON_DOCUMENT(order));
if (!root) { // current BCON_NEW might not return any error such as NULL...
ast_log(LOG_WARNING, "not enough memory\n");
break;
}
} while(0);
if (query)
bson_destroy(query);
if (order)
bson_destroy(order);
// if (root) {
// LOG_BSON_AS_JSON(LOG_DEBUG, "generated query is %s\n", root);
// }
return root;
}
/*!
* \brief check if the models library has specified collection.
* \param collection is name of model to be retrieved.
* \retval true if the library poses the specified collection or any error,
* \retval false if not exist.
*/
static bool model_check(const char* collection)
{
bson_iter_t iter;
return bson_iter_init(&iter, models) && bson_iter_find(&iter, collection);
}
/*!
* \param[in] model_name is name of model to be retrieved.
* \param[in] property
* \param[in] value
* \retval bson type
*/
static bson_type_t model_get_btype(const char* model_name, const char* property, const char* value)
{
bson_type_t btype = BSON_TYPE_UNDEFINED;
bson_iter_t iroot;
bson_iter_t imodel;
ast_mutex_lock(&model_lock);
do {
if (value) {
if (is_bool(value, NULL))
btype = BSON_TYPE_BOOL;
else if (is_real(value, NULL))
btype = BSON_TYPE_DOUBLE;
else
btype = BSON_TYPE_UTF8;
}
if (model_check(model_name) &&
bson_iter_init_find (&iroot, models, model_name) &&
BSON_ITER_HOLDS_DOCUMENT (&iroot) &&
bson_iter_recurse (&iroot, &imodel) &&
bson_iter_find(&imodel, property))
{
btype = (bson_type_t)bson_iter_as_int64(&imodel);
}
} while(0);
ast_mutex_unlock(&model_lock);
return btype;
}
static void model_register(const char *collection, const bson_t *model)
{
ast_mutex_lock(&model_lock);
do {
if (model_check(collection))
ast_log(LOG_DEBUG, "%s already registered\n", collection);
else if (!BSON_APPEND_DOCUMENT(models, collection, model))
ast_log(LOG_ERROR, "cannot register %s\n", collection);
else {
LOG_BSON_AS_JSON(LOG_DEBUG, "models is \"%s\"\n", models);
}
} while(0);
ast_mutex_unlock(&model_lock);
}
static bson_type_t rtype2btype (require_type rtype)
{
bson_type_t btype;
switch(rtype) {
case RQ_INTEGER1:
case RQ_UINTEGER1:
case RQ_INTEGER2:
case RQ_UINTEGER2:
case RQ_INTEGER3:
case RQ_UINTEGER3:
case RQ_INTEGER4:
case RQ_UINTEGER4:
case RQ_INTEGER8:
case RQ_UINTEGER8:
case RQ_FLOAT:
btype = BSON_TYPE_DOUBLE;
break;
case RQ_DATE:
case RQ_DATETIME:
case RQ_CHAR:
btype = BSON_TYPE_UTF8;
break;
default:
ast_log(LOG_ERROR, "unexpected require type %d\n", rtype);
btype = BSON_TYPE_UNDEFINED;
}
return btype;
}
/*!
* Make a document from key-value list
*
* \param[in] table
* \param[in] fields
* \param[out] doc
* \retval true if success
*/
static bool fields2doc(const char* table, const struct ast_variable *fields, bson_t *doc)
{
bool err;
const char* key;
for (err = false; fields && !err; fields = fields->next) {
bson_type_t btype;
if (strlen(fields->value) == 0)
continue;
key = key_asterisk2mongo(fields->name);
btype = model_get_btype(table, key, fields->value);
switch(btype) {
case BSON_TYPE_UTF8:
err = !BSON_APPEND_UTF8(doc, key, fields->value);
break;
case BSON_TYPE_BOOL:
err = !BSON_APPEND_BOOL(doc, key,
strcmp(fields->value, "true") ? false : true);
break;
case BSON_TYPE_INT32:
err = !BSON_APPEND_INT32(doc, key, atol(fields->value));
break;
case BSON_TYPE_INT64:
err = !BSON_APPEND_INT64(doc, key, atoll(fields->value));
break;
case BSON_TYPE_DOUBLE:
err = !BSON_APPEND_DOUBLE(doc, key, atof(fields->value));
break;
default:
ast_log(LOG_WARNING, "unexpected data type: key=%s, value=%s\n", key, fields->value);
break;
}
}
return !err;
}
/*!
* Get a value from a document
*
* \param[in,out] iter is a bson iterator of a document
* \param[out] key is stored pointer to key name of value
* \param[out] value is a buffer to be stored a string of value
* \param[in] size is size of buffer for value
* \retval true if value is valid.
*/
static bool doc2value(bson_iter_t* iter, const char** key, char value[], int size)
{
if (size < 25) {
ast_log(LOG_ERROR, "size of value is too small\n");
return false;
}
if (BSON_ITER_HOLDS_OID(iter)) {
const bson_oid_t * oid;
if (strcmp(bson_iter_key(iter), SERVERID) == 0) {
// SERVERID is hidden property for application
return false;
}
oid = bson_iter_oid(iter);
bson_oid_to_string(oid, value);
}
else if (BSON_ITER_HOLDS_UTF8(iter)) {
uint32_t length;
const char* str = bson_iter_utf8(iter, &length);
if (!bson_utf8_validate(str, length, false)) {
ast_log(LOG_WARNING, "unexpected invalid bson found\n");
return false;
}
snprintf(value, size, "%s", str);
}
else if (BSON_ITER_HOLDS_BOOL(iter)) {
bool d = bson_iter_bool(iter);
snprintf(value, size, "%s", d ? "true" : "false");
}
else if (BSON_ITER_HOLDS_INT32(iter)) {
long d = bson_iter_int32(iter);
snprintf(value, size, "%ld", d);
}
else if (BSON_ITER_HOLDS_INT64(iter)) {
long long d = bson_iter_int64(iter);
snprintf(value, size, "%Ld", d);
}
else if (BSON_ITER_HOLDS_DOUBLE(iter)) {
double d = bson_iter_double(iter);
snprintf(value, size, "%.10g", d);
}
else {
// see http://api.mongodb.org/libbson/current/bson_iter_type.html
ast_log(LOG_WARNING, "unexpected bson type, %x\n", bson_iter_type(iter));
return false;
}
*key = key_mongo2asterisk(bson_iter_key(iter));
return true;
}
/*!
* \brief Update documents in collection that match selector.
* \param[in] collection is a mongoc_collection_t.
* \param[in] selector is a bson_t containing the query to match documents for updating.
* \param[in] update is a bson_t containing the update to perform.
*
* \retval number of rows affected
* \retval -1 on failure
*/
static int _collection_update(
mongoc_collection_t *collection, const bson_t *selector, const bson_t *update)
{
int ret = -1;
bson_t *cmd = NULL;
bson_t *opts = NULL;
bson_t *updates = NULL;
bson_t array = BSON_INITIALIZER;
bson_t reply = BSON_INITIALIZER;
LOG_BSON_AS_JSON(LOG_DEBUG, "selector=%s\n", selector);
LOG_BSON_AS_JSON(LOG_DEBUG, "update=%s\n", update);
do {
bson_error_t error;
bson_iter_t iter;
opts = bson_new();
updates = BCON_NEW(
"q", BCON_DOCUMENT(selector),
"u", BCON_DOCUMENT(update),
"multi", BCON_BOOL(true)
);
bson_append_document(&array, "0", -1, updates);
cmd = BCON_NEW(
"update", BCON_UTF8(mongoc_collection_get_name(collection)),
"updates", BCON_ARRAY(&array)
);
if (!mongoc_collection_write_command_with_opts(
collection, cmd, opts, &reply, &error))
{
ast_log(LOG_ERROR, "update failed, error=%s\n", error.message);
LOG_BSON_AS_JSON(LOG_ERROR, "cmd=%s\n", cmd);
break;
}
LOG_BSON_AS_JSON(LOG_DEBUG, "reply=%s\n", &reply);
if (!bson_iter_init(&iter, &reply)
|| !bson_iter_find(&iter, "nModified")
|| !BSON_ITER_HOLDS_INT32(&iter)) {
ast_log(LOG_ERROR, "no \"nModified\" field found.\n");
break;
}
ret = bson_iter_int32(&iter);
} while(0);
bson_destroy(&reply);
bson_destroy(&array);
if (updates)
bson_destroy(updates);
if (opts)
bson_destroy(opts);
if (cmd)
bson_destroy(cmd);
return ret;
}
/*!
* \brief Execute an SQL query and return ast_variable list
* \param database is name of database
* \param table is name of collection to find specified records
* \param ap list containing one or more field/operator/value set.
*
* Select database and perform query on table, prepare the sql statement
* Sub-in the values to the prepared statement and execute it. Return results
* as a ast_variable list.
*
* \retval var on success
* \retval NULL on failure
*
* \see http://api.mongodb.org/c/current/finding-document.html
*/
static struct ast_variable *realtime(const char *database, const char *table, const struct ast_variable *fields)
{
struct ast_variable *var = NULL;
mongoc_client_t *dbclient;
mongoc_collection_t *collection = NULL;
mongoc_cursor_t *cursor = NULL;
const bson_t *doc = NULL;
bson_t *query = NULL;
if (!database || !table || !fields) {
ast_log(LOG_ERROR, "not enough arguments\n");
return NULL;
}
ast_log(LOG_DEBUG, "database=%s, table=%s.\n", database, table);
if(dbpool == NULL) {
ast_log(LOG_ERROR, "no connection pool\n");
return NULL;
}
dbclient = mongoc_client_pool_pop(dbpool);
if(dbclient == NULL) {
ast_log(LOG_ERROR, "no client allocated\n");
return NULL;
}
do {
query = make_query(fields, NULL);
if(query == NULL) {
ast_log(LOG_ERROR, "cannot make a query to find\n");
break;
}
LOG_BSON_AS_JSON(LOG_DEBUG, "query=%s, database=%s, table=%s\n", query, database, table);
collection = mongoc_client_get_collection(dbclient, database, table);
cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0, query, NULL, NULL);
if (!cursor) {
LOG_BSON_AS_JSON(LOG_ERROR, "query failed with query=%s, database=%s, table=%s\n", query, database, table);
break;
}
if (mongoc_cursor_next(cursor, &doc)) {
bson_iter_t iter;
const char* key;
const char* value;
char work[128];
struct ast_variable *prev = NULL;
LOG_BSON_AS_JSON(LOG_DEBUG, "query found %s\n", doc);
if (!bson_iter_init(&iter, doc)) {
ast_log(LOG_ERROR, "unexpected bson error!\n");
break;
}
while (bson_iter_next(&iter)) {
if (!doc2value(&iter, &key, work, sizeof(work)))
continue;
value = work;
if (prev) {
prev->next = ast_variable_new(key, value, "");
if (prev->next)
prev = prev->next;
}
else
prev = var = ast_variable_new(key, value, "");
}
}
} while(0);
if (doc)
bson_destroy((bson_t *)doc);
if (query)
bson_destroy((bson_t *)query);
if (cursor)
mongoc_cursor_destroy(cursor);
if (collection)
mongoc_collection_destroy(collection);
mongoc_client_pool_push(dbpool, dbclient);
return var;
}
/*!
* \brief Execute an Select query and return ast_config list
* \param database is name of database
* \param table is name of collection to find specified records
* \param fields is a list containing one or more field/operator/value set.
*
* Select database and preform query on table, prepare the sql statement
* Sub-in the values to the prepared statement and execute it.
* Execute this prepared query against MongoDB.
* Return results as an ast_config variable.
*
* \retval var on success
* \retval NULL on failure
*
* \see http://api.mongodb.org/c/current/finding-document.html
*/
static struct ast_config* realtime_multi(const char *database, const char *table, const struct ast_variable *fields)
{
struct ast_config *cfg = NULL;
struct ast_category *cat = NULL;
struct ast_variable *var = NULL;
mongoc_collection_t *collection = NULL;
mongoc_cursor_t* cursor = NULL;
mongoc_client_t* dbclient = NULL;
const bson_t* doc = NULL;
const bson_t* query = NULL;
const char *initfield;
char *op;
if (!database || !table || !fields) {
ast_log(LOG_ERROR, "not enough arguments\n");
return NULL;
}
ast_log(LOG_DEBUG, "database=%s, table=%s.\n", database, table);
if(dbpool == NULL) {
ast_log(LOG_ERROR, "no connection pool\n");
return NULL;
}
dbclient = mongoc_client_pool_pop(dbpool);
if(dbclient == NULL) {
ast_log(LOG_ERROR, "no client allocated\n");
return NULL;
}
initfield = ast_strdupa(fields->name);
if ((op = strchr(initfield, ' '))) {
*op = '\0';
}
do {
query = make_query(fields, initfield);
if(query == NULL) {
ast_log(LOG_ERROR, "cannot make a query to find\n");
break;
}
cfg = ast_config_new();
if (!cfg) {
ast_log(LOG_WARNING, "out of memory!\n");
break;
}
collection = mongoc_client_get_collection(dbclient, database, table);
LOG_BSON_AS_JSON(LOG_DEBUG, "query=%s, database=%s, table=%s\n", query, database, table);
cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
if (!cursor) {
LOG_BSON_AS_JSON(LOG_ERROR, "query failed with query=%s, database=%s, table=%s\n", query, database, table);
break;
}
while (mongoc_cursor_next(cursor, &doc)) {
bson_iter_t iter;
const char* key;
const char* value;
char work[128];
LOG_BSON_AS_JSON(LOG_DEBUG, "query found %s\n", doc);
if (!bson_iter_init(&iter, doc)) {
ast_log(LOG_ERROR, "unexpected bson error!\n");
break;
}
cat = ast_category_new("", "", 99999);
if (!cat) {
ast_log(LOG_WARNING, "out of memory!\n");
break;
}
while (bson_iter_next(&iter)) {
if (!doc2value(&iter, &key, work, sizeof(work)))
continue;
value = work;
if (!strcmp(initfield, key))
ast_category_rename(cat, value);
var = ast_variable_new(key, value, "");
ast_variable_append(cat, var);
}
ast_category_append(cfg, cat);
}
} while(0);
ast_log(LOG_DEBUG, "end of query.\n");
if (query)
bson_destroy((bson_t *)query);
if (cursor)
mongoc_cursor_destroy(cursor);
if (collection)
mongoc_collection_destroy(collection);
mongoc_client_pool_push(dbpool, dbclient);
return cfg;
}
/*!
* \brief Execute an UPDATE query
* \param database is name of database
* \param table is name of collection to update records
* \param keyfield where clause field
* \param lookup value of field for where clause
* \param fields is a list containing one or more field/value set(s).
*
* Update a database table, prepare the sql statement using keyfield and lookup
* control the number of records to change. All values to be changed are stored in ap list.
* Sub-in the values to the prepared statement and execute it.
*
* \retval number of rows affected
* \retval -1 on failure
*/
static int update(const char *database, const char *table, const char *keyfield, const char *lookup, const struct ast_variable *fields)
{
int ret = -1;
bson_t *query = NULL;
bson_t *data = NULL;
bson_t *update = NULL;
mongoc_client_t *dbclient = NULL;
mongoc_collection_t *collection = NULL;
if (!database || !table || !keyfield || !lookup || !fields) {
ast_log(LOG_ERROR, "not enough arguments\n");
return -1;
}
ast_log(LOG_DEBUG, "database=%s, table=%s, keyfield=%s, lookup=%s.\n", database, table, keyfield, lookup);
if(dbpool == NULL) {
ast_log(LOG_ERROR, "no connection pool\n");
return -1;
}
dbclient = mongoc_client_pool_pop(dbpool);
if(dbclient == NULL) {
ast_log(LOG_ERROR, "no client allocated\n");
return -1;
}
do {
query = serverid ? BCON_NEW(SERVERID, BCON_OID(serverid)) : bson_new();
if (!query) {
ast_log(LOG_ERROR, "not enough memory\n");
break;
}
if (!BSON_APPEND_UTF8(query, key_asterisk2mongo(keyfield), lookup)) {
ast_log(LOG_ERROR, "cannot make a query\n");
break;
}
data = bson_new();
if (!data) {
ast_log(LOG_ERROR, "not enough memory\n");
break;
}
update = bson_new();
if (!update) {
ast_log(LOG_ERROR, "not enough memory\n");
break;
}
if (!fields2doc(table, fields, data)) {
ast_log(LOG_ERROR, "cannot make data to update\n");
break;
}
if (!BSON_APPEND_DOCUMENT(update, "$set", data)) {
ast_log(LOG_ERROR,
"cannot make data to update, database=%s, table=%s, keyfield=%s, lookup=%s\n",
database, table, keyfield, lookup);
break;
}
collection = mongoc_client_get_collection(dbclient, database, table);
ret = _collection_update(collection, query, update);
} while(0);
if (data)
bson_destroy((bson_t *)data);
if (update)
bson_destroy((bson_t *)update);
if (query)
bson_destroy((bson_t *)query);
if (collection)
mongoc_collection_destroy(collection);
mongoc_client_pool_push(dbpool, dbclient);
return ret;
}
/*!
* \brief Callback for ast_realtime_require
* \retval 0 Required fields met specified standards
* \retval -1 One or more fields was missing or insufficient
*/
static int require(const char *database, const char *table, va_list ap)
{
bson_t *model = bson_new();
char *elm;
if (!database || !table) {
ast_log(LOG_ERROR, "not enough arguments\n");
return -1;
}
ast_log(LOG_DEBUG, "database=%s, table=%s.\n", database, table);
while ((elm = va_arg(ap, char *))) {
int type = va_arg(ap, require_type);
// int size =
va_arg(ap, int);
// ast_log(LOG_DEBUG, "elm=%s, type=%d, size=%d\n", elm, type, size);
BSON_APPEND_INT64(model, elm, rtype2btype(type));
}
LOG_BSON_AS_JSON(LOG_DEBUG, "required model is \"%s\"\n", model);
model_register(table, model);
bson_destroy(model);
return 0;
}
/*!
* \brief Execute an UPDATE query
* \param database is name of database
* \param table is name of collection to update records
* \param ap list containing one or more field/value set(s).
*
* Update a database table, preparing the sql statement from a list of
* key/value pairs specified in ap. The lookup pairs are specified first
* and are separated from the update pairs by a sentinel value.
* Sub-in the values to the prepared statement and execute it.
*
* \retval number of rows affected
* \retval -1 on failure
*/
static int update2(const char *database, const char *table, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields)
{
int ret = -1;
bson_t *query = NULL;
bson_t *data = NULL;
bson_t *update = NULL;
mongoc_client_t *dbclient = NULL;
mongoc_collection_t *collection = NULL;
if (!database || !table || !lookup_fields || !update_fields) {
ast_log(LOG_ERROR, "not enough arguments\n");
return -1;
}
ast_log(LOG_DEBUG, "database=%s, table=%s\n", database, table);
if(dbpool == NULL) {
ast_log(LOG_ERROR, "no connection pool\n");
return -1;
}
dbclient = mongoc_client_pool_pop(dbpool);
if(dbclient == NULL) {
ast_log(LOG_ERROR, "no client allocated\n");
return -1;
}