Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
90cd7d6
feat: memory based connection limits
hanabi1224 Aug 1, 2023
5014500
sets system ram
hanabi1224 Aug 1, 2023
e5519d7
code golf
hanabi1224 Aug 1, 2023
024da42
fix(examples/file-sharing): set Kademlia `Mode::Server`
mxinden Aug 1, 2023
065efb1
docs: fix last OutboundQueryCompleted in kad doc
thomas-senechal Aug 2, 2023
2a8e371
fix(relay): remove unconditional `async-std` dependency
quininer Aug 2, 2023
94dc11b
deps(yamux): update yamux to `v0.12`
thomaseizinger Aug 2, 2023
51a91b7
deps: bump Swatinem/rust-cache from 2.5.1 to 2.6.0
dependabot[bot] Aug 3, 2023
6581822
move to new crate
hanabi1224 Aug 3, 2023
1106ad7
Merge remote-tracking branch 'origin/master' into memory-based-connec…
hanabi1224 Aug 3, 2023
6066b2e
doc
hanabi1224 Aug 3, 2023
1fa32f0
lock
hanabi1224 Aug 3, 2023
05cbf5e
doc and tests
hanabi1224 Aug 3, 2023
e308be7
Merge branch 'master' into memory-based-connection-limits
hanabi1224 Aug 3, 2023
7d05ee5
Apply suggestions from code review
hanabi1224 Aug 3, 2023
9ba799e
hide MemoryUsageBasedConnectionLimits
hanabi1224 Aug 3, 2023
b8a9916
update MemoryUsageLimitExceeded fmt as suggested
hanabi1224 Aug 3, 2023
f43fed5
fix clippy
hanabi1224 Aug 3, 2023
9a66866
fix rustdoc
hanabi1224 Aug 3, 2023
7990be6
Update misc/memory-connection-limits/src/lib.rs
hanabi1224 Aug 4, 2023
07e30bb
resolve comments
hanabi1224 Aug 4, 2023
6adf21f
Make MemoryUsageLimitExceeded fields private
hanabi1224 Aug 4, 2023
a720f64
Merge branch 'master' into memory-based-connection-limits
hanabi1224 Aug 7, 2023
803d8f5
Pre-calculate max_allowed_bytes
hanabi1224 Aug 7, 2023
f60cfb0
refresh interval
hanabi1224 Aug 7, 2023
259f038
Don't use `update` functions in tests
thomaseizinger Aug 7, 2023
c5e103c
Remove inner `Option`
thomaseizinger Aug 7, 2023
5c63b87
Don't make refresh interval configurable
thomaseizinger Aug 7, 2023
dee261c
Update docs
thomaseizinger Aug 7, 2023
1b7fb24
Remove refresh-interval field
thomaseizinger Aug 7, 2023
280d13a
Use early return to reduce indentation
thomaseizinger Aug 7, 2023
aadad16
Only set timestamp if we actually refreshed the data
thomaseizinger Aug 7, 2023
2875817
Use early return instead of else
thomaseizinger Aug 7, 2023
800d501
Make tests for stable
hanabi1224 Aug 7, 2023
7331b8f
Add docs to constant
thomaseizinger Aug 7, 2023
a1d0b55
Sort functions are per trait definition
thomaseizinger Aug 7, 2023
9da8e1e
Merge branch 'memory-connection-limits-thomas' into memory-based-conn…
thomaseizinger Aug 7, 2023
b24fb86
Re-export from libp2p meta crate
hanabi1224 Aug 7, 2023
14f0866
Merge branch 'master' into memory-based-connection-limits
hanabi1224 Aug 7, 2023
9eeee38
Update libp2p/CHANGELOG.md
thomaseizinger Aug 7, 2023
13f09a8
Merge branch 'master' into memory-based-connection-limits
hanabi1224 Aug 8, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 59 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions misc/connection-limits/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
## 0.2.2
- Rename `ConnectionLimits` to `StaticConnectionLimits`

See [PR XX]

- Refactor `Behaviour` to take a generic `ConnectionLimitsChecker`

See [PR XX]

- Add `MemoryBasedConnectionLimits`

See [PR XX]

[PR XX]: https://github.com/libp2p/rust-libp2p/pull/XX

## 0.2.1

- Do not count a connection as established when it is denied by another sibling `NetworkBehaviour`.
Expand Down
6 changes: 5 additions & 1 deletion misc/connection-limits/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,20 @@ name = "libp2p-connection-limits"
edition = "2021"
rust-version = { workspace = true }
description = "Connection limits for libp2p."
version = "0.2.1"
version = "0.2.2"
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
keywords = ["peer-to-peer", "libp2p", "networking"]
categories = ["network-programming", "asynchronous"]

[dependencies]
memory-stats = "1"
libp2p-core = { workspace = true }
libp2p-swarm = { workspace = true }
libp2p-identity = { workspace = true, features = ["peerid"] }
log = "0.4"
parking_lot = "0.12"
sysinfo = "0.29"
void = "1"

[dev-dependencies]
Expand Down
181 changes: 181 additions & 0 deletions misc/connection-limits/src/connection_limits/memory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// Copyright 2023 Protocol Labs.
//
// 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.

