forked from voipmonitor/sniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql_db.cpp
5861 lines (5528 loc) · 195 KB
/
sql_db.cpp
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
#include <stdio.h>
#include <iostream>
#include <syslog.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <sstream>
#include <stdarg.h>
#include <netdb.h>
#include <mysqld_error.h>
#include <errmsg.h>
#include <dirent.h>
#include <math.h>
#include <signal.h>
#ifndef FREEBSD
#include <sys/inotify.h>
#endif
#include "voipmonitor.h"
#include "tools.h"
#include "sql_db.h"
#include "fraud.h"
#include "calltable.h"
#define QFILE_PREFIX "qoq"
extern int verbosity;
extern int opt_mysql_port;
extern char opt_match_header[128];
extern int opt_ipaccount;
extern int opt_id_sensor;
extern bool opt_cdr_partition;
extern bool opt_cdr_sipport;
extern bool opt_last_rtp_from_end;
extern bool opt_cdr_rtpport;
extern int opt_create_old_partitions;
extern bool opt_disable_partition_operations;
extern vector<dstring> opt_custom_headers_cdr;
extern vector<dstring> opt_custom_headers_message;
extern char get_customers_pn_query[1024];
extern int opt_dscp;
extern int opt_enable_http_enum_tables;
extern int opt_enable_webrtc_table;
extern int opt_mysqlcompress;
extern int opt_mysql_enable_transactions;
extern pthread_mutex_t mysqlconnect_lock;
extern int opt_mos_lqo;
extern int opt_read_from_file;
extern char opt_pb_read_from_file[256];
extern int opt_enable_fraud;
extern bool _save_sip_history;
extern char sql_driver[256];
extern char mysql_host[256];
extern char mysql_database[256];
extern char mysql_user[256];
extern char mysql_password[256];
extern int opt_mysql_port;
extern char opt_mysql_timezone[256];
extern int opt_skiprtpdata;
extern char odbc_dsn[256];
extern char odbc_user[256];
extern char odbc_password[256];
extern char odbc_driver[256];
extern char cloud_host[256];
extern char cloud_token[256];
extern CustomHeaders *custom_headers_cdr;
extern CustomHeaders *custom_headers_message;
int sql_noerror = 0;
int sql_disable_next_attempt_if_error = 0;
bool opt_cdr_partition_oldver = false;
bool exists_column_message_content_length = false;
bool exists_columns_cdr_reason = false;
string SqlDb_row::operator [] (const char *fieldName) {
int indexField = this->getIndexField(fieldName);
if(indexField >= 0 && (unsigned)indexField < row.size()) {
return(row[indexField].content);
}
return("");
}
string SqlDb_row::operator [] (string fieldName) {
return((*this)[fieldName.c_str()]);
}
string SqlDb_row::operator [] (int indexField) {
return(row[indexField].content);
}
SqlDb_row::operator int() {
return(!this->isEmpty());
}
void SqlDb_row::add(const char *content, string fieldName) {
if(fieldName != "") {
for(size_t i = 0; i < row.size(); i++) {
if(row[i].fieldName == fieldName) {
row[i] = SqlDb_rowField(content, fieldName);
return;
}
}
}
this->row.push_back(SqlDb_rowField(content, fieldName));
}
void SqlDb_row::add(string content, string fieldName) {
if(fieldName != "") {
for(size_t i = 0; i < row.size(); i++) {
if(row[i].fieldName == fieldName) {
row[i] = SqlDb_rowField(content, fieldName);
return;
}
}
}
this->row.push_back(SqlDb_rowField(content, fieldName));
}
void SqlDb_row::add(int content, string fieldName, bool null) {
if(!content && null) {
this->add((const char*)NULL, fieldName);
} else {
char str_content[100];
sprintf(str_content, "%i", content);
this->add(str_content, fieldName);
}
}
void SqlDb_row::add(unsigned int content, string fieldName, bool null) {
if(!content && null) {
this->add((const char*)NULL, fieldName);
} else {
char str_content[100];
sprintf(str_content, "%u", content);
this->add(str_content, fieldName);
}
}
void SqlDb_row::add(long int content, string fieldName, bool null) {
if(!content && null) {
this->add((const char*)NULL, fieldName);
} else {
char str_content[100];
sprintf(str_content, "%li", content);
this->add(str_content, fieldName);
}
}
void SqlDb_row::add(double content, string fieldName, bool null) {
if(!content && null) {
this->add((const char*)NULL, fieldName);
} else {
char str_content[100];
sprintf(str_content, "%lf", content);
this->add(str_content, fieldName);
}
}
void SqlDb_row::add(u_int64_t content, string fieldName, bool null) {
if(!content && null) {
this->add((const char*)NULL, fieldName);
} else {
char str_content[100];
sprintf(str_content, "%llu", (unsigned long long)content);
this->add(str_content, fieldName);
}
}
int SqlDb_row::getIndexField(string fieldName) {
for(size_t i = 0; i < row.size(); i++) {
if(!strcasecmp(row[i].fieldName.c_str(), fieldName.c_str())) {
return(i);
}
}
if(this->sqlDb) {
return(this->sqlDb->getIndexField(fieldName));
}
return(-1);
}
string SqlDb_row::getNameField(int indexField) {
if((unsigned)indexField < row.size()) {
if(!row[indexField].fieldName.empty()) {
return(row[indexField].fieldName);
}
if(this->sqlDb) {
return(this->sqlDb->getNameField(indexField));
}
}
return("");
}
bool SqlDb_row::isEmpty() {
return(!row.size());
}
bool SqlDb_row::isNull(string fieldName) {
int indexField = this->getIndexField(fieldName);
if(indexField >= 0) {
return(row[indexField].null);
}
return(false);
}
string SqlDb_row::implodeFields(string separator, string border) {
string rslt;
for(size_t i = 0; i < this->row.size(); i++) {
if(i) { rslt += separator; }
rslt += border + /*'`' +*/ this->row[i].fieldName + /*'`' +*/ border;
}
return(rslt);
}
string SqlDb_row::implodeContent(string separator, string border, bool enableSqlString, bool escapeAll) {
string rslt;
for(size_t i = 0; i < this->row.size(); i++) {
if(i) { rslt += separator; }
if(this->row[i].null) {
rslt += "NULL";
} else if(enableSqlString && this->row[i].content.substr(0, 12) == "_\\_'SQL'_\\_:") {
rslt += this->row[i].content.substr(12);
} else {
rslt += border +
(escapeAll ? sqlEscapeString(this->row[i].content) : this->row[i].content) +
border;
}
}
return(rslt);
}
string SqlDb_row::implodeFieldContent(string separator, string fieldBorder, string contentBorder, bool enableSqlString, bool escapeAll) {
string rslt;
for(size_t i = 0; i < this->row.size(); i++) {
if(i) { rslt += separator; }
rslt += fieldBorder + /*'`' +*/ this->row[i].fieldName + /*'`' +*/ fieldBorder;
rslt += " = ";
if(this->row[i].null) {
rslt += "NULL";
} else if(enableSqlString && this->row[i].content.substr(0, 12) == "_\\_'SQL'_\\_:") {
rslt += this->row[i].content.substr(12);
} else {
rslt += contentBorder +
(escapeAll ? sqlEscapeString(this->row[i].content) : this->row[i].content) +
contentBorder;
}
}
return(rslt);
}
string SqlDb_row::keyvalList(string separator) {
string rslt;
for(size_t i = 0; i < this->row.size(); i++) {
if(this->row[i].null) {
rslt += this->row[i].fieldName + ":NULL\n";
} else {
rslt += this->row[i].fieldName + separator + this->row[i].content + "\n";
}
}
return(rslt);
}
size_t SqlDb_row::getCountFields() {
return(row.size());
}
SqlDb::SqlDb() {
this->clearLastError();
this->conn_port = 0;
this->conn_disable_secure_auth = false;
this->maxQueryPass = UINT_MAX;
this->loginTimeout = (ulong)NULL;
this->enableSqlStringInContent = false;
this->disableNextAttemptIfError = false;
this->disableLogError = false;
this->silentConnect = false;
this->connecting = false;
this->cloud_data_rows = 0;
this->cloud_data_index = 0;
this->maxAllowedPacket = 1024*1024;
this->lastError = 0;
this->lastmysqlresolve = 0;
}
SqlDb::~SqlDb() {
}
void SqlDb::setConnectParameters(string server, string user, string password, string database, u_int16_t port, bool showversion) {
this->conn_server = server;
this->conn_user = user;
this->conn_password = password;
this->conn_database = database;
this->conn_port = port;
this->conn_showversion = showversion;
}
void SqlDb::setCloudParameters(string cloud_host, string cloud_token) {
this->cloud_host = cloud_host;
this->cloud_token = cloud_token;
}
void SqlDb::setLoginTimeout(ulong loginTimeout) {
this->loginTimeout = loginTimeout;
}
void SqlDb::setDisableSecureAuth(bool disableSecureAuth) {
this->conn_disable_secure_auth = disableSecureAuth;
}
bool SqlDb::reconnect() {
if(this->connecting) {
if(verbosity > 1) {
syslog(LOG_NOTICE, "prevent recursion of connect to db");
}
return(false);
}
if(verbosity > 1) {
syslog(LOG_INFO, "start reconnect");
}
this->disconnect();
bool rslt = this->connect();
if(verbosity > 1) {
syslog(LOG_INFO, "reconnect rslt: %s", rslt ? "OK" : "FAIL");
}
return(rslt);
}
bool SqlDb::queryByCurl(string query) {
cloud_data_columns.clear();
cloud_data.clear();
cloud_data_rows = 0;
cloud_data_index = 0;
clearLastError();
bool ok = false;
vector<dstring> postData;
postData.push_back(dstring("query", query.c_str()));
postData.push_back(dstring("token", cloud_token));
unsigned int attempt = 0;
for(unsigned int pass = 0; pass < this->maxQueryPass; pass++, attempt++) {
if(pass > 0) {
sleep(1);
syslog(LOG_INFO, "next attempt %u - query: %s", attempt, prepareQueryForPrintf(query).c_str());
}
SimpleBuffer responseBuffer;
string error;
get_url_response(cloud_redirect.empty() ? cloud_host.c_str() : cloud_redirect.c_str(),
&responseBuffer, &postData, &error);
if(error.empty()) {
if(!responseBuffer.empty()) {
if(responseBuffer.isJsonObject()) {
JsonItem jsonData;
jsonData.parse((char*)responseBuffer);
string result = jsonData.getValue("result");
trim(result);
if(!strcasecmp(result.c_str(), "OK")) {
ok = true;
} else if(!strncasecmp(result.c_str(), "REDIRECT TO", 11)) {
cloud_redirect = result.substr(11);
trim(cloud_redirect);
if(cloud_redirect.empty()) {
setLastError(0, "missing redirect ip / server", true);
} else {
pass = 0;
continue;
}
} else {
bool tryNext = true;
unsigned int errorCode = atol(result.c_str());
size_t posSeparator = result.find('|');
string errorString;
if(posSeparator != string::npos) {
size_t posSeparator2 = result.find('|', posSeparator + 1);
if(posSeparator2 != string::npos) {
tryNext = atoi(result.substr(posSeparator + 1).c_str());
errorString = result.substr(posSeparator2 + 1);
} else {
errorString = result.substr(posSeparator + 1);
}
} else {
errorString = result;
}
if(!sql_noerror && !this->disableLogError) {
setLastError(errorCode, errorString.c_str(), true);
}
if(tryNext) {
if(sql_noerror || sql_disable_next_attempt_if_error ||
this->disableLogError || this->disableNextAttemptIfError ||
errorCode == ER_PARSE_ERROR) {
break;
} else if(errorCode != CR_SERVER_GONE_ERROR &&
pass < this->maxQueryPass - 5) {
pass = this->maxQueryPass - 5;
}
} else {
break;
}
}
if(ok) {
JsonItem *dataJsonDataRows = jsonData.getItem("data_rows");
if(dataJsonDataRows) {
cloud_data_rows = atol(dataJsonDataRows->getLocalValue().c_str());
}
JsonItem *dataJsonItems = jsonData.getItem("data");
if(dataJsonItems) {
for(size_t i = 0; i < dataJsonItems->getLocalCount(); i++) {
JsonItem *dataJsonItem = dataJsonItems->getLocalItem(i);
for(size_t j = 0; j < dataJsonItem->getLocalCount(); j++) {
string dataItem = dataJsonItem->getLocalItem(j)->getLocalValue();
if(i == 0) {
cloud_data_columns.push_back(dataItem);
} else {
if(cloud_data.size() < i) {
vector<string> row;
cloud_data.push_back(row);
}
cloud_data[i-1].push_back(dataItem);
}
}
}
}
break;
}
} else {
setLastError(0, "bad response - " + string(responseBuffer), true);
}
} else {
setLastError(0, "response is empty", true);
}
} else {
setLastError(0, error.c_str(), true);
}
}
return(ok);
}
string SqlDb::prepareQuery(string query, bool nextPass) {
::prepareQuery(this->getSubtypeDb(), query, true, nextPass ? 2 : 1);
return(query);
}
string SqlDb::insertQuery(string table, SqlDb_row row, bool enableSqlStringInContent, bool escapeAll, bool insertIgnore) {
string query =
string("INSERT ") + (insertIgnore ? "IGNORE " : "") + "INTO " + table + " ( " + row.implodeFields(this->getFieldSeparator(), this->getFieldBorder()) +
" ) VALUES ( " + row.implodeContent(this->getContentSeparator(), this->getContentBorder(), enableSqlStringInContent || this->enableSqlStringInContent, escapeAll) + " )";
return(query);
}
string SqlDb::insertQuery(string table, vector<SqlDb_row> *rows, bool enableSqlStringInContent, bool escapeAll, bool insertIgnore) {
if(!rows->size()) {
return("");
}
string values = "";
for(size_t i = 0; i < rows->size(); i++) {
values += "( " + (*rows)[i].implodeContent(this->getContentSeparator(), this->getContentBorder(), enableSqlStringInContent || this->enableSqlStringInContent, escapeAll) + " )";
if(i < rows->size() - 1) {
values += ",";
}
}
string query =
string("INSERT ") + (insertIgnore ? "IGNORE " : "") + "INTO " + table + " ( " + (*rows)[0].implodeFields(this->getFieldSeparator(), this->getFieldBorder()) +
" ) VALUES " + values;
return(query);
}
string SqlDb::updateQuery(string table, SqlDb_row row, const char *whereCond, bool enableSqlStringInContent, bool escapeAll) {
string query =
string("UPDATE ") + table + " set " + row.implodeFieldContent(this->getFieldSeparator(), this->getFieldBorder(), this->getContentBorder(), enableSqlStringInContent || this->enableSqlStringInContent, escapeAll);
if(whereCond) {
query += string(" WHERE ") + whereCond;
}
return(query);
}
int SqlDb::insert(string table, SqlDb_row row) {
string query = this->insertQuery(table, row);
if(this->query(query)) {
return(this->getInsertId());
}
return(-1);
}
int SqlDb::insert(string table, vector<SqlDb_row> *rows) {
if(!rows->size()) {
return(-1);
}
string query = this->insertQuery(table, rows);
if(this->query(query)) {
return(this->getInsertId());
}
return(-1);
}
bool SqlDb::update(string table, SqlDb_row row, const char *whereCond) {
string query = this->updateQuery(table, row, whereCond);
return(this->query(query));
}
int SqlDb::getIdOrInsert(string table, string idField, string uniqueField, SqlDb_row row, const char *uniqueField2) {
string query =
"SELECT * FROM " + table + " WHERE " + uniqueField + " = " +
this->getContentBorder() + row[uniqueField] + this->getContentBorder();
if(uniqueField2) {
query = query + " AND " + uniqueField2 + " = " +
this->getContentBorder() + row[uniqueField2] + this->getContentBorder();
}
if(this->query(query)) {
SqlDb_row rsltRow = this->fetchRow();
if(rsltRow) {
return(atoi(rsltRow[idField].c_str()));
}
}
return(this->insert(table, row));
}
int SqlDb::getIndexField(string fieldName) {
if(isCloud()) {
for(size_t i = 0; i < this->cloud_data_columns.size(); i++) {
if(this->cloud_data_columns[i] == fieldName) {
return(i);
}
}
} else {
for(size_t i = 0; i < this->fields.size(); i++) {
if(this->fields[i] == fieldName) {
return(i);
}
}
}
return(-1);
}
string SqlDb::getNameField(int indexField) {
if(isCloud()) {
if((unsigned)indexField < this->cloud_data_columns.size()) {
return(this->cloud_data_columns[indexField]);
}
} else {
if((unsigned)indexField < this->fields.size()) {
return(this->fields[indexField]);
}
}
return("");
}
void SqlDb::setLastErrorString(string lastErrorString, bool sysLog) {
this->lastErrorString = lastErrorString;
if(sysLog && lastErrorString != "") {
syslog(LOG_ERR, "%s", lastErrorString.c_str());
}
}
void SqlDb::setEnableSqlStringInContent(bool enableSqlStringInContent) {
this->enableSqlStringInContent = enableSqlStringInContent;
}
void SqlDb::setDisableNextAttemptIfError() {
this->disableNextAttemptIfError = true;
}
void SqlDb::setEnableNextAttemptIfError() {
this->disableNextAttemptIfError = false;
}
void SqlDb::setDisableLogError() {
this->disableLogError = true;
}
void SqlDb::setEnableLogError() {
this->disableLogError = false;
}
void SqlDb::setSilentConnect() {
this->silentConnect = true;;
}
void SqlDb::cleanFields() {
this->fields.clear();
}
void SqlDb::addDelayQuery(u_int32_t delay_ms) {
delayQuery_sum_ms += delay_ms;
++delayQuery_count;
}
u_int32_t SqlDb::getAvgDelayQuery() {
u_int64_t _delayQuery_sum_ms = delayQuery_sum_ms;
u_int32_t _delayQuery_count = delayQuery_count;
return(_delayQuery_count ? _delayQuery_sum_ms / _delayQuery_count : 0);
}
void SqlDb::resetDelayQuery() {
delayQuery_sum_ms = 0;
delayQuery_count = 0;
}
volatile u_int64_t SqlDb::delayQuery_sum_ms = 0;
volatile u_int32_t SqlDb::delayQuery_count = 0;
SqlDb_mysql::SqlDb_mysql() {
this->hMysql = NULL;
this->hMysqlConn = NULL;
this->hMysqlRes = NULL;
this->mysqlThreadId = 0;
}
SqlDb_mysql::~SqlDb_mysql() {
this->clean();
}
bool SqlDb_mysql::connect(bool createDb, bool mainInit) {
if(isCloud()) {
return(true);
}
this->connecting = true;
pthread_mutex_lock(&mysqlconnect_lock);
this->hMysql = mysql_init(NULL);
if(this->hMysql) {
my_bool reconnect = 1;
mysql_options(this->hMysql, MYSQL_OPT_RECONNECT, &reconnect);
struct timeval s;
gettimeofday (&s, 0);
if(this->conn_server_ip.empty() and ((lastmysqlresolve + 300) < s.tv_sec)) {
lastmysqlresolve = s.tv_sec;
if(reg_match(this->conn_server.c_str(), "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+", __FILE__, __LINE__)) {
this->conn_server_ip = this->conn_server;
} else {
hostent *conn_server_record = gethostbyname(this->conn_server.c_str());
if(conn_server_record == NULL) {
this->setLastErrorString("mysql connect failed - " + this->conn_server + " is unavailable", true);
pthread_mutex_unlock(&mysqlconnect_lock);
this->connecting = false;
return(false);
}
in_addr *conn_server_address = (in_addr*)conn_server_record->h_addr;
this->conn_server_ip = inet_ntoa(*conn_server_address);
syslog(LOG_NOTICE, "resolve mysql host %s to %s", this->conn_server.c_str(), this->conn_server_ip.c_str());
}
}
for(int connectPass = 0; connectPass < 2; connectPass++) {
if(connectPass) {
if(this->hMysqlRes) {
while(mysql_fetch_row(this->hMysqlRes));
mysql_free_result(this->hMysqlRes);
this->hMysqlRes = NULL;
}
mysql_close(this->hMysqlConn);
}
this->hMysql = mysql_init(NULL);
if(this->conn_disable_secure_auth) {
int arg = 0;
mysql_options(this->hMysql, MYSQL_SECURE_AUTH, &arg);
}
this->hMysqlConn = mysql_real_connect(
this->hMysql,
this->conn_server_ip.c_str(), this->conn_user.c_str(), this->conn_password.c_str(), NULL,
this->conn_port ? this->conn_port : opt_mysql_port,
NULL, CLIENT_MULTI_RESULTS);
if(!this->hMysqlConn) {
break;
}
sql_disable_next_attempt_if_error = 1;
sql_noerror = !mainInit;
if(this->query("SET GLOBAL max_allowed_packet=1024*1024*100") &&
this->query("show variables like 'max_allowed_packet'")) {
sql_disable_next_attempt_if_error = 0;
sql_noerror = 0;
SqlDb_row row;
if((row = this->fetchRow())) {
this->maxAllowedPacket = atoll(row[1].c_str());
if(this->maxAllowedPacket >= 1024*1024*100) {
break;
} else if(connectPass) {
if(mainInit) {
syslog(LOG_WARNING, "Max allowed packet size is only %lu. Concat query size is limited. "
"Please set max_allowed_packet to 100MB manually in your mysql configuration file.",
this->maxAllowedPacket);
}
}
} else {
if(mainInit) {
syslog(LOG_WARNING, "Unknown max allowed packet size. Concat query size is limited. "
"Please set max_allowed_packet to 100MB manually in your mysql configuration file.");
}
break;
}
} else {
sql_disable_next_attempt_if_error = 0;
sql_noerror = 0;
if(mainInit) {
syslog(LOG_WARNING, "Query for set / get max allowed packet size failed. Concat query size is limited. "
"Please set max_allowed_packet to 100MB manually in your mysql configuration file.");
}
break;
}
}
if(this->hMysqlConn) {
bool rslt = true;
this->mysqlThreadId = mysql_thread_id(this->hMysql);
sql_disable_next_attempt_if_error = 1;
if(!this->query("SET NAMES UTF8")) {
rslt = false;
}
sql_noerror = 1;
this->query("SET GLOBAL innodb_stats_on_metadata=0"); // this will speedup "Slow query on information_schema.tables"
if(opt_mysql_timezone[0]) {
this->query(string("SET time_zone = '") + opt_mysql_timezone + "'");
}
sql_noerror = 0;
if(!this->query("SET sql_mode = ''")) {
rslt = false;
}
char tmp[1024];
if(createDb) {
if(this->getDbMajorVersion() >= 5 and
!(this->getDbMajorVersion() == 5 and this->getDbMinorVersion() <= 1)) {
this->query("SET GLOBAL innodb_file_per_table=1;");
}
sprintf(tmp, "CREATE DATABASE IF NOT EXISTS `%s`", this->conn_database.c_str());
if(!this->query(tmp)) {
rslt = false;
}
}
sprintf(tmp, "USE `%s`", this->conn_database.c_str());
if(!this->query(tmp)) {
rslt = false;
}
if(mainInit && !cloud_host[0]) {
this->query("SHOW VARIABLES LIKE \"version\"");
SqlDb_row row;
if((row = this->fetchRow())) {
this->dbVersion = row[1];
}
while(this->fetchRow());
if(this->conn_showversion) {
syslog(LOG_INFO, "connect - db version %i.%i", this->getDbMajorVersion(), this->getDbMinorVersion());
}
}
sql_disable_next_attempt_if_error = 0;
pthread_mutex_unlock(&mysqlconnect_lock);
if(this->hMysqlRes) {
mysql_free_result(this->hMysqlRes);
this->hMysqlRes = NULL;
this->cleanFields();
}
this->connecting = false;
return(rslt);
} else {
if(!this->silentConnect) {
this->checkLastError("connect error (" + this->conn_server + ")", true);
}
}
} else {
this->setLastErrorString("mysql_init failed - insufficient memory ?", true);
}
pthread_mutex_unlock(&mysqlconnect_lock);
this->connecting = false;
return(false);
}
int SqlDb_mysql::multi_on() {
return isCloud() ? true : mysql_set_server_option(this->hMysql, MYSQL_OPTION_MULTI_STATEMENTS_ON);
}
int SqlDb_mysql::multi_off() {
return isCloud() ? true : mysql_set_server_option(this->hMysql, MYSQL_OPTION_MULTI_STATEMENTS_OFF);
}
int SqlDb_mysql::getDbMajorVersion() {
return(atoi(this->dbVersion.c_str()));
}
int SqlDb_mysql::getDbMinorVersion(int minorLevel) {
const char *pointToVersion = this->dbVersion.c_str();
for(int i = 0; i < minorLevel + 1 && pointToVersion; i++) {
const char *pointToSeparator = strchr(pointToVersion, '.');
if(pointToSeparator) {
pointToVersion = pointToSeparator + 1;
}
}
return(pointToVersion ? atoi(pointToVersion) : 0);
}
bool SqlDb_mysql::createRoutine(string routine, string routineName, string routineParamsAndReturn, eRoutineType routineType, bool abortIfFailed) {
bool missing = false;
bool diff = false;
if(this->isCloud()) {
missing = true;
diff = true;
} else {
this->query(string("select routine_definition from information_schema.routines where routine_schema='") + this->conn_database +
"' and routine_name='" + routineName +
"' and routine_type='" + (routineType == procedure ? "PROCEDURE" : "FUNCTION") + "'");
SqlDb_row row = this->fetchRow();
if(!row) {
missing = true;
} else if(row["routine_definition"] != routine) {
size_t i = 0, j = 0;
while(i < routine.length() &&
j < row["routine_definition"].length()) {
if(routine[i] == '\\' && i < routine.length() - 1) {
++i;
}
if(routine[i] != row["routine_definition"][j]) {
diff = true;
break;
}
++i;
++j;
}
if(!diff &&
(i < routine.length() || j < row["routine_definition"].length())) {
diff = true;
}
}
}
if(missing || diff) {
syslog(LOG_NOTICE, "create %s %s", (routineType == procedure ? "procedure" : "function"), routineName.c_str());
this->query(string("drop ") + (routineType == procedure ? "PROCEDURE" : "FUNCTION") +
" if exists " + routineName);
bool rslt = this->query(string("create ") + (routineType == procedure ? "PROCEDURE" : "FUNCTION") + " " +
routineName + routineParamsAndReturn + " " + routine);
if(!rslt && abortIfFailed) {
string errorString =
string("create routine ") + routineName + " failed\n" +
"tip: SET GLOBAL log_bin_trust_function_creators = 1 or put it in my.cnf configuration or grant SUPER privileges to your voipmonitor mysql user.";
syslog(LOG_ERR, errorString.c_str());
vm_terminate_error(errorString.c_str());
}
return(rslt);
} else {
return(true);
}
}
void SqlDb_mysql::disconnect() {
if(isCloud()) {
return;
}
if(this->hMysqlRes) {
while(mysql_fetch_row(this->hMysqlRes));
mysql_free_result(this->hMysqlRes);
this->hMysqlRes = NULL;
}
if(this->hMysqlConn) {
mysql_close(this->hMysqlConn);
this->hMysqlConn = NULL;
}
/* disable dealloc hMysql - is it shared variable ?
this->hMysql = NULL;
}
else if(this->hMysql) {
mysql_close(this->hMysql);
this->hMysql = NULL;
}
*/
}
bool SqlDb_mysql::connected() {
return(isCloud() ? true : this->hMysqlConn != NULL);
}
bool SqlDb_mysql::query(string query, bool callFromStoreProcessWithFixDeadlock, const char *dropProcQuery) {
if(isCloud()) {
string preparedQuery = this->prepareQuery(query, false);
if(verbosity > 1) {
syslog(LOG_INFO, prepareQueryForPrintf(preparedQuery).c_str());
}
return(this->queryByCurl(preparedQuery));
}
u_int32_t startTimeMS = getTimeMS();
if(this->hMysqlRes) {
while(mysql_fetch_row(this->hMysqlRes));
mysql_free_result(this->hMysqlRes);
this->hMysqlRes = NULL;
}
if(this->connected()) {
if(mysql_ping(this->hMysql)) {
if(verbosity > 1) {
syslog(LOG_INFO, "mysql_ping failed -> force reconnect");
}
this->reconnect();
} else if(this->mysqlThreadId &&
this->mysqlThreadId != mysql_thread_id(this->hMysql)) {
if(verbosity > 1) {
syslog(LOG_INFO, "diff thread_id -> force reconnect");
}
this->reconnect();
}
}
bool rslt = false;
this->cleanFields();
unsigned int attempt = 1;
for(unsigned int pass = 0; pass < this->maxQueryPass; pass++) {
string preparedQuery = this->prepareQuery(query, !callFromStoreProcessWithFixDeadlock && attempt > 1);
if(attempt == 1 && verbosity > 1) {
syslog(LOG_INFO, prepareQueryForPrintf(preparedQuery).c_str());
}
if(pass > 0) {
if(is_terminating()) {
usleep(100000);
} else {
sleep(1);
}
syslog(LOG_INFO, "next attempt %u - query: %s", attempt - 1, prepareQueryForPrintf(preparedQuery).c_str());
}
if(!this->connected()) {
this->connect();
}
if(this->connected()) {
if(mysql_query(this->hMysqlConn, preparedQuery.c_str())) {
if(verbosity > 1) {
syslog(LOG_NOTICE, "query error - query: %s", prepareQueryForPrintf(preparedQuery).c_str());
syslog(LOG_NOTICE, "query error - error: %s", mysql_error(this->hMysql));
}
this->checkLastError("query error in [" + preparedQuery.substr(0,200) + (preparedQuery.size() > 200 ? "..." : "") + "]", !sql_noerror && !this->disableLogError);
if(!sql_noerror && !this->disableLogError && (verbosity > 1 || sverb.query_error)) {
cout << endl << "ERROR IN QUERY: " << endl
<< preparedQuery << endl;
}
if(this->connecting) {
break;
} else {
if(this->getLastError() == CR_SERVER_GONE_ERROR ||
this->getLastError() == ER_NO_PARTITION_FOR_GIVEN_VALUE) {
if(pass < this->maxQueryPass - 1) {
this->reconnect();
}
} else if(sql_noerror || sql_disable_next_attempt_if_error ||
this->disableLogError || this->disableNextAttemptIfError ||
this->getLastError() == ER_PARSE_ERROR ||
this->getLastError() == ER_NO_REFERENCED_ROW_2 ||
(callFromStoreProcessWithFixDeadlock && this->getLastError() == ER_LOCK_DEADLOCK)) {
break;
} else {
if(this->getLastError() == ER_SP_ALREADY_EXISTS) {
if(!mysql_query(this->hMysqlConn, "repair table mysql.proc")) {
syslog(LOG_NOTICE, "success call 'repair table mysql.proc'");
MYSQL_RES *res = mysql_use_result(this->hMysqlConn);
if(res) {
while(mysql_fetch_row(res));
mysql_free_result(res);
}
} else {
syslog(LOG_NOTICE, "failed call 'repair table mysql.proc' with error: %s", mysql_error(this->hMysqlConn));
}
if(dropProcQuery) {
if(!mysql_query(this->hMysqlConn, dropProcQuery)) {
MYSQL_RES *res = mysql_use_result(this->hMysqlConn);
if(res) {
while(mysql_fetch_row(res));
mysql_free_result(res);
}
syslog(LOG_NOTICE, "success call '%s'", dropProcQuery);
++attempt;
continue;
} else {
syslog(LOG_NOTICE, "failed call '%s' with error: %s", dropProcQuery, mysql_error(this->hMysqlConn));
}
}
}
extern int opt_load_query_from_files;
if(!opt_load_query_from_files && pass < this->maxQueryPass - 5) {
pass = this->maxQueryPass - 5;
}
if(pass < this->maxQueryPass - 1) {
this->reconnect();
}
}
}
} else {
if(verbosity > 1) {
syslog(LOG_NOTICE, "query ok - %s", prepareQueryForPrintf(preparedQuery).c_str());
}
rslt = true;
break;
}
}
++attempt;
if(is_terminating() && attempt >= 2) {
break;
}
}
SqlDb::addDelayQuery(getTimeMS() - startTimeMS);
return(rslt);
}
SqlDb_row SqlDb_mysql::fetchRow(bool assoc) {
SqlDb_row row(this);
if(isCloud()) {