forked from ethereum-mining/ethminer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoolManager.cpp
More file actions
557 lines (468 loc) · 17.1 KB
/
Copy pathPoolManager.cpp
File metadata and controls
557 lines (468 loc) · 17.1 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
#include <chrono>
#include "PoolManager.h"
using namespace std;
using namespace dev;
using namespace eth;
PoolManager* PoolManager::m_this = nullptr;
PoolManager::PoolManager(PoolSettings _settings)
: m_Settings(std::move(_settings)),
m_io_strand(g_io_service),
m_failovertimer(g_io_service),
m_submithrtimer(g_io_service),
m_reconnecttimer(g_io_service)
{
DEV_BUILD_LOG_PROGRAMFLOW(cnote, "PoolManager::PoolManager() begin");
m_this = this;
m_currentWp.header = h256();
Farm::f().onMinerRestart([&]() {
cnote << "Restart miners...";
if (Farm::f().isMining())
{
cnote << "Shutting down miners...";
Farm::f().stop();
}
cnote << "Spinning up miners...";
Farm::f().start();
});
Farm::f().onSolutionFound([&](const Solution& sol) {
// Solution should passthrough only if client is
// properly connected. Otherwise we'll have the bad behavior
// to log nonce submission but receive no response
if (p_client && p_client->isConnected())
{
p_client->submitSolution(sol);
}
else
{
cnote << string(EthOrange "Solution 0x") + toHex(sol.nonce)
<< " wasted. Waiting for connection...";
}
return false;
});
DEV_BUILD_LOG_PROGRAMFLOW(cnote, "PoolManager::PoolManager() end");
}
void PoolManager::setClientHandlers()
{
p_client->onConnected([&]() {
{
// If HostName is already an IP address no need to append the
// effective ip address.
if (p_client->getConnection()->HostNameType() == dev::UriHostNameType::Dns ||
p_client->getConnection()->HostNameType() == dev::UriHostNameType::Basic)
{
string ep = p_client->ActiveEndPoint();
if (!ep.empty())
m_selectedHost = p_client->getConnection()->Host() + ep;
}
cnote << "Established connection to " << m_selectedHost;
m_connectionAttempt = 0;
// Reset current WorkPackage
m_currentWp.job.clear();
m_currentWp.header = h256();
// Shuffle if needed
if (Farm::f().get_ergodicity() == 1U)
Farm::f().shuffle();
// Rough implementation to return to primary pool
// after specified amount of time
if (m_activeConnectionIdx != 0 && m_Settings.poolFailoverTimeout)
{
m_failovertimer.expires_from_now(
boost::posix_time::minutes(m_Settings.poolFailoverTimeout));
m_failovertimer.async_wait(m_io_strand.wrap(boost::bind(
&PoolManager::failovertimer_elapsed, this, boost::asio::placeholders::error)));
}
else
{
m_failovertimer.cancel();
}
}
if (!Farm::f().isMining())
{
cnote << "Spinning up miners...";
Farm::f().start();
}
else if (Farm::f().paused())
{
cnote << "Resume mining ...";
Farm::f().resume();
}
// Activate timing for HR submission
if (m_Settings.reportHashrate)
{
m_submithrtimer.expires_from_now(boost::posix_time::seconds(m_Settings.hashRateInterval));
m_submithrtimer.async_wait(m_io_strand.wrap(boost::bind(
&PoolManager::submithrtimer_elapsed, this, boost::asio::placeholders::error)));
}
// Signal async operations have completed
m_async_pending.store(false, std::memory_order_relaxed);
});
p_client->onDisconnected([&]() {
cnote << "Disconnected from " << m_selectedHost;
// Clear current connection
p_client->unsetConnection();
m_currentWp.header = h256();
// Stop timing actors
m_failovertimer.cancel();
m_submithrtimer.cancel();
if (m_stopping.load(std::memory_order_relaxed))
{
if (Farm::f().isMining())
{
cnote << "Shutting down miners...";
Farm::f().stop();
}
m_running.store(false, std::memory_order_relaxed);
}
else
{
// Signal we will reconnect async
m_async_pending.store(true, std::memory_order_relaxed);
// Suspend mining and submit new connection request
cnote << "No connection. Suspend mining ...";
Farm::f().pause();
g_io_service.post(m_io_strand.wrap(boost::bind(&PoolManager::rotateConnect, this)));
}
});
p_client->onWorkReceived([&](WorkPackage const& wp) {
// Should not happen !
if (!wp)
return;
int _currentEpoch = m_currentWp.epoch;
bool newEpoch = (_currentEpoch == -1);
// In EthereumStratum/2.0.0 epoch number is set in session
if (!newEpoch)
{
if (p_client->getConnection()->StratumMode() == 3)
newEpoch = (wp.epoch != m_currentWp.epoch);
else
newEpoch = (wp.seed != m_currentWp.seed);
}
bool newDiff = (wp.boundary != m_currentWp.boundary);
m_currentWp = wp;
if (newEpoch)
{
m_epochChanges.fetch_add(1, std::memory_order_relaxed);
// If epoch is valued in workpackage take it
if (wp.epoch == -1)
{
if (m_currentWp.block >= 0)
m_currentWp.epoch = m_currentWp.block / 30000;
else
m_currentWp.epoch = ethash::find_epoch_number(
ethash::hash256_from_bytes(m_currentWp.seed.data()));
}
}
else
{
m_currentWp.epoch = _currentEpoch;
}
if (newDiff || newEpoch)
showMiningAt();
cnote << "Job: " EthWhite << m_currentWp.header.abridged()
<< (m_currentWp.block != -1 ? (" block " + to_string(m_currentWp.block)) : "")
<< EthReset << " " << m_selectedHost;
Farm::f().setWork(m_currentWp);
});
p_client->onSolutionAccepted(
[&](std::chrono::milliseconds const& _responseDelay, unsigned const& _minerIdx, bool _asStale) {
std::stringstream ss;
ss << std::setw(4) << std::setfill(' ') << _responseDelay.count() << " ms. "
<< m_selectedHost;
cnote << EthLime "**Accepted" << (_asStale ? " stale": "") << EthReset << ss.str();
Farm::f().accountSolution(_minerIdx, SolutionAccountingEnum::Accepted);
});
p_client->onSolutionRejected(
[&](std::chrono::milliseconds const& _responseDelay, unsigned const& _minerIdx) {
std::stringstream ss;
ss << std::setw(4) << std::setfill(' ') << _responseDelay.count() << " ms. "
<< m_selectedHost;
cwarn << EthRed "**Rejected" EthReset << ss.str();
Farm::f().accountSolution(_minerIdx, SolutionAccountingEnum::Rejected);
});
}
void PoolManager::stop()
{
DEV_BUILD_LOG_PROGRAMFLOW(cnote, "PoolManager::stop() begin");
if (m_running.load(std::memory_order_relaxed))
{
m_async_pending.store(true, std::memory_order_relaxed);
m_stopping.store(true, std::memory_order_relaxed);
if (p_client && p_client->isConnected())
{
p_client->disconnect();
// Wait for async operations to complete
while (m_running.load(std::memory_order_relaxed))
this_thread::sleep_for(chrono::milliseconds(500));
p_client = nullptr;
}
else
{
// Stop timing actors
m_failovertimer.cancel();
m_submithrtimer.cancel();
m_reconnecttimer.cancel();
if (Farm::f().isMining())
{
cnote << "Shutting down miners...";
Farm::f().stop();
}
}
}
DEV_BUILD_LOG_PROGRAMFLOW(cnote, "PoolManager::stop() end");
}
void PoolManager::addConnection(std::string _connstring)
{
m_Settings.connections.push_back(std::shared_ptr<URI>(new URI(_connstring)));
}
void PoolManager::addConnection(std::shared_ptr<URI> _uri)
{
m_Settings.connections.push_back(_uri);
}
/*
* Remove a connection
* Returns: 0 on success
* -1 failure (out of bounds)
* -2 failure (active connection should be deleted)
*/
void PoolManager::removeConnection(unsigned int idx)
{
// Are there any outstanding operations ?
if (m_async_pending.load(std::memory_order_relaxed))
throw std::runtime_error("Outstanding operations. Retry ...");
// Check bounds
if (idx >= m_Settings.connections.size())
throw std::runtime_error("Index out-of bounds.");
// Can't delete active connection
if (idx == m_activeConnectionIdx)
throw std::runtime_error("Can't remove active connection");
// Remove the selected connection
m_Settings.connections.erase(m_Settings.connections.begin() + idx);
if (m_activeConnectionIdx > idx)
m_activeConnectionIdx--;
}
void PoolManager::setActiveConnectionCommon(unsigned int idx)
{
// Are there any outstanding operations ?
bool ex = false;
if (!m_async_pending.compare_exchange_strong(ex, true))
throw std::runtime_error("Outstanding operations. Retry ...");
if (idx != m_activeConnectionIdx)
{
m_connectionSwitches.fetch_add(1, std::memory_order_relaxed);
m_activeConnectionIdx = idx;
m_connectionAttempt = 0;
p_client->disconnect();
}
else
{
// Release the flag immediately
m_async_pending.store(false, std::memory_order_relaxed);
}
}
/*
* Sets the active connection
* Returns: 0 on success, -1 on failure (out of bounds)
*/
void PoolManager::setActiveConnection(unsigned int idx)
{
// Sets the active connection to the requested index
if (idx >= m_Settings.connections.size())
throw std::runtime_error("Index out-of bounds.");
setActiveConnectionCommon(idx);
}
void PoolManager::setActiveConnection(std::string& _connstring)
{
for (size_t idx = 0; idx < m_Settings.connections.size(); idx++)
if (boost::iequals(m_Settings.connections[idx]->str(), _connstring))
{
setActiveConnectionCommon(idx);
return;
}
throw std::runtime_error("Not found.");
}
std::shared_ptr<URI> PoolManager::getActiveConnection()
{
try
{
return m_Settings.connections.at(m_activeConnectionIdx);
}
catch (const std::exception&)
{
return nullptr;
}
}
Json::Value PoolManager::getConnectionsJson()
{
// Returns the list of configured connections
Json::Value jRes;
for (size_t i = 0; i < m_Settings.connections.size(); i++)
{
Json::Value JConn;
JConn["index"] = (unsigned)i;
JConn["active"] = (i == m_activeConnectionIdx ? true : false);
JConn["uri"] = m_Settings.connections[i]->str();
jRes.append(JConn);
}
return jRes;
}
void PoolManager::start()
{
m_running.store(true, std::memory_order_relaxed);
m_async_pending.store(true, std::memory_order_relaxed);
m_connectionSwitches.fetch_add(1, std::memory_order_relaxed);
g_io_service.post(m_io_strand.wrap(boost::bind(&PoolManager::rotateConnect, this)));
}
void PoolManager::rotateConnect()
{
if (p_client && p_client->isConnected())
return;
// Check we're within bounds
if (m_activeConnectionIdx >= m_Settings.connections.size())
m_activeConnectionIdx = 0;
// If this connection is marked Unrecoverable then discard it
if (m_Settings.connections.at(m_activeConnectionIdx)->IsUnrecoverable())
{
m_Settings.connections.erase(m_Settings.connections.begin() + m_activeConnectionIdx);
m_connectionAttempt = 0;
if (m_activeConnectionIdx >= m_Settings.connections.size())
m_activeConnectionIdx = 0;
m_connectionSwitches.fetch_add(1, std::memory_order_relaxed);
}
else if (m_connectionAttempt >= m_Settings.connectionMaxRetries)
{
// If this is the only connection we can't rotate
// forever
if (m_Settings.connections.size() == 1)
{
m_Settings.connections.erase(m_Settings.connections.begin() + m_activeConnectionIdx);
}
// Rotate connections if above max attempts threshold
else
{
m_connectionAttempt = 0;
m_activeConnectionIdx++;
if (m_activeConnectionIdx >= m_Settings.connections.size())
m_activeConnectionIdx = 0;
m_connectionSwitches.fetch_add(1, std::memory_order_relaxed);
}
}
if (!m_Settings.connections.empty() && m_Settings.connections.at(m_activeConnectionIdx)->Host() != "exit")
{
if (p_client)
p_client = nullptr;
if (m_Settings.connections.at(m_activeConnectionIdx)->Family() == ProtocolFamily::GETWORK)
p_client =
std::unique_ptr<PoolClient>(new EthGetworkClient(m_Settings.noWorkTimeout, m_Settings.getWorkPollInterval));
if (m_Settings.connections.at(m_activeConnectionIdx)->Family() == ProtocolFamily::STRATUM)
p_client = std::unique_ptr<PoolClient>(
new EthStratumClient(m_Settings.noWorkTimeout, m_Settings.noResponseTimeout));
if (m_Settings.connections.at(m_activeConnectionIdx)->Family() == ProtocolFamily::SIMULATION)
p_client = std::unique_ptr<PoolClient>(new SimulateClient(m_Settings.benchmarkBlock));
if (p_client)
setClientHandlers();
// Count connectionAttempts
m_connectionAttempt++;
// Invoke connections
m_selectedHost = m_Settings.connections.at(m_activeConnectionIdx)->Host() + ":" +
to_string(m_Settings.connections.at(m_activeConnectionIdx)->Port());
p_client->setConnection(m_Settings.connections.at(m_activeConnectionIdx));
cnote << "Selected pool " << m_selectedHost;
if ((m_connectionAttempt > 1) && (m_Settings.delayBeforeRetry > 0))
{
cnote << "Next connection attempt in " << m_Settings.delayBeforeRetry << " seconds";
m_reconnecttimer.expires_from_now(boost::posix_time::seconds(m_Settings.delayBeforeRetry));
m_reconnecttimer.async_wait(m_io_strand.wrap(boost::bind(
&PoolManager::reconnecttimer_elapsed, this, boost::asio::placeholders::error)));
}
else
{
p_client->connect();
}
}
else
{
if (m_Settings.connections.empty())
cnote << "No more connections to try. Exiting...";
else
cnote << "'exit' failover just got hit. Exiting...";
// Stop mining if applicable
if (Farm::f().isMining())
{
cnote << "Shutting down miners...";
Farm::f().stop();
}
m_running.store(false, std::memory_order_relaxed);
raise(SIGTERM);
}
}
void PoolManager::showMiningAt()
{
// Should not happen
if (!m_currentWp)
return;
double d = dev::getHashesToTarget(m_currentWp.boundary.hex(HexPrefix::Add));
cnote << "Epoch : " EthWhite << m_currentWp.epoch << EthReset << " Difficulty : " EthWhite
<< dev::getFormattedHashes(d) << EthReset;
}
void PoolManager::failovertimer_elapsed(const boost::system::error_code& ec)
{
if (!ec)
{
if (m_running.load(std::memory_order_relaxed))
{
if (m_activeConnectionIdx != 0)
{
m_activeConnectionIdx = 0;
m_connectionAttempt = 0;
m_connectionSwitches.fetch_add(1, std::memory_order_relaxed);
cnote << "Failover timeout reached, retrying connection to primary pool";
p_client->disconnect();
}
}
}
}
void PoolManager::submithrtimer_elapsed(const boost::system::error_code& ec)
{
if (!ec)
{
if (m_running.load(std::memory_order_relaxed))
{
if (p_client && p_client->isConnected())
p_client->submitHashrate((uint32_t)Farm::f().HashRate(), m_Settings.hashRateId);
// Resubmit actor
m_submithrtimer.expires_from_now(boost::posix_time::seconds(m_Settings.hashRateInterval));
m_submithrtimer.async_wait(m_io_strand.wrap(boost::bind(
&PoolManager::submithrtimer_elapsed, this, boost::asio::placeholders::error)));
}
}
}
void PoolManager::reconnecttimer_elapsed(const boost::system::error_code& ec)
{
if (ec)
return;
if (m_running.load(std::memory_order_relaxed))
{
if (p_client && !p_client->isConnected())
{
p_client->connect();
}
}
}
int PoolManager::getCurrentEpoch()
{
return m_currentWp.epoch;
}
double PoolManager::getCurrentDifficulty()
{
if (!m_currentWp)
return 0.0;
return dev::getHashesToTarget(m_currentWp.boundary.hex(HexPrefix::Add));
}
unsigned PoolManager::getConnectionSwitches()
{
return m_connectionSwitches.load(std::memory_order_relaxed);
}
unsigned PoolManager::getEpochChanges()
{
return m_epochChanges.load(std::memory_order_relaxed);
}