use super::*;
use parking_lot::RwLock;
use std::{
sync::Arc,
time::{Duration, Instant},
};

/// The configurable memory usage based connection limits.
#[derive(Debug)]
pub struct MemoryUsageBasedConnectionLimits {
max_process_memory_usage_bytes: Option<usize>,
max_process_memory_usage_percentage: Option<f64>,
system_physical_memory_bytes: usize,
mem_tracker: ProcessMemoryUsageTracker,
}

impl MemoryUsageBasedConnectionLimits {
pub fn new() -> Self {
use sysinfo::{RefreshKind, SystemExt};

let system_info = sysinfo::System::new_with_specifics(RefreshKind::new().with_memory());

MemoryUsageBasedConnectionLimits {
max_process_memory_usage_bytes: None,
max_process_memory_usage_percentage: None,
system_physical_memory_bytes: system_info.total_memory() as usize,
mem_tracker: ProcessMemoryUsageTracker::new(),
}
}

/// Sets the process memory usage threshold in bytes,
/// all pending connections will be dropped when the threshold is exeeded
pub fn with_max_bytes(mut self, bytes: usize) -> Self {
self.max_process_memory_usage_bytes = Some(bytes);
self
}

/// Sets the process memory usage threshold in the percentage of the total physical memory,
/// all pending connections will be dropped when the threshold is exeeded
pub fn with_max_percentage(mut self, percentage: f64) -> Self {
self.max_process_memory_usage_percentage = Some(percentage);
self
}

fn max_allowed_bytes(&self) -> Option<usize> {
self.max_process_memory_usage_bytes.min(
self.max_process_memory_usage_percentage
.map(|p| (self.system_physical_memory_bytes as f64 * p).round() as usize),
)
}
}

impl Default for MemoryUsageBasedConnectionLimits {
fn default() -> Self {
Self::new()
}
}

impl ConnectionLimitsChecker for MemoryUsageBasedConnectionLimits {
fn check_limit(&self, kind: ConnectionKind, _current: usize) -> Result<(), ConnectionDenied> {
use ConnectionKind::*;

match kind {
PendingIncoming | PendingOutgoing => {
if let Some(max_allowed_bytes) = self.max_allowed_bytes() {
self.mem_tracker.refresh_if_needed();
let process_memory_bytes = self.mem_tracker.total_bytes();
if process_memory_bytes > max_allowed_bytes {
return Err(ConnectionDenied::new(MemoryUsageLimitExceeded {
process_memory_bytes,
max_allowed_bytes,
}));
}
}
}
EstablishedIncoming | EstablishedOutgoing | EstablishedPerPeer | EstablishedTotal => {}
};

Ok(())
}
}

/// A connection limit has been exceeded.
#[derive(Debug, Clone, Copy)]
pub struct MemoryUsageLimitExceeded {
pub process_memory_bytes: usize,
pub max_allowed_bytes: usize,
}

impl std::error::Error for MemoryUsageLimitExceeded {}

impl fmt::Display for MemoryUsageLimitExceeded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"pending connections are dropped, process memory usage limit exceeded: process memory: {} bytes, max allowed: {} bytes",
self.process_memory_bytes,
self.max_allowed_bytes,
)
}
}

#[derive(Debug)]
struct ProcessMemoryUsageTracker(Arc<RwLock<ProcessMemoryUsageTrackerInner>>);

impl ProcessMemoryUsageTracker {
fn new() -> Self {
Self(Arc::new(RwLock::new(ProcessMemoryUsageTrackerInner::new())))
}

fn refresh_if_needed(&self) {
let need_refresh = self.0.read().need_refresh();
if need_refresh {
self.0.write().refresh();
}
}

fn total_bytes(&self) -> usize {
let guard = self.0.read();
guard.physical_bytes + guard.virtual_bytes
}
}

#[derive(Debug)]
struct ProcessMemoryUsageTrackerInner {
last_checked: Instant,
physical_bytes: usize,
virtual_bytes: usize,
}

impl ProcessMemoryUsageTrackerInner {
fn new() -> Self {
let stats = memory_stats::memory_stats();
if stats.is_none() {
log::warn!("Failed to retrive process memory stats");
}
Self {
last_checked: Instant::now(),
physical_bytes: stats.map(|s| s.physical_mem).unwrap_or_default(),
virtual_bytes: stats
.map(|s: memory_stats::MemoryStats| s.virtual_mem)
.unwrap_or_default(),
}
}

fn need_refresh(&self) -> bool {
const PROCESS_MEMORY_USAGE_CHECK_INTERVAL: Duration = Duration::from_millis(1000);

self.last_checked + PROCESS_MEMORY_USAGE_CHECK_INTERVAL < Instant::now()
}

fn refresh(&mut self) {
if let Some(stats) = memory_stats::memory_stats() {
self.physical_bytes = stats.physical_mem;
self.virtual_bytes = stats.virtual_mem;
} else {
log::warn!("Failed to retrive process memory stats");
}
self.last_checked = Instant::now();
}
}
Loading