forked from btccom/btcpool-ABANDONED
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStatsHttpd.inl
More file actions
1969 lines (1689 loc) · 60.8 KB
/
StatsHttpd.inl
File metadata and controls
1969 lines (1689 loc) · 60.8 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
/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "utilities_js.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/thread.hpp>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
//////////////////////////////// WorkerShares ////////////////////////////////
template <class SHARE>
WorkerShares<SHARE>::WorkerShares(const int64_t workerId, const int32_t userId)
: workerId_(workerId)
, userId_(userId) {
assert(STATS_SLIDING_WINDOW_SECONDS >= 3600);
}
template <class SHARE>
void WorkerShares<SHARE>::processShare(SHARE &share, bool acceptStale) {
ScopeLock sl(lock_);
const time_t now = time(nullptr);
if (now > share.timestamp() + STATS_SLIDING_WINDOW_SECONDS) {
return;
}
if (StratumStatus::isAccepted(share.status()) &&
(acceptStale || !StratumStatus::isAcceptedStale(share.status()))) {
acceptCount_++;
acceptShares_.insert(acceptShareTime(share.timestamp()), share.sharediff());
updateAcceptDiff(share.sharediff());
} else if (StratumStatus::isAnyStale(share.status())) {
updateRejectDiff(share);
staleShares_.insert(rejectShareTime(share.timestamp()), share.sharediff());
} else {
updateRejectDiff(share);
rejectShares_[share.status()].insert(
rejectShareTime(share.timestamp()), share.sharediff());
}
lastShareIP_.fromString(share.ip());
lastShareTime_ = share.timestamp();
}
template <class SHARE>
WorkerStatus WorkerShares<SHARE>::getWorkerStatus() {
WorkerStatus s;
getWorkerStatus(s);
return s;
}
template <class SHARE>
void WorkerShares<SHARE>::getWorkerStatus(WorkerStatus &s) {
ScopeLock sl(lock_);
const time_t now = time(nullptr);
s.accept5m_ = acceptShares_.sum(acceptShareTime(now), acceptShareTime(300));
s.accept15m_ = acceptShares_.sum(acceptShareTime(now), acceptShareTime(900));
s.accept1h_ = acceptShares_.sum(acceptShareTime(now), acceptShareTime(3600));
s.stale15m_ = staleShares_.sum(rejectShareTime(now), rejectShareTime(900));
s.stale1h_ = staleShares_.sum(rejectShareTime(now), rejectShareTime(3600));
s.reject15m_ = 0;
s.reject1h_ = 0;
s.rejectDetail15m_ = "{";
s.rejectDetail1h_ = "{";
for (auto &itr : rejectShares_) {
auto reject15m = itr.second.sum(rejectShareTime(now), rejectShareTime(900));
auto reject1h = itr.second.sum(rejectShareTime(now), rejectShareTime(3600));
s.reject15m_ += reject15m;
s.reject1h_ += reject1h;
s.rejectDetail15m_ += "\"" + std::to_string(itr.first) +
"\":" + std::to_string(reject15m) + ",";
s.rejectDetail1h_ += "\"" + std::to_string(itr.first) +
"\":" + std::to_string(reject1h) + ",";
}
// remove the end of ","
if (s.rejectDetail15m_.size() > 1)
s.rejectDetail15m_.resize(s.rejectDetail15m_.size() - 1);
if (s.rejectDetail1h_.size() > 1)
s.rejectDetail1h_.resize(s.rejectDetail1h_.size() - 1);
s.rejectDetail15m_ += "}";
s.rejectDetail1h_ += "}";
s.acceptCount_ = acceptCount_;
s.lastShareIP_ = lastShareIP_;
s.lastShareTime_ = lastShareTime_;
}
template <class SHARE>
bool WorkerShares<SHARE>::isExpired() {
ScopeLock sl(lock_);
return (lastShareTime_ + STATS_SLIDING_WINDOW_SECONDS) <
(uint32_t)time(nullptr);
}
template <class SHARE>
void WorkerSharesNormalized<SHARE>::updateAcceptDiff(uint64_t diff) {
if (diff > 0) {
lastAcceptDiff_ = diff;
}
}
template <class SHARE>
void WorkerSharesNormalized<SHARE>::updateRejectDiff(SHARE &share) const {
if (share.sharediff() > lastAcceptDiff_ * 4) {
share.set_sharediff(lastAcceptDiff_ * 4);
}
}
//////////////////////////////// StatsServerT ////////////////////////////////
template <class SHARE>
StatsServerT<SHARE>::StatsServerT(
const libconfig::Config &cfg,
shared_ptr<DuplicateShareChecker<SHARE>> dupShareChecker)
: running_(true)
, totalWorkerCount_(0)
, totalUserCount_(0)
, uptime_(time(nullptr))
, poolWorker_(0u /* worker id */, 0 /* user id */)
, kafkaConsumer_(
cfg.lookup("kafka.brokers").c_str(),
cfg.lookup("statshttpd.share_topic").c_str(),
0 /* patition */)
, kafkaConsumerCommonEvents_(
cfg.lookup("kafka.brokers").c_str(),
cfg.lookup("statshttpd.common_events_topic").c_str(),
0 /* patition */)
, isInserting_(false)
, isUpdateRedis_(false)
, lastShareTime_(0)
, isInitializing_(true)
, lastFlushTime_(0)
, dupShareChecker_(dupShareChecker)
, requestCount_(0)
, responseBytes_(0) {
httpdHost_ = cfg.lookup("statshttpd.ip").c_str();
int port = httpdPort_;
cfg.lookupValue("statshttpd.port", port);
httpdPort_ = (uint16_t)port;
int flushInterval = kFlushDBInterval_;
cfg.lookupValue("statshttpd.flush_db_interval", flushInterval);
kFlushDBInterval_ = flushInterval;
cfg.lookupValue("statshttpd.file_last_flush_time", fileLastFlushTime_);
cfg.lookupValue("statshttpd.accept_stale", acceptStale_);
cfg.lookupValue("statshttpd.update_worker_name", updateWorkerName_);
cfg.lookupValue("statshttpd.expected_online_workers", expectedOnlineWorkers);
cfg.lookupValue("users.single_user_mode", singleUserMode_);
cfg.lookupValue("users.single_user_puid", singleUserId_);
if (singleUserMode_) {
LOG(INFO) << "[Option] Single User Mode Enabled, puid: " << singleUserId_;
}
bool useMysql = true;
cfg.lookupValue("statshttpd.use_mysql", useMysql);
bool useRedis = false;
cfg.lookupValue("statshttpd.use_redis", useRedis);
if (useMysql) {
int32_t poolDBPort = 3306;
cfg.lookupValue("pooldb.port", poolDBPort);
MysqlConnectInfo poolDBInfo(
cfg.lookup("pooldb.host"),
poolDBPort,
cfg.lookup("pooldb.username"),
cfg.lookup("pooldb.password"),
cfg.lookup("pooldb.dbname"));
poolDB_ = new MySQLConnection(poolDBInfo);
if (updateWorkerName_) {
poolDBCommonEvents_ = new MySQLConnection(poolDBInfo);
}
}
if (useRedis) {
int32_t redisPort = 6379;
cfg.lookupValue("redis.port", redisPort);
RedisConnectInfo redisInfo(
cfg.lookup("redis.host"), redisPort, cfg.lookup("redis.password"));
cfg.lookupValue("redis.key_prefix", redisKeyPrefix_);
cfg.lookupValue("redis.key_expire", redisKeyExpire_);
cfg.lookupValue("redis.publish_policy", redisPublishPolicy_);
cfg.lookupValue("redis.index_policy", redisIndexPolicy_);
cfg.lookupValue("redis.concurrency", redisConcurrency_);
if (updateWorkerName_) {
redisCommonEvents_ = new RedisConnection(redisInfo);
}
for (uint32_t i = 0; i < redisConcurrency_; i++) {
RedisConnection *redis = new RedisConnection(redisInfo);
redisGroup_.push_back(redis);
}
}
pthread_rwlock_init(&rwlock_, nullptr);
}
template <class SHARE>
StatsServerT<SHARE>::~StatsServerT() {
stop();
if (threadConsume_.joinable())
threadConsume_.join();
if (threadConsumeCommonEvents_.joinable())
threadConsumeCommonEvents_.join();
if (poolDB_ != nullptr) {
poolDB_->close();
delete poolDB_;
poolDB_ = nullptr;
}
if (poolDBCommonEvents_ != nullptr) {
poolDBCommonEvents_->close();
delete poolDBCommonEvents_;
poolDBCommonEvents_ = nullptr;
}
if (redisCommonEvents_ != nullptr) {
redisCommonEvents_->close();
delete redisCommonEvents_;
redisCommonEvents_ = nullptr;
}
while (!redisGroup_.empty()) {
RedisConnection *redis = redisGroup_.back();
if (redis != nullptr) {
redis->close();
delete redis;
}
redisGroup_.pop_back();
}
pthread_rwlock_destroy(&rwlock_);
}
template <class SHARE>
string StatsServerT<SHARE>::getRedisKeyMiningWorker(
const int32_t userId, const int64_t workerId) {
string key = redisKeyPrefix_;
key += "mining_workers/pu/";
key += std::to_string(userId);
key += "/wk/";
key += std::to_string(workerId);
return key;
}
template <class SHARE>
string StatsServerT<SHARE>::getRedisKeyMiningWorker(const int32_t userId) {
string key = redisKeyPrefix_;
key += "mining_workers/pu/";
key += std::to_string(userId);
key += "/all";
return key;
}
template <class SHARE>
string StatsServerT<SHARE>::getRedisKeyIndex(
const int32_t userId, const string &indexName) {
string key = redisKeyPrefix_;
key += "mining_workers/pu/";
key += std::to_string(userId);
key += "/sort/";
key += indexName;
return key;
}
template <class SHARE>
bool StatsServerT<SHARE>::init() {
if (poolDB_ != nullptr) {
if (!poolDB_->ping()) {
LOG(INFO) << "db ping failure";
return false;
}
// check db conf (only poolDB_ needs)
string value = poolDB_->getVariable("max_allowed_packet");
if (atoi(value.c_str()) < 16 * 1024 * 1024) {
LOG(INFO) << "db conf 'max_allowed_packet' is less than 16*1024*1024";
return false;
}
}
if (poolDBCommonEvents_ != nullptr && !poolDBCommonEvents_->ping()) {
LOG(INFO) << "common events db ping failure";
return false;
}
if (redisCommonEvents_ != nullptr && !redisCommonEvents_->ping()) {
LOG(INFO) << "common events redis ping failure";
return false;
}
for (size_t i = 0; i < redisGroup_.size(); i++) {
if (redisGroup_[i] != nullptr && !redisGroup_[i]->ping()) {
LOG(INFO) << "redis " << i << " in redisGroup ping failure";
return false;
}
}
return true;
}
template <class SHARE>
void StatsServerT<SHARE>::stop() {
if (!running_)
return;
LOG(INFO) << "stop StatsServer...";
running_ = false;
event_base_loopexit(base_, NULL);
}
template <class SHARE>
void StatsServerT<SHARE>::processShare(SHARE &share) {
const time_t now = time(nullptr);
lastShareTime_ = share.timestamp();
// ignore too old shares
if (now > share.timestamp() + STATS_SLIDING_WINDOW_SECONDS) {
return;
}
if (!filterShare(share)) {
DLOG(INFO) << "filtered share: " << share.toString();
return;
}
WorkerKey key(share.userid(), share.workerhashid());
_processShare(key, share);
poolWorker_.processShare(share, acceptStale_);
}
template <class SHARE>
void StatsServerT<SHARE>::_processShare(WorkerKey &key, SHARE &share) {
const int32_t userId = key.userId_;
pthread_rwlock_rdlock(&rwlock_);
auto workerItr = workerSet_.find(key);
auto userItr = userSet_.find(userId);
pthread_rwlock_unlock(&rwlock_);
shared_ptr<WorkerShares<SHARE>> workerShare = nullptr, userShare = nullptr;
if (workerItr != workerSet_.end()) {
workerItr->second->processShare(share, acceptStale_);
} else {
workerShare = make_shared<WorkerSharesNormalized<SHARE>>(
share.workerhashid(), share.userid());
workerShare->processShare(share, acceptStale_);
}
if (userItr != userSet_.end()) {
userItr->second->processShare(share, acceptStale_);
} else {
userShare =
make_shared<WorkerShares<SHARE>>(share.workerhashid(), share.userid());
userShare->processShare(share, acceptStale_);
}
if (workerShare != nullptr || userShare != nullptr) {
pthread_rwlock_wrlock(&rwlock_); // write lock
if (workerShare != nullptr) {
workerSet_[key] = workerShare;
totalWorkerCount_++;
userWorkerCount_[key.userId_]++;
}
if (userShare != nullptr) {
userSet_[userId] = userShare;
totalUserCount_++;
}
pthread_rwlock_unlock(&rwlock_);
}
}
template <class SHARE>
void StatsServerT<SHARE>::flushWorkersAndUsersToRedis() {
LOG(INFO) << "flush to redis...";
if (isUpdateRedis_) {
LOG(WARNING) << "last redis flush is not finish yet, ignore";
return;
}
isUpdateRedis_ = true;
std::thread t(boost::bind(
&StatsServerT<SHARE>::_flushWorkersAndUsersToRedisThread, this));
t.detach();
}
template <class SHARE>
void StatsServerT<SHARE>::_flushWorkersAndUsersToRedisThread() {
std::vector<std::thread> threadPool;
assert(redisGroup_.size() == redisConcurrency_);
for (uint32_t i = 0; i < redisConcurrency_; i++) {
threadPool.push_back(std::thread(boost::bind(
&StatsServerT<SHARE>::_flushWorkersAndUsersToRedisThread, this, i)));
}
for (auto &t : threadPool) {
if (t.joinable()) {
t.join();
}
}
pthread_rwlock_rdlock(&rwlock_);
LOG(INFO) << "flush to redis... done, " << workerSet_.size() << " workers, "
<< userSet_.size() << " users";
pthread_rwlock_unlock(&rwlock_);
isUpdateRedis_ = false;
}
template <class SHARE>
void StatsServerT<SHARE>::_flushWorkersAndUsersToRedisThread(
uint32_t threadStep) {
if (!checkRedis(threadStep)) {
return;
}
flushWorkersToRedis(threadStep);
flushUsersToRedis(threadStep);
}
template <class SHARE>
bool StatsServerT<SHARE>::checkRedis(uint32_t threadStep) {
if (threadStep > redisGroup_.size() - 1) {
LOG(ERROR) << "checkRedis(" << threadStep << "): "
<< "threadStep out of range, should less than " << threadStep
<< "!";
return false;
}
{
RedisConnection *redis = redisGroup_[threadStep];
if (!redis->ping()) {
LOG(ERROR) << "can't connect to pool redis " << threadStep;
return false;
}
}
return true;
}
template <class SHARE>
void StatsServerT<SHARE>::flushWorkersToRedis(uint32_t threadStep) {
RedisConnection *redis = redisGroup_[threadStep];
size_t workerCounter = 0;
std::unordered_map<int32_t /*userId*/, WorkerIndexBuffer> indexBufferMap;
pthread_rwlock_rdlock(&rwlock_); // read lock
LOG(INFO) << "redis (thread " << threadStep << "): flush workers, rd locked";
size_t stepSize = workerSet_.size() / redisConcurrency_;
if (workerSet_.size() % redisConcurrency_ != 0) {
// +1 to avoid missing the last few items.
// Example: 5 / 2 = 2. Each thread handles 2 items and the fifth was
// missing.
stepSize++;
}
size_t offsetBegin = stepSize * threadStep;
auto itr = workerSet_.begin();
// move to the beginning position
for (size_t i = 0; i < offsetBegin && itr != workerSet_.end(); i++, itr++)
;
// flush all workes status in a stepSize
for (size_t i = 0; i < stepSize && itr != workerSet_.end(); i++, itr++) {
workerCounter++;
const int32_t userId = itr->first.userId_;
const int64_t workerId = itr->first.workerId_;
shared_ptr<WorkerShares<SHARE>> workerShare = itr->second;
const WorkerStatus status = workerShare->getWorkerStatus();
string key = getRedisKeyMiningWorker(userId, workerId);
// update info
redis->prepare({"HMSET",
key,
"accept_5m",
std::to_string(status.accept5m_),
"accept_15m",
std::to_string(status.accept15m_),
"stale_15m",
std::to_string(status.stale15m_),
"reject_15m",
std::to_string(status.reject15m_),
"reject_detail_15m",
status.rejectDetail15m_,
"accept_1h",
std::to_string(status.accept1h_),
"stale_1h",
std::to_string(status.stale1h_),
"reject_1h",
std::to_string(status.reject1h_),
"reject_detail_1h",
status.rejectDetail1h_,
"accept_count",
std::to_string(status.acceptCount_),
"last_share_ip",
status.lastShareIP_.toString(),
"last_share_time",
std::to_string(status.lastShareTime_),
"updated_at",
std::to_string(time(nullptr))});
// set key expire
if (redisKeyExpire_ > 0) {
redis->prepare({"EXPIRE", key, std::to_string(redisKeyExpire_)});
}
// publish notification
if (redisPublishPolicy_ & REDIS_PUBLISH_WORKER_UPDATE) {
redis->prepare({"PUBLISH", key, "1"});
}
// add index to buffer
if (redisIndexPolicy_ != REDIS_INDEX_NONE) {
addIndexToBuffer(indexBufferMap[userId], workerId, status);
}
}
pthread_rwlock_unlock(&rwlock_); // unlock
LOG(INFO) << "redis (thread " << threadStep << "): flush workers, rd unlock";
if (workerCounter == 0) {
LOG(INFO) << "redis (thread " << threadStep << "): no active workers";
return;
}
for (size_t i = 0; i < workerCounter; i++) {
// update info
{
RedisResult r = redis->execute();
if (r.type() != REDIS_REPLY_STATUS || r.str() != "OK") {
LOG(INFO) << "redis (thread " << threadStep << ") HMSET failed, "
<< "item index: " << i << ", "
<< "reply type: " << r.type() << ", "
<< "reply str: " << r.str();
}
}
// set key expire
if (redisKeyExpire_ > 0) {
RedisResult r = redis->execute();
if (r.type() != REDIS_REPLY_INTEGER || r.integer() != 1) {
LOG(INFO) << "redis (thread " << threadStep << ") EXPIRE failed, "
<< "item index: " << i << ", "
<< "reply type: " << r.type() << ", "
<< "reply integer: " << r.integer() << ","
<< "reply str: " << r.str();
}
}
// notification
if (redisPublishPolicy_ & REDIS_PUBLISH_WORKER_UPDATE) {
RedisResult r = redis->execute();
if (r.type() != REDIS_REPLY_INTEGER) {
LOG(INFO) << "redis (thread " << threadStep << ") PUBLISH failed, "
<< "item index: " << i << ", "
<< "reply type: " << r.type() << ", "
<< "reply str: " << r.str();
}
}
}
// flush indexes
if (redisIndexPolicy_ != REDIS_INDEX_NONE) {
flushIndexToRedis(redis, indexBufferMap);
}
LOG(INFO) << "flush workers to redis (thread " << threadStep
<< ") done, workers: " << workerCounter;
return;
}
template <class SHARE>
void StatsServerT<SHARE>::flushIndexToRedis(
RedisConnection *redis,
std::unordered_map<int32_t /*userId*/, WorkerIndexBuffer> &indexBufferMap) {
for (auto itr = indexBufferMap.begin(); itr != indexBufferMap.end(); itr++) {
flushIndexToRedis(redis, itr->second, itr->first);
}
}
template <class SHARE>
void StatsServerT<SHARE>::flushIndexToRedis(
RedisConnection *redis, WorkerIndexBuffer &buffer, const int32_t userId) {
// accept_5m
if (redisIndexPolicy_ & REDIS_INDEX_ACCEPT_5M) {
buffer.accept5m_.insert(
buffer.accept5m_.begin(),
{"ZADD", getRedisKeyIndex(userId, "accept_5m")});
flushIndexToRedis(redis, buffer.accept5m_);
}
// accept_15m
if (redisIndexPolicy_ & REDIS_INDEX_ACCEPT_15M) {
buffer.accept15m_.insert(
buffer.accept15m_.begin(),
{"ZADD", getRedisKeyIndex(userId, "accept_15m")});
flushIndexToRedis(redis, buffer.accept15m_);
}
// stale_15m
if (redisIndexPolicy_ & REDIS_INDEX_STALE_15M) {
buffer.stale15m_.insert(
buffer.stale15m_.begin(),
{"ZADD", getRedisKeyIndex(userId, "stale_15m")});
flushIndexToRedis(redis, buffer.stale15m_);
}
// reject_15m
if (redisIndexPolicy_ & REDIS_INDEX_REJECT_15M) {
buffer.reject15m_.insert(
buffer.reject15m_.begin(),
{"ZADD", getRedisKeyIndex(userId, "reject_15m")});
flushIndexToRedis(redis, buffer.reject15m_);
}
// accept_1h
if (redisIndexPolicy_ & REDIS_INDEX_ACCEPT_1H) {
buffer.accept1h_.insert(
buffer.accept1h_.begin(),
{"ZADD", getRedisKeyIndex(userId, "accept_1h")});
flushIndexToRedis(redis, buffer.accept1h_);
}
// stale_1h
if (redisIndexPolicy_ & REDIS_INDEX_STALE_1H) {
buffer.stale1h_.insert(
buffer.stale1h_.begin(),
{"ZADD", getRedisKeyIndex(userId, "stale_1h")});
flushIndexToRedis(redis, buffer.stale1h_);
}
// reject_1h
if (redisIndexPolicy_ & REDIS_INDEX_REJECT_1H) {
buffer.reject1h_.insert(
buffer.reject1h_.begin(),
{"ZADD", getRedisKeyIndex(userId, "reject_1h")});
flushIndexToRedis(redis, buffer.reject1h_);
}
// accept_count
if (redisIndexPolicy_ & REDIS_INDEX_ACCEPT_COUNT) {
buffer.acceptCount_.insert(
buffer.acceptCount_.begin(),
{"ZADD", getRedisKeyIndex(userId, "accept_count")});
flushIndexToRedis(redis, buffer.acceptCount_);
}
// last_share_ip
if (redisIndexPolicy_ & REDIS_INDEX_LAST_SHARE_IP) {
buffer.lastShareIP_.insert(
buffer.lastShareIP_.begin(),
{"ZADD", getRedisKeyIndex(userId, "last_share_ip")});
flushIndexToRedis(redis, buffer.lastShareIP_);
}
// last_share_time
if (redisIndexPolicy_ & REDIS_INDEX_LAST_SHARE_TIME) {
buffer.lastShareTime_.insert(
buffer.lastShareTime_.begin(),
{"ZADD", getRedisKeyIndex(userId, "last_share_time")});
flushIndexToRedis(redis, buffer.lastShareTime_);
}
}
template <class SHARE>
void StatsServerT<SHARE>::addIndexToBuffer(
WorkerIndexBuffer &buffer,
const int64_t workerId,
const WorkerStatus &status) {
// accept_5m
if (redisIndexPolicy_ & REDIS_INDEX_ACCEPT_5M) {
buffer.accept5m_.push_back(std::to_string(status.accept5m_));
buffer.accept5m_.push_back(std::to_string(workerId));
}
// accept_15m
if (redisIndexPolicy_ & REDIS_INDEX_ACCEPT_15M) {
buffer.accept15m_.push_back(std::to_string(status.accept15m_));
buffer.accept15m_.push_back(std::to_string(workerId));
}
// stale_15m
if (redisIndexPolicy_ & REDIS_INDEX_STALE_15M) {
buffer.stale15m_.push_back(std::to_string(status.stale15m_));
buffer.stale15m_.push_back(std::to_string(workerId));
}
// reject_15m
if (redisIndexPolicy_ & REDIS_INDEX_REJECT_15M) {
buffer.reject15m_.push_back(std::to_string(status.reject15m_));
buffer.reject15m_.push_back(std::to_string(workerId));
}
// accept_1h
if (redisIndexPolicy_ & REDIS_INDEX_ACCEPT_1H) {
buffer.accept1h_.push_back(std::to_string(status.accept1h_));
buffer.accept1h_.push_back(std::to_string(workerId));
}
// stale_1h
if (redisIndexPolicy_ & REDIS_INDEX_STALE_1H) {
buffer.stale1h_.push_back(std::to_string(status.stale1h_));
buffer.stale1h_.push_back(std::to_string(workerId));
}
// reject_1h
if (redisIndexPolicy_ & REDIS_INDEX_REJECT_1H) {
buffer.reject1h_.push_back(std::to_string(status.reject1h_));
buffer.reject1h_.push_back(std::to_string(workerId));
}
// accept_count
if (redisIndexPolicy_ & REDIS_INDEX_ACCEPT_COUNT) {
buffer.acceptCount_.push_back(std::to_string(status.acceptCount_));
buffer.acceptCount_.push_back(std::to_string(workerId));
}
// last_share_ip
if (redisIndexPolicy_ & REDIS_INDEX_LAST_SHARE_IP) {
buffer.lastShareIP_.push_back(
std::to_string(status.lastShareIP_.addrUint64[1]));
buffer.lastShareIP_.push_back(std::to_string(workerId));
}
// last_share_time
if (redisIndexPolicy_ & REDIS_INDEX_LAST_SHARE_TIME) {
buffer.lastShareTime_.push_back(std::to_string(status.lastShareTime_));
buffer.lastShareTime_.push_back(std::to_string(workerId));
}
buffer.size_++;
}
template <class SHARE>
void StatsServerT<SHARE>::flushIndexToRedis(
RedisConnection *redis, const std::vector<string> &commandVector) {
redis->prepare(commandVector);
RedisResult r = redis->execute();
if (r.type() != REDIS_REPLY_INTEGER) {
LOG(INFO) << "redis ZADD failed, "
<< "item key: " << commandVector[1] << ", "
<< "reply type: " << r.type() << ", "
<< "reply str: " << r.str();
}
}
template <class SHARE>
void StatsServerT<SHARE>::flushUsersToRedis(uint32_t threadStep) {
RedisConnection *redis = redisGroup_[threadStep];
size_t userCounter = 0;
pthread_rwlock_rdlock(&rwlock_); // read lock
LOG(INFO) << "redis (thread " << threadStep << "): flush users, rd locked";
size_t stepSize = userSet_.size() / redisConcurrency_;
if (userSet_.size() % redisConcurrency_ != 0) {
// +1 to avoid missing the last few items.
// Example: 5 / 2 = 2. Each thread handles 2 items and the fifth was
// missing.
stepSize++;
}
size_t offsetBegin = stepSize * threadStep;
auto itr = userSet_.begin();
// move to the beginning position
for (size_t i = 0; i < offsetBegin && itr != userSet_.end(); i++, itr++)
;
// flush all users status in a stepSize
for (size_t i = 0; i < stepSize && itr != userSet_.end(); i++, itr++) {
userCounter++;
const int32_t userId = itr->first;
shared_ptr<WorkerShares<SHARE>> workerShare = itr->second;
const WorkerStatus status = workerShare->getWorkerStatus();
const int32_t workerCount = userWorkerCount_[userId];
string key = getRedisKeyMiningWorker(userId);
// update info
redis->prepare({"HMSET", key,
"worker_count", std::to_string(workerCount),
"accept_5m", std::to_string(status.accept5m_),
"accept_15m", std::to_string(status.accept15m_),
"stale_15m", std::to_string(status.stale15m_),
"reject_15m", std::to_string(status.reject15m_),
"accept_1h", std::to_string(status.accept1h_),
"stale_1h", std::to_string(status.stale1h_),
"reject_1h", std::to_string(status.reject1h_),
"accept_count", std::to_string(status.acceptCount_),
"last_share_ip", status.lastShareIP_.toString(),
"last_share_time", std::to_string(status.lastShareTime_),
"updated_at", std::to_string(time(nullptr))});
// set key expire
if (redisKeyExpire_ > 0) {
redis->prepare({"EXPIRE", key, std::to_string(redisKeyExpire_)});
}
// publish notification
if (redisPublishPolicy_ & REDIS_PUBLISH_USER_UPDATE) {
redis->prepare({"PUBLISH", key, std::to_string(workerCount)});
}
}
pthread_rwlock_unlock(&rwlock_); // unlock
LOG(INFO) << "redis (thread " << threadStep << "): flush users, rd unlock";
if (userCounter == 0) {
LOG(INFO) << "redis (thread " << threadStep << "): no active users";
return;
}
for (size_t i = 0; i < userCounter; i++) {
// update info
{
RedisResult r = redis->execute();
if (r.type() != REDIS_REPLY_STATUS || r.str() != "OK") {
LOG(INFO) << "redis (thread " << threadStep << ") HMSET failed, "
<< "item index: " << i << ", "
<< "reply type: " << r.type() << ", "
<< "reply str: " << r.str();
}
}
// set key expire
if (redisKeyExpire_ > 0) {
RedisResult r = redis->execute();
if (r.type() != REDIS_REPLY_INTEGER || r.integer() != 1) {
LOG(INFO) << "redis (thread " << threadStep << ") EXPIRE failed, "
<< "item index: " << i << ", "
<< "reply type: " << r.type() << ", "
<< "reply integer: " << r.integer() << ","
<< "reply str: " << r.str();
}
}
// publish notification
if (redisPublishPolicy_ & REDIS_PUBLISH_USER_UPDATE) {
RedisResult r = redis->execute();
if (r.type() != REDIS_REPLY_INTEGER) {
LOG(INFO) << "redis (thread " << threadStep << ") PUBLISH failed, "
<< "item index: " << i << ", "
<< "reply type: " << r.type() << ", "
<< "reply str: " << r.str();
}
}
}
LOG(INFO) << "flush users to redis (thread " << threadStep
<< ") done, users: " << userCounter;
return;
}
template <class SHARE>
void StatsServerT<SHARE>::flushWorkersAndUsersToDB() {
LOG(INFO) << "flush to DB...";
if (isInserting_) {
LOG(WARNING) << "last DB flush is not finish yet, ignore";
return;
}
isInserting_ = true;
std::thread t(
std::bind(&StatsServerT<SHARE>::_flushWorkersAndUsersToDBThread, this));
t.detach();
}
template <class SHARE>
void StatsServerT<SHARE>::_flushWorkersAndUsersToDBThread() {
//
// merge two table items
// table.`mining_workers` unique index: `puid` + `worker_id`
//
const string mergeSQL = R"(
INSERT INTO `mining_workers`
SELECT * FROM `mining_workers_tmp`
ON DUPLICATE KEY UPDATE
`mining_workers`.`accept_5m` = `mining_workers_tmp`.`accept_5m`,
`mining_workers`.`accept_15m` = `mining_workers_tmp`.`accept_15m`,
`mining_workers`.`stale_15m` = `mining_workers_tmp`.`stale_15m`,
`mining_workers`.`reject_15m` = `mining_workers_tmp`.`reject_15m`,
`mining_workers`.`reject_detail_15m` = `mining_workers_tmp`.`reject_detail_15m`,
`mining_workers`.`accept_1h` = `mining_workers_tmp`.`accept_1h`,
`mining_workers`.`stale_1h` = `mining_workers_tmp`.`stale_1h`,
`mining_workers`.`reject_1h` = `mining_workers_tmp`.`reject_1h`,
`mining_workers`.`reject_detail_1h` = `mining_workers_tmp`.`reject_detail_1h`,
`mining_workers`.`accept_count` = `mining_workers_tmp`.`accept_count`,
`mining_workers`.`last_share_ip` = `mining_workers_tmp`.`last_share_ip`,
`mining_workers`.`last_share_time` = `mining_workers_tmp`.`last_share_time`,
`mining_workers`.`updated_at` = `mining_workers_tmp`.`updated_at`
)";
// fields for table.mining_workers
const string fields =
"`worker_id`, `puid`, `group_id`, `accept_5m`, "
"`accept_15m`, `stale_15m`, `reject_15m`, `reject_detail_15m`, "
"`accept_1h`, `stale_1h`, `reject_1h`, reject_detail_1h, "
"`accept_count`, `last_share_ip`, "
"`last_share_time`, `created_at`, `updated_at`";
// values for multi-insert sql
vector<string> values;
size_t workerCounter = 0;
size_t userCounter = 0;
if (!poolDB_->ping()) {
LOG(ERROR) << "can't connect to pool DB";
goto finish;
}
pthread_rwlock_rdlock(&rwlock_); // read lock
LOG(INFO) << "flush DB: rd locked";
// get all workes status
for (auto itr = workerSet_.begin(); itr != workerSet_.end(); itr++) {
workerCounter++;
const int32_t userId = itr->first.userId_;
const int64_t workerId = itr->first.workerId_;
shared_ptr<WorkerShares<SHARE>> workerShare = itr->second;
const WorkerStatus status = workerShare->getWorkerStatus();
const string nowStr = date("%F %T", time(nullptr));
values.push_back(Strings::Format(
"%d,%d,%d,%u,"
"%u,%u,%u,'%s'," // accept_15m, stale_15m, reject_15m, reject_detail_15m
"%u,%u,%u,'%s'," // accept_1h, stale_1h, reject_1h, reject_detail_1h
"%d,\"%s\","
"\"%s\",\"%s\",\"%s\"",
workerId,
userId,
-1 * userId, /* default group id */
status.accept5m_,
status.accept15m_,
status.stale15m_,
status.reject15m_,
status.rejectDetail15m_,
status.accept1h_,
status.stale1h_,
status.reject1h_,
status.rejectDetail1h_,
status.acceptCount_,
status.lastShareIP_.toString(),
date("%F %T", status.lastShareTime_),
nowStr,
nowStr));
}
// get all users status
for (auto itr = userSet_.begin(); itr != userSet_.end(); itr++) {
userCounter++;
const int32_t userId = itr->first;
const int64_t workerId = 0;
shared_ptr<WorkerShares<SHARE>> workerShare = itr->second;
const WorkerStatus status = workerShare->getWorkerStatus();
const string nowStr = date("%F %T", time(nullptr));
values.push_back(Strings::Format(
"%d,%d,%d,%u,"
"%u,%u,%u,'%s'," // accept_15m, stale_15m, reject_15m, reject_detail_15m
"%u,%u,%u,'%s'," // accept_1h, stale_1h, reject_1h, reject_detail_1h
"%d,\"%s\","
"\"%s\",\"%s\",\"%s\"",
workerId,
userId,
-1 * userId, /* default group id */
status.accept5m_,
status.accept15m_,
status.stale15m_,
status.reject15m_,
status.rejectDetail15m_,
status.accept1h_,
status.stale1h_,