-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpeer_manager.cpp
More file actions
69 lines (60 loc) · 2.18 KB
/
peer_manager.cpp
File metadata and controls
69 lines (60 loc) · 2.18 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
#include "peer_manager.h"
#include "cidr_utils.h"
#include "peer_client.h"
#include <chrono>
#include <thread>
#include <iostream> // TODO : REMOVE
PeerManager::PeerManager(const std::string& cidr, uint16_t port, int interval_seconds, const std::string& our_ip)
: cidr_(cidr), port_(port + 200/*Adding 200 to peer port like seen in p2 handout*/), interval_(interval_seconds), our_ip_(our_ip), running_(true)
{
if (!cidr_.empty()) {
worker_ = std::thread([this]{ scan_loop(); });
} else {
running_ = false;
}
}
PeerManager::~PeerManager() {
stop();
}
void PeerManager::stop() { // TODO :
if (running_.exchange(false)) {
if (worker_.joinable())
worker_.join();
} else {
if (worker_.joinable())
worker_.join();
}
}
std::vector<std::string> PeerManager::peers() const {
std::lock_guard<std::mutex> lk(mu_);
return std::vector<std::string>(alive_.begin(), alive_.end());
}
void PeerManager::scan_loop() {
while (running_) {
one_scan();
if (running_) {
//std::cout << "Sleep for " << interval_ << " seconds" << std::endl; // TODO : REMOVE
std::this_thread::sleep_for(std::chrono::seconds(interval_));
//std::cout << "Woke up from sleep" << std::endl; // TODO : REMOVE
}
}
}
void PeerManager::one_scan() {
//std::cout << "Peermngr: scan " << cidr_ << " : " << port_ << std::endl; // TODO : REMOVE
auto hosts = netcidr::enumerate_ipv4_hosts(cidr_); // keep
//std::cout << "Parsing " << hosts.size() << " hosts" << std::endl; // TODO : REMOVE
std::set<std::string> new_alive;
for (auto h : hosts) {
auto ip = netcidr::ip_to_string(h);
if (ip == our_ip_) // skip self
continue;
PeerClient pc(ip, port_ - 200 /*Peerclient adds its own 200*/, our_ip_);
//std::cout << "Testing peer: " << ip << " port:" << port_ << std::endl; // TODO : REMOVE
if (pc.good()) {
new_alive.insert(ip);
//std::cout << "Peer found: " << ip << std::endl; // TODO : REMOVE
}
}
std::lock_guard<std::mutex> lk(mu_);
alive_.swap(new_alive); // replace old set with new set
}