forked from RangeNetworks/CommonLibs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Configuration.cpp
1293 lines (1126 loc) · 34.3 KB
/
Configuration.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
/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
* Copyright 2011, 2012, 2014 Range Networks, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Configuration.h"
#include "Logger.h"
#include "Utils.h"
#include <fstream>
#include <iostream>
#include <string.h>
#ifdef DEBUG_CONFIG
#define debugLogEarly gLogEarly
#else
#define debugLogEarly(...)
#endif
using namespace std;
char gCmdName[20] = {0}; // Use a char* to avoid avoid static initialization of string, and race at startup.
static const char* createConfigTable = {
"CREATE TABLE IF NOT EXISTS CONFIG ("
"KEYSTRING TEXT UNIQUE NOT NULL, "
"VALUESTRING TEXT, "
"STATIC INTEGER DEFAULT 0, "
"OPTIONAL INTEGER DEFAULT 0, "
"COMMENTS TEXT DEFAULT ''"
")"
};
// (pat) LOG() may not be initialized yet, so use syslog directly.
#define LOGNOW(fmt,...) syslog(LOG_ERR, "ERR %s:" fmt,Utils::timestr().c_str(),__VA_ARGS__)
long ConfigurationRecord::number() const
{
if (mValue.size() == 0 && ! mCRWarned) {
LOGNOW("request for configuration key '%s' as number: configuration value is null", mCRKey.c_str());
mCRWarned = true;
return 0;
}
char *endptr;
long result = strtol(mValue.c_str(),&endptr,0);
if (*endptr && ! mCRWarned) {
// (pat) Warn if the number is invalid.
LOGNOW("request for configuration key '%s' as number: value could not be fully converted: '%s'", mCRKey.c_str(),mValue.c_str());
mCRWarned = true;
}
return result;
}
float ConfigurationRecord::floatNumber() const
{
if (mValue.size() == 0 && ! mCRWarned) {
LOGNOW("request for configuration key '%s' as float number: configuration value is null", mCRKey.c_str());
mCRWarned = true;
return 0;
}
//sscanf(mValue.c_str(),"%f",&val);
char *endptr;
float val = strtof(mValue.c_str(),&endptr);
if (*endptr && ! mCRWarned) {
// (pat) Warn if the number is invalid.
LOGNOW("request for configuration key '%s' as float number: value could not be fully converted: '%s'", mCRKey.c_str(),mValue.c_str());
mCRWarned = true;
}
return val;
}
ConfigurationTable::ConfigurationTable(const char* filename, const char *wCmdName, ConfigurationKeyMap wSchema)
{
gLogEarly(LOG_INFO, "opening configuration table from path %s", filename);
// Connect to the database.
int rc = sqlite3_open(filename,&mDB);
// (pat) When I used malloc here, sqlite3 sporadically crashes.
if (wCmdName) {
strncpy(gCmdName,wCmdName,18);
gCmdName[18] = 0;
strcat(gCmdName,":");
}
if (rc) {
gLogEarly(LOG_EMERG, "cannot open configuration database at %s, error message: %s", filename, sqlite3_errmsg(mDB));
sqlite3_close(mDB);
mDB = NULL;
return;
}
// Create the table, if needed.
if (!sqlite3_command(mDB,createConfigTable)) {
gLogEarly(LOG_EMERG, "cannot create configuration table in database at %s, error message: %s", filename, sqlite3_errmsg(mDB));
}
// Pat and David both do not want to use WAL mode on the config databases.
// Set high-concurrency WAL mode.
//if (!sqlite3_command(mDB,enableWAL)) {
// gLogEarly(LOG_EMERG, "cannot enable WAL mode on database at %s, error message: %s", filename, sqlite3_errmsg(mDB));
//}
// Build CommonLibs schema
ConfigurationKey *tmp;
tmp = new ConfigurationKey("Control.NumSQLTries","3",
"attempts",
ConfigurationKey::DEVELOPER,
ConfigurationKey::VALRANGE,
"1:10",// educated guess
false,
"Number of times to retry SQL queries before declaring a database access failure."
);
mSchema[tmp->getName()] = *tmp;
delete tmp;
tmp = new ConfigurationKey("Log.Alarms.Max","20",
"alarms",
ConfigurationKey::CUSTOMER,
ConfigurationKey::VALRANGE,
"10:20",// educated guess
false,
"Maximum number of alarms to remember inside the application."
);
mSchema[tmp->getName()] = *tmp;
delete tmp;
tmp = new ConfigurationKey("Log.File","",
"",
ConfigurationKey::DEVELOPER,
ConfigurationKey::FILEPATH_OPT,// audited
"",
false,
"Path to use for textfile based logging. "
"By default, this feature is disabled. "
"To enable, specify an absolute path to the file you wish to use, eg: /tmp/my-debug.log. "
"To disable again, execute \"unconfig Log.File\"."
);
mSchema[tmp->getName()] = *tmp;
delete tmp;
tmp = new ConfigurationKey("Log.Level","NOTICE",
"",
ConfigurationKey::CUSTOMER,
ConfigurationKey::CHOICE,
"EMERG|EMERGENCY - report serious faults associated with service failure or hardware damage,"
"ALERT|ALERT - report likely service disruption caused by misconfiguration or poor connectivity,"
"CRIT|CRITICAL - report anomalous events that are likely to degrade service,"
"ERR|ERROR - report internal errors of the software that may result in degradation of service in unusual circumstances,"
"WARNING|WARNING - report anomalous events that may indicate a degradation of normal service,"
"NOTICE|NOTICE - report anomalous events that probably do not affect service but may be of interest to network operators,"
"INFO|INFORMATION - report normal events,"
"DEBUG|DEBUG - only for use by developers and will degrade system performance",
false,
"Default logging level when no other level is defined for a file."
);
mSchema[tmp->getName()] = *tmp;
delete tmp;
// Add application specific schema
mSchema.insert(wSchema.begin(), wSchema.end());
// Init the cross checking callback to something predictable
mCrossCheck = NULL;
#define DUMP_CONFIGURATION_TABLE 1
#if DUMP_CONFIGURATION_TABLE
// (pat) Dump any non-default config variables...
try {
if (wCmdName == NULL) { wCmdName = ""; }
LOG(INFO) << wCmdName << ":" << " List of non-default config parameters:";
string snippet("");
ConfigurationKeyMap view = getSimilarKeys(snippet);
for (ConfigurationKeyMap::iterator it = view.begin(); it != view.end(); it++) {
string name = it->first;
ConfigurationKey key = it->second;
if (name != key.getName()) {
LOG(ALERT) << "SQL database is corrupt at name:"<<name <<" != key:"<<key.getName();
}
string defaultValue= key.getDefaultValue();
string value = this->getStr(name);
if (value != defaultValue) {
LOG(INFO) << "Config Variable"<<LOGVAR(name) <<LOGVAR(value) <<LOGVAR(defaultValue);
}
}
} catch (...) {
LOG(INFO) << wCmdName << ":" << " EXCEPTION CAUGHT";
}
#endif
}
string ConfigurationTable::getDefaultSQL(const std::string& program, const std::string& version)
{
stringstream ss;
ConfigurationKeyMap::iterator mp;
ss << "--" << endl;
ss << "-- This file was generated using: " << program << " --gensql" << endl;
ss << "-- binary version: " << version << endl;
ss << "--" << endl;
ss << "-- Future changes should not be put in this file directly but" << endl;
ss << "-- rather in the program's ConfigurationKey schema." << endl;
ss << "--" << endl;
ss << "PRAGMA foreign_keys=OFF;" << endl;
//ss << "PRAGMA journal_mode=WAL;" << endl;
ss << "BEGIN TRANSACTION;" << endl;
ss << "CREATE TABLE IF NOT EXISTS CONFIG ( KEYSTRING TEXT UNIQUE NOT NULL, VALUESTRING TEXT, STATIC INTEGER DEFAULT 0, OPTIONAL INTEGER DEFAULT 0, COMMENTS TEXT DEFAULT '');" << endl;
mp = mSchema.begin();
while (mp != mSchema.end()) {
ss << "INSERT OR IGNORE INTO \"CONFIG\" VALUES(";
// name
ss << "'" << mp->first << "',";
// default
ss << "'" << mp->second.getDefaultValue() << "',";
// static
if (mp->second.isStatic()) {
ss << "1";
} else {
ss << "0";
}
ss << ",";
// optional
ss << "0,";
// description
const string description = mp->second.getDescription();
// Try to use a quote that will work: if the description contains ' quote with " else '.
// This is not perfect because these quotes could themselves be quoted.
const char * quote = string::npos != description.find('\'') ? "\"" : "'";
ss << quote;
if (mp->second.getType() == ConfigurationKey::BOOLEAN) {
ss << "1=enabled, 0=disabled - ";
}
ss << mp->second.getDescription();
if (mp->second.isStatic()) {
ss << " Static.";
}
ss << quote;
ss << ");" << endl;
mp++;
}
ss << "COMMIT;" << endl;
ss << endl;
return ss.str();
}
string ConfigurationTable::getTeX(const std::string& program, const std::string& version)
{
stringstream ss;
ConfigurationKeyMap::iterator mp;
ss << "% START AUTO-GENERATED CONTENT" << endl;
ss << "% -- these sections were generated using: " << program << " --gentex" << endl;
ss << "% -- binary version: " << version << endl;
ss << "\\section{Customer Site Parameters}" << endl;
ss << "These parameters must be changed to fit your site." << endl;
ss << "\\begin{itemize}" << endl;
mp = mSchema.begin();
while (mp != mSchema.end()) {
if (mp->second.getVisibility() == ConfigurationKey::CUSTOMERSITE) {
ss << " \\item \\texttt{";
// name
ss << mp->first << "} -- ";
// description
ss << mp->second.getDescription();
ss << endl;
}
mp++;
}
ss << "\\end{itemize}" << endl;
ss << endl;
ss << "\\section{Customer Tuneable Parameters}" << endl;
ss << "These parameters can be changed to optimize your site." << endl;
ss << "\\begin{itemize}" << endl;
mp = mSchema.begin();
while (mp != mSchema.end()) {
if (mp->second.getVisibility() != ConfigurationKey::CUSTOMERSITE &&
(
mp->second.getVisibility() == ConfigurationKey::CUSTOMER ||
mp->second.getVisibility() == ConfigurationKey::CUSTOMERTUNE ||
mp->second.getVisibility() == ConfigurationKey::CUSTOMERWARN
)) {
ss << " \\item \\texttt{";
// name
ss << mp->first << "} -- ";
// description
ss << mp->second.getDescription();
ss << endl;
}
mp++;
}
ss << "\\end{itemize}" << endl;
ss << endl;
ss << "\\section{Developer/Factory Parameters}" << endl;
ss << "These parameters should only be changed by when developing new code." << endl;
ss << "\\begin{itemize}" << endl;
mp = mSchema.begin();
while (mp != mSchema.end()) {
if (mp->second.getVisibility() == ConfigurationKey::FACTORY ||
mp->second.getVisibility() == ConfigurationKey::DEVELOPER) {
ss << " \\item \\texttt{";
// name
ss << mp->first << "} -- ";
// description
ss << mp->second.getDescription();
ss << endl;
}
mp++;
}
ss << "\\end{itemize}" << endl;
ss << "% END AUTO-GENERATED CONTENT" << endl;
ss << endl;
string tmp = Utils::replaceAll(ss.str(), "^", "\\^");
return Utils::replaceAll(tmp, "_", "\\_");
}
bool ConfigurationTable::defines(const string& key)
{
try {
ScopedLock lock(mLock);
return lookup(key).defined();
} catch (ConfigurationTableKeyNotFound) {
// TODO: re-enable once we figure out why this message is being sent to syslog regardless of log level
//gLogEarly(LOG_DEBUG, "configuration parameter %s not found", key.c_str());
return false;
}
}
bool ConfigurationTable::keyDefinedInSchema(const std::string& name)
{
return mSchema.find(name) == mSchema.end() ? false : true;
}
bool ConfigurationTable::isValidValue(const std::string& name, const std::string& val) {
bool ret = false;
ConfigurationKey key = mSchema[name];
switch (key.getType()) {
case ConfigurationKey::BOOLEAN: {
if (val == "1" || val == "0") {
ret = true;
}
break;
}
case ConfigurationKey::CHOICE_OPT: {
if (val.length() == 0) {
ret = true;
break;
}
}
case ConfigurationKey::CHOICE: {
int startPos = -1;
uint endPos = 0;
std::string tmp = key.getValidValues();
do {
startPos++;
if ((endPos = tmp.find('|', startPos)) != std::string::npos) {
if (val == tmp.substr(startPos, endPos-startPos)) {
ret = true;
break;
}
} else {
if (val == tmp.substr(startPos, tmp.find(',', startPos)-startPos)) {
ret = true;
break;
}
}
} while ((startPos = tmp.find(',', startPos)) != (int)std::string::npos);
break;
}
case ConfigurationKey::CIDR_OPT: {
if (val.length() == 0) {
ret = true;
break;
}
}
case ConfigurationKey::CIDR: {
uint delimiter;
std::string ip;
int cidr = -1;
delimiter = val.find('/');
if (delimiter != std::string::npos) {
ip = val.substr(0, delimiter);
std::stringstream(val.substr(delimiter+1)) >> cidr;
if (ConfigurationKey::isValidIP(ip) && 0 <= cidr && cidr <= 32) {
ret = true;
}
}
break;
}
case ConfigurationKey::FILEPATH_OPT: {
if (val.length() == 0) {
ret = true;
break;
}
}
case ConfigurationKey::FILEPATH: {
regex_t r;
const char* expression = "^[a-zA-Z0-9/_.-]+$";
int result = regcomp(&r, expression, REG_EXTENDED);
if (result) {
char msg[256];
regerror(result,&r,msg,255);
break;//abort();
}
if (regexec(&r, val.c_str(), 0, NULL, 0)==0) {
ret = true;
}
regfree(&r);
break;
}
case ConfigurationKey::HOSTANDPORT_OPT: {
if (val.length() == 0) {
ret = true;
break;
}
}
case ConfigurationKey::HOSTANDPORT: {
uint delimiter;
std::string host;
int port = -1;
bool validHost = false;
delimiter = val.find(':');
if (delimiter != std::string::npos) {
host = val.substr(0, delimiter);
std::stringstream(val.substr(delimiter+1)) >> port;
if (ConfigurationKey::isValidIP(host)) {
validHost = true;
} else {
regex_t r;
const char* expression = "^[a-zA-Z0-9_.-]+$";
int result = regcomp(&r, expression, REG_EXTENDED);
if (result) {
char msg[256];
regerror(result,&r,msg,255);
break;//abort();
}
if (regexec(&r, host.c_str(), 0, NULL, 0)==0) {
validHost = true;
}
regfree(&r);
}
if (validHost && 1 <= port && port <= 65535) {
ret = true;
}
}
break;
}
case ConfigurationKey::IPADDRESS_OPT: {
if (val.length() == 0) {
ret = true;
break;
}
}
case ConfigurationKey::IPADDRESS: {
ret = ConfigurationKey::isValidIP(val);
break;
}
case ConfigurationKey::IPANDPORT: {
uint delimiter;
std::string ip;
int port = -1;
delimiter = val.find(':');
if (delimiter != std::string::npos) {
ip = val.substr(0, delimiter);
std::stringstream(val.substr(delimiter+1)) >> port;
if (ConfigurationKey::isValidIP(ip) && 1 <= port && port <= 65535) {
ret = true;
}
}
break;
}
case ConfigurationKey::MIPADDRESS_OPT: {
if (val.length() == 0) {
ret = true;
break;
}
}
case ConfigurationKey::MIPADDRESS: {
int startPos = -1;
uint endPos = 0;
uint delimiter;
std::string ip;
int port = -1;
do {
startPos++;
endPos = val.find(' ', startPos);
port = -1;
if (ConfigurationKey::isValidIP(val.substr(startPos, endPos-startPos))) {
ret = true;
} else {
delimiter = val.find(':');
if (delimiter != std::string::npos) {
ip = val.substr(startPos, delimiter);
std::stringstream(val.substr(delimiter+1, endPos)) >> port;
if (ConfigurationKey::isValidIP(ip) && 1 <= port && port <= 65535) {
ret = true;
} else {
ret = false;
break;
}
} else {
ret = false;
break;
}
}
} while ((startPos = endPos) != (int)std::string::npos);
break;
}
case ConfigurationKey::PORT_OPT: {
if (val.length() == 0) {
ret = true;
break;
}
}
case ConfigurationKey::PORT: {
int intVal;
std::stringstream(val) >> intVal;
if (1 <= intVal && intVal <= 65535) {
ret = true;
}
break;
}
case ConfigurationKey::REGEX_OPT: {
if (val.length() == 0) {
ret = true;
break;
}
}
case ConfigurationKey::REGEX: {
regex_t r;
const char* expression = val.c_str();
int result = regcomp(&r, expression, REG_EXTENDED);
if (result) {
char msg[256];
regerror(result,&r,msg,255);
} else {
ret = true;
}
regfree(&r);
break;
}
case ConfigurationKey::STRING_OPT: {
if (val.length() == 0) {
ret = true;
break;
}
}
case ConfigurationKey::STRING: {
regex_t r;
const char* expression = key.getValidValues().c_str();
int result = regcomp(&r, expression, REG_EXTENDED);
if (result) {
char msg[256];
regerror(result,&r,msg,255);
break;//abort();
}
if (regexec(&r, val.c_str(), 0, NULL, 0)==0) {
ret = true;
}
regfree(&r);
break;
}
case ConfigurationKey::VALRANGE: {
regex_t r;
int result;
if (key.getValidValues().find('.') != std::string::npos) {
result = regcomp(&r, "^[0-9.-]+$", REG_EXTENDED);
} else {
result = regcomp(&r, "^[0-9-]+$", REG_EXTENDED);
}
if (result) {
char msg[256];
regerror(result,&r,msg,255);
break;//abort();
}
if (regexec(&r, val.c_str(), 0, NULL, 0)!=0) {
ret = false;
} else if (key.getValidValues().find('.') != std::string::npos) {
ret = ConfigurationKey::isInValRange<float>(key, val, false);
} else {
ret = ConfigurationKey::isInValRange<int>(key, val, true);
}
regfree(&r);
break;
}
}
return ret;
}
ConfigurationKeyMap ConfigurationTable::getSimilarKeys(const std::string& snippet) {
ConfigurationKeyMap tmp;
ConfigurationKeyMap::const_iterator mp = mSchema.begin();
while (mp != mSchema.end()) {
if (mp->first.find(snippet) != std::string::npos) {
tmp[mp->first] = mp->second;
}
mp++;
}
return tmp;
}
const ConfigurationRecord& ConfigurationTable::lookup(const string& key)
{
assert(mDB);
checkCacheAge();
// We assume the caller holds mLock.
// So it is OK to return a reference into the cache.
// Check the cache.
// This is cheap.
ConfigurationMap::const_iterator where = mCache.find(key);
if (where!=mCache.end()) {
if (where->second.defined()) return where->second;
throw ConfigurationTableKeyNotFound(key);
}
// Check the database.
// This is more expensive.
char *value = NULL;
sqlite3_single_lookup(mDB,"CONFIG",
"KEYSTRING",key.c_str(),"VALUESTRING",value);
// (pat 9-2014) If sqlite3_single_lookup returns false, the behavior below is incorrect.
// value found, cache the result
if (value) {
mCache[key] = ConfigurationRecord(key,value);
// key definition found, cache the default
} else if (keyDefinedInSchema(key)) {
mCache[key] = ConfigurationRecord(key,mSchema[key].getDefaultValue());
// total miss, cache the error
} else {
mCache[key] = ConfigurationRecord(key,false);
throw ConfigurationTableKeyNotFound(key);
}
if (value) free(value);
// Leave mLock locked. The caller holds it still.
return mCache[key];
}
bool ConfigurationTable::isStatic(const string& key)
{
if (keyDefinedInSchema(key)) {
return mSchema[key].isStatic();
} else {
return false;
}
}
string ConfigurationTable::getStr(const string& key)
{
// We need the lock because rec is a reference into the cache.
try {
ScopedLock lock(mLock);
return lookup(key).value();
} catch (ConfigurationTableKeyNotFound) {
// Raise an alert and re-throw the exception.
gLogEarly(LOG_DEBUG, "configuration parameter %s has no defined value", key.c_str());
throw ConfigurationTableKeyNotFound(key);
}
}
bool ConfigurationTable::getBool(const string& key)
{
try {
return getNum(key) != 0;
} catch (ConfigurationTableKeyNotFound) {
// Raise an alert and re-throw the exception.
gLogEarly(LOG_DEBUG, "configuration parameter %s has no defined value", key.c_str());
throw ConfigurationTableKeyNotFound(key);
}
}
long ConfigurationTable::getNum(const string& key)
{
// We need the lock because rec is a reference into the cache.
try {
ScopedLock lock(mLock);
return lookup(key).number();
} catch (ConfigurationTableKeyNotFound) {
// Raise an alert and re-throw the exception.
gLogEarly(LOG_DEBUG, "configuration parameter %s has no defined value", key.c_str());
throw ConfigurationTableKeyNotFound(key);
}
}
float ConfigurationTable::getFloat(const string& key)
{
try {
ScopedLock lock(mLock);
return lookup(key).floatNumber();
} catch (ConfigurationTableKeyNotFound) {
// Raise an alert and re-throw the exception.
gLogEarly(LOG_DEBUG, "configuration parameter %s has no defined value", key.c_str());
throw ConfigurationTableKeyNotFound(key);
}
}
std::vector<string> ConfigurationTable::getVectorOfStrings(const string& key)
{
// Look up the string.
char *line=NULL;
try {
ScopedLock lock(mLock);
const ConfigurationRecord& rec = lookup(key);
line = strdup(rec.value().c_str());
} catch (ConfigurationTableKeyNotFound) {
// Raise an alert and re-throw the exception.
gLogEarly(LOG_DEBUG, "configuration parameter %s has no defined value", key.c_str());
throw ConfigurationTableKeyNotFound(key);
}
assert(line);
char *lp = line;
// Parse the string.
std::vector<string> retVal;
while (lp) {
while (*lp==' ') lp++;
if (*lp == '\0') break;
char *tp = strsep(&lp," ");
if (!tp) break;
retVal.push_back(tp);
}
free(line);
return retVal;
}
std::vector<unsigned> ConfigurationTable::getVector(const string& key)
{
// Look up the string.
char *line=NULL;
try {
ScopedLock lock(mLock);
const ConfigurationRecord& rec = lookup(key);
line = strdup(rec.value().c_str());
} catch (ConfigurationTableKeyNotFound) {
// Raise an alert and re-throw the exception.
gLogEarly(LOG_DEBUG, "configuration parameter %s has no defined value", key.c_str());
throw ConfigurationTableKeyNotFound(key);
}
assert(line);
char *lp = line;
// Parse the string.
std::vector<unsigned> retVal;
while (lp) {
// Watch for multiple or trailing spaces.
while (*lp==' ') lp++;
if (*lp=='\0') break;
retVal.push_back(strtol(lp,NULL,0));
strsep(&lp," ");
}
free(line);
return retVal;
}
bool ConfigurationTable::remove(const string& key)
{
assert(mDB);
ScopedLock lock(mLock);
// Clear the cache entry and the database.
ConfigurationMap::iterator where = mCache.find(key);
if (where!=mCache.end()) mCache.erase(where);
// Really remove it.
string cmd = "DELETE FROM CONFIG WHERE KEYSTRING=='"+key+"'";
return sqlite3_command(mDB,cmd.c_str());
}
void ConfigurationTable::find(const string& pat, ostream& os) const
{
// Prepare the statement.
string cmd = "SELECT KEYSTRING,VALUESTRING FROM CONFIG WHERE KEYSTRING LIKE \"%" + pat + "%\"";
sqlite3_stmt *stmt;
if (sqlite3_prepare_statement(mDB,&stmt,cmd.c_str())) return;
// Read the result.
int src = sqlite3_run_query(mDB,stmt);
while (src==SQLITE_ROW) {
const char* value = (const char*)sqlite3_column_text(stmt,1);
os << sqlite3_column_text(stmt,0) << " ";
int len = 0;
if (value) {
len = strlen(value);
}
if (len && value) os << value << endl;
else os << "(disabled)" << endl;
src = sqlite3_run_query(mDB,stmt);
}
sqlite3_finalize(stmt);
}
ConfigurationRecordMap ConfigurationTable::getAllPairs() const
{
ConfigurationRecordMap tmp;
// Prepare the statement.
string cmd = "SELECT KEYSTRING,VALUESTRING FROM CONFIG";
sqlite3_stmt *stmt;
if (sqlite3_prepare_statement(mDB,&stmt,cmd.c_str())) return tmp;
// Read the result.
int src = sqlite3_run_query(mDB,stmt);
while (src==SQLITE_ROW) {
const char* key = (const char*)sqlite3_column_text(stmt,0);
const char* value = (const char*)sqlite3_column_text(stmt,1);
if (key && value) {
string skey(key);
tmp[skey] = ConfigurationRecord(skey,value);
} else if (key && !value) {
string skey(key);
tmp[skey] = ConfigurationRecord(skey,false);
}
src = sqlite3_run_query(mDB,stmt);
}
sqlite3_finalize(stmt);
return tmp;
}
bool ConfigurationTable::set(const string& key, const string& value)
{
assert(mDB);
ScopedLock lock(mLock);
string cmd;
if (keyDefinedInSchema(key)) {
cmd = "INSERT OR REPLACE INTO CONFIG (KEYSTRING,VALUESTRING,OPTIONAL,COMMENTS) VALUES (\"" + key + "\",\"" + value + "\",1,\'" + mSchema[key].getDescription() + "\')";
} else {
cmd = "INSERT OR REPLACE INTO CONFIG (KEYSTRING,VALUESTRING,OPTIONAL) VALUES (\"" + key + "\",\"" + value + "\",1)";
}
bool success = sqlite3_command(mDB,cmd.c_str());
// Cache the result.
if (success) mCache[key] = ConfigurationRecord(key,value);
return success;
}
bool ConfigurationTable::set(const string& key, long value)
{
char buffer[30];
sprintf(buffer,"%ld",value);
return set(key,buffer);
}
void ConfigurationTable::checkCacheAge()
{
// mLock is set by caller
static time_t timeOfLastPurge = 0;
time_t now = time(NULL);
// purge every 3 seconds
// purge period cannot be configuration parameter
if (now - timeOfLastPurge < 3) return;
timeOfLastPurge = now;
// this is purge() without the lock
ConfigurationMap::iterator mp = mCache.begin();
while (mp != mCache.end()) {
ConfigurationMap::iterator prev = mp;
mp++;
mCache.erase(prev);
}
}
void ConfigurationTable::purge()
{
ScopedLock lock(mLock);
ConfigurationMap::iterator mp = mCache.begin();
while (mp != mCache.end()) {
ConfigurationMap::iterator prev = mp;
mp++;
mCache.erase(prev);
}
}
void ConfigurationTable::setUpdateHook(void(*func)(void *,int ,char const *,char const *,sqlite3_int64))
{
assert(mDB);
sqlite3_update_hook(mDB,func,NULL);
}
void ConfigurationTable::setCrossCheckHook(vector<string> (*wCrossCheck)(const string&))
{
mCrossCheck = wCrossCheck;
}
vector<string> ConfigurationTable::crossCheck(const string& key) {
vector<string> ret;
if (mCrossCheck != NULL) {
ret = mCrossCheck(key);
}
return ret;
}
void HashString::computeHash()
{
// FIXME -- Someone needs to review this hash function.
const char* cstr = c_str();
mHash = 0;
for (unsigned i=0; i<size(); i++) {
mHash = mHash ^ (mHash >> 32);
mHash = mHash*127 + cstr[i];
}
}
void SimpleKeyValue::addItem(const char* pair_orig)
{
char *pair = strdup(pair_orig);
char *key = pair;
char *mark = strchr(pair,'=');
if (!mark) return;
*mark = '\0';
char *value = mark+1;
mMap[key] = value;
free(pair);
}
const char* SimpleKeyValue::get(const char* key) const
{
HashStringMap::const_iterator p = mMap.find(key);
if (p==mMap.end()) return NULL;
return p->second.c_str();