Struct sc_network::NetworkWorker
source · pub struct NetworkWorker<B, H, Client>where
B: BlockT + 'static,
H: ExHashT,
Client: HeaderBackend<B> + 'static,{ /* private fields */ }Expand description
Main network worker. Must be polled in order for the network to advance.
You are encouraged to poll this in a separate background thread or task.
Implementations§
source§impl<B, H, Client> NetworkWorker<B, H, Client>where
B: BlockT + 'static,
H: ExHashT,
Client: HeaderBackend<B> + 'static,
impl<B, H, Client> NetworkWorker<B, H, Client>where
B: BlockT + 'static,
H: ExHashT,
Client: HeaderBackend<B> + 'static,
sourcepub fn new(params: Params<B, Client>) -> Result<Self, Error>
pub fn new(params: Params<B, Client>) -> Result<Self, Error>
Creates the network service.
Returns a NetworkWorker that implements Future and must be regularly polled in order
for the network processing to advance. From it, you can extract a NetworkService using
worker.service(). The NetworkService can be shared through the codebase.
sourcepub fn status(&self) -> NetworkStatus<B>
pub fn status(&self) -> NetworkStatus<B>
High-level network status information.
Examples found in repository?
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
let this = &mut *self;
// At the time of writing of this comment, due to a high volume of messages, the network
// worker sometimes takes a long time to process the loop below. When that happens, the
// rest of the polling is frozen. In order to avoid negative side-effects caused by this
// freeze, a limit to the number of iterations is enforced below. If the limit is reached,
// the task is interrupted then scheduled again.
//
// This allows for a more even distribution in the time taken by each sub-part of the
// polling.
let mut num_iterations = 0;
loop {
num_iterations += 1;
if num_iterations >= 100 {
cx.waker().wake_by_ref();
break
}
// Process the next message coming from the `NetworkService`.
let msg = match this.from_service.poll_next_unpin(cx) {
Poll::Ready(Some(msg)) => msg,
Poll::Ready(None) => return Poll::Ready(()),
Poll::Pending => break,
};
match msg {
ServiceToWorkerMsg::AnnounceBlock(hash, data) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.announce_block(hash, data),
ServiceToWorkerMsg::GetValue(key) =>
this.network_service.behaviour_mut().get_value(key),
ServiceToWorkerMsg::PutValue(key, value) =>
this.network_service.behaviour_mut().put_value(key, value),
ServiceToWorkerMsg::SetReservedOnly(reserved_only) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.set_reserved_only(reserved_only),
ServiceToWorkerMsg::SetReserved(peers) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.set_reserved_peers(peers),
ServiceToWorkerMsg::SetPeersetReserved(protocol, peers) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.set_reserved_peerset_peers(protocol, peers),
ServiceToWorkerMsg::AddReserved(peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.add_reserved_peer(peer_id),
ServiceToWorkerMsg::RemoveReserved(peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.remove_reserved_peer(peer_id),
ServiceToWorkerMsg::AddSetReserved(protocol, peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.add_set_reserved_peer(protocol, peer_id),
ServiceToWorkerMsg::RemoveSetReserved(protocol, peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.remove_set_reserved_peer(protocol, peer_id),
ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) =>
this.network_service.behaviour_mut().add_known_address(peer_id, addr),
ServiceToWorkerMsg::AddToPeersSet(protocol, peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.add_to_peers_set(protocol, peer_id),
ServiceToWorkerMsg::RemoveFromPeersSet(protocol, peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.remove_from_peers_set(protocol, peer_id),
ServiceToWorkerMsg::EventStream(sender) => this.event_streams.push(sender),
ServiceToWorkerMsg::Request {
target,
protocol,
request,
pending_response,
connect,
} => {
this.network_service.behaviour_mut().send_request(
&target,
&protocol,
request,
pending_response,
connect,
);
},
ServiceToWorkerMsg::NetworkStatus { pending_response } => {
let _ = pending_response.send(Ok(this.status()));
},
ServiceToWorkerMsg::NetworkState { pending_response } => {
let _ = pending_response.send(Ok(this.network_state()));
},
ServiceToWorkerMsg::DisconnectPeer(who, protocol_name) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.disconnect_peer(&who, protocol_name),
ServiceToWorkerMsg::NewBestBlockImported(hash, number) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.new_best_block_imported(hash, number),
}
}
// `num_iterations` serves the same purpose as in the previous loop.
// See the previous loop for explanations.
let mut num_iterations = 0;
loop {
num_iterations += 1;
if num_iterations >= 1000 {
cx.waker().wake_by_ref();
break
}
// Process the next action coming from the network.
let next_event = this.network_service.select_next_some();
futures::pin_mut!(next_event);
let poll_value = next_event.poll_unpin(cx);
match poll_value {
Poll::Pending => break,
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::InboundRequest {
protocol,
result,
..
})) => {
if let Some(metrics) = this.metrics.as_ref() {
match result {
Ok(serve_time) => {
metrics
.requests_in_success_total
.with_label_values(&[&protocol])
.observe(serve_time.as_secs_f64());
},
Err(err) => {
let reason = match err {
ResponseFailure::Network(InboundFailure::Timeout) => "timeout",
ResponseFailure::Network(
InboundFailure::UnsupportedProtocols,
) =>
// `UnsupportedProtocols` is reported for every single
// inbound request whenever a request with an unsupported
// protocol is received. This is not reported in order to
// avoid confusions.
continue,
ResponseFailure::Network(InboundFailure::ResponseOmission) =>
"busy-omitted",
ResponseFailure::Network(InboundFailure::ConnectionClosed) =>
"connection-closed",
};
metrics
.requests_in_failure_total
.with_label_values(&[&protocol, reason])
.inc();
},
}
}
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::RequestFinished {
protocol,
duration,
result,
..
})) =>
if let Some(metrics) = this.metrics.as_ref() {
match result {
Ok(_) => {
metrics
.requests_out_success_total
.with_label_values(&[&protocol])
.observe(duration.as_secs_f64());
},
Err(err) => {
let reason = match err {
RequestFailure::NotConnected => "not-connected",
RequestFailure::UnknownProtocol => "unknown-protocol",
RequestFailure::Refused => "refused",
RequestFailure::Obsolete => "obsolete",
RequestFailure::Network(OutboundFailure::DialFailure) =>
"dial-failure",
RequestFailure::Network(OutboundFailure::Timeout) => "timeout",
RequestFailure::Network(OutboundFailure::ConnectionClosed) =>
"connection-closed",
RequestFailure::Network(
OutboundFailure::UnsupportedProtocols,
) => "unsupported",
};
metrics
.requests_out_failure_total
.with_label_values(&[&protocol, reason])
.inc();
},
}
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::ReputationChanges {
peer,
changes,
})) =>
for change in changes {
this.network_service.behaviour().user_protocol().report_peer(peer, change);
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::PeerIdentify {
peer_id,
info:
IdentifyInfo {
protocol_version,
agent_version,
mut listen_addrs,
protocols,
..
},
})) => {
if listen_addrs.len() > 30 {
debug!(
target: "sub-libp2p",
"Node {:?} has reported more than 30 addresses; it is identified by {:?} and {:?}",
peer_id, protocol_version, agent_version
);
listen_addrs.truncate(30);
}
for addr in listen_addrs {
this.network_service
.behaviour_mut()
.add_self_reported_address_to_dht(&peer_id, &protocols, addr);
}
this.network_service
.behaviour_mut()
.user_protocol_mut()
.add_default_set_discovered_nodes(iter::once(peer_id));
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::Discovered(peer_id))) => {
this.network_service
.behaviour_mut()
.user_protocol_mut()
.add_default_set_discovered_nodes(iter::once(peer_id));
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::RandomKademliaStarted)) =>
if let Some(metrics) = this.metrics.as_ref() {
metrics.kademlia_random_queries_total.inc();
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamOpened {
remote,
protocol,
negotiated_fallback,
notifications_sink,
role,
})) => {
if let Some(metrics) = this.metrics.as_ref() {
metrics
.notifications_streams_opened_total
.with_label_values(&[&protocol])
.inc();
}
{
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
let _previous_value = peers_notifications_sinks
.insert((remote, protocol.clone()), notifications_sink);
debug_assert!(_previous_value.is_none());
}
this.event_streams.send(Event::NotificationStreamOpened {
remote,
protocol,
negotiated_fallback,
role,
});
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamReplaced {
remote,
protocol,
notifications_sink,
})) => {
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
if let Some(s) = peers_notifications_sinks.get_mut(&(remote, protocol)) {
*s = notifications_sink;
} else {
error!(
target: "sub-libp2p",
"NotificationStreamReplaced for non-existing substream"
);
debug_assert!(false);
}
// TODO: Notifications might have been lost as a result of the previous
// connection being dropped, and as a result it would be preferable to notify
// the users of this fact by simulating the substream being closed then
// reopened.
// The code below doesn't compile because `role` is unknown. Propagating the
// handshake of the secondary connections is quite an invasive change and
// would conflict with https://github.com/paritytech/substrate/issues/6403.
// Considering that dropping notifications is generally regarded as
// acceptable, this bug is at the moment intentionally left there and is
// intended to be fixed at the same time as
// https://github.com/paritytech/substrate/issues/6403.
// this.event_streams.send(Event::NotificationStreamClosed {
// remote,
// protocol,
// });
// this.event_streams.send(Event::NotificationStreamOpened {
// remote,
// protocol,
// role,
// });
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamClosed {
remote,
protocol,
})) => {
if let Some(metrics) = this.metrics.as_ref() {
metrics
.notifications_streams_closed_total
.with_label_values(&[&protocol[..]])
.inc();
}
this.event_streams.send(Event::NotificationStreamClosed {
remote,
protocol: protocol.clone(),
});
{
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
let _previous_value = peers_notifications_sinks.remove(&(remote, protocol));
debug_assert!(_previous_value.is_some());
}
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationsReceived {
remote,
messages,
})) => {
if let Some(metrics) = this.metrics.as_ref() {
for (protocol, message) in &messages {
metrics
.notifications_sizes
.with_label_values(&["in", protocol])
.observe(message.len() as f64);
}
}
this.event_streams.send(Event::NotificationsReceived { remote, messages });
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::SyncConnected(remote))) => {
this.event_streams.send(Event::SyncConnected { remote });
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::SyncDisconnected(remote))) => {
this.event_streams.send(Event::SyncDisconnected { remote });
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::Dht(event, duration))) => {
if let Some(metrics) = this.metrics.as_ref() {
let query_type = match event {
DhtEvent::ValueFound(_) => "value-found",
DhtEvent::ValueNotFound(_) => "value-not-found",
DhtEvent::ValuePut(_) => "value-put",
DhtEvent::ValuePutFailed(_) => "value-put-failed",
};
metrics
.kademlia_query_duration
.with_label_values(&[query_type])
.observe(duration.as_secs_f64());
}
this.event_streams.send(Event::Dht(event));
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::None)) => {
// Ignored event from lower layers.
},
Poll::Ready(SwarmEvent::ConnectionEstablished {
peer_id,
endpoint,
num_established,
concurrent_dial_errors,
}) => {
if let Some(errors) = concurrent_dial_errors {
debug!(target: "sub-libp2p", "Libp2p => Connected({:?}) with errors: {:?}", peer_id, errors);
} else {
debug!(target: "sub-libp2p", "Libp2p => Connected({:?})", peer_id);
}
if let Some(metrics) = this.metrics.as_ref() {
let direction = match endpoint {
ConnectedPoint::Dialer { .. } => "out",
ConnectedPoint::Listener { .. } => "in",
};
metrics.connections_opened_total.with_label_values(&[direction]).inc();
if num_established.get() == 1 {
metrics.distinct_peers_connections_opened_total.inc();
}
}
},
Poll::Ready(SwarmEvent::ConnectionClosed {
peer_id,
cause,
endpoint,
num_established,
}) => {
debug!(target: "sub-libp2p", "Libp2p => Disconnected({:?}, {:?})", peer_id, cause);
if let Some(metrics) = this.metrics.as_ref() {
let direction = match endpoint {
ConnectedPoint::Dialer { .. } => "out",
ConnectedPoint::Listener { .. } => "in",
};
let reason = match cause {
Some(ConnectionError::IO(_)) => "transport-error",
Some(ConnectionError::Handler(EitherError::A(EitherError::A(
EitherError::B(EitherError::A(PingFailure::Timeout)),
)))) => "ping-timeout",
Some(ConnectionError::Handler(EitherError::A(EitherError::A(
EitherError::A(NotifsHandlerError::SyncNotificationsClogged),
)))) => "sync-notifications-clogged",
Some(ConnectionError::Handler(_)) => "protocol-error",
Some(ConnectionError::KeepAliveTimeout) => "keep-alive-timeout",
None => "actively-closed",
};
metrics
.connections_closed_total
.with_label_values(&[direction, reason])
.inc();
// `num_established` represents the number of *remaining* connections.
if num_established == 0 {
metrics.distinct_peers_connections_closed_total.inc();
}
}
},
Poll::Ready(SwarmEvent::NewListenAddr { address, .. }) => {
trace!(target: "sub-libp2p", "Libp2p => NewListenAddr({})", address);
if let Some(metrics) = this.metrics.as_ref() {
metrics.listeners_local_addresses.inc();
}
},
Poll::Ready(SwarmEvent::ExpiredListenAddr { address, .. }) => {
info!(target: "sub-libp2p", "📪 No longer listening on {}", address);
if let Some(metrics) = this.metrics.as_ref() {
metrics.listeners_local_addresses.dec();
}
},
Poll::Ready(SwarmEvent::OutgoingConnectionError { peer_id, error }) => {
if let Some(peer_id) = peer_id {
trace!(
target: "sub-libp2p",
"Libp2p => Failed to reach {:?}: {}",
peer_id, error,
);
if this.boot_node_ids.contains(&peer_id) {
if let DialError::WrongPeerId { obtained, endpoint } = &error {
if let ConnectedPoint::Dialer { address, role_override: _ } =
endpoint
{
warn!(
"💔 The bootnode you want to connect to at `{}` provided a different peer ID `{}` than the one you expect `{}`.",
address,
obtained,
peer_id,
);
}
}
}
}
if let Some(metrics) = this.metrics.as_ref() {
let reason = match error {
DialError::ConnectionLimit(_) => Some("limit-reached"),
DialError::InvalidPeerId(_) => Some("invalid-peer-id"),
DialError::Transport(_) | DialError::ConnectionIo(_) =>
Some("transport-error"),
DialError::Banned |
DialError::LocalPeerId |
DialError::NoAddresses |
DialError::DialPeerConditionFalse(_) |
DialError::WrongPeerId { .. } |
DialError::Aborted => None, // ignore them
};
if let Some(reason) = reason {
metrics
.pending_connections_errors_total
.with_label_values(&[reason])
.inc();
}
}
},
Poll::Ready(SwarmEvent::Dialing(peer_id)) => {
trace!(target: "sub-libp2p", "Libp2p => Dialing({:?})", peer_id)
},
Poll::Ready(SwarmEvent::IncomingConnection { local_addr, send_back_addr }) => {
trace!(target: "sub-libp2p", "Libp2p => IncomingConnection({},{}))",
local_addr, send_back_addr);
if let Some(metrics) = this.metrics.as_ref() {
metrics.incoming_connections_total.inc();
}
},
Poll::Ready(SwarmEvent::IncomingConnectionError {
local_addr,
send_back_addr,
error,
}) => {
debug!(
target: "sub-libp2p",
"Libp2p => IncomingConnectionError({},{}): {}",
local_addr, send_back_addr, error,
);
if let Some(metrics) = this.metrics.as_ref() {
let reason = match error {
PendingConnectionError::ConnectionLimit(_) => Some("limit-reached"),
PendingConnectionError::WrongPeerId { .. } => Some("invalid-peer-id"),
PendingConnectionError::Transport(_) |
PendingConnectionError::IO(_) => Some("transport-error"),
PendingConnectionError::Aborted => None, // ignore it
};
if let Some(reason) = reason {
metrics
.incoming_connections_errors_total
.with_label_values(&[reason])
.inc();
}
}
},
Poll::Ready(SwarmEvent::BannedPeer { peer_id, endpoint }) => {
debug!(
target: "sub-libp2p",
"Libp2p => BannedPeer({}). Connected via {:?}.",
peer_id, endpoint,
);
if let Some(metrics) = this.metrics.as_ref() {
metrics
.incoming_connections_errors_total
.with_label_values(&["banned"])
.inc();
}
},
Poll::Ready(SwarmEvent::ListenerClosed { reason, addresses, .. }) => {
if let Some(metrics) = this.metrics.as_ref() {
metrics.listeners_local_addresses.sub(addresses.len() as u64);
}
let addrs =
addresses.into_iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ");
match reason {
Ok(()) => error!(
target: "sub-libp2p",
"📪 Libp2p listener ({}) closed gracefully",
addrs
),
Err(e) => error!(
target: "sub-libp2p",
"📪 Libp2p listener ({}) closed: {}",
addrs, e
),
}
},
Poll::Ready(SwarmEvent::ListenerError { error, .. }) => {
debug!(target: "sub-libp2p", "Libp2p => ListenerError: {}", error);
if let Some(metrics) = this.metrics.as_ref() {
metrics.listeners_errors_total.inc();
}
},
};
}
let num_connected_peers =
this.network_service.behaviour_mut().user_protocol_mut().num_connected_peers();
// Update the variables shared with the `NetworkService`.
this.num_connected.store(num_connected_peers, Ordering::Relaxed);
{
let external_addresses =
Swarm::<Behaviour<B, Client>>::external_addresses(&this.network_service)
.map(|r| &r.addr)
.cloned()
.collect();
*this.external_addresses.lock() = external_addresses;
}
let is_major_syncing = this
.network_service
.behaviour_mut()
.user_protocol_mut()
.sync_state()
.state
.is_major_syncing();
this.is_major_syncing.store(is_major_syncing, Ordering::Relaxed);
if let Some(metrics) = this.metrics.as_ref() {
if let Some(buckets) = this.network_service.behaviour_mut().num_entries_per_kbucket() {
for (lower_ilog2_bucket_bound, num_entries) in buckets {
metrics
.kbuckets_num_nodes
.with_label_values(&[&lower_ilog2_bucket_bound.to_string()])
.set(num_entries as u64);
}
}
if let Some(num_entries) = this.network_service.behaviour_mut().num_kademlia_records() {
metrics.kademlia_records_count.set(num_entries as u64);
}
if let Some(num_entries) =
this.network_service.behaviour_mut().kademlia_records_total_size()
{
metrics.kademlia_records_sizes_total.set(num_entries as u64);
}
metrics
.peerset_num_discovered
.set(this.network_service.behaviour_mut().user_protocol().num_discovered_peers()
as u64);
metrics.pending_connections.set(
Swarm::network_info(&this.network_service).connection_counters().num_pending()
as u64,
);
}
Poll::Pending
}sourcepub fn total_bytes_inbound(&self) -> u64
pub fn total_bytes_inbound(&self) -> u64
Returns the total number of bytes received so far.
Examples found in repository?
462 463 464 465 466 467 468 469 470 471 472 473 474 475
pub fn status(&self) -> NetworkStatus<B> {
let status = self.sync_state();
NetworkStatus {
sync_state: status.state,
best_seen_block: self.best_seen_block(),
num_sync_peers: self.num_sync_peers(),
num_connected_peers: self.num_connected_peers(),
num_active_peers: self.num_active_peers(),
total_bytes_inbound: self.total_bytes_inbound(),
total_bytes_outbound: self.total_bytes_outbound(),
state_sync: status.state_sync,
warp_sync: status.warp_sync,
}
}sourcepub fn total_bytes_outbound(&self) -> u64
pub fn total_bytes_outbound(&self) -> u64
Returns the total number of bytes sent so far.
Examples found in repository?
462 463 464 465 466 467 468 469 470 471 472 473 474 475
pub fn status(&self) -> NetworkStatus<B> {
let status = self.sync_state();
NetworkStatus {
sync_state: status.state,
best_seen_block: self.best_seen_block(),
num_sync_peers: self.num_sync_peers(),
num_connected_peers: self.num_connected_peers(),
num_active_peers: self.num_active_peers(),
total_bytes_inbound: self.total_bytes_inbound(),
total_bytes_outbound: self.total_bytes_outbound(),
state_sync: status.state_sync,
warp_sync: status.warp_sync,
}
}sourcepub fn num_connected_peers(&self) -> usize
pub fn num_connected_peers(&self) -> usize
Returns the number of peers we’re connected to.
Examples found in repository?
462 463 464 465 466 467 468 469 470 471 472 473 474 475
pub fn status(&self) -> NetworkStatus<B> {
let status = self.sync_state();
NetworkStatus {
sync_state: status.state,
best_seen_block: self.best_seen_block(),
num_sync_peers: self.num_sync_peers(),
num_connected_peers: self.num_connected_peers(),
num_active_peers: self.num_active_peers(),
total_bytes_inbound: self.total_bytes_inbound(),
total_bytes_outbound: self.total_bytes_outbound(),
state_sync: status.state_sync,
warp_sync: status.warp_sync,
}
}sourcepub fn num_active_peers(&self) -> usize
pub fn num_active_peers(&self) -> usize
Returns the number of peers we’re connected to and that are being queried.
Examples found in repository?
462 463 464 465 466 467 468 469 470 471 472 473 474 475
pub fn status(&self) -> NetworkStatus<B> {
let status = self.sync_state();
NetworkStatus {
sync_state: status.state,
best_seen_block: self.best_seen_block(),
num_sync_peers: self.num_sync_peers(),
num_connected_peers: self.num_connected_peers(),
num_active_peers: self.num_active_peers(),
total_bytes_inbound: self.total_bytes_inbound(),
total_bytes_outbound: self.total_bytes_outbound(),
state_sync: status.state_sync,
warp_sync: status.warp_sync,
}
}sourcepub fn sync_state(&self) -> SyncStatus<B>
pub fn sync_state(&self) -> SyncStatus<B>
Current global sync state.
Examples found in repository?
462 463 464 465 466 467 468 469 470 471 472 473 474 475
pub fn status(&self) -> NetworkStatus<B> {
let status = self.sync_state();
NetworkStatus {
sync_state: status.state,
best_seen_block: self.best_seen_block(),
num_sync_peers: self.num_sync_peers(),
num_connected_peers: self.num_connected_peers(),
num_active_peers: self.num_active_peers(),
total_bytes_inbound: self.total_bytes_inbound(),
total_bytes_outbound: self.total_bytes_outbound(),
state_sync: status.state_sync,
warp_sync: status.warp_sync,
}
}sourcepub fn best_seen_block(&self) -> Option<NumberFor<B>>
pub fn best_seen_block(&self) -> Option<NumberFor<B>>
Target sync block number.
Examples found in repository?
462 463 464 465 466 467 468 469 470 471 472 473 474 475
pub fn status(&self) -> NetworkStatus<B> {
let status = self.sync_state();
NetworkStatus {
sync_state: status.state,
best_seen_block: self.best_seen_block(),
num_sync_peers: self.num_sync_peers(),
num_connected_peers: self.num_connected_peers(),
num_active_peers: self.num_active_peers(),
total_bytes_inbound: self.total_bytes_inbound(),
total_bytes_outbound: self.total_bytes_outbound(),
state_sync: status.state_sync,
warp_sync: status.warp_sync,
}
}sourcepub fn num_sync_peers(&self) -> u32
pub fn num_sync_peers(&self) -> u32
Number of peers participating in syncing.
Examples found in repository?
462 463 464 465 466 467 468 469 470 471 472 473 474 475
pub fn status(&self) -> NetworkStatus<B> {
let status = self.sync_state();
NetworkStatus {
sync_state: status.state,
best_seen_block: self.best_seen_block(),
num_sync_peers: self.num_sync_peers(),
num_connected_peers: self.num_connected_peers(),
num_active_peers: self.num_active_peers(),
total_bytes_inbound: self.total_bytes_inbound(),
total_bytes_outbound: self.total_bytes_outbound(),
state_sync: status.state_sync,
warp_sync: status.warp_sync,
}
}sourcepub fn num_queued_blocks(&self) -> u32
pub fn num_queued_blocks(&self) -> u32
Number of blocks in the import queue.
sourcepub fn num_downloaded_blocks(&self) -> usize
pub fn num_downloaded_blocks(&self) -> usize
Returns the number of downloaded blocks.
sourcepub fn num_sync_requests(&self) -> usize
pub fn num_sync_requests(&self) -> usize
Number of active sync requests.
sourcepub fn add_known_address(&mut self, peer_id: PeerId, addr: Multiaddr)
pub fn add_known_address(&mut self, peer_id: PeerId, addr: Multiaddr)
Adds an address for a node.
sourcepub fn service(&self) -> &Arc<NetworkService<B, H>>
pub fn service(&self) -> &Arc<NetworkService<B, H>>
Return a NetworkService that can be shared through the code base and can be used to
manipulate the worker.
sourcepub fn on_block_finalized(&mut self, hash: B::Hash, header: B::Header)
pub fn on_block_finalized(&mut self, hash: B::Hash, header: B::Header)
You must call this when a new block is finalized by the client.
sourcepub fn new_best_block_imported(&mut self, hash: B::Hash, number: NumberFor<B>)
pub fn new_best_block_imported(&mut self, hash: B::Hash, number: NumberFor<B>)
Inform the network service about new best imported block.
sourcepub fn local_peer_id(&self) -> &PeerId
pub fn local_peer_id(&self) -> &PeerId
Returns the local PeerId.
sourcepub fn listen_addresses(&self) -> impl Iterator<Item = &Multiaddr>
pub fn listen_addresses(&self) -> impl Iterator<Item = &Multiaddr>
Returns the list of addresses we are listening on.
Does NOT include a trailing /p2p/ with our PeerId.
sourcepub fn network_state(&mut self) -> NetworkState
pub fn network_state(&mut self) -> NetworkState
Get network state.
Note: Use this only for debugging. This API is unstable. There are warnings literally everywhere about this. Please don’t use this function to retrieve actual information.
Examples found in repository?
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
let this = &mut *self;
// At the time of writing of this comment, due to a high volume of messages, the network
// worker sometimes takes a long time to process the loop below. When that happens, the
// rest of the polling is frozen. In order to avoid negative side-effects caused by this
// freeze, a limit to the number of iterations is enforced below. If the limit is reached,
// the task is interrupted then scheduled again.
//
// This allows for a more even distribution in the time taken by each sub-part of the
// polling.
let mut num_iterations = 0;
loop {
num_iterations += 1;
if num_iterations >= 100 {
cx.waker().wake_by_ref();
break
}
// Process the next message coming from the `NetworkService`.
let msg = match this.from_service.poll_next_unpin(cx) {
Poll::Ready(Some(msg)) => msg,
Poll::Ready(None) => return Poll::Ready(()),
Poll::Pending => break,
};
match msg {
ServiceToWorkerMsg::AnnounceBlock(hash, data) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.announce_block(hash, data),
ServiceToWorkerMsg::GetValue(key) =>
this.network_service.behaviour_mut().get_value(key),
ServiceToWorkerMsg::PutValue(key, value) =>
this.network_service.behaviour_mut().put_value(key, value),
ServiceToWorkerMsg::SetReservedOnly(reserved_only) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.set_reserved_only(reserved_only),
ServiceToWorkerMsg::SetReserved(peers) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.set_reserved_peers(peers),
ServiceToWorkerMsg::SetPeersetReserved(protocol, peers) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.set_reserved_peerset_peers(protocol, peers),
ServiceToWorkerMsg::AddReserved(peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.add_reserved_peer(peer_id),
ServiceToWorkerMsg::RemoveReserved(peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.remove_reserved_peer(peer_id),
ServiceToWorkerMsg::AddSetReserved(protocol, peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.add_set_reserved_peer(protocol, peer_id),
ServiceToWorkerMsg::RemoveSetReserved(protocol, peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.remove_set_reserved_peer(protocol, peer_id),
ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) =>
this.network_service.behaviour_mut().add_known_address(peer_id, addr),
ServiceToWorkerMsg::AddToPeersSet(protocol, peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.add_to_peers_set(protocol, peer_id),
ServiceToWorkerMsg::RemoveFromPeersSet(protocol, peer_id) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.remove_from_peers_set(protocol, peer_id),
ServiceToWorkerMsg::EventStream(sender) => this.event_streams.push(sender),
ServiceToWorkerMsg::Request {
target,
protocol,
request,
pending_response,
connect,
} => {
this.network_service.behaviour_mut().send_request(
&target,
&protocol,
request,
pending_response,
connect,
);
},
ServiceToWorkerMsg::NetworkStatus { pending_response } => {
let _ = pending_response.send(Ok(this.status()));
},
ServiceToWorkerMsg::NetworkState { pending_response } => {
let _ = pending_response.send(Ok(this.network_state()));
},
ServiceToWorkerMsg::DisconnectPeer(who, protocol_name) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.disconnect_peer(&who, protocol_name),
ServiceToWorkerMsg::NewBestBlockImported(hash, number) => this
.network_service
.behaviour_mut()
.user_protocol_mut()
.new_best_block_imported(hash, number),
}
}
// `num_iterations` serves the same purpose as in the previous loop.
// See the previous loop for explanations.
let mut num_iterations = 0;
loop {
num_iterations += 1;
if num_iterations >= 1000 {
cx.waker().wake_by_ref();
break
}
// Process the next action coming from the network.
let next_event = this.network_service.select_next_some();
futures::pin_mut!(next_event);
let poll_value = next_event.poll_unpin(cx);
match poll_value {
Poll::Pending => break,
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::InboundRequest {
protocol,
result,
..
})) => {
if let Some(metrics) = this.metrics.as_ref() {
match result {
Ok(serve_time) => {
metrics
.requests_in_success_total
.with_label_values(&[&protocol])
.observe(serve_time.as_secs_f64());
},
Err(err) => {
let reason = match err {
ResponseFailure::Network(InboundFailure::Timeout) => "timeout",
ResponseFailure::Network(
InboundFailure::UnsupportedProtocols,
) =>
// `UnsupportedProtocols` is reported for every single
// inbound request whenever a request with an unsupported
// protocol is received. This is not reported in order to
// avoid confusions.
continue,
ResponseFailure::Network(InboundFailure::ResponseOmission) =>
"busy-omitted",
ResponseFailure::Network(InboundFailure::ConnectionClosed) =>
"connection-closed",
};
metrics
.requests_in_failure_total
.with_label_values(&[&protocol, reason])
.inc();
},
}
}
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::RequestFinished {
protocol,
duration,
result,
..
})) =>
if let Some(metrics) = this.metrics.as_ref() {
match result {
Ok(_) => {
metrics
.requests_out_success_total
.with_label_values(&[&protocol])
.observe(duration.as_secs_f64());
},
Err(err) => {
let reason = match err {
RequestFailure::NotConnected => "not-connected",
RequestFailure::UnknownProtocol => "unknown-protocol",
RequestFailure::Refused => "refused",
RequestFailure::Obsolete => "obsolete",
RequestFailure::Network(OutboundFailure::DialFailure) =>
"dial-failure",
RequestFailure::Network(OutboundFailure::Timeout) => "timeout",
RequestFailure::Network(OutboundFailure::ConnectionClosed) =>
"connection-closed",
RequestFailure::Network(
OutboundFailure::UnsupportedProtocols,
) => "unsupported",
};
metrics
.requests_out_failure_total
.with_label_values(&[&protocol, reason])
.inc();
},
}
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::ReputationChanges {
peer,
changes,
})) =>
for change in changes {
this.network_service.behaviour().user_protocol().report_peer(peer, change);
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::PeerIdentify {
peer_id,
info:
IdentifyInfo {
protocol_version,
agent_version,
mut listen_addrs,
protocols,
..
},
})) => {
if listen_addrs.len() > 30 {
debug!(
target: "sub-libp2p",
"Node {:?} has reported more than 30 addresses; it is identified by {:?} and {:?}",
peer_id, protocol_version, agent_version
);
listen_addrs.truncate(30);
}
for addr in listen_addrs {
this.network_service
.behaviour_mut()
.add_self_reported_address_to_dht(&peer_id, &protocols, addr);
}
this.network_service
.behaviour_mut()
.user_protocol_mut()
.add_default_set_discovered_nodes(iter::once(peer_id));
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::Discovered(peer_id))) => {
this.network_service
.behaviour_mut()
.user_protocol_mut()
.add_default_set_discovered_nodes(iter::once(peer_id));
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::RandomKademliaStarted)) =>
if let Some(metrics) = this.metrics.as_ref() {
metrics.kademlia_random_queries_total.inc();
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamOpened {
remote,
protocol,
negotiated_fallback,
notifications_sink,
role,
})) => {
if let Some(metrics) = this.metrics.as_ref() {
metrics
.notifications_streams_opened_total
.with_label_values(&[&protocol])
.inc();
}
{
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
let _previous_value = peers_notifications_sinks
.insert((remote, protocol.clone()), notifications_sink);
debug_assert!(_previous_value.is_none());
}
this.event_streams.send(Event::NotificationStreamOpened {
remote,
protocol,
negotiated_fallback,
role,
});
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamReplaced {
remote,
protocol,
notifications_sink,
})) => {
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
if let Some(s) = peers_notifications_sinks.get_mut(&(remote, protocol)) {
*s = notifications_sink;
} else {
error!(
target: "sub-libp2p",
"NotificationStreamReplaced for non-existing substream"
);
debug_assert!(false);
}
// TODO: Notifications might have been lost as a result of the previous
// connection being dropped, and as a result it would be preferable to notify
// the users of this fact by simulating the substream being closed then
// reopened.
// The code below doesn't compile because `role` is unknown. Propagating the
// handshake of the secondary connections is quite an invasive change and
// would conflict with https://github.com/paritytech/substrate/issues/6403.
// Considering that dropping notifications is generally regarded as
// acceptable, this bug is at the moment intentionally left there and is
// intended to be fixed at the same time as
// https://github.com/paritytech/substrate/issues/6403.
// this.event_streams.send(Event::NotificationStreamClosed {
// remote,
// protocol,
// });
// this.event_streams.send(Event::NotificationStreamOpened {
// remote,
// protocol,
// role,
// });
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamClosed {
remote,
protocol,
})) => {
if let Some(metrics) = this.metrics.as_ref() {
metrics
.notifications_streams_closed_total
.with_label_values(&[&protocol[..]])
.inc();
}
this.event_streams.send(Event::NotificationStreamClosed {
remote,
protocol: protocol.clone(),
});
{
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
let _previous_value = peers_notifications_sinks.remove(&(remote, protocol));
debug_assert!(_previous_value.is_some());
}
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationsReceived {
remote,
messages,
})) => {
if let Some(metrics) = this.metrics.as_ref() {
for (protocol, message) in &messages {
metrics
.notifications_sizes
.with_label_values(&["in", protocol])
.observe(message.len() as f64);
}
}
this.event_streams.send(Event::NotificationsReceived { remote, messages });
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::SyncConnected(remote))) => {
this.event_streams.send(Event::SyncConnected { remote });
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::SyncDisconnected(remote))) => {
this.event_streams.send(Event::SyncDisconnected { remote });
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::Dht(event, duration))) => {
if let Some(metrics) = this.metrics.as_ref() {
let query_type = match event {
DhtEvent::ValueFound(_) => "value-found",
DhtEvent::ValueNotFound(_) => "value-not-found",
DhtEvent::ValuePut(_) => "value-put",
DhtEvent::ValuePutFailed(_) => "value-put-failed",
};
metrics
.kademlia_query_duration
.with_label_values(&[query_type])
.observe(duration.as_secs_f64());
}
this.event_streams.send(Event::Dht(event));
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::None)) => {
// Ignored event from lower layers.
},
Poll::Ready(SwarmEvent::ConnectionEstablished {
peer_id,
endpoint,
num_established,
concurrent_dial_errors,
}) => {
if let Some(errors) = concurrent_dial_errors {
debug!(target: "sub-libp2p", "Libp2p => Connected({:?}) with errors: {:?}", peer_id, errors);
} else {
debug!(target: "sub-libp2p", "Libp2p => Connected({:?})", peer_id);
}
if let Some(metrics) = this.metrics.as_ref() {
let direction = match endpoint {
ConnectedPoint::Dialer { .. } => "out",
ConnectedPoint::Listener { .. } => "in",
};
metrics.connections_opened_total.with_label_values(&[direction]).inc();
if num_established.get() == 1 {
metrics.distinct_peers_connections_opened_total.inc();
}
}
},
Poll::Ready(SwarmEvent::ConnectionClosed {
peer_id,
cause,
endpoint,
num_established,
}) => {
debug!(target: "sub-libp2p", "Libp2p => Disconnected({:?}, {:?})", peer_id, cause);
if let Some(metrics) = this.metrics.as_ref() {
let direction = match endpoint {
ConnectedPoint::Dialer { .. } => "out",
ConnectedPoint::Listener { .. } => "in",
};
let reason = match cause {
Some(ConnectionError::IO(_)) => "transport-error",
Some(ConnectionError::Handler(EitherError::A(EitherError::A(
EitherError::B(EitherError::A(PingFailure::Timeout)),
)))) => "ping-timeout",
Some(ConnectionError::Handler(EitherError::A(EitherError::A(
EitherError::A(NotifsHandlerError::SyncNotificationsClogged),
)))) => "sync-notifications-clogged",
Some(ConnectionError::Handler(_)) => "protocol-error",
Some(ConnectionError::KeepAliveTimeout) => "keep-alive-timeout",
None => "actively-closed",
};
metrics
.connections_closed_total
.with_label_values(&[direction, reason])
.inc();
// `num_established` represents the number of *remaining* connections.
if num_established == 0 {
metrics.distinct_peers_connections_closed_total.inc();
}
}
},
Poll::Ready(SwarmEvent::NewListenAddr { address, .. }) => {
trace!(target: "sub-libp2p", "Libp2p => NewListenAddr({})", address);
if let Some(metrics) = this.metrics.as_ref() {
metrics.listeners_local_addresses.inc();
}
},
Poll::Ready(SwarmEvent::ExpiredListenAddr { address, .. }) => {
info!(target: "sub-libp2p", "📪 No longer listening on {}", address);
if let Some(metrics) = this.metrics.as_ref() {
metrics.listeners_local_addresses.dec();
}
},
Poll::Ready(SwarmEvent::OutgoingConnectionError { peer_id, error }) => {
if let Some(peer_id) = peer_id {
trace!(
target: "sub-libp2p",
"Libp2p => Failed to reach {:?}: {}",
peer_id, error,
);
if this.boot_node_ids.contains(&peer_id) {
if let DialError::WrongPeerId { obtained, endpoint } = &error {
if let ConnectedPoint::Dialer { address, role_override: _ } =
endpoint
{
warn!(
"💔 The bootnode you want to connect to at `{}` provided a different peer ID `{}` than the one you expect `{}`.",
address,
obtained,
peer_id,
);
}
}
}
}
if let Some(metrics) = this.metrics.as_ref() {
let reason = match error {
DialError::ConnectionLimit(_) => Some("limit-reached"),
DialError::InvalidPeerId(_) => Some("invalid-peer-id"),
DialError::Transport(_) | DialError::ConnectionIo(_) =>
Some("transport-error"),
DialError::Banned |
DialError::LocalPeerId |
DialError::NoAddresses |
DialError::DialPeerConditionFalse(_) |
DialError::WrongPeerId { .. } |
DialError::Aborted => None, // ignore them
};
if let Some(reason) = reason {
metrics
.pending_connections_errors_total
.with_label_values(&[reason])
.inc();
}
}
},
Poll::Ready(SwarmEvent::Dialing(peer_id)) => {
trace!(target: "sub-libp2p", "Libp2p => Dialing({:?})", peer_id)
},
Poll::Ready(SwarmEvent::IncomingConnection { local_addr, send_back_addr }) => {
trace!(target: "sub-libp2p", "Libp2p => IncomingConnection({},{}))",
local_addr, send_back_addr);
if let Some(metrics) = this.metrics.as_ref() {
metrics.incoming_connections_total.inc();
}
},
Poll::Ready(SwarmEvent::IncomingConnectionError {
local_addr,
send_back_addr,
error,
}) => {
debug!(
target: "sub-libp2p",
"Libp2p => IncomingConnectionError({},{}): {}",
local_addr, send_back_addr, error,
);
if let Some(metrics) = this.metrics.as_ref() {
let reason = match error {
PendingConnectionError::ConnectionLimit(_) => Some("limit-reached"),
PendingConnectionError::WrongPeerId { .. } => Some("invalid-peer-id"),
PendingConnectionError::Transport(_) |
PendingConnectionError::IO(_) => Some("transport-error"),
PendingConnectionError::Aborted => None, // ignore it
};
if let Some(reason) = reason {
metrics
.incoming_connections_errors_total
.with_label_values(&[reason])
.inc();
}
}
},
Poll::Ready(SwarmEvent::BannedPeer { peer_id, endpoint }) => {
debug!(
target: "sub-libp2p",
"Libp2p => BannedPeer({}). Connected via {:?}.",
peer_id, endpoint,
);
if let Some(metrics) = this.metrics.as_ref() {
metrics
.incoming_connections_errors_total
.with_label_values(&["banned"])
.inc();
}
},
Poll::Ready(SwarmEvent::ListenerClosed { reason, addresses, .. }) => {
if let Some(metrics) = this.metrics.as_ref() {
metrics.listeners_local_addresses.sub(addresses.len() as u64);
}
let addrs =
addresses.into_iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ");
match reason {
Ok(()) => error!(
target: "sub-libp2p",
"📪 Libp2p listener ({}) closed gracefully",
addrs
),
Err(e) => error!(
target: "sub-libp2p",
"📪 Libp2p listener ({}) closed: {}",
addrs, e
),
}
},
Poll::Ready(SwarmEvent::ListenerError { error, .. }) => {
debug!(target: "sub-libp2p", "Libp2p => ListenerError: {}", error);
if let Some(metrics) = this.metrics.as_ref() {
metrics.listeners_errors_total.inc();
}
},
};
}
let num_connected_peers =
this.network_service.behaviour_mut().user_protocol_mut().num_connected_peers();
// Update the variables shared with the `NetworkService`.
this.num_connected.store(num_connected_peers, Ordering::Relaxed);
{
let external_addresses =
Swarm::<Behaviour<B, Client>>::external_addresses(&this.network_service)
.map(|r| &r.addr)
.cloned()
.collect();
*this.external_addresses.lock() = external_addresses;
}
let is_major_syncing = this
.network_service
.behaviour_mut()
.user_protocol_mut()
.sync_state()
.state
.is_major_syncing();
this.is_major_syncing.store(is_major_syncing, Ordering::Relaxed);
if let Some(metrics) = this.metrics.as_ref() {
if let Some(buckets) = this.network_service.behaviour_mut().num_entries_per_kbucket() {
for (lower_ilog2_bucket_bound, num_entries) in buckets {
metrics
.kbuckets_num_nodes
.with_label_values(&[&lower_ilog2_bucket_bound.to_string()])
.set(num_entries as u64);
}
}
if let Some(num_entries) = this.network_service.behaviour_mut().num_kademlia_records() {
metrics.kademlia_records_count.set(num_entries as u64);
}
if let Some(num_entries) =
this.network_service.behaviour_mut().kademlia_records_total_size()
{
metrics.kademlia_records_sizes_total.set(num_entries as u64);
}
metrics
.peerset_num_discovered
.set(this.network_service.behaviour_mut().user_protocol().num_discovered_peers()
as u64);
metrics.pending_connections.set(
Swarm::network_info(&this.network_service).connection_counters().num_pending()
as u64,
);
}
Poll::Pending
}sourcepub fn peers_debug_info(&mut self) -> Vec<(PeerId, PeerInfo<B>)> ⓘ
pub fn peers_debug_info(&mut self) -> Vec<(PeerId, PeerInfo<B>)> ⓘ
Get currently connected peers.
sourcepub fn remove_reserved_peer(&self, peer: PeerId)
pub fn remove_reserved_peer(&self, peer: PeerId)
Removes a PeerId from the list of reserved peers.
sourcepub fn add_reserved_peer(&self, peer: MultiaddrWithPeerId) -> Result<(), String>
pub fn add_reserved_peer(&self, peer: MultiaddrWithPeerId) -> Result<(), String>
Adds a PeerId and its Multiaddr as reserved.
sourcepub fn reserved_peers(&self) -> impl Iterator<Item = &PeerId>
pub fn reserved_peers(&self) -> impl Iterator<Item = &PeerId>
Returns the list of reserved peers.
Trait Implementations§
source§impl<B, H, Client> Future for NetworkWorker<B, H, Client>where
B: BlockT + 'static,
H: ExHashT,
Client: HeaderBackend<B> + 'static,
impl<B, H, Client> Future for NetworkWorker<B, H, Client>where
B: BlockT + 'static,
H: ExHashT,
Client: HeaderBackend<B> + 'static,
impl<B, H, Client> Unpin for NetworkWorker<B, H, Client>where
B: BlockT + 'static,
H: ExHashT,
Client: HeaderBackend<B> + 'static,
Auto Trait Implementations§
impl<B, H, Client> !RefUnwindSafe for NetworkWorker<B, H, Client>
impl<B, H, Client> Send for NetworkWorker<B, H, Client>
impl<B, H, Client> !Sync for NetworkWorker<B, H, Client>
impl<B, H, Client> !UnwindSafe for NetworkWorker<B, H, Client>
Blanket Implementations§
source§impl<T> CheckedConversion for T
impl<T> CheckedConversion for T
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T, Global>) -> Box<dyn Any + 'static, Global>
fn into_any(self: Box<T, Global>) -> Box<dyn Any + 'static, Global>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.§impl<T> FutureExt for Twhere
T: Future + ?Sized,
impl<T> FutureExt for Twhere
T: Future + ?Sized,
§fn map<U, F>(self, f: F) -> Map<Self, F>where
F: FnOnce(Self::Output) -> U,
Self: Sized,
fn map<U, F>(self, f: F) -> Map<Self, F>where
F: FnOnce(Self::Output) -> U,
Self: Sized,
§fn map_into<U>(self) -> MapInto<Self, U>where
Self::Output: Into<U>,
Self: Sized,
fn map_into<U>(self) -> MapInto<Self, U>where
Self::Output: Into<U>,
Self: Sized,
§fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>where
F: FnOnce(Self::Output) -> Fut,
Fut: Future,
Self: Sized,
fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>where
F: FnOnce(Self::Output) -> Fut,
Fut: Future,
Self: Sized,
f. Read more§fn left_future<B>(self) -> Either<Self, B>where
B: Future<Output = Self::Output>,
Self: Sized,
fn left_future<B>(self) -> Either<Self, B>where
B: Future<Output = Self::Output>,
Self: Sized,
§fn right_future<A>(self) -> Either<A, Self>where
A: Future<Output = Self::Output>,
Self: Sized,
fn right_future<A>(self) -> Either<A, Self>where
A: Future<Output = Self::Output>,
Self: Sized,
§fn into_stream(self) -> IntoStream<Self>where
Self: Sized,
fn into_stream(self) -> IntoStream<Self>where
Self: Sized,
§fn flatten(self) -> Flatten<Self>where
Self::Output: Future,
Self: Sized,
fn flatten(self) -> Flatten<Self>where
Self::Output: Future,
Self: Sized,
§fn flatten_stream(self) -> FlattenStream<Self>where
Self::Output: Stream,
Self: Sized,
fn flatten_stream(self) -> FlattenStream<Self>where
Self::Output: Stream,
Self: Sized,
§fn fuse(self) -> Fuse<Self>where
Self: Sized,
fn fuse(self) -> Fuse<Self>where
Self: Sized,
poll will never again be called once it has
completed. This method can be used to turn any Future into a
FusedFuture. Read more§fn inspect<F>(self, f: F) -> Inspect<Self, F>where
F: FnOnce(&Self::Output),
Self: Sized,
fn inspect<F>(self, f: F) -> Inspect<Self, F>where
F: FnOnce(&Self::Output),
Self: Sized,
§fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
§fn remote_handle(self) -> (Remote<Self>, RemoteHandle<Self::Output>)where
Self: Sized,
fn remote_handle(self) -> (Remote<Self>, RemoteHandle<Self::Output>)where
Self: Sized,
() on completion and sends
its output to another future on a separate task. Read more§fn boxed<'a>(
self
) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a, Global>>where
Self: 'a + Sized + Send,
fn boxed<'a>(
self
) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a, Global>>where
Self: 'a + Sized + Send,
§fn boxed_local<'a>(
self
) -> Pin<Box<dyn Future<Output = Self::Output> + 'a, Global>>where
Self: 'a + Sized,
fn boxed_local<'a>(
self
) -> Pin<Box<dyn Future<Output = Self::Output> + 'a, Global>>where
Self: 'a + Sized,
§fn unit_error(self) -> UnitError<Self>where
Self: Sized,
fn unit_error(self) -> UnitError<Self>where
Self: Sized,
Future<Output = T> into a
TryFuture<Ok = T, Error = ()>.§fn never_error(self) -> NeverError<Self>where
Self: Sized,
fn never_error(self) -> NeverError<Self>where
Self: Sized,
Future<Output = T> into a
TryFuture<Ok = T, Error = Never>.§impl<F> FutureExt for Fwhere
F: Future + ?Sized,
impl<F> FutureExt for Fwhere
F: Future + ?Sized,
§fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<F> IntoFuture for Fwhere
F: Future,
impl<F> IntoFuture for Fwhere
F: Future,
§type IntoFuture = F
type IntoFuture = F
source§fn into_future(self) -> <F as IntoFuture>::IntoFuture
fn into_future(self) -> <F as IntoFuture>::IntoFuture
source§impl<T, Outer> IsWrappedBy<Outer> for Twhere
Outer: AsRef<T> + AsMut<T> + From<T>,
T: From<Outer>,
impl<T, Outer> IsWrappedBy<Outer> for Twhere
Outer: AsRef<T> + AsMut<T> + From<T>,
T: From<Outer>,
§impl<T> Pointable for T
impl<T> Pointable for T
source§impl<T> SaturatedConversion for T
impl<T> SaturatedConversion for T
source§fn saturated_from<T>(t: T) -> Selfwhere
Self: UniqueSaturatedFrom<T>,
fn saturated_from<T>(t: T) -> Selfwhere
Self: UniqueSaturatedFrom<T>,
source§fn saturated_into<T>(self) -> Twhere
Self: UniqueSaturatedInto<T>,
fn saturated_into<T>(self) -> Twhere
Self: UniqueSaturatedInto<T>,
T. Read moresource§impl<S, T> UncheckedInto<T> for Swhere
T: UncheckedFrom<S>,
impl<S, T> UncheckedInto<T> for Swhere
T: UncheckedFrom<S>,
source§fn unchecked_into(self) -> T
fn unchecked_into(self) -> T
unchecked_from.source§impl<T, S> UniqueSaturatedInto<T> for Swhere
T: Bounded,
S: TryInto<T>,
impl<T, S> UniqueSaturatedInto<T> for Swhere
T: Bounded,
S: TryInto<T>,
source§fn unique_saturated_into(self) -> T
fn unique_saturated_into(self) -> T
T.