/
db_handler.cc
1892 lines (1734 loc) · 69.7 KB
/
db_handler.cc
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 (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <exception>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/uuid/name_generator.hpp>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <base/logging.h>
#include <io/event_manager.h>
#include <base/connection_info.h>
#include <sandesh/sandesh_types.h>
#include <sandesh/sandesh.h>
#include <sandesh/sandesh_message_builder.h>
#include <sandesh/protocol/TXMLProtocol.h>
#ifdef USE_CASSANDRA_CQL
#include <database/cassandra/cql/cql_if.h>
#else // USE_CASSANDRA_CQL
#include <database/cassandra/thrift/thrift_if.h>
#endif // !USE_CASSANDRA_CQL
#include <zookeeper/zookeeper_client.h>
#include "viz_constants.h"
#include "vizd_table_desc.h"
#include "viz_collector.h"
#include "collector.h"
#include "db_handler.h"
#include "parser_util.h"
#include "db_handler_impl.h"
#include "viz_sandesh.h"
#define DB_LOG(_Level, _Msg) \
do { \
if (LoggingDisabled()) break; \
log4cplus::Logger _Xlogger = log4cplus::Logger::getRoot(); \
if (_Xlogger.isEnabledFor(log4cplus::_Level##_LOG_LEVEL)) { \
log4cplus::tostringstream _Xbuf; \
_Xbuf << name_ << ": " << __func__ << ": " << _Msg; \
_Xlogger.forcedLog(log4cplus::_Level##_LOG_LEVEL, \
_Xbuf.str()); \
} \
} while (false)
using std::pair;
using std::string;
using boost::system::error_code;
using namespace pugi;
using namespace contrail::sandesh::protocol;
using process::ConnectionState;
using process::ConnectionType;
using process::ConnectionStatus;
uint32_t DbHandler::field_cache_t2_ = 0;
std::set<std::string> DbHandler::field_cache_set_[2];
uint32_t DbHandler::field_cache_old_t2_ = 0;
uint8_t DbHandler::old_t2_index_ = 0;
uint8_t DbHandler::new_t2_index_ = 1;
tbb::mutex DbHandler::fmutex_;
DbHandler::DbHandler(EventManager *evm,
GenDb::GenDbIf::DbErrorHandler err_handler,
const std::vector<std::string> &cassandra_ips,
const std::vector<int> &cassandra_ports,
std::string name, const TtlMap& ttl_map,
const std::string& cassandra_user,
const std::string& cassandra_password,
const std::string &cassandra_compaction_strategy,
const std::string &cassandra_flow_tables_compaction_strategy,
bool use_cql, const std::string &zookeeper_server_list,
bool use_zookeeper, bool disable_all_writes,
bool disable_statistics_writes, bool disable_messages_writes,
bool disable_messages_keyword_writes) :
name_(name),
drop_level_(SandeshLevel::INVALID),
ttl_map_(ttl_map),
use_cql_(use_cql),
tablespace_(),
compaction_strategy_(cassandra_compaction_strategy),
flow_tables_compaction_strategy_(cassandra_flow_tables_compaction_strategy),
gen_partition_no_((uint8_t)g_viz_constants.PARTITION_MIN,
(uint8_t)g_viz_constants.PARTITION_MAX),
zookeeper_server_list_(zookeeper_server_list),
use_zookeeper_(use_zookeeper),
disable_all_writes_(disable_all_writes),
disable_statistics_writes_(disable_statistics_writes),
disable_messages_writes_(disable_messages_writes),
disable_messages_keyword_writes_(disable_messages_keyword_writes) {
#ifdef USE_CASSANDRA_CQL
if (use_cql) {
dbif_.reset(new cass::cql::CqlIf(evm, cassandra_ips,
cassandra_ports[0], cassandra_user, cassandra_password));
tablespace_ = g_viz_constants.COLLECTOR_KEYSPACE_CQL;
} else {
#else // USE_CASSANDRA_CQL
dbif_.reset(new ThriftIf(err_handler,
cassandra_ips, cassandra_ports, name, false,
cassandra_user, cassandra_password));
tablespace_ = g_viz_constants.COLLECTOR_KEYSPACE;
#endif // !USE_CASSANDRA_CQL
#ifdef USE_CASSANDRA_CQL
}
#endif // USE_CASSANDRA_CQL
error_code error;
col_name_ = boost::asio::ip::host_name(error);
}
DbHandler::DbHandler(GenDb::GenDbIf *dbif, const TtlMap& ttl_map) :
dbif_(dbif),
ttl_map_(ttl_map),
gen_partition_no_((uint8_t)g_viz_constants.PARTITION_MIN,
(uint8_t)g_viz_constants.PARTITION_MAX),
disable_all_writes_(false),
disable_statistics_writes_(false),
disable_messages_writes_(false),
disable_messages_keyword_writes_(false) {
}
DbHandler::~DbHandler() {
}
uint64_t DbHandler::GetTtlInHourFromMap(const TtlMap& ttl_map,
TtlType::type type) {
TtlMap::const_iterator it = ttl_map.find(type);
if (it != ttl_map.end()) {
return it->second;
} else {
return 0;
}
}
uint64_t DbHandler::GetTtlFromMap(const TtlMap& ttl_map,
TtlType::type type) {
TtlMap::const_iterator it = ttl_map.find(type);
if (it != ttl_map.end()) {
return it->second*3600;
} else {
return 0;
}
}
std::string DbHandler::GetName() const {
return name_;
}
std::vector<boost::asio::ip::tcp::endpoint> DbHandler::GetEndpoints() const {
return dbif_->Db_GetEndpoints();
}
bool DbHandler::DropMessage(const SandeshHeader &header,
const VizMsg *vmsg) {
bool drop(DoDropSandeshMessage(header, drop_level_));
if (drop) {
tbb::mutex::scoped_lock lock(smutex_);
dropped_msg_stats_.Update(vmsg);
}
return drop;
}
void DbHandler::SetDropLevel(size_t queue_count, SandeshLevel::type level,
boost::function<void (void)> cb) {
if (drop_level_ != level) {
DB_LOG(INFO, "DB DROP LEVEL: [" <<
Sandesh::LevelToString(drop_level_) << "] -> [" <<
Sandesh::LevelToString(level) << "], DB QUEUE COUNT: " <<
queue_count);
drop_level_ = level;
}
// Always invoke the callback
if (!cb.empty()) {
cb();
}
}
bool DbHandler::CreateTables() {
for (std::vector<GenDb::NewCf>::const_iterator it = vizd_tables.begin();
it != vizd_tables.end(); it++) {
if (!dbif_->Db_AddColumnfamily(*it, compaction_strategy_)) {
DB_LOG(ERROR, it->cfname_ << " FAILED");
return false;
}
}
for (std::vector<GenDb::NewCf>::const_iterator it = vizd_flow_tables.begin();
it != vizd_flow_tables.end(); it++) {
if (!dbif_->Db_AddColumnfamily(*it, flow_tables_compaction_strategy_)) {
DB_LOG(ERROR, it->cfname_ << " FAILED");
return false;
}
}
for (std::vector<GenDb::NewCf>::const_iterator it = vizd_stat_tables.begin();
it != vizd_stat_tables.end(); it++) {
if (!dbif_->Db_AddColumnfamily(*it, compaction_strategy_)) {
DB_LOG(ERROR, it->cfname_ << " FAILED");
return false;
}
}
GenDb::ColList col_list;
std::string cfname = g_viz_constants.SYSTEM_OBJECT_TABLE;
GenDb::DbDataValueVec key;
key.push_back(g_viz_constants.SYSTEM_OBJECT_ANALYTICS);
bool init_done = false;
if (dbif_->Db_GetRow(&col_list, cfname, key)) {
for (GenDb::NewColVec::iterator it = col_list.columns_.begin();
it != col_list.columns_.end(); it++) {
std::string col_name;
try {
col_name = boost::get<std::string>(it->name->at(0));
} catch (boost::bad_get& ex) {
DB_LOG(ERROR, cfname << ": Column Name Get FAILED");
}
if (col_name == g_viz_constants.SYSTEM_OBJECT_START_TIME) {
init_done = true;
}
}
}
if (!init_done) {
std::auto_ptr<GenDb::ColList> col_list(new GenDb::ColList);
col_list->cfname_ = g_viz_constants.SYSTEM_OBJECT_TABLE;
// Rowkey
GenDb::DbDataValueVec& rowkey = col_list->rowkey_;
rowkey.reserve(1);
rowkey.push_back(g_viz_constants.SYSTEM_OBJECT_ANALYTICS);
// Columns
GenDb::NewColVec& columns = col_list->columns_;
columns.reserve(4);
uint64_t current_tm = UTCTimestampUsec();
GenDb::NewCol *col(new GenDb::NewCol(
g_viz_constants.SYSTEM_OBJECT_START_TIME, current_tm, 0));
columns.push_back(col);
GenDb::NewCol *flow_col(new GenDb::NewCol(
g_viz_constants.SYSTEM_OBJECT_FLOW_START_TIME, current_tm, 0));
columns.push_back(flow_col);
GenDb::NewCol *msg_col(new GenDb::NewCol(
g_viz_constants.SYSTEM_OBJECT_MSG_START_TIME, current_tm, 0));
columns.push_back(msg_col);
GenDb::NewCol *stat_col(new GenDb::NewCol(
g_viz_constants.SYSTEM_OBJECT_STAT_START_TIME, current_tm, 0));
columns.push_back(stat_col);
if (!dbif_->Db_AddColumnSync(col_list)) {
DB_LOG(ERROR, g_viz_constants.SYSTEM_OBJECT_TABLE <<
": Start Time Column Add FAILED");
return false;
}
}
/*
* add ttls to cassandra to be retrieved by other daemons
*/
{
std::auto_ptr<GenDb::ColList> col_list(new GenDb::ColList);
col_list->cfname_ = g_viz_constants.SYSTEM_OBJECT_TABLE;
// Rowkey
GenDb::DbDataValueVec& rowkey = col_list->rowkey_;
rowkey.reserve(1);
rowkey.push_back(g_viz_constants.SYSTEM_OBJECT_ANALYTICS);
// Columns
GenDb::NewColVec& columns = col_list->columns_;
columns.reserve(4);
GenDb::NewCol *col(new GenDb::NewCol(
g_viz_constants.SYSTEM_OBJECT_FLOW_DATA_TTL, (uint64_t)DbHandler::GetTtlInHourFromMap(ttl_map_, TtlType::FLOWDATA_TTL), 0));
columns.push_back(col);
GenDb::NewCol *flow_col(new GenDb::NewCol(
g_viz_constants.SYSTEM_OBJECT_STATS_DATA_TTL, (uint64_t)DbHandler::GetTtlInHourFromMap(ttl_map_, TtlType::STATSDATA_TTL), 0));
columns.push_back(flow_col);
GenDb::NewCol *msg_col(new GenDb::NewCol(
g_viz_constants.SYSTEM_OBJECT_CONFIG_AUDIT_TTL, (uint64_t)DbHandler::GetTtlInHourFromMap(ttl_map_, TtlType::CONFIGAUDIT_TTL), 0));
columns.push_back(msg_col);
GenDb::NewCol *stat_col(new GenDb::NewCol(
g_viz_constants.SYSTEM_OBJECT_GLOBAL_DATA_TTL, (uint64_t)DbHandler::GetTtlInHourFromMap(ttl_map_, TtlType::GLOBAL_TTL), 0));
columns.push_back(stat_col);
if (!dbif_->Db_AddColumnSync(col_list)) {
DB_LOG(ERROR, g_viz_constants.SYSTEM_OBJECT_TABLE <<
": TTL Column Add FAILED");
return false;
}
}
return true;
}
void DbHandler::UnInit(int instance) {
dbif_->Db_Uninit("analytics::DbHandler", instance);
dbif_->Db_SetInitDone(false);
}
// The caller *SHOULD* ensure that UnInit() is not called from another
// task that can be executed in parallel.
void DbHandler::UnInitUnlocked(int instance) {
dbif_->Db_UninitUnlocked("analytics::DbHandler", instance);
dbif_->Db_SetInitDone(false);
}
bool DbHandler::Init(bool initial, int instance) {
SetDropLevel(0, SandeshLevel::INVALID, NULL);
if (initial) {
return Initialize(instance);
} else {
return Setup(instance);
}
}
bool DbHandler::InitializeInternal(int instance) {
DB_LOG(DEBUG, "Initializing..");
/* init of vizd table structures */
init_vizd_tables(use_cql_);
if (!dbif_->Db_Init("analytics::DbHandler", instance)) {
DB_LOG(ERROR, "Connection to DB FAILED");
return false;
}
if (!dbif_->Db_AddSetTablespace(tablespace_, "2")) {
DB_LOG(ERROR, "Create/Set KEYSPACE: " << tablespace_ << " FAILED");
return false;
}
if (!CreateTables()) {
DB_LOG(ERROR, "CreateTables FAILED");
return false;
}
dbif_->Db_SetInitDone(true);
DB_LOG(DEBUG, "Initializing Done");
return true;
}
bool DbHandler::InitializeInternalLocked(int instance) {
// Synchronize creation across nodes using zookeeper
zookeeper::client::ZookeeperClient client(name_.c_str(),
zookeeper_server_list_.c_str());
zookeeper::client::ZookeeperLock dmutex(&client, "/collector");
assert(dmutex.Lock());
bool success(InitializeInternal(instance));
assert(dmutex.Release());
return success;
}
bool DbHandler::Initialize(int instance) {
if (use_zookeeper_) {
return InitializeInternalLocked(instance);
} else {
return InitializeInternal(instance);
}
}
bool DbHandler::Setup(int instance) {
DB_LOG(DEBUG, "Setup..");
if (!dbif_->Db_Init("analytics::DbHandler",
instance)) {
DB_LOG(ERROR, "Connection to DB FAILED");
return false;
}
if (!dbif_->Db_SetTablespace(tablespace_)) {
DB_LOG(ERROR, "Set KEYSPACE: " << tablespace_ << " FAILED");
return false;
}
for (std::vector<GenDb::NewCf>::const_iterator it = vizd_tables.begin();
it != vizd_tables.end(); it++) {
if (!dbif_->Db_UseColumnfamily(*it)) {
DB_LOG(ERROR, it->cfname_ <<
": Db_UseColumnfamily FAILED");
return false;
}
}
for (std::vector<GenDb::NewCf>::const_iterator it = vizd_flow_tables.begin();
it != vizd_flow_tables.end(); it++) {
if (!dbif_->Db_UseColumnfamily(*it)) {
DB_LOG(ERROR, it->cfname_ << ": Db_UseColumnfamily FAILED");
return false;
}
}
for (std::vector<GenDb::NewCf>::const_iterator it = vizd_stat_tables.begin();
it != vizd_stat_tables.end(); it++) {
if (!dbif_->Db_UseColumnfamily(*it)) {
DB_LOG(ERROR, it->cfname_ << ": Db_UseColumnfamily FAILED");
return false;
}
}
dbif_->Db_SetInitDone(true);
DB_LOG(DEBUG, "Setup Done");
return true;
}
bool DbHandler::UseCql() const {
return use_cql_;
}
bool DbHandler::IsAllWritesDisabled() const {
return disable_all_writes_;
}
bool DbHandler::IsStatisticsWritesDisabled() const {
return disable_statistics_writes_;
}
bool DbHandler::IsMessagesWritesDisabled() const {
return disable_messages_writes_;
}
bool DbHandler::IsMessagesKeywordWritesDisabled() const {
return disable_messages_keyword_writes_;
}
void DbHandler::DisableAllWrites(bool disable) {
disable_all_writes_ = disable;
}
void DbHandler::DisableStatisticsWrites(bool disable) {
disable_statistics_writes_ = disable;
}
void DbHandler::DisableMessagesWrites(bool disable) {
disable_messages_writes_ = disable;
}
void DbHandler::DisableMessagesKeywordWrites(bool disable) {
disable_messages_keyword_writes_ = disable;
}
void DbHandler::SetDbQueueWaterMarkInfo(Sandesh::QueueWaterMarkInfo &wm,
boost::function<void (void)> defer_undefer_cb) {
dbif_->Db_SetQueueWaterMark(boost::get<2>(wm),
boost::get<0>(wm),
boost::bind(&DbHandler::SetDropLevel, this, _1, boost::get<1>(wm),
defer_undefer_cb));
}
void DbHandler::ResetDbQueueWaterMarkInfo() {
dbif_->Db_ResetQueueWaterMarks();
}
void DbHandler::GetSandeshStats(std::string *drop_level,
std::vector<SandeshStats> *vdropmstats) const {
*drop_level = Sandesh::LevelToString(drop_level_);
if (vdropmstats) {
tbb::mutex::scoped_lock lock(smutex_);
dropped_msg_stats_.Get(vdropmstats);
}
}
bool DbHandler::GetStats(uint64_t *queue_count, uint64_t *enqueues) const {
return dbif_->Db_GetQueueStats(queue_count, enqueues);
}
bool DbHandler::GetStats(std::vector<GenDb::DbTableInfo> *vdbti,
GenDb::DbErrors *dbe, std::vector<GenDb::DbTableInfo> *vstats_dbti) {
{
tbb::mutex::scoped_lock lock(smutex_);
stable_stats_.GetDiffs(vstats_dbti);
}
return dbif_->Db_GetStats(vdbti, dbe);
}
bool DbHandler::GetCumulativeStats(std::vector<GenDb::DbTableInfo> *vdbti,
GenDb::DbErrors *dbe, std::vector<GenDb::DbTableInfo> *vstats_dbti) const {
{
tbb::mutex::scoped_lock lock(smutex_);
stable_stats_.GetCumulative(vstats_dbti);
}
return dbif_->Db_GetCumulativeStats(vdbti, dbe);
}
bool DbHandler::GetCqlMetrics(cass::cql::Metrics *metrics) const {
if (!UseCql()) {
return false;
}
cass::cql::CqlIf *cql_if(dynamic_cast<cass::cql::CqlIf *>(dbif_.get()));
if (cql_if == NULL) {
return false;
}
cql_if->Db_GetCqlMetrics(metrics);
return true;
}
bool DbHandler::GetCqlStats(cass::cql::DbStats *stats) const {
if (!UseCql()) {
return false;
}
cass::cql::CqlIf *cql_if(dynamic_cast<cass::cql::CqlIf *>(dbif_.get()));
if (cql_if == NULL) {
return false;
}
cql_if->Db_GetCqlStats(stats);
return true;
}
bool DbHandler::InsertIntoDb(std::auto_ptr<GenDb::ColList> col_list,
GenDb::GenDbIf::DbAddColumnCb db_cb) {
if (IsAllWritesDisabled()) {
return true;
}
return dbif_->Db_AddColumn(col_list, db_cb);
}
bool DbHandler::AllowMessageTableInsert(const SandeshHeader &header) {
return !IsMessagesWritesDisabled() && !IsAllWritesDisabled() &&
(header.get_Type() != SandeshType::FLOW);
}
bool DbHandler::MessageIndexTableInsert(const std::string& cfname,
const SandeshHeader& header,
const std::string& message_type,
const boost::uuids::uuid& unm,
const std::string keyword,
GenDb::GenDbIf::DbAddColumnCb db_cb) {
std::auto_ptr<GenDb::ColList> col_list(new GenDb::ColList);
col_list->cfname_ = cfname;
// Rowkey
GenDb::DbDataValueVec& rowkey = col_list->rowkey_;
#ifdef USE_CASSANDRA_CQL
rowkey.reserve(2);
uint32_t T2(header.get_Timestamp() >> g_viz_constants.RowTimeInBits);
rowkey.push_back(T2);
//Push partition into row key
rowkey.push_back(gen_partition_no_());
// Columns
GenDb::DbDataValueVec *col_name(new GenDb::DbDataValueVec());
col_name->reserve(3);
int ttl;
if (message_type == "VncApiConfigLog") {
ttl = GetTtl(TtlType::CONFIGAUDIT_TTL);
} else {
ttl = GetTtl(TtlType::GLOBAL_TTL);
}
if (cfname == g_viz_constants.MESSAGE_TABLE_SOURCE) {
col_name->push_back(header.get_Source());
} else if (cfname == g_viz_constants.MESSAGE_TABLE_MODULE_ID) {
col_name->push_back(header.get_Module());
} else if (cfname == g_viz_constants.MESSAGE_TABLE_CATEGORY) {
col_name->push_back(header.get_Category());
} else if (cfname == g_viz_constants.MESSAGE_TABLE_MESSAGE_TYPE) {
col_name->push_back(message_type);
} else if (cfname == g_viz_constants.MESSAGE_TABLE_TIMESTAMP) {
} else if (cfname == g_viz_constants.MESSAGE_TABLE_KEYWORD) {
if (keyword.length()) {
col_name->push_back(keyword);
} else {
return false;
}
} else {
DB_LOG(ERROR, "Unknown table: " << cfname << ", message: "
<< message_type << ", message UUID: " << unm);
return false;
}
uint32_t T1(header.get_Timestamp() & g_viz_constants.RowTimeInMask);
col_name->push_back(T1);
col_name->push_back(unm);
//No value to be stored against the columns
GenDb::DbDataValueVec *col_value(new GenDb::DbDataValueVec(0));
GenDb::NewCol *col(new GenDb::NewCol(col_name, col_value, ttl));
GenDb::NewColVec& columns = col_list->columns_;
columns.reserve(1);
columns.push_back(col);
#else
rowkey.reserve(8);
uint32_t T2(header.get_Timestamp() >> g_viz_constants.RowTimeInBits);
rowkey.push_back(T2);
if (cfname == g_viz_constants.MESSAGE_TABLE_SOURCE) {
rowkey.push_back(header.get_Source());
} else if (cfname == g_viz_constants.MESSAGE_TABLE_MODULE_ID) {
rowkey.push_back(header.get_Module());
} else if (cfname == g_viz_constants.MESSAGE_TABLE_CATEGORY) {
rowkey.push_back(header.get_Category());
} else if (cfname == g_viz_constants.MESSAGE_TABLE_MESSAGE_TYPE) {
rowkey.push_back(message_type);
} else if (cfname == g_viz_constants.MESSAGE_TABLE_TIMESTAMP) {
} else if (cfname == g_viz_constants.MESSAGE_TABLE_KEYWORD) {
if (keyword.length())
rowkey.push_back(keyword);
else
return false;
} else {
DB_LOG(ERROR, "Unknown table: " << cfname << ", message: "
<< message_type << ", message UUID: " << unm);
return false;
}
// Columns
GenDb::NewColVec& columns = col_list->columns_;
columns.reserve(1);
uint32_t T1(header.get_Timestamp() & g_viz_constants.RowTimeInMask);
GenDb::DbDataValueVec *col_name(new GenDb::DbDataValueVec(1, T1));
GenDb::DbDataValueVec *col_value(new GenDb::DbDataValueVec(1, unm));
int ttl;
if (message_type == "VncApiConfigLog") {
ttl = GetTtl(TtlType::CONFIGAUDIT_TTL);
} else {
ttl = GetTtl(TtlType::GLOBAL_TTL);
}
GenDb::NewCol *col(new GenDb::NewCol(col_name, col_value, ttl));
columns.push_back(col);
#endif
if (!InsertIntoDb(col_list, db_cb)) {
DB_LOG(ERROR, "Addition of message: " << message_type <<
", message UUID: " << unm << " to table: " << cfname <<
" FAILED");
return false;
}
return true;
}
void DbHandler::MessageTableOnlyInsert(const VizMsg *vmsgp,
GenDb::GenDbIf::DbAddColumnCb db_cb) {
const SandeshHeader &header(vmsgp->msg->GetHeader());
const std::string &message_type(vmsgp->msg->GetMessageType());
uint64_t temp_u64;
uint32_t temp_u32;
std::string temp_str;
int ttl;
if (message_type == "VncApiConfigLog") {
ttl = GetTtl(TtlType::CONFIGAUDIT_TTL);
} else {
ttl = GetTtl(TtlType::GLOBAL_TTL);
}
std::auto_ptr<GenDb::ColList> col_list(new GenDb::ColList);
col_list->cfname_ = g_viz_constants.COLLECTOR_GLOBAL_TABLE;
// Rowkey
GenDb::DbDataValueVec& rowkey = col_list->rowkey_;
rowkey.reserve(1);
rowkey.push_back(vmsgp->unm);
// Columns
GenDb::NewColVec& columns = col_list->columns_;
columns.reserve(16);
columns.push_back(new GenDb::NewCol(g_viz_constants.SOURCE,
header.get_Source(), ttl));
columns.push_back(new GenDb::NewCol(g_viz_constants.NAMESPACE,
header.get_Namespace(), ttl));
columns.push_back(new GenDb::NewCol(g_viz_constants.MODULE,
header.get_Module(), ttl));
if (!header.get_Context().empty()) {
columns.push_back(new GenDb::NewCol(g_viz_constants.CONTEXT,
header.get_Context(), ttl));
}
if (!header.get_InstanceId().empty()) {
columns.push_back(new GenDb::NewCol(g_viz_constants.INSTANCE_ID,
header.get_InstanceId(), ttl));
}
if (!header.get_NodeType().empty()) {
columns.push_back(new GenDb::NewCol(g_viz_constants.NODE_TYPE,
header.get_NodeType(), ttl));
}
if (header.__isset.IPAddress) {
columns.push_back(new GenDb::NewCol(g_viz_constants.IPADDRESS,
header.get_IPAddress(), ttl));
}
// Convert to network byte order
temp_u64 = header.get_Timestamp();
columns.push_back(new GenDb::NewCol(g_viz_constants.TIMESTAMP, temp_u64, ttl));
columns.push_back(new GenDb::NewCol(g_viz_constants.CATEGORY,
header.get_Category(), ttl));
temp_u32 = header.get_Level();
columns.push_back(new GenDb::NewCol(g_viz_constants.LEVEL, temp_u32, ttl));
columns.push_back(new GenDb::NewCol(g_viz_constants.MESSAGE_TYPE,
message_type, ttl));
temp_u32 = header.get_SequenceNum();
columns.push_back(new GenDb::NewCol(g_viz_constants.SEQUENCE_NUM,
temp_u32, ttl));
temp_u32 = header.get_VersionSig();
columns.push_back(new GenDb::NewCol(g_viz_constants.VERSION, temp_u32, ttl));
uint8_t temp_u8 = header.get_Type();
columns.push_back(new GenDb::NewCol(g_viz_constants.SANDESH_TYPE,
temp_u8, ttl));
if (header.__isset.Pid) {
temp_u32 = header.get_Pid();
columns.push_back(new GenDb::NewCol(g_viz_constants.PID,
temp_u32, ttl));
}
columns.push_back(new GenDb::NewCol(g_viz_constants.DATA,
vmsgp->msg->ExtractMessage(), ttl));
if (!InsertIntoDb(col_list, db_cb)) {
DB_LOG(ERROR, "Addition of message: " << message_type <<
", message UUID: " << vmsgp->unm << " COLUMN FAILED");
return;
}
}
void DbHandler::MessageTableKeywordInsert(const VizMsg *vmsgp,
GenDb::GenDbIf::DbAddColumnCb db_cb) {
if (IsMessagesKeywordWritesDisabled() ||
IsAllWritesDisabled()) {
return;
}
LineParser::WordListType words;
const SandeshHeader &header(vmsgp->msg->GetHeader());
const std::string &message_type(vmsgp->msg->GetMessageType());
const SandeshType::type &stype(header.get_Type());
if (stype == SandeshType::SYSTEM || stype == SandeshType::UVE ||
stype == SandeshType::OBJECT) {
const SandeshXMLMessage *sxmsg =
static_cast<const SandeshXMLMessage *>(vmsgp->msg);
words = LineParser::ParseXML(sxmsg->GetMessageNode(), false);
} else if (!vmsgp->keyword_doc_.empty()) {
std::string s;
s = std::string(vmsgp->keyword_doc_);
if (!s.empty()) {
words = LineParser::Parse(s);
}
}
for (LineParser::WordListType::iterator i = words.begin();
i != words.end(); i++) {
// tableinsert@{(t2,*i), (t1,header.get_Source())} -> vmsgp->unm
bool r = MessageIndexTableInsert(
g_viz_constants.MESSAGE_TABLE_KEYWORD, header,
message_type, vmsgp->unm, *i, db_cb);
if (!r)
DB_LOG(ERROR, "Failed to parse:");
}
}
void DbHandler::MessageTableInsert(const VizMsg *vmsgp,
GenDb::GenDbIf::DbAddColumnCb db_cb) {
const SandeshHeader &header(vmsgp->msg->GetHeader());
const std::string &message_type(vmsgp->msg->GetMessageType());
if (!AllowMessageTableInsert(header))
return;
MessageTableOnlyInsert(vmsgp, db_cb);
MessageIndexTableInsert(g_viz_constants.MESSAGE_TABLE_SOURCE, header,
message_type, vmsgp->unm, "", db_cb);
MessageIndexTableInsert(g_viz_constants.MESSAGE_TABLE_MODULE_ID, header,
message_type, vmsgp->unm, "", db_cb);
MessageIndexTableInsert(g_viz_constants.MESSAGE_TABLE_CATEGORY, header,
message_type, vmsgp->unm, "", db_cb);
MessageIndexTableInsert(g_viz_constants.MESSAGE_TABLE_MESSAGE_TYPE, header,
message_type, vmsgp->unm, "", db_cb);
MessageIndexTableInsert(g_viz_constants.MESSAGE_TABLE_TIMESTAMP, header,
message_type, vmsgp->unm, "", db_cb);
MessageTableKeywordInsert(vmsgp, db_cb);
const SandeshType::type &stype(header.get_Type());
/*
* Insert the message types,module_id in the stat table
* Construct the atttributes,attrib_tags beofore inserting
* to the StatTableInsert
*/
if ((stype == SandeshType::SYSLOG) || (stype == SandeshType::SYSTEM)) {
//Insert only if sandesh type is a SYSTEM LOG or SYSLOG
//Insert into the FieldNames stats table entries for Messagetype and Module ID
int ttl = GetTtl(TtlType::GLOBAL_TTL);
FieldNamesTableInsert(header.get_Timestamp(),
g_viz_constants.COLLECTOR_GLOBAL_TABLE,
":Messagetype", message_type, ttl, db_cb);
FieldNamesTableInsert(header.get_Timestamp(),
g_viz_constants.COLLECTOR_GLOBAL_TABLE,
":ModuleId", header.get_Module(), ttl, db_cb);
FieldNamesTableInsert(header.get_Timestamp(),
g_viz_constants.COLLECTOR_GLOBAL_TABLE,
":Source", header.get_Source(), ttl, db_cb);
}
}
/*
* This function takes field name and field value as arguments and inserts
* into the FieldNames stats table
*/
void DbHandler::FieldNamesTableInsert(uint64_t timestamp,
const std::string& table_prefix,
const std::string& field_name, const std::string& field_val, int ttl,
GenDb::GenDbIf::DbAddColumnCb db_cb) {
/*
* Insert the message types in the stat table
* Construct the atttributes,attrib_tags before inserting
* to the StatTableInsert
*/
uint32_t temp_u32 = timestamp >> g_viz_constants.RowTimeInBits;
std::string table_name(table_prefix);
table_name.append(field_name);
/* Check if fieldname and value were already seen in this T2;
2 caches are mainted one for last T2 and T2-1.
We only need to record them if they have NOT been seen yet */
bool record = false;
std::string fc_entry(table_name);
fc_entry.append(":");
fc_entry.append(field_val);
{
tbb::mutex::scoped_lock lock(fmutex_);
record = CanRecordDataForT2(temp_u32, fc_entry);
}
if (!record) return;
DbHandler::TagMap tmap;
DbHandler::AttribMap amap;
DbHandler::Var pv;
DbHandler::AttribMap attribs;
pv = table_name;
tmap.insert(make_pair("name", make_pair(pv, amap)));
attribs.insert(make_pair(string("name"), pv));
string sattrname("fields.value");
pv = string(field_val);
attribs.insert(make_pair(sattrname,pv));
//pv = string(header.get_Source());
// Put the name of the collector, not the message source.
// Using the message source will make queries slower
pv = string(col_name_);
tmap.insert(make_pair("Source",make_pair(pv,amap)));
attribs.insert(make_pair(string("Source"),pv));
StatTableInsertTtl(timestamp, "FieldNames","fields", tmap, attribs, ttl,
db_cb);
}
/*
* This function checks if the data can be recorded or not
* for the given t2. If t2 corresponding to the data is
* older than field_cache_old_t2_ and field_cache_t2_
* it is ignored
*/
bool DbHandler::CanRecordDataForT2(uint32_t temp_u32, std::string fc_entry) {
bool record = false;
if (temp_u32 > field_cache_t2_) {
// swap old and new index; clear the old cache
old_t2_index_ = new_t2_index_;
new_t2_index_ = (new_t2_index_ == 1)?0:1;
field_cache_old_t2_ = field_cache_t2_;
field_cache_set_[new_t2_index_].clear();
field_cache_t2_ = temp_u32;
} else if (temp_u32 > field_cache_old_t2_ && temp_u32 != field_cache_t2_){
field_cache_set_[old_t2_index_].clear();
field_cache_old_t2_ = temp_u32;
}
// Record only if not found in last or last but one T2 cache.
if (temp_u32 == field_cache_t2_) {
if (field_cache_set_[new_t2_index_].find(fc_entry) ==
field_cache_set_[new_t2_index_].end()) {
field_cache_set_[new_t2_index_].insert(fc_entry);
record = true;
}
} else if (temp_u32 == field_cache_old_t2_) {
if (field_cache_set_[old_t2_index_].find(fc_entry) ==
field_cache_set_[old_t2_index_].end()) {
field_cache_set_[old_t2_index_].insert(fc_entry);
record = true;
}
}
return record;
}
void DbHandler::GetRuleMap(RuleMap& rulemap) {
}
/*
* insert an entry into an ObjectTrace table
* key is T2
* column is
* name: <key>:T1 (value in timestamp)
* value: uuid (of the corresponding global message)
*/
void DbHandler::ObjectTableInsert(const std::string &table, const std::string &objectkey_str,
uint64_t ×tamp, const boost::uuids::uuid& unm, const VizMsg *vmsgp,
GenDb::GenDbIf::DbAddColumnCb db_cb) {
if (IsMessagesWritesDisabled() || IsAllWritesDisabled()) {
return;
}
uint32_t T2(timestamp >> g_viz_constants.RowTimeInBits);
uint32_t T1(timestamp & g_viz_constants.RowTimeInMask);
const std::string &message_type(vmsgp->msg->GetMessageType());
int ttl;
if (message_type == "VncApiConfigLog") {
ttl = GetTtl(TtlType::CONFIGAUDIT_TTL);
} else {
ttl = GetTtl(TtlType::GLOBAL_TTL);
}
{
uint8_t partition_no = 0;
std::auto_ptr<GenDb::ColList> col_list(new GenDb::ColList);
col_list->cfname_ = g_viz_constants.OBJECT_TABLE;
GenDb::DbDataValueVec& rowkey = col_list->rowkey_;
rowkey.reserve(3);
rowkey.push_back(T2);
rowkey.push_back(partition_no);
rowkey.push_back(table);
GenDb::DbDataValueVec *col_name(new GenDb::DbDataValueVec());
col_name->reserve(2);
col_name->push_back(objectkey_str);
col_name->push_back(T1);
GenDb::DbDataValueVec *col_value(new GenDb::DbDataValueVec(1, unm));
GenDb::NewCol *col(new GenDb::NewCol(col_name, col_value, ttl));
GenDb::NewColVec& columns = col_list->columns_;
columns.reserve(1);
columns.push_back(col);
if (!InsertIntoDb(col_list, db_cb)) {
DB_LOG(ERROR, "Addition of " << objectkey_str <<
", message UUID " << unm << " into table " << table <<
" FAILED");
return;
}
}
{
std::auto_ptr<GenDb::ColList> col_list(new GenDb::ColList);
col_list->cfname_ = g_viz_constants.OBJECT_VALUE_TABLE;
GenDb::DbDataValueVec& rowkey = col_list->rowkey_;
rowkey.reserve(2);
rowkey.push_back(T2);
rowkey.push_back(table);
GenDb::DbDataValueVec *col_name(new GenDb::DbDataValueVec(1, T1));
GenDb::DbDataValueVec *col_value(new GenDb::DbDataValueVec(1, objectkey_str));
GenDb::NewCol *col(new GenDb::NewCol(col_name, col_value, ttl));
GenDb::NewColVec& columns = col_list->columns_;
columns.reserve(1);
columns.push_back(col);
if (!InsertIntoDb(col_list, db_cb)) {
DB_LOG(ERROR, "Addition of " << objectkey_str <<
", message UUID " << unm << " " << table << " into table "
<< g_viz_constants.OBJECT_VALUE_TABLE << " FAILED");
return;
}
/*
* Inserting into the stat table
*/
const SandeshHeader &header(vmsgp->msg->GetHeader());
const std::string &message_type(vmsgp->msg->GetMessageType());
//Insert into the FieldNames stats table entries for Messagetype and Module ID
FieldNamesTableInsert(timestamp,
table, ":ObjectId", objectkey_str, ttl, db_cb);
FieldNamesTableInsert(timestamp,
table, ":Messagetype", message_type, ttl, db_cb);
FieldNamesTableInsert(timestamp,
table, ":ModuleId", header.get_Module(), ttl, db_cb);
FieldNamesTableInsert(timestamp,
table, ":Source", header.get_Source(), ttl, db_cb);
FieldNamesTableInsert(timestamp,
"OBJECT:", table, table, ttl, db_cb);
}
}
bool DbHandler::StatTableWrite(uint32_t t2,
const std::string& statName, const std::string& statAttr,
const std::pair<std::string,DbHandler::Var>& ptag,
const std::pair<std::string,DbHandler::Var>& stag,
uint32_t t1, const boost::uuids::uuid& unm,
const std::string& jsonline, int ttl,
GenDb::GenDbIf::DbAddColumnCb db_cb) {
uint8_t part = 0;
string cfname;
const DbHandler::Var& pv = ptag.second;
const DbHandler::Var& sv = stag.second;
GenDb::DbDataValue pg,sg;
bool bad_suffix = false;
switch (pv.type) {
case DbHandler::STRING : {
pg = pv.str;
if (sv.type==DbHandler::STRING) {
cfname = g_viz_constants.STATS_TABLE_BY_STR_STR_TAG;
sg = sv.str;
} else if (sv.type==DbHandler::UINT64) {
cfname = g_viz_constants.STATS_TABLE_BY_STR_U64_TAG;
sg = sv.num;
} else if (sv.type==DbHandler::INVALID) {
cfname = g_viz_constants.STATS_TABLE_BY_STR_TAG;
} else {
bad_suffix = true;
}
}