forked from llxisdsh/mongo_db_plugin_mt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongo_db_plugin.cpp
More file actions
1680 lines (1449 loc) · 70.2 KB
/
mongo_db_plugin.cpp
File metadata and controls
1680 lines (1449 loc) · 70.2 KB
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
/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <eosio/mongo_db_plugin/mongo_db_plugin.hpp>
#include <eosio/chain/eosio_contract.hpp>
#include <eosio/chain/config.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/transaction.hpp>
#include <eosio/chain/types.hpp>
#include <fc/io/json.hpp>
#include <fc/utf8.hpp>
#include <fc/variant.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/chrono.hpp>
#include <boost/signals2/connection.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/tss.hpp>
#include <queue>
#include <vector>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/exception/exception.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/pool.hpp>
#include <mongocxx/exception/operation_exception.hpp>
#include <mongocxx/exception/logic_error.hpp>
namespace fc { class variant; }
namespace eosio {
using chain::account_name;
using chain::action_name;
using chain::block_id_type;
using chain::permission_name;
using chain::transaction;
using chain::signed_transaction;
using chain::signed_block;
using chain::transaction_id_type;
using chain::packed_transaction;
static appbase::abstract_plugin& _mongo_db_plugin = app().register_plugin<mongo_db_plugin>();
struct filter_entry {
name receiver;
name action;
name actor;
friend bool operator<( const filter_entry& a, const filter_entry& b ) {
return std::tie( a.receiver, a.action, a.actor ) < std::tie( b.receiver, b.action, b.actor );
}
// receiver action actor
bool match( const name& rr, const name& an, const name& ar ) const {
return (receiver.value == 0 || receiver == rr) &&
(action.value == 0 || action == an) &&
(actor.value == 0 || actor == ar);
}
};
class mongo_db_plugin_impl {
public:
mongo_db_plugin_impl();
~mongo_db_plugin_impl();
fc::optional<boost::signals2::scoped_connection> accepted_block_connection;
fc::optional<boost::signals2::scoped_connection> irreversible_block_connection;
fc::optional<boost::signals2::scoped_connection> accepted_transaction_connection;
fc::optional<boost::signals2::scoped_connection> applied_transaction_connection;
void consume_blocks();
void accepted_block( const chain::block_state_ptr& );
void applied_irreversible_block(const chain::block_state_ptr&);
void accepted_transaction(const chain::transaction_metadata_ptr&);
void applied_transaction(const chain::transaction_trace_ptr&);
void process_accepted_transaction(const chain::transaction_metadata_ptr&);
void _process_accepted_transaction(const chain::transaction_metadata_ptr&);
void process_applied_transaction(const chain::transaction_trace_ptr&);
void _process_applied_transaction(const chain::transaction_trace_ptr&);
void process_accepted_block( const chain::block_state_ptr& );
void _process_accepted_block( const chain::block_state_ptr& );
void process_irreversible_block(const chain::block_state_ptr&);
void _process_irreversible_block(const chain::block_state_ptr&);
optional<abi_serializer> get_abi_serializer( account_name n );
template<typename T> fc::variant to_variant_with_abi( const T& obj );
void purge_abi_cache();
bool add_action_trace( mongocxx::bulk_write& bulk_action_traces, const chain::action_trace& atrace,
const chain::transaction_trace_ptr& t,
bool executed, const std::chrono::milliseconds& now,
bool& write_ttrace );
void update_account(const chain::action& act);
void add_pub_keys( const vector<chain::key_weight>& keys, const account_name& name,
const permission_name& permission, const std::chrono::milliseconds& now );
void remove_pub_keys( const account_name& name, const permission_name& permission );
void add_account_control( const vector<chain::permission_level_weight>& controlling_accounts,
const account_name& name, const permission_name& permission,
const std::chrono::milliseconds& now );
void remove_account_control( const account_name& name, const permission_name& permission );
/// @return true if act should be added to mongodb, false to skip it
bool filter_include( const account_name& receiver, const action_name& act_name,
const vector<chain::permission_level>& authorization ) const;
bool filter_include( const transaction& trx ) const;
void init();
void wipe_database();
template<typename Queue, typename Entry> void queue(Queue& queue, const Entry& e);
bool configured{false};
bool wipe_database_on_startup{false};
uint32_t start_block_num = 0;
std::atomic_bool start_block_reached{false};
bool is_producer = false;
bool filter_on_star = true;
std::set<filter_entry> filter_on;
std::set<filter_entry> filter_out;
bool update_blocks_via_block_num = false;
bool store_blocks = true;
bool store_block_states = true;
bool store_transactions = true;
bool store_transaction_traces = true;
bool store_action_traces = true;
std::string db_name;
mongocxx::instance mongo_inst;
fc::optional<mongocxx::pool> mongo_pool;
// consum thread
boost::thread_specific_ptr<mongocxx::collection> _accounts;
boost::thread_specific_ptr<mongocxx::collection> _trans;
boost::thread_specific_ptr<mongocxx::collection> _trans_traces;
boost::thread_specific_ptr<mongocxx::collection> _action_traces;
boost::thread_specific_ptr<mongocxx::collection> _block_states;
boost::thread_specific_ptr<mongocxx::collection> _blocks;
boost::thread_specific_ptr<mongocxx::collection> _pub_keys;
boost::thread_specific_ptr<mongocxx::collection> _account_controls;
size_t max_thread_size = 1;
size_t max_queue_size = 0;
int queue_sleep_time = 0;
size_t abi_cache_size = 0;
std::deque<chain::transaction_metadata_ptr> transaction_metadata_queue;
boost::thread_specific_ptr<std::deque<chain::transaction_metadata_ptr>> transaction_metadata_process_queue;
std::deque<chain::transaction_trace_ptr> transaction_trace_queue;
boost::thread_specific_ptr<std::deque<chain::transaction_trace_ptr>> transaction_trace_process_queue;
std::deque<chain::block_state_ptr> block_state_queue;
boost::thread_specific_ptr<std::deque<chain::block_state_ptr>> block_state_process_queue;
std::deque<chain::block_state_ptr> irreversible_block_state_queue;
boost::thread_specific_ptr<std::deque<chain::block_state_ptr>> irreversible_block_state_process_queue;
boost::mutex mtx;
boost::condition_variable condition;
std::vector<boost::thread> consume_thread;
std::atomic_bool done{false};
std::atomic_bool startup{true};
fc::optional<chain::chain_id_type> chain_id;
fc::microseconds abi_serializer_max_time;
struct by_account;
struct by_last_access;
struct abi_cache {
account_name account;
fc::time_point last_accessed;
fc::optional<abi_serializer> serializer;
};
typedef boost::multi_index_container<abi_cache,
indexed_by<
ordered_unique< tag<by_account>, member<abi_cache,account_name,&abi_cache::account> >,
ordered_non_unique< tag<by_last_access>, member<abi_cache,fc::time_point,&abi_cache::last_accessed> >
>
> abi_cache_index_t;
boost::thread_specific_ptr<abi_cache_index_t> abi_cache_index;
static const action_name newaccount;
static const action_name setabi;
static const action_name updateauth;
static const action_name deleteauth;
static const permission_name owner;
static const permission_name active;
static const std::string block_states_col;
static const std::string blocks_col;
static const std::string trans_col;
static const std::string trans_traces_col;
static const std::string action_traces_col;
static const std::string accounts_col;
static const std::string pub_keys_col;
static const std::string account_controls_col;
};
const action_name mongo_db_plugin_impl::newaccount = chain::newaccount::get_name();
const action_name mongo_db_plugin_impl::setabi = chain::setabi::get_name();
const action_name mongo_db_plugin_impl::updateauth = chain::updateauth::get_name();
const action_name mongo_db_plugin_impl::deleteauth = chain::deleteauth::get_name();
const permission_name mongo_db_plugin_impl::owner = chain::config::owner_name;
const permission_name mongo_db_plugin_impl::active = chain::config::active_name;
const std::string mongo_db_plugin_impl::block_states_col = "block_states";
const std::string mongo_db_plugin_impl::blocks_col = "blocks";
const std::string mongo_db_plugin_impl::trans_col = "transactions";
const std::string mongo_db_plugin_impl::trans_traces_col = "transaction_traces";
const std::string mongo_db_plugin_impl::action_traces_col = "action_traces";
const std::string mongo_db_plugin_impl::accounts_col = "accounts";
const std::string mongo_db_plugin_impl::pub_keys_col = "pub_keys";
const std::string mongo_db_plugin_impl::account_controls_col = "account_controls";
bool mongo_db_plugin_impl::filter_include( const account_name& receiver, const action_name& act_name,
const vector<chain::permission_level>& authorization ) const
{
bool include = false;
if( filter_on_star ) {
include = true;
} else {
auto itr = std::find_if( filter_on.cbegin(), filter_on.cend(), [&receiver, &act_name]( const auto& filter ) {
return filter.match( receiver, act_name, 0 );
} );
if( itr != filter_on.cend() ) {
include = true;
} else {
for( const auto& a : authorization ) {
auto itr = std::find_if( filter_on.cbegin(), filter_on.cend(), [&receiver, &act_name, &a]( const auto& filter ) {
return filter.match( receiver, act_name, a.actor );
} );
if( itr != filter_on.cend() ) {
include = true;
break;
}
}
}
}
if( !include ) { return false; }
if( filter_out.empty() ) { return true; }
auto itr = std::find_if( filter_out.cbegin(), filter_out.cend(), [&receiver, &act_name]( const auto& filter ) {
return filter.match( receiver, act_name, 0 );
} );
if( itr != filter_out.cend() ) { return false; }
for( const auto& a : authorization ) {
auto itr = std::find_if( filter_out.cbegin(), filter_out.cend(), [&receiver, &act_name, &a]( const auto& filter ) {
return filter.match( receiver, act_name, a.actor );
} );
if( itr != filter_out.cend() ) { return false; }
}
return true;
}
bool mongo_db_plugin_impl::filter_include( const transaction& trx ) const
{
if( !filter_on_star || !filter_out.empty() ) {
bool include = false;
for( const auto& a : trx.actions ) {
if( filter_include( a.account, a.name, a.authorization ) ) {
include = true;
break;
}
}
if( !include ) {
for( const auto& a : trx.context_free_actions ) {
if( filter_include( a.account, a.name, a.authorization ) ) {
include = true;
break;
}
}
}
return include;
}
return true;
}
template<typename Queue, typename Entry>
void mongo_db_plugin_impl::queue( Queue& queue, const Entry& e ) {
boost::mutex::scoped_lock lock( mtx );
auto queue_size = queue.size();
if( queue_size > max_queue_size ) {
lock.unlock();
condition.notify_one();
queue_sleep_time += 10;
if( queue_sleep_time > 1000 )
wlog("queue size: ${q}", ("q", queue_size));
boost::this_thread::sleep_for( boost::chrono::milliseconds( queue_sleep_time ));
lock.lock();
} else {
queue_sleep_time -= 10;
if( queue_sleep_time < 0 ) queue_sleep_time = 0;
}
queue.emplace_back( e );
lock.unlock();
condition.notify_one();
}
void mongo_db_plugin_impl::accepted_transaction( const chain::transaction_metadata_ptr& t ) {
try {
if( store_transactions ) {
queue( transaction_metadata_queue, t );
}
} catch (fc::exception& e) {
elog("FC Exception while accepted_transaction ${e}", ("e", e.to_string()));
} catch (std::exception& e) {
elog("STD Exception while accepted_transaction ${e}", ("e", e.what()));
} catch (...) {
elog("Unknown exception while accepted_transaction");
}
}
void mongo_db_plugin_impl::applied_transaction( const chain::transaction_trace_ptr& t ) {
try {
// Traces emitted from an incomplete block leave the producer_block_id as empty.
//
// Avoid adding the action traces or transaction traces to the database if the producer_block_id is empty.
// This way traces from speculatively executed transactions are not included in the Mongo database which can
// avoid potential confusion for consumers of that database.
//
// Due to forks, it could be possible for multiple incompatible action traces with the same block_num and trx_id
// to exist in the database. And if the producer double produces a block, even the block_time may not
// disambiguate the two action traces. Without a producer_block_id to disambiguate and determine if the action
// trace comes from an orphaned fork branching off of the blockchain, consumers of the Mongo DB database may be
// reacting to a stale action trace that never actually executed in the current blockchain.
//
// It is better to avoid this potential confusion by not logging traces from speculative execution, i.e. emitted
// from an incomplete block. This means that traces will not be recorded in speculative read-mode, but
// users should not be using the mongo_db_plugin in that mode anyway.
//
// Allow logging traces if node is a producer for testing purposes, so a single nodeos can do both for testing.
//
// It is recommended to run mongo_db_plugin in read-mode = read-only.
//
if( !is_producer && !t->producer_block_id.valid() )
return;
// always queue since account information always gathered
queue( transaction_trace_queue, t );
} catch (fc::exception& e) {
elog("FC Exception while applied_transaction ${e}", ("e", e.to_string()));
} catch (std::exception& e) {
elog("STD Exception while applied_transaction ${e}", ("e", e.what()));
} catch (...) {
elog("Unknown exception while applied_transaction");
}
}
void mongo_db_plugin_impl::applied_irreversible_block( const chain::block_state_ptr& bs ) {
try {
if( store_blocks || store_block_states || store_transactions ) {
queue( irreversible_block_state_queue, bs );
}
} catch (fc::exception& e) {
elog("FC Exception while applied_irreversible_block ${e}", ("e", e.to_string()));
} catch (std::exception& e) {
elog("STD Exception while applied_irreversible_block ${e}", ("e", e.what()));
} catch (...) {
elog("Unknown exception while applied_irreversible_block");
}
}
void mongo_db_plugin_impl::accepted_block( const chain::block_state_ptr& bs ) {
try {
if( !start_block_reached ) {
if( bs->block_num >= start_block_num ) {
start_block_reached = true;
}
}
if( store_blocks || store_block_states ) {
queue( block_state_queue, bs );
}
} catch (fc::exception& e) {
elog("FC Exception while accepted_block ${e}", ("e", e.to_string()));
} catch (std::exception& e) {
elog("STD Exception while accepted_block ${e}", ("e", e.what()));
} catch (...) {
elog("Unknown exception while accepted_block");
}
}
void mongo_db_plugin_impl::consume_blocks() {
try {
//boost::mutex::scoped_lock lock_0(mtx);
auto mongo_client = mongo_pool->acquire();
auto& mongo_conn = *mongo_client;
_accounts.reset(new mongocxx::collection(mongo_conn[db_name][accounts_col]));
_trans.reset(new mongocxx::collection(mongo_conn[db_name][trans_col]));
_trans_traces.reset(new mongocxx::collection(mongo_conn[db_name][trans_traces_col]));
_action_traces.reset(new mongocxx::collection(mongo_conn[db_name][action_traces_col]));
_blocks.reset(new mongocxx::collection(mongo_conn[db_name][blocks_col]));
_block_states.reset(new mongocxx::collection(mongo_conn[db_name][block_states_col]));
_pub_keys.reset(new mongocxx::collection(mongo_conn[db_name][pub_keys_col]));
_account_controls.reset(new mongocxx::collection(mongo_conn[db_name][account_controls_col]));
transaction_metadata_process_queue.reset(new std::deque<chain::transaction_metadata_ptr>());
transaction_trace_process_queue.reset(new std::deque<chain::transaction_trace_ptr>());
block_state_process_queue.reset(new std::deque<chain::block_state_ptr>());
irreversible_block_state_process_queue.reset(new std::deque<chain::block_state_ptr>());
abi_cache_index.reset(new abi_cache_index_t());
//lock_0.unlock();
while (true) {
boost::mutex::scoped_lock lock(mtx);
while ( transaction_metadata_queue.empty() &&
transaction_trace_queue.empty() &&
block_state_queue.empty() &&
irreversible_block_state_queue.empty() &&
!done ) {
condition.wait(lock);
}
// capture for processing
size_t transaction_metadata_size = transaction_metadata_queue.size();
if (transaction_metadata_size > 0) {
(*transaction_metadata_process_queue) = move(transaction_metadata_queue);
transaction_metadata_queue.clear();
}
size_t transaction_trace_size = transaction_trace_queue.size();
if (transaction_trace_size > 0) {
(*transaction_trace_process_queue) = move(transaction_trace_queue);
transaction_trace_queue.clear();
}
size_t block_state_size = block_state_queue.size();
if (block_state_size > 0) {
(*block_state_process_queue) = move(block_state_queue);
block_state_queue.clear();
}
size_t irreversible_block_size = irreversible_block_state_queue.size();
if (irreversible_block_size > 0) {
(*irreversible_block_state_process_queue) = move(irreversible_block_state_queue);
irreversible_block_state_queue.clear();
}
lock.unlock();
if (done) {
ilog("draining queue, size: ${q}", ("q", transaction_metadata_size + transaction_trace_size + block_state_size + irreversible_block_size));
}
// process transactions
auto start_time = fc::time_point::now();
auto size = (*transaction_trace_process_queue).size();
while (!(*transaction_trace_process_queue).empty()) {
const auto& t = (*transaction_trace_process_queue).front();
process_applied_transaction(t);
(*transaction_trace_process_queue).pop_front();
}
auto time = fc::time_point::now() - start_time;
auto per = size > 0 ? time.count()/size : 0;
if( time > fc::microseconds(500000) ) // reduce logging, .5 secs
ilog( "process_applied_transaction, time per: ${p}, size: ${s}, time: ${t}", ("s", size)("t", time)("p", per) );
start_time = fc::time_point::now();
size = (*transaction_metadata_process_queue).size();
while (!(*transaction_metadata_process_queue).empty()) {
const auto& t = (*transaction_metadata_process_queue).front();
process_accepted_transaction(t);
(*transaction_metadata_process_queue).pop_front();
}
time = fc::time_point::now() - start_time;
per = size > 0 ? time.count()/size : 0;
if( time > fc::microseconds(500000) ) // reduce logging, .5 secs
ilog( "process_accepted_transaction, time per: ${p}, size: ${s}, time: ${t}", ("s", size)( "t", time )( "p", per ));
// process blocks
start_time = fc::time_point::now();
size = (*block_state_process_queue).size();
while (!(*block_state_process_queue).empty()) {
const auto& bs = (*block_state_process_queue).front();
process_accepted_block( bs );
(*block_state_process_queue).pop_front();
}
time = fc::time_point::now() - start_time;
per = size > 0 ? time.count()/size : 0;
if( time > fc::microseconds(500000) ) // reduce logging, .5 secs
ilog( "process_accepted_block, time per: ${p}, size: ${s}, time: ${t}", ("s", size)("t", time)("p", per) );
// process irreversible blocks
start_time = fc::time_point::now();
size = (*irreversible_block_state_process_queue).size();
while (!(*irreversible_block_state_process_queue).empty()) {
const auto& bs = (*irreversible_block_state_process_queue).front();
process_irreversible_block(bs);
(*irreversible_block_state_process_queue).pop_front();
}
time = fc::time_point::now() - start_time;
per = size > 0 ? time.count()/size : 0;
if( time > fc::microseconds(500000) ) // reduce logging, .5 secs
ilog( "process_irreversible_block, time per: ${p}, size: ${s}, time: ${t}", ("s", size)("t", time)("p", per) );
if( transaction_metadata_size == 0 &&
transaction_trace_size == 0 &&
block_state_size == 0 &&
irreversible_block_size == 0 &&
done ) {
break;
}
}
ilog("mongo_db_plugin consume thread shutdown gracefully");
} catch (fc::exception& e) {
elog("FC Exception while consuming block ${e}", ("e", e.to_string()));
} catch (std::exception& e) {
elog("STD Exception while consuming block ${e}", ("e", e.what()));
} catch (...) {
elog("Unknown exception while consuming block");
}
}
namespace {
auto find_account( mongocxx::collection& accounts, const account_name& name ) {
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::kvp;
return accounts.find_one( make_document( kvp( "name", name.to_string())));
}
auto find_block( mongocxx::collection& blocks, const string& id ) {
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::kvp;
mongocxx::options::find options;
options.projection( make_document( kvp( "_id", 1 )) ); // only return _id
return blocks.find_one( make_document( kvp( "block_id", id )), options);
}
void handle_mongo_exception( const std::string& desc, int line_num ) {
bool shutdown = true;
try {
try {
throw;
} catch( mongocxx::logic_error& e) {
// logic_error on invalid key, do not shutdown
wlog( "mongo logic error, ${desc}, line ${line}, code ${code}, ${what}",
("desc", desc)( "line", line_num )( "code", e.code().value() )( "what", e.what() ));
shutdown = false;
} catch( mongocxx::operation_exception& e) {
elog( "mongo exception, ${desc}, line ${line}, code ${code}, ${details}",
("desc", desc)( "line", line_num )( "code", e.code().value() )( "details", e.code().message() ));
if (e.raw_server_error()) {
elog( " raw_server_error: ${e}", ( "e", bsoncxx::to_json(e.raw_server_error()->view())));
}
} catch( mongocxx::exception& e) {
elog( "mongo exception, ${desc}, line ${line}, code ${code}, ${what}",
("desc", desc)( "line", line_num )( "code", e.code().value() )( "what", e.what() ));
} catch( bsoncxx::exception& e) {
elog( "bsoncxx exception, ${desc}, line ${line}, code ${code}, ${what}",
("desc", desc)( "line", line_num )( "code", e.code().value() )( "what", e.what() ));
} catch( fc::exception& er ) {
elog( "mongo fc exception, ${desc}, line ${line}, ${details}",
("desc", desc)( "line", line_num )( "details", er.to_detail_string()));
} catch( const std::exception& e ) {
elog( "mongo std exception, ${desc}, line ${line}, ${what}",
("desc", desc)( "line", line_num )( "what", e.what()));
} catch( ... ) {
elog( "mongo unknown exception, ${desc}, line ${line_nun}", ("desc", desc)( "line_num", line_num ));
}
} catch (...) {
std::cerr << "Exception attempting to handle exception for " << desc << " " << line_num << std::endl;
}
if( shutdown ) {
// shutdown if mongo failed to provide opportunity to fix issue and restart
app().quit();
}
}
} // anonymous namespace
void mongo_db_plugin_impl::purge_abi_cache() {
if( (*abi_cache_index).size() < abi_cache_size ) return;
// remove the oldest (smallest) last accessed
auto& idx = (*abi_cache_index).get<by_last_access>();
auto itr = idx.begin();
if( itr != idx.end() ) {
idx.erase( itr );
}
}
optional<abi_serializer> mongo_db_plugin_impl::get_abi_serializer( account_name n ) {
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
if( n.good()) {
try {
auto itr = (*abi_cache_index).find( n );
if( itr != (*abi_cache_index).end() ) {
(*abi_cache_index).modify( itr, []( auto& entry ) {
entry.last_accessed = fc::time_point::now();
});
return itr->serializer;
}
auto account = (*_accounts).find_one( make_document( kvp("name", n.to_string())) );
if(account) {
auto view = account->view();
abi_def abi;
if( view.find( "abi" ) != view.end()) {
try {
abi = fc::json::from_string( bsoncxx::to_json( view["abi"].get_document())).as<abi_def>();
} catch (...) {
ilog( "Unable to convert account abi to abi_def for ${n}", ( "n", n ));
return optional<abi_serializer>();
}
purge_abi_cache(); // make room if necessary
abi_cache entry;
entry.account = n;
entry.last_accessed = fc::time_point::now();
abi_serializer abis;
if( n == chain::config::system_account_name ) {
// redefine eosio setabi.abi from bytes to abi_def
// Done so that abi is stored as abi_def in mongo instead of as bytes
auto itr = std::find_if( abi.structs.begin(), abi.structs.end(),
[]( const auto& s ) { return s.name == "setabi"; } );
if( itr != abi.structs.end() ) {
auto itr2 = std::find_if( itr->fields.begin(), itr->fields.end(),
[]( const auto& f ) { return f.name == "abi"; } );
if( itr2 != itr->fields.end() ) {
if( itr2->type == "bytes" ) {
itr2->type = "abi_def";
// unpack setabi.abi as abi_def instead of as bytes
abis.add_specialized_unpack_pack( "abi_def",
std::make_pair<abi_serializer::unpack_function, abi_serializer::pack_function>(
[]( fc::datastream<const char*>& stream, bool is_array, bool is_optional ) -> fc::variant {
EOS_ASSERT( !is_array && !is_optional, chain::mongo_db_exception, "unexpected abi_def");
chain::bytes temp;
fc::raw::unpack( stream, temp );
return fc::variant( fc::raw::unpack<abi_def>( temp ) );
},
[]( const fc::variant& var, fc::datastream<char*>& ds, bool is_array, bool is_optional ) {
EOS_ASSERT( false, chain::mongo_db_exception, "never called" );
}
) );
}
}
}
}
abis.set_abi( abi, abi_serializer_max_time );
entry.serializer.emplace( std::move( abis ) );
(*abi_cache_index).insert( entry );
return entry.serializer;
}
}
} FC_CAPTURE_AND_LOG((n))
}
return optional<abi_serializer>();
}
template<typename T>
fc::variant mongo_db_plugin_impl::to_variant_with_abi( const T& obj ) {
fc::variant pretty_output;
abi_serializer::to_variant( obj, pretty_output,
[&]( account_name n ) { return get_abi_serializer( n ); },
abi_serializer_max_time );
return pretty_output;
}
void mongo_db_plugin_impl::process_accepted_transaction( const chain::transaction_metadata_ptr& t ) {
try {
if( start_block_reached ) {
_process_accepted_transaction( t );
}
} catch (fc::exception& e) {
elog("FC Exception while processing accepted transaction metadata: ${e}", ("e", e.to_detail_string()));
} catch (std::exception& e) {
elog("STD Exception while processing accepted tranasction metadata: ${e}", ("e", e.what()));
} catch (...) {
elog("Unknown exception while processing accepted transaction metadata");
}
}
void mongo_db_plugin_impl::process_applied_transaction( const chain::transaction_trace_ptr& t ) {
try {
// always call since we need to capture setabi on accounts even if not storing transaction traces
_process_applied_transaction( t );
} catch (fc::exception& e) {
elog("FC Exception while processing applied transaction trace: ${e}", ("e", e.to_detail_string()));
} catch (std::exception& e) {
elog("STD Exception while processing applied transaction trace: ${e}", ("e", e.what()));
} catch (...) {
elog("Unknown exception while processing applied transaction trace");
}
}
void mongo_db_plugin_impl::process_irreversible_block(const chain::block_state_ptr& bs) {
try {
if( start_block_reached ) {
_process_irreversible_block( bs );
}
} catch (fc::exception& e) {
elog("FC Exception while processing irreversible block: ${e}", ("e", e.to_detail_string()));
} catch (std::exception& e) {
elog("STD Exception while processing irreversible block: ${e}", ("e", e.what()));
} catch (...) {
elog("Unknown exception while processing irreversible block");
}
}
void mongo_db_plugin_impl::process_accepted_block( const chain::block_state_ptr& bs ) {
try {
if( start_block_reached ) {
_process_accepted_block( bs );
}
} catch (fc::exception& e) {
elog("FC Exception while processing accepted block trace ${e}", ("e", e.to_string()));
} catch (std::exception& e) {
elog("STD Exception while processing accepted block trace ${e}", ("e", e.what()));
} catch (...) {
elog("Unknown exception while processing accepted block trace");
}
}
void mongo_db_plugin_impl::_process_accepted_transaction( const chain::transaction_metadata_ptr& t ) {
using namespace bsoncxx::types;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::make_array;
namespace bbb = bsoncxx::builder::basic;
const auto& trx = t->trx;
if( !filter_include( trx ) ) return;
auto trans_doc = bsoncxx::builder::basic::document{};
auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::microseconds{fc::time_point::now().time_since_epoch().count()} );
const auto& trx_id = t->id;
const auto trx_id_str = trx_id.str();
trans_doc.append( kvp( "trx_id", trx_id_str ) );
auto v = to_variant_with_abi( trx );
string trx_json = fc::json::to_string( v );
try {
const auto& trx_value = bsoncxx::from_json( trx_json );
trans_doc.append( bsoncxx::builder::concatenate_doc{trx_value.view()} );
} catch( bsoncxx::exception& ) {
try {
trx_json = fc::prune_invalid_utf8( trx_json );
const auto& trx_value = bsoncxx::from_json( trx_json );
trans_doc.append( bsoncxx::builder::concatenate_doc{trx_value.view()} );
trans_doc.append( kvp( "non-utf8-purged", b_bool{true} ) );
} catch( bsoncxx::exception& e ) {
elog( "Unable to convert transaction JSON to MongoDB JSON: ${e}", ("e", e.what()) );
elog( " JSON: ${j}", ("j", trx_json) );
}
}
string signing_keys_json;
if( t->signing_keys.valid() ) {
signing_keys_json = fc::json::to_string( t->signing_keys->second );
} else {
auto signing_keys = trx.get_signature_keys( *chain_id, false, false );
if( !signing_keys.empty() ) {
signing_keys_json = fc::json::to_string( signing_keys );
}
}
if( !signing_keys_json.empty() ) {
try {
const auto& keys_value = bsoncxx::from_json( signing_keys_json );
trans_doc.append( kvp( "signing_keys", keys_value ) );
} catch( bsoncxx::exception& e ) {
// should never fail, so don't attempt to remove invalid utf8
elog( "Unable to convert signing keys JSON to MongoDB JSON: ${e}", ("e", e.what()) );
elog( " JSON: ${j}", ("j", signing_keys_json) );
}
}
trans_doc.append( kvp( "accepted", b_bool{t->accepted} ) );
trans_doc.append( kvp( "implicit", b_bool{t->implicit} ) );
trans_doc.append( kvp( "scheduled", b_bool{t->scheduled} ) );
trans_doc.append( kvp( "createdAt", b_date{now} ) );
try {
mongocxx::options::update update_opts{};
update_opts.upsert( true );
if( !(*_trans).update_one( make_document( kvp( "trx_id", trx_id_str ) ),
make_document( kvp( "$set", trans_doc.view() ) ), update_opts ) ) {
EOS_ASSERT( false, chain::mongo_db_insert_fail, "Failed to insert trans ${id}", ("id", trx_id) );
}
} catch( ... ) {
handle_mongo_exception( "trans insert", __LINE__ );
}
}
bool
mongo_db_plugin_impl::add_action_trace( mongocxx::bulk_write& bulk_action_traces, const chain::action_trace& atrace,
const chain::transaction_trace_ptr& t,
bool executed, const std::chrono::milliseconds& now,
bool& write_ttrace )
{
using namespace bsoncxx::types;
using bsoncxx::builder::basic::kvp;
if( executed && atrace.receipt.receiver == chain::config::system_account_name ) {
update_account( atrace.act );
}
bool added = false;
const bool in_filter = (store_action_traces || store_transaction_traces) && start_block_reached &&
filter_include( atrace.receipt.receiver, atrace.act.name, atrace.act.authorization );
write_ttrace |= in_filter;
if( start_block_reached && store_action_traces && in_filter ) {
auto action_traces_doc = bsoncxx::builder::basic::document{};
const chain::base_action_trace& base = atrace; // without inline action traces
auto v = to_variant_with_abi( base );
string json = fc::json::to_string( v );
try {
const auto& value = bsoncxx::from_json( json );
action_traces_doc.append( bsoncxx::builder::concatenate_doc{value.view()} );
} catch( bsoncxx::exception& ) {
try {
json = fc::prune_invalid_utf8( json );
const auto& value = bsoncxx::from_json( json );
action_traces_doc.append( bsoncxx::builder::concatenate_doc{value.view()} );
action_traces_doc.append( kvp( "non-utf8-purged", b_bool{true} ) );
} catch( bsoncxx::exception& e ) {
elog( "Unable to convert action trace JSON to MongoDB JSON: ${e}", ("e", e.what()) );
elog( " JSON: ${j}", ("j", json) );
}
}
if( t->receipt.valid() ) {
action_traces_doc.append( kvp( "trx_status", std::string( t->receipt->status ) ) );
}
action_traces_doc.append( kvp( "createdAt", b_date{now} ) );
mongocxx::model::insert_one insert_op{action_traces_doc.view()};
bulk_action_traces.append( insert_op );
added = true;
}
for( const auto& iline_atrace : atrace.inline_traces ) {
added |= add_action_trace( bulk_action_traces, iline_atrace, t, executed, now, write_ttrace );
}
return added;
}
void mongo_db_plugin_impl::_process_applied_transaction( const chain::transaction_trace_ptr& t ) {
using namespace bsoncxx::types;
using bsoncxx::builder::basic::kvp;
auto trans_traces_doc = bsoncxx::builder::basic::document{};
auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::microseconds{fc::time_point::now().time_since_epoch().count()});
mongocxx::options::bulk_write bulk_opts;
bulk_opts.ordered(false);
mongocxx::bulk_write bulk_action_traces = (*_action_traces).create_bulk_write(bulk_opts);
bool write_atraces = false;
bool write_ttrace = false; // filters apply to transaction_traces as well
bool executed = t->receipt.valid() && t->receipt->status == chain::transaction_receipt_header::executed;
for( const auto& atrace : t->action_traces ) {
try {
write_atraces |= add_action_trace( bulk_action_traces, atrace, t, executed, now, write_ttrace );
} catch(...) {
handle_mongo_exception("add action traces", __LINE__);
}
}
if( !start_block_reached ) return; //< add_action_trace calls update_account which must be called always
// transaction trace insert
if( store_transaction_traces && write_ttrace ) {
try {
auto v = to_variant_with_abi( *t );
string json = fc::json::to_string( v );
try {
const auto& value = bsoncxx::from_json( json );
trans_traces_doc.append( bsoncxx::builder::concatenate_doc{value.view()} );
} catch( bsoncxx::exception& ) {
try {
json = fc::prune_invalid_utf8( json );
const auto& value = bsoncxx::from_json( json );
trans_traces_doc.append( bsoncxx::builder::concatenate_doc{value.view()} );
trans_traces_doc.append( kvp( "non-utf8-purged", b_bool{true} ) );
} catch( bsoncxx::exception& e ) {
elog( "Unable to convert transaction JSON to MongoDB JSON: ${e}", ("e", e.what()) );
elog( " JSON: ${j}", ("j", json) );
}
}
trans_traces_doc.append( kvp( "createdAt", b_date{now} ) );
try {
if( !(*_trans_traces).insert_one( trans_traces_doc.view() ) ) {
EOS_ASSERT( false, chain::mongo_db_insert_fail, "Failed to insert trans ${id}", ("id", t->id) );
}
} catch( ... ) {
handle_mongo_exception( "trans_traces insert: " + json, __LINE__ );
}
} catch( ... ) {
handle_mongo_exception( "trans_traces serialization: " + t->id.str(), __LINE__ );
}
}
// insert action_traces
if( write_atraces ) {
try {
if( !bulk_action_traces.execute() ) {
EOS_ASSERT( false, chain::mongo_db_insert_fail,
"Bulk action traces insert failed for transaction trace: ${id}", ("id", t->id) );
}
} catch( ... ) {
handle_mongo_exception( "action traces insert", __LINE__ );
}
}
}
void mongo_db_plugin_impl::_process_accepted_block( const chain::block_state_ptr& bs ) {
using namespace bsoncxx::types;
using namespace bsoncxx::builder;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
mongocxx::options::update update_opts{};
update_opts.upsert( true );
auto block_num = bs->block_num;
if( block_num % 1000 == 0 )
ilog( "block_num: ${b}", ("b", block_num) );
const auto& block_id = bs->id;
const auto block_id_str = block_id.str();
auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::microseconds{fc::time_point::now().time_since_epoch().count()});
if( store_block_states ) {
auto block_state_doc = bsoncxx::builder::basic::document{};
block_state_doc.append( kvp( "block_num", b_int32{static_cast<int32_t>(block_num)} ),
kvp( "block_id", block_id_str ),
kvp( "validated", b_bool{bs->validated} ) );
const chain::block_header_state& bhs = *bs;
auto json = fc::json::to_string( bhs );
try {
const auto& value = bsoncxx::from_json( json );
block_state_doc.append( kvp( "block_header_state", value ) );
} catch( bsoncxx::exception& ) {
try {
json = fc::prune_invalid_utf8( json );
const auto& value = bsoncxx::from_json( json );
block_state_doc.append( kvp( "block_header_state", value ) );
block_state_doc.append( kvp( "non-utf8-purged", b_bool{true} ) );
} catch( bsoncxx::exception& e ) {
elog( "Unable to convert block_header_state JSON to MongoDB JSON: ${e}", ("e", e.what()) );
elog( " JSON: ${j}", ("j", json) );
}
}
block_state_doc.append( kvp( "createdAt", b_date{now} ) );
try {
if( update_blocks_via_block_num ) {
if( !(*_block_states).update_one( make_document( kvp( "block_num", b_int32{static_cast<int32_t>(block_num)} ) ),
make_document( kvp( "$set", block_state_doc.view() ) ), update_opts ) ) {
EOS_ASSERT( false, chain::mongo_db_insert_fail, "Failed to insert block_state ${num}", ("num", block_num) );
}
} else {
if( !(*_block_states).update_one( make_document( kvp( "block_id", block_id_str ) ),