Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes for using rand crate with version 0.9 #9594

Merged
merged 2 commits into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
229 changes: 140 additions & 89 deletions Cargo.lock

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions components/butterfly/src/member.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ use log::{debug,
trace};
use prometheus::{register_int_gauge_vec,
IntGaugeVec};
use rand::{seq::{IteratorRandom,
SliceRandom},
thread_rng};
use rand::{rng,
seq::{IteratorRandom,
SliceRandom}};
use serde::{de,
ser::{SerializeMap,
SerializeStruct},
Expand Down Expand Up @@ -705,7 +705,7 @@ impl MemberList {
.filter(|member| member.id != exclude_id)
.cloned()
.collect();
members.shuffle(&mut thread_rng());
members.shuffle(&mut rng());

members
}
Expand All @@ -728,7 +728,7 @@ impl MemberList {
&& member.id != target_member_id
&& *health == Health::Alive
})
.choose_multiple(&mut thread_rng(), PINGREQ_TARGETS)
.choose_multiple(&mut rng(), PINGREQ_TARGETS)
{
with_closure(member);
}
Expand Down
4 changes: 2 additions & 2 deletions components/butterfly/tests/rumor/election.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::iter::FromIterator;

use rand::prelude::SliceRandom;
use rand::prelude::IndexedRandom;

use crate::btest;
use habitat_butterfly::{member::Health,
Expand Down Expand Up @@ -250,7 +250,7 @@ fn five_persistent_members_same_leader_multiple_non_quorum_partitions() {

// Making sure - running multiple times after a subset of follower (non-quorum) is partitioned
// and reconnected the leader stays the same.
let mut rng = rand::thread_rng();
let mut rng = rand::rng();
let idxes = Vec::from_iter(1_usize..5_usize).choose_multiple(&mut rng, 2)
.copied()
.collect::<Vec<usize>>();
Expand Down
9 changes: 5 additions & 4 deletions components/core/src/flowcontrol/backoff.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::time::Duration;

use rand::{thread_rng,
use rand::{rng,
Rng};
use tokio::time::Instant;

Expand Down Expand Up @@ -48,12 +48,13 @@ impl Backoff {
pub fn record_attempt_start(&mut self) -> Option<Duration> {
match &self.last_attempt {
Some(RetryAttempt { sleep_duration, .. }) => {
let mut rng = thread_rng();
let mut rng = rng();
// We use the decorrelated jitter algorithm mentioned here:
// https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
let new_sleep_duration =
self.max_backoff.min(rng.gen_range(self.base_backoff
..=sleep_duration.mul_f64(self.multiplier)));
self.max_backoff
.min(rng.random_range(self.base_backoff
..=sleep_duration.mul_f64(self.multiplier)));
self.last_attempt = Some(RetryAttempt { attempt_started_at: Instant::now(),
attempt_ended_at: None,
sleep_duration: new_sleep_duration, });
Expand Down
2 changes: 1 addition & 1 deletion components/core/src/os/process/windows_child.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ pub fn anon_pipe(ours_readable: bool) -> io::Result<Pipes> {
let mut reject_remote_clients_flag = PIPE_REJECT_REMOTE_CLIENTS;
loop {
tries += 1;
let key: u64 = rand::thread_rng().gen();
let key: u64 = rand::rng().random();
name = format!(r"\\.\pipe\__rust_anonymous_pipe1__.{}.{}",
processthreadsapi::GetCurrentProcessId(),
key);
Expand Down
2 changes: 1 addition & 1 deletion components/sup-protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ habitat_core = { path = "../core" }
lazy_static = "*"
log = "0.4"
prost = { version = "*", features = ["prost-derive"] }
rand = "*"
rand = { version = "0.9", features = ["thread_rng"] }
serde = {version = "*", features = ["derive"] }
tokio = { version = "*", features = ["full"] }
tokio-util = { version = "0.7", features = ["full"] }
Expand Down
9 changes: 6 additions & 3 deletions components/sup-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,16 @@ pub mod types;
use crate::{core::env as henv,
net::{ErrCode,
NetResult}};
use rand::RngCore;

use std::{fs::File,
io::Read,
net::SocketAddr,
path::{Path,
PathBuf}};

use rand::{rngs::OsRng,
TryRngCore};

// Name of file containing the CtlGateway secret key.
const CTL_SECRET_FILENAME: &str = "CTL_SECRET";
/// Length of characters in CtlGateway secret key.
Expand All @@ -63,9 +66,9 @@ lazy_static! {

/// Generate a new secret key used for authenticating clients to the `CtlGateway`.
pub fn generate_secret_key(out: &mut String) {
let mut rng = rand::rngs::OsRng;
let mut rng = OsRng;
let mut result = vec![0u8; CTL_SECRET_LEN];
rng.fill_bytes(&mut result);
let _ = rng.try_fill_bytes(&mut result);
*out = core::base64::encode(&result);
}

Expand Down
2 changes: 1 addition & 1 deletion components/sup/src/manager/self_updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ impl SelfUpdater {
update_channel,
period, } = runner;
let period = SelfUpdatePeriod::get().unwrap_or(period);
let splay = Duration::from_secs(rand::thread_rng().gen_range(0..period.as_secs()));
let splay = Duration::from_secs(rand::rng().random_range(0..period.as_secs()));
debug!("Starting self updater with current package {} in {}s",
current,
splay.as_secs());
Expand Down
2 changes: 1 addition & 1 deletion components/sup/src/manager/service/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ pub fn check_repeatedly(supervisor: Arc<Mutex<Supervisor>>,
if !first_ok_health_check_recorded {
// If this was the first successful check, splay future health check runs across
// the nominal interval
let splay = rand::thread_rng().gen_range(0..u64::from(nominal_interval));
let splay = rand::rng().random_range(0..u64::from(nominal_interval));
let splay = Duration::from_secs(splay);
debug!("Following `{}`'s first `ok` health-check, delaying a randomly chosen \
{}s to introduce health-check splay",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ impl PackageUpdateWorker {
pub async fn update(&self) -> IncarnatedPackageIdent {
let ident = self.ident.clone();
let period = PackageUpdateWorkerPeriod::get().unwrap_or(self.period);
let splay = Duration::from_secs(rand::thread_rng().gen_range(0..period.as_secs()));
let splay = Duration::from_secs(rand::rng().random_range(0..period.as_secs()));
debug!("Starting package update worker for {} in {}s",
ident,
splay.as_secs());
Expand Down
8 changes: 4 additions & 4 deletions components/sup/tests/utils/test_sup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use anyhow::{anyhow,
Result};
use habitat_core::os::process::Pid;
use rand::{self,
distributions::{Distribution,
Uniform}};
distr::{Distribution,
Uniform}};
use reqwest::Method;
use serde_json::Value;
use std::{collections::HashSet,
Expand Down Expand Up @@ -109,8 +109,8 @@ async fn unclaimed_port(max_attempts: u16) -> Result<u16> {
/// Return a random unprivileged, unregistered TCP port number.
fn random_port() -> u16 {
// IANA port registrations go to 49151
let between = Uniform::new_inclusive(49152, u16::MAX);
let mut rng = rand::thread_rng();
let between = Uniform::new_inclusive(49152, u16::MAX).expect("Invalid Parameters");
let mut rng = rand::rng();
between.sample(&mut rng)
}

Expand Down