-
Notifications
You must be signed in to change notification settings - Fork 22
/
elasticsearch_plugin.cpp
1288 lines (1093 loc) · 51.6 KB
/
elasticsearch_plugin.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <eosio/elasticsearch_plugin/elasticsearch_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 <fc/variant_object.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/signals2/connection.hpp>
#include <thread>
#include <mutex>
#include <queue>
#include <stack>
#include <utility>
#include <functional>
#include <unordered_map>
#include "elastic_client.hpp"
#include "exceptions.hpp"
#include "serializer.hpp"
#include "bulker.hpp"
#include "ThreadPool/ThreadPool.h"
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& _elasticsearch_plugin = app().register_plugin<elasticsearch_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 elasticsearch_plugin_impl {
public:
elasticsearch_plugin_impl();
~elasticsearch_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 check_task_queue_size();
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_applied_transaction(chain::transaction_trace_ptr);
void _process_applied_transaction(chain::transaction_trace_ptr);
void process_accepted_transaction(chain::transaction_metadata_ptr);
void _process_accepted_transaction(chain::transaction_metadata_ptr);
void process_accepted_block( chain::block_state_ptr );
void _process_accepted_block( chain::block_state_ptr );
void process_irreversible_block( chain::block_state_ptr );
void _process_irreversible_block( chain::block_state_ptr );
void upsert_account(
std::unordered_map<uint64_t, std::pair<std::string, fc::mutable_variant_object>> &account_upsert_actions,
const chain::action& act, const chain::block_timestamp_type& block_time );
void create_new_account( fc::mutable_variant_object& param_doc, const chain::newaccount& newacc, const chain::block_timestamp_type& block_time );
void update_account_auth( fc::mutable_variant_object& param_doc, const chain::updateauth& update );
void delete_account_auth( fc::mutable_variant_object& param_doc, const chain::deleteauth& del );
void upsert_account_setabi( fc::mutable_variant_object& param_doc, const chain::setabi& setabi );
/// @return true if act should be added to elasticsearch, 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();
template<typename Queue, typename Entry> void queue(Queue& queue, const Entry& e);
bool configured{false};
bool delete_index_on_startup{false};
uint32_t start_block_num = 0;
std::atomic_bool start_block_reached{false};
bool filter_on_star = true;
std::set<filter_entry> filter_on;
std::set<filter_entry> filter_out;
bool store_blocks = true;
bool store_block_states = true;
bool store_transactions = true;
bool store_transaction_traces = true;
bool store_action_traces = true;
size_t max_task_queue_size = 0;
int task_queue_sleep_time = 0;
std::queue<std::function<void()>> upsert_account_task_queue;
std::mutex upsert_account_task_mtx;
size_t max_queue_size = 0;
int queue_sleep_time = 0;
std::deque<chain::transaction_metadata_ptr> transaction_metadata_queue;
std::deque<chain::transaction_metadata_ptr> transaction_metadata_process_queue;
std::deque<chain::transaction_trace_ptr> transaction_trace_queue;
std::deque<chain::transaction_trace_ptr> transaction_trace_process_queue;
std::deque<chain::block_state_ptr> block_state_queue;
std::deque<chain::block_state_ptr> block_state_process_queue;
std::deque<chain::block_state_ptr> irreversible_block_state_queue;
std::deque<chain::block_state_ptr> irreversible_block_state_process_queue;
std::mutex mtx;
std::condition_variable condition;
std::thread consume_thread;
std::atomic<bool> done{false};
std::atomic<bool> startup{true};
fc::optional<chain::chain_id_type> chain_id;
std::unique_ptr<elastic_client> es_client;
std::unique_ptr<serializer> serializer;
std::unique_ptr<bulker_pool> bulk_pool;
std::unique_ptr<ThreadPool> thread_pool;
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;
std::string accounts_index = "accounts";
std::string blocks_index = "blocks";
std::string trans_index = "transactions";
std::string block_states_index = "block_states";
std::string trans_traces_index = "transaction_traces";
std::string action_traces_index = "action_traces";
};
const action_name elasticsearch_plugin_impl::newaccount = chain::newaccount::get_name();
const action_name elasticsearch_plugin_impl::setabi = chain::setabi::get_name();
const action_name elasticsearch_plugin_impl::updateauth = chain::updateauth::get_name();
const action_name elasticsearch_plugin_impl::deleteauth = chain::deleteauth::get_name();
const permission_name elasticsearch_plugin_impl::owner = chain::config::owner_name;
const permission_name elasticsearch_plugin_impl::active = chain::config::active_name;
bool elasticsearch_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 elasticsearch_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;
}
elasticsearch_plugin_impl::elasticsearch_plugin_impl()
{
}
elasticsearch_plugin_impl::~elasticsearch_plugin_impl()
{
if (!startup) {
try {
ilog( "elasticsearch_plugin shutdown in process please be patient this can take a few minutes" );
done = true;
condition.notify_one();
consume_thread.join();
} catch( std::exception& e ) {
elog( "Exception on elasticsearch_plugin shutdown of consume thread: ${e}", ("e", e.what()));
}
}
}
template<typename Queue, typename Entry>
void elasticsearch_plugin_impl::queue( Queue& queue, const Entry& e ) {
std::unique_lock<std::mutex> 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));
std::this_thread::sleep_for( std::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 elasticsearch_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 elasticsearch_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 Elasticsearch 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 elasticsearch_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 elasticsearch_plugin in read-mode = read-only.
//
if( !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 elasticsearch_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 elasticsearch_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 elasticsearch_plugin_impl::process_accepted_transaction( chain::transaction_metadata_ptr t ) {
try {
if( start_block_reached ) {
_process_accepted_transaction( std::move(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 elasticsearch_plugin_impl::process_applied_transaction( 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( std::move(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 elasticsearch_plugin_impl::process_irreversible_block( chain::block_state_ptr bs) {
try {
if( start_block_reached ) {
_process_irreversible_block( std::move(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 elasticsearch_plugin_impl::process_accepted_block( chain::block_state_ptr bs ) {
try {
if( start_block_reached ) {
_process_accepted_block( std::move(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 elasticsearch_plugin_impl::create_new_account(
fc::mutable_variant_object& param_doc, const chain::newaccount& newacc,
const chain::block_timestamp_type& block_time )
{
fc::variants pub_keys;
fc::variants account_controls;
param_doc("name", newacc.name.to_string());
param_doc("creator", newacc.creator.to_string());
param_doc("account_create_time", block_time);
for( const auto& account : newacc.owner.accounts ) {
fc::mutable_variant_object account_entry;
account_entry( "permission", owner.to_string());
account_entry( "name", account.permission.actor.to_string());
account_controls.emplace_back(account_entry);
}
for( const auto& account : newacc.active.accounts ) {
fc::mutable_variant_object account_entry;
account_entry( "permission", active.to_string());
account_entry( "name", account.permission.actor.to_string());
account_controls.emplace_back(account_entry);
}
for( const auto& pub_key_weight : newacc.owner.keys ) {
fc::mutable_variant_object key_entry;
key_entry( "permission", owner.to_string());
key_entry( "key", pub_key_weight.key.operator string());
pub_keys.emplace_back(key_entry);
}
for( const auto& pub_key_weight : newacc.active.keys ) {
fc::mutable_variant_object key_entry;
key_entry( "permission", active.to_string());
key_entry( "key", pub_key_weight.key.operator string());
pub_keys.emplace_back(key_entry);
}
param_doc("pub_keys", pub_keys);
param_doc("account_controls", account_controls);
}
void elasticsearch_plugin_impl::update_account_auth(
fc::mutable_variant_object& param_doc, const chain::updateauth& update)
{
fc::variants pub_keys;
fc::variants account_controls;
for( const auto& pub_key_weight : update.auth.keys ) {
fc::mutable_variant_object key_entry;
key_entry( "permission", update.permission.to_string());
key_entry( "key", pub_key_weight.key.operator string());
pub_keys.emplace_back(key_entry);
}
for( const auto& account : update.auth.accounts ) {
fc::mutable_variant_object account_entry;
account_entry( "permission", update.permission.to_string());
account_entry( "name", account.permission.actor.to_string());
account_controls.emplace_back(account_entry);
}
param_doc("permission", update.permission.to_string());
param_doc("pub_keys", pub_keys);
param_doc("account_controls", account_controls);
}
void elasticsearch_plugin_impl::delete_account_auth(
fc::mutable_variant_object& param_doc, const chain::deleteauth& del)
{
param_doc("permission", del.permission.to_string());
}
void elasticsearch_plugin_impl::upsert_account_setabi(
fc::mutable_variant_object& param_doc, const chain::setabi& setabi)
{
abi_def abi_def = fc::raw::unpack<chain::abi_def>( setabi.abi );
serializer->upsert_abi_cache( setabi.account, abi_def );
param_doc("name", setabi.account.to_string());
param_doc("abi", abi_def);
}
void elasticsearch_plugin_impl::upsert_account(
std::unordered_map<uint64_t, std::pair<std::string, fc::mutable_variant_object>> &account_upsert_actions,
const chain::action& act, const chain::block_timestamp_type& block_time )
{
if (act.account != chain::config::system_account_name)
return;
uint64_t account_id;
std::string upsert_script;
fc::mutable_variant_object param_doc;
try {
if( act.name == newaccount ) {
auto newacc = act.data_as<chain::newaccount>();
create_new_account(param_doc, newacc, block_time);
account_id = newacc.name.value;
upsert_script =
"ctx._source.name = params[\"%1%\"].name;"
"ctx._source.creator = params[\"%1%\"].creator;"
"ctx._source.account_create_time = params[\"%1%\"].account_create_time;"
"ctx._source.pub_keys = params[\"%1%\"].pub_keys;"
"ctx._source.account_controls = params[\"%1%\"].account_controls;";
} else if( act.name == updateauth ) {
const auto update = act.data_as<chain::updateauth>();
update_account_auth(param_doc, update);
account_id = update.account.value;
upsert_script =
"ctx._source.pub_keys.removeIf(item -> item.permission == params[\"%1%\"].permission);"
"ctx._source.account_controls.removeIf(item -> item.permission == params[\"%1%\"].permission);"
"ctx._source.pub_keys.addAll(params[\"%1%\"].pub_keys);"
"ctx._source.account_controls.addAll(params[\"%1%\"].account_controls);";
} else if( act.name == deleteauth ) {
const auto del = act.data_as<chain::deleteauth>();
delete_account_auth(param_doc, del);
account_id = del.account.value;
upsert_script =
"ctx._source.pub_keys.removeIf(item -> item.permission == params[\"%1%\"].permission);"
"ctx._source.account_controls.removeIf(item -> item.permission == params[\"%1%\"].permission);";
} else if( act.name == setabi ) {
auto setabi = act.data_as<chain::setabi>();
upsert_account_setabi(param_doc, setabi);
account_id = setabi.account.value;
upsert_script =
"ctx._source.name = params[\"%1%\"].name;"
"ctx._source.abi = params[\"%1%\"].abi;";
}
if ( start_block_reached && !upsert_script.empty() ) {
auto it = account_upsert_actions.find(account_id);
if ( it != account_upsert_actions.end() ) {
auto idx = std::to_string(it->second.second.size());
auto script = boost::str(boost::format(upsert_script) % idx);
it->second.first.append(script);
it->second.second.operator()(idx, param_doc);
} else {
auto idx = "0";
auto script = boost::str(boost::format(upsert_script) % idx);
account_upsert_actions.emplace(
account_id,
std::pair<std::string, fc::mutable_variant_object>(script, fc::mutable_variant_object(idx, param_doc)));
}
}
} catch( fc::exception& e ) {
// if unable to unpack native type, skip account creation
}
}
void elasticsearch_plugin_impl::_process_applied_transaction( chain::transaction_trace_ptr t ) {
std::unordered_map<uint64_t, std::pair<std::string, fc::mutable_variant_object>> account_upsert_actions;
std::vector<std::reference_wrapper<chain::base_action_trace>> base_action_traces; // without inline action traces
bool executed = t->receipt.valid() && t->receipt->status == chain::transaction_receipt_header::executed;
std::stack<std::reference_wrapper<chain::action_trace>> stack;
for( auto& atrace : t->action_traces ) {
stack.emplace(atrace);
while ( !stack.empty() )
{
auto &atrace = stack.top().get();
stack.pop();
if( executed && atrace.receipt.receiver == chain::config::system_account_name ) {
upsert_account( account_upsert_actions, atrace.act, atrace.block_time );
}
if( start_block_reached && filter_include( atrace.receipt.receiver, atrace.act.name, atrace.act.authorization ) ) {
base_action_traces.emplace_back( atrace );
}
auto &inline_traces = atrace.inline_traces;
for( auto it = inline_traces.rbegin(); it != inline_traces.rend(); ++it ) {
stack.emplace(*it);
}
}
}
if ( !account_upsert_actions.empty() ) {
auto f = [ account_upsert_actions{std::move(account_upsert_actions)}, this ]()
{
elasticlient::SameIndexBulkData bulk_account_upserts(accounts_index);
for( auto& action : account_upsert_actions ) {
fc::mutable_variant_object source_doc;
fc::mutable_variant_object script_doc;
script_doc("lang", "painless");
script_doc("source", action.second.first);
script_doc("params", action.second.second);
source_doc("scripted_upsert", true);
source_doc("upsert", fc::variant_object());
source_doc("script", script_doc);
auto id = std::to_string(action.first);
auto json = fc::json::to_string(source_doc);
bulk_account_upserts.updateDocument("_doc", id, json);
}
try {
es_client->bulk_perform(bulk_account_upserts);
} catch( ... ) {
handle_elasticsearch_exception( "upsert accounts " + bulk_account_upserts.body(), __LINE__ );
}
};
upsert_account_task_queue.emplace( std::move(f) );
check_task_queue_size();
thread_pool->enqueue(
[ this ]()
{
std::unique_lock<std::mutex> guard(upsert_account_task_mtx);
std::function<void()> task = std::move( upsert_account_task_queue.front() );
task();
upsert_account_task_queue.pop();
}
);
}
if( base_action_traces.empty() ) return; //< do not index transaction_trace if all action_traces filtered out
check_task_queue_size();
thread_pool->enqueue(
[ t{std::move(t)}, base_action_traces{std::move(base_action_traces)}, this ]()
{
const auto& trx_id = t->id;
const auto trx_id_str = trx_id.str();
if ( store_action_traces ) {
for (auto& atrace : base_action_traces) {
fc::mutable_variant_object action_traces_doc;
chain::base_action_trace &base = atrace.get();
fc::from_variant( serializer->to_variant_with_abi( base ), action_traces_doc );
fc::mutable_variant_object act_doc;
fc::from_variant( action_traces_doc["act"], act_doc );
act_doc["data"] = fc::json::to_string( act_doc["data"] );
action_traces_doc["act"] = act_doc;
fc::mutable_variant_object action_doc;
action_doc("_index", action_traces_index);
action_doc("_type", "_doc");
action_doc("_id", base.receipt.global_sequence);
action_doc("retry_on_conflict", 100);
auto action = fc::json::to_string( fc::variant_object("index", action_doc) );
auto json = fc::prune_invalid_utf8( fc::json::to_string(action_traces_doc) );
bulker& bulk = bulk_pool->get();
bulk.append_document(std::move(action), std::move(json));
}
}
if( store_transaction_traces ) {
// transaction trace index
fc::mutable_variant_object trans_traces_doc;
fc::from_variant( serializer->to_variant_with_abi( *t ), trans_traces_doc );
fc::mutable_variant_object action_doc;
action_doc("_index", trans_traces_index);
action_doc("_type", "_doc");
action_doc("_id", trx_id_str);
action_doc("retry_on_conflict", 100);
auto action = fc::json::to_string( fc::variant_object("index", action_doc) );
auto json = fc::prune_invalid_utf8( fc::json::to_string( trans_traces_doc ) );
bulker& bulk = bulk_pool->get();
bulk.append_document(std::move(action), std::move(json));
}
}
);
}
void elasticsearch_plugin_impl::_process_accepted_transaction( chain::transaction_metadata_ptr t ) {
check_task_queue_size();
thread_pool->enqueue(
[ t{std::move(t)}, this ]()
{
const signed_transaction& trx = t->packed_trx->get_signed_transaction();
if( !filter_include( trx ) ) return;
const auto& trx_id = t->id;
const auto trx_id_str = trx_id.str();
fc::mutable_variant_object trans_doc;
fc::mutable_variant_object doc;
fc::from_variant( serializer->to_variant_with_abi( trx ), trans_doc );
trans_doc("trx_id", trx_id_str);
fc::variant signing_keys;
if( t->signing_keys_future.wait_for(std::chrono::seconds(0)) == std::future_status::ready ) {
signing_keys = std::get<2>(t->signing_keys_future.get());
} else {
flat_set<public_key_type> keys;
trx.get_signature_keys( *chain_id, fc::time_point::maximum(), keys, false );
signing_keys = keys;
}
if( !signing_keys.is_null() ) {
trans_doc("signing_keys", signing_keys);
}
trans_doc("accepted", t->accepted);
trans_doc("implicit", t->implicit);
trans_doc("scheduled", t->scheduled);
doc("doc", trans_doc);
doc("doc_as_upsert", true);
fc::mutable_variant_object action_doc;
action_doc("_index", trans_index);
action_doc("_type", "_doc");
action_doc("_id", trx_id_str);
action_doc("retry_on_conflict", 100);
auto action = fc::json::to_string( fc::variant_object("update", action_doc) );
auto json = fc::prune_invalid_utf8( fc::json::to_string( doc ) );
bulker& bulk = bulk_pool->get();
bulk.append_document(std::move(action), std::move(json));
}
);
}
void elasticsearch_plugin_impl::_process_accepted_block( chain::block_state_ptr bs ) {
check_task_queue_size();
thread_pool->enqueue(
[ bs{std::move(bs)}, this ]()
{
auto block_num = bs->block_num;
if( block_num % 10000 == 0 )
ilog( "block_num: ${b}", ("b", block_num) );
const auto block_id = bs->id;
const auto block_id_str = block_id.str();
if( store_block_states ) {
auto source = "int v;"; // Do nothing if document already exsit.
fc::mutable_variant_object doc;
fc::mutable_variant_object bs_doc(bs);
fc::mutable_variant_object script_doc;
bs_doc.erase("block");
script_doc("source", source);
script_doc("lang", "painless");
doc("script", script_doc);
doc("scripted_upsert", true);
doc("upsert", bs_doc);
fc::mutable_variant_object action_doc;
action_doc("_index", block_states_index);
action_doc("_type", "_doc");
action_doc("_id", block_id_str);
action_doc("retry_on_conflict", 100);
auto action = fc::json::to_string( fc::variant_object("update", action_doc) );
auto json = fc::prune_invalid_utf8( fc::json::to_string( doc ) );
bulker& bulk = bulk_pool->get();
bulk.append_document(std::move(action), std::move(json));
}
if( store_blocks ) {
auto source = "int v;"; // Do nothing if document already exsit.
fc::mutable_variant_object doc;
fc::mutable_variant_object block_doc;
fc::mutable_variant_object script_doc;
fc::from_variant(serializer->to_variant_with_abi( *bs->block ), block_doc);
script_doc("source", source);
script_doc("lang", "painless");
doc("script", script_doc);
doc("scripted_upsert", true);
doc("upsert", block_doc);
fc::mutable_variant_object action_doc;
action_doc("_index", blocks_index);
action_doc("_type", "_doc");
action_doc("_id", block_id_str);
action_doc("retry_on_conflict", 100);
auto action = fc::json::to_string( fc::variant_object("update", action_doc) );
auto json = fc::prune_invalid_utf8( fc::json::to_string( doc ) );
bulker& bulk = bulk_pool->get();
bulk.append_document(std::move(action), std::move(json));
}
}
);
}
void elasticsearch_plugin_impl::_process_irreversible_block(chain::block_state_ptr bs) {
check_task_queue_size();
thread_pool->enqueue(
[ bs{std::move(bs)}, this ]()
{
const auto block_id = bs->block->id();
const auto block_id_str = block_id.str();
const auto block_num = bs->block->block_num();
auto source =
"ctx._source.validated = params.validated;"
"ctx._source.irreversible = params.irreversible;";
fc::mutable_variant_object params_doc;
fc::mutable_variant_object script_doc;
params_doc("validated", bs->validated);
params_doc("irreversible", true);
script_doc("source", source);
script_doc("lang", "painless");
script_doc("params", params_doc);
if( store_block_states ) {
fc::mutable_variant_object doc;
fc::mutable_variant_object bs_doc(bs);
bs_doc.erase("block");
bs_doc("irreversible", true);
doc("script", script_doc);
doc("upsert", bs_doc);
fc::mutable_variant_object action_doc;
action_doc("_index", block_states_index);
action_doc("_type", "_doc");
action_doc("_id", block_id_str);
action_doc("retry_on_conflict", 100);
auto action = fc::json::to_string( fc::variant_object("update", action_doc) );
auto json = fc::prune_invalid_utf8( fc::json::to_string( doc ) );
bulker& bulk = bulk_pool->get();
bulk.append_document(std::move(action), std::move(json));
}
if( store_blocks ) {
fc::mutable_variant_object doc;
fc::mutable_variant_object block_doc;
fc::from_variant(serializer->to_variant_with_abi( *bs->block ), block_doc);
block_doc("irreversible", true);
block_doc("validated", bs->validated);
doc("script", script_doc);
doc("upsert", block_doc);
fc::mutable_variant_object action_doc;
action_doc("_index", blocks_index);
action_doc("_type", "_doc");
action_doc("_id", block_id_str);
action_doc("retry_on_conflict", 100);
auto action = fc::json::to_string( fc::variant_object("update", action_doc) );
auto json = fc::prune_invalid_utf8( fc::json::to_string( doc ) );
bulker& bulk = bulk_pool->get();
bulk.append_document(std::move(action), std::move(json));
}
if( store_transactions ) {
for( const auto& receipt : bs->block->transactions ) {
string trx_id_str;
if( receipt.trx.contains<packed_transaction>() ) {
const auto& pt = receipt.trx.get<packed_transaction>();
// get id via get_raw_transaction() as packed_transaction.id() mutates internal transaction state
const auto& raw = pt.get_raw_transaction();
const auto& trx = fc::raw::unpack<transaction>( raw );
if( !filter_include( trx ) ) continue;
const auto& id = trx.id();
trx_id_str = id.str();
} else {
const auto& id = receipt.trx.get<transaction_id_type>();
trx_id_str = id.str();
}
fc::mutable_variant_object trans_doc;
fc::mutable_variant_object doc;
trans_doc("irreversible", true);
trans_doc("block_id", block_id_str);
trans_doc("block_num", static_cast<int32_t>(block_num));
doc("doc", trans_doc);
doc("doc_as_upsert", true);
fc::mutable_variant_object action_doc;
action_doc("_index", trans_index);
action_doc("_type", "_doc");
action_doc("_id", trx_id_str);
action_doc("retry_on_conflict", 100);
auto action = fc::json::to_string( fc::variant_object("update", action_doc) );
auto json = fc::prune_invalid_utf8( fc::json::to_string( doc ) );
bulker& bulk = bulk_pool->get();
bulk.append_document(std::move(action), std::move(json));
}
}
}
);
}
void elasticsearch_plugin_impl::check_task_queue_size() {
auto task_queue_size = thread_pool->queue_size();
if ( task_queue_size > max_task_queue_size ) {
task_queue_sleep_time += 10;
if( task_queue_sleep_time > 1000 )
wlog("thread pool task queue size: ${q}", ("q", task_queue_size));
std::this_thread::sleep_for( std::chrono::milliseconds( task_queue_sleep_time ));
} else {
task_queue_sleep_time -= 10;
if( task_queue_sleep_time < 0 ) task_queue_sleep_time = 0;
}
}
void elasticsearch_plugin_impl::consume_blocks() {
try {
while (true) {
std::unique_lock<std::mutex> 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));