mirror of
https://github.com/rustfs/rustfs.git
synced 2026-07-28 17:18:58 +00:00
adc07e5209
* init audit logger module * add audit webhook default config kvs * feat: Add comprehensive tests for authentication module (#309) * feat: add comprehensive tests for authentication module - Add 33 unit tests covering all public functions in auth.rs - Test IAMAuth struct creation and secret key validation - Test check_claims_from_token with various credential types and scenarios - Test session token extraction from headers and query parameters - Test condition values generation for different user types - Test query parameter parsing with edge cases - Test Credentials helper methods (is_expired, is_temp, is_service_account) - Ensure tests handle global state dependencies gracefully - All tests pass successfully with 100% coverage of testable functions * style: fix code formatting issues * Add verification script for checking PR branch statuses and tests Co-authored-by: anzhengchao <anzhengchao@gmail.com> * fix: resolve clippy uninlined format args warning --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> * feat: add basic tests for core storage module (#313) * feat: add basic tests for core storage module - Add 6 unit tests for FS struct and basic functionality - Test FS creation, Debug and Clone trait implementations - Test RUSTFS_OWNER constant definition and values - Test S3 error code creation and handling - Test compression format detection for common file types - Include comprehensive documentation about integration test needs Note: Full S3 API testing requires complex setup with storage backend, global configuration, and network infrastructure - better suited for integration tests rather than unit tests. * style: fix code formatting issues * fix: resolve clippy warnings in storage tests --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> * feat: add tests for admin handlers module (#314) * feat: add tests for admin handlers module - Add 5 new unit tests for admin handler functionality - Test AccountInfo struct creation, serialization and default values - Test creation of all admin handler structs (13 handlers) - Test HealOpts JSON serialization and deserialization - Test HealOpts URL encoding/decoding with proper field types - Maintain existing test while adding comprehensive coverage - Include documentation about integration test requirements All tests pass successfully with proper error handling for complex dependencies. * style: fix code formatting issues * fix: resolve clippy warnings in admin handlers tests --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> * build(deps): bump the dependencies group with 3 updates (#326) * perf: avoid transmitting parity shards when the object is good (#322) * upgrade version * Fix: fix data integrity check Signed-off-by: junxiang Mu <1948535941@qq.com> * Fix: Separate Clippy's fix and check commands into two commands. Signed-off-by: junxiang Mu <1948535941@qq.com> * fix: miss inline metadata (#345) * Update dependabot.yml * fix: Fixed an issue where the list_objects_v2 API did not return dire… (#352) * fix: Fixed an issue where the list_objects_v2 API did not return directory names when they conflicted with file names in the same bucket (e.g., test/ vs. test.txt, aaa/ vs. aaa.csv) (#335) * fix: adjusted the order of directory listings * init * fix * fix * feat: add docker usage for rustfs mcp (#365) * feat: enhance metadata extraction with object name for MIME type detection Signed-off-by: junxiang Mu <1948535941@qq.com> * Feature: lock support auto release Signed-off-by: junxiang Mu <1948535941@qq.com> * improve lock Signed-off-by: junxiang Mu <1948535941@qq.com> * Fix: fix scanner detect Signed-off-by: junxiang Mu <1948535941@qq.com> * Fix: clippy && fmt Signed-off-by: junxiang Mu <1948535941@qq.com> * refactor(ecstore): Optimize memory usage for object integrity verification Change the object integrity verification from reading all data to streaming processing to avoid memory overflow caused by large objects. Modify the TLS key log check to use environment variables directly instead of configuration constants. Add memory limits for object data reading in the AHM module. Signed-off-by: junxiang Mu <1948535941@qq.com> * Chore: reduce PR template checklist Signed-off-by: junxiang Mu <1948535941@qq.com> * Chore: remove comment code (#376) Signed-off-by: junxiang Mu <1948535941@qq.com> * chore: upgrade actions/checkout from v4 to v5 (#381) * chore: upgrade actions/checkout from v4 to v5 - Update GitHub Actions checkout action version - Ensure compatibility with latest workflow features - Maintain existing checkout behavior and configuration * upgrade version * fix * add and improve code for notify * feat: extend rustfs mcp with bucket creation and deletion (#416) * feat: extend rustfs mcp with bucket creation and deletion * update file to fix pipeline error * change variable name to fix pipeline error * fix(ecstore): add async-recursion to resolve nightly trait solver reg… (#415) * fix(ecstore): add async-recursion to resolve nightly trait solver regression The newest nightly compiler switched to the new trait solver, which currently rejects async recursive functions that were previously accepted. This causes the following compilation failures: - `LocalDisk::delete_file()` - `LocalDisk::scan_dir()` Add `async-recursion` as a workspace dependency and annotate both functions with `#[async_recursion]` so that the crate compiles cleanly with the latest nightly and will continue to build once the new solver lands in stable. Signed-off-by: reigadegr <2722688642@qq.com> * fix: resolve duplicate bound error in scan_dir function Replaced inline trait bounds with where clause to avoid duplication caused by macro expansion. Signed-off-by: reigadegr <2722688642@qq.com> --------- Signed-off-by: reigadegr <2722688642@qq.com> Co-authored-by: 安正超 <anzhengchao@gmail.com> * fix:make bucket exists (#428) * feat: include user-defined metadata in S3 response (#431) * fix: simplify Docker entrypoint following efficient user switching pattern (#421) * fix: simplify Docker entrypoint following efficient user switching pattern - Remove ALL file permission modifications (no chown at all) - Use chroot --userspec or gosu to switch user context - Extremely simple and fast implementation - Zero filesystem modifications for permissions Fixes #388 * Update entrypoint.sh Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update entrypoint.sh Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update entrypoint.sh Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * wip * wip * wip --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * docs: update doc/docker-data-dir README.md (#432) * add targets crates * feat(targets): extract targets module into a standalone crate - Move all target-related code (MQTT, Webhook, etc.) into a new `targets` crate - Update imports and dependencies to reference the new crate - Refactor interfaces to ensure compatibility with the new crate structure - Adjust Cargo.toml and workspace configuration accordingly * fix * fix --------- Signed-off-by: junxiang Mu <1948535941@qq.com> Signed-off-by: reigadegr <2722688642@qq.com> Co-authored-by: 安正超 <anzhengchao@gmail.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: zzhpro <56196563+zzhpro@users.noreply.github.com> Co-authored-by: junxiang Mu <1948535941@qq.com> Co-authored-by: weisd <im@weisd.in> Co-authored-by: shiro.lee <69624924+shiroleeee@users.noreply.github.com> Co-authored-by: majinghe <42570491+majinghe@users.noreply.github.com> Co-authored-by: guojidan <63799833+guojidan@users.noreply.github.com> Co-authored-by: reigadegr <103645642+reigadegr@users.noreply.github.com> Co-authored-by: 0xdx2 <xuedamon2@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
309 lines
12 KiB
Rust
309 lines
12 KiB
Rust
// Copyright 2024 RustFS Team
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
use crate::{Event, integration::NotificationMetrics};
|
|
use rustfs_targets::StoreError;
|
|
use rustfs_targets::Target;
|
|
use rustfs_targets::TargetError;
|
|
use rustfs_targets::store::{Key, Store};
|
|
use rustfs_targets::target::EntityTarget;
|
|
use std::sync::Arc;
|
|
use std::time::{Duration, Instant};
|
|
use tokio::sync::{Semaphore, mpsc};
|
|
use tokio::time::sleep;
|
|
use tracing::{debug, error, info, warn};
|
|
|
|
/// Streams events from the store to the target
|
|
pub async fn stream_events(
|
|
store: &mut (dyn Store<Event, Error = StoreError, Key = Key> + Send),
|
|
target: &dyn Target<Event>,
|
|
mut cancel_rx: mpsc::Receiver<()>,
|
|
) {
|
|
info!("Starting event stream for target: {}", target.name());
|
|
|
|
// Retry configuration
|
|
const MAX_RETRIES: usize = 5;
|
|
const RETRY_DELAY: Duration = Duration::from_secs(5);
|
|
|
|
loop {
|
|
// Check for cancellation signal
|
|
if cancel_rx.try_recv().is_ok() {
|
|
info!("Cancellation received for target: {}", target.name());
|
|
return;
|
|
}
|
|
|
|
// Get list of events in the store
|
|
let keys = store.list();
|
|
if keys.is_empty() {
|
|
// No events, wait before checking again
|
|
sleep(Duration::from_secs(1)).await;
|
|
continue;
|
|
}
|
|
|
|
// Process each event
|
|
for key in keys {
|
|
// Check for cancellation before processing each event
|
|
if cancel_rx.try_recv().is_ok() {
|
|
info!("Cancellation received during processing for target: {}", target.name());
|
|
return;
|
|
}
|
|
|
|
let mut retry_count = 0;
|
|
let mut success = false;
|
|
|
|
// Retry logic
|
|
while retry_count < MAX_RETRIES && !success {
|
|
match target.send_from_store(key.clone()).await {
|
|
Ok(_) => {
|
|
info!("Successfully sent event for target: {}", target.name());
|
|
success = true;
|
|
}
|
|
Err(e) => {
|
|
// Handle specific errors
|
|
match &e {
|
|
TargetError::NotConnected => {
|
|
warn!("Target {} not connected, retrying...", target.name());
|
|
retry_count += 1;
|
|
sleep(RETRY_DELAY).await;
|
|
}
|
|
TargetError::Timeout(_) => {
|
|
warn!("Timeout for target {}, retrying...", target.name());
|
|
retry_count += 1;
|
|
sleep(Duration::from_secs((retry_count * 5) as u64)).await; // Exponential backoff
|
|
}
|
|
_ => {
|
|
// Permanent error, skip this event
|
|
error!("Permanent error for target {}: {}", target.name(), e);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Remove event from store if successfully sent
|
|
if retry_count >= MAX_RETRIES && !success {
|
|
warn!("Max retries exceeded for event {}, target: {}, skipping", key.to_string(), target.name());
|
|
}
|
|
}
|
|
|
|
// Small delay before next iteration
|
|
sleep(Duration::from_millis(100)).await;
|
|
}
|
|
}
|
|
|
|
/// Starts the event streaming process for a target
|
|
pub fn start_event_stream(
|
|
mut store: Box<dyn Store<Event, Error = StoreError, Key = Key> + Send>,
|
|
target: Arc<dyn Target<Event> + Send + Sync>,
|
|
) -> mpsc::Sender<()> {
|
|
let (cancel_tx, cancel_rx) = mpsc::channel(1);
|
|
|
|
tokio::spawn(async move {
|
|
stream_events(&mut *store, &*target, cancel_rx).await;
|
|
info!("Event stream stopped for target: {}", target.name());
|
|
});
|
|
|
|
cancel_tx
|
|
}
|
|
|
|
/// Start event stream with batch processing
|
|
pub fn start_event_stream_with_batching(
|
|
mut store: Box<dyn Store<EntityTarget<Event>, Error = StoreError, Key = Key> + Send>,
|
|
target: Arc<dyn Target<Event> + Send + Sync>,
|
|
metrics: Arc<NotificationMetrics>,
|
|
semaphore: Arc<Semaphore>,
|
|
) -> mpsc::Sender<()> {
|
|
let (cancel_tx, cancel_rx) = mpsc::channel(1);
|
|
debug!("Starting event stream with batching for target: {}", target.name());
|
|
tokio::spawn(async move {
|
|
stream_events_with_batching(&mut *store, &*target, cancel_rx, metrics, semaphore).await;
|
|
info!("Event stream stopped for target: {}", target.name());
|
|
});
|
|
|
|
cancel_tx
|
|
}
|
|
|
|
/// Event stream processing with batch processing
|
|
pub async fn stream_events_with_batching(
|
|
store: &mut (dyn Store<EntityTarget<Event>, Error = StoreError, Key = Key> + Send),
|
|
target: &dyn Target<Event>,
|
|
mut cancel_rx: mpsc::Receiver<()>,
|
|
metrics: Arc<NotificationMetrics>,
|
|
semaphore: Arc<Semaphore>,
|
|
) {
|
|
info!("Starting event stream with batching for target: {}", target.name());
|
|
|
|
// Configuration parameters
|
|
const DEFAULT_BATCH_SIZE: usize = 1;
|
|
let batch_size = std::env::var("RUSTFS_EVENT_BATCH_SIZE")
|
|
.ok()
|
|
.and_then(|s| s.parse::<usize>().ok())
|
|
.unwrap_or(DEFAULT_BATCH_SIZE);
|
|
const BATCH_TIMEOUT: Duration = Duration::from_secs(5);
|
|
const MAX_RETRIES: usize = 5;
|
|
const BASE_RETRY_DELAY: Duration = Duration::from_secs(2);
|
|
|
|
let mut batch: Vec<EntityTarget<Event>> = Vec::with_capacity(batch_size);
|
|
let mut batch_keys = Vec::with_capacity(batch_size);
|
|
let mut last_flush = Instant::now();
|
|
|
|
loop {
|
|
// Check the cancel signal
|
|
if cancel_rx.try_recv().is_ok() {
|
|
info!("Cancellation received for target: {}", target.name());
|
|
return;
|
|
}
|
|
|
|
// Get a list of events in storage
|
|
let keys = store.list();
|
|
debug!("Found {} keys in store for target: {}", keys.len(), target.name());
|
|
if keys.is_empty() {
|
|
// If there is data in the batch and timeout, refresh the batch
|
|
if !batch.is_empty() && last_flush.elapsed() >= BATCH_TIMEOUT {
|
|
process_batch(&mut batch, &mut batch_keys, target, MAX_RETRIES, BASE_RETRY_DELAY, &metrics, &semaphore).await;
|
|
last_flush = Instant::now();
|
|
}
|
|
|
|
// No event, wait before checking
|
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
|
continue;
|
|
}
|
|
|
|
// Handle each event
|
|
for key in keys {
|
|
// Check the cancel signal again
|
|
if cancel_rx.try_recv().is_ok() {
|
|
info!("Cancellation received during processing for target: {}", target.name());
|
|
|
|
// Processing collected batches before exiting
|
|
if !batch.is_empty() {
|
|
process_batch(&mut batch, &mut batch_keys, target, MAX_RETRIES, BASE_RETRY_DELAY, &metrics, &semaphore).await;
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Try to get events from storage
|
|
match store.get(&key) {
|
|
Ok(event) => {
|
|
// Add to batch
|
|
batch.push(event);
|
|
batch_keys.push(key);
|
|
metrics.increment_processing();
|
|
|
|
// If the batch is full or enough time has passed since the last refresh, the batch will be processed
|
|
if batch.len() >= batch_size || last_flush.elapsed() >= BATCH_TIMEOUT {
|
|
process_batch(&mut batch, &mut batch_keys, target, MAX_RETRIES, BASE_RETRY_DELAY, &metrics, &semaphore)
|
|
.await;
|
|
last_flush = Instant::now();
|
|
}
|
|
}
|
|
Err(e) => {
|
|
error!("Failed to target: {}, get event {} from store: {}", target.name(), key.to_string(), e);
|
|
// Consider deleting unreadable events to prevent infinite loops from trying to read
|
|
match store.del(&key) {
|
|
Ok(_) => {
|
|
info!("Deleted corrupted event {} from store", key.to_string());
|
|
}
|
|
Err(del_err) => {
|
|
error!("Failed to delete corrupted event {}: {}", key.to_string(), del_err);
|
|
}
|
|
}
|
|
|
|
metrics.increment_failed();
|
|
}
|
|
}
|
|
}
|
|
|
|
// A small delay will be conducted to check the next round
|
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
|
}
|
|
}
|
|
|
|
/// Processing event batches
|
|
async fn process_batch(
|
|
batch: &mut Vec<EntityTarget<Event>>,
|
|
batch_keys: &mut Vec<Key>,
|
|
target: &dyn Target<Event>,
|
|
max_retries: usize,
|
|
base_delay: Duration,
|
|
metrics: &Arc<NotificationMetrics>,
|
|
semaphore: &Arc<Semaphore>,
|
|
) {
|
|
debug!("Processing batch of {} events for target: {}", batch.len(), target.name());
|
|
if batch.is_empty() {
|
|
return;
|
|
}
|
|
|
|
// Obtain semaphore permission to limit concurrency
|
|
let permit = match semaphore.clone().acquire_owned().await {
|
|
Ok(permit) => permit,
|
|
Err(e) => {
|
|
error!("Failed to acquire semaphore permit: {}", e);
|
|
return;
|
|
}
|
|
};
|
|
|
|
// Handle every event in the batch
|
|
for (_event, key) in batch.iter().zip(batch_keys.iter()) {
|
|
let mut retry_count = 0;
|
|
let mut success = false;
|
|
|
|
// Retry logic
|
|
while retry_count < max_retries && !success {
|
|
match target.send_from_store(key.clone()).await {
|
|
Ok(_) => {
|
|
info!("Successfully sent event for target: {}, Key: {}", target.name(), key.to_string());
|
|
success = true;
|
|
metrics.increment_processed();
|
|
}
|
|
Err(e) => {
|
|
// Different retry strategies are adopted according to the error type
|
|
match &e {
|
|
TargetError::NotConnected => {
|
|
warn!("Target {} not connected, retrying...", target.name());
|
|
retry_count += 1;
|
|
tokio::time::sleep(base_delay * (1 << retry_count)).await; // Exponential backoff
|
|
}
|
|
TargetError::Timeout(_) => {
|
|
warn!("Timeout for target {}, retrying...", target.name());
|
|
retry_count += 1;
|
|
tokio::time::sleep(base_delay * (1 << retry_count)).await;
|
|
}
|
|
_ => {
|
|
// Permanent error, skip this event
|
|
error!("Permanent error for target {}: {}", target.name(), e);
|
|
metrics.increment_failed();
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Handle the situation where the maximum number of retry exhaustion is exhausted
|
|
if retry_count >= max_retries && !success {
|
|
warn!("Max retries exceeded for event {}, target: {}, skipping", key.to_string(), target.name());
|
|
metrics.increment_failed();
|
|
}
|
|
}
|
|
|
|
// Clear processed batches
|
|
batch.clear();
|
|
batch_keys.clear();
|
|
|
|
// Release semaphore permission (via drop)
|
|
drop(permit);
|
|
}
|