diff --git a/rust/config/parameters.yaml b/rust/config/parameters.yaml index 3bbfb53630..48c68b4fa6 100644 --- a/rust/config/parameters.yaml +++ b/rust/config/parameters.yaml @@ -45,14 +45,6 @@ edit_level: DYNAMIC_EFFECTIVE description: "the percentage of disk space used by the data files. Range: [0,99] in integer" -- name: _datafile_usage_upper_bound_percentage - type: INT - default: "90" - range: "[5,99]" - section: SSTABLE - edit_level: DYNAMIC_EFFECTIVE - description: "the percentage of disk space usage upper bound to trigger datafile extend. Range: [5,99] in integer" - - name: enable_rpc_service type: BOOL default: "False" @@ -1045,14 +1037,6 @@ description: "default tablet size, has to be a multiple of 2M" checker: "common::ObConfigTabletSizeChecker" -- name: builtin_db_data_verify_cycle - type: INT - default: "20" - range: "[0, 360]" - section: OBSERVER - edit_level: DYNAMIC_EFFECTIVE - description: "check cycle of db data. Range: [0, 360] in integer. Unit: day. 0: check nothing. 1-360: check all data every specified days. The default value is 20. The real check cycle maybe longer than the specified value for insuring performance." - - name: micro_block_merge_verify_level type: INT default: "2" diff --git a/rust/storage-io/src/block_file.rs b/rust/storage-io/src/block_file.rs index 1cb10b1f22..16b5327e58 100644 --- a/rust/storage-io/src/block_file.rs +++ b/rust/storage-io/src/block_file.rs @@ -22,22 +22,53 @@ use std::fs::File; use std::io; use std::ops::Range; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; +const MAX_GENERATION: u64 = (1 << 60) - 1; + +/// The identity recorded in persistent metadata. An index alone cannot address +/// a block once that position has been reused. #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct BlockIndex(u64); +pub struct BlockId { + index: u64, + generation: u64, +} -impl BlockIndex { - pub fn new(index: u64) -> Result { +impl BlockId { + pub fn new(index: u64, generation: u64) -> Result { if index == 0 || index > i64::MAX as u64 { return Err(BlockError::InvalidBlock(index)); } - Ok(Self(index)) + if generation > MAX_GENERATION { + return Err(BlockError::InvalidInput("invalid block generation")); + } + Ok(Self { index, generation }) + } + + pub fn index(self) -> u64 { + self.index } - pub fn get(self) -> u64 { - self.0 + pub fn generation(self) -> u64 { + self.generation } + + fn position(self) -> Result { + usize::try_from(self.index).map_err(|_| BlockError::InvalidBlock(self.index)) + } +} + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum BlockKind { + Metadata, + Data, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct BlockMember { + pub id: BlockId, + pub kind: BlockKind, } #[derive(Clone, Copy, Debug)] @@ -61,10 +92,13 @@ pub struct BlockSnapshot { pub free_blocks: u64, pub pending_release_blocks: u64, pub reclamation_failures: u64, + pub published_data_blocks: u64, + pub published_metadata_blocks: u64, } +#[cfg(test)] #[derive(Debug)] -pub enum ReleaseOutcome { +pub(crate) enum ReleaseOutcome { Pending, Reusable { reclamation_error: Option, @@ -73,14 +107,23 @@ pub enum ReleaseOutcome { enum Slot { Header, - Unmarked { live: bool, leases: usize }, - Allocated { leases: usize }, - Pending { leases: usize }, + Unknown { leases: u32 }, + Live { + generation: u64, + raw_owner: bool, + owners: u32, + leases: u32, + published_data: u32, + published_metadata: u32, + }, + Pending { leases: u32 }, Free, } struct State { slots: Vec, + last_generation: u64, + recovering: bool, free: VecDeque, retired: VecDeque, punch_holes: bool, @@ -103,6 +146,51 @@ pub struct BlockFile { inner: Arc, } +/// Keeps a set of blocks readable until its last owner drops it. +#[derive(Clone)] +pub struct BlockGroup(Arc); + +struct GroupHold { + inner: Arc, + blocks: HeldBlocks, + published: AtomicBool, +} + +enum HeldBlocks { + Single([BlockMember; 1]), + Many(Vec), +} + +impl HeldBlocks { + fn new(members: &[BlockMember]) -> Result { + if let [member] = members { + return Ok(Self::Single([*member])); + } + let mut blocks = Vec::new(); + blocks.try_reserve_exact(members.len())?; + blocks.extend_from_slice(members); + // Prefer the data classification if an identity is used in both roles. + blocks.sort_unstable_by_key(|block| { + (block.id.index, block.id.generation, std::cmp::Reverse(block.kind)) + }); + blocks.dedup_by_key(|block| block.id); + for pair in blocks.windows(2) { + if pair[0].id.index == pair[1].id.index { + return Err(BlockError::StaleBlock(pair[0].id.index)); + } + } + Ok(Self::Many(blocks)) + } + + fn members(&self) -> &[BlockMember] { + match self { + Self::Single(members) => members, + Self::Many(members) => members, + } + } + +} + struct RegionLease { inner: Arc, index: usize, @@ -303,12 +391,11 @@ impl UnmarkedBlockFile { free.try_reserve_exact(count)?; retired.try_reserve_exact(count)?; slots.push(Slot::Header); - slots.resize_with(count, || Slot::Unmarked { - live: false, - leases: 0, - }); + slots.resize_with(count, || Slot::Unknown { leases: 0 }); Ok(State { slots, + last_generation: 0, + recovering: true, free, retired, punch_holes: config.punch_holes, @@ -334,34 +421,41 @@ impl UnmarkedBlockFile { } } - pub fn mark(&mut self, used: &[BlockIndex]) -> Result<(), BlockError> { - if !self.marking_valid { - return Err(BlockError::MarkingAborted); - } + #[cfg(test)] + pub(crate) fn mark(&mut self, used: &[BlockId]) -> Result<(), BlockError> { + self.check_marking()?; let mut state = self.inner.lock(); - if let Some(index) = used - .iter() - .find(|index| index.0 >= state.slots.len() as u64) - { - self.marking_valid = false; - return Err(BlockError::InvalidBlock(index.0)); - } - for index in used { - if let Slot::Unmarked { live, .. } = &mut state.slots[index.0 as usize] { - *live = true; + for &id in used { + if let Err(error) = state.register(id, true) { + self.marking_valid = false; + return Err(error); } } Ok(()) } + /// Registers the identities of one recovered object and keeps them live. + /// Allocation remains disabled until every persistent object is registered. + pub fn recover(&mut self, members: &[BlockMember]) -> Result { + self.check_marking()?; + let result = HeldBlocks::new(members).and_then(|blocks| self.inner.hold(blocks)); + if result.is_err() { + self.marking_valid = false; + } + result + } + pub fn abort_marking(&mut self) { self.marking_valid = false; } - pub fn restart_marking(&mut self) { - for slot in &mut self.inner.lock().slots { - if let Slot::Unmarked { live, .. } = slot { - *live = false; + #[cfg(test)] + pub(crate) fn restart_marking(&mut self) { + let mut state = self.inner.lock(); + for slot in &mut state.slots { + if let Slot::Live { raw_owner, .. } = slot { + *raw_owner = false; + slot.retire_if_unowned(true); } } self.marking_valid = true; @@ -379,25 +473,21 @@ impl UnmarkedBlockFile { self.check_marking()?; { let mut state = self.inner.lock(); + state.recovering = false; for index in 1..state.slots.len() { - let Slot::Unmarked { live, leases } = state.slots[index] else { - unreachable!("unmarked owner holds unmarked slots"); - }; - state.slots[index] = if live { - Slot::Allocated { leases } - } else { - Slot::Pending { leases } - }; - if !live && leases == 0 { - self.inner.reclaim(&mut state, index); + if let Slot::Unknown { leases } = state.slots[index] { + state.slots[index] = Slot::Pending { leases }; + if leases == 0 { + self.inner.reclaim(&mut state, index); + } } } } Ok(BlockFile { inner: self.inner }) } - pub fn region(&self, index: BlockIndex, range: Range) -> Result { - self.inner.region(index, range) + pub fn region(&self, id: BlockId, range: Range) -> Result { + self.inner.region(id, range) } pub fn sync(&self) -> Result<(), BlockError> { @@ -493,86 +583,106 @@ fn cleanup_creation( } impl BlockFile { - pub fn allocate(&self) -> Result { + #[cfg(test)] + pub(crate) fn allocate(&self) -> Result { let mut state = self.inner.lock(); self.inner.reclaim_retired(&mut state); - let index = state.free.pop_front().ok_or(BlockError::Exhausted)?; - state.slots[index] = Slot::Allocated { leases: 0 }; - Ok(BlockIndex(index as u64)) + state.allocate(true) } /// Allocates one block, growing the file when reusable blocks are exhausted. /// The supplied policy is fixed for this operation; later calls may use a new one. - pub fn allocate_with_growth( + #[cfg(test)] + pub(crate) fn allocate_with_growth( &self, policy: GrowthPolicy, budget: SpaceBudget, - ) -> Result { + ) -> Result { + self.allocate_with_policy(policy, budget, true) + } + + fn allocate_with_policy( + &self, + policy: GrowthPolicy, + budget: SpaceBudget, + raw_owner: bool, + ) -> Result { policy.validate()?; let mut state = self.inner.lock(); self.inner.reclaim_retired(&mut state); + if state.last_generation == MAX_GENERATION { + return Err(BlockError::GenerationExhausted); + } if state.free.is_empty() { self.inner.extend(&mut state, policy, budget)?; } - let index = state.free.pop_front().ok_or(BlockError::Exhausted)?; - state.slots[index] = Slot::Allocated { leases: 0 }; - Ok(BlockIndex(index as u64)) + state.allocate(raw_owner) } - /// Uses the caller's existing maintenance schedule; no worker is created. - pub fn extend_if_needed( + /// Allocates a block and returns a hold that will return it when dropped. + pub fn allocate_owned( &self, policy: GrowthPolicy, budget: SpaceBudget, - ) -> Result<(), BlockError> { - policy.validate()?; - let mut state = self.inner.lock(); - self.inner.reclaim_retired(&mut state); - if policy.needs_growth(state.slots.len() as u64, state.free.len() as u64) { - self.inner.extend(&mut state, policy, budget)?; - } - Ok(()) + ) -> Result<(BlockId, BlockGroup), BlockError> { + let id = self.allocate_with_policy(policy, budget, false)?; + let member = BlockMember { id, kind: BlockKind::Metadata }; + Ok((id, self.inner.group(HeldBlocks::Single([member])))) + } + + /// Acquires every identity in one operation. Repeated IDs need only one hold. + pub fn hold(&self, members: &[BlockMember]) -> Result { + self.inner.hold(HeldBlocks::new(members)?) + } + + #[cfg(feature = "cxx")] + pub(crate) fn is_live(&self, id: BlockId) -> bool { + self.inner.lock().allocated_mut(id).is_ok() } - pub fn allocate_many(&self, count: usize) -> Result, BlockError> { + #[cfg(test)] + pub(crate) fn allocate_many(&self, count: usize) -> Result, BlockError> { let mut state = self.inner.lock(); self.inner.reclaim_retired(&mut state); let count = count.min(state.free.len()); + if count as u64 > MAX_GENERATION - state.last_generation { + return Err(BlockError::GenerationExhausted); + } let mut result = Vec::new(); result.try_reserve_exact(count)?; for _ in 0..count { - let index = state.free.pop_front().expect("checked free count"); - state.slots[index] = Slot::Allocated { leases: 0 }; - result.push(BlockIndex(index as u64)); + result.push(state.allocate(true)?); } Ok(result) } - pub fn release(&self, index: BlockIndex) -> Result { + #[cfg(test)] + pub(crate) fn release(&self, id: BlockId) -> Result { let mut state = self.inner.lock(); - let position = usize::try_from(index.0).map_err(|_| BlockError::InvalidBlock(index.0))?; - let slot = state - .slots - .get_mut(position) - .ok_or(BlockError::InvalidBlock(index.0))?; - let Slot::Allocated { leases } = *slot else { - return Err(BlockError::NotAllocated(index.0)); + let slot = state.allocated_mut(id)?; + let Slot::Live { raw_owner, .. } = slot else { + unreachable!("validated block slot"); }; - *slot = Slot::Pending { leases }; - if leases != 0 { - Ok(ReleaseOutcome::Pending) - } else { + if !*raw_owner { + return Err(BlockError::NotAllocated(id.index)); + } + *raw_owner = false; + if slot.retire_if_unowned(false) { + let position = id.index as usize; let reclamation_error = self.inner.reclaim(&mut state, position); Ok(ReleaseOutcome::Reusable { reclamation_error }) + } else { + Ok(ReleaseOutcome::Pending) } } - pub fn reclaim_released(&self) { + #[cfg(test)] + pub(crate) fn reclaim_released(&self) { self.inner.reclaim_retired(&mut self.inner.lock()); } - pub fn region(&self, index: BlockIndex, range: Range) -> Result { - self.inner.region(index, range) + pub fn region(&self, id: BlockId, range: Range) -> Result { + self.inner.region(id, range) } pub fn sync(&self) -> Result<(), BlockError> { @@ -599,7 +709,8 @@ impl BlockFile { capacity::used_percentage( self.inner.block_size, state.slots.len() as u64, - state.free.len() as u64, + // Allocation drains this queue before looking at free slots. + (state.free.len() + state.retired.len()) as u64, self.inner.maximum_capacity(&state, max_bytes, budget), required_bytes, ) @@ -658,7 +769,113 @@ fn extend_and_sync(file: &File, range: Range) -> io::Result<()> { file.sync_all() } +impl State { + fn allocate(&mut self, raw_owner: bool) -> Result { + if self.last_generation == MAX_GENERATION { + return Err(BlockError::GenerationExhausted); + } + let index = self.free.pop_front().ok_or(BlockError::Exhausted)?; + self.last_generation += 1; + let generation = self.last_generation; + self.slots[index] = Slot::Live { + generation, + raw_owner, + owners: u32::from(!raw_owner), + leases: 0, + published_data: 0, + published_metadata: 0, + }; + Ok(BlockId { + index: index as u64, + generation, + }) + } + + fn check_hold(&self, id: BlockId) -> Result<(), BlockError> { + let slot = self.slots.get(id.position()?) + .ok_or(BlockError::InvalidBlock(id.index))?; + match slot { + Slot::Live { generation, .. } if *generation != id.generation => { + Err(BlockError::StaleBlock(id.index)) + } + Slot::Live { owners, .. } if *owners == u32::MAX => { + Err(BlockError::InvalidInput("too many block owners")) + } + Slot::Live { .. } | Slot::Unknown { .. } => Ok(()), + _ => Err(BlockError::NotAllocated(id.index)), + } + } + + fn register(&mut self, id: BlockId, raw: bool) -> Result<(), BlockError> { + self.check_hold(id)?; + let slot = &mut self.slots[id.index as usize]; + match slot { + Slot::Unknown { leases } => { + *slot = Slot::Live { + generation: id.generation, + raw_owner: raw, + owners: u32::from(!raw), + leases: *leases, + published_data: 0, + published_metadata: 0, + }; + self.last_generation = self.last_generation.max(id.generation); + } + Slot::Live { raw_owner, owners, .. } => { + *raw_owner |= raw; + *owners += u32::from(!raw); + } + _ => unreachable!("checked block slot"), + } + Ok(()) + } + + fn allocated_mut(&mut self, id: BlockId) -> Result<&mut Slot, BlockError> { + let slot = self.slots.get_mut(id.position()?) + .ok_or(BlockError::InvalidBlock(id.index))?; + match slot { + Slot::Live { generation, .. } if *generation == id.generation => Ok(slot), + Slot::Live { .. } => Err(BlockError::StaleBlock(id.index)), + _ => Err(BlockError::NotAllocated(id.index)), + } + } + +} + +impl Slot { + // The caller either reclaims a newly idle slot or queues it for maintenance. + fn retire_if_unowned(&mut self, recovering: bool) -> bool { + if let Self::Live { raw_owner: false, owners: 0, leases, .. } = *self { + *self = if recovering { Self::Unknown { leases } } else { Self::Pending { leases } }; + !recovering && leases == 0 + } else { + false + } + } +} + impl Inner { + fn hold(self: &Arc, blocks: HeldBlocks) -> Result { + { + let mut state = self.lock(); + for block in blocks.members() { + state.check_hold(block.id)?; + } + for block in blocks.members() { + state.register(block.id, false).expect("validated block identities"); + } + } + Ok(self.group(blocks)) + } + + fn group(self: &Arc, blocks: HeldBlocks) -> BlockGroup { + BlockGroup(Arc::new(GroupHold { + inner: Arc::clone(self), + blocks, + published: AtomicBool::new(false), + })) + } + fn capacity(&self, state: &State) -> u64 { state.slots.len() as u64 * self.block_size } @@ -726,28 +943,28 @@ impl Inner { self.state.lock().expect("physical block state poisoned") } - fn region( - self: &Arc, - index: BlockIndex, - range: Range, - ) -> Result { + fn region(self: &Arc, id: BlockId, range: Range) -> Result { if range.start > range.end || range.end > self.block_size { return Err(BlockError::InvalidInput("range exceeds physical block")); } let mut state = self.lock(); - let position = usize::try_from(index.0).map_err(|_| BlockError::InvalidBlock(index.0))?; + let position = id.position()?; let slot = state .slots .get_mut(position) - .ok_or(BlockError::InvalidBlock(index.0))?; - match slot { - Slot::Allocated { leases } | Slot::Unmarked { leases, .. } => { - *leases = leases - .checked_add(1) - .ok_or(BlockError::InvalidInput("too many region leases"))?; + .ok_or(BlockError::InvalidBlock(id.index))?; + let leases = match slot { + Slot::Live { generation, leases, .. } => { + if *generation != id.generation { + return Err(BlockError::StaleBlock(id.index)); + } + leases } - _ => return Err(BlockError::NotAllocated(index.0)), - } + Slot::Unknown { leases } => leases, + _ => return Err(BlockError::NotAllocated(id.index)), + }; + *leases = leases.checked_add(1) + .ok_or(BlockError::InvalidInput("too many region leases"))?; Ok(BlockRegion { lease: Arc::new(RegionLease { inner: Arc::clone(self), @@ -755,7 +972,7 @@ impl Inner { #[cfg(any(test, feature = "ownership-test-support"))] drop_witness: crate::drop_witness::DropRegistration::default(), }), - start: index.0 * self.block_size + range.start, + start: id.index * self.block_size + range.start, length: range.end - range.start, }) } @@ -793,17 +1010,26 @@ impl Inner { fn snapshot(&self) -> BlockSnapshot { let state = self.lock(); + let mut pending_release_blocks = 0; + let mut published_data_blocks = 0; + let mut published_metadata_blocks = 0; + for slot in &state.slots { + match slot { + Slot::Pending { .. } => pending_release_blocks += 1, + Slot::Live { published_data, .. } if *published_data != 0 => published_data_blocks += 1, + Slot::Live { published_metadata, .. } if *published_metadata != 0 => published_metadata_blocks += 1, + _ => {} + } + } BlockSnapshot { block_size: self.block_size, - capacity: state.slots.len() as u64 * self.block_size, + capacity: self.capacity(&state), total_blocks: state.slots.len() as u64, free_blocks: state.free.len() as u64, - pending_release_blocks: state - .slots - .iter() - .filter(|slot| matches!(slot, Slot::Pending { .. })) - .count() as u64, reclamation_failures: state.reclamation_failures, + pending_release_blocks, + published_data_blocks, + published_metadata_blocks, } } } @@ -882,7 +1108,7 @@ impl Drop for RegionLease { let _witness = self.drop_witness.enter(); let mut state = self.inner.lock(); match &mut state.slots[self.index] { - Slot::Allocated { leases } | Slot::Unmarked { leases, .. } => *leases -= 1, + Slot::Live { leases, .. } | Slot::Unknown { leases } => *leases -= 1, Slot::Pending { leases } => { *leases -= 1; if *leases == 0 { @@ -894,6 +1120,58 @@ impl Drop for RegionLease { } } +impl BlockGroup { + /// Marks a group's current durable publication. Old readers can keep the + /// same blocks alive after the publication is replaced. + pub fn set_published(&self, published: bool) { + let mut state = self.0.inner.lock(); + self.0.set_published(&mut state, published); + } +} + +impl GroupHold { + fn set_published(&self, state: &mut State, published: bool) { + if self.published.swap(published, Ordering::Relaxed) == published { + return; + } + for block in self.blocks.members() { + let Slot::Live { published_data, published_metadata, .. } = + &mut state.slots[block.id.index as usize] + else { + unreachable!("published group owns its blocks"); + }; + let counter = match block.kind { + BlockKind::Data => published_data, + BlockKind::Metadata => published_metadata, + }; + if published { + *counter += 1; + } else { + *counter -= 1; + } + } + } +} + +impl Drop for GroupHold { + fn drop(&mut self) { + let mut state = self.inner.lock(); + self.set_published(&mut state, false); + let recovering = state.recovering; + for block in self.blocks.members() { + let position = block.id.index as usize; + let slot = &mut state.slots[position]; + let Slot::Live { owners, .. } = slot else { + unreachable!("group owns its blocks"); + }; + *owners -= 1; + if slot.retire_if_unowned(recovering) { + state.retired.push_back(position); + } + } + } +} + #[cfg(test)] #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum CreationStage { diff --git a/rust/storage-io/src/bridge.rs b/rust/storage-io/src/bridge.rs index d91acb90e0..a32bfd7a33 100644 --- a/rust/storage-io/src/bridge.rs +++ b/rust/storage-io/src/bridge.rs @@ -22,7 +22,7 @@ use statistics::{ }; mod requests; use crate::Request; -use blocks::{new_block_owner, BlockOwner}; +use blocks::{new_block_group, new_block_owner, BlockGroupHandle, BlockOwner}; pub use ffi::RequestOptions; use file_io::toggle_worker_fault_delay; pub use requests::{new_service_handle, ServiceHandle}; @@ -75,6 +75,8 @@ pub mod ffi { InvalidHeader, ChecksumMismatch, NotAllocated, + StaleBlock, + GenerationExhausted, MarkingAborted, Exhausted, IoError, @@ -97,11 +99,41 @@ pub mod ffi { punch_holes: bool, } + #[derive(Clone, Copy)] + struct BlockAddress { + index: u64, + generation: u64, + } + + enum BlockKind { + Metadata, + Data, + } + + struct BlockMember { + address: BlockAddress, + kind: BlockKind, + } + + #[derive(Clone)] + struct BlockFailure { + address: BlockAddress, + third_id: i64, + error_type: i64, + observed_us: i64, + file: Vec, + message: Vec, + } + + struct BlockRead { + request: Box, + hold: Box, + } + struct BlockGrowth { max_bytes: u64, next_bytes: u64, reserved_bytes: u64, - usage_upper_percent: u8, } struct BlockOpenResult { @@ -115,20 +147,22 @@ pub mod ffi { directory_summary: DirectorySyncSummary, } - struct BlockRelease { + struct BlockAllocation { status: BlockStatus, - pending: bool, - reclamation_error: i32, - reclamation_os_error: i32, + address: BlockAddress, + hold: Box, } struct BlockStats { + ready: bool, block_size: u64, capacity: u64, total_blocks: u64, free_blocks: u64, pending_release_blocks: u64, reclamation_failures: u64, + published_data_blocks: u64, + published_metadata_blocks: u64, } enum RequestMode { @@ -293,6 +327,9 @@ pub mod ffi { ) -> Box; fn read_named(self: &NamedFile, bytes: &mut [u8], offset: u64) -> IoResult; fn resize_named(self: &NamedFile, length: u64) -> i32; + type BlockGroupHandle; + fn new_block_group() -> Box; + fn set_published(self: &BlockGroupHandle, published: bool); type BlockOwner; fn new_block_owner() -> Box; fn open_blocks(self: &BlockOwner, path: &[u8], options: &BlockOptions) -> BlockOpenResult; @@ -306,18 +343,28 @@ pub mod ffi { fn validate_block_workers(self: &BlockOwner, configured: usize) -> i32; fn submit_block( self: &BlockOwner, - index: u64, + id: BlockAddress, options: &RequestOptions, bytes: &[u8], callback: UniquePtr, ) -> Box; - fn mark_blocks(self: &BlockOwner, indices: &[u64]) -> BlockStatus; - fn restart_marking(self: &BlockOwner) -> BlockStatus; + fn submit_block_read( + self: &BlockOwner, + id: BlockAddress, + options: &RequestOptions, + callback: UniquePtr, + ) -> BlockRead; + fn hold_blocks( + self: &BlockOwner, + members: &[BlockMember], + out: &mut BlockGroupHandle, + ) -> BlockStatus; + fn allocate_held_block(self: &BlockOwner, policy: &BlockGrowth) -> BlockAllocation; + fn block_live(self: &BlockOwner, address: BlockAddress) -> bool; + fn record_block_failure(self: &BlockOwner, failure: BlockFailure) -> BlockStatus; + fn block_failures(self: &BlockOwner) -> Vec; fn finish_marking(self: &BlockOwner) -> BlockStatus; - fn allocate_block(self: &BlockOwner, policy: &BlockGrowth, out: &mut u64) -> BlockStatus; - fn release_block(self: &BlockOwner, index: u64) -> BlockRelease; fn sync_blocks(self: &BlockOwner) -> BlockStatus; - fn extend_blocks(self: &BlockOwner, policy: &BlockGrowth) -> BlockStatus; fn resize_blocks( self: &BlockOwner, bytes: u64, diff --git a/rust/storage-io/src/bridge/blocks.rs b/rust/storage-io/src/bridge/blocks.rs index c614d6745d..71d5cb0ca2 100644 --- a/rust/storage-io/src/bridge/blocks.rs +++ b/rust/storage-io/src/bridge/blocks.rs @@ -18,10 +18,10 @@ use super::{ }; use crate::file_session::FileSession; use crate::{ - BlockConfig, BlockError, BlockFile, BlockIndex, BlockRegion, FileSize, GrowthPolicy, - ReleaseOutcome, SpaceBudget, UnmarkedBlockFile, + BlockConfig, BlockError, BlockFile, BlockGroup, BlockId, BlockKind, BlockMember, BlockRegion, FileSize, GrowthPolicy, + SpaceBudget, UnmarkedBlockFile, }; -use file_io::bridge::{error_number, legacy_path}; +use file_io::bridge::legacy_path; use std::{ io, ops::Range, @@ -34,15 +34,31 @@ enum State { Ready(BlockFile), } +pub struct BlockGroupHandle(Option); + +pub fn new_block_group() -> Box { + Box::new(BlockGroupHandle(None)) +} + +impl BlockGroupHandle { + pub fn set_published(&self, published: bool) { + if let Some(group) = &self.0 { + group.set_published(published); + } + } +} + pub struct BlockOwner { state: Mutex, session: FileSession, + failures: Mutex>, } pub fn new_block_owner() -> Box { Box::new(BlockOwner { state: Mutex::new(State::Empty), session: FileSession::default(), + failures: Mutex::new(Vec::new()), }) } @@ -62,7 +78,6 @@ fn growth_policy(policy: &ffi::BlockGrowth) -> GrowthPolicy { GrowthPolicy { max_bytes: policy.max_bytes, next_bytes: policy.next_bytes, - usage_upper_percent: policy.usage_upper_percent, } } @@ -85,6 +100,8 @@ fn failure(error: BlockError) -> ffi::BlockStatus { BlockError::InvalidHeader => ffi::BlockCode::InvalidHeader, BlockError::ChecksumMismatch => ffi::BlockCode::ChecksumMismatch, BlockError::NotAllocated(_) => ffi::BlockCode::NotAllocated, + BlockError::StaleBlock(_) => ffi::BlockCode::StaleBlock, + BlockError::GenerationExhausted => ffi::BlockCode::GenerationExhausted, BlockError::MarkingAborted => ffi::BlockCode::MarkingAborted, BlockError::Exhausted => ffi::BlockCode::Exhausted, BlockError::Io(_) | BlockError::DirectorySync { .. } => ffi::BlockCode::IoError, @@ -155,29 +172,6 @@ fn open_result( opened } -fn release_result(result: Result) -> ffi::BlockRelease { - let mut release = ffi::BlockRelease { - status: code_status(ffi::BlockCode::Ok), - pending: false, - reclamation_error: 0, - reclamation_os_error: 0, - }; - match result { - Ok(ReleaseOutcome::Pending) => release.pending = true, - Ok(ReleaseOutcome::Reusable { - reclamation_error: Some(error), - }) => { - release.reclamation_os_error = error.raw_os_error().unwrap_or(0); - release.reclamation_error = error_number(error); - } - Ok(ReleaseOutcome::Reusable { - reclamation_error: None, - }) => (), - Err(status) => release.status = status, - } - release -} - impl BlockOwner { fn lock(&self) -> MutexGuard<'_, State> { self.state @@ -238,30 +232,74 @@ impl BlockOwner { requests::prepare_session(&self.session, service, directory, execution) } pub fn close_blocks(&self) -> i32 { - requests::status(self.session.close(|| *self.lock() = State::Empty)) + requests::status(self.session.close(|| { + *self.lock() = State::Empty; + self.failures.lock().expect("block failures poisoned").clear(); + })) } pub fn validate_block_workers(&self, configured: usize) -> i32 { requests::status(self.session.validate_workers(configured)) } pub fn submit_block( &self, - index: u64, + id: ffi::BlockAddress, options: &ffi::RequestOptions, bytes: &[u8], callback: cxx::UniquePtr, ) -> Box { - self.submit_block_request(index, options, bytes, requests::take_callback(callback)) + self.submit_block_request(id, options, bytes, requests::take_callback(callback)) + } + + pub fn submit_block_read( + &self, + address: ffi::BlockAddress, + options: &ffi::RequestOptions, + callback: cxx::UniquePtr, + ) -> ffi::BlockRead { + let callback = requests::take_callback(callback); + let captured = self.session.capture(|endpoint| { + if options.mode != ffi::RequestMode::Read { + return Err(io::ErrorKind::InvalidInput.into()); + } + let plan = requests::logical_plan(options)?; + let id = block_id(address).map_err(block_io_error)?; + let range = region_range(plan.offset, plan.length)?; + let member = BlockMember { id, kind: BlockKind::Metadata }; + let mut state = self.lock(); + let (hold, region) = match &mut *state { + State::Empty => return Err(io::ErrorKind::NotConnected.into()), + State::Marking(file) => (file.recover(&[member]), file.region(id, range)), + State::Ready(file) => (file.hold(&[member]), file.region(id, range)), + }; + Ok(( + std::sync::Arc::clone(endpoint), + plan, + crate::Target::Block(region.map_err(block_io_error)?), + hold.map_err(block_io_error)?, + )) + }); + let (request, hold) = match captured { + Ok((endpoint, plan, target, hold)) => ( + requests::submit_owned(&endpoint, target, &plan, options, &[], callback), + Some(hold), + ), + Err(error) => (requests::reject(error, callback), None), + }; + ffi::BlockRead { request, hold: Box::new(BlockGroupHandle(hold)) } } + pub(super) fn submit_block_request( &self, - index: u64, + id: ffi::BlockAddress, options: &ffi::RequestOptions, bytes: &[u8], callback: Option, ) -> Box { let captured = self.session.capture(|endpoint| { let plan = requests::logical_plan(options)?; - let target = checked_region(self, index, plan.offset, plan.length)?; + let target = checked_region( + self, id, plan.offset, plan.length, options.mode == ffi::RequestMode::Write, + )?; Ok(( std::sync::Arc::clone(endpoint), plan, @@ -276,42 +314,100 @@ impl BlockOwner { } } - pub fn mark_blocks(&self, indices: &[u64]) -> ffi::BlockStatus { + pub fn hold_blocks( + &self, + members: &[ffi::BlockMember], + out: &mut BlockGroupHandle, + ) -> ffi::BlockStatus { + if out.0.is_some() { + return code_status(ffi::BlockCode::AlreadyOpen); + } let mut state = self.lock(); - let file = match &mut *state { - State::Empty => return code_status(ffi::BlockCode::NotOpen), - State::Ready(_) => { - return failure(BlockError::InvalidInput("marking already finished")); - } - State::Marking(file) => file, - }; + if matches!(*state, State::Empty) { + return code_status(ffi::BlockCode::NotOpen); + } let result = (|| { - file.check_marking()?; - let mut used = Vec::new(); - used.try_reserve_exact(indices.len())?; - for &index in indices { - used.push(BlockIndex::new(index)?); + let mut blocks = Vec::new(); + blocks.try_reserve_exact(members.len())?; + for member in members { + let id = BlockId::new(member.address.index, member.address.generation)?; + let kind = match member.kind { + ffi::BlockKind::Metadata => BlockKind::Metadata, + ffi::BlockKind::Data => BlockKind::Data, + _ => return Err(BlockError::InvalidInput("invalid block role")), + }; + blocks.push(BlockMember { id, kind }); + } + match &mut *state { + State::Empty => unreachable!("open block state required"), + State::Marking(file) => file.recover(&blocks), + State::Ready(file) => file.hold(&blocks), } - file.mark(&used) })(); - if result.is_err() { - file.abort_marking(); + match result { + Ok(group) => { + out.0 = Some(group); + code_status(ffi::BlockCode::Ok) + } + Err(error) => { + if let State::Marking(file) = &mut *state { + file.abort_marking(); + } + failure(error) + } } - result_status(result) } - pub fn restart_marking(&self) -> ffi::BlockStatus { - let mut state = self.lock(); - match &mut *state { + pub fn allocate_held_block(&self, policy: &ffi::BlockGrowth) -> ffi::BlockAllocation { + let result = self.with_ready(|file| { + file.allocate_owned(growth_policy(policy), space_budget(policy.reserved_bytes)) + }); + let (status, address, group) = match result { + Ok((id, hold)) => ( + code_status(ffi::BlockCode::Ok), + ffi::BlockAddress { index: id.index(), generation: id.generation() }, + Some(hold), + ), + Err(status) => (status, ffi::BlockAddress { index: 0, generation: 0 }, None), + }; + ffi::BlockAllocation { status, address, hold: Box::new(BlockGroupHandle(group)) } + } + + pub fn block_live(&self, address: ffi::BlockAddress) -> bool { + self.with_ready(|file| { + Ok(file.is_live(BlockId::new(address.index, address.generation)?)) + }).unwrap_or(false) + } + + pub fn record_block_failure(&self, failure: ffi::BlockFailure) -> ffi::BlockStatus { + let state = self.lock(); + let total_blocks = match &*state { State::Empty => return code_status(ffi::BlockCode::NotOpen), - State::Ready(_) => { - return failure(BlockError::InvalidInput("marking already finished")); - } - State::Marking(file) => file.restart_marking(), + State::Marking(file) => file.snapshot().total_blocks, + State::Ready(file) => file.snapshot().total_blocks, + }; + let mut failures = self.failures.lock().expect("block failures poisoned"); + if failures.iter().any(|entry| { + entry.address.index == failure.address.index + && entry.address.generation == failure.address.generation + && entry.third_id == failure.third_id + }) { + return code_status(ffi::BlockCode::Ok); + } + if failures.len() as u64 >= (total_blocks / 100).max(10) { + return code_status(ffi::BlockCode::Exhausted); + } + if failures.try_reserve(1).is_err() { + return code_status(ffi::BlockCode::Memory); } + failures.push(failure); code_status(ffi::BlockCode::Ok) } + pub fn block_failures(&self) -> Vec { + self.failures.lock().expect("block failures poisoned").clone() + } + pub fn finish_marking(&self) -> ffi::BlockStatus { let mut state = self.lock(); match &*state { @@ -344,41 +440,11 @@ impl BlockOwner { let state = self.lock(); match &*state { State::Empty => Err(code_status(ffi::BlockCode::NotOpen)), - State::Marking(_) => Err(failure(BlockError::InvalidInput("marking not finished"))), + State::Marking(_) => Err(code_status(ffi::BlockCode::NotOpen)), State::Ready(file) => action(file).map_err(failure), } } - pub fn allocate_block(&self, policy: &ffi::BlockGrowth, out: &mut u64) -> ffi::BlockStatus { - match self.with_ready(|file| { - file.allocate_with_growth(growth_policy(policy), space_budget(policy.reserved_bytes)) - }) { - Ok(index) => { - *out = index.get(); - code_status(ffi::BlockCode::Ok) - } - Err(status) => status, - } - } - - pub fn release_block(&self, index: u64) -> ffi::BlockRelease { - let state = self.lock(); - let file = match &*state { - State::Empty => return release_result(Err(code_status(ffi::BlockCode::NotOpen))), - State::Marking(_) => { - return release_result(Err(failure(BlockError::InvalidInput( - "marking not finished", - )))); - } - State::Ready(file) => file, - }; - release_result( - BlockIndex::new(index) - .and_then(|index| file.release(index)) - .map_err(failure), - ) - } - pub fn sync_blocks(&self) -> ffi::BlockStatus { let state = self.lock(); result_status(match &*state { @@ -388,14 +454,10 @@ impl BlockOwner { }) } - pub fn extend_blocks(&self, policy: &ffi::BlockGrowth) -> ffi::BlockStatus { - self.with_ready(|file| { - file.extend_if_needed(growth_policy(policy), space_budget(policy.reserved_bytes)) - }) - .map_or_else(|status| status, |()| code_status(ffi::BlockCode::Ok)) - } - pub fn resize_blocks(&self, bytes: u64, percentage: u8, reserved: u64) -> ffi::BlockStatus { + if matches!(*self.lock(), State::Marking(_)) { + return code_status(ffi::BlockCode::Ok); + } self.with_ready(|file| file.resize(file_size(bytes, percentage), space_budget(reserved))) .map_or_else(|status| status, |()| code_status(ffi::BlockCode::Ok)) } @@ -434,40 +496,55 @@ impl BlockOwner { State::Ready(file) => file.snapshot(), }; *stats = ffi::BlockStats { + ready: matches!(*state, State::Ready(_)), block_size: snapshot.block_size, capacity: snapshot.capacity, total_blocks: snapshot.total_blocks, free_blocks: snapshot.free_blocks, pending_release_blocks: snapshot.pending_release_blocks, reclamation_failures: snapshot.reclamation_failures, + published_data_blocks: snapshot.published_data_blocks, + published_metadata_blocks: snapshot.published_metadata_blocks, }; code_status(ffi::BlockCode::Ok) } - fn region(&self, index: BlockIndex, range: Range) -> io::Result { + fn region(&self, id: BlockId, range: Range, writable: bool) -> io::Result { let state = self.lock(); match &*state { State::Empty => return Err(io::ErrorKind::NotConnected.into()), - State::Marking(file) => file.region(index, range), - State::Ready(file) => file.region(index, range), + State::Marking(file) if !writable => file.region(id, range), + State::Marking(_) => return Err(io::ErrorKind::NotConnected.into()), + State::Ready(file) => file.region(id, range), } - .map_err(|error| match error { - BlockError::Io(error) => error, - error => io::Error::new(io::ErrorKind::InvalidInput, error), - }) + .map_err(block_io_error) } } pub(super) fn checked_region( owner: &BlockOwner, - index: u64, + id: ffi::BlockAddress, offset: u64, length: usize, + writable: bool, ) -> io::Result { - let end = offset - .checked_add(length as u64) - .ok_or(io::ErrorKind::InvalidInput)?; - let index = BlockIndex::new(index) - .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?; - owner.region(index, offset..end) + owner.region(block_id(id).map_err(block_io_error)?, region_range(offset, length)?, writable) +} + +fn block_id(address: ffi::BlockAddress) -> Result { + BlockId::new(address.index, address.generation) +} + +fn region_range(offset: u64, length: usize) -> io::Result> { + let end = offset.checked_add(length as u64).ok_or(io::ErrorKind::InvalidInput)?; + Ok(offset..end) +} + +fn block_io_error(error: BlockError) -> io::Error { + match error { + BlockError::Io(error) => error, + BlockError::NotAllocated(_) => io::Error::new(io::ErrorKind::NotFound, error), + BlockError::Memory(_) => io::Error::new(io::ErrorKind::OutOfMemory, error), + error => io::Error::new(io::ErrorKind::InvalidInput, error), + } } diff --git a/rust/storage-io/src/capacity.rs b/rust/storage-io/src/capacity.rs index f50e78898a..1eab99dca9 100644 --- a/rust/storage-io/src/capacity.rs +++ b/rust/storage-io/src/capacity.rs @@ -24,7 +24,6 @@ pub enum FileSize { pub struct GrowthPolicy { pub max_bytes: u64, pub next_bytes: u64, - pub usage_upper_percent: u8, } impl FileSize { @@ -65,19 +64,12 @@ impl GrowthPolicy { pub(crate) fn validate(self) -> Result<(), BlockError> { if self.max_bytes > i64::MAX as u64 || self.next_bytes > i64::MAX as u64 - || !(1..100).contains(&self.usage_upper_percent) { return Err(BlockError::InvalidInput("invalid datafile growth policy")); } Ok(()) } - pub(crate) fn needs_growth(self, total: u64, free: u64) -> bool { - let threshold = - total - (u128::from(total) * u128::from(self.usage_upper_percent) / 100) as u64; - free <= threshold || free <= 8 - } - pub(crate) fn target(self, current: u64, block_size: u64) -> Result { self.validate()?; if self.max_bytes <= current || block_size == 0 { diff --git a/rust/storage-io/src/lib.rs b/rust/storage-io/src/lib.rs index de45f1830e..2129225cd2 100644 --- a/rust/storage-io/src/lib.rs +++ b/rust/storage-io/src/lib.rs @@ -32,9 +32,12 @@ mod service; pub mod statistics; pub use block_file::{ - BlockConfig, BlockFile, BlockIndex, BlockRegion, BlockSnapshot, ReleaseOutcome, SpaceBudget, + BlockConfig, BlockFile, BlockGroup, BlockId, BlockKind, BlockMember, BlockRegion, BlockSnapshot, + SpaceBudget, UnmarkedBlockFile, }; +#[cfg(test)] +pub(crate) use block_file::ReleaseOutcome; pub use header::{encode_block_header, validate_block_header, HEADER_PAGE_SIZE}; pub use service::{ AdmissionLimits, CancelOutcome, CompletionRequirement, CompletionStatus, Config, ConfigError, @@ -74,6 +77,8 @@ pub enum BlockError { ChecksumMismatch, InvalidBlock(u64), NotAllocated(u64), + StaleBlock(u64), + GenerationExhausted, MarkingAborted, Exhausted, Io(io::Error), @@ -96,6 +101,8 @@ impl fmt::Display for BlockError { Self::ChecksumMismatch => f.write_str("physical block file header checksum mismatch"), Self::InvalidBlock(index) => write!(f, "invalid physical block index {index}"), Self::NotAllocated(index) => write!(f, "physical block {index} is not allocated"), + Self::StaleBlock(index) => write!(f, "stale identity for physical block {index}"), + Self::GenerationExhausted => f.write_str("physical block generation exhausted"), Self::MarkingAborted => f.write_str("startup marking must be restarted"), Self::Exhausted => f.write_str("physical block capacity exhausted"), Self::Io(error) => error.fmt(f), diff --git a/rust/storage-io/src/service/tests.rs b/rust/storage-io/src/service/tests.rs index eb495c6249..cb7562f0bf 100644 --- a/rust/storage-io/src/service/tests.rs +++ b/rust/storage-io/src/service/tests.rs @@ -316,7 +316,7 @@ fn native_service_retires_block_lease_before_consumed_buffer_is_released() { assert_eq!(read.data().unwrap(), &[0x35; 8]); assert_eq!(service.snapshot().unwrap().reserved_bytes, 4096); owner.release(block).unwrap(); - assert_eq!(owner.allocate().unwrap(), block); + assert_eq!(owner.allocate().unwrap().index(), block.index()); service.shutdown().unwrap(); assert_eq!(read.data().unwrap(), &[0x35; 8]); } @@ -467,7 +467,7 @@ fn cancellation_keeps_region_and_budget_until_physical_retirement() { retire(&mut engine); assert!(engine.active.is_empty()); assert_eq!(engine.snapshot().reserved_bytes, 0); - assert_eq!(owner.allocate().unwrap(), block); + assert_eq!(owner.allocate().unwrap().index(), block.index()); assert!(result.try_recv().is_err()); } #[test] diff --git a/rust/storage-io/src/service/tests/ownership.rs b/rust/storage-io/src/service/tests/ownership.rs index 64226ee149..08c3e7aae1 100644 --- a/rust/storage-io/src/service/tests/ownership.rs +++ b/rust/storage-io/src/service/tests/ownership.rs @@ -13,7 +13,7 @@ // limitations under the License. use super::*; -use crate::{BlockError, BlockFile, BlockIndex}; +use crate::{BlockError, BlockFile, BlockId}; use std::path::Path; fn config() -> BlockConfig { @@ -42,7 +42,7 @@ fn assert_claimed(path: &Path) { } } -fn write(owner: &BlockFile, block: BlockIndex) -> RequestSpec { +fn write(owner: &BlockFile, block: BlockId) -> RequestSpec { RequestSpec::new( DEVICE, Target::Block(owner.region(block, 0..4096).unwrap()), @@ -135,7 +135,7 @@ fn lease_witness_observes_a_region_clone_after_lifetime_release() { assert!(unavailable); assert!(witness.finished()); assert!(!witness.timed_out()); - assert_eq!(owner.allocate().unwrap(), block); + assert_eq!(owner.allocate().unwrap().index(), block.index()); } #[test] @@ -246,7 +246,7 @@ fn retired_block_can_be_reused_while_completion_keeps_file_claim() { assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); engine.retired(id, retired); engine.flush_test(); - assert_eq!(owner.allocate().unwrap(), block); + assert_eq!(owner.allocate().unwrap().index(), block.index()); drop(owner); assert_claimed(&path); let completion = results.recv_timeout(Duration::from_secs(1)).unwrap(); @@ -365,11 +365,12 @@ fn subregion_and_retained_clone_span_cancelled_physical_retirement() { assert_eq!(&bytes, b"late"); drop(retained); } - assert_eq!(owner.allocate().unwrap(), block); + let replacement = owner.allocate().unwrap(); + assert_eq!(replacement.index(), block.index()); assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); let mut bytes = [0; 4]; owner - .region(block, 12..16) + .region(replacement, 12..16) .unwrap() .read_at(&mut bytes, 0) .result @@ -410,12 +411,7 @@ fn named_timeout_retains_unlinked_charge_until_physical_retirement() { }, 4096, ); - let (request_id, results) = enqueue( - &mut engine, - request, - Direction::Write, - &[0x57; 4096], - ); + let (request_id, results) = enqueue(&mut engine, request, Direction::Write, &[0x57; 4096]); dispatch(&mut engine); drop(binding); owner.remove(parent, name()).unwrap(); diff --git a/rust/storage-io/src/tests.rs b/rust/storage-io/src/tests.rs index 45eb333bf6..6f63cd9c94 100644 --- a/rust/storage-io/src/tests.rs +++ b/rust/storage-io/src/tests.rs @@ -61,8 +61,8 @@ impl Drop for Directory { } } -fn index(value: u64) -> BlockIndex { - BlockIndex::new(value).unwrap() +fn id(index: u64) -> BlockId { + BlockId::new(index, 0).unwrap() } #[test] @@ -105,9 +105,10 @@ fn invalid_header_and_checksum_remain_distinct() { #[test] fn recovery_reads_before_marking_and_preserves_live_blocks() { let directory = Directory::new(); + let live = BlockId::new(2, 90).unwrap(); let owner = directory.open(4, false); owner - .region(index(2), 0..BLOCK) + .region(live, 0..BLOCK) .unwrap() .write_at(b"recovered", 17) .result @@ -115,14 +116,20 @@ fn recovery_reads_before_marking_and_preserves_live_blocks() { owner.sync().unwrap(); drop(owner); let mut reopened = directory.open(99, true); - let region = reopened.region(index(2), 17..26).unwrap(); + let region = reopened.region(live, 17..26).unwrap(); let mut bytes = [0; 9]; assert_eq!(region.read_at(&mut bytes, 0).bytes, 9); assert_eq!(&bytes, b"recovered"); - reopened.mark(&[index(2), index(2)]).unwrap(); + reopened.mark(&[live, live]).unwrap(); let ready = reopened.finish_marking().unwrap(); assert_eq!(ready.snapshot().capacity, BLOCK * 4); - assert_eq!(ready.allocate_many(10).unwrap(), [index(1), index(3)]); + let fresh = ready.allocate_many(10).unwrap(); + assert_eq!(indices(&fresh), [1, 3]); + assert_eq!(fresh[0].generation(), live.generation() + 1); + assert!(matches!( + ready.region(id(2), 17..26), + Err(BlockError::StaleBlock(2)) + )); assert!(matches!(ready.allocate(), Err(BlockError::Exhausted))); region.read_at(&mut bytes, 0).result.unwrap(); assert_eq!(&bytes, b"recovered"); @@ -181,13 +188,13 @@ fn direct_block_file_reopens_and_transfers_aligned_regions() { fn failed_marking_cannot_publish_partial_live_set() { let directory = Directory::new(); let mut owner = directory.open(4, false); - owner.mark(&[index(1)]).unwrap(); + owner.mark(&[id(1)]).unwrap(); assert!(matches!( - owner.mark(&[index(2), index(4)]), + owner.mark(&[id(2), id(4)]), Err(BlockError::InvalidBlock(4)) )); assert!(matches!( - owner.mark(&[index(3)]), + owner.mark(&[id(3)]), Err(BlockError::MarkingAborted) )); assert!(matches!( @@ -195,53 +202,93 @@ fn failed_marking_cannot_publish_partial_live_set() { Err(BlockError::MarkingAborted) )); let mut owner = directory.open(4, false); - owner.mark(&[index(1)]).unwrap(); + owner.mark(&[id(1)]).unwrap(); owner.abort_marking(); owner.restart_marking(); - owner.mark(&[index(2)]).unwrap(); + owner.mark(&[id(2)]).unwrap(); assert_eq!( - owner.finish_marking().unwrap().allocate_many(4).unwrap(), - [index(1), index(3)] + indices(&owner.finish_marking().unwrap().allocate_many(4).unwrap()), + [1, 3] ); } +#[test] +fn conflicting_recovery_identities_prevent_reuse() { + let directory = Directory::new(); + let mut owner = directory.open(2, false); + let live = BlockId::new(1, 70).unwrap(); + owner.mark(&[live]).unwrap(); + assert!(matches!( + owner.mark(&[id(1)]), + Err(BlockError::StaleBlock(1)) + )); + assert!(matches!( + owner.finish_marking(), + Err(BlockError::MarkingAborted) + )); +} + +#[test] +fn recovered_group_owns_blocks_across_startup_and_reader_lifetimes() { + let directory = Directory::new(); + let mut recovery = directory.open(2, false); + let id = BlockId::new(1, 70).unwrap(); + let durable = recovery.recover(&[data_member(id)]).unwrap(); + let reader = durable.clone(); + let ready = recovery.finish_marking().unwrap(); + assert!(matches!(ready.allocate(), Err(BlockError::Exhausted))); + drop(durable); + assert!(ready.region(id, 0..1).is_ok()); + drop(reader); + let replacement = ready.allocate().unwrap(); + assert_eq!(replacement.index(), id.index()); + assert_eq!(replacement.generation(), id.generation() + 1); + assert!(matches!(ready.region(id, 0..1), Err(BlockError::StaleBlock(1)))); +} + +fn data_member(id: BlockId) -> BlockMember { + BlockMember { id, kind: BlockKind::Data } +} + +fn indices(blocks: &[BlockId]) -> Vec { + blocks.iter().map(|block| block.index()).collect() +} + #[test] fn allocation_is_fifo_and_returns_short_batches() { let directory = Directory::new(); let owner = directory.open(4, false).finish_marking().unwrap(); assert_eq!(owner.allocate_many(0).unwrap(), []); - assert_eq!( - owner.allocate_many(20).unwrap(), - [index(1), index(2), index(3)] - ); - owner.release(index(2)).unwrap(); - owner.release(index(1)).unwrap(); + let allocated = owner.allocate_many(20).unwrap(); + assert_eq!(indices(&allocated), [1, 2, 3]); + owner.release(allocated[1]).unwrap(); + owner.release(allocated[0]).unwrap(); assert!(matches!( - owner.release(index(1)), + owner.release(allocated[0]), Err(BlockError::NotAllocated(1)) )); - assert_eq!(owner.allocate_many(20).unwrap(), [index(2), index(1)]); + assert_eq!(indices(&owner.allocate_many(20).unwrap()), [2, 1]); assert!(matches!( - owner.release(index(u32::MAX as u64 + 2)), + owner.release(id(u32::MAX as u64 + 2)), Err(BlockError::InvalidBlock(_)) )); - assert!(BlockIndex::new(0).is_err()); + assert!(BlockId::new(0, 0).is_err()); } #[test] fn recovery_lease_delays_reuse_when_marking_does_not_keep_block() { let directory = Directory::new(); let owner = directory.open(3, true); - let region = owner.region(index(1), 0..BLOCK).unwrap(); + let region = owner.region(id(1), 0..BLOCK).unwrap(); let retained = region.subregion(4..8).unwrap().clone(); let owner = owner.finish_marking().unwrap(); assert_eq!(owner.snapshot().pending_release_blocks, 1); - assert_eq!(owner.allocate().unwrap(), index(2)); + assert_eq!(owner.allocate().unwrap().index(), 2); assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); drop(region); assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); drop(retained); - assert_eq!(owner.allocate().unwrap(), index(1)); + assert_eq!(owner.allocate().unwrap().index(), 1); assert_eq!(owner.snapshot().pending_release_blocks, 0); } @@ -267,8 +314,18 @@ fn late_write_cannot_cross_release_and_reallocation() { worker.join().unwrap(); assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); drop(second); - assert_eq!(owner.allocate().unwrap(), block); - let next = owner.region(block, 0..BLOCK).unwrap(); + let replacement = owner.allocate().unwrap(); + assert_eq!(replacement.index(), block.index()); + assert_ne!(replacement.generation(), block.generation()); + assert!(matches!( + owner.region(block, 0..BLOCK), + Err(BlockError::StaleBlock(1)) + )); + assert!(matches!( + owner.release(block), + Err(BlockError::StaleBlock(1)) + )); + let next = owner.region(replacement, 0..BLOCK).unwrap(); #[cfg(any(target_os = "linux", target_os = "android"))] { let mut bytes = [0xff; 19]; @@ -411,17 +468,18 @@ fn block_reuse_waits_for_last_clone_or_subregion() { assert_eq!(owner.snapshot().pending_release_blocks, 1); assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); drop(last); - assert_eq!(owner.allocate().unwrap(), block); + let replacement = owner.allocate().unwrap(); + assert_eq!(replacement.index(), block.index()); assert_eq!(owner.snapshot().pending_release_blocks, 0); owner.reclaim_released(); assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); assert!(matches!( - owner.release(block).unwrap(), + owner.release(replacement).unwrap(), ReleaseOutcome::Reusable { reclamation_error: None } )); - assert_eq!(owner.allocate().unwrap(), block); + assert_eq!(owner.allocate().unwrap().index(), block.index()); assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); } @@ -430,7 +488,7 @@ fn region_outlives_owner_and_rejects_out_of_bounds_io() { let directory = Directory::new(); let owner = directory.open(3, false).finish_marking().unwrap(); let block = owner.allocate().unwrap(); - assert!(owner.region(index(u32::MAX as u64 + 2), 0..1).is_err()); + assert!(owner.region(id(u32::MAX as u64 + 2), 0..1).is_err()); assert!(owner.region(block, 1..BLOCK + 1).is_err()); let region = owner.region(block, 8..12).unwrap(); drop(owner); @@ -508,7 +566,10 @@ fn reopening_through_an_alias_waits_for_all_regions_to_retire() { .result .unwrap(); assert_eq!(&data, b"last write"); - assert_eq!(owner.finish_marking().unwrap().allocate().unwrap(), block); + assert_eq!( + owner.finish_marking().unwrap().allocate().unwrap().index(), + block.index() + ); } #[test] @@ -524,13 +585,11 @@ fn growth_preserves_free_order_and_data() { .unwrap(); owner.release(first).unwrap(); owner.grow(BLOCK * 6, SpaceBudget::default()).unwrap(); - assert_eq!( - owner.allocate_many(9).unwrap(), - [index(2), index(3), index(1), index(4), index(5)] - ); + let allocated = owner.allocate_many(9).unwrap(); + assert_eq!(indices(&allocated), [2, 3, 1, 4, 5]); let mut bytes = [0; 4]; owner - .region(first, 0..BLOCK) + .region(allocated[2], 0..BLOCK) .unwrap() .read_at(&mut bytes, 0) .result @@ -561,13 +620,11 @@ fn failed_growth_does_not_publish_capacity_and_retry_preserves_tail() { assert_eq!(owner.snapshot(), before); assert_eq!(fs::metadata(directory.path()).unwrap().len(), BLOCK * 5); owner.grow(BLOCK * 5, SpaceBudget::default()).unwrap(); - assert_eq!( - owner.allocate_many(9).unwrap(), - [index(1), index(2), index(3), index(4)] - ); + let allocated = owner.allocate_many(9).unwrap(); + assert_eq!(indices(&allocated), [1, 2, 3, 4]); let mut bytes = [0; 4]; owner - .region(index(4), 0..BLOCK) + .region(allocated[3], 0..BLOCK) .unwrap() .read_at(&mut bytes, 0) .result @@ -705,7 +762,7 @@ fn opening_valid_existing_file_never_extends_or_removes_it() { let directory = Directory::new(); let owner = directory.open(3, false); owner - .region(index(1), 0..BLOCK) + .region(id(1), 0..BLOCK) .unwrap() .write_at(b"live", 0) .result @@ -1079,7 +1136,6 @@ fn growth_policy(max_blocks: u64) -> GrowthPolicy { GrowthPolicy { max_bytes: BLOCK * max_blocks, next_bytes: 0, - usage_upper_percent: 90, } } @@ -1090,7 +1146,7 @@ fn allocation_grows_on_exhaustion_and_observes_changed_policy() { let first = owner .allocate_with_growth(growth_policy(2), SpaceBudget::default()) .unwrap(); - assert_eq!(first, index(1)); + assert_eq!(first.index(), 1); assert!(matches!( owner.allocate_with_growth(growth_policy(2), SpaceBudget::default()), Err(BlockError::Exhausted) @@ -1098,7 +1154,7 @@ fn allocation_grows_on_exhaustion_and_observes_changed_policy() { let second = owner .allocate_with_growth(growth_policy(3), SpaceBudget::default()) .unwrap(); - assert_eq!(second, index(2)); + assert_eq!(second.index(), 2); assert_eq!(owner.snapshot().capacity, BLOCK * 3); let before = owner.snapshot(); let mut unaligned_limit = growth_policy(3); @@ -1131,12 +1187,63 @@ fn allocation_reclaims_retired_lease_before_trying_growth() { assert_eq!( owner .allocate_with_growth(growth_policy(4), impossible_budget) - .unwrap(), - first + .unwrap() + .index(), + first.index() ); assert_eq!(owner.snapshot().capacity, BLOCK * 2); } +#[test] +fn published_group_and_inflight_read_keep_block_alive_after_writer_drops() { + let directory = Directory::new(); + let owner = directory.open(2, false).finish_marking().unwrap(); + let (id, writer) = owner + .allocate_owned(growth_policy(2), SpaceBudget::default()) + .unwrap(); + owner.region(id, 0..4).unwrap().write_at(b"keep", 0).result.unwrap(); + let published = owner.hold(&[data_member(id), data_member(id)]).unwrap(); + published.set_published(true); + assert_eq!(owner.snapshot().published_data_blocks, 1); + let reader = published.clone(); + drop(writer); + published.set_published(false); + drop(published); + assert_eq!(owner.snapshot().published_data_blocks, 0); + assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); + let read = owner.region(id, 0..4).unwrap(); + drop(reader); + assert!(matches!( + owner.check_usage(0, 2 * BLOCK, SpaceBudget::default(), 90), + Err(BlockError::Exhausted) + )); + assert!(matches!(owner.allocate(), Err(BlockError::Exhausted))); + let mut bytes = [0; 4]; + read.read_at(&mut bytes, 0).result.unwrap(); + assert_eq!(&bytes, b"keep"); + drop(read); + assert_eq!( + owner.check_usage(0, 2 * BLOCK, SpaceBudget::default(), 90).unwrap(), + 50 + ); + let next = owner.allocate().unwrap(); + assert_eq!(next.index(), id.index()); + assert_ne!(next, id); +} + +#[test] +fn failed_group_hold_does_not_keep_earlier_blocks() { + let directory = Directory::new(); + let owner = directory.open(3, false).finish_marking().unwrap(); + let (first, writer) = owner + .allocate_owned(growth_policy(3), SpaceBudget::default()) + .unwrap(); + let later = BlockId::new(2, first.generation()).unwrap(); + assert!(matches!(owner.hold(&[data_member(first), data_member(later)]), Err(BlockError::NotAllocated(2)))); + drop(writer); + assert_eq!(indices(&owner.allocate_many(2).unwrap()), [2, 1]); +} + #[test] fn failed_allocation_growth_preserves_capacity_and_allocated_data() { let directory = Directory::new(); @@ -1185,7 +1292,7 @@ fn concurrent_allocations_grow_without_duplicate_blocks_or_exceeding_limit() { .collect(); tasks .into_iter() - .map(|task| task.join().unwrap().get()) + .map(|task| task.join().unwrap().index()) .collect::>() }); allocated.sort_unstable(); @@ -1240,26 +1347,6 @@ fn manual_resize_rounds_preserves_data_and_does_not_require_auto_growth() { assert_eq!(directory.open(2, false).snapshot().capacity, BLOCK * 5); } -#[test] -fn periodic_growth_leaves_healthy_capacity_unchanged_then_refills_low_space() { - let directory = Directory::new(); - let owner = directory.open(20, false).finish_marking().unwrap(); - owner - .extend_if_needed(growth_policy(40), SpaceBudget::default()) - .unwrap(); - assert_eq!(owner.snapshot().capacity, BLOCK * 20); - let allocated = owner.allocate_many(12).unwrap(); - assert_eq!(allocated.len(), 12); - owner - .extend_if_needed(growth_policy(40), SpaceBudget::default()) - .unwrap(); - assert_eq!(owner.snapshot().capacity, BLOCK * 40); - assert_eq!(owner.snapshot().free_blocks, 27); - for block in allocated { - assert!(owner.region(block, 0..BLOCK).is_ok()); - } -} - #[test] fn capacity_admission_preserves_usage_limit_and_header_accounting() { let directory = Directory::new(); diff --git a/src/observer/ob_data_file_stats.h b/src/observer/ob_data_file_stats.h new file mode 100644 index 0000000000..45e3239729 --- /dev/null +++ b/src/observer/ob_data_file_stats.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * 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. + */ + +#pragma once + +#include +#include "rust/config.h" +#include "share/io_request.h" + +namespace oceanbase::observer +{ + +inline storage_io::BlockStats read_data_file_stats(const storage_io::BlockOwner &block_file) +{ + storage_io::BlockStats stats{}; + return common::OB_SUCCESS == common::convert_block_status(block_file.block_stats(stats)) + ? stats : storage_io::BlockStats{}; +} + +inline int64_t maximum_data_file_bytes(const storage_io::BlockOwner &block_file, + const storage_io::BlockStats &stats, + const int64_t reserved_bytes) +{ + uint64_t maximum = 0; + const int64_t configured = std::max(int64_t{0}, config::datafile_maxsize()); + if (reserved_bytes < 0 || common::OB_SUCCESS != common::convert_block_status( + block_file.maximum_block_capacity(configured, reserved_bytes, maximum))) { + maximum = stats.capacity; + } + return static_cast(maximum); +} + +inline int64_t used_data_file_bytes(const storage_io::BlockStats &stats) +{ + return stats.ready + ? (stats.total_blocks - 1 - stats.free_blocks - stats.pending_release_blocks) * stats.block_size : 0; +} + +} diff --git a/src/observer/ob_server.cpp b/src/observer/ob_server.cpp index 324592c98e..3575ac1046 100644 --- a/src/observer/ob_server.cpp +++ b/src/observer/ob_server.cpp @@ -67,7 +67,7 @@ namespace oceanbase { namespace observer { common::ObILobReadService * ObServer: #include "storage/tx/ob_ts_mgr.h" #include "storage/ob_file_system_router.h" #include "sql/engine/px/ob_px_target_monitor.h" -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" #include "storage/ob_tablet_autoincrement_service.h" #include "storage/tx_storage/ob_memstore_freezer.h" #include "storage/memtable/ob_lock_wait_mgr.h" @@ -136,6 +136,11 @@ class ObServer::StandbyHostAdapter final : public standby::IStandbyHost public: explicit StandbyHostAdapter(ObServer &server) : server_(server) {} + int check_restore_disk_space(int64_t required_size) const override + { + return blocksstable::check_block_space(*server_.block_file_, required_size); + } + int load_log_restore_source( common::ObIAllocator &allocator, common::ObString &source) const override @@ -670,7 +675,7 @@ ObServer::ObServer() stop_(true), need_bootstrap_(false), has_stopped_(true), has_destroy_(false), net_frame_(gctx_), sql_proxy_(), - reload_config_(gctx_), config_mgr_(reload_config_), + reload_config_(gctx_, *block_file_), config_mgr_(reload_config_), timezone_mgr_(omt::ObTimezoneMgr::get_instance()), schema_service_sql_impl_(NULL), schema_service_(share::schema::ObMultiVersionSchemaService::get_instance()), @@ -685,9 +690,10 @@ ObServer::ObServer() session_mgr_(), standby_host_(nullptr), standby_module_(nullptr), - ob_service_(gctx_, *this, local_store_), + ob_service_(gctx_, *this, local_store_, *block_file_), debug_sync_broadcaster_(ob_service_), - server_runtime_controller_(), vt_data_service_(local_management_service_, self_addr_), + server_runtime_controller_(), + vt_data_service_(local_management_service_, self_addr_, ob_service_, *block_file_), start_time_(ObTimeUtility::current_time()), warm_up_start_time_(0), scramble_rand_(), @@ -898,7 +904,7 @@ int ObServer::init(const ObServerOptions &opts) LOG_ERROR("init ObLogAllocatorMgr failed", KR(ret)); } else if (OB_FAIL(startup_accel_handler_.init())) { LOG_ERROR("init server startup task handler failed", KR(ret)); - } else if (OB_FAIL(STORAGE_META_SERVICE.init(server_runtime_controller_, local_store_))) { + } else if (OB_FAIL(STORAGE_META_SERVICE.init(server_runtime_controller_, local_store_, *block_file_))) { LOG_ERROR("init server storage meta handler failed", KR(ret)); } else if (OB_FAIL(init_server_runtime())) { LOG_ERROR("init server runtime failed", KR(ret)); @@ -1114,10 +1120,6 @@ void ObServer::destroy() ObQueryRetryCtrl::destroy(); FLOG_INFO("query retry ctrl destroy"); - FLOG_INFO("begin to destroy storage object mgr"); - OB_STORAGE_OBJECT_MGR.destroy(); - FLOG_INFO("storage object mgr destroyed"); - FLOG_INFO("begin to destroy server startup task handler"); startup_accel_handler_.destroy(); FLOG_INFO("server startup task handler destroyed"); @@ -1147,7 +1149,7 @@ void ObServer::destroy() deinit_fts(); - const int data_close_error = OB_SERVER_BLOCK_MGR.close_file(); + const int data_close_error = convert_storage_error(block_file_->close_blocks()); if (data_close_error != OB_SUCCESS) { LOG_ERROR_RET(data_close_error, "data file close failed"); } @@ -1215,10 +1217,10 @@ int ObServer::start() if (OB_FAIL(ret)) { } else if (OB_FAIL(STORAGE_META_SERVICE.get_reserved_size(metadata_reserved_size))) { LOG_WARN("fail to get local metadata reserved size", KR(ret), K(metadata_reserved_size)); - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.start(metadata_reserved_size))) { - LOG_ERROR("start storage object mgr fail", KR(ret), K(metadata_reserved_size)); + } else if (OB_FAIL(start_block_file(metadata_reserved_size))) { + LOG_ERROR("failed to open block file", KR(ret), K(metadata_reserved_size)); } else { - FLOG_INFO("success to start storage object manager"); + FLOG_INFO("block file opened"); } if (FAILEDx(standby_module_->prepare_storage_replay())) { LOG_ERROR("fail to restore server role before runtime and storage replay", KR(ret)); @@ -1566,11 +1568,6 @@ int ObServer::stop() net_frame_.sql_nio_stop(); FLOG_INFO("sql nio stopped"); - - FLOG_INFO("begin to stop storage object mgr"); - OB_STORAGE_OBJECT_MGR.stop(); - FLOG_INFO("storage object mgr stopped"); - FLOG_INFO("begin to stop timer monitor"); ObTimerMonitor::get_instance().stop(); FLOG_INFO("timer monitor stopped"); @@ -2011,7 +2008,7 @@ int ObServer::validate_io_threads() const int64_t data_threads = config::sync_io_thread_count(); const int64_t log_threads = config::disk_io_thread_count(); if (data_threads < 0 || log_threads < 0) { return OB_INVALID_ARGUMENT; } - return OB_SERVER_BLOCK_MGR.validate_io_threads(data_threads); + return convert_storage_error(block_file_->validate_block_workers(data_threads)); } int ObServer::configure_io(int64_t server_memory_bytes, int64_t callback_threads) @@ -2043,7 +2040,6 @@ int ObServer::init_io() } else { storage_env_.data_dir_ = OB_FILE_SYSTEM_ROUTER.get_data_dir(); storage_env_.sstable_dir_ = OB_FILE_SYSTEM_ROUTER.get_sstable_dir(); - storage_env_.default_block_size_ = OB_DEFAULT_MACRO_BLOCK_SIZE; // 2MB // log storage_env_.clog_dir_ = OB_FILE_SYSTEM_ROUTER.get_clog_dir(); @@ -2078,9 +2074,12 @@ int ObServer::init_io() } if (OB_SUCC(ret)) { - ret = OB_SERVER_BLOCK_MGR.prepare_file(*io_service_, - storage_env_.data_dir_, storage_env_.sstable_dir_, storage_env_.default_block_size_, - storage_env_.data_disk_size_, storage_env_.data_disk_percentage_, sync_threads, max_io_depth); + storage_io::ExecutionOptions execution{}; + execution.worker_threads = sync_threads; + execution.max_depth = max_io_depth; + const char *directory = storage_env_.sstable_dir_; + ret = convert_storage_error(block_file_->prepare_blocks(*io_service_, + {reinterpret_cast(directory), STRLEN(directory)}, execution)); } } } @@ -2088,6 +2087,69 @@ int ObServer::init_io() return ret; } +int ObServer::start_block_file(const int64_t reserved_size) +{ + int ret = OB_SUCCESS; + LOG_DBA_INFO_V2(OB_SERVER_BLOCK_MANAGER_START_BEGIN, + DBA_STEP_INC_INFO(server_start), + "block file open begin."); + + char path[common::OB_MAX_FILE_NAME_LENGTH]; + if (reserved_size < 0) { + ret = OB_INVALID_ARGUMENT; + } else if (OB_FAIL(databuff_printf(path, sizeof(path), "%s/%s/%s", + storage_env_.data_dir_, BLOCK_SSTBALE_DIR_NAME, BLOCK_SSTBALE_FILE_NAME))) { + } else { + storage_io::BlockOptions options{}; + options.block_size = OB_DEFAULT_MACRO_BLOCK_SIZE; + options.initial_size = storage_env_.data_disk_size_; + options.initial_percentage = storage_env_.data_disk_percentage_; + options.reserved_bytes = reserved_size; + options.punch_holes = config::_enable_block_file_punch_hole(); + auto opened = block_file_->open_blocks( + {reinterpret_cast(path), STRLEN(path)}, options); + ret = convert_block_status(opened.status); + if (ret != OB_SUCCESS) { + LOG_WARN("data file open failed", K(ret), K(path), + "native_error", opened.primary_error.native_code, "error", opened.primary_error.message.c_str()); + } + auto &summary = opened.directory_summary; + if (summary.count != 0) { + LOG_WARN("directory durability unconfirmed; only first failure detail retained", K(ret), + "failed_flush_count", summary.count, "count_is_lower_bound", summary.count == UINT64_MAX, + "first_path", ObString(static_cast(summary.first_path.size()), + reinterpret_cast(summary.first_path.data())), + "native_error", summary.first_error.native_code, "error", summary.first_error.message.c_str()); + } + if (opened.sync.stage != file_io::SyncStage::Complete) { + LOG_WARN("data file creation directory sync failed", K(ret), K(path), + "stage", static_cast(opened.sync.stage), "native_error", opened.sync.primary.native_code, + "error", opened.sync.primary.message.c_str(), "close_error", opened.sync.close.native_code); + } + if (opened.cleanup_close.domain != file_io::ErrorDomain::None + || opened.cleanup_remove.domain != file_io::ErrorDomain::None + || opened.cleanup_sync.stage != file_io::SyncStage::Complete) { + LOG_WARN("data file creation cleanup failed", K(ret), K(path), + "close_error", opened.cleanup_close.native_code, "remove_error", opened.cleanup_remove.native_code, + "sync_error", opened.cleanup_sync.primary.native_code, "sync_close_error", opened.cleanup_sync.close.native_code); + } + } + + if (ret != OB_SUCCESS) { + LOG_DBA_ERROR_V2(OB_SERVER_BLOCK_MANAGER_START_FAIL, ret, + DBA_STEP_INC_INFO(server_start), + "block file open failed. ", + "you may find solutions in previous error logs or seek " + "help from official technicians."); + } else { + LOG_DBA_INFO_V2(OB_SERVER_BLOCK_MANAGER_START_SUCCESS, + DBA_STEP_INC_INFO(server_start), + "block file open succeeded."); + } + + return ret; +} + int ObServer::init_interrupt() { int ret = OB_SUCCESS; @@ -2435,8 +2497,6 @@ int ObServer::init_storage() } if (OB_SUCC(ret)) { if (OB_FAIL(OB_STORE_CACHE.init(storage_env_.bf_cache_miss_count_threshold_))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.init( - storage_env_.default_block_size_))) { } else if (OB_FAIL(disk_usage_report_task_.init(sql_proxy_))) { } } diff --git a/src/observer/ob_server.h b/src/observer/ob_server.h index 801bbdaa0b..7f6dccf085 100644 --- a/src/observer/ob_server.h +++ b/src/observer/ob_server.h @@ -356,6 +356,7 @@ class ObServer : public share::ObIMemstoreRuntime, int init_server_runtime(); int init_sql_proxy(); int init_io(); + int start_block_file(int64_t reserved_size); int init_schema(); int init_autoincrement_service(); int init_tablet_autoincrement_service(); @@ -418,6 +419,8 @@ class ObServer : public share::ObIMemstoreRuntime, common::ObMySQLProxy sql_proxy_; common::ObMySQLProxy ddl_sql_proxy_; + rust::Box block_file_ = storage_io::new_block_owner(); + // The OceanBase configuration relating to. ObServerReloadConfig reload_config_; common::ObConfigManager config_mgr_; diff --git a/src/observer/ob_server_reload_config.cpp b/src/observer/ob_server_reload_config.cpp index b0f2c7ad49..46fbe502c6 100644 --- a/src/observer/ob_server_reload_config.cpp +++ b/src/observer/ob_server_reload_config.cpp @@ -26,6 +26,7 @@ #include "storage/allocator/ob_shared_memory_allocator_mgr.h" #include "storage/compaction/ob_tablet_scheduler.h" #include "storage/meta_store/storage_meta_service.h" +#include "share/io_request.h" #include "storage/tmp_file/tmp_file_service.h" #include @@ -36,8 +37,9 @@ using namespace oceanbase::observer; using namespace oceanbase::storage; using namespace oceanbase::share; -ObServerReloadConfig::ObServerReloadConfig(ObGlobalContext &gctx) - : gctx_(gctx) +ObServerReloadConfig::ObServerReloadConfig( + ObGlobalContext &gctx, const storage_io::BlockOwner &block_file) + : gctx_(gctx), block_file_(block_file) { } @@ -98,8 +100,11 @@ int ObServerReloadConfig::operator()() if (OB_TMP_FAIL(ObServerUtils::get_data_disk_info_in_config(data_disk_size, data_disk_percentage))) { } else if (OB_TMP_FAIL(STORAGE_META_SERVICE.get_reserved_size(reserved_size))) { - } else if (OB_TMP_FAIL(OB_SERVER_BLOCK_MGR.resize_file( - data_disk_size, data_disk_percentage, reserved_size))) { + } else if (data_disk_size < 0 || data_disk_percentage < 0 || data_disk_percentage >= 100 + || reserved_size < 0) { + tmp_ret = OB_INVALID_ARGUMENT; + } else if (OB_TMP_FAIL(convert_block_status(block_file_.resize_blocks( + data_disk_size, data_disk_percentage, reserved_size)))) { } { diff --git a/src/observer/ob_server_reload_config.h b/src/observer/ob_server_reload_config.h index f19e699b93..873b26e283 100644 --- a/src/observer/ob_server_reload_config.h +++ b/src/observer/ob_server_reload_config.h @@ -21,6 +21,8 @@ #include "share/config/ob_server_config.h" #include "share/ob_server_struct.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace observer @@ -30,7 +32,7 @@ class ObServerReloadConfig : public common::ObReloadConfig { public: - explicit ObServerReloadConfig(share::ObGlobalContext &gctx); + ObServerReloadConfig(share::ObGlobalContext &gctx, const storage_io::BlockOwner &block_file); virtual ~ObServerReloadConfig(); int operator()(); @@ -39,6 +41,7 @@ class ObServerReloadConfig void reload_memstore_freezer_config_(); private: ObGlobalContext &gctx_; + const storage_io::BlockOwner &block_file_; }; } // end of namespace observer diff --git a/src/observer/ob_service.cpp b/src/observer/ob_service.cpp index 12609c1fc5..356a3b8725 100644 --- a/src/observer/ob_service.cpp +++ b/src/observer/ob_service.cpp @@ -18,6 +18,7 @@ +#include "observer/ob_data_file_stats.h" #include "rust/config.h" #include "lib/stat/ob_diagnostic_info_guard.h" #include "lib/time/ob_time_utility.h" @@ -151,11 +152,13 @@ int TelemetryTask::report() ObService::ObService( const ObGlobalContext &gctx, query::ObIChangeStreamService &change_stream_service, - share::LocalStore &store) + share::LocalStore &store, + const storage_io::BlockOwner &block_file) : inited_(false), stopped_(false), schema_updater_(), gctx_(gctx), + block_file_(block_file), change_stream_service_(change_stream_service), schema_release_task_(), telemetry_task_(store) @@ -718,10 +721,9 @@ int ObService::get_server_resource_info(share::ObServerResourceInfo &resource_in resource_info.report_log_disk_assigned_ = svr_res_assigned.log_disk_size_; // data_disk { - resource_info.data_disk_total_ - = OB_STORAGE_OBJECT_MGR.get_max_macro_block_count(reserved_size) * OB_STORAGE_OBJECT_MGR.get_macro_block_size(); - resource_info.data_disk_in_use_ - = OB_STORAGE_OBJECT_MGR.get_used_macro_block_count() * OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + const auto stats = read_data_file_stats(block_file_); + resource_info.data_disk_total_ = maximum_data_file_bytes(block_file_, stats, reserved_size); + resource_info.data_disk_in_use_ = used_data_file_bytes(stats); if (auto *tmp_files = share::server_service(); OB_NOT_NULL(tmp_files)) { int64_t tmp_data_bytes = 0; int64_t tmp_occupied_bytes = 0; diff --git a/src/observer/ob_service.h b/src/observer/ob_service.h index cb813e4a72..e3bbad6c65 100644 --- a/src/observer/ob_service.h +++ b/src/observer/ob_service.h @@ -31,6 +31,8 @@ #include "query/command/ob_local_command_service.h" #include "rootserver/ob_rootserver_local_runtime.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace share @@ -83,7 +85,8 @@ class ObService : public rootserver::ObIRootserverLocalRuntime, ObService( const share::ObGlobalContext &gctx, query::ObIChangeStreamService &change_stream_service, - share::LocalStore &store); + share::LocalStore &store, + const storage_io::BlockOwner &block_file); virtual ~ObService(); int init(common::ObMySQLProxy &sql_proxy); @@ -170,6 +173,7 @@ class ObService : public rootserver::ObIRootserverLocalRuntime, //lease const share::ObGlobalContext &gctx_; + const storage_io::BlockOwner &block_file_; query::ObIChangeStreamService &change_stream_service_; ObSchemaReleaseTimeTask schema_release_task_; TelemetryTask telemetry_task_; diff --git a/src/observer/omt/ob_server_runtime_controller.cpp b/src/observer/omt/ob_server_runtime_controller.cpp index d721e0da47..28b27f4b5b 100644 --- a/src/observer/omt/ob_server_runtime_controller.cpp +++ b/src/observer/omt/ob_server_runtime_controller.cpp @@ -1030,7 +1030,7 @@ int ObServer::obs_construct_modules() int ret = OB_SUCCESS; if (OB_SUCC(ret) && OB_FAIL(server_module_new_default(mods_shared_timer_))) { SERVER_LOG(WARN, "mods_shared_timer_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(server_module_new_default(mods_shared_macro_block_mgr_))) { SERVER_LOG(WARN, "mods_shared_macro_block_mgr_ fail", KR(ret)); } - if (OB_SUCC(ret) && OB_FAIL(ObStorageMetaMemMgr::server_module_new(mods_storage_meta_mem_mgr_))) { SERVER_LOG(WARN, "mods_storage_meta_mem_mgr_ fail", KR(ret)); } + if (OB_SUCC(ret) && OB_FAIL(ObStorageMetaMemMgr::server_module_new(*block_file_, mods_storage_meta_mem_mgr_))) { SERVER_LOG(WARN, "mods_storage_meta_mem_mgr_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(server_module_new_default(mods_mds_service_))) { SERVER_LOG(WARN, "mods_mds_service_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(server_module_new_default(mods_shared_mem_alloc_mgr_))) { SERVER_LOG(WARN, "mods_shared_mem_alloc_mgr_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(server_module_new_default(mods_trans_service_))) { SERVER_LOG(WARN, "mods_trans_service_ fail", KR(ret)); } @@ -1210,7 +1210,7 @@ int ObServer::obs_init_modules() { int ret = OB_SUCCESS; if (OB_SUCC(ret) && OB_FAIL(ObSharedTimer::server_module_init(mods_shared_timer_))) { SERVER_LOG(WARN, "mods_shared_timer_ fail", KR(ret)); } - if (OB_SUCC(ret) && OB_FAIL(server_module_init_default(mods_shared_macro_block_mgr_))) { SERVER_LOG(WARN, "mods_shared_macro_block_mgr_ fail", KR(ret)); } + if (OB_SUCC(ret) && OB_FAIL(mods_shared_macro_block_mgr_->init(*block_file_))) { SERVER_LOG(WARN, "mods_shared_macro_block_mgr_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(server_module_init_default(mods_storage_meta_mem_mgr_))) { SERVER_LOG(WARN, "mods_storage_meta_mem_mgr_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(storage::mds::ObMdsService::server_module_init(mods_mds_service_))) { SERVER_LOG(WARN, "mods_mds_service_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(share::ObSharedMemAllocMgr::server_module_init(mods_shared_mem_alloc_mgr_))) { SERVER_LOG(WARN, "mods_shared_mem_alloc_mgr_ fail", KR(ret)); } @@ -1223,8 +1223,8 @@ int ObServer::obs_init_modules() mods_log_service_, mods_log_storage_adapter_, log_block_mgr_))) { SERVER_LOG(WARN, "mods_log_service_ fail", KR(ret)); } - if (OB_SUCC(ret) && OB_FAIL(ObLSService::server_module_init(mods_ls_service_))) { SERVER_LOG(WARN, "mods_ls_service_ fail", KR(ret)); } - if (OB_SUCC(ret) && OB_FAIL(ObLocalStorageMetaService::server_module_init(mods_local_storage_meta_service_))) { SERVER_LOG(WARN, "mods_local_storage_meta_service_ fail", KR(ret)); } + if (OB_SUCC(ret) && OB_FAIL(mods_ls_service_->init(*block_file_))) { SERVER_LOG(WARN, "mods_ls_service_ fail", KR(ret)); } + if (OB_SUCC(ret) && OB_FAIL(ObLocalStorageMetaService::server_module_init(mods_local_storage_meta_service_, *block_file_))) { SERVER_LOG(WARN, "mods_local_storage_meta_service_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(tmp_file::ObTmpFileManager::server_module_init(mods_tmp_file_manager_))) { SERVER_LOG(WARN, "mods_tmp_file_manager_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(compaction::ObCompactionProgressMgr::server_module_init(mods_compaction_progress_mgr_))) { SERVER_LOG(WARN, "mods_compaction_progress_mgr_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(compaction::ObServerCompactionEventHistory::server_module_init(mods_server_compaction_event_history_))) { SERVER_LOG(WARN, "mods_server_compaction_event_history_ fail", KR(ret)); } @@ -1277,15 +1277,15 @@ int ObServer::obs_init_modules() if (OB_SUCC(ret) && OB_FAIL(ObMemstoreFreezer::server_module_init(mods_memstore_freezer_))) { SERVER_LOG(WARN, "mods_memstore_freezer_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(ObCheckPointService::server_module_init(mods_check_point_service_))) { SERVER_LOG(WARN, "mods_check_point_service_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(ObTabletGCService::server_module_init(mods_tablet_gc_service_))) { SERVER_LOG(WARN, "mods_tablet_gc_service_ fail", KR(ret)); } - if (OB_SUCC(ret) && OB_FAIL(compaction::ObTabletScheduler::server_module_init(mods_tablet_scheduler_))) { SERVER_LOG(WARN, "mods_tablet_scheduler_ fail", KR(ret)); } + if (OB_SUCC(ret) && OB_FAIL(mods_tablet_scheduler_->init(*block_file_))) { SERVER_LOG(WARN, "mods_tablet_scheduler_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(compaction::ObMediumChecker::server_module_init(mods_medium_checker_))) { SERVER_LOG(WARN, "mods_medium_checker_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(storage::ObCompactionMemPool::server_module_init(mods_compaction_mem_pool_))) { SERVER_LOG(WARN, "mods_compaction_mem_pool_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(server_module_init_default(mods_ddl_merge_bucket_lock_))) { SERVER_LOG(WARN, "mods_ddl_merge_bucket_lock_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(ObDagScheduler::server_module_init(mods_dag_scheduler_))) { SERVER_LOG(WARN, "mods_dag_scheduler_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(ObFreezeInfoMgr::server_module_init(mods_freeze_info_mgr_))) { SERVER_LOG(WARN, "mods_freeze_info_mgr_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(ObTxLoopWorker::server_module_init(mods_tx_loop_worker_))) { SERVER_LOG(WARN, "mods_tx_loop_worker_ fail", KR(ret)); } - if (OB_SUCC(ret) && OB_FAIL(ObAccessService::server_module_init(mods_access_service_))) { SERVER_LOG(WARN, "mods_access_service_ fail", KR(ret)); } - if (OB_SUCC(ret) && OB_FAIL(ObMultiVersionGarbageCollector::server_module_init(mods_multi_version_garbage_collector_))) { SERVER_LOG(WARN, "mods_multi_version_garbage_collector_ fail", KR(ret)); } + if (OB_SUCC(ret) && OB_FAIL(mods_access_service_->init(mods_ls_service_, *block_file_))) { SERVER_LOG(WARN, "mods_access_service_ fail", KR(ret)); } + if (OB_SUCC(ret) && OB_FAIL(mods_multi_version_garbage_collector_->init(*block_file_))) { SERVER_LOG(WARN, "mods_multi_version_garbage_collector_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(ObEmptyReadBucket::server_module_init(mods_empty_read_bucket_))) { SERVER_LOG(WARN, "mods_empty_read_bucket_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(rootserver::ObDBMSSchedService::server_module_init(mods_dbms_sched_service_))) { SERVER_LOG(WARN, "mods_dbms_sched_service_ fail", KR(ret)); } if (OB_SUCC(ret) && OB_FAIL(ObOptStatMonitorManager::server_module_init(mods_opt_stat_monitor_manager_))) { SERVER_LOG(WARN, "mods_opt_stat_monitor_manager_ fail", KR(ret)); } diff --git a/src/observer/virtual_table/ob_all_disk_stat.cpp b/src/observer/virtual_table/ob_all_disk_stat.cpp index 5a3eaf4558..7005ef512b 100644 --- a/src/observer/virtual_table/ob_all_disk_stat.cpp +++ b/src/observer/virtual_table/ob_all_disk_stat.cpp @@ -17,9 +17,7 @@ #include "observer/virtual_table/ob_all_disk_stat.h" #include "storage/meta_store/storage_meta_service.h" -#include "storage/blocksstable/ob_object_manager.h" - -using namespace oceanbase::blocksstable; +#include "observer/ob_data_file_stats.h" using namespace oceanbase::common; namespace oceanbase @@ -27,8 +25,9 @@ namespace oceanbase namespace observer { using namespace storage; -ObInfoSchemaDiskStatTable::ObInfoSchemaDiskStatTable() +ObInfoSchemaDiskStatTable::ObInfoSchemaDiskStatTable(const storage_io::BlockOwner &block_file) : ObVirtualTableScannerIterator(), + block_file_(block_file), addr_(NULL), ipstr_(), port_(0), @@ -84,6 +83,7 @@ int ObInfoSchemaDiskStatTable::inner_get_next_row(ObNewRow *&row) } if (OB_SUCC(ret)) { + const auto stats = read_data_file_stats(block_file_); for (int64_t cell_idx = 0; OB_SUCC(ret) && cell_idx < col_count; ++cell_idx) { uint64_t col_id = output_column_ids_.at(cell_idx); switch(col_id) { @@ -91,20 +91,20 @@ int ObInfoSchemaDiskStatTable::inner_get_next_row(ObNewRow *&row) int64_t reserved_size = 0; if (OB_FAIL(STORAGE_META_SERVICE.get_reserved_size(reserved_size))) { } else { - cells[cell_idx].set_int(OB_STORAGE_OBJECT_MGR.get_max_macro_block_count(reserved_size) *OB_STORAGE_OBJECT_MGR.get_macro_block_size()); + cells[cell_idx].set_int(maximum_data_file_bytes(block_file_, stats, reserved_size)); } break; } case ALLOCATED_SIZE: { - cells[cell_idx].set_int(OB_STORAGE_OBJECT_MGR.get_total_macro_block_count() *OB_STORAGE_OBJECT_MGR.get_macro_block_size()); + cells[cell_idx].set_int(stats.capacity); break; } case USED_SIZE: { - cells[cell_idx].set_int(OB_STORAGE_OBJECT_MGR.get_used_macro_block_count() *OB_STORAGE_OBJECT_MGR.get_macro_block_size()); + cells[cell_idx].set_int(used_data_file_bytes(stats)); break; } case FREE_SIZE: { - cells[cell_idx].set_int(OB_STORAGE_OBJECT_MGR.get_free_macro_block_count() *OB_STORAGE_OBJECT_MGR.get_macro_block_size()); + cells[cell_idx].set_int(stats.free_blocks * stats.block_size); break; } default: { diff --git a/src/observer/virtual_table/ob_all_disk_stat.h b/src/observer/virtual_table/ob_all_disk_stat.h index 0361de8b51..a8a917f010 100644 --- a/src/observer/virtual_table/ob_all_disk_stat.h +++ b/src/observer/virtual_table/ob_all_disk_stat.h @@ -20,6 +20,8 @@ #include "observer/virtual_table/ob_virtual_table_scanner_iterator.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace common @@ -33,7 +35,7 @@ namespace observer class ObInfoSchemaDiskStatTable : public common::ObVirtualTableScannerIterator { public: - ObInfoSchemaDiskStatTable(); + explicit ObInfoSchemaDiskStatTable(const storage_io::BlockOwner &block_file); virtual ~ObInfoSchemaDiskStatTable(); virtual int inner_get_next_row(common::ObNewRow *&row); virtual void reset(); @@ -48,6 +50,7 @@ class ObInfoSchemaDiskStatTable : public common::ObVirtualTableScannerIterator FREE_SIZE, ALLOCATED_SIZE }; + const storage_io::BlockOwner &block_file_; common::ObAddr *addr_; common::ObString ipstr_; int32_t port_; diff --git a/src/observer/virtual_table/ob_all_virtual_bad_block_table.cpp b/src/observer/virtual_table/ob_all_virtual_bad_block_table.cpp index a3c63b6b81..37742414bf 100644 --- a/src/observer/virtual_table/ob_all_virtual_bad_block_table.cpp +++ b/src/observer/virtual_table/ob_all_virtual_bad_block_table.cpp @@ -101,13 +101,13 @@ void ObVirtualBadBlockTable::reset() MEMSET(ip_buf_, 0, sizeof(ip_buf_)); } -int ObVirtualBadBlockTable::init(const common::ObAddr &addr) +int ObVirtualBadBlockTable::init(const common::ObAddr &addr, storage_io::BlockOwner &block_file) { int ret = OB_SUCCESS; if (!addr.is_valid()) { ret = OB_INVALID_ARGUMENT; SERVER_LOG(WARN, "Invalid argument, ", K(ret), K(addr)); - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.get_bad_block_infos(bad_block_infos_))) { + } else if (OB_FAIL(blocksstable::collect_bad_block_infos(block_file, bad_block_infos_))) { } else { addr_ = addr; MEMSET(ip_buf_, 0, sizeof(ip_buf_)); diff --git a/src/observer/virtual_table/ob_all_virtual_bad_block_table.h b/src/observer/virtual_table/ob_all_virtual_bad_block_table.h index 730a6788ff..a47c3e068d 100644 --- a/src/observer/virtual_table/ob_all_virtual_bad_block_table.h +++ b/src/observer/virtual_table/ob_all_virtual_bad_block_table.h @@ -17,11 +17,15 @@ #ifndef OB_ALL_VIRTUAL_BAD_BLOCK_TABLE_H #define OB_ALL_VIRTUAL_BAD_BLOCK_TABLE_H -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" +#include "storage/blocksstable/ob_block_sstable_struct.h" #include "observer/virtual_table/ob_virtual_table_scanner_iterator.h" #include "sql/ob_scanner.h" #include "common/row/ob_row.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace observer @@ -34,7 +38,7 @@ class ObVirtualBadBlockTable : public ObVirtualTableScannerIterator virtual ~ObVirtualBadBlockTable(); virtual int inner_get_next_row(common::ObNewRow *&row) override; virtual void reset() override; - int init(const common::ObAddr &addr); + int init(const common::ObAddr &addr, storage_io::BlockOwner &block_file); private: enum BAD_BLOCK_COLUMN { diff --git a/src/observer/virtual_table/ob_all_virtual_macro_block_marker_status.cpp b/src/observer/virtual_table/ob_all_virtual_macro_block_marker_status.cpp index 5d65efe187..be226de072 100644 --- a/src/observer/virtual_table/ob_all_virtual_macro_block_marker_status.cpp +++ b/src/observer/virtual_table/ob_all_virtual_macro_block_marker_status.cpp @@ -16,6 +16,7 @@ #include "ob_all_virtual_macro_block_marker_status.h" #include "observer/ob_server.h" +#include "share/io_request.h" namespace oceanbase { @@ -36,17 +37,29 @@ ObAllVirtualMacroBlockMarkerStatus::~ObAllVirtualMacroBlockMarkerStatus() { } -int ObAllVirtualMacroBlockMarkerStatus::init ( - const blocksstable::ObMacroBlockMarkerStatus &marker_status) +int ObAllVirtualMacroBlockMarkerStatus::init(const storage_io::BlockOwner &block_file) { int ret = OB_SUCCESS; - + storage_io::BlockStats stats{}; if (start_to_read_) { ret = OB_INIT_TWICE; SERVER_LOG(WARN, "cannot init twice", K(ret)); + } else if (OB_FAIL(convert_block_status(block_file.block_stats(stats)))) { } else { - marker_status.fill_comment(comment_, sizeof(comment_)); // ignore ret - marker_status_ = marker_status; + marker_status_.reset(); + marker_status_.total_block_count_ = stats.total_blocks; + marker_status_.reserved_block_count_ = 1; + marker_status_.free_count_ = stats.free_blocks; + marker_status_.pending_free_count_ = stats.pending_release_blocks; + marker_status_.data_block_count_ = stats.published_data_blocks; + marker_status_.index_block_count_ = stats.published_metadata_blocks; + marker_status_.mark_finished_ = stats.ready; + if (stats.ready) { + marker_status_.hold_count_ = stats.total_blocks - 1 - stats.free_blocks + - stats.pending_release_blocks - stats.published_data_blocks + - stats.published_metadata_blocks; + } + marker_status_.fill_comment(comment_, sizeof(comment_)); is_end_ = false; start_to_read_ = true; } diff --git a/src/observer/virtual_table/ob_all_virtual_macro_block_marker_status.h b/src/observer/virtual_table/ob_all_virtual_macro_block_marker_status.h index ac96f24856..d2e4968192 100644 --- a/src/observer/virtual_table/ob_all_virtual_macro_block_marker_status.h +++ b/src/observer/virtual_table/ob_all_virtual_macro_block_marker_status.h @@ -21,6 +21,8 @@ #include "sql/ob_scanner.h" #include "common/row/ob_row.h" #include "storage/blocksstable/ob_block_sstable_struct.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace observer @@ -32,7 +34,7 @@ class ObAllVirtualMacroBlockMarkerStatus: public common::ObVirtualTableScannerIt ObAllVirtualMacroBlockMarkerStatus(); virtual ~ObAllVirtualMacroBlockMarkerStatus(); - int init (const blocksstable::ObMacroBlockMarkerStatus &marker_status); + int init (const storage_io::BlockOwner &block_file); virtual int inner_get_next_row(common::ObNewRow *&row); virtual void reset(); diff --git a/src/observer/virtual_table/ob_all_virtual_server.cpp b/src/observer/virtual_table/ob_all_virtual_server.cpp index 8c3a2d308c..4182246ee4 100644 --- a/src/observer/virtual_table/ob_all_virtual_server.cpp +++ b/src/observer/virtual_table/ob_all_virtual_server.cpp @@ -14,6 +14,7 @@ * limitations under the License. */ +#include "observer/ob_data_file_stats.h" #include "rust/config.h" #include "observer/virtual_table/ob_all_virtual_server.h" #include "share/rc/ob_server_runtime.h" @@ -33,8 +34,10 @@ using namespace oceanbase; using namespace oceanbase::observer; using namespace oceanbase::common; -ObAllVirtualServer::ObAllVirtualServer() +ObAllVirtualServer::ObAllVirtualServer(ObService &ob_service, const storage_io::BlockOwner &block_file) : ObVirtualTableScannerIterator(), + ob_service_(ob_service), + block_file_(block_file), addr_() { ip_buf_[0] = '\0'; @@ -73,14 +76,10 @@ int ObAllVirtualServer::inner_get_next_row(ObNewRow *&row) } else if (OB_ISNULL(cur_row_.cells_)) { ret = OB_ERR_UNEXPECTED; SERVER_LOG(ERROR, "cur row cell is NULL", KR(ret)); - } else if (OB_ISNULL(::oceanbase::share::server_service<::oceanbase::observer::ObService>())) { - ret = OB_ERR_UNEXPECTED; - SERVER_LOG(ERROR, "ob_service_ is NULL", KR(ret), KP(::oceanbase::share::server_service<::oceanbase::observer::ObService>())); - } else if (OB_FAIL(::oceanbase::share::server_service<::oceanbase::observer::ObService>()->get_server_resource_info(resource_info))) { + } else if (OB_FAIL(ob_service_.get_server_resource_info(resource_info))) { } else { const int64_t col_count = output_column_ids_.count(); - const int64_t data_disk_allocated = - OB_STORAGE_OBJECT_MGR.get_total_macro_block_count() * OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + const int64_t data_disk_allocated = read_data_file_stats(block_file_).capacity; const share::ObServerRole::Role active_role = share::server_role(); share::ObServerInfo server_info; const share::IServerRoleStateProvider *role_state_provider = diff --git a/src/observer/virtual_table/ob_all_virtual_server.h b/src/observer/virtual_table/ob_all_virtual_server.h index b19207e7ca..bc6ef9e3f6 100644 --- a/src/observer/virtual_table/ob_all_virtual_server.h +++ b/src/observer/virtual_table/ob_all_virtual_server.h @@ -19,10 +19,14 @@ #include "observer/virtual_table/ob_virtual_table_scanner_iterator.h" // ObVirtualTableScannerIterator +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace observer { +class ObService; + class ObAllVirtualServer : public common::ObVirtualTableScannerIterator { enum COLUMN_ID_LIST @@ -57,12 +61,14 @@ class ObAllVirtualServer : public common::ObVirtualTableScannerIterator }; public: - ObAllVirtualServer(); + ObAllVirtualServer(ObService &ob_service, const storage_io::BlockOwner &block_file); virtual ~ObAllVirtualServer(); int init(common::ObAddr &addr); virtual int inner_get_next_row(common::ObNewRow *&row); private: + ObService &ob_service_; + const storage_io::BlockOwner &block_file_; char ip_buf_[common::OB_IP_STR_BUFF]; common::ObAddr addr_; char role_buf_[64]; diff --git a/src/observer/virtual_table/ob_all_virtual_tablet_sstable_macro_info.cpp b/src/observer/virtual_table/ob_all_virtual_tablet_sstable_macro_info.cpp index 312567a893..d3445c27e3 100644 --- a/src/observer/virtual_table/ob_all_virtual_tablet_sstable_macro_info.cpp +++ b/src/observer/virtual_table/ob_all_virtual_tablet_sstable_macro_info.cpp @@ -14,6 +14,8 @@ * limitations under the License. */ +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_all_virtual_tablet_sstable_macro_info.h" #include "observer/virtual_table/ob_virtual_table_tablet_iter.h" @@ -119,8 +121,9 @@ void ObAllVirtualTabletSSTableMacroInfo::MacroInfo::reset() row_store_type_ = ObRowStoreType::MAX_ROW_STORE; } -ObAllVirtualTabletSSTableMacroInfo::ObAllVirtualTabletSSTableMacroInfo() +ObAllVirtualTabletSSTableMacroInfo::ObAllVirtualTabletSSTableMacroInfo(storage_io::BlockOwner &block_file) : ObVirtualTableScannerIterator(), + block_file_(block_file), tablet_iter_(nullptr), tablet_allocator_("VTTable"), tablet_handle_(), @@ -224,14 +227,14 @@ int ObAllVirtualTabletSSTableMacroInfo::get_macro_info( macro_read_info.macro_block_id_ = macro_id; macro_read_info.io_desc_.set_mode(ObIOMode::READ); macro_read_info.offset_ = 0; - macro_read_info.size_ = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + macro_read_info.size_ = OB_DEFAULT_MACRO_BLOCK_SIZE; macro_read_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000L; if (OB_UNLIKELY(!macro_id.is_valid())) { ret = OB_INVALID_ARGUMENT; SERVER_LOG(WARN, "invalid argument", K(ret), K(macro_id)); - } else if (OB_FAIL(ObObjectManager::read_object(macro_read_info, macro_handle))) { + } else if (OB_FAIL(macro_handle.read(block_file_, macro_read_info))) { } else { ObMacroBlockCommonHeader common_header; ObSSTableMacroBlockHeader macro_header; diff --git a/src/observer/virtual_table/ob_all_virtual_tablet_sstable_macro_info.h b/src/observer/virtual_table/ob_all_virtual_tablet_sstable_macro_info.h index c389e544d3..2757912ced 100644 --- a/src/observer/virtual_table/ob_all_virtual_tablet_sstable_macro_info.h +++ b/src/observer/virtual_table/ob_all_virtual_tablet_sstable_macro_info.h @@ -30,6 +30,8 @@ #include "observer/omt/ob_server_runtime_controller.h" #include "storage/meta_mem/ob_tablet_handle.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace storage @@ -64,7 +66,7 @@ class ObAllVirtualTabletSSTableMacroInfo : public common::ObVirtualTableScannerI ROW_STORE_TYPE }; public: - ObAllVirtualTabletSSTableMacroInfo(); + explicit ObAllVirtualTabletSSTableMacroInfo(storage_io::BlockOwner &block_file); virtual ~ObAllVirtualTabletSSTableMacroInfo(); int init(common::ObIAllocator *allocator); virtual int inner_get_next_row(common::ObNewRow *&row); @@ -117,6 +119,7 @@ class ObAllVirtualTabletSSTableMacroInfo : public common::ObVirtualTableScannerI int get_macro_info(const blocksstable::MacroBlockId ¯o_id, MacroInfo &info); int get_macro_info(const blocksstable::ObMacroBlockDesc ¯o_desc, MacroInfo &info); private: + storage_io::BlockOwner &block_file_; ObTabletIterator *tablet_iter_; common::ObArenaAllocator tablet_allocator_; ObTabletHandle tablet_handle_; diff --git a/src/observer/virtual_table/ob_virtual_data_access_service.h b/src/observer/virtual_table/ob_virtual_data_access_service.h index 6190d0d338..c4228e42bc 100644 --- a/src/observer/virtual_table/ob_virtual_data_access_service.h +++ b/src/observer/virtual_table/ob_virtual_data_access_service.h @@ -38,8 +38,8 @@ class ObVirtualDataAccessService : public common::ObIVirtualTableScan public: ObVirtualDataAccessService( rootserver::ObLocalManagementService &local_management_service, - common::ObAddr &addr) - : vt_iter_factory_(local_management_service, addr) + common::ObAddr &addr, ObService &ob_service, storage_io::BlockOwner &block_file) + : vt_iter_factory_(local_management_service, addr, ob_service, block_file) { } virtual ~ObVirtualDataAccessService() {} diff --git a/src/observer/virtual_table/ob_virtual_table_iterator_factory.cpp b/src/observer/virtual_table/ob_virtual_table_iterator_factory.cpp index 47c0474a45..97d5b99e8e 100644 --- a/src/observer/virtual_table/ob_virtual_table_iterator_factory.cpp +++ b/src/observer/virtual_table/ob_virtual_table_iterator_factory.cpp @@ -213,9 +213,11 @@ ObVirtualTableIteratorFactory::ObVirtualTableIteratorFactory(ObVTIterCreator &vt } ObVirtualTableIteratorFactory::ObVirtualTableIteratorFactory(ObLocalManagementService &local_management_service, - common::ObAddr &addr) : + common::ObAddr &addr, + ObService &ob_service, + storage_io::BlockOwner &block_file) : ObIVirtualTableIteratorFactory(), - vt_iter_creator_(local_management_service, addr) + vt_iter_creator_(local_management_service, addr, ob_service, block_file) { } @@ -971,7 +973,7 @@ int ObVTIterCreator::create_vt_iter(ObVTableScanParam ¶ms, } case OB_ALL_VIRTUAL_DISK_STAT_TID: { ObInfoSchemaDiskStatTable *disk_stat_table = NULL; - if (OB_SUCC(NEW_VIRTUAL_TABLE(ObInfoSchemaDiskStatTable, disk_stat_table))) { + if (OB_SUCC(NEW_VIRTUAL_TABLE(ObInfoSchemaDiskStatTable, disk_stat_table, block_file_))) { disk_stat_table->set_addr(addr_); vt_iter = static_cast(disk_stat_table); } @@ -1014,7 +1016,7 @@ int ObVTIterCreator::create_vt_iter(ObVTableScanParam ¶ms, BEGIN_CREATE_VT_ITER_SWITCH_LAMBDA case OB_ALL_VIRTUAL_TABLET_SSTABLE_MACRO_INFO_TID: { ObAllVirtualTabletSSTableMacroInfo *sstable_macro_info = NULL; - if (OB_SUCC(NEW_VIRTUAL_TABLE(ObAllVirtualTabletSSTableMacroInfo, sstable_macro_info))) { + if (OB_SUCC(NEW_VIRTUAL_TABLE(ObAllVirtualTabletSSTableMacroInfo, sstable_macro_info, block_file_))) { if (OB_FAIL(sstable_macro_info->init(&allocator))) { } else { vt_iter = static_cast(sstable_macro_info); @@ -1043,11 +1045,9 @@ int ObVTIterCreator::create_vt_iter(ObVTableScanParam ¶ms, case OB_ALL_VIRTUAL_MACRO_BLOCK_MARKER_STATUS_TID: { ObAllVirtualMacroBlockMarkerStatus *all_virtual_marker_status = NULL; if (OB_SUCC(NEW_VIRTUAL_TABLE(ObAllVirtualMacroBlockMarkerStatus, all_virtual_marker_status))) { - blocksstable::ObMacroBlockMarkerStatus marker_status; - if (OB_FAIL(OB_SERVER_BLOCK_MGR.get_marker_status(marker_status))) { - } else if (OB_FAIL(all_virtual_marker_status->init(marker_status))) { + if (OB_FAIL(all_virtual_marker_status->init(block_file_))) { } else { - vt_iter = static_cast(all_virtual_marker_status); + vt_iter = all_virtual_marker_status; } } break; @@ -1110,7 +1110,7 @@ int ObVTIterCreator::create_vt_iter(ObVTableScanParam ¶ms, case OB_ALL_VIRTUAL_BAD_BLOCK_TABLE_TID: { ObVirtualBadBlockTable *bad_block_table = NULL; if (OB_SUCC(NEW_VIRTUAL_TABLE(ObVirtualBadBlockTable, bad_block_table))) { - if (OB_FAIL(bad_block_table->init(addr_))) { + if (OB_FAIL(bad_block_table->init(addr_, block_file_))) { } else { vt_iter = static_cast(bad_block_table); } @@ -1231,7 +1231,7 @@ int ObVTIterCreator::create_vt_iter(ObVTableScanParam ¶ms, } case OB_ALL_VIRTUAL_SERVER_STAT_TID: { ObAllVirtualServer *server = NULL; - if (OB_FAIL(NEW_VIRTUAL_TABLE(ObAllVirtualServer, server))) { + if (OB_FAIL(NEW_VIRTUAL_TABLE(ObAllVirtualServer, server, ob_service_, block_file_))) { } else if (OB_FAIL(server->init(addr_))) { } else { vt_iter = static_cast(server); diff --git a/src/observer/virtual_table/ob_virtual_table_iterator_factory.h b/src/observer/virtual_table/ob_virtual_table_iterator_factory.h index 143eedcf3b..7f6ceb04a0 100644 --- a/src/observer/virtual_table/ob_virtual_table_iterator_factory.h +++ b/src/observer/virtual_table/ob_virtual_table_iterator_factory.h @@ -23,6 +23,8 @@ #include "share/config/ob_server_config.h" #include "sql/engine/table/ob_i_virtual_table_iterator_factory.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace common @@ -44,12 +46,15 @@ class ObLocalManagementService; } namespace observer { +class ObService; + class ObVTIterCreator { public: - ObVTIterCreator(rootserver::ObLocalManagementService &local_management_service, common::ObAddr &addr) + ObVTIterCreator(rootserver::ObLocalManagementService &local_management_service, + common::ObAddr &addr, ObService &ob_service, storage_io::BlockOwner &block_file) : local_management_service_(local_management_service), - addr_(addr) + addr_(addr), ob_service_(ob_service), block_file_(block_file) {} virtual ~ObVTIterCreator() {} int get_latest_expected_schema(const uint64_t table_id, @@ -65,6 +70,8 @@ class ObVTIterCreator private: rootserver::ObLocalManagementService &local_management_service_; common::ObAddr &addr_; + ObService &ob_service_; + storage_io::BlockOwner &block_file_; }; class ObVirtualTableIteratorFactory : public sql::ObIVirtualTableIteratorFactory @@ -72,7 +79,8 @@ class ObVirtualTableIteratorFactory : public sql::ObIVirtualTableIteratorFactory public: explicit ObVirtualTableIteratorFactory(ObVTIterCreator &vt_iter_creator); ObVirtualTableIteratorFactory(rootserver::ObLocalManagementService &local_management_service, - common::ObAddr &addr); + common::ObAddr &addr, ObService &ob_service, + storage_io::BlockOwner &block_file); virtual ~ObVirtualTableIteratorFactory(); virtual int create_virtual_table_iterator(common::ObVTableScanParam ¶ms, common::ObVirtualTableIterator *&vt_iter); diff --git a/src/share/io_request.cpp b/src/share/io_request.cpp index eda84a3d57..164bafead7 100644 --- a/src/share/io_request.cpp +++ b/src/share/io_request.cpp @@ -293,6 +293,9 @@ int oceanbase::common::convert_block_status(const storage_io::BlockStatus &statu case storage_io::BlockCode::InvalidArgument: return OB_INVALID_ARGUMENT; case storage_io::BlockCode::InvalidHeader: return OB_INVALID_DATA; case storage_io::BlockCode::ChecksumMismatch: return OB_PHYSIC_CHECKSUM_ERROR; + case storage_io::BlockCode::NotAllocated: return OB_ENTRY_NOT_EXIST; + case storage_io::BlockCode::StaleBlock: return OB_STATE_NOT_MATCH; + case storage_io::BlockCode::GenerationExhausted: return OB_ERROR_OUT_OF_RANGE; case storage_io::BlockCode::Exhausted: return OB_SERVER_OUTOF_DISK_SPACE; case storage_io::BlockCode::Memory: return OB_ALLOCATE_MEMORY_FAILED; case storage_io::BlockCode::NotOpen: return OB_NOT_INIT; diff --git a/src/share/io_request.h b/src/share/io_request.h index 2720d86275..9d093e80cf 100644 --- a/src/share/io_request.h +++ b/src/share/io_request.h @@ -42,8 +42,7 @@ enum ObIOModule { CALIBRATION_IO, DETECT_IO, SSTABLE_WHOLE_SCANNER_IO, - INSPECT_BAD_BLOCK_IO, - SSTABLE_INDEX_BUILDER_IO, + SSTABLE_INDEX_BUILDER_IO = 6, // Keep existing I/O statistics module IDs. BACKUP_READER_IO, BLOOM_FILTER_IO, INDEX_BLOCK_TREE_CURSOR_IO, diff --git a/src/standby/ob_standby_bootstrap_service.cpp b/src/standby/ob_standby_bootstrap_service.cpp index c90bb45534..f29a384e19 100644 --- a/src/standby/ob_standby_bootstrap_service.cpp +++ b/src/standby/ob_standby_bootstrap_service.cpp @@ -50,6 +50,7 @@ bool ObStandbyBootstrapParam::is_valid() const int ObStandbyBootstrapService::bootstrap( const ObStandbyBootstrapParam ¶m, + const IStandbyHost &host, share::SCN &source_end_scn) { int ret = OB_SUCCESS; @@ -70,7 +71,7 @@ int ObStandbyBootstrapService::bootstrap( primary_addr, param.bandwidth_throttle_, *param.restore_config_))) { LOG_WARN("failed to init standby sstable copier", KR(ret), K(primary_addr)); } else if (OB_FAIL(copier.prepare_replay_base( - restore_checkpoint_scn, wal_base_info, source_end_scn))) { + host, restore_checkpoint_scn, wal_base_info, source_end_scn))) { LOG_WARN("failed to prepare standby replay base", KR(ret), K(primary_addr)); } else if (OB_FAIL(create_sys_ls_(param, wal_base_info, restore_checkpoint_scn))) { LOG_WARN("failed to create standby restore sys ls", KR(ret)); diff --git a/src/standby/ob_standby_bootstrap_service.h b/src/standby/ob_standby_bootstrap_service.h index 223851be58..623182bc0e 100644 --- a/src/standby/ob_standby_bootstrap_service.h +++ b/src/standby/ob_standby_bootstrap_service.h @@ -30,6 +30,7 @@ class ObInOutBandwidthThrottle; namespace standby { +class IStandbyHost; struct StandbyConfig; struct ObStandbyBootstrapParam final @@ -48,6 +49,7 @@ class ObStandbyBootstrapService final public: static int bootstrap( const ObStandbyBootstrapParam ¶m, + const IStandbyHost &host, share::SCN &source_end_scn); static int check_bootstrap_source( const ObStandbyBootstrapParam ¶m, diff --git a/src/standby/restore/ob_physical_copy_task.cpp b/src/standby/restore/ob_physical_copy_task.cpp index 923ff1c024..0318cc7cae 100644 --- a/src/standby/restore/ob_physical_copy_task.cpp +++ b/src/standby/restore/ob_physical_copy_task.cpp @@ -332,7 +332,7 @@ int ObPhysicalCopyTask::get_macro_block_writer_( if (OB_ISNULL(tmp_writer)) { ret = OB_ALLOCATE_MEMORY_FAILED; LOG_WARN("failed to alloc memory", K(ret)); - } else if (OB_FAIL(tmp_writer->init(copy_ctx_->tenant_id_, copy_ctx_->ls_id_, copy_ctx_->tablet_id_, + } else if (OB_FAIL(tmp_writer->init(finish_task_->block_file(), copy_ctx_->tenant_id_, copy_ctx_->ls_id_, copy_ctx_->tablet_id_, copy_ctx_->copy_id_, sstable_param, reader, index_block_rebuilder, copy_ctx_->extra_info_, copy_ctx_->helper_->get_config().io_timeout_ms_))) { STORAGE_LOG(WARN, "failed to init macro block writer", K(ret), KPC(copy_ctx_)); diff --git a/src/standby/restore/ob_restore_helper.cpp b/src/standby/restore/ob_restore_helper.cpp index b1dd904f33..7f0e6f1e63 100644 --- a/src/standby/restore/ob_restore_helper.cpp +++ b/src/standby/restore/ob_restore_helper.cpp @@ -15,7 +15,7 @@ */ #define USING_LOG_PREFIX STORAGE -#include "storage/blocksstable/ob_block_manager.h" +#include "standby/standby_host.h" #include "ob_restore_helper.h" #include "standby/restore/ob_restore_helper_ctx.h" #include "standby/standby_host.h" @@ -138,7 +138,7 @@ int ObStandbyRestoreHelper::copy_for_task( return ret; } -int ObStandbyRestoreHelper::check_restore_precondition() +int ObStandbyRestoreHelper::check_restore_precondition(const standby::IStandbyHost &host) { int ret = OB_SUCCESS; int64_t required_size = 0; @@ -161,7 +161,7 @@ int ObStandbyRestoreHelper::check_restore_precondition() KR(ret), "primary_version", result.data_version_, "standby_version", local_data_version); } else { result.required_disk_size_ = std::max(result.required_disk_size_, result.total_tablet_size_); - if (OB_FAIL(OB_SERVER_BLOCK_MGR.check_space_full(result.required_disk_size_))) { + if (OB_FAIL(host.check_restore_disk_space(result.required_disk_size_))) { LOG_ERROR("failed to check_is_disk_full, cannot restore", KR(ret), K(result)); } else { LOG_INFO("disk space and data version check passed", diff --git a/src/standby/restore/ob_restore_helper.h b/src/standby/restore/ob_restore_helper.h index 574e4446cb..6fa7e083f1 100644 --- a/src/standby/restore/ob_restore_helper.h +++ b/src/standby/restore/ob_restore_helper.h @@ -30,6 +30,7 @@ namespace oceanbase { namespace standby { +class IStandbyHost; struct StandbyConfig; } namespace storage @@ -52,7 +53,7 @@ class ObStandbyRestoreHelper common::ObInOutBandwidthThrottle *bandwidth_throttle, const standby::StandbyConfig &config); const standby::StandbyConfig &get_config() const { return *config_; } - int check_restore_precondition(); + int check_restore_precondition(const standby::IStandbyHost &host); int init_for_ls_view(); int fetch_next_tablet_info(obcall::ObCopyTabletInfo &tablet_info); int fetch_ls_meta(storage::ObLSMeta &ls_meta, share::SCN &physical_checkpoint_scn); diff --git a/src/standby/restore/ob_sstable_copy_finish_task.cpp b/src/standby/restore/ob_sstable_copy_finish_task.cpp index fa928bedd9..028aaceb22 100644 --- a/src/standby/restore/ob_sstable_copy_finish_task.cpp +++ b/src/standby/restore/ob_sstable_copy_finish_task.cpp @@ -147,14 +147,18 @@ int ObCopiedSSTableCreatorImpl::init_create_sstable_param_( return ret; } +storage_io::BlockOwner &ObSSTableCopyFinishTask::block_file() const +{ + return ls_->block_file(); +} + int ObCopiedSSTableCreatorImpl::do_create_sstable_( const ObTabletCreateSSTableParam ¶m, ObTableHandleV2 &table_handle) const { int ret = OB_SUCCESS; - if (OB_FAIL(ObTabletCreateDeleteHelper::create_sstable(param, - *allocator_, - table_handle))) { + if (OB_FAIL(ObTabletCreateDeleteHelper::create_sstable( + finish_task_->block_file(), param, *allocator_, table_handle))) { LOG_WARN("failed to create sstable", K(ret), K(param)); } @@ -449,6 +453,7 @@ int ObSSTableCopyFinishTask::prepare_data_store_desc_( LOG_WARN("tablet should not be NULL", K(ret), K(tablet_id)); } else { if (OB_FAIL(desc.init( + tablet->block_file(), false/*is ddl*/, *storage_schema, tablet_id, diff --git a/src/standby/restore/ob_sstable_copy_finish_task.h b/src/standby/restore/ob_sstable_copy_finish_task.h index e8ce9016de..4e61c084e8 100644 --- a/src/standby/restore/ob_sstable_copy_finish_task.h +++ b/src/standby/restore/ob_sstable_copy_finish_task.h @@ -152,6 +152,7 @@ class ObSSTableCopyFinishTask virtual ~ObSSTableCopyFinishTask(); int init( const ObPhysicalCopyTaskInitParam &init_param); + storage_io::BlockOwner &block_file() const; ObPhysicalCopyCtx *get_copy_ctx() { return ©_ctx_; } const ObMigrationSSTableParam *get_sstable_param() { return sstable_param_; } int get_next_macro_block_copy_info( diff --git a/src/standby/restore/ob_standby_restore_macro_block_writer.cpp b/src/standby/restore/ob_standby_restore_macro_block_writer.cpp index 43d2654e45..bb0f8aaf88 100644 --- a/src/standby/restore/ob_standby_restore_macro_block_writer.cpp +++ b/src/standby/restore/ob_standby_restore_macro_block_writer.cpp @@ -15,7 +15,9 @@ */ #define USING_LOG_PREFIX STORAGE -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" +#include "storage/blocksstable/ob_block_sstable_struct.h" #include "ob_standby_restore_macro_block_writer.h" namespace oceanbase @@ -42,6 +44,7 @@ ObStandbyRestoreMacroBlockWriter::ObStandbyRestoreMacroBlockWriter() } int ObStandbyRestoreMacroBlockWriter::init( + storage_io::BlockOwner &blocks, const uint64_t tenant_id, const share::ObLSID &ls_id, const common::ObTabletID &tablet_id, @@ -81,6 +84,7 @@ int ObStandbyRestoreMacroBlockWriter::init( index_block_rebuilder_ = index_block_rebuilder; extra_info_ = extra_info; io_timeout_ms_ = io_timeout_ms; + blocks_ = &blocks; is_inited_ = true; } return ret; @@ -113,7 +117,6 @@ int ObStandbyRestoreMacroBlockWriter::process( int ret = OB_SUCCESS; int64_t start_time = ObTimeUtility::current_time(); blocksstable::ObBufferReader data(NULL, 0, 0); - ObStorageObjectOpt opt; blocksstable::ObDatumRow macro_meta_row; blocksstable::ObStorageObjectWriteInfo write_info; blocksstable::ObStorageObjectHandle write_handle; @@ -136,7 +139,7 @@ int ObStandbyRestoreMacroBlockWriter::process( STORAGE_LOG(INFO, "macro block writer begin", K_(tenant_id), K_(ls_id), K_(tablet_id), K_(copy_id), KPC_(sstable_param)); while (OB_SUCC(ret)) { - if (OB_FAIL(OB_SERVER_BLOCK_MGR.check_space_full(0 /*required_size*/))) { + if (OB_FAIL(blocksstable::check_block_space(*blocks_, 0))) { STORAGE_LOG(ERROR, "failed to check disk space", K(ret), K_(tenant_id), K_(ls_id), K_(tablet_id), K_(copy_id), KPC_(sstable_param)); break; @@ -159,7 +162,7 @@ int ObStandbyRestoreMacroBlockWriter::process( ret = OB_INVALID_ARGUMENT; STORAGE_LOG(ERROR, "invalid macro id (id is default)", K(ret), K(macro_id), K(read_data), K_(tenant_id), K_(ls_id), K_(tablet_id), K_(copy_id), KPC_(sstable_param)); - } else if (OB_FAIL(copied_ctx.add_macro_block_id(macro_id))) { + } else if (OB_FAIL(copied_ctx.add_macro_block_id(*blocks_, macro_id))) { STORAGE_LOG(ERROR, "fail to add macro id", K(ret), K(macro_id), K_(tenant_id), K_(ls_id), K_(tablet_id), K_(copy_id), KPC_(sstable_param)); } else if (OB_FAIL(index_block_rebuilder_->append_macro_row(*read_data.macro_meta_))) { @@ -182,11 +185,11 @@ int ObStandbyRestoreMacroBlockWriter::process( STORAGE_LOG(ERROR, "failed to wait write handle", K(ret), K(write_info), K(macro_block_id), K_(tenant_id), K_(ls_id), K_(tablet_id), K_(copy_id), KPC_(sstable_param)); - } else if (OB_FAIL(set_macro_write_info_(macro_block_id, write_info, opt))) { + } else if (OB_FAIL(set_macro_write_info_(macro_block_id, write_info))) { LOG_ERROR("failed to set macro write info", K(ret), K(macro_block_id), K_(tenant_id), K_(ls_id), K_(tablet_id), K_(copy_id), KPC_(sstable_param)); - } else if (OB_FAIL(write_macro_block_(opt, write_info, write_handle, copied_ctx, data))) { - LOG_ERROR("failed to write macro block", K(ret), K(opt), K(macro_block_id), + } else if (OB_FAIL(write_macro_block_(write_info, write_handle, copied_ctx, data))) { + LOG_ERROR("failed to write macro block", K(ret), K(macro_block_id), K_(tenant_id), K_(ls_id), K_(tablet_id), K_(copy_id), KPC_(sstable_param)); } else { ++write_count; @@ -236,7 +239,6 @@ int ObStandbyRestoreMacroBlockWriter::process( } int ObStandbyRestoreMacroBlockWriter::write_macro_block_( - const ObStorageObjectOpt &opt, blocksstable::ObStorageObjectWriteInfo &write_info, blocksstable::ObStorageObjectHandle &write_handle, blocksstable::ObMacroBlocksWriteCtx &copied_ctx, @@ -251,9 +253,9 @@ int ObStandbyRestoreMacroBlockWriter::write_macro_block_( write_info.size_ = data.upper_align_length(); write_handle.reset(); - if (OB_FAIL(ObObjectManager::async_write_object(opt, write_info, write_handle))) { + if (OB_FAIL(write_handle.allocate_and_write(*blocks_, write_info))) { LOG_WARN("fail to async write block", K(ret), K(write_info), K(write_handle)); - } else if (OB_FAIL(copied_ctx.add_macro_block_id(write_handle.get_macro_id()))) { + } else if (OB_FAIL(copied_ctx.add_macro_block(write_handle))) { LOG_WARN("fail to add macro id", K(ret), "macro id", write_handle.get_macro_id()); } else if (OB_FAIL(append_macro_row_(data.data(), data.capacity(), write_handle.get_macro_id()))) { LOG_WARN("failed to append macro row", K(ret), K(write_handle)); @@ -272,8 +274,7 @@ int ObStandbyRestoreLocalMacroBlockWriter::check_sstable_param_for_init_(const O int ObStandbyRestoreLocalMacroBlockWriter::set_macro_write_info_( const MacroBlockId ¯o_block_id, - blocksstable::ObStorageObjectWriteInfo &write_info, - blocksstable::ObStorageObjectOpt &opt) + blocksstable::ObStorageObjectWriteInfo &write_info) { int ret = OB_SUCCESS; UNUSED(macro_block_id); @@ -287,7 +288,6 @@ int ObStandbyRestoreLocalMacroBlockWriter::set_macro_write_info_( write_info.io_desc_.set_sys_module_id(ObIOModule::SSTABLE_MACRO_BLOCK_WRITE_IO); write_info.io_timeout_ms_ = io_timeout_ms_; write_info.offset_ = 0; - opt.set_data_macro_object_opt(); } return ret; } diff --git a/src/standby/restore/ob_standby_restore_macro_block_writer.h b/src/standby/restore/ob_standby_restore_macro_block_writer.h index ecd4eb65d9..1dc92f947f 100644 --- a/src/standby/restore/ob_standby_restore_macro_block_writer.h +++ b/src/standby/restore/ob_standby_restore_macro_block_writer.h @@ -17,7 +17,8 @@ #ifndef OCEANBASE_STORAGE_STANDBY_RESTORE_MACRO_BLOCK_WRITER_ #define OCEANBASE_STORAGE_STANDBY_RESTORE_MACRO_BLOCK_WRITER_ -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "storage/blocksstable/ob_block_sstable_struct.h" #include "storage/blocksstable/ob_macro_block_struct.h" #include "storage/blocksstable/ob_macro_block_checker.h" @@ -53,6 +54,7 @@ class ObStandbyRestoreMacroBlockWriter : public ObIStandbyRestoreMacroBlockWrite ObStandbyRestoreMacroBlockWriter(); virtual ~ObStandbyRestoreMacroBlockWriter() {} int init( + storage_io::BlockOwner &blocks, const uint64_t tenant_id, const share::ObLSID &ls_id, const common::ObTabletID &tablet_id, @@ -70,8 +72,7 @@ class ObStandbyRestoreMacroBlockWriter : public ObIStandbyRestoreMacroBlockWrite virtual int check_sstable_param_for_init_(const ObMigrationSSTableParam *sstable_param) const = 0; virtual int set_macro_write_info_( const MacroBlockId ¯o_block_id, - blocksstable::ObStorageObjectWriteInfo &write_info, - blocksstable::ObStorageObjectOpt &opt) = 0; + blocksstable::ObStorageObjectWriteInfo &write_info) = 0; virtual int append_macro_row_( const char *buf, const int64_t size, @@ -81,13 +82,13 @@ class ObStandbyRestoreMacroBlockWriter : public ObIStandbyRestoreMacroBlockWrite int check_macro_block_( const blocksstable::ObBufferReader &data); int write_macro_block_( - const ObStorageObjectOpt &opt, - blocksstable::ObStorageObjectWriteInfo &write_info, + blocksstable::ObStorageObjectWriteInfo &write_info, blocksstable::ObStorageObjectHandle &write_handle, blocksstable::ObMacroBlocksWriteCtx &copied_ctx, blocksstable::ObBufferReader &data); protected: + storage_io::BlockOwner *blocks_ = nullptr; bool is_inited_; uint64_t tenant_id_; share::ObLSID ls_id_; @@ -113,8 +114,7 @@ class ObStandbyRestoreLocalMacroBlockWriter final : public ObStandbyRestoreMacro virtual int check_sstable_param_for_init_(const ObMigrationSSTableParam *sstable_param) const override; virtual int set_macro_write_info_( const MacroBlockId ¯o_block_id, - blocksstable::ObStorageObjectWriteInfo &write_info, - blocksstable::ObStorageObjectOpt &opt) override; + blocksstable::ObStorageObjectWriteInfo &write_info) override; virtual int append_macro_row_( const char *buf, const int64_t size, diff --git a/src/standby/restore/ob_standby_restore_reader.cpp b/src/standby/restore/ob_standby_restore_reader.cpp index ccf09b8bfc..db50c45d57 100644 --- a/src/standby/restore/ob_standby_restore_reader.cpp +++ b/src/standby/restore/ob_standby_restore_reader.cpp @@ -462,8 +462,7 @@ int ObCopyMacroBlockObProducer::prefetch_() if (OB_FAIL(get_read_info_(macro_meta, read_info))) { LOG_WARN("failed to build macro block read info", K(ret), K(macro_meta)); - } else if (OB_FAIL(ObObjectManager::async_read_object( - read_info, copy_macro_block_handle_[handle_idx_].read_handle_))) { + } else if (OB_FAIL(copy_macro_block_handle_[handle_idx_].read_handle_.async_read(sstable_->block_file(), read_info))) { STORAGE_LOG(ERROR, "Fail to async read block, ", K(ret), K(read_info), K(macro_meta)); } } diff --git a/src/standby/restore/ob_standby_restore_reader.h b/src/standby/restore/ob_standby_restore_reader.h index 4970a74caf..748a214167 100644 --- a/src/standby/restore/ob_standby_restore_reader.h +++ b/src/standby/restore/ob_standby_restore_reader.h @@ -21,7 +21,9 @@ #include "share/ob_define.h" #include "lib/utility/ob_macro_utils.h" #include "ob_standby_restore_storage_struct.h" -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" +#include "storage/blocksstable/ob_block_sstable_struct.h" #include "storage/ob_i_table.h" #include "standby/restore/ob_standby_restore_rpc.h" #include "ob_storage_restore_struct.h" diff --git a/src/standby/restore/ob_standby_sstable_copier.cpp b/src/standby/restore/ob_standby_sstable_copier.cpp index aabab47bfc..3d70a7c585 100644 --- a/src/standby/restore/ob_standby_sstable_copier.cpp +++ b/src/standby/restore/ob_standby_sstable_copier.cpp @@ -110,6 +110,7 @@ int ObStandbySSTableCopier::init( } int ObStandbySSTableCopier::prepare_replay_base( + const standby::IStandbyHost &host, share::SCN &restore_checkpoint_scn, wal::BaseInfo &wal_base_info, share::SCN &source_end_scn) @@ -129,7 +130,7 @@ int ObStandbySSTableCopier::prepare_replay_base( ret = OB_INIT_TWICE; } else if (OB_FAIL(init_helper_(ls_view_helper_))) { LOG_WARN("failed to init ls view helper", K(ret), K_(src)); - } else if (OB_FAIL(ls_view_helper_.check_restore_precondition())) { + } else if (OB_FAIL(ls_view_helper_.check_restore_precondition(host))) { LOG_WARN("standby restore precondition check failed", K(ret), K_(src)); } else if (OB_FAIL(ls_view_helper_.init_for_ls_view())) { LOG_WARN("failed to initialize source ls view", K(ret), K_(src)); diff --git a/src/standby/restore/ob_standby_sstable_copier.h b/src/standby/restore/ob_standby_sstable_copier.h index 6989a1304e..7b539f2af1 100644 --- a/src/standby/restore/ob_standby_sstable_copier.h +++ b/src/standby/restore/ob_standby_sstable_copier.h @@ -29,6 +29,7 @@ namespace oceanbase { namespace standby { +class IStandbyHost; struct StandbyConfig; } namespace common @@ -57,6 +58,7 @@ class ObStandbySSTableCopier final common::ObInOutBandwidthThrottle *bandwidth_throttle, const standby::StandbyConfig &config); int prepare_replay_base( + const standby::IStandbyHost &host, share::SCN &restore_checkpoint_scn, wal::BaseInfo &wal_base_info, share::SCN &source_end_scn); diff --git a/src/standby/standby_host.h b/src/standby/standby_host.h index 3f88906b44..1eee6a03c5 100644 --- a/src/standby/standby_host.h +++ b/src/standby/standby_host.h @@ -91,6 +91,7 @@ class IStandbyHost virtual void reset_max_id_cache() = 0; virtual int refresh_schema() = 0; + virtual int check_restore_disk_space(int64_t required_size) const = 0; virtual int bootstrap_primary() = 0; virtual int report_bootstrap_telemetry() = 0; virtual int wait_primary_metadata_ready() = 0; diff --git a/src/standby/standby_module.cpp b/src/standby/standby_module.cpp index 1c7cd40af2..f3eb9e028c 100644 --- a/src/standby/standby_module.cpp +++ b/src/standby/standby_module.cpp @@ -327,7 +327,7 @@ int StandbyModule::Impl::bootstrap_standby_() if (OB_FAIL(ret)) { } else if (OB_FAIL(ObStandbyTimestampProvider::enable())) { LOG_WARN("failed to prepare standby timestamp provider for bootstrap", KR(ret)); - } else if (OB_FAIL(ObStandbyBootstrapService::bootstrap(param, source_end_scn))) { + } else if (OB_FAIL(ObStandbyBootstrapService::bootstrap(param, *host_, source_end_scn))) { LOG_WARN("failed to bootstrap standby", KR(ret)); } else if (OB_FAIL(log_sync_service_.set_startup_target_scn(source_end_scn))) { LOG_WARN("failed to record standby startup replay target", KR(ret), K(source_end_scn)); diff --git a/src/storage/access/ob_index_sstable_estimator.cpp b/src/storage/access/ob_index_sstable_estimator.cpp index 06ebbe953d..b1175f9003 100644 --- a/src/storage/access/ob_index_sstable_estimator.cpp +++ b/src/storage/access/ob_index_sstable_estimator.cpp @@ -88,6 +88,7 @@ int ObIndexBlockScanEstimator::init_index_scanner(ObSSTable &sstable) context_.query_flag_, sstable.get_macro_offset()))) { } + block_file_ = &sstable.block_file(); if (FAILEDx(sstable.get_index_tree_root(root_index_block_))) { } return ret; @@ -338,6 +339,7 @@ int ObIndexBlockScanEstimator::prefetch_index_block_data( bool found = false; const MacroBlockId ¯o_id = micro_index_info.get_macro_id(); micro_handle.allocator_ = &allocator_; + micro_handle.block_file_ = block_file_; ObMicroBlockCacheKey key(micro_index_info); ObIMicroBlockCache *cache = nullptr; @@ -361,7 +363,7 @@ int ObIndexBlockScanEstimator::prefetch_index_block_data( } if (OB_SUCC(ret) && !found) { if (OB_FAIL(micro_index_info.row_header_->fill_micro_des_meta(micro_handle.des_meta_))) { - } else if (OB_FAIL(cache->prefetch(macro_id, micro_index_info, + } else if (OB_FAIL(cache->prefetch(*block_file_, macro_id, micro_index_info, context_.query_flag_.is_use_block_cache(), micro_handle.io_handle_, &allocator_))) { } else if (ObSSTableMicroBlockState::UNKNOWN_STATE == micro_handle.block_state_) { diff --git a/src/storage/access/ob_index_sstable_estimator.h b/src/storage/access/ob_index_sstable_estimator.h index eb85132302..d6cbcf0a91 100644 --- a/src/storage/access/ob_index_sstable_estimator.h +++ b/src/storage/access/ob_index_sstable_estimator.h @@ -141,6 +141,7 @@ class ObIndexBlockScanEstimator blocksstable::ObMicroBlockData index_block_data_; const ObIndexSSTableEstimateContext &context_; ObArenaAllocator allocator_; + storage_io::BlockOwner *block_file_ = nullptr; }; } diff --git a/src/storage/access/ob_index_tree_prefetcher.ipp b/src/storage/access/ob_index_tree_prefetcher.ipp index 4c7a43b867..7af48c4420 100644 --- a/src/storage/access/ob_index_tree_prefetcher.ipp +++ b/src/storage/access/ob_index_tree_prefetcher.ipp @@ -371,6 +371,7 @@ inline int ObIndexTreePrefetcher::prefetch_block_data( ++access_ctx_->table_store_stat_.block_cache_hit_cnt_; } else if (OB_FAIL(ret)) { } else if (OB_FAIL(access_ctx_->micro_block_handle_mgr_.get_micro_block_handle( + sstable_->block_file(), access_ctx_, index_block_info, is_data, @@ -592,6 +593,7 @@ inline int ObIndexTreeMultiPrefetcher::multi_prefetch() && ObSSTableMicroBlockState::NEED_SYNC_IO != read_handle.micro_handle_->block_state_))) { ret = OB_ERR_UNEXPECTED; } else if (OB_FAIL(access_ctx_->micro_block_handle_mgr_.get_micro_block_handle( + sstable_->block_file(), access_ctx_, cur_index_info, cur_index_info.is_data_block(), @@ -1609,6 +1611,7 @@ inline int ObIndexTreeMultiPassPrefetcher 0) { if (OB_FAIL(access_ctx_->micro_block_handle_mgr_.prefetch_multi_data_block( + sstable_->block_file(), access_ctx_, micro_data_infos_, micro_data_handles_, diff --git a/src/storage/access/ob_micro_block_handle_mgr.cpp b/src/storage/access/ob_micro_block_handle_mgr.cpp index 53cacea81b..c5a868471f 100644 --- a/src/storage/access/ob_micro_block_handle_mgr.cpp +++ b/src/storage/access/ob_micro_block_handle_mgr.cpp @@ -52,6 +52,7 @@ ObMicroBlockDataHandle::~ObMicroBlockDataHandle() } void ObMicroBlockDataHandle::init( + storage_io::BlockOwner &block_file, const MacroBlockId ¯o_id, const int64_t offset, const int64_t size, @@ -59,6 +60,7 @@ void ObMicroBlockDataHandle::init( const int64_t data_checksum, ObMicroBlockHandleMgr *handle_mgr) { + block_file_ = &block_file; macro_block_id_ = macro_id; micro_info_.set(offset, size, logic_micro_id, data_checksum); handle_mgr_ = handle_mgr; @@ -72,6 +74,7 @@ void ObMicroBlockDataHandle::reset() } block_state_ = ObSSTableMicroBlockState::UNKNOWN_STATE; macro_block_id_.reset(); + block_file_ = nullptr; block_index_ = -1; micro_info_.reset(); cache_handle_.reset(); @@ -86,6 +89,7 @@ void ObMicroBlockDataHandle::move_from(ObMicroBlockDataHandle& other) this->macro_block_id_ = other.macro_block_id_; + this->block_file_ = other.block_file_; this->block_state_ = other.block_state_; this->block_index_ = other.block_index_; this->micro_info_ = other.micro_info_; @@ -114,6 +118,7 @@ int ObMicroBlockDataHandle::assign(const ObMicroBlockDataHandle& other) } else { this->macro_block_id_ = other.macro_block_id_; + this->block_file_ = other.block_file_; this->block_state_ = other.block_state_; this->block_index_ = other.block_index_; this->micro_info_ = other.micro_info_; @@ -153,6 +158,8 @@ int ObMicroBlockDataHandle::get_micro_block_data( if (THIS_WORKER.get_timeout_remain() <= 0) { // already timeout, don't retry LOG_INFO("get data block data already timeout", K(ret), K(THIS_WORKER.get_timeout_remain())); + } else if (OB_ISNULL(block_file_)) { + ret = OB_NOT_INIT; } else { //try sync io ObMicroBlockId micro_block_id; @@ -161,7 +168,7 @@ int ObMicroBlockDataHandle::get_micro_block_data( micro_block_id.size_ = micro_info_.size_; is_loaded_block_ = true; if (OB_FAIL(ObStorageCacheSuite::get_instance().get_micro_block_cache(is_data_block).load_block( - micro_block_id, + *block_file_, micro_block_id, des_meta_, micro_info_.logic_micro_id_, micro_info_.data_checksum_, @@ -410,6 +417,7 @@ int ObMicroBlockHandleMgr::init(const bool enable_prefetch_limiting, ObTableScan } int ObMicroBlockHandleMgr::get_micro_block_handle( + storage_io::BlockOwner &block_file, ObTableAccessContext *access_ctx, ObMicroIndexInfo &index_block_info, const bool is_data_block, @@ -433,7 +441,7 @@ int ObMicroBlockHandleMgr::get_micro_block_handle( } else if (OB_ISNULL(idx_header)) { ret = OB_ERR_UNEXPECTED; } else if (OB_FAIL(idx_header->fill_micro_des_meta(micro_block_handle.des_meta_))) { - } else if (FALSE_IT(micro_block_handle.init(macro_id, offset, size, index_block_info.get_logic_micro_id(), + } else if (FALSE_IT(micro_block_handle.init(block_file, macro_id, offset, size, index_block_info.get_logic_micro_id(), index_block_info.get_data_checksum(), this))) { } else if (OB_LIKELY(nullptr != ps_node) && OB_SUCC(ps_node->access_mem_ptr(micro_block_handle.cache_handle_))) { @@ -468,6 +476,7 @@ int ObMicroBlockHandleMgr::get_micro_block_handle( } int ObMicroBlockHandleMgr::prefetch_multi_data_block( + storage_io::BlockOwner &block_file, ObTableAccessContext *access_ctx, const ObMicroIndexInfo *micro_data_infos, ObMicroBlockDataHandle *micro_data_handles, @@ -485,7 +494,7 @@ int ObMicroBlockHandleMgr::prefetch_multi_data_block( if (1 == multi_io_params.count()) { for (int64_t i = 0; OB_SUCC(ret) && i < multi_io_params.count(); i++) { const ObMicroIndexInfo &index_info = micro_data_infos[multi_io_params.prefetch_idx_[i] % max_micro_handle_cnt]; - if (OB_FAIL(data_block_cache_->prefetch(macro_id, index_info, true, + if (OB_FAIL(data_block_cache_->prefetch(block_file, macro_id, index_info, true, macro_handle, &block_io_allocator_))) { } else { ObMicroBlockDataHandle µ_handle = micro_data_handles[multi_io_params.prefetch_idx_[i] % max_micro_handle_cnt]; @@ -497,7 +506,7 @@ int ObMicroBlockHandleMgr::prefetch_multi_data_block( REALTIME_MONITOR_ADD_IO_READ_BYTES(access_ctx, index_info.get_block_size()); } } - } else if (OB_FAIL(data_block_cache_->prefetch_multi_block(macro_id, + } else if (OB_FAIL(data_block_cache_->prefetch_multi_block(block_file, macro_id, multi_io_params, true, /* use_cache */ macro_handle))) { @@ -542,7 +551,7 @@ int ObMicroBlockHandleMgr::submit_async_io( micro_block_handle.block_state_ = ObSSTableMicroBlockState::NEED_MULTI_IO; ret = OB_SUCCESS; // continue and use prefetch in batch later - } else if (OB_FAIL(cache->prefetch(macro_id, index_block_info, use_cache, + } else if (OB_FAIL(cache->prefetch(*micro_block_handle.block_file_, macro_id, index_block_info, use_cache, macro_handle, &block_io_allocator_))) { } else { micro_block_handle.block_state_ = ObSSTableMicroBlockState::IN_BLOCK_IO; diff --git a/src/storage/access/ob_micro_block_handle_mgr.h b/src/storage/access/ob_micro_block_handle_mgr.h index b8e3d8cfd1..6bb565ce54 100644 --- a/src/storage/access/ob_micro_block_handle_mgr.h +++ b/src/storage/access/ob_micro_block_handle_mgr.h @@ -18,7 +18,6 @@ #define OB_MICRO_BLOCK_HANDLE_MGR_H_ #include "data_plane/access/ob_tablet_scan.h" -#include "storage/blocksstable/ob_block_manager.h" #include "storage/blocksstable/ob_block_sstable_struct.h" #include "storage/blocksstable/ob_imicro_block_reader.h" #include "storage/blocksstable/ob_macro_block_reader.h" @@ -48,6 +47,7 @@ struct ObMicroBlockDataHandle ObMicroBlockDataHandle(); virtual ~ObMicroBlockDataHandle(); void init( + storage_io::BlockOwner &block_file, const blocksstable::MacroBlockId ¯o_id, const int64_t offset, const int64_t size, @@ -79,6 +79,7 @@ struct ObMicroBlockDataHandle blocksstable::ObMicroBlockDesMeta des_meta_; blocksstable::ObMicroBlockBufferHandle cache_handle_; blocksstable::ObStorageObjectHandle io_handle_; + storage_io::BlockOwner *block_file_ = nullptr; ObMicroBlockHandleMgr *handle_mgr_; ObIAllocator *allocator_; blocksstable::ObMicroBlockData loaded_block_data_; @@ -178,6 +179,7 @@ class ObMicroBlockHandleMgr int init(const bool enable_prefetch_limiting, ObTableScanStoreStat& store_stat, ObTableScanStatistic* scan_stat, ObQueryFlag& query_flag); int get_micro_block_handle( + storage_io::BlockOwner &block_file, ObTableAccessContext *access_ctx, blocksstable::ObMicroIndexInfo &index_block_info, const bool is_data_block, @@ -186,6 +188,7 @@ class ObMicroBlockHandleMgr ObMicroBlockDataHandle µ_block_handle, int16_t cur_level); int prefetch_multi_data_block( + storage_io::BlockOwner &block_file, ObTableAccessContext *access_ctx, const ObMicroIndexInfo *micro_data_infos, ObMicroBlockDataHandle *micro_data_handles, diff --git a/src/storage/access/ob_sstable_row_whole_scanner.cpp b/src/storage/access/ob_sstable_row_whole_scanner.cpp index b734b4e4a6..1290fa4620 100644 --- a/src/storage/access/ob_sstable_row_whole_scanner.cpp +++ b/src/storage/access/ob_sstable_row_whole_scanner.cpp @@ -254,7 +254,7 @@ int ObSSTableRowWholeScanner::open( if (OB_FAIL(ret)) { - } else if (OB_FAIL(ObObjectManager::async_read_object(read_info, scan_handle.macro_io_handle_))) { + } else if (OB_FAIL(scan_handle.macro_io_handle_.async_read(sstable_->block_file(), read_info))) { } else { ++prefetch_macro_cursor_; is_macro_prefetch_end_ = true; @@ -387,7 +387,7 @@ int ObSSTableRowWholeScanner::prefetch() if (OB_FAIL(ret)) { - } else if (OB_FAIL(ObObjectManager::async_read_object(read_info, scan_handle.macro_io_handle_))) { + } else if (OB_FAIL(scan_handle.macro_io_handle_.async_read(sstable_->block_file(), read_info))) { } else { ++prefetch_macro_cursor_; } diff --git a/src/storage/blocksstable/index_block/ob_clustered_index_block_writer.cpp b/src/storage/blocksstable/index_block/ob_clustered_index_block_writer.cpp index 778a69400e..f74078b01d 100644 --- a/src/storage/blocksstable/index_block/ob_clustered_index_block_writer.cpp +++ b/src/storage/blocksstable/index_block/ob_clustered_index_block_writer.cpp @@ -16,6 +16,7 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_clustered_index_block_writer.h" #include "storage/blocksstable/index_block/ob_index_block_builder.h" @@ -251,7 +252,7 @@ int ObClusteredIndexBlockWriter::rewrite_and_append_clustered_index_micro_block( read_info.io_desc_.set_sys_module_id(ObIOModule::SSTABLE_INDEX_BUILDER_IO); read_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000L; - if (OB_FAIL(ObObjectManager::read_object(read_info, object_handle))) { + if (OB_FAIL(object_handle.read(data_store_desc_->block_file(), read_info))) { } } // Make clustered index micro block. diff --git a/src/storage/blocksstable/index_block/ob_index_block_builder.cpp b/src/storage/blocksstable/index_block/ob_index_block_builder.cpp index 6dfde9df6b..116524fa32 100644 --- a/src/storage/blocksstable/index_block/ob_index_block_builder.cpp +++ b/src/storage/blocksstable/index_block/ob_index_block_builder.cpp @@ -16,7 +16,7 @@ #define USING_LOG_PREFIX STORAGE -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_index_block_builder.h" #include "share/rc/ob_server_runtime.h" @@ -221,6 +221,8 @@ ObSSTableMergeRes::ObSSTableMergeRes() ObMemAttr attr("SSTMrgeResArr", ObCtxIds::MERGE_RESERVE_CTX_ID); data_block_ids_.set_attr(attr); other_block_ids_.set_attr(attr); + data_block_holds_.set_attr(attr); + other_block_holds_.set_attr(attr); data_column_checksums_.set_attr(attr); } } @@ -229,18 +231,9 @@ ObSSTableMergeRes::~ObSSTableMergeRes() { reset(); } void ObSSTableMergeRes::reset() { - int ret = OB_SUCCESS; - for (int64_t i = 0; i < data_block_ids_.count(); ++i) { - const MacroBlockId &block_id = data_block_ids_.at(i); - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(block_id))) { - } - } + data_block_holds_.destroy(); + other_block_holds_.destroy(); data_block_ids_.destroy(); - for (int64_t i = 0; i < other_block_ids_.count(); ++i) { - const MacroBlockId &block_id = other_block_ids_.at(i); - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(block_id))) { - } - } other_block_ids_.destroy(); index_blocks_cnt_ = 0; data_blocks_cnt_ = 0; @@ -302,34 +295,12 @@ int ObSSTableMergeRes::assign(const ObSSTableMergeRes &src) root_row_store_type_ = src.root_row_store_type_; root_macro_seq_ = src.root_macro_seq_; - if (OB_FAIL(data_block_ids_.reserve(src.data_block_ids_.count()))) { - } else { - for (int64_t i = 0; OB_SUCC(ret) && i < src.data_block_ids_.count(); - ++i) { - const MacroBlockId &block_id = src.data_block_ids_.at(i); - if (OB_FAIL(data_block_ids_.push_back(block_id))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(block_id))) { - data_block_ids_.pop_back(); // pop if inc_ref failed - STORAGE_LOG(ERROR, "failed to inc macro block ref cnt", K(ret), - "macro id", block_id); - } - } - } - if (OB_FAIL(ret)) { - } else if (OB_FAIL( - other_block_ids_.reserve(src.other_block_ids_.count()))) { - } else { - for (int64_t i = 0; OB_SUCC(ret) && i < src.other_block_ids_.count(); - ++i) { - const MacroBlockId &block_id = src.other_block_ids_.at(i); - if (OB_FAIL(other_block_ids_.push_back(block_id))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(block_id))) { - other_block_ids_.pop_back(); // pop if inc_ref failed - STORAGE_LOG(ERROR, "failed to inc macro block ref cnt", K(ret), - "macro id", block_id); - } - } + if (OB_FAIL(data_block_ids_.assign(src.data_block_ids_))) { + } else if (OB_FAIL(other_block_ids_.assign(src.other_block_ids_))) { + } else if (OB_FAIL(data_block_holds_.assign(src.data_block_holds_))) { + } else if (OB_FAIL(other_block_holds_.assign(src.other_block_holds_))) { } + if (OB_FAIL(ret)) { reset(); } } return ret; } @@ -662,6 +633,7 @@ int ObSSTableIndexBuilder::trim_empty_roots() } int ObSSTableIndexBuilder::ObMacroMetaIter::init( + storage_io::BlockOwner &blocks, common::ObIAllocator &allocator, IndexTreeRootCtxList &roots, const int64_t meta_row_column_count, @@ -671,7 +643,7 @@ int ObSSTableIndexBuilder::ObMacroMetaIter::init( if (IS_INIT) { ret = OB_INIT_TWICE; STORAGE_LOG(WARN, "Init twice", K(ret)); - } else if (OB_FAIL(index_block_loader_.init(allocator, data_version))) { + } else if (OB_FAIL(index_block_loader_.init(blocks, allocator, data_version))) { } else if (OB_FAIL(meta_row_.init(allocator, meta_row_column_count))) { } else { for (int64_t i = 0; OB_SUCC(ret) && i < roots.count(); ++i) { @@ -736,7 +708,7 @@ int ObSSTableIndexBuilder::init_meta_iter(common::ObIAllocator &allocator, ObMac STORAGE_LOG(WARN, "invalid sstable builder", K(ret), K_(is_inited)); } else if (OB_FAIL(trim_empty_roots())) { } else if (OB_FAIL(sort_roots())) { - } else if (OB_FAIL(iter.init(allocator, + } else if (OB_FAIL(iter.init(data_store_desc_.get_desc().block_file(), allocator, roots_, container_store_desc_.get_row_column_count(), data_version))) { @@ -814,7 +786,7 @@ int ObSSTableIndexBuilder::merge_index_tree( if (OB_FAIL(ret)) { } else if (OB_FAIL(index_builder_.close(self_allocator_, tree_info))) { } else if (OB_FAIL(macro_writer_.close())) { - } else if (OB_FAIL(macro_writer_.get_macro_block_write_ctx().get_macro_id_array(res.other_block_ids_))) { + } else if (OB_FAIL(macro_writer_.get_macro_block_write_ctx().append_blocks(res.other_block_ids_, res.other_block_holds_))) { } else { macro_seq = macro_writer_.get_last_macro_seq(); res.index_blocks_cnt_ += macro_writer_.get_macro_block_write_ctx().macro_block_list_.count(); @@ -905,13 +877,13 @@ int ObSSTableIndexBuilder::merge_index_tree_from_meta_block(ObSSTableMergeRes &r ret = OB_ERR_UNEXPECTED; STORAGE_LOG(WARN, "unexpected clustered index write ctx", K(ret), KP(clustered_index_write_ctx)); } else if (FALSE_IT(res.index_blocks_cnt_ += clustered_index_write_ctx->get_macro_block_count())) { - } else if (OB_FAIL(clustered_index_write_ctx->get_macro_id_array(res.other_block_ids_))) { + } else if (OB_FAIL(clustered_index_write_ctx->append_blocks(res.other_block_ids_, res.other_block_holds_))) { } } } if (OB_SUCC(ret)) { - if (OB_FAIL(write_ctx->get_macro_id_array(res.data_block_ids_))) { + if (OB_FAIL(write_ctx->append_blocks(res.data_block_ids_, res.data_block_holds_))) { } else { res.use_old_macro_block_count_ += write_ctx->use_old_macro_block_count_; } @@ -1011,7 +983,7 @@ int ObSSTableIndexBuilder::build_meta_tree_from_meta_block(ObSSTableMergeRes &re } else if (roots_[i]->meta_block_info_.need_rewrite_ && OB_FAIL(roots_[i]->meta_block_info_.block_write_ctx_->pop_macro_block_id(macro_block_id))) { STORAGE_LOG(WARN, "fail to pop macro id of rewrite block", K(ret), K(macro_block_id)); - } else if (OB_FAIL(roots_[i]->meta_block_info_.block_write_ctx_->get_macro_id_array(res.other_block_ids_))) { + } else if (OB_FAIL(roots_[i]->meta_block_info_.block_write_ctx_->append_blocks(res.other_block_ids_, res.other_block_holds_))) { } else { res.index_blocks_cnt_ += roots_[i]->meta_block_info_.block_write_ctx_->macro_block_list_.count(); } @@ -1067,7 +1039,7 @@ int ObSSTableIndexBuilder::build_meta_tree( res.nested_size_, res.nested_offset_, res.data_root_desc_))) { } else if (OB_FAIL(macro_writer_.close())) { - } else if (OB_FAIL(macro_writer_.get_macro_block_write_ctx().get_macro_id_array(res.other_block_ids_))) { + } else if (OB_FAIL(macro_writer_.get_macro_block_write_ctx().append_blocks(res.other_block_ids_, res.other_block_holds_))) { } else { macro_seq = macro_writer_.get_last_macro_seq(); res.index_blocks_cnt_ += macro_writer_.get_macro_block_write_ctx().macro_block_list_.count(); @@ -1152,7 +1124,7 @@ int ObSSTableIndexBuilder::fsync_block() } if (in_array || all_in_mem) { // do nothing - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.fsync_block())) { + } else if (OB_FAIL(convert_block_status(data_store_desc_.get_desc().block_file().sync_blocks()))) { } return ret; } @@ -1203,7 +1175,7 @@ int ObSSTableIndexBuilder::close_with_macro_seq_inner( } else if (OB_UNLIKELY(is_closed_)) { if (OB_FAIL(res.assign(res_))) { } - } else if (OB_FAIL(index_block_loader_.init(load_allocator, data_version))) { + } else if (OB_FAIL(index_block_loader_.init(data_store_desc_.get_desc().block_file(), load_allocator, data_version))) { } else if (OB_FAIL(res.prepare_column_checksum_array(index_store_desc_.get_desc().get_full_stored_col_cnt()))) { } else if (OB_FAIL(trim_empty_roots())) { } else if (OB_UNLIKELY(roots_.empty())) { @@ -1334,8 +1306,8 @@ int ObSSTableIndexBuilder::rewrite_small_sstable(ObSSTableMergeRes &res) row_allocator_, index_block_loader_, container_store_desc_, roots_, macro_meta))) { } else if (FALSE_IT(read_info.macro_block_id_ = macro_meta.val_.macro_id_)) { - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.fsync_block())) { - } else if (OB_FAIL(ObObjectManager::async_read_object(read_info, read_handle))) { + } else if (OB_FAIL(convert_block_status(data_store_desc_.get_desc().block_file().sync_blocks()))) { + } else if (OB_FAIL(read_handle.async_read(data_store_desc_.get_desc().block_file(), read_info))) { } else if (OB_FAIL(read_handle.wait())) { } else { ObSharedMacroBlockMgr *shared_block_mgr = ::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>(); @@ -1381,12 +1353,12 @@ int ObSSTableIndexBuilder::do_check_and_rewrite_sstable(ObBlockInfo &block_info) ObDataMacroBlockMeta macro_meta; ObSSTableMacroBlockHeader macro_header; const char *data_buf = nullptr; - const int64_t macro_block_size = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + const int64_t macro_block_size = OB_DEFAULT_MACRO_BLOCK_SIZE; if (OB_FAIL(get_single_macro_meta(row_allocator_, index_block_loader_, container_store_desc_, roots_, macro_meta))) { } else if (OB_FAIL(load_single_macro_block( - macro_meta, macro_block_size, 0, self_allocator_, data_buf))) { + container_store_desc_.block_file(), macro_meta, macro_block_size, 0, self_allocator_, data_buf))) { } else if (OB_FAIL(parse_macro_header(data_buf, macro_block_size, macro_header))) { } else { roots_[0]->meta_block_offset_ = macro_header.fixed_header_.meta_block_offset_; @@ -1415,6 +1387,7 @@ int ObSSTableIndexBuilder::do_check_and_rewrite_sstable(ObBlockInfo &block_info) } int ObSSTableIndexBuilder::load_single_macro_block( + storage_io::BlockOwner &blocks, const ObDataMacroBlockMeta ¯o_meta, const int64_t nested_size, const int64_t nested_offset, @@ -1439,8 +1412,8 @@ int ObSSTableIndexBuilder::load_single_macro_block( ret = OB_ALLOCATE_MEMORY_FAILED; STORAGE_LOG(WARN, "failed to alloc macro read info buffer", K(ret), K(read_info.size_)); - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.fsync_block())) { - } else if (OB_FAIL(ObObjectManager::async_read_object(read_info, read_handle))) { + } else if (OB_FAIL(convert_block_status(blocks.sync_blocks()))) { + } else if (OB_FAIL(read_handle.async_read(blocks, read_info))) { } else if (OB_FAIL(read_handle.wait())) { } else { MEMCPY(buffer, read_handle.get_buffer(), read_handle.get_data_size()); @@ -2944,7 +2917,7 @@ int ObMetaIndexBlockBuilder::build_single_macro_row_desc( ObSSTableMacroBlockHeader macro_header; const char *data_buf = nullptr; if (OB_FAIL(ObSSTableIndexBuilder::load_single_macro_block( - macro_meta, nested_size, nested_offset, allocator, data_buf))) { + index_store_desc_->block_file(), macro_meta, nested_size, nested_offset, allocator, data_buf))) { } else if (OB_FAIL(ObSSTableIndexBuilder::parse_macro_header( data_buf, nested_size, macro_header))) { } else { @@ -3398,7 +3371,7 @@ int ObIndexBlockRebuilder::inner_append_macro_row( } else { lib::ObMutexGuard guard(mutex_); // callers may append concurrently if (OB_FAIL(add_macro_block_meta(macro_meta))) { - } else if (OB_FAIL(data_write_ctx_.add_macro_block_id(macro_meta.val_.macro_id_))) { + } else if (OB_FAIL(data_write_ctx_.add_macro_block_id(index_store_desc_->block_file(), macro_meta.val_.macro_id_))) { } else if (index_tree_root_ctx_->use_absolute_offset() && OB_FAIL(index_tree_root_ctx_->add_absolute_row_offset(abs_offset))) { STORAGE_LOG(WARN, "failed to add abs row offset", K(ret), K(abs_offset)); } else { diff --git a/src/storage/blocksstable/index_block/ob_index_block_builder.h b/src/storage/blocksstable/index_block/ob_index_block_builder.h index 23ea52a513..21eacdff1b 100644 --- a/src/storage/blocksstable/index_block/ob_index_block_builder.h +++ b/src/storage/blocksstable/index_block/ob_index_block_builder.h @@ -237,6 +237,8 @@ struct ObSSTableMergeRes final ObIndexTreeRootBlockDesc data_root_desc_; common::ObSEArray data_block_ids_; common::ObSEArray other_block_ids_; + common::ObSEArray data_block_holds_; + common::ObSEArray other_block_holds_; int64_t index_blocks_cnt_; int64_t data_blocks_cnt_; int64_t micro_block_cnt_; @@ -538,6 +540,7 @@ class ObSSTableIndexBuilder final {} ~ObMacroMetaIter() = default; int init( + storage_io::BlockOwner &blocks, common::ObIAllocator &allocator, IndexTreeRootCtxList &roots, const int64_t meta_row_column_count, @@ -606,6 +609,7 @@ class ObSSTableIndexBuilder final public: static int load_single_macro_block( + storage_io::BlockOwner &blocks, const ObDataMacroBlockMeta ¯o_meta, const int64_t nested_size, const int64_t nested_offset, diff --git a/src/storage/blocksstable/index_block/ob_index_block_dumper.cpp b/src/storage/blocksstable/index_block/ob_index_block_dumper.cpp index 840f458eb7..c19cc29699 100644 --- a/src/storage/blocksstable/index_block/ob_index_block_dumper.cpp +++ b/src/storage/blocksstable/index_block/ob_index_block_dumper.cpp @@ -16,6 +16,7 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_index_block_dumper.h" #include "storage/blocksstable/index_block/ob_index_block_builder.h" @@ -397,6 +398,7 @@ void ObIndexBlockLoader::reset() data_version_ = 0; macro_id_array_ = nullptr; io_allocator_ = nullptr; + blocks_ = nullptr; is_inited_ = false; } @@ -412,7 +414,8 @@ void ObIndexBlockLoader::reuse() macro_id_array_ = nullptr; } -int ObIndexBlockLoader::init(common::ObIAllocator &allocator, const uint64_t data_version) +int ObIndexBlockLoader::init(storage_io::BlockOwner &blocks, + common::ObIAllocator &allocator, const uint64_t data_version) { int ret = OB_SUCCESS; if (IS_INIT) { @@ -432,6 +435,7 @@ int ObIndexBlockLoader::init(common::ObIAllocator &allocator, const uint64_t dat cur_block_idx_ = -1; prefetch_idx_ = -1; data_version_ = data_version; + blocks_ = &blocks; is_inited_ = true; } } @@ -568,7 +572,7 @@ int ObIndexBlockLoader::prefetch() read_info.offset_ = 0; read_info.size_ = common::OB_DEFAULT_MACRO_BLOCK_SIZE; - if (OB_FAIL(blocksstable::ObObjectManager::async_read_object(read_info, macro_io_handle))) { + if (OB_FAIL(macro_io_handle.async_read(*blocks_, read_info))) { } } else { break; diff --git a/src/storage/blocksstable/index_block/ob_index_block_dumper.h b/src/storage/blocksstable/index_block/ob_index_block_dumper.h index a5ecb90372..8aefd88a4e 100644 --- a/src/storage/blocksstable/index_block/ob_index_block_dumper.h +++ b/src/storage/blocksstable/index_block/ob_index_block_dumper.h @@ -150,7 +150,7 @@ class ObIndexBlockLoader final ~ObIndexBlockLoader(); void reset(); void reuse(); - int init(common::ObIAllocator &allocator, const uint64_t data_version); + int init(storage_io::BlockOwner &blocks, common::ObIAllocator &allocator, const uint64_t data_version); int open(const ObIndexBlockInfo& index_block_info); int get_next_row(ObDatumRow &row); // get micro block only for disk info @@ -189,6 +189,7 @@ class ObIndexBlockLoader final ObIMicroBlockReader *micro_reader_; const ObIndexBlockInfo *index_block_info_; common::ObIArray *macro_id_array_; + storage_io::BlockOwner *blocks_ = nullptr; ObIAllocator *io_allocator_; char *micro_buf_; int64_t curr_block_row_idx_; diff --git a/src/storage/blocksstable/index_block/ob_index_block_tree_cursor.cpp b/src/storage/blocksstable/index_block/ob_index_block_tree_cursor.cpp index 7cd3b43479..ab356e089d 100644 --- a/src/storage/blocksstable/index_block/ob_index_block_tree_cursor.cpp +++ b/src/storage/blocksstable/index_block/ob_index_block_tree_cursor.cpp @@ -16,6 +16,7 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_index_block_tree_cursor.h" @@ -290,6 +291,7 @@ void ObIndexBlockTreeCursor::reset() micro_reader_helper_.reset(); reader_ = nullptr; read_info_ = nullptr; + blocks_ = nullptr; sstable_meta_handle_.reset(); is_inited_ = false; } @@ -320,6 +322,7 @@ int ObIndexBlockTreeCursor::init( = static_cast(sstable_meta_handle_.get_sstable_meta().get_basic_meta().root_row_store_type_); curr_path_item_->row_store_type_ = root_row_store_type; read_info_ = read_info; + blocks_ = &sstable.block_file(); rowkey_column_cnt_ = read_info_->get_rowkey_count(); tree_type_ = tree_type; switch (tree_type) { @@ -1136,7 +1139,7 @@ int ObIndexBlockTreeCursor::load_micro_block_data(const MacroBlockId ¯o_bloc idx_row_header.fill_deserialize_meta(block_des_meta); - if (OB_FAIL(ObObjectManager::read_object(read_info, macro_handle))) { + if (OB_FAIL(macro_handle.read(*blocks_, read_info))) { } else { const char *src_block_buf = macro_handle.get_buffer(); const int64_t src_buf_size = idx_row_header.get_block_size(); diff --git a/src/storage/blocksstable/index_block/ob_index_block_tree_cursor.h b/src/storage/blocksstable/index_block/ob_index_block_tree_cursor.h index 0a297712f0..7c418e578c 100644 --- a/src/storage/blocksstable/index_block/ob_index_block_tree_cursor.h +++ b/src/storage/blocksstable/index_block/ob_index_block_tree_cursor.h @@ -264,6 +264,7 @@ class ObIndexBlockTreeCursor ObDatumRowkey vector_endkey_; ObIndexBlockRowParser idx_row_parser_; const ObITableReadInfo *read_info_; + storage_io::BlockOwner *blocks_ = nullptr; ObSSTableMetaHandle sstable_meta_handle_; bool is_inited_; }; diff --git a/src/storage/blocksstable/index_block/ob_sstable_index_scanner.cpp b/src/storage/blocksstable/index_block/ob_sstable_index_scanner.cpp index 50898bcdbb..1c48343ac3 100644 --- a/src/storage/blocksstable/index_block/ob_sstable_index_scanner.cpp +++ b/src/storage/blocksstable/index_block/ob_sstable_index_scanner.cpp @@ -211,7 +211,8 @@ int ObSSTableIndexBlockLevelScanner::prefetch_root_block(ObSSTable &sstable) return ret; } -int ObSSTableIndexBlockLevelScanner::prefetch_next_index_block(ObSSTableIndexBlockLevelScanner &parent_scanner) +int ObSSTableIndexBlockLevelScanner::prefetch_next_index_block( + storage_io::BlockOwner &block_file, ObSSTableIndexBlockLevelScanner &parent_scanner) { int ret = OB_SUCCESS; ObMicroIndexInfo idx_block_row; @@ -236,11 +237,12 @@ int ObSSTableIndexBlockLevelScanner::prefetch_next_index_block(ObSSTableIndexBlo ObIndexMicroBlockCache &index_block_cache = ObStorageCacheSuite::get_instance().get_index_block_cache(); prefetch_handle.reset(); prefetch_handle.allocator_ = io_allocator_; + prefetch_handle.block_file_ = &block_file; if (OB_FAIL(index_block_cache.get_cache_block(key, prefetch_handle.cache_handle_))) { // prefetch on cache miss if (OB_UNLIKELY(OB_ENTRY_NOT_EXIST != ret)) { } else if (OB_FAIL(index_block_cache.prefetch( - idx_block_row.get_macro_id(), + block_file, idx_block_row.get_macro_id(), idx_block_row, use_block_cache_, prefetch_handle.io_handle_, @@ -503,7 +505,7 @@ int ObSSTableIndexScanner::advance_to(const ObDatumRowkey &rowkey, const bool in ret = OB_ERR_UNEXPECTED; } else if (!curr_scanner->can_prefetch_next_block() || parent_scanner->is_iter_end()) { // skip prefetch - } else if (OB_FAIL(curr_scanner->prefetch_next_index_block(*parent_scanner))) { + } else if (OB_FAIL(curr_scanner->prefetch_next_index_block(sstable_->block_file(), *parent_scanner))) { } } } @@ -523,7 +525,7 @@ int ObSSTableIndexScanner::try_prefetch() } while (OB_SUCC(ret) && curr_scanner->can_prefetch_next_block() && !parent_scanner->is_iter_end()) { - if (OB_FAIL(curr_scanner->prefetch_next_index_block(*parent_scanner))) { + if (OB_FAIL(curr_scanner->prefetch_next_index_block(sstable_->block_file(), *parent_scanner))) { } } } @@ -579,7 +581,7 @@ int ObSSTableIndexScanner::init_level_scanners( } else if (0 == i) { if (OB_FAIL(level_scanner->prefetch_root_block(sstable))) { } - } else if (OB_FAIL(level_scanner->prefetch_next_index_block(*level_scanners_.at(i - 1)))) { + } else if (OB_FAIL(level_scanner->prefetch_next_index_block(sstable.block_file(), *level_scanners_.at(i - 1)))) { } } diff --git a/src/storage/blocksstable/index_block/ob_sstable_index_scanner.h b/src/storage/blocksstable/index_block/ob_sstable_index_scanner.h index a22c25cbb4..278187f5a2 100644 --- a/src/storage/blocksstable/index_block/ob_sstable_index_scanner.h +++ b/src/storage/blocksstable/index_block/ob_sstable_index_scanner.h @@ -108,7 +108,8 @@ class ObSSTableIndexBlockLevelScanner final ObIAllocator &io_allocator); int get_next_row(ObMicroIndexInfo &index_row); int prefetch_root_block(ObSSTable &sstable); - int prefetch_next_index_block(ObSSTableIndexBlockLevelScanner &parent_scanner); + int prefetch_next_index_block(storage_io::BlockOwner &block_file, + ObSSTableIndexBlockLevelScanner &parent_scanner); int advance_to(const ObDatumRowkey &rowkey, const bool inclusive); bool can_prefetch_next_block() const { return prefetch_idx_ - read_idx_ < prefetch_depth_ - 1; } bool is_iter_end() const { return iter_end_; } diff --git a/src/storage/blocksstable/index_block/ob_sstable_meta_info.cpp b/src/storage/blocksstable/index_block/ob_sstable_meta_info.cpp index e2b35a5594..b6ace1c741 100644 --- a/src/storage/blocksstable/index_block/ob_sstable_meta_info.cpp +++ b/src/storage/blocksstable/index_block/ob_sstable_meta_info.cpp @@ -16,6 +16,7 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_sstable_meta_info.h" #include "storage/blocksstable/ob_macro_block_reader.h" @@ -72,6 +73,7 @@ int ObRootBlockInfo::serialize(char *buf, const int64_t buf_len, int64_t &pos) c } int ObRootBlockInfo::deserialize( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta, const char *buf, @@ -93,7 +95,7 @@ int ObRootBlockInfo::deserialize( if (OB_FAIL(ret)) { } else if (OB_UNLIKELY(version != ROOT_BLOCK_INFO_VERSION)) { ret = OB_NOT_SUPPORTED; - } else if (OB_FAIL(deserialize_(allocator, des_meta, buf + pos, data_len, tmp_pos))) { + } else if (OB_FAIL(deserialize_(blocks, allocator, des_meta, buf + pos, data_len, tmp_pos))) { } else if (OB_UNLIKELY(len != tmp_pos)) { ret = OB_ERR_UNEXPECTED; } else { @@ -162,6 +164,7 @@ int ObRootBlockInfo::init_root_block_info( } int ObRootBlockInfo::load_root_block_data( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta) { @@ -176,7 +179,7 @@ int ObRootBlockInfo::load_root_block_data( const ObMemAttr mem_attr("RootBlkInfo"); if (OB_ISNULL(orig_buf = static_cast(ob_malloc(addr_.size(), mem_attr)))) { ret = OB_ALLOCATE_MEMORY_FAILED; - } else if (OB_FAIL(read_block_data(addr_, orig_buf, addr_.size()))) { + } else if (OB_FAIL(read_block_data(blocks, addr_, orig_buf, addr_.size()))) { } else { ObMacroBlockReader reader; bool is_compressed = false; @@ -227,6 +230,7 @@ int ObRootBlockInfo::transform_root_block_extra_buf(common::ObArenaAllocator &al } int ObRootBlockInfo::read_block_data( + storage_io::BlockOwner &blocks, const storage::ObMetaDiskAddr &addr, char *buf, const int64_t buf_len) @@ -235,8 +239,8 @@ int ObRootBlockInfo::read_block_data( if (OB_UNLIKELY(!addr.is_valid()) || OB_UNLIKELY(!addr.is_block()) || OB_UNLIKELY(buf_len < addr.size()) - || OB_UNLIKELY(addr.offset() >=OB_STORAGE_OBJECT_MGR.get_macro_block_size()) - || OB_UNLIKELY(0 == addr.size() || addr.size() >OB_STORAGE_OBJECT_MGR.get_macro_block_size()) + || OB_UNLIKELY(addr.offset() >=OB_DEFAULT_MACRO_BLOCK_SIZE) + || OB_UNLIKELY(0 == addr.size() || addr.size() >OB_DEFAULT_MACRO_BLOCK_SIZE) || OB_ISNULL(buf)) { ret = OB_INVALID_ARGUMENT; } else { @@ -248,7 +252,7 @@ int ObRootBlockInfo::read_block_data( read_info.io_desc_.set_sys_module_id(ObIOModule::ROOT_BLOCK_IO); if (OB_FAIL(addr.get_block_addr(read_info.macro_block_id_, read_info.offset_, read_info.size_))) { - } else if (OB_FAIL(ObObjectManager::read_object(read_info, handle))) { + } else if (OB_FAIL(handle.read(blocks, read_info))) { } else { MEMCPY(buf, handle.get_buffer(), handle.get_data_size()); } @@ -286,6 +290,7 @@ int ObRootBlockInfo::serialize_( } int ObRootBlockInfo::deserialize_( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta, const char *buf, @@ -311,7 +316,7 @@ int ObRootBlockInfo::deserialize_( char *orig_buf = nullptr; if (OB_ISNULL(orig_buf = static_cast(ob_malloc(addr_.size(), mem_attr)))) { ret = OB_ALLOCATE_MEMORY_FAILED; - } else if (OB_FAIL(read_block_data(addr_, orig_buf, addr_.size()))) { + } else if (OB_FAIL(read_block_data(blocks, addr_, orig_buf, addr_.size()))) { } else { ObMacroBlockReader reader; bool is_compressed = false; @@ -464,7 +469,7 @@ ObMacroIdIterator::ObMacroIdIterator() { } -int ObMacroIdIterator::init(const Type type, const MacroBlockId &entry_id, const int64_t pos) +int ObMacroIdIterator::init(storage_io::BlockOwner &blocks, const Type type, const MacroBlockId &entry_id, const int64_t pos) { int ret = OB_SUCCESS; MacroBlockId *data_blk_ids = nullptr; @@ -475,7 +480,7 @@ int ObMacroIdIterator::init(const Type type, const MacroBlockId &entry_id, const ret = OB_INIT_TWICE; } else if (OB_UNLIKELY(type >= Type::MAX || !entry_id.is_valid() || pos < 0 || count_ < 0)) { ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(ObSSTableMacroInfo::read_block_ids(entry_id, allocator_, data_blk_ids, + } else if (OB_FAIL(ObSSTableMacroInfo::read_block_ids(blocks, entry_id, allocator_, data_blk_ids, data_blk_cnt, other_blk_ids, other_blk_cnt))) { } else { if (Type::DATA_BLOCK == type) { @@ -560,6 +565,7 @@ ObSSTableMacroInfo::~ObSSTableMacroInfo() } int ObSSTableMacroInfo::init_macro_info( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const storage::ObTabletCreateSSTableParam ¶m) { @@ -593,6 +599,7 @@ int ObSSTableMacroInfo::init_macro_info( if (OB_FAIL(ret)) { reset(); } else { + blocks_ = &blocks; is_meta_root_ = param.is_meta_root_; nested_offset_ = param.nested_offset_; nested_size_ = 0 == param.nested_size_ ? OB_DEFAULT_MACRO_BLOCK_SIZE : param.nested_size_; @@ -601,10 +608,11 @@ int ObSSTableMacroInfo::init_macro_info( } int ObSSTableMacroInfo::load_root_block_data( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta) { - return macro_meta_info_.load_root_block_data(allocator, des_meta); + return macro_meta_info_.load_root_block_data(blocks, allocator, des_meta); } bool ObSSTableMacroInfo::is_valid() const @@ -614,6 +622,7 @@ bool ObSSTableMacroInfo::is_valid() const void ObSSTableMacroInfo::reset() { + blocks_ = nullptr; macro_meta_info_.reset(); if (nullptr != data_block_ids_) { for (int64_t i = 0; i < data_block_count_; i++) { @@ -695,7 +704,7 @@ int ObSSTableMacroInfo::persist_block_ids( for (int64_t i = 0; OB_SUCC(ret) && i < block_writer.get_meta_block_list().count(); i++) { - if (OB_FAIL(linked_block_write_ctx.add_object_id(block_writer.get_meta_block_list().at(i)))) { + if (OB_FAIL(linked_block_write_ctx.add_object_id(*blocks_, block_writer.get_meta_block_list().at(i)))) { } } if (OB_SUCC(ret)) { @@ -711,32 +720,13 @@ int ObSSTableMacroInfo::persist_block_ids( LOG_WARN("fail to close block_writer", K(tmp_ret)); } for (int64_t i = 0; i < block_writer.get_meta_block_list().count(); ++i) { - if (OB_TMP_FAIL(linked_block_write_ctx.add_object_id(block_writer.get_meta_block_list().at(i)))) { + if (OB_TMP_FAIL(linked_block_write_ctx.add_object_id(*blocks_, block_writer.get_meta_block_list().at(i)))) { } } } return ret; } -void ObSSTableMacroInfo::dec_linked_block_ref_cnt() -{ - int ret = OB_SUCCESS; - int64_t idx = 0; - if (0 == linked_block_count_) { - // skip the decrease - } else if (OB_ISNULL(linked_block_ids_)) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("linked_block_ids is null, but linked_block_count_ is not 0", K(linked_block_count_)); - } else { - for (; idx < linked_block_count_; idx++) { - const MacroBlockId ¯o_id = linked_block_ids_[idx]; - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } - } - } -} - - int ObSSTableMacroInfo::save_linked_block_list( const common::ObIArray &list, common::ObArenaAllocator &allocator) @@ -757,6 +747,7 @@ int ObSSTableMacroInfo::save_linked_block_list( } int ObSSTableMacroInfo::deserialize( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta, const char *buf, @@ -780,10 +771,11 @@ int ObSSTableMacroInfo::deserialize( ret = OB_NOT_SUPPORTED; } else if (OB_UNLIKELY(data_len - pos < len)) { ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(deserialize_(allocator, des_meta, buf + pos, len, tmp_pos))) { + } else if (OB_FAIL(deserialize_(blocks, allocator, des_meta, buf + pos, len, tmp_pos))) { } else if (OB_UNLIKELY(len != tmp_pos)) { ret = OB_ERR_UNEXPECTED; } else { + blocks_ = &blocks; pos += tmp_pos; } } @@ -791,6 +783,7 @@ int ObSSTableMacroInfo::deserialize( } int ObSSTableMacroInfo::deserialize_( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta, const char *buf, @@ -800,7 +793,7 @@ int ObSSTableMacroInfo::deserialize_( int ret = OB_SUCCESS; nested_size_ = OB_DEFAULT_MACRO_BLOCK_SIZE; - if (OB_FAIL(macro_meta_info_.deserialize(allocator, des_meta, buf, data_len, pos))) { + if (OB_FAIL(macro_meta_info_.deserialize(blocks, allocator, des_meta, buf, data_len, pos))) { } else if (OB_FAIL(entry_id_.deserialize(buf, data_len, pos))) { } else if (!entry_id_.is_empty_list_entry()) { ObLinkedMacroBlockItemReader block_reader; @@ -809,7 +802,7 @@ int ObSSTableMacroInfo::deserialize_( int64_t pos = 0; int64_t reader_len = 0; ObMemAttr mem_attr("SSTableBlockId"); - if (OB_FAIL(block_reader.init(entry_id_, mem_attr))) { + if (OB_FAIL(block_reader.init(blocks, entry_id_, mem_attr))) { } else if (OB_FAIL(block_reader.get_next_item(reader_buf, reader_len, addr))) { } else if (OB_FAIL(serialization::decode(reader_buf, reader_len, pos, data_block_count_))) { } else if (OB_FAIL(block_reader.get_next_item(reader_buf, reader_len, addr))) { @@ -835,6 +828,7 @@ int ObSSTableMacroInfo::deserialize_( } int ObSSTableMacroInfo::read_block_ids( + storage_io::BlockOwner &blocks, const MacroBlockId &entry_id, common::ObArenaAllocator &allocator, MacroBlockId *&data_blk_ids, @@ -847,7 +841,7 @@ int ObSSTableMacroInfo::read_block_ids( ObMemAttr mem_attr("SSTableBlockId"); if (OB_UNLIKELY(!entry_id.is_valid())) { ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(block_reader.init(entry_id, mem_attr))) { + } else if (OB_FAIL(block_reader.init(blocks, entry_id, mem_attr))) { } else if (OB_FAIL(read_block_ids(allocator, block_reader, data_blk_ids, data_blk_cnt, other_blk_ids, other_blk_cnt))) { } @@ -894,7 +888,7 @@ int ObSSTableMacroInfo::get_data_block_iter(ObMacroIdIterator &iterator) const if (entry_id_.is_empty_list_entry()) { if (OB_FAIL(iterator.init(data_block_ids_, data_block_count_))) { } - } else if (OB_FAIL(iterator.init(ObMacroIdIterator::DATA_BLOCK, entry_id_))) { + } else if (OB_FAIL(iterator.init(*blocks_, ObMacroIdIterator::DATA_BLOCK, entry_id_))) { } return ret; } @@ -905,7 +899,7 @@ int ObSSTableMacroInfo::get_other_block_iter(ObMacroIdIterator &iterator) const if (entry_id_.is_empty_list_entry()) { if (OB_FAIL(iterator.init(other_block_ids_, other_block_count_))) { } - } else if (OB_FAIL(iterator.init(ObMacroIdIterator::OTHER_BLOCK, entry_id_))) { + } else if (OB_FAIL(iterator.init(*blocks_, ObMacroIdIterator::OTHER_BLOCK, entry_id_))) { } return ret; } @@ -953,7 +947,7 @@ int ObSSTableMacroInfo::write_block_ids( OB_UNLIKELY((0 != data_block_count_ && OB_ISNULL(data_block_ids_)) || OB_UNLIKELY((0 != other_block_count_ && OB_ISNULL(other_block_ids_))))) { ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(writer.init(false, ObMemAttr("SSTableBlockId")))) { + } else if (OB_FAIL(writer.init(*blocks_, false, ObMemAttr("SSTableBlockId")))) { } else if (OB_FAIL(flush_ids(data_block_ids_, data_block_count_, writer))) { } else if (OB_FAIL(flush_ids(other_block_ids_, other_block_count_, writer))) { } else if (OB_FAIL(writer.close())) { @@ -1045,6 +1039,7 @@ int ObSSTableMacroInfo::deep_copy( } else { dest.data_block_ids_ = nullptr; } + dest.blocks_ = blocks_; dest.data_block_count_ = data_block_count_; if (OB_NOT_NULL(other_block_ids_)) { dest.other_block_ids_ = reinterpret_cast(buf + pos); diff --git a/src/storage/blocksstable/index_block/ob_sstable_meta_info.h b/src/storage/blocksstable/index_block/ob_sstable_meta_info.h index b85a11b441..4be369541e 100644 --- a/src/storage/blocksstable/index_block/ob_sstable_meta_info.h +++ b/src/storage/blocksstable/index_block/ob_sstable_meta_info.h @@ -24,6 +24,8 @@ #include "storage/blocksstable/ob_block_sstable_struct.h" #include "storage/blocksstable/ob_imicro_block_reader.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace storage @@ -60,6 +62,7 @@ class ObRootBlockInfo final void reset(); int serialize(char *buf, const int64_t buf_len, int64_t &pos) const; int deserialize( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta, const char *buf, @@ -72,6 +75,7 @@ class ObRootBlockInfo final const ObMicroBlockData &block_data, const common::ObRowStoreType row_store_type); int load_root_block_data( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta); int transform_root_block_extra_buf(common::ObArenaAllocator &allocator); @@ -96,11 +100,13 @@ class ObRootBlockInfo final private: static const int64_t ROOT_BLOCK_INFO_VERSION = 1; static int read_block_data( + storage_io::BlockOwner &blocks, const storage::ObMetaDiskAddr &addr, char *buf, const int64_t buf_len); int serialize_(char *buf, const int64_t buf_len, int64_t &pos) const; int deserialize_( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta, const char *buf, @@ -133,7 +139,7 @@ class ObMacroIdIterator final ObMacroIdIterator(); ~ObMacroIdIterator() { reset(); } bool is_valid() const { return is_inited_ && count_ >= 0; } - int init(const Type type, const MacroBlockId &entry_id, const int64_t pos = 0); + int init(storage_io::BlockOwner &blocks, const Type type, const MacroBlockId &entry_id, const int64_t pos = 0); int init(MacroBlockId *ptr, const int64_t count, const int64_t pos = 0); void reset(); int get_next_macro_id(MacroBlockId ¯o_id); @@ -152,15 +158,18 @@ class ObSSTableMacroInfo final ObSSTableMacroInfo(); ~ObSSTableMacroInfo(); int init_macro_info( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const storage::ObTabletCreateSSTableParam ¶m); int load_root_block_data( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta); bool is_valid() const; void reset(); int serialize(char *buf, const int64_t buf_len, int64_t &pos) const; int deserialize( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta, const char *buf, @@ -220,6 +229,7 @@ class ObSSTableMacroInfo final return nested_size_; } static int read_block_ids( + storage_io::BlockOwner &blocks, const MacroBlockId &entry_id, common::ObArenaAllocator &allocator, MacroBlockId *&data_block_ids, @@ -234,6 +244,7 @@ class ObSSTableMacroInfo final private: int serialize_(char *buf, const int64_t buf_len, int64_t &pos) const; int deserialize_( + storage_io::BlockOwner &blocks, common::ObArenaAllocator &allocator, const ObMicroBlockDesMeta &des_meta, const char *buf, @@ -260,7 +271,6 @@ class ObSSTableMacroInfo final int save_linked_block_list( const common::ObIArray &list, common::ObArenaAllocator &allocator); - void dec_linked_block_ref_cnt(); static int deserialize_block_ids( common::ObArenaAllocator &allocator, const char *buf, @@ -283,6 +293,7 @@ class ObSSTableMacroInfo final static const int64_t MACRO_INFO_VERSION = 1; static const int64_t BLOCK_CNT_THRESHOLD = 15000; // 15000 ids, represents 30G data + metadata private: + storage_io::BlockOwner *blocks_ = nullptr; ObRootBlockInfo macro_meta_info_; MacroBlockId *data_block_ids_; MacroBlockId *other_block_ids_; diff --git a/src/storage/blocksstable/index_block/ob_sstable_sec_meta_iterator.cpp b/src/storage/blocksstable/index_block/ob_sstable_sec_meta_iterator.cpp index fac5ee42af..5c77c25a83 100644 --- a/src/storage/blocksstable/index_block/ob_sstable_sec_meta_iterator.cpp +++ b/src/storage/blocksstable/index_block/ob_sstable_sec_meta_iterator.cpp @@ -35,6 +35,7 @@ ObSSTableSecMetaIterator::ObSSTableSecMetaIterator() void ObSSTableSecMetaIterator::reset() { + block_file_ = nullptr; rowkey_read_info_ = nullptr; sstable_meta_hdl_.reset(); @@ -87,6 +88,7 @@ int ObSSTableSecMetaIterator::open( is_inited_ = true; } else if (OB_FAIL(sstable.get_meta(sstable_meta_hdl_))) { } else { + block_file_ = &sstable.block_file(); rowkey_read_info_ = &rowkey_read_info; prefetch_flag_.set_not_use_block_cache(); @@ -449,6 +451,7 @@ int ObSSTableSecMetaIterator::get_micro_block( { int ret = OB_SUCCESS; data_handle.reset(); + data_handle.block_file_ = block_file_; ObTabletHandle tablet_handle; const int64_t nested_offset = sstable_meta_hdl_.get_sstable_meta().get_macro_info().get_nested_offset(); @@ -472,7 +475,7 @@ int ObSSTableSecMetaIterator::get_micro_block( data_handle.allocator_ = &io_allocator_; // TODO: @saitong.zst not safe here, remove tablet_handle from SecMeta prefetch interface, disable cache decoders if (OB_FAIL(block_cache_->prefetch( - macro_id, + *block_file_, macro_id, idx_info, prefetch_flag_.is_use_block_cache(), data_handle.io_handle_, diff --git a/src/storage/blocksstable/index_block/ob_sstable_sec_meta_iterator.h b/src/storage/blocksstable/index_block/ob_sstable_sec_meta_iterator.h index 9afb0367db..3d71a7c59c 100644 --- a/src/storage/blocksstable/index_block/ob_sstable_sec_meta_iterator.h +++ b/src/storage/blocksstable/index_block/ob_sstable_sec_meta_iterator.h @@ -82,6 +82,7 @@ class ObSSTableSecMetaIterator static const int32_t HANDLE_BUFFER_SIZE = 16; static const int32_t MAX_SECONDAY_META_COLUMN_COUNT = OB_MAX_ROWKEY_COLUMN_NUMBER + 3; + storage_io::BlockOwner *block_file_ = nullptr; const ObITableReadInfo *rowkey_read_info_; ObSSTableMetaHandle sstable_meta_hdl_; common::ObQueryFlag prefetch_flag_; diff --git a/src/storage/blocksstable/ob_block_manager.cpp b/src/storage/blocksstable/ob_block_manager.cpp deleted file mode 100644 index d37f3340c7..0000000000 --- a/src/storage/blocksstable/ob_block_manager.cpp +++ /dev/null @@ -1,1395 +0,0 @@ -/* - * Copyright (c) 2025 OceanBase. - * - * 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. - */ - -#define USING_LOG_PREFIX STORAGE_BLKMGR - -#include "rust/file_io.h" -#include "rust/config.h" -#include "ob_block_manager.h" -#include -#include "share/rc/ob_server_runtime.h" -#include "storage/blocksstable/ob_shared_macro_block_manager.h" -#include "storage/meta_mem/ob_storage_meta_mem_mgr.h" -#include "storage/meta_store/storage_meta_service.h" -#include "storage/meta_store/ob_local_storage_meta_service.h" -#include "storage/tablet/ob_tablet_macro_info_iterator.h" - -using namespace oceanbase::common; -using namespace oceanbase::common::hash; -using namespace oceanbase::blocksstable; -using namespace oceanbase::storage; -using namespace oceanbase::share; - - -namespace oceanbase { -namespace blocksstable { -/** - * ------------------------------------ObMacroBlockRewriteSeqGenerator------------------------------------- - */ -ObMacroBlockRewriteSeqGenerator::ObMacroBlockRewriteSeqGenerator() - : rewrite_seq_(0), lock_(common::ObLatchIds::BLOCK_ID_GENERATOR_LOCK) {} - -ObMacroBlockRewriteSeqGenerator::~ObMacroBlockRewriteSeqGenerator() { - rewrite_seq_ = 0; -} - -void ObMacroBlockRewriteSeqGenerator::reset() { rewrite_seq_ = 0; } - -int ObMacroBlockRewriteSeqGenerator::generate_next_sequence(uint64_t &blk_seq) { - int ret = OB_SUCCESS; - SpinWLockGuard guard(lock_); - if (OB_UNLIKELY(MacroBlockId::MAX_WRITE_SEQ == rewrite_seq_)) { - ret = OB_ERROR_OUT_OF_RANGE; - LOG_ERROR("rewrite sequence number overflow!", K(ret), - LITERAL_K(MacroBlockId::MAX_WRITE_SEQ), K(rewrite_seq_)); - } else { - blk_seq = ++rewrite_seq_; - if (OB_UNLIKELY(BLOCK_SEQUENCE_WARNING_LINE < blk_seq)) { - const int64_t remaining_rewritten_block_count = - MacroBlockId::MAX_WRITE_SEQ - blk_seq; - LOG_ERROR("macro block rewrite sequence is close to exhaustion; stop local writes before overflow", - K(remaining_rewritten_block_count)); - } - } - return ret; -} - -/** - * -----------------------------------------ObBlockManager------------------------------------------ - */ -ObBlockManager::ObBlockManager() - : bucket_lock_(), block_map_(), default_block_size_(0), - marker_status_(), marker_lock_(), is_mark_sweep_enabled_(false), - sweep_lock_(), mark_block_task_(*this), inspect_bad_block_task_(*this), - timer_(), bad_block_lock_(), data_file_(storage_io::new_block_owner()), - data_path_{}, initial_file_size_(0), disk_percentage_(0), blk_seq_generator_(), - alloc_num_(0), is_inited_(false), is_started_(false) {} - -ObBlockManager::~ObBlockManager() { destroy(); } - -int ObBlockManager::prepare_file(const storage_io::ServiceHandle &service, - const char *data_dir, const char *sstable_dir, int64_t block_size, - int64_t initial_size, int64_t disk_percentage, size_t worker_threads, size_t max_depth) -{ - int ret = OB_SUCCESS; - if (data_path_[0] != '\0') { return OB_INIT_TWICE; } - if (data_dir == nullptr || sstable_dir == nullptr || data_dir[0] == '\0' - || sstable_dir[0] == '\0' || STRLEN(sstable_dir) >= OB_MAX_FILE_NAME_LENGTH - || block_size < DIO_READ_ALIGN_SIZE || block_size % DIO_READ_ALIGN_SIZE != 0 - || initial_size < 0 || disk_percentage < 0 || disk_percentage >= 100) { - return OB_INVALID_ARGUMENT; - } - char path[OB_MAX_FILE_NAME_LENGTH]; - if (OB_FAIL(databuff_printf(path, sizeof(path), "%s/%s/%s", - data_dir, BLOCK_SSTBALE_DIR_NAME, BLOCK_SSTBALE_FILE_NAME))) { - return ret; - } - storage_io::ExecutionOptions execution{}; - execution.worker_threads = worker_threads; - execution.max_depth = max_depth; - if (OB_FAIL(convert_storage_error(data_file_->prepare_blocks(service, - {reinterpret_cast(sstable_dir), STRLEN(sstable_dir)}, execution)))) { - return ret; - } - STRNCPY(data_path_, path, sizeof(data_path_)); - default_block_size_ = block_size; - initial_file_size_ = initial_size; - disk_percentage_ = disk_percentage; - return ret; -} - -int ObBlockManager::open_file(int64_t reserved_size) -{ - int ret = OB_SUCCESS; - if (reserved_size < 0) { return OB_INVALID_ARGUMENT; } - const rust::Slice path{ - reinterpret_cast(data_path_), STRLEN(data_path_)}; - storage_io::BlockOptions options{}; - options.block_size = default_block_size_; - options.initial_size = initial_file_size_; - options.initial_percentage = disk_percentage_; - options.reserved_bytes = reserved_size; - options.punch_holes = config::_enable_block_file_punch_hole(); - auto opened = data_file_->open_blocks(path, options); - ret = convert_block_status(opened.status); - if (ret != OB_SUCCESS) { - LOG_WARN("data file open failed", K(ret), K(data_path_), - "native_error", opened.primary_error.native_code, "error", opened.primary_error.message.c_str()); - } - auto &summary = opened.directory_summary; - if (summary.count != 0) { - LOG_WARN("directory durability unconfirmed; only first failure detail retained", K(ret), - "failed_flush_count", summary.count, "count_is_lower_bound", summary.count == UINT64_MAX, - "first_path", ObString(static_cast(summary.first_path.size()), - reinterpret_cast(summary.first_path.data())), - "native_error", summary.first_error.native_code, "error", summary.first_error.message.c_str()); - } - if (opened.sync.stage != file_io::SyncStage::Complete) { - LOG_WARN("data file creation directory sync failed", K(ret), K(data_path_), - "stage", static_cast(opened.sync.stage), "native_error", opened.sync.primary.native_code, - "error", opened.sync.primary.message.c_str(), "close_error", opened.sync.close.native_code); - } - if (opened.cleanup_close.domain != file_io::ErrorDomain::None - || opened.cleanup_remove.domain != file_io::ErrorDomain::None - || opened.cleanup_sync.stage != file_io::SyncStage::Complete) { - LOG_WARN("data file creation cleanup failed", K(ret), K(data_path_), - "close_error", opened.cleanup_close.native_code, "remove_error", opened.cleanup_remove.native_code, - "sync_error", opened.cleanup_sync.primary.native_code, "sync_close_error", opened.cleanup_sync.close.native_code); - } - return ret; -} - -int ObBlockManager::close_file() -{ - const int ret = convert_storage_error(data_file_->close_blocks()); - if (ret == OB_SUCCESS) { - data_path_[0] = '\0'; - } - return ret; -} - -int ObBlockManager::validate_io_threads(size_t worker_threads) const -{ - return convert_storage_error(data_file_->validate_block_workers(worker_threads)); -} - -int ObBlockManager::fsync_block() -{ - return convert_block_status(data_file_->sync_blocks()); -} - -int ObBlockManager::submit_read(const MacroBlockId &id, int64_t offset, int64_t size, - const ObIOFlag &flag, int64_t timeout_us, - std::unique_ptr callback, ObIOHandle &handle) -{ - handle.reset(); - if (!id.is_valid() || offset < 0 || size <= 0 || !flag.is_valid()) { return OB_INVALID_ARGUMENT; } - const auto options = make_request_options(flag, storage_io::RequestMode::Read, offset, size, timeout_us); - return accept_io_request(data_file_->submit_block(id.block_index(), options, {}, std::move(callback)), handle); -} - -static int64_t handle_io_timeout_us(const int64_t timeout_ms) -{ - return std::min(timeout_ms, config::_data_storage_io_timeout() / 1000L) * 1000L; -} - -int ObBlockManager::submit_handle_read( - const MacroBlockId ¯o_id, const int64_t offset, const int64_t size, - const common::ObIOFlag &flag, const int64_t timeout_ms, - std::unique_ptr callback, common::ObIOHandle &io_handle) -{ - const int64_t timeout_us = handle_io_timeout_us(timeout_ms); - return OB_SERVER_BLOCK_MGR.submit_read( - macro_id, offset, size, flag, timeout_us, std::move(callback), io_handle); -} - -int ObBlockManager::submit_handle_write( - const MacroBlockId ¯o_id, const ObStorageObjectWriteInfo &write_info, - common::ObIOHandle &io_handle) -{ - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!write_info.is_valid())) { - ret = OB_INVALID_ARGUMENT; - } else { - const int64_t timeout_us = handle_io_timeout_us(write_info.io_timeout_ms_); - if (OB_FAIL(OB_SERVER_BLOCK_MGR.submit_write( - macro_id, write_info.offset_, write_info.buffer_, write_info.size_, write_info.io_desc_, - timeout_us, io_handle))) { - } else { - int tmp_ret = OB_SUCCESS; - if (OB_TMP_FAIL(OB_SERVER_BLOCK_MGR.update_write_time(macro_id))) { - } - } - } - return ret; -} - -int ObBlockManager::submit_write(const MacroBlockId &id, int64_t offset, const char *buffer, int64_t size, - const ObIOFlag &flag, int64_t timeout_us, ObIOHandle &handle) -{ - handle.reset(); - if (!id.is_valid() || offset < 0 || buffer == nullptr || size <= 0 || !flag.is_valid()) { - return OB_INVALID_ARGUMENT; - } - const auto options = make_request_options(flag, storage_io::RequestMode::Write, offset, size, timeout_us); - return accept_io_request(data_file_->submit_block(id.block_index(), options, - {reinterpret_cast(buffer), static_cast(size)}, nullptr), handle); -} - -void ObBlockManager::release_block(uint64_t index) -{ - const auto result = data_file_->release_block(index); - const int ret = convert_block_status(result.status); - if (ret != OB_SUCCESS || result.reclamation_error != 0) { - LOG_WARN("block release or reclamation failed", K(ret), K(index), - "reclamation_error", result.reclamation_error, "os_error", result.reclamation_os_error); - } -} - -int ObBlockManager::make_growth_policy(storage_io::BlockGrowth &policy) const -{ - int ret = OB_SUCCESS; - int64_t reserved = 0; - if (OB_FAIL(STORAGE_META_SERVICE.get_reserved_size(reserved))) { - } else { - policy.max_bytes = config::datafile_maxsize(); - policy.next_bytes = config::datafile_next(); - policy.usage_upper_percent = config::_datafile_usage_upper_bound_percentage(); - policy.reserved_bytes = reserved; - } - return ret; -} - -int64_t ObBlockManager::get_max_block_size(int64_t reserved_size) const -{ - uint64_t maximum = 0; - const int64_t configured = std::max(int64_t{0}, config::datafile_maxsize()); - if (reserved_size < 0 || OB_SUCCESS != convert_block_status( - data_file_->maximum_block_capacity(configured, reserved_size, maximum))) { - return get_total_block_size(); - } - return static_cast(maximum); -} - -int ObBlockManager::check_space_full(int64_t required_size, bool alarm_if_space_full) const -{ - if (!is_mark_sweep_enabled()) { return OB_NOT_INIT; } - if (required_size < 0) { return OB_INVALID_ARGUMENT; } - int ret = OB_SUCCESS; - int64_t reserved = 0; - if (OB_FAIL(STORAGE_META_SERVICE.get_reserved_size(reserved))) { return ret; } - ret = convert_block_status(data_file_->check_block_space(required_size, - config::datafile_maxsize(), reserved, config::data_disk_usage_limit_percentage())); - if (ret == OB_SERVER_OUTOF_DISK_SPACE && alarm_if_space_full - && REACH_TIME_INTERVAL(24 * 3600LL * 1000 * 1000)) { - LOG_DBA_ERROR_V2(OB_SHARE_OUTOF_DISK_SPACE, ret, - "disk is almost full. required size is ", required_size, - ". [suggestion] Increase the datafile_size or datafile_disk_percentage parameter. "); - } - return ret; -} - -int ObBlockManager::init(const int64_t block_size) { - int ret = OB_SUCCESS; - if (OB_UNLIKELY(is_inited_)) { - ret = OB_INIT_TWICE; - } else if (data_path_[0] == '\0' || block_size != default_block_size_ - || OB_UNLIKELY(block_size < DIO_READ_ALIGN_SIZE)) { - ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(timer_.set_run_wrapper_with_ret(share::server_runtime()))) { - } else if (OB_FAIL(timer_.init("BlkMgr"))) { - } else if (OB_FAIL(bucket_lock_.init(DEFAULT_LOCK_BUCKET_COUNT, - ObLatchIds::BLOCK_MANAGER_LOCK))) { - } else if (OB_FAIL(block_map_.init( - ObMemAttr("BlockMap")))) { - } else { - default_block_size_ = block_size; - ATOMIC_STORE(&alloc_num_, 0); - is_inited_ = true; - } - - if (IS_NOT_INIT) { - destroy(); - } - return ret; -} - -int ObBlockManager::start(const int64_t reserved_size) { - int ret = OB_SUCCESS; - LOG_DBA_INFO_V2(OB_SERVER_BLOCK_MANAGER_START_BEGIN, - DBA_STEP_INC_INFO(server_start), - "block manager start begin."); - - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else if (OB_FAIL(open_file(reserved_size))) { - } else { - if (!timer_.task_exist(inspect_bad_block_task_)) { - if (OB_FAIL(timer_.schedule(inspect_bad_block_task_, INSPECT_DELAY_US, - true))) { - } - } - if (OB_SUCC(ret) && !timer_.task_exist(mark_block_task_)) { - if (OB_FAIL(timer_.schedule(mark_block_task_, RECYCLE_DELAY_US, true))) { - } - } - if (OB_SUCC(ret) && OB_FAIL(timer_.start())) { - } - } - if (OB_FAIL(ret)) { - LOG_DBA_ERROR_V2(OB_SERVER_BLOCK_MANAGER_START_FAIL, ret, - DBA_STEP_INC_INFO(server_start), - "block manager start fail. ", - "you may find solutions in previous error logs or seek " - "help from official technicians."); - } else { - is_started_ = true; - LOG_INFO("start block manager"); - LOG_DBA_INFO_V2(OB_SERVER_BLOCK_MANAGER_START_SUCCESS, - DBA_STEP_INC_INFO(server_start), - "block manager start success."); - } - - return ret; -} - -void ObBlockManager::stop() { timer_.stop(); } - -void ObBlockManager::wait() { - timer_.wait(); - LOG_INFO("the block manager finish wait"); -} - -void ObBlockManager::destroy() { - timer_.destroy(); - inspect_bad_block_task_.reset(); - bucket_lock_.destroy(); - block_map_.destroy(); - { - lib::ObMutexGuard bad_block_guard(bad_block_lock_); - bad_block_infos_.destroy(); - } - const int close_ret = close_file(); - if (close_ret != OB_SUCCESS) { LOG_ERROR_RET(close_ret, "data file close failed", K(close_ret)); } - default_block_size_ = 0; - is_mark_sweep_enabled_ = false; - marker_status_.reset(); - blk_seq_generator_.reset(); - ATOMIC_STORE(&alloc_num_, 0); - is_inited_ = false; -} - -int ObBlockManager::inner_alloc_block(uint64_t &index) { - storage_io::BlockGrowth policy{}; - const int ret = make_growth_policy(policy); - return ret == OB_SUCCESS - ? convert_block_status(data_file_->allocate_block(policy, index)) : ret; -} - -int ObBlockManager::alloc_object(ObStorageObjectHandle &object_handle) { - int ret = OB_SUCCESS; - MacroBlockId macro_id; - uint64_t block_index = 0; - bool physical_owned = false; - uint64_t write_seq = 0; - - if (IS_NOT_INIT || !is_started()) { - ret = OB_NOT_INIT; - } else if (OB_FAIL(inner_alloc_block(block_index))) { - } else { - physical_owned = true; - } - - if (OB_SUCC(ret)) { - if (OB_FAIL(blk_seq_generator_.generate_next_sequence(write_seq))) { - } else { - macro_id.reset(); - macro_id.set_write_seq(write_seq); - macro_id.set_block_index(block_index); - if (OB_FAIL(object_handle.set_macro_block_id(macro_id))) { - } else { - physical_owned = false; - ATOMIC_AAF(&alloc_num_, 1); - FLOG_INFO("successfully alloc block", K(macro_id)); - } - } - } - if (physical_owned) { release_block(block_index); } - return ret; -} - -int ObBlockManager::alloc_block(ObMacroBlockHandle ¯o_handle) { - int ret = OB_SUCCESS; - uint64_t block_index = 0; - bool physical_owned = false; - uint64_t write_seq = 0; - - if (IS_NOT_INIT || !is_started()) { - ret = OB_NOT_INIT; - } else if (OB_FAIL(inner_alloc_block(block_index))) { - } else { - physical_owned = true; - } - - if (OB_SUCC(ret)) { - if (OB_FAIL(blk_seq_generator_.generate_next_sequence(write_seq))) { - } else { - MacroBlockId macro_id(write_seq, block_index, 0); - if (OB_FAIL(macro_handle.set_macro_block_id(macro_id))) { - } else { - physical_owned = false; - ATOMIC_AAF(&alloc_num_, 1); - FLOG_INFO("successfully alloc block", K(macro_id)); - } - } - } - - if (physical_owned) { - release_block(block_index); - } - return ret; -} - -int ObBlockManager::async_read_block(const ObMacroBlockReadInfo &read_info, - ObMacroBlockHandle ¯o_handle) { - return macro_handle.async_read(read_info); -} - -int ObBlockManager::async_write_block(const ObMacroBlockWriteInfo &write_info, - ObMacroBlockHandle ¯o_handle) { - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!write_info.is_valid())) { - ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.alloc_block(macro_handle))) { - } else if (OB_FAIL(macro_handle.async_write(write_info))) { - } - return ret; -} - -int ObBlockManager::read_block(const ObMacroBlockReadInfo &read_info, - ObMacroBlockHandle ¯o_handle) { - int ret = OB_SUCCESS; - if (OB_FAIL(async_read_block(read_info, macro_handle))) { - } else if (OB_FAIL(macro_handle.wait())) { - } - return ret; -} - -int ObBlockManager::write_block(const ObMacroBlockWriteInfo &write_info, - ObMacroBlockHandle ¯o_handle) { - int ret = OB_SUCCESS; - if (OB_FAIL(async_write_block(write_info, macro_handle))) { - } else if (OB_FAIL(macro_handle.wait())) { - } - return ret; -} - -int ObBlockManager::first_mark_device() { - int ret = OB_SUCCESS; - if (IS_NOT_INIT) { return OB_NOT_INIT; } - if (is_mark_sweep_enabled()) { return OB_INIT_TWICE; } - ret = convert_block_status(data_file_->restart_marking()); - BlockMap::BlurredIterator iter(block_map_); - MacroBlockId id; - BlockInfo info; - uint64_t max_write_sequence = 0; - while (OB_SUCC(ret) && OB_SUCC(ret = iter.next(id, info))) { - if (id.block_index() < 1) { ret = OB_INVALID_DATA; } - else { - const uint64_t index = id.block_index(); - ret = convert_block_status(data_file_->mark_blocks({&index, 1})); - max_write_sequence = std::max(max_write_sequence, id.write_seq()); - } - } - if (ret == OB_ITER_END) { ret = convert_block_status(data_file_->finish_marking()); } - if (OB_SUCC(ret)) { - blk_seq_generator_.update_sequence(max_write_sequence); - enable_mark_sweep(); - storage_io::BlockStats stats{}; - if (convert_block_status(data_file_->block_stats(stats)) == OB_SUCCESS && stats.reclamation_failures > 0) { - LOG_WARN("block reclamation failed during marking", "failures", stats.reclamation_failures); - } - } else { - data_file_->restart_marking(); - } - return ret; -} - -int64_t ObBlockManager::get_max_macro_block_count(int64_t reserved_size) const { - return default_block_size_ > 0 ? get_max_block_size(reserved_size) / default_block_size_ : 0; -} - -int64_t ObBlockManager::get_free_macro_block_count() const { - storage_io::BlockStats stats{}; - return convert_block_status(data_file_->block_stats(stats)) == OB_SUCCESS ? stats.free_blocks : 0; -} - -int64_t ObBlockManager::get_used_macro_block_count() const { - return block_map_.count(); -} - -int64_t ObBlockManager::get_total_block_size() const { - storage_io::BlockStats stats{}; - return convert_block_status(data_file_->block_stats(stats)) == OB_SUCCESS ? stats.capacity : 0; -} - -int ObBlockManager::get_macro_block_info( - const MacroBlockId ¯o_id, ObMacroBlockInfo ¯o_block_info, - ObMacroBlockHandle ¯o_block_handle) { - int ret = OB_SUCCESS; - BlockInfo block_info; - bool has_inc_ref = false; - - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else if (OB_UNLIKELY(!macro_id.is_valid())) { - ret = OB_INVALID_ARGUMENT; - } else { - ObBucketHashWLockGuard lock_guard(bucket_lock_, macro_id.hash()); - if (OB_FAIL(block_map_.get(macro_id, block_info)) && - ret != OB_HASH_NOT_EXIST) { - // BUG, should not happen - LOG_ERROR("fatal error, this block should be in block map", K(ret), - K(macro_id)); - } else if (OB_UNLIKELY(OB_SUCCESS == ret && block_info.ref_cnt_ < 0)) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("fatal error, invalid refcnt", K(ret), K(macro_id), - K(block_info)); - } else if (OB_UNLIKELY(OB_HASH_NOT_EXIST == ret || - 0 == block_info.ref_cnt_)) { - // set `is_free_` to true, skip this MacroBlock in upper layer. - ret = OB_SUCCESS; - macro_block_info.is_free_ = true; - } else { - macro_block_info.is_free_ = false; - macro_block_info.ref_cnt_ = block_info.ref_cnt_; - macro_block_info.access_time_ = block_info.last_write_time_; - block_info.access_time_ = ObTimeUtility::fast_current_time(); - block_info.ref_cnt_++; - if (OB_FAIL(block_map_.insert_or_update(macro_id, block_info))) { - } else { - has_inc_ref = true; - LOG_DEBUG("debug ref_cnt: inc_ref in memory", K(ret), K(macro_id), - K(block_info), K(lbt())); - } - } - } - if (OB_SUCC(ret) && !macro_block_info.is_free_) { - if (OB_FAIL(macro_block_handle.set_macro_block_id(macro_id))) { - } - } - if (has_inc_ref) { - int tmp_ret = OB_SUCCESS; - if (OB_TMP_FAIL(dec_ref(macro_id))) { - } - } - - return ret; -} - -int ObBlockManager::check_macro_block_free(const MacroBlockId ¯o_id, - bool &is_free) const { - int ret = OB_SUCCESS; - is_free = false; - BlockInfo block_info; - - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else if (OB_UNLIKELY(!macro_id.is_valid())) { - ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(block_map_.get(macro_id, block_info))) { - if (OB_ENTRY_NOT_EXIST != ret) { - } else { - is_free = true; - ret = OB_SUCCESS; - } - } else { - is_free = 0 == block_info.ref_cnt_; - } - return ret; -} - -int ObBlockManager::get_bad_block_infos( - common::ObIArray &bad_block_infos) { - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!is_inited_)) { - ret = OB_NOT_INIT; - } else { - lib::ObMutexGuard bad_block_guard(bad_block_lock_); - if (OB_FAIL(bad_block_infos.assign(bad_block_infos_))) { - } - } - return ret; -} - -int ObBlockManager::report_bad_block(const MacroBlockId ¯o_block_id, - const int64_t error_type, - const char *error_msg, - const char *file_path) { - int ret = OB_SUCCESS; - const int64_t MAX_BAD_BLOCK_NUMBER = - std::max(static_cast(10), OB_STORAGE_OBJECT_MGR.get_total_macro_block_count() / 100); - if (OB_UNLIKELY(!is_inited_)) { - ret = OB_NOT_INIT; - } else if (OB_UNLIKELY(!macro_block_id.is_valid() || - OB_TIMEOUT == error_type || NULL == error_msg)) { - ret = OB_INVALID_ARGUMENT; - } else if (is_bad_block(macro_block_id)) { - ret = OB_SUCCESS; // No need to print warn log - LOG_INFO("already found this bad block, ", K(macro_block_id), K(error_type), - K(error_msg)); - } else { - ObBadBlockInfo bad_block_info; - lib::ObMutexGuard bad_block_guard(bad_block_lock_); - if (bad_block_infos_.count() >= MAX_BAD_BLOCK_NUMBER) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(databuff_printf(bad_block_info.error_msg_, - sizeof(bad_block_info.error_msg_), "%s", - error_msg))) { - } else { - STRNCPY(bad_block_info.store_file_path_, file_path, - sizeof(bad_block_info.store_file_path_) - 1); - bad_block_info.disk_id_ = macro_block_id.first_id(); - bad_block_info.macro_block_id_ = macro_block_id; - bad_block_info.error_type_ = error_type; - bad_block_info.check_time_ = ObTimeUtility::current_time(); - if (OB_FAIL(bad_block_infos_.push_back(bad_block_info))) { - } else { - LOG_ERROR("add bad block info", K(bad_block_info)); - } - } - } - return ret; -} - -int ObBlockManager::resize_file(const int64_t new_data_file_size, - const int64_t new_data_file_disk_percentage, - const int64_t reserved_size) { - int ret = OB_SUCCESS; - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else if (OB_UNLIKELY(reserved_size < 0)) { - ret = OB_INVALID_ARGUMENT; - } else if (!is_mark_sweep_enabled()) { - LOG_INFO("mark and sweep is disabled, do not resize file at present"); - } else { - SpinWLockGuard sweep_guard(sweep_lock_); - if (new_data_file_size < 0 || new_data_file_disk_percentage < 0 - || new_data_file_disk_percentage >= 100) { - ret = OB_INVALID_ARGUMENT; - } else { - ret = convert_block_status(data_file_->resize_blocks( - new_data_file_size, new_data_file_disk_percentage, reserved_size)); - } - } - return ret; -} - -int ObBlockManager::inc_ref(const MacroBlockId ¯o_id) { - int ret = OB_SUCCESS; - BlockInfo block_info; - - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - LOG_ERROR("not init", K(ret)); - } else if (OB_UNLIKELY(!macro_id.is_valid())) { - ret = OB_INVALID_ARGUMENT; - LOG_ERROR("Invalid argument, ", K(ret), K(macro_id)); - } else { - ObBucketHashWLockGuard lock_guard(bucket_lock_, macro_id.hash()); - if (OB_FAIL(block_map_.get(macro_id, block_info))) { - if (OB_ENTRY_NOT_EXIST == ret) { - block_info.reset(); - ret = OB_SUCCESS; - } else { - LOG_ERROR("get block_info fail", K(ret), K(macro_id)); - } - } else if (OB_UNLIKELY( - block_info.ref_cnt_ < 0 || - (0 == block_info.ref_cnt_ && is_mark_sweep_enabled()))) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("un-expected MacroBlock refcnt", K(ret), K(macro_id), - K(block_info)); - } - - if (OB_SUCC(ret)) { - block_info.access_time_ = ObTimeUtility::fast_current_time(); - block_info.ref_cnt_++; - if (OB_FAIL(block_map_.insert_or_update(macro_id, block_info))) { - } else { - LOG_DEBUG("debug ref_cnt: inc_ref in memory", K(ret), K(macro_id), - K(block_info), K(lbt())); - } - } - } - return ret; -} - -int ObBlockManager::dec_ref(const MacroBlockId ¯o_id) { - int ret = OB_SUCCESS; - BlockInfo block_info; - - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - LOG_ERROR("not init", K(ret)); - } else if (OB_UNLIKELY(!macro_id.is_valid())) { - ret = OB_INVALID_ARGUMENT; - LOG_ERROR("Invalid argument, ", K(ret), K(macro_id)); - } else { - ObBucketHashWLockGuard lock_guard(bucket_lock_, macro_id.hash()); - if (OB_FAIL(block_map_.get(macro_id, block_info))) { - } else if (OB_UNLIKELY(0 == block_info.ref_cnt_)) { - // BUG, should not happen - ret = OB_ERR_SYS; - LOG_ERROR("fatal error, ref cnt must not less than 0", K(ret), - K(macro_id), K(block_info)); - } else { - block_info.access_time_ = ObTimeUtility::fast_current_time(); - block_info.ref_cnt_--; - if (OB_FAIL(block_map_.insert_or_update(macro_id, block_info))) { - } else { - LOG_DEBUG("debug ref_cnt: dec_ref in memory", K(ret), K(macro_id), - K(block_info), K(lbt())); - } - } - } - return ret; -} - -int ObBlockManager::update_write_time(const MacroBlockId ¯o_id, - const bool update_to_max_time) { - int ret = OB_SUCCESS; - BlockInfo block_info; - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - LOG_ERROR("not init", K(ret)); - } else if (OB_UNLIKELY(!macro_id.is_valid())) { - ret = OB_INVALID_ARGUMENT; - LOG_ERROR("invalid argument", K(ret), K(macro_id)); - } else { - ObBucketHashWLockGuard lock_guard(bucket_lock_, macro_id.hash()); - if (OB_FAIL(block_map_.get(macro_id, block_info))) { - } else { - block_info.last_write_time_ = - update_to_max_time ? INT64_MAX : ObTimeUtility::fast_current_time(); - if (OB_FAIL(block_map_.insert_or_update(macro_id, block_info))) { - } - } - } - return ret; -} - -int ObBlockManager::get_marker_status(ObMacroBlockMarkerStatus &status) { - int ret = OB_SUCCESS; - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else { - SpinRLockGuard guard(marker_lock_); - status = marker_status_; - } - return ret; -} - -void ObBlockManager::update_marker_status(const ObMacroBlockMarkerStatus &tmp_status) -{ - SpinWLockGuard guard(marker_lock_); - ObMacroBlockMarkerStatus prev_result = marker_status_; - marker_status_.reset(); - marker_status_.total_block_count_ = OB_STORAGE_OBJECT_MGR.get_total_macro_block_count(); - constexpr int64_t FILE_HEADER_BLOCK_COUNT = 1; - marker_status_.reserved_block_count_ = FILE_HEADER_BLOCK_COUNT + tmp_status.reserved_block_count_; - marker_status_.free_count_ = get_free_macro_block_count(); - marker_status_.hold_count_ = tmp_status.hold_count_; - marker_status_.mark_cost_time_ = tmp_status.mark_cost_time_; - marker_status_.sweep_cost_time_ = tmp_status.sweep_cost_time_; - marker_status_.start_time_ = tmp_status.start_time_; - marker_status_.mark_finished_ = tmp_status.mark_finished_; - if (tmp_status.mark_finished_) { - // Mark succeed, update marker status with new result. - marker_status_.last_end_time_ = tmp_status.last_end_time_; - marker_status_.linked_block_count_ = tmp_status.linked_block_count_; - marker_status_.index_block_count_ = tmp_status.index_block_count_; - marker_status_.ids_block_count_ = tmp_status.ids_block_count_; - marker_status_.data_block_count_ = tmp_status.data_block_count_; - marker_status_.pending_free_count_ = tmp_status.pending_free_count_; - marker_status_.hold_info_ = tmp_status.hold_info_; - } else { - // Mark skipped, update marker status with previous result. - marker_status_.last_end_time_ = prev_result.last_end_time_; - marker_status_.linked_block_count_ = prev_result.linked_block_count_; - marker_status_.index_block_count_ = prev_result.index_block_count_; - marker_status_.ids_block_count_ = prev_result.ids_block_count_; - marker_status_.data_block_count_ = prev_result.data_block_count_; - marker_status_.pending_free_count_ = prev_result.pending_free_count_; - marker_status_.hold_info_ = prev_result.hold_info_; - } -} - -bool ObBlockManager::GetOldestHoldBlockFunctor::operator()( - const MacroBlockId &key, const BlockInfo &value) { - int ret = OB_SUCCESS; - if (OB_FAIL(macro_id_set_.exist_refactored(key))) { - if (OB_HASH_EXIST == ret) { - ret = OB_SUCCESS; - } else if (OB_HASH_NOT_EXIST == ret) { - // TODO yunshan.tys : add new solutions to find leaked macro blocks - if (0 != value.ref_cnt_ // not wash tablet block - && (!oldest_hold_block_info_.macro_id_.is_valid() || - value.access_time_ < oldest_hold_block_info_.last_access_time_)) { - oldest_hold_block_info_.macro_id_ = key; - oldest_hold_block_info_.last_access_time_ = value.access_time_; - oldest_hold_block_info_.ref_cnt_ = value.ref_cnt_; - } - ret = OB_SUCCESS; - } else { - } - } - ret_code_ = ret; - return OB_SUCCESS == ret; -} - -bool ObBlockManager::GetPendingFreeBlockFunctor::operator()( - const MacroBlockId &key, const BlockInfo &value) { - int ret = OB_SUCCESS; - if (value.ref_cnt_ > 0) { - hold_count_++; - } else if (OB_UNLIKELY(value.ref_cnt_ < 0)) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("fatal error, macro block ref cnt less than 0", K(ret), K(key), - K(value)); - } else if (OB_UNLIKELY(blk_map_.count() >= max_free_blk_cnt_)) { - // skip inserting more free block - } else if (OB_FAIL(blk_map_.insert(key, true))) { - } - ret_code_ = ret; - return OB_SUCCESS == ret; -} - -bool ObBlockManager::GetAllMacroBlockIdFunctor::operator()( - const MacroBlockId &key, const BlockInfo &value) { - int ret = OB_SUCCESS; - if (OB_UNLIKELY(value.ref_cnt_ < 0)) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("fatal error, macro block ref cnt less than 0", K(ret), K(key), - K(value)); - } else if (OB_FAIL(block_ids_.push_back(key))) { - } - ret_code_ = ret; - return OB_SUCCESS == ret; -} - -bool ObBlockManager::DoBlockSweepFunctor::operator()( - const MacroBlockId ¯o_id, const bool can_free) { - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!can_free)) { - // ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(block_manager_.sweep_one_block(macro_id))) { - } - // record last failure ret - ret_code_ = OB_SUCCESS == ret ? ret_code_ : ret; - // ignore ret to sweep all blocks - return true; -} - -bool ObBlockManager::LimitedIterGetBlockFunctor::operator()(const MacroBlockId &key, const BlockInfo &value) -{ - int ret = OB_SUCCESS; - if (OB_UNLIKELY(value.ref_cnt_ < 0)) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("fatal error, macro block ref cnt less than 0", K(ret), K(key), - K(value)); - } else if (OB_FAIL(block_ids_.push_back(key))) { - } - ret_code_ = ret; - max_iteration_--; - return max_iteration_ > 0 && OB_SUCCESS == ret; -} - -bool ObBlockManager::is_bad_block(const MacroBlockId ¯o_block_id) { - bool is_exist = false; - lib::ObMutexGuard bad_block_guard(bad_block_lock_); - for (int64_t i = 0; i < bad_block_infos_.count(); ++i) { - if (bad_block_infos_[i].macro_block_id_ == macro_block_id) { - is_exist = true; - break; - } - } - return is_exist; -} - -int ObBlockManager::do_sweep(MacroBlkIdMap &mark_info) { - int ret = OB_SUCCESS; - DoBlockSweepFunctor functor(*this); - if (0 == mark_info.count()) { - // do nothing - } else if (OB_FAIL(mark_info.for_each(functor))) { - ret = functor.get_ret_code(); - } - return ret; -} - -int ObBlockManager::sweep_one_block(const MacroBlockId ¯o_id) { - int ret = OB_SUCCESS; - ObBucketHashWLockGuard lock_guard(bucket_lock_, macro_id.hash()); - BlockInfo block_info; - const uint64_t block_index = macro_id.second_id(); - if (OB_FAIL(block_map_.get(macro_id, block_info))) { - } else if (OB_UNLIKELY(block_info.ref_cnt_ > 0)) { - // skip using block. - } else if (OB_FAIL(block_map_.erase(macro_id))) { - } else { - release_block(block_index); - FLOG_INFO("block manager free block", K(macro_id)); - } - return ret; -} - -void ObBlockManager::mark_and_sweep() -{ - int ret = OB_SUCCESS; - ObHashSet macro_id_set; - MacroBlkIdMap mark_info; - ObMacroBlockMarkerStatus tmp_status; - // we must assign alloc_num_ before mark_macro_blocks, because it will be set to 0 in this func - int64_t alloc_num = 0; - // recycle maximum 400 GB space, but no more than 8MB memory consumption for mark_info - const int64_t MAX_FREE_BLOCK_COUNT_PER_ROUND = 200000; - - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else if (!is_mark_sweep_enabled()) { - LOG_INFO("mark and sweep is disabled, do not mark and sweep this round"); - } else { - if (OB_FAIL(mark_info.init(ObModIds::OB_STORAGE_FILE_BLOCK_REF))) { - } else if (OB_FAIL(macro_id_set.create(MAX(2, MIN(MAX_FREE_BLOCK_COUNT_PER_ROUND, block_map_.get_bkt_cnt())), - "BlkIdSetBkt", - "BlkIdSetNode"))) { - } else { - GetPendingFreeBlockFunctor pending_free_functor( - MAX_FREE_BLOCK_COUNT_PER_ROUND, mark_info, tmp_status.hold_count_); - tmp_status.start_time_ = ObTimeUtility::fast_current_time(); - if (OB_FAIL(block_map_.for_each(pending_free_functor))) { - ret = pending_free_functor.get_ret_code(); - } else if ((mark_info.count() < MAX_FREE_BLOCK_COUNT_PER_ROUND)) { - // Only try to set alloc_num_ to 0 when macro info is complete, else do mark and sweep again. - if (0 != (alloc_num = ATOMIC_SET(&alloc_num_, 0))) { - // Some one alloc block after GetPendingFreeBlockFunctor concurrently. let mark and sweep do again next round - // whatever mark_info is empty or not - ATOMIC_SET(&alloc_num_, alloc_num); - } - } - - if (OB_FAIL(ret)) { - } else if (OB_FAIL(mark_macro_blocks(mark_info, macro_id_set, tmp_status))) { - if (OB_ALLOCATE_MEMORY_FAILED == ret) { - LOG_INFO("mark blocks meet memory issue, still countinue sweep to lease compaction space"); - ret = OB_SUCCESS; - } else { - } - } - - if (OB_FAIL(ret)) { - ATOMIC_FAA(&alloc_num_, alloc_num); // add alloc_num back to trigger next round mark - } else { - tmp_status.pending_free_count_ += mark_info.count(); - tmp_status.mark_cost_time_ = ObTimeUtility::fast_current_time() - tmp_status.start_time_; - // sweep - SpinWLockGuard guard(sweep_lock_); - if (OB_FAIL(do_sweep(mark_info))) { - } else if (tmp_status.mark_finished_) { - tmp_status.last_end_time_ = ObTimeUtility::fast_current_time(); - tmp_status.sweep_cost_time_ = tmp_status.last_end_time_ - tmp_status.start_time_ - tmp_status.mark_cost_time_; - - GetOldestHoldBlockFunctor hold_info_functor(macro_id_set, tmp_status.hold_info_); - if (OB_FAIL(block_map_.for_each(hold_info_functor))) { - ret = hold_info_functor.get_ret_code(); - } - } - } - if (OB_SUCC(ret)) { - update_marker_status(tmp_status); - } - FLOG_INFO("finish once mark and sweep", K(ret), K(alloc_num), - K(mark_info.count()), K_(marker_status), "map_cnt", - block_map_.count()); - } - } - macro_id_set.destroy(); -} - -int ObBlockManager::mark_macro_blocks( - MacroBlkIdMap &mark_info, - common::hash::ObHashSet ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status) -{ - int ret = OB_SUCCESS; - if (0 == mark_info.count() && 0 == alloc_num_) { - tmp_status.mark_finished_ = false; - LOG_INFO("no block alloc/free, no need to mark blocks", K(ret)); - } else { - MacroBlockId macro_id; - if (OB_FAIL(mark_local_storage_blocks(mark_info, macro_id_set, tmp_status))) { - } else if (OB_FALSE_IT( - ::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>()->get_cur_shared_block( - macro_id))) { - } else if (OB_FAIL( - mark_held_block( - macro_id, mark_info, macro_id_set, tmp_status))) { - } else if (OB_FALSE_IT(::oceanbase::share::server_service<::oceanbase::storage::ObLocalStorageMetaService>() - ->get_object_reader_writer() - .get_cur_block(macro_id))) { - } else if (OB_FAIL(mark_held_block(macro_id, mark_info, macro_id_set, tmp_status))) { - } - if (OB_SUCC(ret)) { - tmp_status.mark_finished_ = true; - } - } - return ret; -} - -int ObBlockManager::mark_held_block( - const MacroBlockId ¯o_id, MacroBlkIdMap &mark_info, - common::hash::ObHashSet - ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status) { - int ret = OB_SUCCESS; - - if (!macro_id.is_valid()) { - // no block is currently held - } else if (OB_FAIL(update_mark_info(macro_id, mark_info))) { - } else if (OB_FAIL( - macro_id_set.set_refactored(macro_id, 0 /*no override*/))) { - if (OB_HASH_EXIST != ret) { - } else { - ret = OB_SUCCESS; - } - } else { - tmp_status.hold_count_--; - tmp_status.reserved_block_count_++; - } - return ret; -} - -int ObBlockManager::mark_local_storage_blocks( - MacroBlkIdMap &mark_info, - common::hash::ObHashSet - ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status) { - int ret = OB_SUCCESS; - ObLocalStorageMetaService *meta_service = ::oceanbase::share::server_service<::oceanbase::storage::ObLocalStorageMetaService>(); - ObStorageMetaMemMgr *t3m = ::oceanbase::share::server_service<::oceanbase::storage::ObStorageMetaMemMgr>(); - if (OB_ISNULL(t3m) || OB_ISNULL(meta_service)) { - ret = OB_ERR_UNEXPECTED; - } else { - ObArenaAllocator iter_allocator("MarkIter", OB_MALLOC_NORMAL_BLOCK_SIZE); - ObTabletIterator tablet_iter(*t3m, iter_allocator, nullptr /*no op*/); - ObTabletHandle handle; - while (OB_SUCC(ret)) { - handle.reset(); - iter_allocator.reuse(); - if (OB_FAIL(tablet_iter.get_next_tablet(handle))) { - if (OB_ITER_END == ret) { - ret = OB_SUCCESS; - break; - } else { - } - } else if (OB_FAIL(mark_tablet_block(mark_info, handle, macro_id_set, - tmp_status))) { - } - } - } - return ret; -} - -int ObBlockManager::mark_tablet_block( - MacroBlkIdMap &mark_info, storage::ObTabletHandle &handle, - common::hash::ObHashSet - ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status) { - int ret = OB_SUCCESS; - const ObTablet *tablet = handle.get_obj(); - ObTabletBlockInfo block_info(tablet->get_tablet_addr().block_id(), - ObTabletMacroType::META_BLOCK, - 0 /*useless param*/); - - if (tablet->get_tablet_addr().is_block() && - OB_FAIL(do_mark_tablet_block(block_info, mark_info, macro_id_set, - tmp_status))) { - } else if (!tablet - ->is_empty_shell()) { // empty shell may don't have macro info - ObArenaAllocator allocator("MarkTabletBlock"); - ObTabletMacroInfo *macro_info = nullptr; - bool in_memory = true; - ObMacroInfoIterator macro_iter; - if (OB_FAIL(tablet->load_macro_info( - allocator, macro_info, in_memory))) { - } else if (OB_FAIL(macro_iter.init(ObTabletMacroType::MAX, *macro_info))) { - } - while (OB_SUCC(ret)) { - block_info.reset(); - if (OB_FAIL(macro_iter.get_next(block_info))) { - if (OB_ITER_END != ret) { - } else { - ret = OB_SUCCESS; - break; - } - } else if (OB_FAIL(do_mark_tablet_block(block_info, mark_info, macro_id_set, tmp_status))) { - } - } - if (OB_NOT_NULL(macro_info) && !in_memory) { - macro_info->reset(); - } - } - return ret; -} - -int ObBlockManager::do_mark_tablet_block( - const ObTabletBlockInfo &block_info, MacroBlkIdMap &mark_info, - common::hash::ObHashSet - ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status) { - int ret = OB_SUCCESS; - const MacroBlockId ¯o_id = block_info.macro_id_; - if (OB_FAIL(update_mark_info(macro_id, mark_info))) { - } else if (OB_FAIL(macro_id_set.set_refactored(macro_id, - 0 /* not overwrite */))) { - if (OB_HASH_EXIST != ret) { - } else { - ret = OB_SUCCESS; - } - } else { - switch (block_info.block_type_) { - case ObTabletMacroType::META_BLOCK: - case ObTabletMacroType::LINKED_BLOCK: - tmp_status.index_block_count_++; - break; - case ObTabletMacroType::DATA_BLOCK: - case ObTabletMacroType::SHARED_DATA_BLOCK: - tmp_status.data_block_count_++; - break; - default: - ret = OB_INVALID_ARGUMENT; - break; - } - if (OB_SUCC(ret)) { - tmp_status.hold_count_--; - } - } - return ret; -} - -int ObBlockManager::update_mark_info(const MacroBlockId ¯o_id, - MacroBlkIdMap &mark_info) { - int ret = OB_SUCCESS; - BlockInfo block_info; - bool can_free = false; - if (OB_UNLIKELY(!macro_id.is_valid())) { - ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(block_map_.get(macro_id, block_info))) { // double check. - if (OB_ENTRY_NOT_EXIST == ret) { - // BUG, should not happen - LOG_ERROR("macro block is using, not exist in block map, fatal error", - K(ret), K(macro_id), K(block_info)); - } else { - } - } else if (OB_UNLIKELY(block_info.ref_cnt_ < 0)) { - LOG_ERROR("macro block should is using, ref cnt shouldn't be less than or " - "equal to 0, " - "fatal error", - K(ret), K(macro_id), K(block_info)); - } else if (OB_FAIL(mark_info.get(macro_id, can_free))) { - if (OB_ENTRY_NOT_EXIST == ret) { - ret = OB_SUCCESS; - } else { - } - } else if (!can_free) { - // do nothing. - } else { - if (OB_UNLIKELY(0 == block_info.ref_cnt_)) { - // BUG, should not happen - LOG_ERROR("macro block is using, should not mark sweep, fatal error", - K(ret), K(macro_id), K(block_info)); - } else { - LOG_INFO("macro block is using, and ref cnt is more than 0", K(macro_id), - K(block_info)); - } - - if (OB_FAIL(mark_info.insert_or_update(macro_id, false))) { - } - } - return ret; -} - -void ObBlockManager::MarkBlockTask::runTimerTask() { - blk_mgr_.mark_and_sweep(); - (void)blk_mgr_.extend_file_size_if_need(); // auto extend -} - -// 2 days -const int64_t ObBlockManager::InspectBadBlockTask::ACCESS_TIME_INTERVAL = - 2 * 86400 * 1000000ull; -// block count inspected per round -const int64_t ObBlockManager::InspectBadBlockTask::MIN_OPEN_BLOCKS_PER_ROUND = - 1; -// max search number per round -const int64_t ObBlockManager::InspectBadBlockTask::MAX_SEARCH_COUNT_PER_ROUND = - 1000; - -ObBlockManager::InspectBadBlockTask::InspectBadBlockTask( - ObBlockManager &blk_mgr) - : blk_mgr_(blk_mgr), last_macro_idx_(-1), last_check_time_(0) {} - -ObBlockManager::InspectBadBlockTask::~InspectBadBlockTask() { reset(); } - -void ObBlockManager::InspectBadBlockTask::reset() { - last_macro_idx_ = -1; - last_check_time_ = 0; -} - -void ObBlockManager::InspectBadBlockTask::runTimerTask() { - const int64_t next_check_time = last_check_time_ + ACCESS_TIME_INTERVAL; - if (next_check_time <= - ObTimeUtility::fast_current_time()) { /* exceed 2 days */ - inspect_bad_block(); - if (last_macro_idx_ == -1) { // finished - last_check_time_ = ObTimeUtility::fast_current_time(); - } - } else { - LOG_INFO("skip inspect bad block", K_(last_check_time), K_(last_macro_idx)); - } -} - -int ObBlockManager::InspectBadBlockTask::check_block( - ObMacroBlockHandle ¯o_block_handle) { - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!macro_block_handle.is_valid())) { - ret = OB_INVALID_ARGUMENT; - } else { - const MacroBlockId ¯o_id = macro_block_handle.get_macro_id(); - ObMacroBlockReadInfo read_info; - read_info.io_timeout_ms_ = std::max(config::_data_storage_io_timeout() / 1000, - DEFAULT_IO_WAIT_TIME_MS); - read_info.macro_block_id_ = macro_id; - read_info.offset_ = 0; - read_info.size_ = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); - read_info.io_desc_.set_sys_module_id(ObIOModule::INSPECT_BAD_BLOCK_IO); - - if (OB_FAIL(ObBlockManager::async_read_block(read_info, - macro_block_handle))) { - } else if (OB_FAIL(macro_block_handle.wait())) { - } else if (macro_block_handle.get_data_size() != read_info.size_) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(ObSSTableMacroBlockChecker::check( - macro_block_handle.get_buffer(), read_info.size_, - ObMacroBlockCheckLevel::CHECK_LEVEL_PHYSICAL))) { - LOG_ERROR("fail to check sstable macro block", K(ret), K(macro_id), - KP(macro_block_handle.get_buffer()), K(read_info.size_)); - char error_msg[common::OB_MAX_ERROR_MSG_LEN]; - char macro_id_str[128]; - MEMSET(error_msg, 0, sizeof(error_msg)); - MEMSET(macro_id_str, 0, sizeof(macro_id_str)); - int tmp_ret = OB_SUCCESS; - macro_id.to_string(macro_id_str, sizeof(macro_id_str)); - if (OB_SUCCESS != (tmp_ret = databuff_printf( - error_msg, sizeof(error_msg), - "Bad data block: macro id=%s", macro_id_str))) { - } else if (OB_SUCCESS != - (tmp_ret = blk_mgr_.report_bad_block(macro_id, ret, error_msg, - config::data_dir().c_str()))) { - } else { - ret = OB_SUCCESS; // after report bad block, overwrite ret code and - // continue to check. - } - } - } - return ret; -} - -int ObBlockManager::extend_file_size_if_need() { - if (IS_NOT_INIT) { return OB_NOT_INIT; } - if (!is_mark_sweep_enabled()) { return OB_SUCCESS; } - storage_io::BlockGrowth policy{}; - const int ret = make_growth_policy(policy); - return ret == OB_SUCCESS - ? convert_block_status(data_file_->extend_blocks(policy)) : ret; -} - -static inline int64_t get_disk_allowed_iops(const int64_t macro_block_size) { - const int64_t max_bkgd_band_width = 64 * 1024 * 1024; - const int64_t max_check_iops = max_bkgd_band_width / macro_block_size; - return max_check_iops; -} - -void ObBlockManager::InspectBadBlockTask::inspect_bad_block() { - int ret = OB_SUCCESS; - const int64_t macro_block_size = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); - const int64_t verify_cycle = config::builtin_db_data_verify_cycle(); - const int64_t sec_per_day = 24 * 3600; - const int64_t check_times_per_day = - sec_per_day * 1000 * 1000 / ObBlockManager::INSPECT_DELAY_US; - ObArray macro_ids; - GetAllMacroBlockIdFunctor getter(macro_ids); - - if (OB_UNLIKELY(verify_cycle <= 0)) { - // macro block inspection is disabled, do nothing - } else if (OB_UNLIKELY(!blk_mgr_.is_inited_)) { - ret = OB_NOT_INIT; - } else if (OB_FAIL(macro_ids.reserve(blk_mgr_.block_map_.count()))) { - } else if (OB_FAIL(blk_mgr_.block_map_.for_each(getter))) { - } else if (OB_UNLIKELY(0 == macro_ids.size())) { - // nothing to do. - } else { - const int64_t total_used_macro_block_count = macro_ids.size(); - const int64_t check_blk_cnt_per_day = std::max( - MIN_OPEN_BLOCKS_PER_ROUND, total_used_macro_block_count / verify_cycle); - const int64_t blk_cnt_per_round = - check_blk_cnt_per_day / check_times_per_day; - const int64_t search_num_per_round = - 0 == blk_cnt_per_round ? MIN_OPEN_BLOCKS_PER_ROUND : blk_cnt_per_round; - const int64_t disk_allowed_iops = get_disk_allowed_iops(macro_block_size); - const int64_t max_check_count_per_round = - std::min(search_num_per_round, - std::max(MIN_OPEN_BLOCKS_PER_ROUND, disk_allowed_iops)); - const int64_t inspect_timeout_us = - std::max(config::_data_storage_io_timeout() * 1, - max_check_count_per_round * DEFAULT_IO_WAIT_TIME_MS * 1000); - const int64_t begin_time = ObTimeUtility::current_time(); - int64_t check_count = 0; - - for (int64_t i = 0; - i < MAX_SEARCH_COUNT_PER_ROUND && - check_count < max_check_count_per_round && - (ObTimeUtility::current_time() - begin_time) < inspect_timeout_us; - ++i) { - ++last_macro_idx_; - if (last_macro_idx_ >= total_used_macro_block_count) { - last_macro_idx_ = -1; // finished this round - break; - } - - const MacroBlockId ¯o_id = macro_ids.at(last_macro_idx_); - ObMacroBlockInfo block_info; - ObMacroBlockHandle macro_block_handle; - if (OB_FAIL(blk_mgr_.get_macro_block_info(macro_id, block_info, - macro_block_handle))) { - } else if (OB_UNLIKELY(block_info.is_free_)) { - // do nothing, this MacroBlock has been released. skip this MacroBlock - // and continue. - } else if (!block_info.is_free_ && block_info.ref_cnt_ > 0 - && (begin_time - block_info.access_time_) > - ACCESS_TIME_INTERVAL) { - ++check_count; - LOG_INFO("check macro block", K(block_info), "time_interval", - begin_time - block_info.access_time_); - if (OB_FAIL(check_block(macro_block_handle))) { - } - } - } - if (REACH_COUNT_INTERVAL(60)) { // print log per 60 times. - const int64_t cost_time = ObTimeUtility::current_time() - begin_time; - LOG_INFO("inspect bad block cost time", K(cost_time), K(check_count), - K(total_used_macro_block_count), K(max_check_count_per_round)); - } - } -} - -ObServerBlockManager &ObServerBlockManager::get_instance() { - static ObServerBlockManager instance_; - return instance_; -} - -} // namespace blocksstable -} // namespace oceanbase diff --git a/src/storage/blocksstable/ob_block_manager.h b/src/storage/blocksstable/ob_block_manager.h deleted file mode 100644 index 423b4b2c4d..0000000000 --- a/src/storage/blocksstable/ob_block_manager.h +++ /dev/null @@ -1,475 +0,0 @@ -/* - * Copyright (c) 2025 OceanBase. - * - * 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. - */ - -#ifndef OCEANBASE_BLOCKSSTABLE_OB_BLOCK_MANAGER_H_ -#define OCEANBASE_BLOCKSSTABLE_OB_BLOCK_MANAGER_H_ - -#include "share/io_request.h" -#include "lib/atomic/ob_atomic.h" -#include "lib/hash/ob_hashset.h" -#include "lib/hash/ob_linear_hash_map.h" -#include "lib/lock/ob_bucket_lock.h" -#include "storage/blocksstable/ob_block_sstable_struct.h" -#include "storage/blocksstable/ob_macro_block_checker.h" -#include "storage/blocksstable/ob_storage_object_handle.h" -#include "storage/blocksstable/ob_storage_object_rw_info.h" -#include "storage/tablet/ob_tablet_block_aggregated_info.h" - -namespace oceanbase -{ - -namespace storage -{ -class ObLocalStorageMetaService; -class ObTabletHandle; -struct ObTabletBlockInfo; -} - -namespace blocksstable -{ - -class ObMacroBlockHandle; -struct ObMacroBlocksWriteCtx; -class ObObjectManager; - -struct ObMacroBlockInfo final -{ -public: - ObMacroBlockInfo() : ref_cnt_(0), is_free_(false), access_time_(0) {} - ~ObMacroBlockInfo() = default; - TO_STRING_KV(K_(ref_cnt), K_(is_free), K_(access_time)); -public: - int32_t ref_cnt_; - bool is_free_; - int64_t access_time_; -}; - -struct ObBadBlockInfo final -{ -public: - ObBadBlockInfo() { reset(); } - ~ObBadBlockInfo() {} - OB_INLINE void reset() { MEMSET(this, 0, sizeof(*this)); } - TO_STRING_KV( - K(disk_id_), - K(macro_block_id_), - K(error_type_), - K(store_file_path_), - K(error_msg_), - K(check_time_)); - -public: - int64_t disk_id_; - MacroBlockId macro_block_id_; - int64_t error_type_; - char store_file_path_[MAX_PATH_SIZE]; - char error_msg_[common::OB_MAX_ERROR_MSG_LEN]; - int64_t check_time_; -}; - -struct ObMacroBlockReadInfo final -{ -public: - ObMacroBlockReadInfo() - : macro_block_id_(), offset_(), size_(), io_timeout_ms_(DEFAULT_IO_WAIT_TIME_MS), - io_desc_() - {} - ~ObMacroBlockReadInfo() = default; - OB_INLINE bool is_valid() const - { - return is_valid_storage_read(macro_block_id_, offset_, size_, io_desc_); - } - TO_STRING_KV(K_(offset), K_(size), K_(io_timeout_ms), K_(io_desc), - K_(macro_block_id)); -public: - blocksstable::MacroBlockId macro_block_id_; - int64_t offset_; - int64_t size_; - int64_t io_timeout_ms_; - common::ObIOFlag io_desc_; -}; - -class ObMacroBlockRewriteSeqGenerator final -{ -public: - // start to give an alarm when remaining 10T size to rewrite. - static const int64_t BLOCK_SEQUENCE_WARNING_LINE = MacroBlockId::MAX_WRITE_SEQ - 5000000; -public: - ObMacroBlockRewriteSeqGenerator(); - ~ObMacroBlockRewriteSeqGenerator(); - void reset(); - - // thread safe - int generate_next_sequence(uint64_t &blk_seq); - OB_INLINE void update_sequence(const uint64_t blk_seq) - { - common::SpinWLockGuard guard(lock_); - rewrite_seq_ = blk_seq; - } - TO_STRING_KV(K_(rewrite_seq)); - -private: - uint64_t rewrite_seq_; - common::SpinRWLock lock_; -}; - -class ObBlockManager -{ -public: - ObBlockManager(); - virtual ~ObBlockManager(); - - int prepare_file(const storage_io::ServiceHandle &service, - const char *data_dir, const char *sstable_dir, int64_t block_size, - int64_t initial_size, int64_t disk_percentage, size_t worker_threads, size_t max_depth); - int init(const int64_t block_size); - int close_file(); - int validate_io_threads(size_t worker_threads) const; - int fsync_block(); - int check_space_full(int64_t required_size, bool alarm_if_space_full = true) const; - int submit_read(const MacroBlockId &id, int64_t offset, int64_t size, - const common::ObIOFlag &flag, int64_t timeout_us, - std::unique_ptr callback, common::ObIOHandle &handle); - static int submit_handle_read( - const MacroBlockId ¯o_id, const int64_t offset, const int64_t size, - const common::ObIOFlag &flag, const int64_t timeout_ms, - std::unique_ptr callback, common::ObIOHandle &io_handle); - static int submit_handle_write( - const MacroBlockId ¯o_id, const ObStorageObjectWriteInfo &write_info, - common::ObIOHandle &io_handle); - int submit_write(const MacroBlockId &id, int64_t offset, const char *buffer, int64_t size, - const common::ObIOFlag &flag, int64_t timeout_us, common::ObIOHandle &handle); - int start(const int64_t reserved_size); - void stop(); - void wait(); - void destroy(); - int alloc_object(ObStorageObjectHandle &object_handle); - - // block interfaces - int alloc_block( - ObMacroBlockHandle ¯o_handle); - static int async_read_block( - const ObMacroBlockReadInfo &read_info, - ObMacroBlockHandle ¯o_handle); - static int async_write_block( - const ObMacroBlockWriteInfo &write_info, - ObMacroBlockHandle ¯o_handle); - static int write_block( - const ObMacroBlockWriteInfo &write_info, - ObMacroBlockHandle ¯o_handle); - static int read_block( - const ObMacroBlockReadInfo &read_info, - ObMacroBlockHandle ¯o_handle); - - int64_t get_free_macro_block_count() const; - int64_t get_used_macro_block_count() const; - int64_t get_max_macro_block_count(int64_t reserved_size) const; - int64_t get_total_block_size() const; - - int check_macro_block_free(const MacroBlockId ¯o_id, bool &is_free) const; - int get_bad_block_infos(common::ObIArray &bad_block_infos); - int report_bad_block( - const MacroBlockId ¯o_block_id, - const int64_t error_type, - const char *error_msg, - const char *file_path); - - int resize_file( - const int64_t new_data_file_size, - const int64_t new_data_file_disk_percentage, - const int64_t reserved_size); - - // reference count interfaces - int inc_ref(const MacroBlockId ¯o_id); - int dec_ref(const MacroBlockId ¯o_id); - // If update_to_max_time is true, it means modify the last_write_time_ of the block to max, - // which is used to skip the bad block inspection. - int update_write_time(const MacroBlockId ¯o_id, const bool update_to_max_time = false); - - // mark and sweep - int get_marker_status(ObMacroBlockMarkerStatus &status); - void mark_and_sweep(); - int first_mark_device(); - - bool is_started() { return is_started_; } -private: - struct BlockInfo - { - int64_t ref_cnt_; - int64_t access_time_; - int64_t last_write_time_; - BlockInfo() : ref_cnt_(0), access_time_(0), last_write_time_(INT64_MAX) {} - void reset() - { - ref_cnt_ = 0; - access_time_ = 0; - last_write_time_ = INT64_MAX; - } - TO_STRING_KV(K_(ref_cnt), K_(access_time), K_(last_write_time)); - }; - - class GetAllMacroBlockIdFunctor final - { - public: - GetAllMacroBlockIdFunctor(common::ObIArray &block_ids) - : ret_code_(common::OB_SUCCESS), block_ids_(block_ids) {} - ~GetAllMacroBlockIdFunctor() = default; - - bool operator()(const MacroBlockId &key, const BlockInfo &value); - int get_ret_code() const { return ret_code_; } - - private: - int ret_code_; - common::ObIArray &block_ids_; - }; - - class LimitedIterGetBlockFunctor final - { - public: - LimitedIterGetBlockFunctor(common::ObIArray &block_ids, int64_t max_iteration) - : ret_code_(common::OB_SUCCESS), block_ids_(block_ids), max_iteration_(max_iteration) - {} - ~LimitedIterGetBlockFunctor() = default; - - bool operator()(const MacroBlockId &key, const BlockInfo &value); - int get_ret_code() const - { - return ret_code_; - } - int ret_code_; - common::ObIArray &block_ids_; - int64_t max_iteration_; - }; - -private: - static constexpr double MARK_THRESHOLD = 0.2; - static const int64_t DEFAULT_LOCK_BUCKET_COUNT = 2048; - static const int64_t DEFAULT_PENDING_FREE_COUNT = 1024; - - static const int64_t RECYCLE_DELAY_US = 30 * 1000 * 1000; // 30s - static const int64_t INSPECT_DELAY_US = 1 * 1000 * 1000; // 1s - - typedef common::ObLinearHashMap BlockMap; - typedef common::ObLinearHashMap MacroBlkIdMap; - - class GetOldestHoldBlockFunctor final - { - public: - GetOldestHoldBlockFunctor( - common::hash::ObHashSet &id_set, - ObSimpleMacroBlockInfo &info) - : ret_code_(common::OB_SUCCESS), - macro_id_set_(id_set), - oldest_hold_block_info_(info) - {} - ~GetOldestHoldBlockFunctor() = default; - bool operator()(const MacroBlockId &key, const BlockInfo &value); - int get_ret_code() const { return ret_code_; } - private: - int ret_code_; - common::hash::ObHashSet ¯o_id_set_; - ObSimpleMacroBlockInfo &oldest_hold_block_info_; - }; - - class GetPendingFreeBlockFunctor final - { - public: - GetPendingFreeBlockFunctor( - const int64_t max_free_blk_cnt, - MacroBlkIdMap &blk_map, - int64_t &hold_count) - : ret_code_(common::OB_SUCCESS), - max_free_blk_cnt_(max_free_blk_cnt), - blk_map_(blk_map), - hold_count_(hold_count) - {} - ~GetPendingFreeBlockFunctor() = default; - - bool operator()(const MacroBlockId &key, const BlockInfo &value); - int get_ret_code() const { return ret_code_; } - - private: - int ret_code_; - int64_t max_free_blk_cnt_; - MacroBlkIdMap &blk_map_; - int64_t &hold_count_; - }; - - class DoBlockSweepFunctor final - { - public: - DoBlockSweepFunctor(ObBlockManager& block_manager) - : ret_code_(common::OB_SUCCESS), - block_manager_(block_manager) - {} - ~DoBlockSweepFunctor() = default; - - bool operator()(const MacroBlockId ¯o_id, const bool can_free); - int get_ret_code() const { return ret_code_; } - - private: - int ret_code_; - ObBlockManager& block_manager_; - }; - -private: - int get_macro_block_info(const MacroBlockId ¯o_id, - ObMacroBlockInfo ¯o_block_info, - ObMacroBlockHandle ¯o_block_handle); - bool is_bad_block(const MacroBlockId ¯o_block_id); - int mark_macro_blocks( - MacroBlkIdMap &mark_info, - common::hash::ObHashSet ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status); - int mark_held_block( - const MacroBlockId ¯o_id, - MacroBlkIdMap &mark_info, - common::hash::ObHashSet ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status); - int mark_local_storage_blocks( - MacroBlkIdMap &mark_info, - common::hash::ObHashSet ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status); - int mark_tablet_block( - MacroBlkIdMap &mark_info, - storage::ObTabletHandle &handle, - common::hash::ObHashSet ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status); - int do_mark_tablet_block( - const ObTabletBlockInfo &block_info, - MacroBlkIdMap &mark_info, - common::hash::ObHashSet ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status); - int mark_sstable_blocks( - MacroBlkIdMap &mark_info, - storage::ObTabletHandle &handle, - common::hash::ObHashSet ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status); - int mark_sstable_meta_block( - const blocksstable::ObSSTable &sstable, - MacroBlkIdMap &mark_info, - common::hash::ObHashSet ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status); - int mark_tablet_meta_blocks( - MacroBlkIdMap &mark_info, - storage::ObTabletHandle &handle, - common::hash::ObHashSet ¯o_id_set, - ObMacroBlockMarkerStatus &tmp_status); - int do_sweep(MacroBlkIdMap &mark_info); - int sweep_one_block(const MacroBlockId& macro_id); - - int update_mark_info( - const MacroBlockId ¯o_id, - MacroBlkIdMap &mark_info); - void update_marker_status(const ObMacroBlockMarkerStatus &tmp_status); - void disable_mark_sweep() { ATOMIC_SET(&is_mark_sweep_enabled_, false); } - void enable_mark_sweep() { ATOMIC_SET(&is_mark_sweep_enabled_, true); } - bool is_mark_sweep_enabled() const { return ATOMIC_LOAD(&is_mark_sweep_enabled_); } - - int extend_file_size_if_need(); - int inner_alloc_block(uint64_t &index); - void release_block(uint64_t index); - int open_file(int64_t reserved_size); - int make_growth_policy(storage_io::BlockGrowth &policy) const; - int64_t get_max_block_size(int64_t reserved_size) const; - -private: - class MarkBlockTask : public common::ObTimerTask - { - public: - MarkBlockTask(ObBlockManager &blk_mgr) - : blk_mgr_(blk_mgr) - { - disable_timeout_check(); - } - virtual ~MarkBlockTask() = default; - virtual void runTimerTask() override; - - private: - ObBlockManager &blk_mgr_; - }; - - class InspectBadBlockTask : public common::ObTimerTask - { - public: - InspectBadBlockTask(ObBlockManager &blk_mgr); - virtual ~InspectBadBlockTask(); - virtual void runTimerTask(); - void reset(); - - private: - int check_block(ObMacroBlockHandle ¯o_block_handle); - void inspect_bad_block(); - - private: - static const int64_t ACCESS_TIME_INTERVAL; - static const int64_t MIN_OPEN_BLOCKS_PER_ROUND; - static const int64_t MAX_SEARCH_COUNT_PER_ROUND; - - ObBlockManager &blk_mgr_; - int64_t last_macro_idx_; - int64_t last_check_time_; - private: - DISALLOW_COPY_AND_ASSIGN(InspectBadBlockTask); - }; - -private: - friend class InspectBadBlockTask; - - ObBucketLock bucket_lock_; - BlockMap block_map_; - - int64_t default_block_size_; - ObMacroBlockMarkerStatus marker_status_; - common::SpinRWLock marker_lock_; - - bool is_mark_sweep_enabled_; - common::SpinRWLock sweep_lock_; - - MarkBlockTask mark_block_task_; - InspectBadBlockTask inspect_bad_block_task_; - common::ObTimer timer_; - - lib::ObMutex bad_block_lock_; - common::ObArray bad_block_infos_; - - rust::Box data_file_; - char data_path_[common::OB_MAX_FILE_NAME_LENGTH]; - int64_t initial_file_size_; - int64_t disk_percentage_; - ObMacroBlockRewriteSeqGenerator blk_seq_generator_; - int64_t alloc_num_; - - bool is_inited_; - bool is_started_; -}; - -class ObServerBlockManager : public ObBlockManager -{ -public: - static ObServerBlockManager &get_instance(); - -private: - ObServerBlockManager() = default; - virtual ~ObServerBlockManager() = default; -}; - -} -} - -#define OB_SERVER_BLOCK_MGR (oceanbase::blocksstable::ObServerBlockManager::get_instance()) - -#endif /* OCEANBASE_BLOCKSSTABLE_OB_BLOCK_MANAGER_H_ */ diff --git a/src/storage/blocksstable/ob_block_sstable_struct.h b/src/storage/blocksstable/ob_block_sstable_struct.h index 07c4f96622..77828aa288 100644 --- a/src/storage/blocksstable/ob_block_sstable_struct.h +++ b/src/storage/blocksstable/ob_block_sstable_struct.h @@ -70,7 +70,6 @@ struct ObStorageEnv // for disk manager const char *data_dir_; const char *sstable_dir_; - int64_t default_block_size_; int64_t data_disk_size_; int64_t data_disk_percentage_; int64_t log_disk_size_; @@ -93,7 +92,6 @@ struct ObStorageEnv memset(this, 0, sizeof(*this)); } TO_STRING_KV(K_(data_dir), - K_(default_block_size), K_(data_disk_size), K_(data_disk_percentage), K_(log_disk_size), diff --git a/src/storage/blocksstable/ob_data_store_desc.cpp b/src/storage/blocksstable/ob_data_store_desc.cpp index 9f265fcf85..d9a20709cf 100644 --- a/src/storage/blocksstable/ob_data_store_desc.cpp +++ b/src/storage/blocksstable/ob_data_store_desc.cpp @@ -37,7 +37,8 @@ ObStaticDataStoreDesc::ObStaticDataStoreDesc() bool ObStaticDataStoreDesc::is_valid() const { bool is_valid = - tablet_id_.is_valid() + blocks_ != nullptr + && tablet_id_.is_valid() && compressor_type_ > ObCompressorType::INVALID_COMPRESSOR && snapshot_version_ > 0 && schema_version_ >= 0; @@ -53,6 +54,7 @@ void ObStaticDataStoreDesc::reset() int ObStaticDataStoreDesc::assign(const ObStaticDataStoreDesc &desc) { int ret = OB_SUCCESS; + blocks_ = desc.blocks_; is_ddl_ = desc.is_ddl_; merge_type_ = desc.merge_type_; compressor_type_ = desc.compressor_type_; @@ -76,7 +78,7 @@ int ObStaticDataStoreDesc::assign(const ObStaticDataStoreDesc &desc) void ObStaticDataStoreDesc::init_block_size(const ObMergeSchema &merge_schema) { const int64_t pct_free = merge_schema.get_pctfree(); - macro_block_size_ = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + macro_block_size_ = OB_DEFAULT_MACRO_BLOCK_SIZE; if (pct_free >= 0 && pct_free <= 50) { macro_store_size_ = macro_block_size_ * (100 - pct_free) / 100; } else { @@ -89,6 +91,7 @@ void ObStaticDataStoreDesc::init_block_size(const ObMergeSchema &merge_schema) } int ObStaticDataStoreDesc::init( + storage_io::BlockOwner &blocks, const bool is_ddl, const ObMergeSchema &merge_schema, const common::ObTabletID tablet_id, @@ -109,6 +112,7 @@ int ObStaticDataStoreDesc::init( STORAGE_LOG(WARN, "arguments is invalid", K(ret), K(merge_schema), K(snapshot_version), K(end_scn), K(data_format_version)); } else { reset(); + blocks_ = &blocks; is_ddl_ = is_ddl; merge_type_ = merge_type; tablet_id_ = tablet_id; @@ -588,6 +592,7 @@ int ObWholeDataStoreDesc::init( } int ObWholeDataStoreDesc::init( + storage_io::BlockOwner &blocks, const bool is_ddl, const ObMergeSchema &merge_schema, const common::ObTabletID tablet_id, @@ -610,7 +615,7 @@ int ObWholeDataStoreDesc::init( } - if (OB_FAIL(static_desc_.init(is_ddl, merge_schema, tablet_id, merge_type, + if (OB_FAIL(static_desc_.init(blocks, is_ddl, merge_schema, tablet_id, merge_type, snapshot_version, end_scn, data_format_version, micro_index_clustered, concurrent_cnt, need_submit_io, encoding_granularity))) { diff --git a/src/storage/blocksstable/ob_data_store_desc.h b/src/storage/blocksstable/ob_data_store_desc.h index 137c9ba919..14d157a268 100644 --- a/src/storage/blocksstable/ob_data_store_desc.h +++ b/src/storage/blocksstable/ob_data_store_desc.h @@ -25,6 +25,8 @@ #include "common/ob_store_format.h" #include "share/scn.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace share @@ -54,6 +56,7 @@ struct ObStaticDataStoreDesc ObStaticDataStoreDesc(); ~ObStaticDataStoreDesc() { reset(); } int init( + storage_io::BlockOwner &blocks, const bool is_ddl, const share::schema::ObMergeSchema &merge_schema, const common::ObTabletID tablet_id, @@ -93,6 +96,7 @@ struct ObStaticDataStoreDesc static const ObCompressorType DEFAULT_MINOR_COMPRESSOR_TYPE = ObCompressorType::ZSTD_COMPRESSOR; bool operator==(const ObStaticDataStoreDesc &other) const; // for unittest public: + storage_io::BlockOwner *blocks_; bool is_ddl_; // only used to print ERROR or WARN log compaction::ObMergeType merge_type_; ObCompressorType compressor_type_; @@ -170,6 +174,7 @@ struct ObDataStoreDesc const share::schema::ObMergeSchema &schema, const ObRowStoreType row_store_type); bool is_valid() const; + storage_io::BlockOwner &block_file() const { return *static_desc_->blocks_; } void reset(); // CAREFUL! static_desc_/col_desc_ are pointer int shallow_copy(const ObDataStoreDesc &desc); @@ -312,6 +317,7 @@ struct ObWholeDataStoreDesc const ObStaticDataStoreDesc &static_desc, const share::schema::ObMergeSchema &merge_schema); int init( + storage_io::BlockOwner &blocks, const bool is_ddl, const share::schema::ObMergeSchema &merge_schema, const common::ObTabletID tablet_id, diff --git a/src/storage/blocksstable/ob_macro_block_handle.cpp b/src/storage/blocksstable/ob_macro_block_handle.cpp deleted file mode 100644 index c7857eaa15..0000000000 --- a/src/storage/blocksstable/ob_macro_block_handle.cpp +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright (c) 2025 OceanBase. - * - * 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. - */ - -#define USING_LOG_PREFIX STORAGE_BLKMGR - - -#include "rust/config.h" -#include "ob_macro_block_handle.h" -#include "storage/blocksstable/ob_block_manager.h" -#include "share/rc/ob_server_runtime.h" - -namespace oceanbase -{ -namespace blocksstable -{ - -/** - * ---------------------------------------ObMacroBlockHandle---------------------------------------- - */ - -ObMacroBlockHandle::~ObMacroBlockHandle() -{ - reset(); -} - -ObMacroBlockHandle::ObMacroBlockHandle(const ObMacroBlockHandle &other) -{ - *this = other; -} - -ObMacroBlockHandle& ObMacroBlockHandle::operator=(const ObMacroBlockHandle &other) -{ - int ret = OB_SUCCESS; - if (&other != this) { - reset(); - io_handle_ = other.io_handle_; - macro_id_ = other.macro_id_; - if (macro_id_.is_valid()) { - if (OB_FAIL(OB_SERVER_BLOCK_MGR.inc_ref(macro_id_))) { - } - if (OB_FAIL(ret)) { - macro_id_.reset(); - } - } - } - return *this; -} - -void ObMacroBlockHandle::reset() -{ - io_handle_.reset(); - reset_macro_id(); -} - -void ObMacroBlockHandle::reuse() -{ - reset(); -} - -void ObMacroBlockHandle::reset_macro_id() -{ - int ret = OB_SUCCESS; - if (macro_id_.is_valid()) { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id_))) { - } else { - macro_id_.reset(); - } - } - abort_unless(OB_SUCCESS == ret); -} - -int ObMacroBlockHandle::report_bad_block() const -{ - int ret = OB_SUCCESS; - int io_errno = 0; - if (OB_FAIL(io_handle_.get_fs_errno(io_errno))) { - } else if (0 != io_errno) { - LOG_ERROR("fail to io macro block, ", K(macro_id_), K(ret), K(io_errno)); - char error_msg[common::OB_MAX_ERROR_MSG_LEN]; - MEMSET(error_msg, 0, sizeof(error_msg)); - if (OB_FAIL(databuff_printf(error_msg, - sizeof(error_msg), - "Sys IO error, ret=%d, errno=%d, errstr=%s", - ret, - io_errno, - strerror(io_errno)))){ - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.report_bad_block(macro_id_, - ret, - error_msg, - config::data_dir().c_str()))) { - } - } - return ret; -} - - - -int ObMacroBlockHandle::async_read(const ObMacroBlockReadInfo &read_info) -{ - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!read_info.is_valid())) { - ret = OB_INVALID_ARGUMENT; - } else { - reuse(); - if (OB_FAIL(ObBlockManager::submit_handle_read( - read_info.macro_block_id_, read_info.offset_, read_info.size_, read_info.io_desc_, - read_info.io_timeout_ms_, nullptr, io_handle_))) { - } else if (OB_FAIL(set_macro_block_id(read_info.macro_block_id_))) { - } - } - return ret; -} - -int ObMacroBlockHandle::async_write(const ObMacroBlockWriteInfo &write_info) -{ - int ret = OB_SUCCESS; - if (OB_FAIL(ObBlockManager::submit_handle_write(macro_id_, write_info, io_handle_))) { - } else { - FLOG_INFO("Async write macro block", K(macro_id_)); - } - if (OB_FAIL(ret)) { - reset(); - } - return ret; -} - -int ObMacroBlockHandle::wait(const int64_t wait_timeout_ms) -{ - int ret = OB_SUCCESS; - if (io_handle_.is_empty()) { - // do nothing - } else if (OB_FAIL(io_handle_.wait(wait_timeout_ms))) { - if (OB_EAGAIN != ret) { - int tmp_ret = OB_SUCCESS; - if (OB_SUCCESS != (tmp_ret = report_bad_block())) { - } - io_handle_.reset(); - } - } - return ret; -} - - -int ObMacroBlockHandle::set_macro_block_id(const MacroBlockId ¯o_block_id) -{ - int ret = common::OB_SUCCESS; - - if (macro_id_.is_valid()) { - ret = common::OB_ERR_SYS; - LOG_ERROR("cannot set macro block id twice", K(ret), K(macro_block_id), K(*this)); - } else if (!macro_block_id.is_valid()) { - ret = common::OB_INVALID_ARGUMENT; - } else { - macro_id_ = macro_block_id; - if (macro_id_.is_valid()) { - if (OB_FAIL(OB_SERVER_BLOCK_MGR.inc_ref(macro_id_))) { - } - if (OB_FAIL(ret)) { - macro_id_.reset(); - } - } - } - return ret; -} - -/** - * --------------------------------------ObStorageObjectsHandle---------------------------------------- - */ -ObStorageObjectsHandle::ObStorageObjectsHandle() - : macro_id_list_() -{ - macro_id_list_.set_attr(ObMemAttr("MacroIdList")); -} - -ObStorageObjectsHandle::~ObStorageObjectsHandle() -{ - reset(); -} - -int ObStorageObjectsHandle::add(const MacroBlockId ¯o_id) -{ - int ret = OB_SUCCESS; - - if (OB_FAIL(macro_id_list_.push_back(macro_id))) { - } else { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(macro_id))) { - } - - if (OB_FAIL(ret)) { - macro_id_list_.pop_back(); - } - } - - return ret; -} - - -void ObStorageObjectsHandle::reset() -{ - if (macro_id_list_.count() > 0) { - int tmp_ret = OB_SUCCESS; - - for (int64_t i = 0; i < macro_id_list_.count(); ++i) { - if (OB_SUCCESS != (tmp_ret = OB_STORAGE_OBJECT_MGR.dec_ref(macro_id_list_.at(i)))) { - LOG_ERROR_RET(tmp_ret, "failed to dec macro block ref cnt", K(tmp_ret), "macro_id", macro_id_list_.at(i)); - } - } - } - macro_id_list_.reset(); -} - -int ObStorageObjectsHandle::reserve(const int64_t block_cnt) -{ - int ret = OB_SUCCESS; - if (block_cnt > 0) { - if (OB_FAIL(macro_id_list_.reserve(block_cnt))) { - } - } - return ret; -} - -} // namespace blocksstable -} // namespace oceanbase diff --git a/src/storage/blocksstable/ob_macro_block_handle.h b/src/storage/blocksstable/ob_macro_block_handle.h deleted file mode 100644 index 561739c0cc..0000000000 --- a/src/storage/blocksstable/ob_macro_block_handle.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2025 OceanBase. - * - * 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. - */ - -#ifndef OCEANBASE_BLOCKSSTABLE_OB_MACRO_BLOCK_HANDLE -#define OCEANBASE_BLOCKSSTABLE_OB_MACRO_BLOCK_HANDLE - -#include "lib/container/ob_array.h" -#include "lib/utility/ob_print_utils.h" -#include "share/io_request.h" -#include "storage/blocksstable/ob_macro_block_id.h" -#include "storage/blocksstable/ob_storage_object_rw_info.h" - -namespace oceanbase -{ -namespace blocksstable -{ -struct ObMacroBlockReadInfo; - -class ObMacroBlockHandle final -{ -public: - ObMacroBlockHandle() = default; - ~ObMacroBlockHandle(); - ObMacroBlockHandle(const ObMacroBlockHandle &other); - ObMacroBlockHandle &operator=(const ObMacroBlockHandle &other); - void reset(); - void reuse(); - void reset_macro_id(); - bool is_valid() const { return io_handle_.is_valid(); } - bool is_empty() const { return io_handle_.is_empty(); } - OB_INLINE bool is_finished() const { return io_handle_.is_empty() || io_handle_.is_finished(); } - const char *get_buffer() { return io_handle_.get_buffer(); } - const MacroBlockId& get_macro_id() const { return macro_id_; } - common::ObIOHandle &get_io_handle() { return io_handle_; } - int64_t get_data_size() const { return io_handle_.get_data_size(); } - int async_read(const ObMacroBlockReadInfo &read_info); - int async_write(const ObMacroBlockWriteInfo &write_info); - int set_macro_block_id(const MacroBlockId ¯o_block_id); - int wait(const int64_t wait_timeout_ms=UINT64_MAX); - TO_STRING_KV(K_(macro_id), K_(io_handle)); -private: - int report_bad_block() const; - -private: - MacroBlockId macro_id_; - common::ObIOHandle io_handle_; -}; - -class ObStorageObjectsHandle final -{ -public: - ObStorageObjectsHandle(); - ~ObStorageObjectsHandle(); - int add(const MacroBlockId ¯o_id); - int64_t count() const { return macro_id_list_.count(); } - MacroBlockId at(const int64_t i) const { return macro_id_list_.at(i); } - const common::ObIArray &get_macro_id_list() const { return macro_id_list_; } - common::ObIArray &get_macro_id_list() { return macro_id_list_; } - void reset(); - int reserve(const int64_t block_cnt); - TO_STRING_KV(K_(macro_id_list)); -private: - common::ObArray macro_id_list_; - DISALLOW_COPY_AND_ASSIGN(ObStorageObjectsHandle); -}; - -} // namespace blocksstable -} // namespace oceanbase - -#endif // OCEANBASE_BLOCKSSTABLE_OB_MACRO_BLOCK_HANDLE diff --git a/src/storage/blocksstable/ob_macro_block_struct.cpp b/src/storage/blocksstable/ob_macro_block_struct.cpp index a2ce9edd10..71d8e12370 100644 --- a/src/storage/blocksstable/ob_macro_block_struct.cpp +++ b/src/storage/blocksstable/ob_macro_block_struct.cpp @@ -35,14 +35,7 @@ ObMacroBlocksWriteCtx::~ObMacroBlocksWriteCtx() void ObMacroBlocksWriteCtx::clear() { - int ret = OB_SUCCESS; - if (OB_SUCC(ret)) { - for (int64_t i = 0; i < macro_block_list_.count(); ++i) { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_block_list_.at(i)))) { - } - } - } - + holds_.reset(); macro_block_list_.reset(); use_old_macro_block_count_ = 0; } @@ -63,7 +56,7 @@ int ObMacroBlocksWriteCtx::set(ObMacroBlocksWriteCtx &src) } for (int64_t i = 0; OB_SUCC(ret) && i < src.macro_block_list_.count(); ++i) { - if (OB_FAIL(add_macro_block_id(src.macro_block_list_.at(i)))) { + if (OB_FAIL(add_macro_block_id(src.macro_block_list_.at(i), src.holds_.at(i)))) { } } @@ -97,46 +90,41 @@ int ObMacroBlocksWriteCtx::deep_copy(ObMacroBlocksWriteCtx *&dst, ObIAllocator & return ret; } -int ObMacroBlocksWriteCtx::get_macro_id_array(ObIArray &block_ids) +int ObMacroBlocksWriteCtx::append_blocks(ObIArray &ids, ObIArray &holds) const { int ret = OB_SUCCESS; - const int64_t start = block_ids.count(); for (int64_t i = 0; OB_SUCC(ret) && i < macro_block_list_.count(); ++i) { - MacroBlockId &block_id= macro_block_list_.at(i); - if (OB_FAIL(block_ids.push_back(block_id))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(block_id))) { - block_ids.pop_back(); - LOG_ERROR("failed to inc macro block ref cnt", K(ret)); + if (OB_FAIL(ids.push_back(macro_block_list_.at(i)))) { + } else if (OB_FAIL(holds.push_back(holds_.at(i)))) { + ids.pop_back(); } } return ret; } -int ObMacroBlocksWriteCtx::add_macro_block_id(const MacroBlockId ¯o_block_id) +int ObMacroBlocksWriteCtx::add_macro_block_id(storage_io::BlockOwner &blocks, const MacroBlockId &id) +{ + BlockHold hold; + const int ret = retain_block(blocks, id, hold); + return ret == OB_SUCCESS ? add_macro_block_id(id, hold) : ret; +} + +int ObMacroBlocksWriteCtx::add_macro_block_id(const MacroBlockId &id, const BlockHold &hold) { int ret = OB_SUCCESS; - if (OB_UNLIKELY(!macro_block_id.is_valid())) { + if (!id.is_valid() || !hold) { ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(macro_block_list_.push_back(macro_block_id))) { - } else { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(macro_block_id))) { - } - if (OB_FAIL(ret)) { - macro_block_list_.pop_back(); - } + } else if (OB_FAIL(macro_block_list_.push_back(id))) { + } else if (OB_FAIL(holds_.push_back(hold))) { + macro_block_list_.pop_back(); } return ret; } -int ObMacroBlocksWriteCtx::pop_macro_block_id(MacroBlockId ¯o_block_id) +int ObMacroBlocksWriteCtx::pop_macro_block_id(MacroBlockId &id) { - int ret = OB_SUCCESS; - if (OB_UNLIKELY(macro_block_list_.empty())) { - ret = OB_ERR_UNEXPECTED; - LOG_WARN("unexpect macro block list", K(macro_block_list_)); - } else if (OB_FAIL(macro_block_list_.pop_back(macro_block_id))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_block_id))) { - } + const int ret = macro_block_list_.pop_back(id); + if (ret == OB_SUCCESS) { holds_.pop_back(); } return ret; } diff --git a/src/storage/blocksstable/ob_macro_block_struct.h b/src/storage/blocksstable/ob_macro_block_struct.h index b75e7ec125..3ec06507e8 100644 --- a/src/storage/blocksstable/ob_macro_block_struct.h +++ b/src/storage/blocksstable/ob_macro_block_struct.h @@ -14,6 +14,7 @@ * limitations under the License. */ +#include "storage/blocksstable/ob_storage_object_handle.h" #include "storage/blocksstable/ob_block_sstable_struct.h" #ifndef OB_MACRO_BLOCK_STRUCT_H_ @@ -34,8 +35,13 @@ struct ObMacroBlocksWriteCtx final void clear(); int set(ObMacroBlocksWriteCtx &src); int deep_copy(ObMacroBlocksWriteCtx *&dst, ObIAllocator &allocator); - int get_macro_id_array(common::ObIArray &block_ids); - int add_macro_block_id(const blocksstable::MacroBlockId ¯o_block_id); + int append_blocks(common::ObIArray &ids, common::ObIArray &holds) const; + int add_macro_block_id(const MacroBlockId &id, const BlockHold &hold); + int add_macro_block_id(storage_io::BlockOwner &blocks, const MacroBlockId &id); + int add_macro_block(const ObStorageObjectHandle &handle) + { + return add_macro_block_id(handle.get_macro_id(), handle.block_hold()); + } int pop_macro_block_id(blocksstable::MacroBlockId ¯o_block_id); OB_INLINE void increment_old_block_count() { ++use_old_macro_block_count_; } OB_INLINE int64_t get_macro_block_count() const { return macro_block_list_.count(); } @@ -46,6 +52,8 @@ struct ObMacroBlocksWriteCtx final common::ObSEArray macro_block_list_; int64_t use_old_macro_block_count_; DISALLOW_COPY_AND_ASSIGN(ObMacroBlocksWriteCtx); +private: + common::ObSEArray holds_; }; } // end namespace blocksstable diff --git a/src/storage/blocksstable/ob_macro_block_writer.cpp b/src/storage/blocksstable/ob_macro_block_writer.cpp index e8d2422e96..e32900e201 100644 --- a/src/storage/blocksstable/ob_macro_block_writer.cpp +++ b/src/storage/blocksstable/ob_macro_block_writer.cpp @@ -16,7 +16,7 @@ #define USING_LOG_PREFIX STORAGE -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_macro_block_writer.h" #include "ob_imacro_block_flush_callback.h" @@ -381,7 +381,7 @@ int ObMacroBlockWriter::ObDefaultMacroBlockFlusher::write_disk(ObMacroBlock& mac } } if (OB_FAIL(ret)) { - } else if (OB_FAIL(macro_block_writer_->post_flush_normal_macro_block(macro_block, macro_handle_->get_macro_id()))) { + } else if (OB_FAIL(macro_block_writer_->post_flush_normal_macro_block(macro_block, *macro_handle_))) { } else if (need_flush_macro) { macro_block.print_flush_log(*macro_handle_); } @@ -1781,9 +1781,10 @@ int ObMacroBlockWriter::post_flush_small_sstable_data_macro_block( } int ObMacroBlockWriter::post_flush_normal_macro_block(const ObMacroBlock ¯o_block, - const MacroBlockId ¯o_block_id) + const ObStorageObjectHandle &handle) { int ret = OB_SUCCESS; + const MacroBlockId ¯o_block_id = handle.get_macro_id(); const bool need_alloc_block = is_alloc_block_needed(); if (OB_UNLIKELY(!macro_block_id.is_valid())) { ret = OB_INVALID_ARGUMENT; @@ -1791,7 +1792,7 @@ int ObMacroBlockWriter::post_flush_normal_macro_block(const ObMacroBlock ¯o_ } else if (OB_NOT_NULL(builder_) && OB_FAIL(builder_->append_meta_row_to_dumper(macro_block_id))) { STORAGE_LOG(WARN, "builder fail to append meta to to dumper.", K(ret)); - } else if (need_alloc_block && OB_FAIL(block_write_ctx_.add_macro_block_id(macro_block_id))) { + } else if (need_alloc_block && OB_FAIL(block_write_ctx_.add_macro_block(handle))) { STORAGE_LOG(WARN, "fail to add macro id", K(ret), "macro id", macro_block_id); } else if (OB_FAIL(prewarm_and_cluster_micro_blocks(macro_block, macro_block_id))) { } @@ -1816,7 +1817,7 @@ int ObMacroBlockWriter::flush_reuse_macro_block(const ObDataMacroBlockMeta ¯ { int ret = OB_SUCCESS; const MacroBlockId ¯o_id = macro_meta.get_macro_id(); - if (OB_FAIL(block_write_ctx_.add_macro_block_id(macro_id))) { + if (OB_FAIL(block_write_ctx_.add_macro_block_id(data_store_desc_->block_file(), macro_id))) { } else { block_write_ctx_.increment_old_block_count(); FLOG_INFO("Async reuse macro block", K(macro_meta.end_key_), "macro_block_id", macro_id, K(macro_meta)); @@ -1845,7 +1846,7 @@ int ObMacroBlockWriter::check_write_complete(const MacroBlockId ¯o_block_id) ObStorageObjectReadInfo read_info; read_info.offset_ = 0; - read_info.size_ = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + read_info.size_ = OB_DEFAULT_MACRO_BLOCK_SIZE; read_info.io_desc_.set_mode(ObIOMode::READ); read_info.io_desc_.set_sys_module_id(ObIOModule::SSTABLE_MACRO_BLOCK_WRITE_IO); read_info.io_timeout_ms_ = std::max(config::_data_storage_io_timeout() / 1000, DEFAULT_IO_WAIT_TIME_MS); @@ -1853,8 +1854,8 @@ int ObMacroBlockWriter::check_write_complete(const MacroBlockId ¯o_block_id) ObStorageObjectHandle read_handle; - if (OB_FAIL(OB_SERVER_BLOCK_MGR.fsync_block())) { - } else if (OB_FAIL(ObObjectManager::async_read_object(read_info, read_handle))) { + if (OB_FAIL(convert_block_status(data_store_desc_->block_file().sync_blocks()))) { + } else if (OB_FAIL(read_handle.async_read(data_store_desc_->block_file(), read_info))) { } else if (OB_FAIL(read_handle.wait())) { } else if (OB_FAIL(ObSSTableMacroBlockChecker::check( read_handle.get_buffer(), @@ -1964,12 +1965,6 @@ int ObMacroBlockWriter::alloc_block() { int ret = OB_SUCCESS; ObStorageObjectHandle ¯o_handle = macro_handles_[current_index_]; - ObStorageObjectOpt storage_opt; - if (data_store_desc_->is_for_index_or_meta()) { - storage_opt.set_meta_macro_object_opt(); - } else { - storage_opt.set_data_macro_object_opt(); - } if (macro_handle.get_macro_id().is_valid()) { ret = OB_ERR_UNEXPECTED; STORAGE_LOG(WARN, "block maybe wrong, should never valid macro id.", K(macro_handle)); @@ -1977,7 +1972,7 @@ int ObMacroBlockWriter::alloc_block() ret = OB_ERR_UNEXPECTED; STORAGE_LOG(INFO, "block maybe wrong", K(macro_handle)); - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.alloc_object(storage_opt, macro_handle))) { + } else if (OB_FAIL(macro_handle.allocate(data_store_desc_->block_file()))) { } return ret; } diff --git a/src/storage/blocksstable/ob_macro_block_writer.h b/src/storage/blocksstable/ob_macro_block_writer.h index 1f648ae56d..35b3af9865 100644 --- a/src/storage/blocksstable/ob_macro_block_writer.h +++ b/src/storage/blocksstable/ob_macro_block_writer.h @@ -23,7 +23,9 @@ #include "lib/container/ob_array_wrap.h" #include "index_block/ob_index_block_row_struct.h" #include "index_block/ob_index_block_aggregator.h" -#include "ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" +#include "storage/blocksstable/ob_block_sstable_struct.h" #include "ob_macro_block_checker.h" #include "ob_macro_block_reader.h" #include "ob_macro_block.h" @@ -273,7 +275,7 @@ class ObMacroBlockWriter ObIMacroBlockFlusher *&final_flusher); int prepare_default_macro_block_flusher(const bool is_close_flush); int post_flush_normal_macro_block(const ObMacroBlock ¯o_block, - const MacroBlockId ¯o_block_id); + const ObStorageObjectHandle &handle); int post_flush_small_sstable_data_macro_block(const ObBlockInfo &block_info); int try_active_flush_macro_block(); int wait_io_finish(ObStorageObjectHandle ¯o_handle, ObMacroBlock *macro_block); diff --git a/src/storage/blocksstable/ob_micro_block_cache.cpp b/src/storage/blocksstable/ob_micro_block_cache.cpp index 718ef38e1a..b99a81ea40 100644 --- a/src/storage/blocksstable/ob_micro_block_cache.cpp +++ b/src/storage/blocksstable/ob_micro_block_cache.cpp @@ -787,6 +787,7 @@ int ObIMicroBlockCache::get_cache_block( } int ObIMicroBlockCache::prefetch( + storage_io::BlockOwner &block_file, const MacroBlockId ¯o_id, const ObMicroIndexInfo& idx_row, const bool use_cache, @@ -808,7 +809,7 @@ int ObIMicroBlockCache::prefetch( callback = new (buf) ObAsyncSingleMicroBlockIOCallback; callback->allocator_ = allocator; callback->use_block_cache_ = use_cache; - if (OB_FAIL(prefetch(macro_id, idx_row, macro_handle, *callback))) { + if (OB_FAIL(prefetch(block_file, macro_id, idx_row, macro_handle, *callback))) { } } } @@ -816,6 +817,7 @@ int ObIMicroBlockCache::prefetch( } int ObIMicroBlockCache::prefetch( + storage_io::BlockOwner &block_file, const MacroBlockId ¯o_id, const ObMicroIndexInfo& idx_row, ObStorageObjectHandle ¯o_handle, @@ -844,7 +846,7 @@ int ObIMicroBlockCache::prefetch( read_info.size_ = idx_row.get_block_size(); read_info.io_timeout_ms_ = max(THIS_WORKER.get_timeout_remain() / 1000, 0); - if (OB_FAIL(ObObjectManager::async_read_object(read_info, macro_handle, std::move(owner)))) { + if (OB_FAIL(macro_handle.async_read(block_file, read_info, std::move(owner)))) { STORAGE_LOG(WARN, "Fail to async read block, ", K(ret), K(read_info)); } else { } @@ -853,6 +855,7 @@ int ObIMicroBlockCache::prefetch( } int ObIMicroBlockCache::prefetch( + storage_io::BlockOwner &block_file, const MacroBlockId ¯o_id, const ObMultiBlockIOParam &io_param, const bool use_cache, @@ -880,7 +883,7 @@ int ObIMicroBlockCache::prefetch( read_info.size_ = size; read_info.io_timeout_ms_ = max(THIS_WORKER.get_timeout_remain() / 1000, 0); - if (OB_FAIL(ObObjectManager::async_read_object(read_info, macro_handle, std::move(owner)))) { + if (OB_FAIL(macro_handle.async_read(block_file, read_info, std::move(owner)))) { STORAGE_LOG(WARN, "Fail to async read block, ", K(ret), K(read_info)); } else { } @@ -969,7 +972,7 @@ void ObDataMicroBlockCache::destroy() allocator_.destroy(); } -int ObDataMicroBlockCache::prefetch_multi_block(const MacroBlockId ¯o_id, +int ObDataMicroBlockCache::prefetch_multi_block(storage_io::BlockOwner &block_file, const MacroBlockId ¯o_id, const ObMultiBlockIOParam &io_param, const bool use_cache, ObStorageObjectHandle ¯o_handle) @@ -993,6 +996,7 @@ int ObDataMicroBlockCache::prefetch_multi_block(const MacroBlockId ¯o_id, allocator->free(callback); } } else if (OB_FAIL(ObIMicroBlockCache::prefetch( + block_file, macro_id, io_param, use_cache, macro_handle, *callback))) { } } @@ -1001,6 +1005,7 @@ int ObDataMicroBlockCache::prefetch_multi_block(const MacroBlockId ¯o_id, } int ObDataMicroBlockCache::load_block( + storage_io::BlockOwner &block_file, const ObMicroBlockId µ_block_id, const ObMicroBlockDesMeta &des_meta, const ObLogicMicroBlockId &logic_micro_id, @@ -1040,7 +1045,7 @@ int ObDataMicroBlockCache::load_block( auto owner = storage_io::adopt_callback(callback); if (!owner) { ret = OB_ALLOCATE_MEMORY_FAILED; } - else if (OB_FAIL(ObObjectManager::async_read_object(macro_read_info, macro_handle, std::move(owner)))) { + else if (OB_FAIL(macro_handle.async_read(block_file, macro_read_info, std::move(owner)))) { LOG_WARN("Fail to async read block", K(ret), K(macro_read_info)); } else if (OB_FAIL(macro_handle.wait())) { } else { @@ -1251,6 +1256,7 @@ int ObIndexMicroBlockCache::init(const char *cache_name) } int ObIndexMicroBlockCache::load_block( + storage_io::BlockOwner &block_file, const ObMicroBlockId µ_block_id, const ObMicroBlockDesMeta &des_meta, const ObLogicMicroBlockId &logic_micro_id, @@ -1296,7 +1302,7 @@ int ObIndexMicroBlockCache::load_block( char *raw_idx_block_buf = nullptr; auto owner = storage_io::adopt_callback(callback); if (!owner) { ret = OB_ALLOCATE_MEMORY_FAILED; } - else if (OB_FAIL(ObObjectManager::async_read_object(macro_read_info, macro_handle, std::move(owner)))) { + else if (OB_FAIL(macro_handle.async_read(block_file, macro_read_info, std::move(owner)))) { LOG_WARN("Fail to async read block", K(ret), K(macro_read_info)); } else if (OB_FAIL(macro_handle.wait())) { } diff --git a/src/storage/blocksstable/ob_micro_block_cache.h b/src/storage/blocksstable/ob_micro_block_cache.h index 82218f5241..69044559c0 100644 --- a/src/storage/blocksstable/ob_micro_block_cache.h +++ b/src/storage/blocksstable/ob_micro_block_cache.h @@ -24,7 +24,8 @@ #include "storage/ob_i_table.h" #include "storage/blocksstable/ob_micro_block_info.h" #include "storage/meta_mem/ob_tablet_handle.h" -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" namespace oceanbase @@ -382,12 +383,14 @@ class ObIMicroBlockCache const ObMicroBlockCacheKey &key, ObMicroBlockBufferHandle &handle); int prefetch( + storage_io::BlockOwner &block_file, const MacroBlockId ¯o_id, const ObMicroIndexInfo& idx_row, const bool use_cache, ObStorageObjectHandle ¯o_handle, ObIAllocator *allocator); virtual int load_block( + storage_io::BlockOwner &block_file, const ObMicroBlockId µ_block_id, const ObMicroBlockDesMeta &des_meta, const ObLogicMicroBlockId &logic_micro_id, @@ -422,11 +425,13 @@ class ObIMicroBlockCache protected: int add_put_size(const int64_t put_size); int prefetch( + storage_io::BlockOwner &block_file, const MacroBlockId ¯o_id, const ObMicroIndexInfo& idx_row, ObStorageObjectHandle ¯o_handle, ObIMicroBlockIOCallback &callback); int prefetch( + storage_io::BlockOwner &block_file, const MacroBlockId ¯o_id, const ObMultiBlockIOParam &io_param, const bool use_cache, @@ -444,11 +449,12 @@ class ObDataMicroBlockCache int init(const char *cache_name); virtual void destroy() override; using ObIMicroBlockCache::prefetch; - int prefetch_multi_block(const MacroBlockId ¯o_id, + int prefetch_multi_block(storage_io::BlockOwner &block_file, const MacroBlockId ¯o_id, const ObMultiBlockIOParam &io_param, const bool use_cache, ObStorageObjectHandle ¯o_handle); int load_block( + storage_io::BlockOwner &block_file, const ObMicroBlockId µ_block_id, const ObMicroBlockDesMeta &des_meta, const ObLogicMicroBlockId &logic_micro_id, @@ -498,6 +504,7 @@ class ObIndexMicroBlockCache : public ObDataMicroBlockCache virtual ~ObIndexMicroBlockCache(); int init(const char *cache_name); int load_block( + storage_io::BlockOwner &block_file, const ObMicroBlockId µ_block_id, const ObMicroBlockDesMeta &des_meta, const ObLogicMicroBlockId &logic_micro_id, diff --git a/src/storage/blocksstable/ob_object_manager.cpp b/src/storage/blocksstable/ob_object_manager.cpp deleted file mode 100644 index 66aafa9405..0000000000 --- a/src/storage/blocksstable/ob_object_manager.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2025 OceanBase. - * - * 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. - */ - -#define USING_LOG_PREFIX STORAGE - -#include "ob_object_manager.h" -#include "storage/blocksstable/ob_block_manager.h" -#include "storage/meta_store/ob_local_storage_meta_service.h" - -namespace oceanbase -{ -namespace blocksstable -{ -// ============================ ObStorageObjectOpt ======================================// - -int64_t ObStorageObjectOpt::to_string(char *buf, const int64_t buf_len) const -{ - int ret = OB_SUCCESS; - int64_t pos = 0; - const char *type_name = "UNKNOWN"; - switch (object_type_) { - case ObStorageObjectType::DATA_MACRO: - type_name = "DATA_MACRO"; - break; - case ObStorageObjectType::META_MACRO: - type_name = "META_MACRO"; - break; - default: - break; - } - if (OB_FAIL(databuff_printf(buf, buf_len, pos, "object_type=%s", type_name))) { - } - return pos; -} - -//================================ ObObjectManager =====================================// - -ObObjectManager &ObObjectManager::get_instance() -{ - static ObObjectManager instance_; - return instance_; -} - -ObObjectManager::ObObjectManager() - : is_inited_(false), - macro_object_size_(0) -{ -} - -ObObjectManager::~ObObjectManager() -{ -} - -int ObObjectManager::init(const int64_t macro_object_size) -{ - int ret = OB_SERVER_BLOCK_MGR.init(macro_object_size); - if (OB_SUCC(ret)) { - macro_object_size_ = macro_object_size; - is_inited_ = true; - LOG_INFO("succeed to init object mgr", K(macro_object_size_)); - } - return ret; -} - -int ObObjectManager::start(const int64_t reserved_size) -{ - int ret = OB_SUCCESS; - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else if (OB_UNLIKELY(reserved_size < 0)) { - ret = OB_INVALID_ARGUMENT; - } else { - ret = OB_SERVER_BLOCK_MGR.start(reserved_size); - } - return ret; -} - -void ObObjectManager::stop() -{ - OB_SERVER_BLOCK_MGR.stop(); -} - -void ObObjectManager::wait() -{ - OB_SERVER_BLOCK_MGR.wait(); -} - -void ObObjectManager::destroy() -{ - OB_SERVER_BLOCK_MGR.destroy(); -} - -int ObObjectManager::alloc_object(const ObStorageObjectOpt &opt, ObStorageObjectHandle &object_handle) -{ - int ret = OB_SUCCESS; - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else if (ObStorageObjectType::DATA_MACRO != opt.object_type_ - && ObStorageObjectType::META_MACRO != opt.object_type_) { - ret = OB_NOT_SUPPORTED; - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.alloc_object(object_handle))) { - } - return ret; -} - -int ObObjectManager::async_read_object( - const ObStorageObjectReadInfo &read_info, - ObStorageObjectHandle &object_handle, - std::unique_ptr callback) -{ - return object_handle.async_read(read_info, std::move(callback)); -} - -int ObObjectManager::async_write_object( - const ObStorageObjectOpt &opt, - const ObStorageObjectWriteInfo &write_info, - ObStorageObjectHandle &object_handle) -{ - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!write_info.is_valid())) { - ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.alloc_object(opt, object_handle))) { - } else if (OB_FAIL(object_handle.async_write(write_info))) { - } - return ret; -} - -int ObObjectManager::read_object( - const ObStorageObjectReadInfo &read_info, - ObStorageObjectHandle &object_handle, - std::unique_ptr callback) -{ - int ret = OB_SUCCESS; - if (OB_FAIL(async_read_object(read_info, object_handle, std::move(callback)))) { - } else if (OB_FAIL(object_handle.wait())) { - } - return ret; -} -int ObObjectManager::write_object( - const ObStorageObjectOpt &opt, - const ObStorageObjectWriteInfo &write_info, - ObStorageObjectHandle &object_handle) -{ - int ret = OB_SUCCESS; - if (OB_FAIL(async_write_object(opt, write_info, object_handle))) { - } else if (OB_FAIL(object_handle.wait())) { - } - return ret; -} - -int ObObjectManager::inc_ref(const MacroBlockId &object_id) const -{ - int ret = OB_SUCCESS; - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else { - ret = OB_SERVER_BLOCK_MGR.inc_ref(object_id); - } - return ret; -} - -int ObObjectManager::dec_ref(const MacroBlockId &object_id) const -{ - int ret = OB_SUCCESS; - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else { - ret = OB_SERVER_BLOCK_MGR.dec_ref(object_id); - } - return ret; -} - -int64_t ObObjectManager::get_total_macro_block_count() const -{ - return macro_object_size_ > 0 ? OB_SERVER_BLOCK_MGR.get_total_block_size() / macro_object_size_ : 0; -} - -int64_t ObObjectManager::get_max_macro_block_count(int64_t reserved_size) const -{ - return OB_SERVER_BLOCK_MGR.get_max_macro_block_count(reserved_size); -} - -int64_t ObObjectManager::get_used_macro_block_count() const -{ - return OB_SERVER_BLOCK_MGR.get_used_macro_block_count(); -} - -int64_t ObObjectManager::get_free_macro_block_count() const -{ - return OB_SERVER_BLOCK_MGR.get_free_macro_block_count(); -} - -} // namespace blocksstable -} // oceanbase diff --git a/src/storage/blocksstable/ob_object_manager.h b/src/storage/blocksstable/ob_object_manager.h deleted file mode 100644 index c888cae925..0000000000 --- a/src/storage/blocksstable/ob_object_manager.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2025 OceanBase. - * - * 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. - */ - -#ifndef OCEANBASE_BLOCKSSTABLE_OB_OBJECT_MANAGER_H_ -#define OCEANBASE_BLOCKSSTABLE_OB_OBJECT_MANAGER_H_ - -#include "lib/lock/mutex.h" -#include "storage/blocksstable/ob_storage_object_rw_info.h" -#include "storage/blocksstable/ob_storage_object_handle.h" - -namespace oceanbase -{ -namespace blocksstable -{ -enum class ObStorageObjectType : uint8_t -{ - DATA_MACRO = 0, - META_MACRO, - MAX -}; - -// ================================= ObStorageObjectOpt ====================================// - -class ObStorageObjectOpt final -{ -public: - ObStorageObjectOpt() - : object_type_(ObStorageObjectType::DATA_MACRO) {} - - ~ObStorageObjectOpt() {} - void set_data_macro_object_opt() - { - object_type_ = ObStorageObjectType::DATA_MACRO; - } - void set_meta_macro_object_opt() - { - object_type_ = ObStorageObjectType::META_MACRO; - } - - int64_t to_string(char *buf, const int64_t buf_len) const; - -public: - ObStorageObjectType object_type_; -}; - -// ================================== ObObjectManager =====================================// -class ObObjectManager final -{ -public: - int init(const int64_t macro_object_size); - int start(const int64_t reserved_size); - void stop(); - void wait(); - void destroy(); - - int alloc_object( - const ObStorageObjectOpt &opt, - ObStorageObjectHandle &object_handle); - static int async_read_object( - const ObStorageObjectReadInfo &read_info, - ObStorageObjectHandle &object_handle, - std::unique_ptr callback = nullptr); - static int async_write_object( - const ObStorageObjectOpt &opt, - const ObStorageObjectWriteInfo &write_info, - ObStorageObjectHandle &object_handle); - static int read_object( - const ObStorageObjectReadInfo &read_info, - ObStorageObjectHandle &object_handle, - std::unique_ptr callback = nullptr); - static int write_object( - const ObStorageObjectOpt &opt, - const ObStorageObjectWriteInfo &write_info, - ObStorageObjectHandle &object_handle); - int64_t get_macro_object_size() const { return macro_object_size_; } - int inc_ref(const MacroBlockId &object_id) const; - int dec_ref(const MacroBlockId &object_id) const; - - static ObObjectManager &get_instance(); - - int64_t get_macro_block_size() const - { - return macro_object_size_; - } - int64_t get_max_macro_block_count(int64_t reserved_size) const; - int64_t get_used_macro_block_count() const; - int64_t get_free_macro_block_count() const; - int64_t get_total_macro_block_count() const; - -private: - ObObjectManager(); - ~ObObjectManager(); - -private: - bool is_inited_; - int64_t macro_object_size_; - - - DISALLOW_COPY_AND_ASSIGN(ObObjectManager); -}; - -#define OB_STORAGE_OBJECT_MGR (oceanbase::blocksstable::ObObjectManager::get_instance()) - -} // namespace blocksstable -} // namespace oceanbase - -#endif // OCEANBASE_BLOCKSSTABLE_OB_OBJECT_MANAGER_H_ diff --git a/src/storage/blocksstable/ob_shared_macro_block_manager.cpp b/src/storage/blocksstable/ob_shared_macro_block_manager.cpp index 60fc89f05f..11f85f12a5 100644 --- a/src/storage/blocksstable/ob_shared_macro_block_manager.cpp +++ b/src/storage/blocksstable/ob_shared_macro_block_manager.cpp @@ -16,9 +16,10 @@ #define USING_LOG_PREFIX STORAGE_BLKMGR -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "storage/blocksstable/ob_shared_macro_block_manager.h" +#include "storage/blocksstable/ob_macro_block_checker.h" #include "share/rc/ob_server_runtime.h" #include "storage/tablet/ob_mds_schema_helper.h" @@ -88,6 +89,7 @@ void ObSharedMacroBlockMgr::destroy() { defragment_timer_.destroy(); macro_handle_.reset(); + blocks_ = nullptr; offset_ = OB_DEFAULT_MACRO_BLOCK_SIZE; // so we can init block automatically for first write header_size_ = 0; if (nullptr != common_header_buf_) { @@ -99,7 +101,7 @@ void ObSharedMacroBlockMgr::destroy() is_inited_ = false; } -int ObSharedMacroBlockMgr::init() +int ObSharedMacroBlockMgr::init(storage_io::BlockOwner &blocks) { int ret = OB_SUCCESS; ObMacroBlockCommonHeader common_header; @@ -117,6 +119,7 @@ int ObSharedMacroBlockMgr::init() } else if (OB_FAIL(defragment_timer_.init( "SSTableDefrag", ObMemAttr("SSTableDefrag")))) { } else { + blocks_ = &blocks; is_inited_ = true; } @@ -164,7 +167,7 @@ int ObSharedMacroBlockMgr::write_block( } else if (OB_UNLIKELY(0 != size % DIO_READ_ALIGN_SIZE)) { ret = OB_INVALID_ARGUMENT; } else { - ObMacroBlockWriteInfo write_info; + ObStorageObjectWriteInfo write_info; write_info.buffer_ = buf; write_info.size_ = size; write_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000; @@ -180,7 +183,7 @@ int ObSharedMacroBlockMgr::write_block( if (OB_SUCC(ret)) { write_info.offset_ = offset_; write_info.io_timeout_ms_ = std::max(config::_data_storage_io_timeout() / 1000, DEFAULT_IO_WAIT_TIME_MS); - if (OB_FAIL(do_write_block(macro_handle_.get_macro_id(), write_info, block_info))) { + if (OB_FAIL(do_write_block(macro_handle_, write_info, block_info))) { } // no matter success or failure, advance offset_ @@ -190,7 +193,7 @@ int ObSharedMacroBlockMgr::write_block( FLOG_INFO("successfully write small sstable", K(ret), K(block_info), K(offset_), "old_block", write_ctx.get_macro_block_list()); write_ctx.reset(); - if (OB_FAIL(write_ctx.add_macro_block_id(macro_handle_.get_macro_id()))) { + if (OB_FAIL(write_ctx.add_macro_block(macro_handle_))) { } } } @@ -199,18 +202,17 @@ int ObSharedMacroBlockMgr::write_block( return ret; } -/*static*/int ObSharedMacroBlockMgr::do_write_block( - const MacroBlockId& macro_id, - const ObMacroBlockWriteInfo &write_info, +int ObSharedMacroBlockMgr::do_write_block( + const ObStorageObjectHandle &block, + const ObStorageObjectWriteInfo &write_info, ObBlockInfo &block_info) { int ret = OB_SUCCESS; - ObMacroBlockHandle write_macro_handle; + ObStorageObjectHandle write_macro_handle(block); const int64_t offset = write_info.offset_; const int64_t size = write_info.size_; - if (OB_FAIL(write_macro_handle.set_macro_block_id(macro_id))) { - } else if (OB_FAIL(write_macro_handle.async_write(write_info))) { + if (OB_FAIL(write_macro_handle.async_write(write_info))) { } else if (OB_FAIL(write_macro_handle.wait())) { } @@ -223,30 +225,30 @@ int ObSharedMacroBlockMgr::write_block( } if (OB_SUCC(ret)) { - block_info.macro_id_ = macro_id; + block_info.macro_id_ = block.get_macro_id(); block_info.nested_size_ = size; block_info.nested_offset_ = offset; } return ret; } -/*static*/int ObSharedMacroBlockMgr::check_write_complete( +int ObSharedMacroBlockMgr::check_write_complete( const MacroBlockId ¯o_id, const int64_t offset, const int64_t size) { int ret = OB_SUCCESS; - ObMacroBlockReadInfo read_info; + ObStorageObjectReadInfo read_info; read_info.macro_block_id_ = macro_id; read_info.size_ = size; read_info.offset_ = offset; read_info.io_timeout_ms_ = std::max(config::_data_storage_io_timeout() / 1000, DEFAULT_IO_WAIT_TIME_MS); read_info.io_desc_.set_sys_module_id(ObIOModule::SSTABLE_WHOLE_SCANNER_IO); - ObMacroBlockHandle read_handle; + ObStorageObjectHandle read_handle; ObSSTableMacroBlockChecker macro_block_checker; - if (OB_FAIL(OB_SERVER_BLOCK_MGR.fsync_block())) { - } else if (OB_FAIL(ObBlockManager::async_read_block(read_info, read_handle))) { + if (OB_FAIL(convert_block_status(blocks_->sync_blocks()))) { + } else if (OB_FAIL(read_handle.async_read(*blocks_, read_info))) { } else if (OB_FAIL(read_handle.wait())) { } else if (OB_FAIL(macro_block_checker.check( read_handle.get_buffer(), @@ -262,38 +264,31 @@ int ObSharedMacroBlockMgr::try_switch_macro_block() int ret = OB_SUCCESS; const MacroBlockId &block_id = macro_handle_.get_macro_id(); const int32_t used_size = offset_; - ObMacroBlockHandle new_macro_handle; + ObStorageObjectHandle new_macro_handle; // we add_block_size extraly to avoid defragmenting the previous block if some sstables haven't been inited if (block_id.is_valid() && OB_FAIL(add_block(block_id, used_size))) { } else if (FALSE_IT(macro_handle_.reset())) { } else if (FALSE_IT(offset_ = OB_DEFAULT_MACRO_BLOCK_SIZE /* invalid offset */)) { - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.alloc_block(new_macro_handle))) { + } else if (OB_FAIL(new_macro_handle.allocate(*blocks_))) { } else { - ObMacroBlockWriteInfo write_info; + ObStorageObjectWriteInfo write_info; ObBlockInfo block_info; write_info.buffer_ = common_header_buf_; write_info.size_ = header_size_; write_info.offset_ = 0; write_info.io_timeout_ms_ = std::max(config::_data_storage_io_timeout() / 1000, DEFAULT_IO_WAIT_TIME_MS); - if (OB_FAIL(do_write_block(new_macro_handle.get_macro_id(), write_info, block_info))) { + if (OB_FAIL(do_write_block(new_macro_handle, write_info, block_info))) { } } if (OB_SUCC(ret)) { - if (OB_FAIL(macro_handle_.set_macro_block_id(new_macro_handle.get_macro_id()))) { - } else { - offset_ = header_size_; - } + macro_handle_ = new_macro_handle; + offset_ = header_size_; } return ret; } -void ObSharedMacroBlockMgr::get_cur_shared_block(MacroBlockId ¯o_id) -{ - lib::ObMutexGuard guard(mutex_); - macro_id = macro_handle_.get_macro_id(); -} bool ObSharedMacroBlockMgr::is_recyclable(const MacroBlockId ¯o_id, const int64_t &used_size) const { @@ -577,7 +572,7 @@ int ObSharedMacroBlockMgr::rebuild_sstable( sstable_index_builder.reset(); index_block_rebuilder.reset(); ObDataMacroBlockMeta data_macro_meta; - ObMacroBlockHandle block_handle; + ObStorageObjectHandle block_handle; ObBlockInfo block_info; ObMacroBlocksWriteCtx write_ctx; ObSSTableMergeRes res; @@ -634,6 +629,7 @@ int ObSharedMacroBlockMgr::create_new_sstable( meta_handle.get_sstable_meta(), block_info))) { } else if (OB_UNLIKELY(!param.is_valid())) { ret = OB_INVALID_ARGUMENT; + } else if (FALSE_IT(new_sstable.bind_block_file(*blocks_))) { } else if (OB_FAIL(new_sstable.init(param, &allocator))) { } @@ -658,7 +654,7 @@ int ObSharedMacroBlockMgr::prepare_data_desc( } else if (OB_UNLIKELY(!storage_schema->is_valid())) { ret = OB_ERR_UNEXPECTED; } else if (OB_FAIL(data_desc.init( - false/*is_ddl*/, + *blocks_, false/*is_ddl*/, *storage_schema, tablet.get_tablet_meta().tablet_id_, merge_type, @@ -675,7 +671,7 @@ int ObSharedMacroBlockMgr::prepare_data_desc( } if (FAILEDx(data_desc.init( - false/*is_ddl*/, + *blocks_, false/*is_ddl*/, *storage_schema, tablet.get_tablet_meta().tablet_id_, merge_type, @@ -735,10 +731,10 @@ int ObSharedMacroBlockMgr::alloc_for_tools( int ObSharedMacroBlockMgr::read_sstable_block( const ObSSTable &sstable, - ObMacroBlockHandle &block_handle) + ObStorageObjectHandle &block_handle) { int ret = OB_SUCCESS; - ObMacroBlockReadInfo read_info; + ObStorageObjectReadInfo read_info; ObSSTableMetaHandle meta_handle; ObMacroIdIterator id_iterator; MacroBlockId macro_id; @@ -753,7 +749,8 @@ int ObSharedMacroBlockMgr::read_sstable_block( read_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000L; read_info.io_desc_.set_sys_module_id(ObIOModule::SSTABLE_WHOLE_SCANNER_IO); - if (OB_FAIL(ObBlockManager::read_block(read_info, block_handle))) { + if (OB_FAIL(block_handle.async_read(*blocks_, read_info))) { + } else if (OB_FAIL(block_handle.wait())) { } else if (OB_UNLIKELY(!block_handle.is_valid() || sstable.get_macro_read_size() != block_handle.get_data_size())) { ret = OB_ERR_UNEXPECTED; diff --git a/src/storage/blocksstable/ob_shared_macro_block_manager.h b/src/storage/blocksstable/ob_shared_macro_block_manager.h index e807c332af..7820f3e6ff 100644 --- a/src/storage/blocksstable/ob_shared_macro_block_manager.h +++ b/src/storage/blocksstable/ob_shared_macro_block_manager.h @@ -17,9 +17,8 @@ #ifndef OCEANBASE_BLOCKSSTABLE_OB_SHARED_MACRO_BLOCK_MANAGER #define OCEANBASE_BLOCKSSTABLE_OB_SHARED_MACRO_BLOCK_MANAGER -#include "storage/blocksstable/ob_macro_block_handle.h" +#include "storage/blocksstable/ob_storage_object_handle.h" #include "lib/hash/ob_linear_hash_map.h" -#include "storage/blocksstable/ob_block_manager.h" #include "lib/task/ob_timer.h" #include "storage/compaction/ob_compaction_util.h" #include "storage/meta_mem/ob_tablet_pointer.h" @@ -35,11 +34,6 @@ class ObSSTableMergeRes; struct ObSSTableBasicMeta; struct ObWholeDataStoreDesc; -inline bool is_retryable_macro_ref_error(const int ret) -{ - return common::OB_ALLOCATE_MEMORY_FAILED == ret || common::OB_TIMEOUT == ret || common::OB_DISK_HUNG == ret; -} - struct ObBlockInfo { public: @@ -65,11 +59,10 @@ class ObSharedMacroBlockMgr final ObSharedMacroBlockMgr(); ~ObSharedMacroBlockMgr(); void destroy(); - int init(); + int init(storage_io::BlockOwner &blocks); int start(); void stop(); void wait(); - void get_cur_shared_block(MacroBlockId ¯o_id); int write_block(const char* buf, const int64_t size, ObBlockInfo &block_info, ObMacroBlocksWriteCtx &write_ctx); int add_block(const MacroBlockId &block_id, const int64_t block_size); int free_block(const MacroBlockId &block_id, const int64_t block_size); @@ -103,12 +96,14 @@ class ObSharedMacroBlockMgr final { int ret = OB_SUCCESS; bool bool_ret = true; - bool is_free = false; if (OB_UNLIKELY(MAX_RECYCLABLE_BLOCK_CNT == block_ids.count())) { bool_ret = false; execution_ret_ = OB_ITER_END; - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.check_macro_block_free(id, is_free))) { - } else if (is_free && unused_block_ids.count() < MAX_RECYCLABLE_BLOCK_CNT) { + } else if (OB_UNLIKELY(!id.is_valid())) { + ret = OB_INVALID_ARGUMENT; + } else if (!shared_mgr_.blocks_->block_live( + {static_cast(id.block_index()), id.write_seq()}) + && unused_block_ids.count() < MAX_RECYCLABLE_BLOCK_CNT) { if (OB_FAIL(unused_block_ids.push_back(id))) { } else { bool_ret = true; @@ -163,7 +158,7 @@ class ObSharedMacroBlockMgr final ObIndexBlockRebuilder *&index_block_rebuilder); int read_sstable_block( const ObSSTable &sstable, - ObMacroBlockHandle &block_handle); + ObStorageObjectHandle &block_handle); int create_new_sstable( common::ObArenaAllocator &allocator, const ObSSTableMergeRes &res, @@ -172,13 +167,13 @@ class ObSharedMacroBlockMgr final ObSSTable &new_sstable) const; int parse_merge_type(const ObSSTable &sstable, compaction::ObMergeType &merge_type) const; int try_switch_macro_block(); - static int check_write_complete( + int check_write_complete( const MacroBlockId ¯o_id, const int64_t offset, const int64_t size); - static int do_write_block( - const MacroBlockId& macro_id, - const ObMacroBlockWriteInfo &write_info, + int do_write_block( + const ObStorageObjectHandle &block, + const ObStorageObjectWriteInfo &write_info, ObBlockInfo &block_info); DISALLOW_COPY_AND_ASSIGN(ObSharedMacroBlockMgr); @@ -190,7 +185,8 @@ class ObSharedMacroBlockMgr final const static int64_t FAILURE_COUNT_INTERVAL = 10; private: - ObMacroBlockHandle macro_handle_; + storage_io::BlockOwner *blocks_ = nullptr; + ObStorageObjectHandle macro_handle_; int64_t offset_; char *common_header_buf_; int64_t header_size_; diff --git a/src/storage/blocksstable/ob_sstable.cpp b/src/storage/blocksstable/ob_sstable.cpp index 9c5adee964..97e8a1cb22 100644 --- a/src/storage/blocksstable/ob_sstable.cpp +++ b/src/storage/blocksstable/ob_sstable.cpp @@ -17,6 +17,7 @@ #define USING_LOG_PREFIX STORAGE #include "ob_sstable.h" +#include "share/io_request.h" #include "share/rc/ob_server_runtime.h" #include "storage/access/ob_sstable_multi_version_row_iterator.h" #include "storage/access/ob_sstable_row_lock_checker.h" @@ -200,15 +201,62 @@ OB_DEF_SERIALIZE_SIZE_SIMPLE(ObSSTableMetaCache) return len; } +class SSTableBlockHold final +{ +public: + SSTableBlockHold() : physical_(storage_io::new_block_group()) {} + ~SSTableBlockHold() + { + if (shared_bytes_ > 0) { + if (auto *manager = server_service()) { + // One charge comes from SSTable creation and one from the packed writer. + for (int i = 0; i < 2; ++i) { + const int ret = manager->free_block(shared_id_, shared_bytes_); + if (ret != OB_SUCCESS) { + LOG_ERROR_RET(ret, "failed to release SSTable shared block occupancy", K_(shared_id), K_(shared_bytes)); + } + } + } + } + } + + int hold(const storage_io::BlockOwner &block_file, rust::Slice members) + { + return convert_block_status(block_file.hold_blocks(members, *physical_)); + } + + int track_shared_block(const MacroBlockId &id, int64_t bytes) + { + int ret = OB_SUCCESS; + auto *manager = server_service(); + if (OB_UNLIKELY(bytes <= 0)) { + ret = OB_INVALID_DATA; + } else if (OB_ISNULL(manager)) { + ret = OB_ERR_UNEXPECTED; + } else if (OB_FAIL(manager->add_block(id, bytes))) { + } else { + shared_id_ = id; + shared_bytes_ = bytes; + } + return ret; + } + +private: + rust::Box physical_; + MacroBlockId shared_id_; + int64_t shared_bytes_ = 0; +}; + ObSSTable::ObSSTable() : addr_(), meta_cache_(), valid_for_reading_(false), is_tmp_sstable_(false), + block_hold_(), meta_(nullptr) { #if defined(__x86_64__) - static_assert(sizeof(ObSSTable) <= 264, "The size of ObSSTable will affect the meta memory manager, and the necessity of adding new fields needs to be considered."); + static_assert(sizeof(ObSSTable) <= 272, "The size of ObSSTable will affect the meta memory manager, and the necessity of adding new fields needs to be considered."); #endif } @@ -221,62 +269,41 @@ int ObSSTable::init( const ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator *allocator) { - int ret = OB_SUCCESS; - bool inc_success = false; if (OB_UNLIKELY(valid_for_reading_)) { - ret = OB_STATE_NOT_MATCH; - } else if (OB_UNLIKELY(!param.is_valid()) || OB_ISNULL(allocator)) { - ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(ObITable::init(param.table_key()))) { - } else if (OB_FAIL(init_sstable_meta(param, allocator))) { - } else if (FALSE_IT(addr_.set_mem_addr(0, sizeof(ObSSTable)))) { - } else if (OB_FAIL(inc_macro_ref(inc_success))) { - } else if (FALSE_IT(meta_->macro_info_.dec_linked_block_ref_cnt())) { - } else if (FALSE_IT(is_tmp_sstable_ = true)) { - } else if (param.is_ready_for_read()) { - if (OB_FAIL(check_valid_for_reading())) { - } + return OB_STATE_NOT_MATCH; + } + if (OB_UNLIKELY(!param.is_valid()) || OB_ISNULL(allocator)) { + return OB_INVALID_ARGUMENT; + } + if (OB_NOT_NULL(meta_)) { + return OB_INIT_TWICE; } - if (OB_FAIL(ret)) { + int ret = OB_SUCCESS; + if (OB_FAIL(ObITable::init(param.table_key()))) { + } else if (OB_FAIL(init_sstable_meta(param, allocator))) { + } else if (FALSE_IT(addr_.set_mem_addr(0, sizeof(ObSSTable)))) { + } else if (OB_FAIL(hold_blocks(param))) { + } else if (param.is_ready_for_read() && OB_FAIL(check_valid_for_reading())) { } else if (OB_UNLIKELY(!(SSTABLE_READY_FOR_READ == meta_->get_basic_meta().status_ || SSTABLE_WRITE_BUILDING == meta_->get_basic_meta().status_))) { - if (OB_SUCCESS == ret) { - ret = OB_STATE_NOT_MATCH; - } - reset(); - } else if (!lib::is_log_reduction()) { - FLOG_INFO("succeeded to init sstable", K(ret), KPC(this)); + ret = OB_STATE_NOT_MATCH; } - return ret; -} -int ObSSTable::copy_from_old_sstable(const ObSSTable &src, common::ObArenaAllocator &allocator, ObSSTable *&dst) -{ - int ret = OB_SUCCESS; - ObSSTable *sstable = nullptr; - if (OB_UNLIKELY(!src.is_valid() || !src.is_loaded())) { - ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(src.inner_deep_copy_and_inc_macro_ref(allocator, sstable))) { - } if (OB_FAIL(ret)) { - if (OB_NOT_NULL(sstable)) { - sstable->reset(); - } + reset(); } else { - dst = sstable; - FLOG_INFO("succeeded to init sstable", K(ret), KPC(dst)); + is_tmp_sstable_ = true; + if (!lib::is_log_reduction()) { + FLOG_INFO("succeeded to init sstable", K(ret), KPC(this)); + } } return ret; } void ObSSTable::reset() { - // dec ref first, then reset sstable meta - if (is_tmp_sstable_) { - ObSSTable::dec_macro_ref(); // dec the used_size added by sstable::init() - dec_used_size(); // dec the used_size added by shared macro block manager - } + block_hold_.reset(); if (nullptr != meta_) { meta_->reset(); } @@ -766,7 +793,7 @@ int ObSSTable::get_last_rowkey( return ret; } -int ObSSTable::deep_copy(ObIAllocator &allocator, ObSSTable *&dst, const bool move_macro_ref) const +int ObSSTable::deep_copy(ObIAllocator &allocator, ObSSTable *&dst) const { int ret = OB_SUCCESS; const int64_t deep_copy_size = get_deep_copy_size(); @@ -777,10 +804,6 @@ int ObSSTable::deep_copy(ObIAllocator &allocator, ObSSTable *&dst, const bool mo } else if (OB_FAIL(deep_copy(buf, deep_copy_size, meta_obj))) { } else { dst = static_cast(meta_obj); - if (move_macro_ref) { - const_cast(this)->is_tmp_sstable_ = false; - dst->is_tmp_sstable_ = true; - } } return ret; } @@ -801,8 +824,8 @@ int ObSSTable::deep_copy(char *buf, const int64_t buf_len, ObIStorageMetaObj *&v int64_t pos = sizeof(ObSSTable); pvalue->key_ = key_; pvalue->addr_ = addr_; + pvalue->block_file_ = block_file_; pvalue->meta_cache_ = meta_cache_; - pvalue->is_tmp_sstable_ = false; pvalue->valid_for_reading_ = valid_for_reading_; if (is_loaded()) { if (OB_FAIL(meta_->deep_copy(buf, buf_len, pos, pvalue->meta_))) { @@ -934,7 +957,7 @@ int ObSSTable::deserialize(common::ObArenaAllocator &allocator, if (OB_ISNULL(meta_buf = static_cast(allocator.alloc(sizeof(ObSSTableMeta))))) { ret = OB_ALLOCATE_MEMORY_FAILED; } else if (FALSE_IT(meta_ = new (meta_buf) ObSSTableMeta())) { - } else if (OB_FAIL(meta_->deserialize(allocator, buf, data_len, pos))) { + } else if (OB_FAIL(meta_->deserialize(block_file(), allocator, buf, data_len, pos))) { } else if (OB_UNLIKELY(!meta_->is_valid())) { ret = OB_ERR_UNEXPECTED; } else if (OB_FAIL(ObSSTableMetaCompactUtil::fix_filled_tx_scn_value_for_compact(key_, meta_->get_basic_meta().filled_tx_scn_))) { @@ -1092,234 +1115,36 @@ int64_t ObSSTable::get_ref() const return cnt; } -void ObSSTable::dec_macro_ref() const +int ObSSTable::hold_blocks(const ObTabletCreateSSTableParam ¶m) { int ret = OB_SUCCESS; - MacroBlockId macro_id; - ObMacroIdIterator iterator; - common::ObArenaAllocator tmp_allocator(common::ObMemAttr("CacheSST")); - ObSafeArenaAllocator safe_allocator(tmp_allocator); - ObSSTableMetaHandle meta_handle; - - if (OB_FAIL(dec_used_size())) { - } - do { - safe_allocator.reuse(); - ret = get_meta(meta_handle, &safe_allocator); - } while (is_retryable_macro_ref_error(ret)); - if (OB_FAIL(ret)) { - } else if (OB_UNLIKELY(!meta_handle.is_valid())) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("meta handle is invalid", K(ret), K(meta_handle)); - } else { - do { - iterator.reset(); - ret = meta_handle.get_sstable_meta().get_macro_info().get_data_block_iter(iterator); - } while (is_retryable_macro_ref_error(ret)); - if (OB_FAIL(ret)) { - } else { - while (OB_SUCC(iterator.get_next_macro_id(macro_id))) { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } else { - LOG_DEBUG("barry debug decrease data ref cnt", K(macro_id), KPC(this), K(lbt())); - } - } - } - - do { - iterator.reset(); - ret = meta_handle.get_sstable_meta().get_macro_info().get_other_block_iter(iterator); - } while (is_retryable_macro_ref_error(ret)); - if (OB_FAIL(ret)) { - } else { - while (OB_SUCC(iterator.get_next_macro_id(macro_id))) { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } else { - LOG_DEBUG("barry debug decrease other ref cnt", K(macro_id), KPC(this), K(lbt())); - } - } - } - iterator.reset(); - if (OB_FAIL(meta_handle.get_sstable_meta().get_macro_info().get_linked_block_iter(iterator))) { - } else { - while (OB_SUCC(iterator.get_next_macro_id(macro_id))) { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } else { - LOG_DEBUG("barry debug decrease link ref cnt", K(macro_id), KPC(this), K(lbt())); - } - } - } - } -} - -int ObSSTable::inc_macro_ref(bool &inc_success) const -{ - int ret = OB_SUCCESS; - int tmp_ret = OB_SUCCESS; - inc_success = false; - MacroBlockId macro_id; - ObMacroIdIterator iter; - int64_t data_blk_cnt = 0; - int64_t other_blk_cnt = 0; - int64_t linked_blk_cnt = 0; - common::ObArenaAllocator tmp_allocator(common::ObMemAttr("CacheSST")); - ObSafeArenaAllocator safe_allocator(tmp_allocator); - ObSSTableMetaHandle meta_handle; - if (OB_FAIL(get_meta(meta_handle, &safe_allocator))) { - } else if (OB_UNLIKELY(!meta_handle.is_valid())) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(meta_handle.get_sstable_meta().get_macro_info().get_data_block_iter(iter))) { - } else if (OB_UNLIKELY(!iter.is_valid())) { - ret = OB_ERR_UNEXPECTED; - } else { - while (OB_SUCC(ret)) { - if (OB_FAIL(iter.get_next_macro_id(macro_id))) { - if (OB_UNLIKELY(OB_ITER_END != ret)) { - } - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(macro_id))) { + ObSEArray members; + const auto append = [&](const ObIArray &ids, storage_io::BlockKind kind) { + int result = OB_SUCCESS; + for (int64_t i = 0; result == OB_SUCCESS && i < ids.count(); ++i) { + const auto &id = ids.at(i); + if (OB_UNLIKELY(!id.is_valid() || id.block_index() <= 0)) { + result = OB_INVALID_DATA; } else { - ++data_blk_cnt; + result = members.push_back({{static_cast(id.block_index()), id.write_seq()}, kind}); } - LOG_DEBUG("barry debug increase data ref cnt", K(ret), K(macro_id), KPC(this), K(lbt())); } - iter.reset(); - } - - if (OB_FAIL(ret) && OB_ITER_END != ret) { - } else if (OB_FAIL(meta_handle.get_sstable_meta().get_macro_info().get_other_block_iter(iter))) { - } else if (OB_UNLIKELY(!iter.is_valid())) { + return result; + }; + const bool shared = is_small_sstable() && get_data_macro_block_count() != 0; + if (shared && OB_UNLIKELY(param.data_block_ids_.count() != 1 || get_data_macro_block_count() != 1)) { ret = OB_ERR_UNEXPECTED; - } else { - while (OB_SUCC(ret)) { - if (OB_FAIL(iter.get_next_macro_id(macro_id))) { - if (OB_UNLIKELY(OB_ITER_END != ret)) { - } - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(macro_id))) { - } else { - ++other_blk_cnt; - } - LOG_DEBUG("barry debug increase other ref cnt", K(ret), K(macro_id), KPC(this), K(lbt())); - } - iter.reset(); - } - - if (OB_FAIL(ret) && OB_ITER_END != ret) { - } else if (OB_FAIL(meta_handle.get_sstable_meta().get_macro_info().get_linked_block_iter(iter))) { - } else if (OB_UNLIKELY(!iter.is_valid())) { - ret = OB_ERR_UNEXPECTED; - } else { - while (OB_SUCC(ret)) { - if (OB_FAIL(iter.get_next_macro_id(macro_id))) { - if (OB_UNLIKELY(OB_ITER_END != ret)) { - } - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(macro_id))) { - } else { - ++linked_blk_cnt; - } - LOG_DEBUG("barry debug increase link ref cnt", K(ret), K(macro_id), KPC(this), K(lbt())); - } - iter.reset(); - } - - if (OB_SUCCESS == ret || OB_ITER_END == ret) { - ret = OB_SUCCESS; - } - - if ((OB_SUCC(ret) || OB_LIKELY(OB_ITER_END == ret)) - && OB_FAIL(add_used_size())) { - } - - if (OB_SUCC(ret)) { - inc_success = true; - } else if (meta_handle.is_valid()) { - int tmp_ret = OB_SUCCESS; - if (OB_TMP_FAIL(meta_handle.get_sstable_meta().get_macro_info().get_data_block_iter(iter))) { - } else { - for (int64_t i = data_blk_cnt; i > 0; --i) { // ignore ret - if (OB_TMP_FAIL(iter.get_next_macro_id(macro_id))) { - } else if (OB_TMP_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } else { - LOG_DEBUG("barry debug decrease data ref cnt", K(macro_id), KPC(this), K(lbt())); - } - } - iter.reset(); - } - if (OB_TMP_FAIL(meta_handle.get_sstable_meta().get_macro_info().get_other_block_iter(iter))) { - } else { - for (int64_t i = other_blk_cnt; i > 0; --i) { // ignore ret - if (OB_TMP_FAIL(iter.get_next_macro_id(macro_id))) { - } else if (OB_TMP_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } else { - LOG_DEBUG("barry debug decrease other ref cnt", K(macro_id), KPC(this), K(lbt())); - } - } - iter.reset(); - } - if (OB_TMP_FAIL(meta_handle.get_sstable_meta().get_macro_info().get_linked_block_iter(iter))) { - } else { - for (int64_t i = linked_blk_cnt; i > 0; --i) { - if (OB_TMP_FAIL(iter.get_next_macro_id(macro_id))) { - } else if (OB_TMP_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } else { - LOG_DEBUG("barry debug decrease link ref cnt", K(macro_id), KPC(this), K(lbt())); - } - } - iter.reset(); - } - } - - return ret; -} - -int ObSSTable::add_used_size() const -{ - int ret = OB_SUCCESS; - ObSSTableMetaHandle meta_handle; - ObMacroIdIterator id_iterator; - MacroBlockId macro_id; - if (OB_FAIL(get_meta(meta_handle))) { - } else if (!is_small_sstable() || 0 == get_data_macro_block_count()) { - // A normal or empty SSTable occupies no nested range. - } else if (OB_UNLIKELY(1 != get_data_macro_block_count())) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(meta_handle.get_sstable_meta() - .get_macro_info() - .get_data_block_iter(id_iterator))) { - } else if (OB_FAIL(id_iterator.get_next_macro_id(macro_id))) { - } else { - ObSharedMacroBlockMgr *shared_block_mgr = - ::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>(); - if (OB_ISNULL(shared_block_mgr)) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL( - shared_block_mgr->add_block(macro_id, get_macro_read_size()))) { + } else if (OB_FAIL(append(param.data_block_ids_, storage_io::BlockKind::Data))) { + } else if (OB_FAIL(append(param.other_block_ids_, storage_io::BlockKind::Metadata))) { + } else if (!members.empty()) { + std::unique_ptr hold(new (std::nothrow) SSTableBlockHold()); + if (!hold) { + ret = OB_ALLOCATE_MEMORY_FAILED; + } else if (OB_FAIL(hold->hold(block_file(), {members.get_data(), static_cast(members.count())}))) { + } else if (shared && OB_FAIL(hold->track_shared_block(param.data_block_ids_.at(0), get_macro_read_size()))) { } - } - return ret; -} - -int ObSSTable::dec_used_size() const -{ - int ret = OB_SUCCESS; - ObSSTableMetaHandle meta_handle; - ObMacroIdIterator id_iterator; - MacroBlockId macro_id; - if (OB_FAIL(get_meta(meta_handle))) { - } else if (!is_small_sstable() || 0 == get_data_macro_block_count()) { - // A normal or empty SSTable occupies no nested range. - } else if (OB_UNLIKELY(1 != get_data_macro_block_count())) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(meta_handle.get_sstable_meta() - .get_macro_info() - .get_data_block_iter(id_iterator))) { - } else if (OB_FAIL(id_iterator.get_next_macro_id(macro_id))) { - } else { - ObSharedMacroBlockMgr *shared_block_mgr = - ::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>(); - if (OB_ISNULL(shared_block_mgr)) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL( - shared_block_mgr->free_block(macro_id, get_macro_read_size()))) { + if (OB_SUCC(ret)) { + block_hold_ = std::move(hold); } } return ret; @@ -1462,9 +1287,9 @@ int ObSSTable::get_meta( ObStorageMetaValue::MetaType meta_type = ObStorageMetaValue::MetaType::SSTABLE; const bool bypass_cache = nullptr != allocator; if (!bypass_cache) { - if (OB_FAIL(meta_cache.get_meta(meta_type, meta_key, meta_handle.handle_, nullptr))) { + if (OB_FAIL(meta_cache.get_meta(block_file(), meta_type, meta_key, meta_handle.handle_, nullptr))) { } - } else if (OB_FAIL(meta_cache.bypass_get_meta(meta_type, meta_key, *allocator, meta_handle.handle_))) { + } else if (OB_FAIL(meta_cache.bypass_get_meta(block_file(), meta_type, meta_key, *allocator, meta_handle.handle_))) { } if (FAILEDx(meta_handle.handle_.get_value(value))) { } else if (OB_ISNULL(value)) { @@ -1499,7 +1324,7 @@ int ObSSTable::bypass_load_meta(common::ObArenaAllocator &allocator) ObSSTable *sstable_ptr = nullptr; ObStorageMetaKey meta_key(addr_); ObStorageMetaValue::MetaType meta_type = ObStorageMetaValue::MetaType::SSTABLE; - if (OB_FAIL(meta_cache.bypass_get_meta(meta_type, meta_key, safe_allocator, meta_handle.handle_))) { + if (OB_FAIL(meta_cache.bypass_get_meta(block_file(), meta_type, meta_key, safe_allocator, meta_handle.handle_))) { } else if (OB_FAIL(meta_handle.handle_.get_value(value))) { } else if (OB_ISNULL(value)) { ret = OB_ERR_UNEXPECTED; @@ -1529,7 +1354,7 @@ int ObSSTable::init_sstable_meta( if (OB_ISNULL(buf)) { ret = OB_ALLOCATE_MEMORY_FAILED; } else if (FALSE_IT(meta_ = new (buf) ObSSTableMeta())) { - } else if (OB_FAIL(meta_->init(param, *allocator))) { + } else if (OB_FAIL(meta_->init(block_file(), param, *allocator))) { } else if (OB_FAIL(meta_->transform_root_block_extra_buf(*allocator))) { } else if (OB_FAIL(meta_cache_.init(meta_, is_multi_version_table()))) { } @@ -1550,43 +1375,5 @@ int ObSSTable::fill_column_ckm_array(ObIArray &column_checksums) const return ret; } -int ObSSTable::inner_deep_copy_and_inc_macro_ref( - common::ObIAllocator &allocator, - ObSSTable *&sstable) const -{ - int ret = OB_SUCCESS; - bool inc_success = false; - const int64_t deep_copy_size = get_deep_copy_size(); - char *buf = nullptr; - ObIStorageMetaObj *meta_obj = nullptr; - ObSSTable *table = nullptr; - if (OB_ISNULL(buf = static_cast(allocator.alloc(deep_copy_size)))) { - ret = OB_ALLOCATE_MEMORY_FAILED; - } else if (OB_FAIL(deep_copy(buf, deep_copy_size, meta_obj))) { - } else { - table = static_cast(meta_obj); - table->addr_.set_mem_addr(0, deep_copy_size); - if (OB_FAIL(table->inc_macro_ref(inc_success))) { - } else if (!inc_success) { - ret = OB_ERR_UNEXPECTED; - } else { - table->is_tmp_sstable_ = true; - } - } - if (OB_FAIL(ret)) { - if (OB_NOT_NULL(table)) { - table->reset(); - } - if (OB_NOT_NULL(buf)) { - allocator.free(buf); - } - } else { - sstable = table; - LOG_INFO("succeeded to copy sstable and increase macro reference count", K(ret), KPC(sstable)); - } - -return ret; -} - } // namespace blocksstable } // namespace oceanbase diff --git a/src/storage/blocksstable/ob_sstable.h b/src/storage/blocksstable/ob_sstable.h index 5f9d1e2aa5..8265de0643 100644 --- a/src/storage/blocksstable/ob_sstable.h +++ b/src/storage/blocksstable/ob_sstable.h @@ -24,6 +24,7 @@ #include "share/scn.h" #include "ob_datum_range.h" #include "storage/ddl/ob_ddl_struct.h" +#include namespace oceanbase { @@ -38,6 +39,7 @@ namespace blocksstable { extern const char *DDL_EMPTY_SSTABLE_DUMMY_INDEX_DATA_BUF; extern const int64_t DDL_EMPTY_SSTABLE_DUMMY_INDEX_DATA_SIZE; +class SSTableBlockHold; class ObSSTableIndexScanParam; class ObSSTableIndexScanner; class ObSSTableSecMetaIterator; @@ -124,6 +126,8 @@ class ObSSTable : public ObITable, public ObIStorageMetaObj { public: ObSSTable(); + void bind_block_file(storage_io::BlockOwner &block_file) { block_file_ = &block_file; } + storage_io::BlockOwner &block_file() const { return *block_file_; } virtual ~ObSSTable(); // From 4.2, the SSTable object reference count will be abandoned. Otherwise, when SSTable @@ -135,7 +139,6 @@ class ObSSTable : public ObITable, public ObIStorageMetaObj virtual int init( const ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator *allocator); - static int copy_from_old_sstable(const ObSSTable &old_sstable, common::ObArenaAllocator &allocator, ObSSTable *&sstable); void reset(); // Query interfaces @@ -266,8 +269,6 @@ class ObSSTable : public ObITable, public ObIStorageMetaObj get_key().get_end_scn().get_val_for_tx(); } virtual int get_frozen_schema_version(int64_t &schema_version) const override; - virtual int inc_macro_ref(bool &inc_success) const; - virtual void dec_macro_ref() const; OB_INLINE bool is_valid() const { return valid_for_reading_; } OB_INLINE bool is_loaded() const { return nullptr != meta_; } int persist_linked_block_if_need( @@ -286,7 +287,7 @@ class ObSSTable : public ObITable, public ObIStorageMetaObj common::ObIAllocator &allocator, ObDatumRowkey &endkey); - int deep_copy(common::ObIAllocator &allocator, ObSSTable *&dst, const bool move_macro_ref = false) const; + int deep_copy(common::ObIAllocator &allocator, ObSSTable *&dst) const; virtual int deep_copy(char *buf, const int64_t buf_len, ObIStorageMetaObj *&value) const override; virtual int64_t get_deep_copy_size() const override { @@ -333,8 +334,7 @@ class ObSSTable : public ObITable, public ObIStorageMetaObj static const int64_t AARCH64_CP_BUF_ALIGN = 8; protected: int check_valid_for_reading(); - int add_used_size() const; - int dec_used_size() const; + int hold_blocks(const ObTabletCreateSSTableParam ¶m); int init_sstable_meta( const ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator *allocator); @@ -343,7 +343,6 @@ class ObSSTable : public ObITable, public ObIStorageMetaObj int deserialize_fixed_struct(const char *buf, const int64_t data_len, int64_t &pos); int64_t get_sstable_fix_serialize_size() const; int64_t get_sstable_fix_serialize_payload_size() const; - int inner_deep_copy_and_inc_macro_ref(common::ObIAllocator &allocator, ObSSTable *&sstable) const; protected: static const int64_t SSTABLE_VERSION = 2; struct StatusForSerialize @@ -369,6 +368,8 @@ class ObSSTable : public ObITable, public ObIStorageMetaObj // in-memory bool valid_for_reading_; bool is_tmp_sstable_; + std::unique_ptr block_hold_; + storage_io::BlockOwner *block_file_ = nullptr; // serialized blocksstable::ObSSTableMeta *meta_; DISALLOW_COPY_AND_ASSIGN(ObSSTable); diff --git a/src/storage/blocksstable/ob_sstable_meta.cpp b/src/storage/blocksstable/ob_sstable_meta.cpp index c568c83b40..1be8262e36 100644 --- a/src/storage/blocksstable/ob_sstable_meta.cpp +++ b/src/storage/blocksstable/ob_sstable_meta.cpp @@ -16,8 +16,8 @@ #define USING_LOG_PREFIX STORAGE -#include "storage/blocksstable/ob_block_manager.h" #include "ob_sstable_meta.h" +#include "share/io_request.h" #include "storage/blocksstable/index_block/ob_index_block_builder.h" #include "storage/tablet/ob_tablet_create_sstable_param.h" @@ -524,14 +524,15 @@ ObSSTableMeta::~ObSSTableMeta() reset(); } -int ObSSTableMeta::load_root_block_data(common::ObArenaAllocator &allocator) +int ObSSTableMeta::load_root_block_data( + storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator) { int ret = OB_SUCCESS; ObMicroBlockDesMeta des_meta(basic_meta_.compressor_type_, basic_meta_.root_row_store_type_); if (OB_UNLIKELY(SSTABLE_WRITE_BUILDING != basic_meta_.status_)) { ret = OB_STATE_NOT_MATCH; - } else if (OB_FAIL(data_root_info_.load_root_block_data(allocator, des_meta))) { - } else if (OB_FAIL(macro_info_.load_root_block_data(allocator, des_meta))) { + } else if (OB_FAIL(data_root_info_.load_root_block_data(block_file, allocator, des_meta))) { + } else if (OB_FAIL(macro_info_.load_root_block_data(block_file, allocator, des_meta))) { } return ret; } @@ -615,19 +616,21 @@ bool ObSSTableMeta::check_meta() const && macro_info_.is_valid(); } -int ObSSTableMeta::fsync_block(const ObTabletCreateSSTableParam ¶m) +int ObSSTableMeta::fsync_block( + const storage_io::BlockOwner &block_file, const ObTabletCreateSSTableParam ¶m) { int ret = OB_SUCCESS; const bool root_block_in_disk = param.root_block_addr_.is_disked(); const bool macro_meta_in_disk = param.data_block_macro_meta_addr_.is_disked(); if (root_block_in_disk || macro_meta_in_disk) { - if (OB_FAIL(OB_SERVER_BLOCK_MGR.fsync_block())) { + if (OB_FAIL(convert_block_status(block_file.sync_blocks()))) { } } return ret; } int ObSSTableMeta::init( + storage_io::BlockOwner &block_file, const ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator &allocator) { @@ -640,9 +643,9 @@ int ObSSTableMeta::init( } else if (OB_FAIL(init_data_index_tree_info(param, allocator))) { } else if (OB_UNLIKELY(SSTABLE_WRITE_BUILDING != basic_meta_.status_)) { ret = OB_STATE_NOT_MATCH; - } else if (OB_FAIL(macro_info_.init_macro_info(allocator, param))) { - } else if (OB_FAIL(fsync_block(param))) { - } else if (OB_FAIL(load_root_block_data(allocator))) { + } else if (OB_FAIL(macro_info_.init_macro_info(block_file, allocator, param))) { + } else if (OB_FAIL(fsync_block(block_file, param))) { + } else if (OB_FAIL(load_root_block_data(block_file, allocator))) { } else if (OB_UNLIKELY(!check_meta())) { ret = OB_ERR_UNEXPECTED; } @@ -688,6 +691,7 @@ int ObSSTableMeta::serialize_(char *buf, const int64_t buf_len, int64_t &pos) co } int ObSSTableMeta::deserialize( + storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator, const char *buf, const int64_t data_len, @@ -707,7 +711,7 @@ int ObSSTableMeta::deserialize( if (OB_FAIL(ret)) { } else if (OB_UNLIKELY(version != SSTABLE_META_VERSION)) { ret = OB_NOT_SUPPORTED; - } else if (OB_FAIL(deserialize_(allocator, buf + pos, len, tmp_pos))) { + } else if (OB_FAIL(deserialize_(block_file, allocator, buf + pos, len, tmp_pos))) { } else if (OB_UNLIKELY(len != tmp_pos)) { ret = OB_ERR_UNEXPECTED; } else { @@ -722,6 +726,7 @@ int ObSSTableMeta::deserialize( } int ObSSTableMeta::deserialize_( + storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator, const char *buf, const int64_t data_len, @@ -733,8 +738,8 @@ int ObSSTableMeta::deserialize_( } else { ObMicroBlockDesMeta des_meta(basic_meta_.compressor_type_, basic_meta_.root_row_store_type_); - if (OB_FAIL(data_root_info_.deserialize(allocator, des_meta, buf, data_len, pos))) { - } else if (OB_FAIL(macro_info_.deserialize(allocator, des_meta, buf, data_len, pos))) { + if (OB_FAIL(data_root_info_.deserialize(block_file, allocator, des_meta, buf, data_len, pos))) { + } else if (OB_FAIL(macro_info_.deserialize(block_file, allocator, des_meta, buf, data_len, pos))) { } else if (OB_FAIL(tx_ctx_.deserialize(allocator, buf, data_len, pos))) { } } diff --git a/src/storage/blocksstable/ob_sstable_meta.h b/src/storage/blocksstable/ob_sstable_meta.h index 20f459fb1a..d9f520954e 100644 --- a/src/storage/blocksstable/ob_sstable_meta.h +++ b/src/storage/blocksstable/ob_sstable_meta.h @@ -194,6 +194,7 @@ class ObSSTableMeta final ObSSTableMeta(); ~ObSSTableMeta(); int init( + storage_io::BlockOwner &block_file, const storage::ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator &allocator); void reset(); @@ -273,13 +274,14 @@ class ObSSTableMeta final OB_INLINE int64_t get_progressive_merge_step() const { return basic_meta_.progressive_merge_step_; } OB_INLINE const ObRootBlockInfo &get_root_info() const { return data_root_info_; } OB_INLINE const ObSSTableMacroInfo &get_macro_info() const { return macro_info_; } - int load_root_block_data(common::ObArenaAllocator &allocator); //TODO:@jinzhu remove me after using kv cache. + int load_root_block_data(storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator); //TODO:@jinzhu remove me after using kv cache. inline int transform_root_block_extra_buf(common::ObArenaAllocator &allocator) { return data_root_info_.transform_root_block_extra_buf(allocator); } int serialize(char *buf, const int64_t buf_len, int64_t &pos) const; int deserialize( + storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator, const char *buf, const int64_t data_len, @@ -298,7 +300,7 @@ class ObSSTableMeta final int get_column_checksums(common::ObIArray &column_checksums) const; TO_STRING_KV(K_(basic_meta), K_(column_ckm_struct), K_(data_root_info), K_(macro_info), K_(tx_ctx), K_(is_inited)); private: - int fsync_block(const ObTabletCreateSSTableParam ¶m); + int fsync_block(const storage_io::BlockOwner &block_file, const ObTabletCreateSSTableParam ¶m); bool check_meta() const; int init_base_meta(const ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator &allocator); int init_data_index_tree_info( @@ -306,6 +308,7 @@ class ObSSTableMeta final common::ObArenaAllocator &allocator); int serialize_(char *buf, const int64_t buf_len, int64_t &pos) const; int deserialize_( + storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator, const char *buf, const int64_t data_len, diff --git a/src/storage/blocksstable/ob_storage_object_handle.cpp b/src/storage/blocksstable/ob_storage_object_handle.cpp index 6d9686af3c..397df09186 100644 --- a/src/storage/blocksstable/ob_storage_object_handle.cpp +++ b/src/storage/blocksstable/ob_storage_object_handle.cpp @@ -18,9 +18,10 @@ #include "rust/config.h" #include "ob_storage_object_handle.h" -#include "storage/blocksstable/ob_block_manager.h" -#include "share/config/ob_server_config.h" -#include "share/rc/ob_server_runtime.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" +#include "storage/meta_store/storage_meta_service.h" +#include +#include "lib/time/ob_time_utility.h" namespace oceanbase { @@ -29,38 +30,18 @@ namespace blocksstable using namespace oceanbase::storage; -ObStorageObjectHandle::~ObStorageObjectHandle() -{ - reset(); -} +ObStorageObjectHandle::~ObStorageObjectHandle() = default; -ObStorageObjectHandle::ObStorageObjectHandle(const ObStorageObjectHandle &other) -{ - *this = other; -} +ObStorageObjectHandle::ObStorageObjectHandle(const ObStorageObjectHandle &other) = default; -ObStorageObjectHandle &ObStorageObjectHandle::operator=(const ObStorageObjectHandle &other) -{ - int ret = OB_SUCCESS; - if (&other != this) { - reset(); - io_handle_ = other.io_handle_; - macro_id_ = other.macro_id_; - if (macro_id_.is_valid()) { - if (OB_FAIL(OB_SERVER_BLOCK_MGR.inc_ref(macro_id_))) { - } - if (OB_FAIL(ret)) { - macro_id_.reset(); - } - } - } - return *this; -} +ObStorageObjectHandle &ObStorageObjectHandle::operator=(const ObStorageObjectHandle &other) = default; void ObStorageObjectHandle::reset() { io_handle_.reset(); - reset_macro_id(); + group_.reset(); + macro_id_.reset(); + blocks_ = nullptr; } void ObStorageObjectHandle::reuse() @@ -68,109 +49,195 @@ void ObStorageObjectHandle::reuse() reset(); } -void ObStorageObjectHandle::reset_macro_id() +namespace { +storage_io::BlockAddress block_address(const MacroBlockId &id) +{ + return {static_cast(id.block_index()), id.write_seq()}; +} + +int64_t handle_io_timeout_us(const int64_t timeout_ms) +{ + return std::min(timeout_ms, config::_data_storage_io_timeout() / 1000L) * 1000L; +} +} + +int check_block_space(storage_io::BlockOwner &blocks, int64_t required_size, bool alarm_if_space_full) { + if (required_size < 0) { return OB_INVALID_ARGUMENT; } int ret = OB_SUCCESS; - if (macro_id_.is_valid()) { - if (OB_FAIL(OB_SERVER_BLOCK_MGR.dec_ref(macro_id_))) { - } else { - macro_id_.reset(); - } + int64_t reserved = 0; + if (OB_FAIL(STORAGE_META_SERVICE.get_reserved_size(reserved))) { return ret; } + ret = common::convert_block_status(blocks.check_block_space(required_size, + config::datafile_maxsize(), reserved, config::data_disk_usage_limit_percentage())); + if (ret == OB_SERVER_OUTOF_DISK_SPACE && alarm_if_space_full + && REACH_TIME_INTERVAL(24 * 3600LL * 1000 * 1000)) { + LOG_DBA_ERROR_V2(OB_SHARE_OUTOF_DISK_SPACE, ret, + "disk is almost full. required size is ", required_size, + ". [suggestion] Increase the datafile_size or datafile_disk_percentage parameter. "); } - abort_unless(OB_SUCCESS == ret); + return ret; } -int ObStorageObjectHandle::report_bad_block() const +int collect_bad_block_infos(storage_io::BlockOwner &blocks, common::ObIArray &out) { int ret = OB_SUCCESS; - int io_errno = 0; - if (OB_FAIL(io_handle_.get_fs_errno(io_errno))) { - } else if (0 != io_errno) { - LOG_ERROR("fail to io macro block", K(macro_id_), K(ret), K(io_errno)); - char error_msg[common::OB_MAX_ERROR_MSG_LEN]; - MEMSET(error_msg, 0, sizeof(error_msg)); - if (OB_FAIL(databuff_printf(error_msg, - sizeof(error_msg), - "Sys IO error, ret=%d, errno=%d, errstr=%s", - ret, - io_errno, - strerror(io_errno)))){ - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.report_bad_block(macro_id_, - ret, - error_msg, - config::data_dir().c_str()))) { + out.reset(); + for (const auto &failure : blocks.block_failures()) { + ObBadBlockInfo info; + info.macro_block_id_ = MacroBlockId(failure.address.generation, failure.address.index, failure.third_id); + info.disk_id_ = info.macro_block_id_.first_id(); + info.error_type_ = failure.error_type; + info.check_time_ = failure.observed_us; + if (!failure.file.empty()) { + MEMCPY(info.store_file_path_, failure.file.data(), + std::min(failure.file.size(), sizeof(info.store_file_path_) - 1)); + } + if (!failure.message.empty()) { + MEMCPY(info.error_msg_, failure.message.data(), + std::min(failure.message.size(), sizeof(info.error_msg_) - 1)); + } + if (OB_FAIL(out.push_back(info))) { + break; } } return ret; } - - -int ObStorageObjectHandle::async_read(const ObStorageObjectReadInfo &read_info, - std::unique_ptr callback) +void ObStorageObjectHandle::report_bad_block(int error_type) const { - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!read_info.is_valid())) { - ret = OB_INVALID_ARGUMENT; - } else { - if (OB_FAIL(sn_async_read(read_info, std::move(callback)))) { + int io_errno = 0; + if (blocks_ == nullptr || error_type == OB_TIMEOUT || !macro_id_.is_valid() || + io_handle_.get_fs_errno(io_errno) != OB_SUCCESS || io_errno == 0) { + return; + } + LOG_ERROR_RET(error_type, "macro block I/O failed", K(macro_id_), K(io_errno)); + char message[common::OB_MAX_ERROR_MSG_LEN]; + const int ret = databuff_printf(message, sizeof(message), + "Sys IO error, ret=%d, errno=%d, errstr=%s", error_type, io_errno, strerror(io_errno)); + if (ret == OB_SUCCESS) { + auto path = config::data_dir(); + storage_io::BlockFailure failure{}; + failure.address = block_address(macro_id_); + failure.third_id = macro_id_.third_id(); + failure.error_type = error_type; + failure.observed_us = ObTimeUtility::current_time(); + const auto append = [](const char *text, rust::Vec &bytes) { + const size_t length = STRLEN(text); + bytes.reserve(length); + for (size_t i = 0; i < length; ++i) { + bytes.push_back(static_cast(text[i])); + } + }; + append(path.c_str(), failure.file); + append(message, failure.message); + const int report_ret = common::convert_block_status(blocks_->record_block_failure(std::move(failure))); + if (report_ret != OB_SUCCESS) { + LOG_WARN("failed to record macro block I/O error", K(report_ret), K(macro_id_)); } } - return ret; } -int ObStorageObjectHandle::async_write(const ObStorageObjectWriteInfo &write_info) +int ObStorageObjectHandle::allocate(storage_io::BlockOwner &blocks) { int ret = OB_SUCCESS; - if (OB_UNLIKELY(!write_info.is_valid())) { - ret = OB_INVALID_ARGUMENT; + int64_t reserved = 0; + if (macro_id_.is_valid()) { + ret = OB_ERR_SYS; + } else if (OB_FAIL(STORAGE_META_SERVICE.get_reserved_size(reserved))) { } else { - if (OB_FAIL(sn_async_write(write_info))) { + storage_io::BlockGrowth policy{}; + policy.max_bytes = config::datafile_maxsize(); + policy.next_bytes = config::datafile_next(); + policy.reserved_bytes = reserved; + auto allocated = blocks.allocate_held_block(policy); + if (OB_FAIL(common::convert_block_status(allocated.status))) { + } else if (OB_FAIL(adopt(MacroBlockId(allocated.address.generation, allocated.address.index, 0), + std::move(allocated.hold)))) { + } else { + blocks_ = &blocks; } } return ret; } -int ObStorageObjectHandle::sn_async_read(const ObStorageObjectReadInfo &read_info, +int ObStorageObjectHandle::allocate_and_write( + storage_io::BlockOwner &blocks, const ObStorageObjectWriteInfo &write_info) +{ + if (!write_info.is_valid()) { return OB_INVALID_ARGUMENT; } + const int ret = allocate(blocks); + return ret == OB_SUCCESS ? submit_write(write_info) : ret; +} + +int ObStorageObjectHandle::async_read(storage_io::BlockOwner &blocks, + const ObStorageObjectReadInfo &read_info, std::unique_ptr callback) { int ret = OB_SUCCESS; if (OB_UNLIKELY(!read_info.is_valid())) { ret = OB_INVALID_ARGUMENT; } else { - reuse(); - if (OB_FAIL(ObBlockManager::submit_handle_read( - read_info.macro_block_id_, read_info.offset_, read_info.size_, read_info.io_desc_, - read_info.io_timeout_ms_, std::move(callback), io_handle_))) { - } else if (OB_FAIL(set_macro_block_id(read_info.macro_block_id_))) { + // Keep the old block alive until the new request has acquired its hold. + const auto previous_group = group_; + reset(); + const auto options = common::make_request_options( + read_info.io_desc_, storage_io::RequestMode::Read, + read_info.offset_, read_info.size_, handle_io_timeout_us(read_info.io_timeout_ms_)); + auto read = blocks.submit_block_read(block_address(read_info.macro_block_id_), + options, std::move(callback)); + if (OB_FAIL(common::accept_io_request(std::move(read.request), io_handle_))) { + } else if (OB_FAIL(adopt(read_info.macro_block_id_, std::move(read.hold)))) { + io_handle_.reset(); + } else { + blocks_ = &blocks; } } return ret; } -int ObStorageObjectHandle::sn_async_write(const ObStorageObjectWriteInfo &write_info) +int ObStorageObjectHandle::read(storage_io::BlockOwner &blocks, + const ObStorageObjectReadInfo &read_info, + std::unique_ptr callback) { - int ret = OB_SUCCESS; - if (OB_FAIL(ObBlockManager::submit_handle_write(macro_id_, write_info, io_handle_))) { - } else { - FLOG_INFO("Async write macro block", K(macro_id_)); + const int ret = async_read(blocks, read_info, std::move(callback)); + return ret == OB_SUCCESS ? wait() : ret; +} + +int ObStorageObjectHandle::async_write(const ObStorageObjectWriteInfo &write_info) +{ + if (OB_UNLIKELY(!write_info.is_valid())) { + return OB_INVALID_ARGUMENT; + } else if (blocks_ == nullptr) { + reset(); + return OB_INVALID_ARGUMENT; } - if (OB_FAIL(ret)) { + return submit_write(write_info); +} + +int ObStorageObjectHandle::submit_write(const ObStorageObjectWriteInfo &write_info) +{ + io_handle_.reset(); + const auto options = common::make_request_options( + write_info.io_desc_, storage_io::RequestMode::Write, + write_info.offset_, write_info.size_, handle_io_timeout_us(write_info.io_timeout_ms_)); + const rust::Slice bytes{ + reinterpret_cast(write_info.buffer_), static_cast(write_info.size_)}; + const int ret = common::accept_io_request( + blocks_->submit_block(block_address(macro_id_), options, bytes, nullptr), io_handle_); + if (ret != OB_SUCCESS) { reset(); + } else { + FLOG_INFO("Async write macro block", K(macro_id_)); } return ret; } - int ObStorageObjectHandle::wait() { int ret = OB_SUCCESS; if (io_handle_.is_empty()) { // do nothing } else if (OB_FAIL(io_handle_.wait())) { - int tmp_ret = OB_SUCCESS; - if (OB_SUCCESS != (tmp_ret = report_bad_block())) { - } + report_bad_block(ret); io_handle_.reset(); } return ret; @@ -181,25 +248,72 @@ int ObStorageObjectHandle::get_io_time_us(int64_t &io_time_us) const return io_handle_.get_io_time_us(io_time_us); } -int ObStorageObjectHandle::set_macro_block_id(const MacroBlockId ¯o_block_id) +namespace { +int share_group(rust::Box group, BlockHold &hold) { - int ret = common::OB_SUCCESS; + try { + hold = std::make_shared>(std::move(group)); + } catch (const std::bad_alloc &) { + return OB_ALLOCATE_MEMORY_FAILED; + } + return OB_SUCCESS; +} +} - if (macro_id_.is_valid()) { - ret = common::OB_ERR_SYS; - LOG_ERROR("cannot set macro block id twice", K(ret), K(macro_block_id), K(*this)); - } else if (!macro_block_id.is_valid()) { - ret = common::OB_INVALID_ARGUMENT; - } else { - macro_id_ = macro_block_id; - if (OB_FAIL(OB_SERVER_BLOCK_MGR.inc_ref(macro_id_))) { - } - if (OB_FAIL(ret)) { - macro_id_.reset(); - } +int retain_block(storage_io::BlockOwner &blocks, const MacroBlockId &id, BlockHold &hold) +{ + if (!id.is_valid()) { return OB_INVALID_ARGUMENT; } + const storage_io::BlockMember member{ + {static_cast(id.block_index()), id.write_seq()}, + storage_io::BlockKind::Metadata}; + auto group = storage_io::new_block_group(); + const int ret = common::convert_block_status(blocks.hold_blocks({&member, 1}, *group)); + return ret == OB_SUCCESS ? share_group(std::move(group), hold) : ret; +} + +int ObStorageObjectHandle::adopt(const MacroBlockId &id, rust::Box group) +{ + const int ret = share_group(std::move(group), group_); + if (ret == OB_SUCCESS) { macro_id_ = id; } + return ret; +} + +int ObStorageObjectHandle::set_macro_block_id(storage_io::BlockOwner &blocks, const MacroBlockId &id) +{ + if (macro_id_.is_valid()) { return OB_ERR_SYS; } + const int ret = retain_block(blocks, id, group_); + if (ret == OB_SUCCESS) { + macro_id_ = id; + blocks_ = &blocks; } return ret; } +ObStorageObjectsHandle::ObStorageObjectsHandle() +{ + macro_id_list_.set_attr(ObMemAttr("MacroIdList")); + holds_.set_attr(ObMemAttr("MacroHolds")); +} + +ObStorageObjectsHandle::~ObStorageObjectsHandle() = default; + +int ObStorageObjectsHandle::add(const ObStorageObjectHandle &handle) +{ + int ret = OB_SUCCESS; + if (!handle.block_hold()) { + ret = OB_INVALID_ARGUMENT; + } else if (OB_FAIL(macro_id_list_.push_back(handle.get_macro_id()))) { + } else if (OB_FAIL(holds_.push_back(handle.block_hold()))) { + macro_id_list_.pop_back(); + } + return ret; +} + +void ObStorageObjectsHandle::reset() +{ + holds_.reset(); + macro_id_list_.reset(); +} + } // namespace blocksstable } // namespace oceanbase diff --git a/src/storage/blocksstable/ob_storage_object_handle.h b/src/storage/blocksstable/ob_storage_object_handle.h index 66ca4e6447..fcbbed9a19 100644 --- a/src/storage/blocksstable/ob_storage_object_handle.h +++ b/src/storage/blocksstable/ob_storage_object_handle.h @@ -17,6 +17,7 @@ #ifndef OCEANBASE_STORAGE_BLOCKSSTABLE_OB_OBJECT_HANDLE_H_ #define OCEANBASE_STORAGE_BLOCKSSTABLE_OB_OBJECT_HANDLE_H_ +#include "lib/container/ob_array.h" #include "share/io_request.h" #include "storage/blocksstable/ob_macro_block_id.h" namespace oceanbase @@ -24,19 +25,49 @@ namespace oceanbase namespace storage { class ObBloomFilterBuildTask; +class ObDDLMacroHandle; } namespace blocksstable { struct ObStorageObjectReadInfo; struct ObStorageObjectWriteInfo; -class ObMacroBlockWriter; +class ObSharedMacroBlockMgr; + +struct ObBadBlockInfo final +{ +public: + ObBadBlockInfo() { reset(); } + ~ObBadBlockInfo() {} + OB_INLINE void reset() { MEMSET(this, 0, sizeof(*this)); } + TO_STRING_KV( + K(disk_id_), + K(macro_block_id_), + K(error_type_), + K(store_file_path_), + K(error_msg_), + K(check_time_)); + +public: + int64_t disk_id_; + MacroBlockId macro_block_id_; + int64_t error_type_; + char store_file_path_[MAX_PATH_SIZE]; + char error_msg_[common::OB_MAX_ERROR_MSG_LEN]; + int64_t check_time_; +}; + +int collect_bad_block_infos(storage_io::BlockOwner &blocks, common::ObIArray &out); +int check_block_space(storage_io::BlockOwner &blocks, int64_t required_size, bool alarm_if_space_full = true); + +using BlockHold = std::shared_ptr>; +int retain_block(storage_io::BlockOwner &blocks, const MacroBlockId &id, BlockHold &hold); class ObStorageObjectHandle final { // for call set_macro_block_id - friend class ObObjectManager; // in ObObjectManager::ss_get_object_id - friend class ObBlockManager; // in ObBlockManager::alloc_object + friend class ObSharedMacroBlockMgr; friend class storage::ObBloomFilterBuildTask; // keeps the macro block alive while the task is queued + friend class storage::ObDDLMacroHandle; public: ObStorageObjectHandle() = default; ~ObStorageObjectHandle(); @@ -44,7 +75,6 @@ class ObStorageObjectHandle final ObStorageObjectHandle &operator=(const ObStorageObjectHandle &other); void reset(); void reuse(); - void reset_macro_id(); bool is_valid() const { return io_handle_.is_valid(); } bool is_empty() const { return io_handle_.is_empty(); } OB_INLINE bool is_finished() const { return io_handle_.is_empty() || io_handle_.is_finished(); } @@ -59,10 +89,14 @@ class ObStorageObjectHandle final const auto *callback = io_handle_.get_callback_output(); return callback != nullptr ? callback->micro_blocks() : nullptr; } + const BlockHold &block_hold() const { return group_; } const MacroBlockId& get_macro_id() const { return macro_id_; } - common::ObIOHandle &get_io_handle() { return io_handle_; } int64_t get_data_size() const { return io_handle_.get_data_size(); } - int async_read(const ObStorageObjectReadInfo &read_info, + int allocate(storage_io::BlockOwner &blocks); + int allocate_and_write(storage_io::BlockOwner &blocks, const ObStorageObjectWriteInfo &write_info); + int async_read(storage_io::BlockOwner &blocks, const ObStorageObjectReadInfo &read_info, + std::unique_ptr callback = nullptr); + int read(storage_io::BlockOwner &blocks, const ObStorageObjectReadInfo &read_info, std::unique_ptr callback = nullptr); int async_write(const ObStorageObjectWriteInfo &write_info); int wait(); @@ -70,16 +104,33 @@ class ObStorageObjectHandle final TO_STRING_KV(K_(macro_id), K_(io_handle)); private: - int set_macro_block_id(const MacroBlockId ¯o_block_id); - int report_bad_block() const; - - int sn_async_read(const ObStorageObjectReadInfo &read_info, - std::unique_ptr callback); - int sn_async_write(const ObStorageObjectWriteInfo &write_info); + int adopt(const MacroBlockId &id, rust::Box group); + int set_macro_block_id(storage_io::BlockOwner &blocks, const MacroBlockId ¯o_block_id); + int submit_write(const ObStorageObjectWriteInfo &write_info); + void report_bad_block(int error_type) const; -private: + BlockHold group_; MacroBlockId macro_id_; common::ObIOHandle io_handle_; + storage_io::BlockOwner *blocks_ = nullptr; +}; + +class ObStorageObjectsHandle final +{ +public: + ObStorageObjectsHandle(); + ~ObStorageObjectsHandle(); + int add(const ObStorageObjectHandle &handle); + int64_t count() const { return macro_id_list_.count(); } + MacroBlockId at(const int64_t i) const { return macro_id_list_.at(i); } + common::ObIArray &get_macro_id_list() { return macro_id_list_; } + void reset(); + TO_STRING_KV(K_(macro_id_list)); + +private: + common::ObArray macro_id_list_; + common::ObArray holds_; + DISALLOW_COPY_AND_ASSIGN(ObStorageObjectsHandle); }; } // namespace blocksstable diff --git a/src/storage/blocksstable/ob_storage_object_rw_info.h b/src/storage/blocksstable/ob_storage_object_rw_info.h index d869c51b28..063e5efa33 100644 --- a/src/storage/blocksstable/ob_storage_object_rw_info.h +++ b/src/storage/blocksstable/ob_storage_object_rw_info.h @@ -49,14 +49,6 @@ struct ObStorageObjectWriteInfo final common::ObIOFlag io_desc_; }; -using ObMacroBlockWriteInfo = ObStorageObjectWriteInfo; - -inline bool is_valid_storage_read(const MacroBlockId &id, const int64_t offset, - const int64_t size, const common::ObIOFlag &io_desc) -{ - return id.is_valid() && offset >= 0 && size > 0 && io_desc.is_valid(); -} - struct ObStorageObjectReadInfo final { public: @@ -67,7 +59,7 @@ struct ObStorageObjectReadInfo final ~ObStorageObjectReadInfo() = default; OB_INLINE bool is_valid() const { - return is_valid_storage_read(macro_block_id_, offset_, size_, io_desc_); + return macro_block_id_.is_valid() && offset_ >= 0 && size_ > 0 && io_desc_.is_valid(); } TO_STRING_KV(K_(macro_block_id), K_(offset), K_(size), K_(io_timeout_ms), K_(io_desc)); public: diff --git a/src/storage/blockstore/ob_linked_macro_block_reader.cpp b/src/storage/blockstore/ob_linked_macro_block_reader.cpp index b5387808fe..c6769f4b21 100644 --- a/src/storage/blockstore/ob_linked_macro_block_reader.cpp +++ b/src/storage/blockstore/ob_linked_macro_block_reader.cpp @@ -16,6 +16,7 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "storage/blockstore/ob_linked_macro_block_reader.h" @@ -35,11 +36,12 @@ ObLinkedMacroBlockReader::ObLinkedMacroBlockReader() handles_[1].reset(); } -int ObLinkedMacroBlockReader::init(const MacroBlockId &entry_block) +int ObLinkedMacroBlockReader::init(storage_io::BlockOwner &blocks, const MacroBlockId &entry_block) { int ret = OB_SUCCESS; if (OB_UNLIKELY(is_inited_)) { ret = OB_INIT_TWICE; + } else if (FALSE_IT(blocks_ = &blocks)) { } else if (OB_FAIL(get_meta_blocks(entry_block))) { } else if (OB_FAIL(prefetch_block())) { } else { @@ -65,11 +67,11 @@ int ObLinkedMacroBlockReader::get_meta_blocks(const MacroBlockId &entry_block) int64_t handle_pos = 0; MacroBlockId previous_block_id; handles_[handle_pos].reset(); - if (OB_FAIL(ObObjectManager::async_read_object(read_info, handles_[handle_pos]))) { + if (OB_FAIL(handles_[handle_pos].async_read(*blocks_, read_info))) { } else { while (OB_SUCC(ret)) { if (OB_FAIL(handles_[handle_pos].wait())) { - } else if (OB_FAIL(macros_handle_.add(read_info.macro_block_id_))) { + } else if (OB_FAIL(macros_handle_.add(handles_[handle_pos]))) { } else if (OB_FAIL(get_previous_block_id(handles_[handle_pos].get_buffer(), handles_[handle_pos].get_data_size(), previous_block_id))) { } else { @@ -77,7 +79,7 @@ int ObLinkedMacroBlockReader::get_meta_blocks(const MacroBlockId &entry_block) handle_pos = 1 - handle_pos; read_info.macro_block_id_ = previous_block_id; handles_[handle_pos].reset(); - if (OB_FAIL(ObObjectManager::async_read_object(read_info, handles_[handle_pos]))) { + if (OB_FAIL(handles_[handle_pos].async_read(*blocks_, read_info))) { } } else { break; @@ -102,14 +104,14 @@ int ObLinkedMacroBlockReader::prefetch_block() } else { ObStorageObjectReadInfo read_info; read_info.offset_ = 0; - read_info.size_ = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + read_info.size_ = OB_DEFAULT_MACRO_BLOCK_SIZE; read_info.io_desc_.set_mode(ObIOMode::READ); read_info.io_desc_.set_sys_module_id(ObIOModule::LINKED_MACRO_BLOCK_IO); read_info.macro_block_id_ = macros_handle_.at(prefetch_macro_block_idx_); read_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000L; handles_[handle_pos_].reset(); - if (OB_FAIL(ObObjectManager::async_read_object(read_info, handles_[handle_pos_]))) { + if (OB_FAIL(handles_[handle_pos_].async_read(*blocks_, read_info))) { } else { handle_pos_ = 1 - handle_pos_; --prefetch_macro_block_idx_; @@ -138,7 +140,7 @@ int ObLinkedMacroBlockReader::iter_read_block(char *&buf, int64_t &buf_len, Macr return ret; } -int ObLinkedMacroBlockReader::pread_block(const ObMetaDiskAddr &addr, ObStorageObjectHandle &handler) +int ObLinkedMacroBlockReader::pread_block(storage_io::BlockOwner &blocks, const ObMetaDiskAddr &addr, ObStorageObjectHandle &handler) { int ret = OB_SUCCESS; ObStorageObjectReadInfo read_info; @@ -148,27 +150,28 @@ int ObLinkedMacroBlockReader::pread_block(const ObMetaDiskAddr &addr, ObStorageO read_info.io_desc_.set_sys_module_id(ObIOModule::LINKED_MACRO_BLOCK_IO); if (OB_FAIL(addr.get_block_addr(read_info.macro_block_id_, read_info.offset_, read_info.size_))) { - } else if (OB_FAIL(ObObjectManager::async_read_object(read_info, handler))) { + } else if (OB_FAIL(handler.async_read(blocks, read_info))) { } else if (OB_FAIL(handler.wait())) { } return ret; } int ObLinkedMacroBlockReader::read_block_by_id( + storage_io::BlockOwner &blocks, const MacroBlockId &block_id, ObStorageObjectHandle &handler) { int ret = OB_SUCCESS; ObStorageObjectReadInfo read_info; read_info.offset_ = 0; - read_info.size_ = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + read_info.size_ = OB_DEFAULT_MACRO_BLOCK_SIZE; read_info.io_desc_.set_mode(ObIOMode::READ); read_info.io_desc_.set_sys_module_id(ObIOModule::LINKED_MACRO_BLOCK_IO); read_info.macro_block_id_ = block_id; read_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000L; handler.reset(); - if (OB_FAIL(ObObjectManager::async_read_object(read_info, handler))) { + if (OB_FAIL(handler.async_read(blocks, read_info))) { } else if (OB_FAIL(handler.wait())) { } else if (OB_FAIL(check_data_checksum(handler.get_buffer(), handler.get_data_size()))) { } @@ -202,6 +205,7 @@ ObIArray &ObLinkedMacroBlockReader::get_meta_block_list() void ObLinkedMacroBlockReader::reset() { + blocks_ = nullptr; is_inited_ = false; handles_[0].reset(); handles_[1].reset(); @@ -238,14 +242,14 @@ ObLinkedMacroBlockItemReader::ObLinkedMacroBlockItemReader() { } -int ObLinkedMacroBlockItemReader::init(const MacroBlockId &entry_block, const ObMemAttr &mem_attr) +int ObLinkedMacroBlockItemReader::init(storage_io::BlockOwner &blocks, const MacroBlockId &entry_block, const ObMemAttr &mem_attr) { int ret = OB_SUCCESS; if (OB_UNLIKELY(is_inited_)) { ret = OB_INIT_TWICE; } else if (OB_UNLIKELY(!entry_block.is_valid())) { ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(block_reader_.init(entry_block))) { + } else if (OB_FAIL(block_reader_.init(blocks, entry_block))) { } else { allocator_.set_attr(mem_attr); is_inited_ = true; @@ -394,7 +398,7 @@ int ObLinkedMacroBlockItemReader::check_item_crc( return ret; } -int ObLinkedMacroBlockItemReader::read_item(const ObIArray &block_list, +int ObLinkedMacroBlockItemReader::read_item(storage_io::BlockOwner &blocks, const ObIArray &block_list, const ObMetaDiskAddr &addr, char *item_buf, int64_t &item_buf_len) { int ret = OB_SUCCESS; @@ -404,9 +408,9 @@ int ObLinkedMacroBlockItemReader::read_item(const ObIArray &block_ LOG_WARN("disk addr is invalid", K(ret), K(addr)); } else { // item not cross the boundary of macro block - if (OB_LIKELY(addr.offset() + addr.size() <=OB_STORAGE_OBJECT_MGR.get_macro_block_size())) { + if (OB_LIKELY(addr.offset() + addr.size() <=OB_DEFAULT_MACRO_BLOCK_SIZE)) { blocksstable::ObStorageObjectHandle handler; - if (OB_FAIL(ObLinkedMacroBlockReader::pread_block(addr, handler))) { + if (OB_FAIL(ObLinkedMacroBlockReader::pread_block(blocks, addr, handler))) { } else { const char *item_buf_with_head = handler.get_buffer(); const ObLinkedMacroBlockItemHeader *item_header = @@ -422,7 +426,7 @@ int ObLinkedMacroBlockItemReader::read_item(const ObIArray &block_ memmove(item_buf, item_buf_with_head + sizeof(ObLinkedMacroBlockItemHeader), item_buf_len); } } - } else if (OB_FAIL(read_large_item(block_list, addr, item_buf, item_buf_len))) { + } else if (OB_FAIL(read_large_item(blocks, block_list, addr, item_buf, item_buf_len))) { } } @@ -456,7 +460,7 @@ int ObLinkedMacroBlockItemReader::get_next_block_id(const ObIArray return ret; } -int ObLinkedMacroBlockItemReader::read_large_item(const ObIArray &block_list, +int ObLinkedMacroBlockItemReader::read_large_item(storage_io::BlockOwner &blocks, const ObIArray &block_list, const ObMetaDiskAddr &addr, char *item_buf, int64_t &item_buf_len) { LOG_INFO("reading item cross the block boundary is inefficient", K(addr)); @@ -466,10 +470,10 @@ int ObLinkedMacroBlockItemReader::read_large_item(const ObIArray & MacroBlockId block_id; int64_t offset = 0; int64_t size = 0; - const int64_t buf_len = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + const int64_t buf_len = OB_DEFAULT_MACRO_BLOCK_SIZE; int64_t pos = 0; if (OB_FAIL(addr.get_block_addr(block_id, offset, size))) { - } else if (OB_FAIL(ObLinkedMacroBlockReader::read_block_by_id(block_id, handler))) { + } else if (OB_FAIL(ObLinkedMacroBlockReader::read_block_by_id(blocks, block_id, handler))) { } else { // item_buf not include the item header item_buf_len = size - sizeof(ObLinkedMacroBlockItemHeader); @@ -504,7 +508,7 @@ int ObLinkedMacroBlockItemReader::read_large_item(const ObIArray & MacroBlockId next_block_id; while (OB_SUCC(ret) && 0 == item_count) { if (OB_FAIL(get_next_block_id(block_list, block_id, next_block_id))) { - } else if (OB_FAIL(ObLinkedMacroBlockReader::read_block_by_id(next_block_id, + } else if (OB_FAIL(ObLinkedMacroBlockReader::read_block_by_id(blocks, next_block_id, handler))) { } else { pos = 0; diff --git a/src/storage/blockstore/ob_linked_macro_block_reader.h b/src/storage/blockstore/ob_linked_macro_block_reader.h index b0070ab2e1..9126dbbe93 100644 --- a/src/storage/blockstore/ob_linked_macro_block_reader.h +++ b/src/storage/blockstore/ob_linked_macro_block_reader.h @@ -17,7 +17,7 @@ #pragma once #include "storage/blocksstable/ob_block_sstable_struct.h" -#include "storage/blocksstable/ob_macro_block_handle.h" +#include "storage/blocksstable/ob_storage_object_handle.h" #include "storage/blockstore/ob_linked_macro_block_struct.h" #include "storage/meta_mem/ob_meta_obj_struct.h" @@ -40,14 +40,14 @@ class ObLinkedMacroBlockReader final ObLinkedMacroBlockReader(const ObLinkedMacroBlockReader &) = delete; ObLinkedMacroBlockReader &operator=(const ObLinkedMacroBlockReader &) = delete; - int init(const blocksstable::MacroBlockId &entry_block); + int init(storage_io::BlockOwner &blocks, const blocksstable::MacroBlockId &entry_block); int iter_read_block(char *&buf, int64_t &buf_len, blocksstable::MacroBlockId &block_id); void reset(); ObIArray &get_meta_block_list(); - static int pread_block(const ObMetaDiskAddr &addr, + static int pread_block(storage_io::BlockOwner &blocks, const ObMetaDiskAddr &addr, blocksstable::ObStorageObjectHandle &handler); - static int read_block_by_id(const blocksstable::MacroBlockId &block_id, + static int read_block_by_id(storage_io::BlockOwner &blocks, const blocksstable::MacroBlockId &block_id, blocksstable::ObStorageObjectHandle &handler); private: @@ -59,6 +59,7 @@ class ObLinkedMacroBlockReader final static int check_data_checksum(const char *buf, const int64_t buf_len); private: + storage_io::BlockOwner *blocks_ = nullptr; bool is_inited_; blocksstable::ObStorageObjectHandle handles_[2]; int64_t handle_pos_; @@ -75,14 +76,14 @@ class ObLinkedMacroBlockItemReader final ObLinkedMacroBlockItemReader(const ObLinkedMacroBlockItemReader &) = delete; ObLinkedMacroBlockItemReader &operator=(const ObLinkedMacroBlockItemReader &) = delete; - int init(const blocksstable::MacroBlockId &entry_block, const ObMemAttr &mem_attr); + int init(storage_io::BlockOwner &blocks, const blocksstable::MacroBlockId &entry_block, const ObMemAttr &mem_attr); int get_next_item(char *&item_buf, int64_t &item_buf_len, ObMetaDiskAddr &addr); void reset(); common::ObIArray &get_meta_block_list(); static int get_next_block_id(const common::ObIArray &block_list, const blocksstable::MacroBlockId &block_id, blocksstable::MacroBlockId &next_block_id); - static int read_item(const common::ObIArray &block_list, + static int read_item(storage_io::BlockOwner &blocks, const common::ObIArray &block_list, const ObMetaDiskAddr &addr, char *item_buf, int64_t &item_buf_len); private: @@ -90,7 +91,7 @@ class ObLinkedMacroBlockItemReader final int parse_item(char *&item_buf, int64_t &item_buf_len, ObMetaDiskAddr &addr); static int check_item_crc(const int32_t crc, const char *item_buf, const int64_t item_buf_len); - static int read_large_item(const common::ObIArray &block_list, + static int read_large_item(storage_io::BlockOwner &blocks, const common::ObIArray &block_list, const ObMetaDiskAddr &addr, char *item_buf, int64_t &item_buf_len); private: diff --git a/src/storage/blockstore/ob_linked_macro_block_struct.h b/src/storage/blockstore/ob_linked_macro_block_struct.h index 19c89cdd4c..c7ffa873e8 100644 --- a/src/storage/blockstore/ob_linked_macro_block_struct.h +++ b/src/storage/blockstore/ob_linked_macro_block_struct.h @@ -18,7 +18,6 @@ #include "lib/utility/ob_print_utils.h" #include "storage/blocksstable/ob_macro_block_id.h" -#include "storage/blocksstable/ob_macro_block_handle.h" namespace oceanbase { diff --git a/src/storage/blockstore/ob_linked_macro_block_writer.cpp b/src/storage/blockstore/ob_linked_macro_block_writer.cpp index 66f5d31dbf..d4506a5dd0 100644 --- a/src/storage/blockstore/ob_linked_macro_block_writer.cpp +++ b/src/storage/blockstore/ob_linked_macro_block_writer.cpp @@ -16,6 +16,7 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "share/ob_server_struct.h" @@ -34,12 +35,13 @@ ObLinkedMacroBlockWriter::ObLinkedMacroBlockWriter() { } -int ObLinkedMacroBlockWriter::init() +int ObLinkedMacroBlockWriter::init(storage_io::BlockOwner &blocks) { int ret = OB_SUCCESS; if (OB_UNLIKELY(is_inited_)) { ret = OB_INIT_TWICE; } else { + blocks_ = &blocks; is_inited_ = true; } return ret; @@ -56,8 +58,6 @@ int ObLinkedMacroBlockWriter::write_block( } else if (OB_UNLIKELY(nullptr == buf || buf_len < 0)) { ret = OB_INVALID_ARGUMENT; } else { - ObStorageObjectOpt opt; - opt.set_meta_macro_object_opt(); ObStorageObjectWriteInfo write_info; write_info.size_ = buf_len; write_info.buffer_ = buf; @@ -92,8 +92,8 @@ int ObLinkedMacroBlockWriter::write_block( } if (OB_SUCC(ret)) { handle_.reset(); - if (OB_FAIL(ObObjectManager::async_write_object(opt, write_info, handle_))) { - } else if (OB_FAIL(write_ctx_.add_macro_block_id(handle_.get_macro_id()))) { + if (OB_FAIL(handle_.allocate_and_write(*blocks_, write_info))) { + } else if (OB_FAIL(write_ctx_.add_macro_block(handle_))) { } } } @@ -129,6 +129,7 @@ ObIArray &ObLinkedMacroBlockWriter::get_meta_block_list() void ObLinkedMacroBlockWriter::reset() { + blocks_ = nullptr; is_inited_ = false; write_ctx_.reset(); handle_.reset(); @@ -137,6 +138,7 @@ void ObLinkedMacroBlockWriter::reset() void ObLinkedMacroBlockWriter::reuse_for_next_round() { + blocks_ = nullptr; is_inited_ = false; handle_.reset(); entry_block_id_.reset(); @@ -153,14 +155,14 @@ ObLinkedMacroBlockItemWriter::ObLinkedMacroBlockItemWriter() { } -int ObLinkedMacroBlockItemWriter::init(const bool need_disk_addr, const ObMemAttr &mem_attr) +int ObLinkedMacroBlockItemWriter::init(storage_io::BlockOwner &blocks, const bool need_disk_addr, const ObMemAttr &mem_attr) { int ret = OB_SUCCESS; - const int64_t macro_block_size = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + const int64_t macro_block_size = OB_DEFAULT_MACRO_BLOCK_SIZE; if (OB_UNLIKELY(is_inited_)) { ret = OB_INIT_TWICE; } else if (FALSE_IT(allocator_.set_attr(mem_attr))) { - } else if (OB_FAIL(block_writer_.init())) { + } else if (OB_FAIL(block_writer_.init(blocks))) { } else if (OB_ISNULL(io_buf_ = static_cast(allocator_.alloc(macro_block_size)))) { ret = OB_ALLOCATE_MEMORY_FAILED; } else if (FALSE_IT(MEMSET(io_buf_, 0, macro_block_size))) { diff --git a/src/storage/blockstore/ob_linked_macro_block_writer.h b/src/storage/blockstore/ob_linked_macro_block_writer.h index 464dfaeb7b..c0fe28431d 100644 --- a/src/storage/blockstore/ob_linked_macro_block_writer.h +++ b/src/storage/blockstore/ob_linked_macro_block_writer.h @@ -37,7 +37,7 @@ class ObLinkedMacroBlockWriter final ObLinkedMacroBlockWriter(const ObLinkedMacroBlockWriter &) = delete; ObLinkedMacroBlockWriter &operator=(const ObLinkedMacroBlockWriter &) = delete; - int init(); + int init(storage_io::BlockOwner &blocks); int write_block( char *buf, const int64_t buf_len, blocksstable::ObMacroBlockCommonHeader &common_header, @@ -51,6 +51,7 @@ class ObLinkedMacroBlockWriter final void reuse_for_next_round(); private: + storage_io::BlockOwner *blocks_ = nullptr; bool is_inited_; blocksstable::ObMacroBlocksWriteCtx write_ctx_; blocksstable::ObStorageObjectHandle handle_; @@ -64,7 +65,7 @@ class ObLinkedMacroBlockItemWriter final ~ObLinkedMacroBlockItemWriter() = default; ObLinkedMacroBlockItemWriter(const ObLinkedMacroBlockItemWriter &) = delete; ObLinkedMacroBlockItemWriter &operator=(const ObLinkedMacroBlockItemWriter &) = delete; - int init(const bool need_disk_addr, const ObMemAttr &mem_attr); + int init(storage_io::BlockOwner &blocks, const bool need_disk_addr, const ObMemAttr &mem_attr); int write_item(const char *item_buf, const int64_t item_buf_len, int64_t *item_idx = nullptr); int close(); inline bool is_closed() const { return is_closed_; }; diff --git a/src/storage/blockstore/ob_object_reader_writer.cpp b/src/storage/blockstore/ob_object_reader_writer.cpp index d71c2169b2..3baf6186b5 100644 --- a/src/storage/blockstore/ob_object_reader_writer.cpp +++ b/src/storage/blockstore/ob_object_reader_writer.cpp @@ -15,6 +15,7 @@ */ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "ob_object_reader_writer.h" #include "src/storage/ob_storage_struct.h" @@ -77,17 +78,9 @@ ObObjectsWriteCtx::~ObObjectsWriteCtx() void ObObjectsWriteCtx::clear() { - int ret = OB_SUCCESS; - if (OB_SUCC(ret)) { - for (int64_t i = 0; i < block_ids_.count(); ++i) { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(block_ids_.at(i)))) { - } - abort_unless(OB_SUCCESS == ret); - } - } + holds_.reset(); block_ids_.reset(); addr_.reset(); - next_opt_.set_data_macro_object_opt(); } int ObObjectsWriteCtx::set_addr(const ObMetaDiskAddr &addr) { @@ -100,18 +93,26 @@ int ObObjectsWriteCtx::set_addr(const ObMetaDiskAddr &addr) return ret; } -int ObObjectsWriteCtx::add_object_id(const blocksstable::MacroBlockId &object_id) +int ObObjectsWriteCtx::add_object_id(storage_io::BlockOwner &blocks, const MacroBlockId &id) +{ + if (!block_ids_.empty() && id == block_ids_.at(block_ids_.count() - 1)) { + return OB_SUCCESS; + } + BlockHold hold; + const int ret = retain_block(blocks, id, hold); + return ret == OB_SUCCESS ? add_object_id(id, hold) : ret; +} + +int ObObjectsWriteCtx::add_object_id(const MacroBlockId &id, const BlockHold &hold) { int ret = OB_SUCCESS; - const int64_t cnt = block_ids_.count(); - if (OB_UNLIKELY(!object_id.is_valid())) { + const int64_t count = block_ids_.count(); + if (!id.is_valid() || !hold) { ret = OB_INVALID_ARGUMENT; - } else if (cnt > 0 && object_id == block_ids_.at(cnt - 1)) { - // skip, link handle uses one write_ctx to record all blocks' id sequentially - } else if (OB_FAIL(block_ids_.push_back(object_id))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(object_id))) { + } else if (count > 0 && id == block_ids_.at(count - 1)) { + } else if (OB_FAIL(block_ids_.push_back(id))) { + } else if (OB_FAIL(holds_.push_back(hold))) { block_ids_.pop_back(); - LOG_ERROR("Fail to inc macro block ref cnt", K(ret)); } return ret; } @@ -122,13 +123,10 @@ int ObObjectsWriteCtx::assign(const ObObjectsWriteCtx &other) if (this != &other) { clear(); if (OB_FAIL(set_addr(other.addr_))) { - } else { - next_opt_ = other.next_opt_; - for (int64_t i = 0; OB_SUCC(ret) && i < other.block_ids_.count(); ++i) { - if (OB_FAIL(add_object_id(other.block_ids_.at(i)))) { - } - } + } else if (OB_FAIL(block_ids_.assign(other.block_ids_))) { + } else if (OB_FAIL(holds_.assign(other.holds_))) { } + if (OB_FAIL(ret)) { clear(); } } return ret; } @@ -396,7 +394,8 @@ int ObObjectWriteHandle::get_write_ctx(ObObjectsWriteCtx &write_ctx) } else if (OB_FAIL(write_ctx.set_addr(addrs_.at(0)))) { } else { for (int64_t i = 0; OB_SUCC(ret) && i < object_handles_.count(); ++i) { - if (OB_FAIL(write_ctx.add_object_id(object_handles_.at(i).get_macro_id()))) { + const auto &handle = object_handles_.at(i); + if (OB_FAIL(write_ctx.add_object_id(handle.get_macro_id(), handle.block_hold()))) { } } } @@ -427,23 +426,8 @@ int ObObjectBatchHandle::batch_get_write_ctx(ObIArray &write_ } -bool ObObjectLinkHandle::is_valid() const -{ - return object_handles_.count() > 0 && addrs_.count() == 1; // only record last addr -} -int ObObjectLinkHandle::get_write_ctx(ObObjectsWriteCtx &write_ctx) -{ - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!is_valid())) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(wait())) { - } else if (OB_FAIL(write_ctx.assign(write_ctx_))) { - } - return ret; -} - -int ObObjectLinkIter::init(const ObMetaDiskAddr &head) +int ObObjectLinkIter::init(storage_io::BlockOwner &blocks, const ObMetaDiskAddr &head) { int ret = OB_SUCCESS; if (IS_INIT) { @@ -452,6 +436,7 @@ int ObObjectLinkIter::init(const ObMetaDiskAddr &head) ret = OB_INVALID_ARGUMENT; LOG_WARN("Invalid meta disk addr", K(ret), K(head)); } else { + blocks_ = &blocks; head_ = head; cur_ = head; is_inited_ = true; @@ -509,7 +494,7 @@ int ObObjectLinkIter::read_next_block(ObObjectReadHandle &object_io_handle) ObObjectReadInfo read_info; ObObjectHeader header; read_info.addr_ = cur_; - if (OB_FAIL(ObObjectReaderWriter::async_read(read_info, object_io_handle))) { + if (OB_FAIL(ObObjectReaderWriter::async_read(*blocks_, read_info, object_io_handle))) { } else if (OB_FAIL(object_io_handle.wait())) { } else { int64_t pos = 0; @@ -628,7 +613,7 @@ ObObjectReaderWriter::~ObObjectReaderWriter() reset(); } -int ObObjectReaderWriter::init() +int ObObjectReaderWriter::init(storage_io::BlockOwner &blocks) { int ret = OB_SUCCESS; if (IS_INIT) { @@ -636,6 +621,7 @@ int ObObjectReaderWriter::init() } else { offset_ = 0; align_offset_ = 0; + blocks_ = &blocks; write_align_size_ = DIO_READ_ALIGN_SIZE; // 4K hanging_ = false; is_inited_ = true; @@ -645,6 +631,7 @@ int ObObjectReaderWriter::init() void ObObjectReaderWriter::reset() { object_handle_.reset(); + blocks_ = nullptr; offset_ = 0; align_offset_ = 0; write_align_size_ = 0; @@ -691,15 +678,11 @@ int callback_do_write_io(const ObIArray &write_infos) int ObObjectReaderWriter::async_write( const ObObjectWriteInfo &write_info, - const blocksstable::ObStorageObjectOpt &curr_opt, ObObjectWriteHandle &object_io_handle) { int ret = OB_SUCCESS; ObObjectWriteArgs write_args; - ObMetaDiskAddr prev_addr; - prev_addr.set_none_addr(); write_args.with_header_ = false; - write_args.object_opt_ = curr_opt; ObObjectHeader header; ObObjectsWriteCtx tmp_write_ctx; ObObjectWriteSession write_session; @@ -737,8 +720,7 @@ int ObObjectReaderWriter::async_write( int ObObjectReaderWriter::async_batch_write( const ObIArray &write_infos, - ObObjectBatchHandle &object_io_handle, - blocksstable::ObStorageObjectOpt &curr_opt) + ObObjectBatchHandle &object_io_handle) { int ret = OB_SUCCESS; ObObjectWriteSession write_session; @@ -757,12 +739,9 @@ int ObObjectReaderWriter::async_batch_write( // only the last need flush and align write_args.need_flush_ = (i == write_infos.count() - 1); write_args.need_align_ = (i == write_infos.count() - 1); - write_args.object_opt_ = curr_opt; write_ctx.clear(); if (OB_FAIL(inner_async_write(write_session, write_infos.at(i), write_args, object_io_handle, write_ctx))) { } else if (OB_FAIL(object_io_handle.write_ctxs_.push_back(write_ctx))) { - } else { - curr_opt = write_ctx.next_opt_; } } if (OB_FAIL(ret)) { @@ -776,48 +755,6 @@ int ObObjectReaderWriter::async_batch_write( return ret; } -int ObObjectReaderWriter::async_link_write( - const ObObjectWriteInfo &write_info, - const blocksstable::ObStorageObjectOpt &curr_opt, - ObObjectLinkHandle &object_io_handle) -{ - int ret = OB_SUCCESS; - ObObjectWriteSession write_session; - { - lib::ObMutexGuard guard(mutex_); - ObObjectWriteArgs write_args; - ObObjectsWriteCtx write_ctx; - write_args.object_opt_ = curr_opt; - write_args.need_flush_ = true; - write_args.need_align_ = true; - write_args.is_linked_ = true; - if (IS_NOT_INIT) { - ret = OB_NOT_INIT; - } else if (OB_UNLIKELY(hanging_)) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(object_io_handle.wait())) { - } else { - write_session.set_clean_state(*this); - } - - if (FAILEDx(inner_async_write(write_session, write_info, write_args, object_io_handle, write_ctx))) { - } else if (OB_FAIL(object_io_handle.write_ctx_.set_addr(write_ctx.addr_))) { - } else { - for (int64_t i = 0; OB_SUCC(ret) && i < write_ctx.block_ids_.count(); ++i) { - if (OB_FAIL(object_io_handle.write_ctx_.add_object_id(write_ctx.block_ids_.at(i)))) { - } - } - } - if (OB_FAIL(ret)) { - write_session.rollback(*this); - } - } - if (OB_FAIL(ret)) { - } else if (OB_FAIL(callback_do_write_io(write_info))) { - } - return ret; -} - int ObObjectReaderWriter::inner_async_write( ObObjectWriteSession &write_session, const ObObjectWriteInfo &write_info, @@ -856,9 +793,8 @@ int ObObjectReaderWriter::reserve_header(ObObjectWriteSession &write_session) return ret; } -int ObObjectReaderWriter::switch_object(ObObjectWriteSession &write_session, - ObStorageObjectHandle &object_handle, - const blocksstable::ObStorageObjectOpt &next_opt) +int ObObjectReaderWriter::switch_object( + ObObjectWriteSession &write_session, ObStorageObjectHandle &object_handle) { int ret = OB_SUCCESS; object_handle.reset(); @@ -875,14 +811,13 @@ int ObObjectReaderWriter::switch_object(ObObjectWriteSession &write_session, } } if (OB_SUCC(ret)) { - if (OB_FAIL(do_switch(write_session, next_opt))) { + if (OB_FAIL(do_switch(write_session))) { } } return ret; } -int ObObjectReaderWriter::do_switch(ObObjectWriteSession &write_session, - const ObStorageObjectOpt &opt) +int ObObjectReaderWriter::do_switch(ObObjectWriteSession &write_session) { int ret = OB_SUCCESS; hanging_ = false; @@ -890,7 +825,7 @@ int ObObjectReaderWriter::do_switch(ObObjectWriteSession &write_session, object_handle_.reset(); offset_ = 0; align_offset_ = 0; - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.alloc_object(opt, object_handle_))) { + if (OB_FAIL(object_handle_.allocate(*blocks_))) { } else if (OB_FAIL(write_session.data_.clean())) { } return ret; @@ -947,14 +882,13 @@ int ObObjectReaderWriter::inner_write_block( int64_t store_size = 0, align_store_size = 0; bool need_align = write_args.need_align_; bool need_flush = write_args.need_flush_; - write_ctx.next_opt_ = write_args.object_opt_; if (OB_FAIL(check_object_size_(blk_size, need_align))) { } else if (OB_FAIL(ensure_data_buffer_for_write_(write_session))) { } else if (OB_FAIL(calc_store_size(blk_size, need_align, store_size, align_store_size))) { } else if (!object_handle_.get_macro_id().is_valid() - && OB_FAIL(OB_STORAGE_OBJECT_MGR.alloc_object(write_args.object_opt_, object_handle_))) { + && OB_FAIL(object_handle_.allocate(*blocks_))) { } else if (store_size + offset_ > OB_DEFAULT_MACRO_BLOCK_SIZE) { - if (OB_FAIL(switch_object(write_session, object_handle, write_ctx.next_opt_))) { + if (OB_FAIL(switch_object(write_session, object_handle))) { } else { write_session.set_clean_state(*this); if (object_handle.is_valid() && OB_FAIL(object_io_handle.add_object_handle(object_handle))) { @@ -1001,7 +935,7 @@ int ObObjectReaderWriter::inner_write_block( } else if (OB_FAIL(object_io_handle.add_meta_addr(addr))) { } else if (OB_FAIL(write_session.data_.advance(store_size))) { } else if (OB_FAIL(write_ctx.set_addr(addr))) { - } else if (OB_FAIL(write_ctx.add_object_id(addr.block_id()))) { + } else if (OB_FAIL(write_ctx.add_object_id(addr.block_id(), object_handle_.block_hold()))) { } else { offset_ += store_size; } @@ -1036,11 +970,6 @@ int ObObjectReaderWriter::inner_write_block( return ret; } -void ObObjectReaderWriter::get_cur_block(blocksstable::MacroBlockId ¯o_id) -{ - lib::ObMutexGuard guard(mutex_); - macro_id = object_handle_.get_macro_id(); -} int ObObjectReaderWriter::write_block( ObObjectWriteSession &write_session, @@ -1050,13 +979,8 @@ int ObObjectReaderWriter::write_block( ObObjectsWriteCtx &write_ctx) { int ret = OB_SUCCESS; - ObMetaDiskAddr prev_addr; - prev_addr.set_none_addr(); if (OB_UNLIKELY(!write_info.is_valid())) { ret = OB_INVALID_ARGUMENT; - } else if (write_args.is_linked_ && object_io_handle.addrs_.count() > 0) { - prev_addr = object_io_handle.addrs_.at(0); - object_io_handle.reset(); // clear prev blocks info } if (OB_SUCC(ret)) { ObObjectHeader header; @@ -1065,7 +989,6 @@ int ObObjectReaderWriter::write_block( header.data_size_ = write_info.size_; header.checksum_ = ob_crc64_sse42(write_info.buffer_, write_info.size_); header.next_macro_id_ = ObObjectHeader::DEFAULT_MACRO_ID; - header.prev_addr_ = prev_addr; header.header_size_ = header.get_serialize_size(); if (OB_FAIL(inner_write_block(write_session, header, write_info, write_args, object_io_handle, write_ctx))) { } @@ -1074,6 +997,7 @@ int ObObjectReaderWriter::write_block( } int ObObjectReaderWriter::async_read( + storage_io::BlockOwner &blocks, const ObObjectReadInfo &read_info, ObObjectReadHandle &object_io_handle, std::unique_ptr callback) @@ -1090,7 +1014,7 @@ int ObObjectReaderWriter::async_read( object_read_info.macro_block_id_, object_read_info.offset_, object_read_info.size_))) { - } else if (OB_FAIL(object_handle.async_read(object_read_info, std::move(callback)))) { + } else if (OB_FAIL(object_handle.async_read(blocks, object_read_info, std::move(callback)))) { } else if (OB_FAIL(object_io_handle.set_addr_and_object_handle(read_info.addr_, object_handle))) { } return ret; diff --git a/src/storage/blockstore/ob_object_reader_writer.h b/src/storage/blockstore/ob_object_reader_writer.h index b4e7cd1c87..9c2d78714c 100644 --- a/src/storage/blockstore/ob_object_reader_writer.h +++ b/src/storage/blockstore/ob_object_reader_writer.h @@ -18,11 +18,10 @@ #define OCEANBASE_STORAGE_BLOCKSTORE_OB_OBJECT_READER_WRITER_H_ #include "storage/meta_mem/ob_meta_obj_struct.h" -#include "storage/blocksstable/ob_macro_block_handle.h" #include "storage/blocksstable/ob_macro_block_id.h" #include "storage/blocksstable/ob_data_buffer.h" #include "storage/blocksstable/ob_storage_object_handle.h" -#include "storage/blocksstable/ob_object_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" #include "storage/blocksstable/ob_imacro_block_flush_callback.h" namespace oceanbase @@ -67,21 +66,24 @@ struct ObObjectsWriteCtx final { public: ObObjectsWriteCtx() - : addr_(), block_ids_(), next_opt_() + : addr_(), block_ids_() { block_ids_.set_attr(ObMemAttr("ObjectWCtx")); + holds_.set_attr(ObMemAttr("ObjectHolds")); } ~ObObjectsWriteCtx(); bool is_valid() const; int set_addr(const ObMetaDiskAddr &addr); // overwrite - int add_object_id(const blocksstable::MacroBlockId &object_id); // distinct + int add_object_id(const blocksstable::MacroBlockId &id, const blocksstable::BlockHold &hold); + int add_object_id(storage_io::BlockOwner &blocks, const blocksstable::MacroBlockId &id); void clear(); int assign(const ObObjectsWriteCtx &other); - TO_STRING_KV(K_(addr), K_(block_ids), K_(next_opt)); + TO_STRING_KV(K_(addr), K_(block_ids)); public: ObMetaDiskAddr addr_; ObArray block_ids_; - blocksstable::ObStorageObjectOpt next_opt_; +private: + ObArray holds_; DISALLOW_COPY_AND_ASSIGN(ObObjectsWriteCtx); }; @@ -221,20 +223,6 @@ class ObObjectBatchHandle final : public ObObjectBaseHandle private: DISALLOW_COPY_AND_ASSIGN(ObObjectBatchHandle); }; -class ObObjectLinkHandle final : public ObObjectBaseHandle -{ - friend class ObObjectReaderWriter; -public: - ObObjectLinkHandle() = default; - ~ObObjectLinkHandle() = default; - bool is_valid() const; - int get_write_ctx(ObObjectsWriteCtx &write_ctx); // always get prev block - INHERIT_TO_STRING_KV("ObObjectBaseHandle", ObObjectBaseHandle, K_(write_ctx)); -protected: - ObObjectsWriteCtx write_ctx_; -private: - DISALLOW_COPY_AND_ASSIGN(ObObjectLinkHandle); -}; class ObObjectLinkIter final { @@ -243,7 +231,7 @@ class ObObjectLinkIter final : head_(), cur_(), is_inited_(false) {} ~ObObjectLinkIter() = default; - int init(const ObMetaDiskAddr &head); + int init(storage_io::BlockOwner &blocks, const ObMetaDiskAddr &head); int reuse(); int get_next_block(ObIAllocator &allocator, char *&buf, int64_t &buf_len); int get_next_macro_id(blocksstable::MacroBlockId ¯o_id); @@ -251,6 +239,7 @@ class ObObjectLinkIter final private: int read_next_block(ObObjectReadHandle &object_io_handle); private: + storage_io::BlockOwner *blocks_ = nullptr; ObMetaDiskAddr head_; ObMetaDiskAddr cur_; bool is_inited_; @@ -264,10 +253,9 @@ class ObObjectReaderWriter final public: ObObjectReaderWriter(); ~ObObjectReaderWriter(); - int init(); + int init(storage_io::BlockOwner &blocks); void reset(); - void get_cur_block(blocksstable::MacroBlockId ¯o_id); - static int async_read(const ObObjectReadInfo &read_info, ObObjectReadHandle &object_io_handle, + static int async_read(storage_io::BlockOwner &blocks, const ObObjectReadInfo &read_info, ObObjectReadHandle &object_io_handle, std::unique_ptr callback = nullptr); static int parse_data_from_object( blocksstable::ObStorageObjectHandle &object_handle, @@ -276,16 +264,10 @@ class ObObjectReaderWriter final int64_t &buf_len); int async_write( const ObObjectWriteInfo &write_info, - const blocksstable::ObStorageObjectOpt &curr_opt, ObObjectWriteHandle &object_io_handle); int async_batch_write( const common::ObIArray &write_infos, - ObObjectBatchHandle &object_io_handle, - blocksstable::ObStorageObjectOpt &curr_opt); - int async_link_write( - const ObObjectWriteInfo &write_infos, - const blocksstable::ObStorageObjectOpt &curr_opt, - ObObjectLinkHandle &object_io_handle); + ObObjectBatchHandle &object_io_handle); private: int inner_async_write( ObObjectWriteSession &write_session, @@ -312,10 +294,8 @@ class ObObjectReaderWriter final ObObjectBaseHandle &object_io_handle, ObObjectsWriteCtx &write_ctx); int switch_object(ObObjectWriteSession &write_session, - blocksstable::ObStorageObjectHandle &object_handle, - const blocksstable::ObStorageObjectOpt &next_opt); - int do_switch(ObObjectWriteSession &write_session, - const blocksstable::ObStorageObjectOpt &opt); + blocksstable::ObStorageObjectHandle &object_handle); + int do_switch(ObObjectWriteSession &write_session); int reserve_header(ObObjectWriteSession &write_session); int ensure_data_buffer_for_write_(ObObjectWriteSession &write_session); int check_object_size_(const int64_t total_size, const bool need_align); @@ -324,18 +304,17 @@ struct ObObjectWriteArgs final { public: ObObjectWriteArgs() - : need_flush_(true), need_align_(true), is_linked_(false), with_header_(true), object_opt_() + : need_flush_(true), need_align_(true), with_header_(true) {} ~ObObjectWriteArgs() = default; - TO_STRING_KV(K_(need_flush), K_(need_align), K_(is_linked), K_(with_header), K_(object_opt)); + TO_STRING_KV(K_(need_flush), K_(need_align), K_(with_header)); bool need_flush_; bool need_align_; - bool is_linked_; bool with_header_; - blocksstable::ObStorageObjectOpt object_opt_; }; private: lib::ObMutex mutex_; + storage_io::BlockOwner *blocks_ = nullptr; blocksstable::ObStorageObjectHandle object_handle_; int64_t offset_; int64_t align_offset_; diff --git a/src/storage/compaction/ob_basic_tablet_merge_ctx.cpp b/src/storage/compaction/ob_basic_tablet_merge_ctx.cpp index 240af241ef..0d24041322 100644 --- a/src/storage/compaction/ob_basic_tablet_merge_ctx.cpp +++ b/src/storage/compaction/ob_basic_tablet_merge_ctx.cpp @@ -813,7 +813,7 @@ int ObBasicTabletMergeCtx::init_static_desc() { int ret = OB_SUCCESS; static_param_.concurrent_cnt_ = get_concurrent_cnt(); - if (OB_FAIL(static_desc_.init(false/*is_ddl*/, *get_schema(), get_tablet_id(), + if (OB_FAIL(static_desc_.init(get_tablet()->block_file(), false/*is_ddl*/, *get_schema(), get_tablet_id(), get_merge_type(), get_snapshot(), static_param_.scn_range_.end_scn_, static_param_.data_version_, diff --git a/src/storage/compaction/ob_index_block_micro_iterator.cpp b/src/storage/compaction/ob_index_block_micro_iterator.cpp index 56fd7cf8ee..a58cfbaa66 100644 --- a/src/storage/compaction/ob_index_block_micro_iterator.cpp +++ b/src/storage/compaction/ob_index_block_micro_iterator.cpp @@ -16,6 +16,7 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_index_block_micro_iterator.h" @@ -167,7 +168,7 @@ int ObIndexBlockMicroIterator::init( read_info.macro_block_id_ = macro_desc.macro_block_id_; - if (OB_FAIL(ObObjectManager::async_read_object(read_info, macro_handle_))) { + if (OB_FAIL(macro_handle_.async_read(sstable->block_file(), read_info))) { } else if (OB_FAIL(macro_handle_.wait())) { } else if (OB_ISNULL(macro_handle_.get_buffer()) || (OB_UNLIKELY(macro_handle_.get_data_size() != read_info.size_))) { diff --git a/src/storage/compaction/ob_index_block_micro_iterator.h b/src/storage/compaction/ob_index_block_micro_iterator.h index 958f5d21b3..32b6559f73 100644 --- a/src/storage/compaction/ob_index_block_micro_iterator.h +++ b/src/storage/compaction/ob_index_block_micro_iterator.h @@ -21,11 +21,12 @@ #include "share/io_request.h" #include "share/schema/ob_table_schema.h" #include "storage/access/ob_table_read_info.h" -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" +#include "storage/blocksstable/ob_block_sstable_struct.h" #include "storage/blocksstable/index_block/ob_index_block_tree_cursor.h" #include "storage/blocksstable/ob_macro_block_reader.h" #include "storage/blocksstable/index_block/ob_index_block_dual_meta_iterator.h" -#include "storage/blocksstable/ob_block_manager.h" namespace oceanbase { diff --git a/src/storage/compaction/ob_partition_parallel_merge_ctx.cpp b/src/storage/compaction/ob_partition_parallel_merge_ctx.cpp index 602c6f8d24..9e96a79636 100644 --- a/src/storage/compaction/ob_partition_parallel_merge_ctx.cpp +++ b/src/storage/compaction/ob_partition_parallel_merge_ctx.cpp @@ -417,7 +417,7 @@ int ObParallelMergeCtx::get_concurrent_cnt( } else if (0 == tablet_size) { concurrent_cnt = 1; } else { - const int64_t macro_block_size = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + const int64_t macro_block_size = OB_DEFAULT_MACRO_BLOCK_SIZE; if (((macro_block_cnt * macro_block_size + tablet_size - 1) / tablet_size) <= max_merge_thread) { concurrent_cnt = (macro_block_cnt * macro_block_size + tablet_size - 1) / tablet_size; diff --git a/src/storage/compaction/ob_sstable_builder.cpp b/src/storage/compaction/ob_sstable_builder.cpp index 104966af7a..31e88eba74 100644 --- a/src/storage/compaction/ob_sstable_builder.cpp +++ b/src/storage/compaction/ob_sstable_builder.cpp @@ -15,6 +15,7 @@ */ #define USING_LOG_PREFIX STORAGE_COMPACTION +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_sstable_builder.h" #include "storage/compaction/ob_basic_tablet_merge_ctx.h" @@ -48,7 +49,7 @@ int ObSSTableRebuildMicroBlockIter::prefetch() read_info.macro_block_id_ = macro_id_array_.at(prefetch_idx_); - if (OB_FAIL(ObObjectManager::async_read_object(read_info, macro_io_handle))) { + if (OB_FAIL(macro_io_handle.async_read(blocks_, read_info))) { } } else { break; @@ -360,7 +361,7 @@ int ObSSTableRebuilder::rebuild_macro_block(const ObIArray ¯o_ ret = OB_ERR_UNEXPECTED; STORAGE_LOG(WARN, "unexpected null read info", K(ret)); } else { - ObSSTableRebuildMicroBlockIter micro_iter(macro_id_array, *index_read_info_); + ObSSTableRebuildMicroBlockIter micro_iter(data_store_desc_.get_desc().block_file(), macro_id_array, *index_read_info_); { blocksstable::ObDataMacroBlockMeta macro_meta; int64_t macro_id_idx = 0; diff --git a/src/storage/compaction/ob_sstable_builder.h b/src/storage/compaction/ob_sstable_builder.h index c3ec87bc3c..b4aef19340 100644 --- a/src/storage/compaction/ob_sstable_builder.h +++ b/src/storage/compaction/ob_sstable_builder.h @@ -36,9 +36,10 @@ class ObSSTableRebuildMicroBlockIter final { public: ObSSTableRebuildMicroBlockIter( + storage_io::BlockOwner &blocks, const ObIArray ¯o_id_array, const ObITableReadInfo &index_read_info) - : allocator_("RebuildIter"), + : blocks_(blocks), allocator_("RebuildIter"), macro_id_array_(macro_id_array), index_read_info_(index_read_info), mirco_block_iter_(), @@ -63,6 +64,7 @@ class ObSSTableRebuildMicroBlockIter final } static const int64_t PREFETCH_DEPTH = 3; private: + storage_io::BlockOwner &blocks_; ObArenaAllocator allocator_; const ObIArray ¯o_id_array_; const ObITableReadInfo &index_read_info_; diff --git a/src/storage/compaction/ob_tablet_merge_info.cpp b/src/storage/compaction/ob_tablet_merge_info.cpp index 32925fbed5..e314ee3b9d 100644 --- a/src/storage/compaction/ob_tablet_merge_info.cpp +++ b/src/storage/compaction/ob_tablet_merge_info.cpp @@ -188,7 +188,7 @@ int ObTabletMergeInfo::create_sstable( } else if (FALSE_IT(res.root_macro_seq_ = new_root_macro_seq)) { } else if (OB_FAIL(build_create_sstable_param(ctx, res, param))) { } else if (OB_FAIL(ObTabletCreateDeleteHelper::create_sstable( - param, ctx.mem_ctx_.get_allocator(), merge_table_handle))) { + ctx.get_tablet()->block_file(), param, ctx.mem_ctx_.get_allocator(), merge_table_handle))) { LOG_ERROR("fail to create sstable", K(ret), K(param)); CTX_SET_DIAGNOSE_LOCATION(ctx); } diff --git a/src/storage/compaction/ob_tablet_scheduler.cpp b/src/storage/compaction/ob_tablet_scheduler.cpp index 6bf6f65af8..62683bb24d 100644 --- a/src/storage/compaction/ob_tablet_scheduler.cpp +++ b/src/storage/compaction/ob_tablet_scheduler.cpp @@ -261,7 +261,7 @@ void ObTabletScheduler::reset() LOG_INFO("The ObTabletScheduler destroy"); } -int ObTabletScheduler::init() +int ObTabletScheduler::init(storage_io::BlockOwner &blocks) { int ret = OB_SUCCESS; bool enable_adaptive_compaction = false; @@ -288,6 +288,7 @@ int ObTabletScheduler::init() IGNORE_RETURN runtime_status_.refresh_runtime_config(enable_adaptive_compaction); timer_task_mgr_.set_scheduler_interval(schedule_interval); batch_size_mgr_.set_tablet_batch_size(schedule_batch_size); + blocks_ = &blocks; is_inited_ = true; } return ret; @@ -330,11 +331,6 @@ int ObTabletScheduler::reload_runtime_config() return ret; } -int ObTabletScheduler::server_module_init(ObTabletScheduler* &scheduler) -{ - return scheduler->init(); -} - void ObTabletScheduler::stop() { is_stop_ = true; @@ -524,7 +520,7 @@ int ObTabletScheduler::schedule_build_bloomfilter( } else if (OB_UNLIKELY(!macro_id.is_valid() || prefix_len <= 0)) { ret = OB_INVALID_ARGUMENT; } else { - ObBloomFilterBuildTask task(table_id, macro_id, prefix_len); + ObBloomFilterBuildTask task(*blocks_, table_id, macro_id, prefix_len); if (OB_FAIL(bf_queue_.add_task(task))) { if (OB_LIKELY(OB_EAGAIN == ret)) { ret = OB_SUCCESS; diff --git a/src/storage/compaction/ob_tablet_scheduler.h b/src/storage/compaction/ob_tablet_scheduler.h index 647613c5eb..acdc40db86 100644 --- a/src/storage/compaction/ob_tablet_scheduler.h +++ b/src/storage/compaction/ob_tablet_scheduler.h @@ -30,6 +30,8 @@ #include "storage/compaction/ob_compaction_schedule_util.h" #include "storage/compaction/ob_medium_loop.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace blocksstable @@ -98,9 +100,7 @@ class ObTabletScheduler : public ObBasicMergeScheduler public: ObTabletScheduler(); virtual ~ObTabletScheduler(); - static int server_module_init(ObTabletScheduler* &scheduler); - - int init(); + int init(storage_io::BlockOwner &blocks); int start(); void destroy(); void reset(); @@ -196,6 +196,7 @@ class ObTabletScheduler : public ObBasicMergeScheduler static const int64_t PRINT_LOG_INTERVAL = 2 * 60 * 1000 * 1000L; // 2m static const int64_t MERGE_BACTH_FREEZE_CNT = 100L; private: + storage_io::BlockOwner *blocks_ = nullptr; bool is_inited_; common::ObDedupQueue bf_queue_; ObFastFreezeChecker fast_freeze_checker_; diff --git a/src/storage/concurrency_control/ob_multi_version_garbage_collector.cpp b/src/storage/concurrency_control/ob_multi_version_garbage_collector.cpp index f60fb53e52..2dc22a763f 100644 --- a/src/storage/concurrency_control/ob_multi_version_garbage_collector.cpp +++ b/src/storage/concurrency_control/ob_multi_version_garbage_collector.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "storage/blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" #include "rust/config.h" #include "storage/concurrency_control/ob_multi_version_garbage_collector.h" #include "query/ob_i_active_snapshot_service.h" @@ -45,13 +45,7 @@ ObMultiVersionGarbageCollector::ObMultiVersionGarbageCollector() ObMultiVersionGarbageCollector::~ObMultiVersionGarbageCollector() {} -int ObMultiVersionGarbageCollector::server_module_init( - ObMultiVersionGarbageCollector *&m) -{ - return m->init(); -} - -int ObMultiVersionGarbageCollector::init() +int ObMultiVersionGarbageCollector::init(storage_io::BlockOwner &blocks) { int ret = OB_SUCCESS; if (OB_UNLIKELY(is_inited_)) { @@ -63,6 +57,7 @@ int ObMultiVersionGarbageCollector::init() has_error_when_study_ = false; gc_is_disabled_ = false; local_reserved_snapshot_ = share::SCN::min_scn(); + blocks_ = &blocks; is_inited_ = true; MVCC_LOG(INFO, "multi version garbage collector init", KP(this)); } @@ -462,7 +457,7 @@ int ObMultiVersionGarbageCollector::is_disk_almost_full_(bool &is_almost_full) // Case1: io device is almost full if (!is_almost_full - && OB_FAIL(OB_SERVER_BLOCK_MGR.check_space_full(required_size))) { + && OB_FAIL(blocksstable::check_block_space(*blocks_, required_size))) { if (OB_SERVER_OUTOF_DISK_SPACE == ret) { ret = OB_SUCCESS; is_almost_full = true; diff --git a/src/storage/concurrency_control/ob_multi_version_garbage_collector.h b/src/storage/concurrency_control/ob_multi_version_garbage_collector.h index 3f8d304c85..1a649a4ad1 100644 --- a/src/storage/concurrency_control/ob_multi_version_garbage_collector.h +++ b/src/storage/concurrency_control/ob_multi_version_garbage_collector.h @@ -20,6 +20,8 @@ #include "lib/task/ob_timer.h" #include "share/scn.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace concurrency_control @@ -52,9 +54,8 @@ class ObMultiVersionGarbageCollector public: ObMultiVersionGarbageCollector(); ~ObMultiVersionGarbageCollector(); - static int server_module_init(ObMultiVersionGarbageCollector *&p_garbage_colloector); public: - int init(); + int init(storage_io::BlockOwner &blocks); int start(); int stop(); void wait(); @@ -134,6 +135,7 @@ class ObMultiVersionGarbageCollector bool gc_is_disabled_; // Last complete local safety-watermark sample for active transactions. share::SCN local_reserved_snapshot_; + storage_io::BlockOwner *blocks_ = nullptr; bool is_inited_; }; diff --git a/src/storage/ddl/ob_complement_data_task.cpp b/src/storage/ddl/ob_complement_data_task.cpp index a2e17e8c38..de05b5aea6 100644 --- a/src/storage/ddl/ob_complement_data_task.cpp +++ b/src/storage/ddl/ob_complement_data_task.cpp @@ -83,6 +83,7 @@ int ObComplementDataParam::fill_tablet_param() } else if (OB_FAIL(tablet_handle.get_obj()->load_storage_schema(allocator_, tablet_param_.storage_schema_))) { } else if (OB_FAIL(tablet_handle.get_obj()->get_ddl_kv_mgr(ddl_kv_mgr_handle, true /*try_create]*/))) { } else { + tablet_param_.blocks_ = &tablet_handle.get_obj()->block_file(); tablet_param_.is_micro_index_clustered_ = tablet_handle.get_obj()->get_tablet_meta().micro_index_clustered_; ObTabletBindingMdsUserData mds_data; if (OB_FAIL(tablet_handle.get_obj()->ObITabletMdsInterface::get_ddl_data(share::SCN::max_scn(), mds_data))) { @@ -92,6 +93,7 @@ int ObComplementDataParam::fill_tablet_param() if (OB_FAIL(ObDDLStorageUtil::ddl_get_tablet(ls, mds_data.lob_meta_tablet_id_, lob_meta_tablet_handle, ObMDSGetTabletMode::READ_ALL_COMMITED))) { } else if (OB_FAIL(lob_meta_tablet_handle.get_obj()->load_storage_schema(allocator_, lob_meta_tablet_param_.storage_schema_))) { } else { + lob_meta_tablet_param_.blocks_ = &lob_meta_tablet_handle.get_obj()->block_file(); lob_meta_tablet_param_.is_micro_index_clustered_ = lob_meta_tablet_handle.get_obj()->get_tablet_meta().micro_index_clustered_; ObDDLKvMgrHandle lob_ddl_kv_mgr_handle; if (OB_FAIL(lob_meta_tablet_handle.get_obj()->get_ddl_kv_mgr(lob_ddl_kv_mgr_handle, true /*try_create]*/))) { diff --git a/src/storage/ddl/ob_ddl_clog.cpp b/src/storage/ddl/ob_ddl_clog.cpp index c5a037ac6a..8f5aab6c34 100644 --- a/src/storage/ddl/ob_ddl_clog.cpp +++ b/src/storage/ddl/ob_ddl_clog.cpp @@ -68,21 +68,12 @@ void ObDDLClogCb::try_release() } ObDDLMacroBlockClogCb::ObDDLMacroBlockClogCb() - : is_inited_(false), status_(), macro_block_id_(), + : is_inited_(false), status_(), data_buffer_lock_(), is_data_buffer_freed_(false), ddl_macro_block_(), snapshot_version_(0), data_format_version_(0), direct_load_type_(ObDirectLoadType::DIRECT_LOAD_INVALID), block_checksum_(0), is_macro_block_exist_(false) {} -ObDDLMacroBlockClogCb::~ObDDLMacroBlockClogCb() -{ - int ret = OB_SUCCESS; - if (macro_block_id_.is_valid() && OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_block_id_))) { - LOG_ERROR("dec ref failed", K(ret), K(macro_block_id_), K(common::lbt())); - } - macro_block_id_.reset(); -} - int ObDDLMacroBlockClogCb::init(const storage::ObDDLMacroBlockRedoInfo &redo_info, const blocksstable::MacroBlockId ¯o_block_id, ObTabletHandle &tablet_handle, @@ -92,27 +83,21 @@ int ObDDLMacroBlockClogCb::init(const storage::ObDDLMacroBlockRedoInfo &redo_inf if (OB_UNLIKELY(is_inited_)) { ret = OB_INIT_TWICE; } else if (OB_UNLIKELY(!redo_info.is_valid() || !macro_block_id.is_valid() - || !is_valid_direct_load(direct_load_type))) { + || !tablet_handle.is_valid() || !is_valid_direct_load(direct_load_type))) { ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(macro_block_id))) { + } else if (OB_FAIL(ddl_macro_block_.block_handle_.set_block_id(tablet_handle.get_obj()->block_file(), macro_block_id))) { + } else if (OB_FAIL(ddl_macro_block_.set_data_macro_meta(macro_block_id, + redo_info.data_buffer_.ptr(), redo_info.data_buffer_.length(), redo_info.block_type_))) { } else { - macro_block_id_ = macro_block_id; tablet_handle_ = tablet_handle; snapshot_version_ = redo_info.table_key_.get_snapshot_version(); data_format_version_ = redo_info.data_format_version_; direct_load_type_ = direct_load_type; - if (OB_FAIL(ddl_macro_block_.block_handle_.set_block_id(macro_block_id_))) { - } else if (OB_FAIL(ddl_macro_block_.set_data_macro_meta(macro_block_id_, - redo_info.data_buffer_.ptr(), - redo_info.data_buffer_.length(), - redo_info.block_type_))) { - } else { - ddl_macro_block_.block_type_ = redo_info.block_type_; - ddl_macro_block_.logic_id_ = redo_info.logic_id_; - ddl_macro_block_.ddl_start_scn_ = redo_info.start_scn_; - ddl_macro_block_.table_key_ = redo_info.table_key_; - ddl_macro_block_.merge_slice_idx_ = redo_info.merge_slice_idx_; - } + ddl_macro_block_.block_type_ = redo_info.block_type_; + ddl_macro_block_.logic_id_ = redo_info.logic_id_; + ddl_macro_block_.ddl_start_scn_ = redo_info.start_scn_; + ddl_macro_block_.table_key_ = redo_info.table_key_; + ddl_macro_block_.merge_slice_idx_ = redo_info.merge_slice_idx_; } ObTablet *tablet = nullptr; ObDDLKvMgrHandle kv_mgr_handle; @@ -137,6 +122,9 @@ int ObDDLMacroBlockClogCb::init(const storage::ObDDLMacroBlockRedoInfo &redo_inf is_macro_block_exist_))) { } } + if (OB_SUCC(ret)) { + is_inited_ = true; + } return ret; } diff --git a/src/storage/ddl/ob_ddl_clog.h b/src/storage/ddl/ob_ddl_clog.h index 75d8a2589f..011e2d6f90 100644 --- a/src/storage/ddl/ob_ddl_clog.h +++ b/src/storage/ddl/ob_ddl_clog.h @@ -89,7 +89,7 @@ class ObDDLMacroBlockClogCb : public logservice::AppendCb { public: ObDDLMacroBlockClogCb(); - virtual ~ObDDLMacroBlockClogCb(); + ~ObDDLMacroBlockClogCb() override = default; int init(const storage::ObDDLMacroBlockRedoInfo &redo_info, const blocksstable::MacroBlockId ¯o_block_id, ObTabletHandle &tablet_handle, @@ -105,7 +105,6 @@ class ObDDLMacroBlockClogCb : public logservice::AppendCb private: bool is_inited_; ObDDLClogCbStatus status_; - blocksstable::MacroBlockId macro_block_id_; ObSpinLock data_buffer_lock_; bool is_data_buffer_freed_; ObTabletHandle tablet_handle_; diff --git a/src/storage/ddl/ob_ddl_macro_block_writer.cpp b/src/storage/ddl/ob_ddl_macro_block_writer.cpp index fc11b26492..4690d0005e 100644 --- a/src/storage/ddl/ob_ddl_macro_block_writer.cpp +++ b/src/storage/ddl/ob_ddl_macro_block_writer.cpp @@ -66,7 +66,7 @@ int ObDDLMacroBlockWriter::init( || !start_sequence.is_valid() || row_offset < 0)) { ret = OB_INVALID_ARGUMENT; - } else if (OB_ISNULL(tablet_param.storage_schema_)) { + } else if (OB_ISNULL(tablet_param.storage_schema_) || OB_ISNULL(tablet_param.blocks_)) { ret = OB_ERR_UNEXPECTED; } else { share::SCN mock_start_scn; @@ -85,7 +85,7 @@ int ObDDLMacroBlockWriter::init( macro_seq_param.start_ = start_sequence.macro_data_seq_; if (OB_FAIL(pre_warm_param.init(table_key.tablet_id_))) { - } else if (OB_FAIL(data_desc_.init(true/*is ddl*/, + } else if (OB_FAIL(data_desc_.init(*tablet_param.blocks_, true/*is ddl*/, *tablet_param.storage_schema_, table_key.get_tablet_id(), compaction::ObMergeType::MAJOR_MERGE, diff --git a/src/storage/ddl/ob_ddl_merge_task.cpp b/src/storage/ddl/ob_ddl_merge_task.cpp index d778603724..6641309790 100644 --- a/src/storage/ddl/ob_ddl_merge_task.cpp +++ b/src/storage/ddl/ob_ddl_merge_task.cpp @@ -615,7 +615,7 @@ int ObTabletDDLUtil::prepare_index_data_desc(const ObTablet &tablet, const bool micro_index_clustered = tablet.get_tablet_meta().micro_index_clustered_; if (OB_UNLIKELY(!tablet_id.is_valid() || snapshot_version <= 0 || data_format_version <= 0 || OB_ISNULL(storage_schema))) { ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(data_desc.init(true/*is_ddl*/, + } else if (OB_FAIL(data_desc.init(tablet.block_file(), true/*is_ddl*/, *storage_schema, tablet_id, table_key.is_minor_sstable() ? compaction::MINOR_MERGE : compaction::MAJOR_MERGE, @@ -724,7 +724,8 @@ int ObTabletDDLUtil::create_ddl_sstable( ObTabletCreateSSTableParam param; if (OB_FAIL(param.init_for_ddl(sstable_index_builder, ddl_param, first_ddl_sstable, *storage_schema, macro_block_column_count, create_schema_version_on_tablet, macro_id_array))) { - } else if (OB_FAIL(ObTabletCreateDeleteHelper::create_sstable(param, allocator, sstable_handle))) { + } else if (OB_FAIL(ObTabletCreateDeleteHelper::create_sstable( + tablet.block_file(), param, allocator, sstable_handle))) { } if (OB_SUCC(ret)) { LOG_INFO("create ddl sstable success", K(ddl_param), K(sstable_handle), diff --git a/src/storage/ddl/ob_ddl_replay_executor.cpp b/src/storage/ddl/ob_ddl_replay_executor.cpp index c2d8448691..853d8805cf 100644 --- a/src/storage/ddl/ob_ddl_replay_executor.cpp +++ b/src/storage/ddl/ob_ddl_replay_executor.cpp @@ -16,6 +16,7 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "rust/config.h" #include "ob_ddl_replay_executor.h" #include "share/rc/ob_server_runtime.h" @@ -117,12 +118,8 @@ int ObDDLRedoReplayExecutor::do_replay_(ObTabletHandle &tablet_handle) ret = OB_INVALID_ARGUMENT; } else { const ObDDLMacroBlockRedoInfo &redo_info = log_->get_redo_info(); - ObMacroBlockWriteInfo write_info; ObDDLMacroBlock macro_block; bool can_skip = false; - write_info.buffer_ = redo_info.data_buffer_.ptr(); - write_info.size_= redo_info.data_buffer_.length(); - write_info.io_timeout_ms_ = max(DDL_FLUSH_MACRO_BLOCK_TIMEOUT / 1000L, config::_data_storage_io_timeout() / 1000L); macro_block.block_type_ = redo_info.block_type_; macro_block.logic_id_ = redo_info.logic_id_; macro_block.scn_ = scn_; @@ -133,7 +130,7 @@ int ObDDLRedoReplayExecutor::do_replay_(ObTabletHandle &tablet_handle) if (OB_FAIL(filter_redo_log_(redo_info, tablet_handle, can_skip))) { } else if (can_skip) { } else { - if (OB_FAIL(do_full_replay_(tablet_handle, write_info, macro_block))) { + if (OB_FAIL(do_full_replay_(tablet_handle, macro_block))) { } } if (OB_SERVER_OUTOF_DISK_SPACE == ret) { @@ -194,11 +191,9 @@ int set_idem_block_checksum(ObTabletHandle &tablet_handle, const ObDDLMacroBlock int ObDDLRedoReplayExecutor::do_full_replay_( ObTabletHandle &tablet_handle, - blocksstable::ObMacroBlockWriteInfo &write_info, storage::ObDDLMacroBlock ¯o_block) { int ret = OB_SUCCESS; - ObMacroBlockHandle macro_handle; bool need_replay = true; ObTabletMemberWrapper table_store_wrapper; int64_t checksum = 0; @@ -224,8 +219,6 @@ int ObDDLRedoReplayExecutor::do_full_replay_( } else if (!need_replay) { } else { const ObDDLMacroBlockRedoInfo &redo_info = log_->get_redo_info(); - ObStorageObjectOpt opt; - opt.set_data_macro_object_opt(); ObStorageObjectHandle macro_handle; ObStorageObjectWriteInfo write_info; write_info.buffer_ = redo_info.data_buffer_.ptr(); @@ -234,9 +227,10 @@ int ObDDLRedoReplayExecutor::do_full_replay_( write_info.io_timeout_ms_ = max(DDL_FLUSH_MACRO_BLOCK_TIMEOUT / 1000L, config::_data_storage_io_timeout() / 1000L); - if (OB_FAIL(ObObjectManager::async_write_object(opt, write_info, macro_handle))) { + auto &blocks = tablet_handle.get_obj()->block_file(); + if (OB_FAIL(macro_handle.allocate_and_write(blocks, write_info))) { } else if (OB_FAIL(macro_handle.wait())) { - } else if (OB_FAIL(macro_block.block_handle_.set_block_id(macro_handle.get_macro_id()))) { + } else if (OB_FAIL(macro_block.block_handle_.set_block_id(blocks, macro_handle.get_macro_id()))) { } if (OB_FAIL(ret)) { diff --git a/src/storage/ddl/ob_ddl_replay_executor.h b/src/storage/ddl/ob_ddl_replay_executor.h index 294fd4dc95..7e3b367c19 100644 --- a/src/storage/ddl/ob_ddl_replay_executor.h +++ b/src/storage/ddl/ob_ddl_replay_executor.h @@ -102,8 +102,7 @@ class ObDDLRedoReplayExecutor final : public ObDDLReplayExecutor private: int do_full_replay_( - ObTabletHandle &tablet_handle, - blocksstable::ObMacroBlockWriteInfo &write_info, + ObTabletHandle &tablet_handle, storage::ObDDLMacroBlock ¯o_block); int filter_redo_log_( const ObDDLMacroBlockRedoInfo &redo_info, diff --git a/src/storage/ddl/ob_ddl_struct.cpp b/src/storage/ddl/ob_ddl_struct.cpp index d170bd252f..f81cab8c5b 100644 --- a/src/storage/ddl/ob_ddl_struct.cpp +++ b/src/storage/ddl/ob_ddl_struct.cpp @@ -28,51 +28,16 @@ using namespace oceanbase::storage; using namespace oceanbase::blocksstable; using namespace oceanbase::share; -ObDDLMacroHandle::ObDDLMacroHandle() - : block_id_() -{ - -} - -ObDDLMacroHandle::ObDDLMacroHandle(const ObDDLMacroHandle &other) -{ - *this = other; -} - -ObDDLMacroHandle &ObDDLMacroHandle::operator=(const ObDDLMacroHandle &other) -{ - if (&other != this) { - (void)set_block_id(other.get_block_id()); - } - return *this; -} - -ObDDLMacroHandle::~ObDDLMacroHandle() -{ - reset_macro_block_ref(); -} - -int ObDDLMacroHandle::set_block_id(const blocksstable::MacroBlockId &block_id) +int ObDDLMacroHandle::set_block_id(storage_io::BlockOwner &blocks, const blocksstable::MacroBlockId &block_id) { int ret = OB_SUCCESS; + ObStorageObjectHandle next; if (OB_UNLIKELY(!block_id.is_valid())) { ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(reset_macro_block_ref())) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(block_id))) { + } else if (block_id == get_block_id()) { + } else if (OB_FAIL(next.set_macro_block_id(blocks, block_id))) { } else { - block_id_ = block_id; - } - return ret; -} - -int ObDDLMacroHandle::reset_macro_block_ref() -{ - int ret = OB_SUCCESS; - if (block_id_.is_valid()) { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(block_id_))) { - } else { - block_id_.reset(); - } + handle_ = next; } return ret; } diff --git a/src/storage/ddl/ob_ddl_struct.h b/src/storage/ddl/ob_ddl_struct.h index 51a866f910..c4e58c39a2 100644 --- a/src/storage/ddl/ob_ddl_struct.h +++ b/src/storage/ddl/ob_ddl_struct.h @@ -23,6 +23,7 @@ #include "storage/access/ob_store_row_iterator.h" #include "storage/blocksstable/ob_block_sstable_struct.h" #include "storage/blocksstable/ob_macro_block_meta.h" +#include "storage/blocksstable/ob_storage_object_handle.h" #include "storage/ob_i_table.h" #include "data_plane/ddl/ob_direct_load_type.h" namespace oceanbase @@ -46,20 +47,15 @@ enum ObDDLMacroBlockType DDL_MB_TABLET_META_TYPE = 4, }; -class ObDDLMacroHandle +class ObDDLMacroHandle final { public: - ObDDLMacroHandle(); - ObDDLMacroHandle(const ObDDLMacroHandle &other); - ObDDLMacroHandle &operator=(const ObDDLMacroHandle &other); - ~ObDDLMacroHandle(); - bool is_valid() const { return block_id_.is_valid(); } - int set_block_id(const blocksstable::MacroBlockId &block_id); - int reset_macro_block_ref(); - const blocksstable::MacroBlockId &get_block_id() const { return block_id_; } - TO_STRING_KV(K_(block_id)); + bool is_valid() const { return get_block_id().is_valid(); } + int set_block_id(storage_io::BlockOwner &blocks, const blocksstable::MacroBlockId &block_id); + const blocksstable::MacroBlockId &get_block_id() const { return handle_.get_macro_id(); } + TO_STRING_KV("block_id", get_block_id()); private: - blocksstable::MacroBlockId block_id_; + blocksstable::ObStorageObjectHandle handle_; }; class ObDDLMacroBlock final @@ -404,16 +400,18 @@ struct ObWriteTabletParam public: ObWriteTabletParam() : is_micro_index_clustered_(false), - storage_schema_(nullptr) { } + storage_schema_(nullptr), blocks_(nullptr) { } void reset() { is_micro_index_clustered_ = false; storage_schema_ = nullptr; + blocks_ = nullptr; } TO_STRING_KV(K_(is_micro_index_clustered), KP_(storage_schema)); public: bool is_micro_index_clustered_; // get from tablet meta ObStorageSchema *storage_schema_; // references to ObDDLTableSchema + storage_io::BlockOwner *blocks_; }; struct ObWriteMacroParam final diff --git a/src/storage/ddl/ob_ddl_tablet_context.cpp b/src/storage/ddl/ob_ddl_tablet_context.cpp index ef5c298cf8..1b694f96bd 100644 --- a/src/storage/ddl/ob_ddl_tablet_context.cpp +++ b/src/storage/ddl/ob_ddl_tablet_context.cpp @@ -166,6 +166,7 @@ int init_tablet_param(ObTablet *tablet, ObStorageSchema *storage_schema, const O const ObTabletMeta &tablet_meta = tablet->get_tablet_meta(); tablet_param.is_micro_index_clustered_ = tablet_meta.micro_index_clustered_; tablet_param.storage_schema_ = storage_schema; + tablet_param.blocks_ = &tablet->block_file(); if (OB_FAIL(tablet->get_ddl_kv_mgr(ddl_kv_mgr_handle, true /*try_create]*/))) { } } diff --git a/src/storage/ddl/ob_tablet_ddl_kv.cpp b/src/storage/ddl/ob_tablet_ddl_kv.cpp index 40c7924aa7..2edb8daf14 100644 --- a/src/storage/ddl/ob_tablet_ddl_kv.cpp +++ b/src/storage/ddl/ob_tablet_ddl_kv.cpp @@ -643,6 +643,7 @@ int ObDDLMemtable::init( && OB_FAIL(ddl_table_iter.get_boundary_table(false/*is_last*/, first_ddl_sstable))) { } else if (OB_FAIL(block_meta_tree_.init(tablet, table_key, ddl_start_scn, data_format_version, storage_schema, static_cast(first_ddl_sstable)))) { } else if (OB_FAIL(init_sstable_param(*storage_schema, table_key, ddl_start_scn, sstable_param))) { + } else if (FALSE_IT(bind_block_file(tablet.block_file()))) { } else if (OB_FAIL(ObSSTable::init(sstable_param, &allocator))) { } else { ddl_kv_type_ = ddl_kv_type; @@ -865,7 +866,7 @@ int ObDDLKV::set_macro_block( const bool can_freeze) { int ret = OB_SUCCESS; - const int64_t MAX_DDL_BLOCK_COUNT = 10LL * 10LL * 1024LL * 1024LL * 1024LL / OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + const int64_t MAX_DDL_BLOCK_COUNT = 10LL * 10LL * 1024LL * 1024LL * 1024LL / OB_DEFAULT_MACRO_BLOCK_SIZE; const int64_t MEMORY_LIMIT = 50 * 1024 * 1024; // 50M int64_t freeze_block_count = MAX_DDL_BLOCK_COUNT; if (OB_UNLIKELY(!is_inited_)) { @@ -882,7 +883,7 @@ int ObDDLKV::set_macro_block( } else if (OB_TMP_FAIL(runtime->get_server_log_disk_size(log_disk_size))) { } else { const int64_t log_allowed_block_count = - log_disk_size * 0.2 / OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + log_disk_size * 0.2 / OB_DEFAULT_MACRO_BLOCK_SIZE; if (log_allowed_block_count <= 0) { tmp_ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid macro block count by log disk size", K(tmp_ret), diff --git a/src/storage/ddl/ob_tablet_fork_task.cpp b/src/storage/ddl/ob_tablet_fork_task.cpp index 501ab8f474..4dcb5bce24 100644 --- a/src/storage/ddl/ob_tablet_fork_task.cpp +++ b/src/storage/ddl/ob_tablet_fork_task.cpp @@ -494,7 +494,7 @@ int ObTabletForkCtx::prepare_index_builder(const ObTabletForkParam ¶m) const int64_t snapshot_version = param.fork_snapshot_version_; if (OB_FAIL(data_desc.init( - true/*is_ddl*/, *storage_schema, + dst_tablet_handle_.get_obj()->block_file(), true/*is_ddl*/, *storage_schema, param.dest_tablet_id_, merge_type, snapshot_version, param.data_format_version_, dst_tablet_handle_.get_obj()->get_tablet_meta().micro_index_clustered_, 0/*concurrent_cnt*/, @@ -825,7 +825,7 @@ int ObTabletForkReuseTask::process_reuse_sstable() } else if (OB_FAIL(context_->src_tablet_handle_.get_obj()->build_sstable_clone_param( src_table_key, clone_sstable_param))) { } else if (OB_FAIL(param.init_for_fork(clone_sstable_param, param_->dest_tablet_id_, src_table_key, meta_handle.get_sstable_meta(), fork_snapshot_scn))) { - } else if (OB_FAIL(context_->create_sstable(param, table_handle))) { + } else if (OB_FAIL(context_->create_sstable(context_->ls_->block_file(), param, table_handle))) { } if (OB_SUCC(ret)) { @@ -883,7 +883,7 @@ int ObTabletForkRewriteTask::process() if (OB_FAIL(max_end_scn.convert_for_tx(param_->fork_snapshot_version_))) { } else if (OB_FAIL(create_param.init_for_fork(param_->dest_tablet_id_, src_table_key, basic_meta, basic_meta.schema_version_, merge_res, max_end_scn))) { - } else if (OB_FAIL(context_->create_sstable(create_param, table_handle))) { + } else if (OB_FAIL(context_->create_sstable(context_->ls_->block_file(), create_param, table_handle))) { } if (OB_SUCC(ret)) { if (OB_FAIL(context_->add_created_sstable(table_handle))) { @@ -950,7 +950,7 @@ int ObTabletForkRewriteTask::prepare_macro_block_writer( const int64_t snapshot_version = param_->fork_snapshot_version_; const bool micro_index_clustered = context_->dst_tablet_handle_.get_obj()->get_tablet_meta().micro_index_clustered_; if (OB_FAIL(data_desc.init( - true/*is_ddl*/, clipped_storage_schema, + context_->dst_tablet_handle_.get_obj()->block_file(), true/*is_ddl*/, clipped_storage_schema, param_->dest_tablet_id_, merge_type, snapshot_version, @@ -1150,7 +1150,7 @@ int ObTabletForkMergeTask::create_sstables() param_->dest_tablet_id_, end_scn, create_sstable_param))) { - } else if (OB_FAIL(context_->create_sstable(create_sstable_param, table_handle))) { + } else if (OB_FAIL(context_->create_sstable(context_->ls_->block_file(), create_sstable_param, table_handle))) { } if (OB_SUCC(ret)) { if (OB_FAIL(batch_sstables_handle.add_table(table_handle))) { diff --git a/src/storage/ddl/ob_tablet_fork_task.h b/src/storage/ddl/ob_tablet_fork_task.h index 01b180b9c1..1497a885af 100644 --- a/src/storage/ddl/ob_tablet_fork_task.h +++ b/src/storage/ddl/ob_tablet_fork_task.h @@ -145,11 +145,12 @@ struct ObTabletForkCtx final int get_created_sstable(const int64_t idx, ObTableHandleV2 &table_handle); // Thread-safe wrapper for create_sstable with allocator protection template - int create_sstable(const ObTabletCreateSSTableParam ¶m, ObTableHandleV2 &table_handle) + int create_sstable(storage_io::BlockOwner &blocks, + const ObTabletCreateSSTableParam ¶m, ObTableHandleV2 &table_handle) { int ret = common::OB_SUCCESS; common::ObSpinLockGuard guard(allocator_lock_); - if (OB_FAIL(ObTabletCreateDeleteHelper::create_sstable(param, allocator_, table_handle))) { + if (OB_FAIL(ObTabletCreateDeleteHelper::create_sstable(blocks, param, allocator_, table_handle))) { } return ret; } diff --git a/src/storage/ls/ob_ls.cpp b/src/storage/ls/ob_ls.cpp index f6deb95815..49de60db54 100644 --- a/src/storage/ls/ob_ls.cpp +++ b/src/storage/ls/ob_ls.cpp @@ -49,13 +49,14 @@ const uint64_t ObLS::INNER_TABLET_ID_LIST[TOTAL_INNER_TABLET_NUM] = { common::ObTabletID::LS_LOCK_TABLET_ID, }; -ObLS::ObLS() +ObLS::ObLS(storage_io::BlockOwner &block_file) : ls_tx_svr_(this), replay_handler_(), ls_freezer_(this), ls_sync_tablet_seq_handler_(), ls_ddl_log_handler_(), vector_idx_scheduler_(nullptr), + block_file_(block_file), is_inited_(false), running_state_(), switch_epoch_(0), diff --git a/src/storage/ls/ob_ls.h b/src/storage/ls/ob_ls.h index 2d919cb3c2..da286c7623 100644 --- a/src/storage/ls/ob_ls.h +++ b/src/storage/ls/ob_ls.h @@ -47,6 +47,8 @@ #include "data_plane/vector/ob_i_vector_index_runtime.h" #include "storage/ls/ob_freezer_define.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace share @@ -132,7 +134,7 @@ class ObLS DISALLOW_COPY_AND_ASSIGN(WRLockGuard); }; public: - ObLS(); + explicit ObLS(storage_io::BlockOwner &block_file); virtual ~ObLS(); int init(const ObRestoreStatus &restore_status, const share::SCN &create_scn, @@ -155,6 +157,7 @@ class ObLS ObLockTable *get_lock_table() { return &lock_table_; } ObTxTable *get_tx_table() { return &tx_table_; } ObLSWRSHandler *get_ls_wrs_handler() { return &ls_wrs_handler_; } + storage_io::BlockOwner &block_file() const { return block_file_; } ObLSTabletService *get_tablet_svr() { return &ls_tablet_svr_; } ObFreezer *get_freezer() { return &ls_freezer_; } checkpoint::ObCheckpointExecutor *get_checkpoint_executor() { return &checkpoint_executor_; } @@ -669,6 +672,7 @@ class ObLS data_plane::ObIVectorIndexScheduler *vector_idx_scheduler_; common::ObTimer vector_idx_scheduler_timer_; private: + storage_io::BlockOwner &block_file_; bool is_inited_; // set running state of ls. diff --git a/src/storage/ls/ob_ls_tablet_service.cpp b/src/storage/ls/ob_ls_tablet_service.cpp index e8ce7473ed..745856f8fc 100644 --- a/src/storage/ls/ob_ls_tablet_service.cpp +++ b/src/storage/ls/ob_ls_tablet_service.cpp @@ -1073,11 +1073,13 @@ int ObLSTabletService::replay_create_tablet( key, old_addr, disk_addr, pool_type, - true /* whether to set tablet pool */))) { + true /* set tablet pool */, + tablet->block_group_))) { } else if (FALSE_IT(time_guard.click("CASwap"))) { } else if (OB_FAIL(tablet->check_and_set_initial_state())) { } else if (OB_FAIL(tablet->start_direct_load_task_if_need())) { - } else if (OB_FAIL(tablet->inc_macro_ref_cnt())) { + } else if (tablet->block_group_) { + ret = STORAGE_META_SERVICE.register_recovered_tablet(*tablet); } if (OB_SUCC(ret)) { @@ -2561,7 +2563,7 @@ int ObLSTabletService::safe_update_cas_tablet( int ret = OB_SUCCESS; ObUpdateTabletPointerParam param; if (OB_FAIL(new_handle.get_obj()->get_updating_tablet_pointer_param(param))) { - } else if (OB_FAIL(STORAGE_META_SERVICE.update_tablet(key.tablet_id_, addr))) { + } else if (OB_FAIL(STORAGE_META_SERVICE.update_tablet(*new_handle.get_obj(), addr))) { } else if (FALSE_IT(time_guard.click("PersistMeta"))) { } else if (OB_FAIL(::oceanbase::share::server_service<::oceanbase::storage::ObStorageMetaMemMgr>()->compare_and_swap_tablet(key, old_handle, new_handle, param))) { LOG_ERROR("failed to compare and swap tablet", K(ret), K(key), K(addr), K(param)); @@ -2607,7 +2609,7 @@ int ObLSTabletService::safe_create_cas_tablet( int ret = OB_SUCCESS; ObUpdateTabletPointerParam param; if (OB_FAIL(tablet_handle.get_obj()->get_updating_tablet_pointer_param(param))) { - } else if (OB_FAIL(STORAGE_META_SERVICE.update_tablet(tablet_id, addr))) { + } else if (OB_FAIL(STORAGE_META_SERVICE.update_tablet(*tablet_handle.get_obj(), addr))) { } else if (FALSE_IT(time_guard.click("PersistMeta"))) { } else if (OB_FAIL(refresh_tablet_addr(tablet_id, param, tablet_handle))) { LOG_ERROR("failed to refresh tablet addr", K(ret), K(tablet_id), K(param), K(lbt())); diff --git a/src/storage/meta_mem/ob_meta_obj_struct.h b/src/storage/meta_mem/ob_meta_obj_struct.h index 9e2f5547ab..adcddd9058 100644 --- a/src/storage/meta_mem/ob_meta_obj_struct.h +++ b/src/storage/meta_mem/ob_meta_obj_struct.h @@ -21,7 +21,7 @@ #include "share/rc/ob_server_runtime.h" #include "share/ob_define.h" #include "storage/meta_mem/ob_storage_meta_obj_pool.h" -#include "storage/blocksstable/ob_macro_block_handle.h" +#include "storage/blocksstable/ob_macro_block_id.h" #include "storage/meta_mem/ob_i_storage_meta_obj.h" // interfaces have been made layer-neutral(conf L2), backfill namespace oceanbase diff --git a/src/storage/meta_mem/ob_storage_meta_cache.cpp b/src/storage/meta_mem/ob_storage_meta_cache.cpp index 0c7327f419..c1146ce31e 100644 --- a/src/storage/meta_mem/ob_storage_meta_cache.cpp +++ b/src/storage/meta_mem/ob_storage_meta_cache.cpp @@ -192,6 +192,7 @@ int ObStorageMetaValue::get_table_store(const ObTabletTableStore *&store) const } int ObStorageMetaValue::process_sstable( + storage_io::BlockOwner &block_file, ObStorageMetaValueHandle &handle, const ObStorageMetaKey &key, const char *buf, @@ -202,6 +203,7 @@ int ObStorageMetaValue::process_sstable( int ret = OB_SUCCESS; ObArenaAllocator allocator(common::ObMemAttr("ProSStable")); blocksstable::ObSSTable sstable; + sstable.bind_block_file(block_file); ObIStorageMetaObj *tiny_meta = nullptr; char *tmp_buf = nullptr; int64_t pos = 0; @@ -225,6 +227,7 @@ int ObStorageMetaValue::process_sstable( } int ObStorageMetaValue::process_table_store( + storage_io::BlockOwner &, ObStorageMetaValueHandle &handle, const ObStorageMetaKey &key, const char *buf, @@ -394,6 +397,7 @@ void ObStorageMetaCache::destory() } ObStorageMetaCache::ObStorageMetaIOCallback::ObStorageMetaIOCallback( + storage_io::BlockOwner &block_file, common::ObIAllocator *io_allocator, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, @@ -401,6 +405,7 @@ ObStorageMetaCache::ObStorageMetaIOCallback::ObStorageMetaIOCallback( const ObTablet *tablet, common::ObSafeArenaAllocator *arena_allocator) : ObObjectIOCallback(io_allocator, key.get_meta_addr(), common::ObIOCallbackType::STORAGE_META_CALLBACK), + block_file_(block_file), meta_type_(type), key_(key), handle_(handle), @@ -425,10 +430,10 @@ int ObStorageMetaCache::ObStorageMetaIOCallback::do_process(const char *buf, con } else if (OB_UNLIKELY(buf_len <= 0 || buf == nullptr)) { ret = OB_INVALID_DATA; } else if (OB_UNLIKELY(nullptr != arena_allocator_)) { // bypass cache processor - if (OB_FAIL(ObStorageMetaValue::bypass_processor[meta_type_](meta_type_, *arena_allocator_, + if (OB_FAIL(ObStorageMetaValue::bypass_processor[meta_type_](block_file_, meta_type_, *arena_allocator_, handle_, buf, buf_len))) { } - } else if (OB_FAIL(ObStorageMetaValue::processor[meta_type_](handle_, key_, buf, buf_len, tablet_))) { + } else if (OB_FAIL(ObStorageMetaValue::processor[meta_type_](block_file_, handle_, key_, buf, buf_len, tablet_))) { } return ret; } @@ -441,6 +446,7 @@ bool ObStorageMetaCache::ObStorageMetaIOCallback::is_valid() const } int ObStorageMetaCache::get_meta( + storage_io::BlockOwner &block_file, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, ObStorageMetaHandle &meta_handle, @@ -453,7 +459,7 @@ int ObStorageMetaCache::get_meta( } else if (OB_FAIL(get(key, meta_handle.cache_handle_.get_cache_value()->value_, meta_handle.cache_handle_.get_cache_value()->cache_handle_))) { if (OB_UNLIKELY(OB_ENTRY_NOT_EXIST != ret)) { - } else if (OB_FAIL(prefetch(type, key, meta_handle, tablet))) { + } else if (OB_FAIL(prefetch(block_file, type, key, meta_handle, tablet))) { } else { } } else { @@ -463,6 +469,7 @@ int ObStorageMetaCache::get_meta( } int ObStorageMetaCache::bypass_get_meta( + storage_io::BlockOwner &block_file, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, common::ObSafeArenaAllocator &allocator, @@ -473,12 +480,13 @@ int ObStorageMetaCache::bypass_get_meta( ret = OB_INVALID_ARGUMENT; } else if (OB_UNLIKELY(ObStorageMetaValue::TABLE_STORE == type)) { ret = OB_NOT_SUPPORTED; - } else if (OB_FAIL(get_meta_and_bypass_cache(type, key, allocator, meta_handle))) { + } else if (OB_FAIL(get_meta_and_bypass_cache(block_file, type, key, allocator, meta_handle))) { } return ret; } int ObStorageMetaCache::batch_get_meta_and_bypass_cache( + storage_io::BlockOwner &block_file, const common::ObIArray &meta_types, const common::ObIArray &keys, common::ObSafeArenaAllocator &allocator, @@ -497,7 +505,7 @@ int ObStorageMetaCache::batch_get_meta_and_bypass_cache( if (OB_UNLIKELY(ObStorageMetaValue::TABLE_STORE == meta_type)) { ret = OB_NOT_SUPPORTED; - } else if (OB_FAIL(get_meta_and_bypass_cache(meta_type, key, allocator, meta_handle))) { + } else if (OB_FAIL(get_meta_and_bypass_cache(block_file, meta_type, key, allocator, meta_handle))) { } else if (OB_FAIL(meta_handles.push_back(meta_handle))) { } } @@ -509,6 +517,7 @@ int ObStorageMetaCache::batch_get_meta_and_bypass_cache( } int ObStorageMetaCache::prefetch( + storage_io::BlockOwner &block_file, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, ObStorageMetaHandle &meta_handle, @@ -525,7 +534,7 @@ int ObStorageMetaCache::prefetch( ret = OB_ALLOCATE_MEMORY_FAILED; STORAGE_LOG(WARN, "allocate callback memory failed", K(ret)); } else { - callback = new (buf) ObStorageMetaIOCallback(&io_allocator, + callback = new (buf) ObStorageMetaIOCallback(block_file, &io_allocator, type, key, meta_handle.cache_handle_, @@ -539,6 +548,7 @@ int ObStorageMetaCache::prefetch( } int ObStorageMetaCache::get_meta_and_bypass_cache( + storage_io::BlockOwner &block_file, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, common::ObSafeArenaAllocator &allocator, @@ -556,7 +566,7 @@ int ObStorageMetaCache::get_meta_and_bypass_cache( ret = OB_ALLOCATE_MEMORY_FAILED; STORAGE_LOG(WARN, "allocate callback memory failed", K(ret)); } else { - callback = new (buf) ObStorageMetaIOCallback(&io_allocator, + callback = new (buf) ObStorageMetaIOCallback(block_file, &io_allocator, type, key, handle.cache_handle_, @@ -588,7 +598,7 @@ int ObStorageMetaCache::read_io( read_info.io_desc_.set_mode(ObIOMode::READ); read_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000L; handle.phy_addr_ = meta_addr; - if (OB_FAIL(ObObjectReaderWriter::async_read(read_info, handle.io_handle_, std::move(owner)))) { + if (OB_FAIL(ObObjectReaderWriter::async_read(callback.block_file_, read_info, handle.io_handle_, std::move(owner)))) { } } return ret; diff --git a/src/storage/meta_mem/ob_storage_meta_cache.h b/src/storage/meta_mem/ob_storage_meta_cache.h index 0b5e7a554e..4136549564 100644 --- a/src/storage/meta_mem/ob_storage_meta_cache.h +++ b/src/storage/meta_mem/ob_storage_meta_cache.h @@ -87,12 +87,14 @@ class ObStorageMetaValue final : public common::ObIKVCacheValue obj_ = nullptr; } static int process_sstable( + storage_io::BlockOwner &block_file, ObStorageMetaValueHandle &handle, const ObStorageMetaKey &key, const char *buf, const int64_t size, const ObTablet *tablet); static int process_table_store( + storage_io::BlockOwner &block_file, ObStorageMetaValueHandle &handle, const ObStorageMetaKey &key, const char *buf, @@ -101,12 +103,14 @@ class ObStorageMetaValue final : public common::ObIKVCacheValue TO_STRING_KV(K_(type), KP_(obj)); public: typedef int (*StorageMetaProcessor)( + storage_io::BlockOwner &, ObStorageMetaValueHandle &, const ObStorageMetaKey &, const char*, const int64_t, const ObTablet *); typedef int (*StorageMetaBypassProcessor)( + storage_io::BlockOwner &, const MetaType, common::ObSafeArenaAllocator &, ObStorageMetaValueHandle &, @@ -117,6 +121,7 @@ class ObStorageMetaValue final : public common::ObIKVCacheValue private: template static int bypass_process_storage_meta( + storage_io::BlockOwner &block_file, const MetaType type, common::ObSafeArenaAllocator &allocator, ObStorageMetaValueHandle &handle, @@ -198,16 +203,19 @@ class ObStorageMetaCache final int init(const char *cache_name); void destory(); int get_meta( + storage_io::BlockOwner &block_file, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, ObStorageMetaHandle &meta_handle, const ObTablet *tablet); int bypass_get_meta( + storage_io::BlockOwner &block_file, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, common::ObSafeArenaAllocator &allocator, ObStorageMetaHandle &meta_handle); int batch_get_meta_and_bypass_cache( + storage_io::BlockOwner &block_file, const common::ObIArray &meta_types, const common::ObIArray &keys, common::ObSafeArenaAllocator &allocator, @@ -217,6 +225,7 @@ class ObStorageMetaCache final { public: ObStorageMetaIOCallback( + storage_io::BlockOwner &block_file, common::ObIAllocator *io_allocator, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, @@ -235,6 +244,7 @@ class ObStorageMetaCache final private: friend class ObStorageMetaCache; + storage_io::BlockOwner &block_file_; ObStorageMetaValue::MetaType meta_type_; ObStorageMetaKey key_; ObStorageMetaValueHandle handle_; @@ -243,11 +253,13 @@ class ObStorageMetaCache final }; private: int prefetch( + storage_io::BlockOwner &block_file, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, ObStorageMetaHandle &meta_handle, const ObTablet *tablet); int get_meta_and_bypass_cache( + storage_io::BlockOwner &block_file, const ObStorageMetaValue::MetaType type, const ObStorageMetaKey &key, common::ObSafeArenaAllocator &allocator, @@ -262,6 +274,7 @@ class ObStorageMetaCache final template int ObStorageMetaValue::bypass_process_storage_meta( + storage_io::BlockOwner &block_file, const MetaType type, common::ObSafeArenaAllocator &allocator, ObStorageMetaValueHandle &handle, @@ -272,6 +285,7 @@ int ObStorageMetaValue::bypass_process_storage_meta( ObArenaAllocator tmp_allocator(common::ObMemAttr("ProcMetaVaule")); int64_t pos = 0; T t; + t.bind_block_file(block_file); char *buffer = nullptr; ObTimeGuard time_guard("bypass_process", 10_ms); if (OB_ISNULL(buf) || OB_UNLIKELY(size <= 0 || !handle.is_valid())) { diff --git a/src/storage/meta_mem/ob_storage_meta_mem_mgr.cpp b/src/storage/meta_mem/ob_storage_meta_mem_mgr.cpp index ee6d75eeaf..81a5ebffde 100644 --- a/src/storage/meta_mem/ob_storage_meta_mem_mgr.cpp +++ b/src/storage/meta_mem/ob_storage_meta_mem_mgr.cpp @@ -148,12 +148,13 @@ int ObStorageMetaMemMgr::TabletGCQueue::push(ObTablet *tablet) return ret; } -ObStorageMetaMemMgr::ObStorageMetaMemMgr() +ObStorageMetaMemMgr::ObStorageMetaMemMgr(storage_io::BlockOwner &block_file) : wash_lock_(common::ObLatchIds::STORAGE_META_MEM_MGR_LOCK), wash_func_(*this), bucket_lock_(), - full_tablet_creator_(), - tablet_map_(), + block_file_(block_file), + full_tablet_creator_(*this), + tablet_map_(*this), flying_tablet_map_(FLYING_TABLET_THRESHOLD), external_tablet_cnt_map_(), gc_timer_(), @@ -186,12 +187,13 @@ ObStorageMetaMemMgr::~ObStorageMetaMemMgr() destroy(); } -int ObStorageMetaMemMgr::server_module_new(ObStorageMetaMemMgr *&meta_mem_mgr) +int ObStorageMetaMemMgr::server_module_new( + storage_io::BlockOwner &block_file, ObStorageMetaMemMgr *&meta_mem_mgr) { int ret = OB_SUCCESS; - meta_mem_mgr = OB_NEW(ObStorageMetaMemMgr, ObMemAttr("MetaMemMgr")); + meta_mem_mgr = OB_NEW(ObStorageMetaMemMgr, ObMemAttr("MetaMemMgr"), block_file); if (OB_ISNULL(meta_mem_mgr)) { ret = OB_ALLOCATE_MEMORY_FAILED; } @@ -710,7 +712,6 @@ int ObStorageMetaMemMgr::gc_tablets_in_queue(bool &all_tablet_cleaned) void *ObStorageMetaMemMgr::release_tablet(ObTablet *tablet, const bool return_buf_ptr_after_release) { void *free_obj = nullptr; - tablet->dec_macro_ref_cnt(); ObIAllocator *allocator = tablet->get_allocator(); if (OB_ISNULL(allocator)) { if (return_buf_ptr_after_release) { @@ -1113,6 +1114,7 @@ int ObStorageMetaMemMgr::create_tmp_tablet( STORAGE_LOG(WARN, "fail to allocate memory", K(ret), KP(buf)); } else { tablet_handle.set_obj(new (buf) ObTablet(), &allocator, this); + tablet_handle.get_obj()->bind_block_file(block_file_); tablet_handle.set_wash_priority(priority); tablet_handle.get_obj()->set_allocator(&allocator); tablet_handle.disallow_copy_and_assign(); @@ -1190,6 +1192,7 @@ int ObStorageMetaMemMgr::acquire_tablet( ret = OB_ERR_UNEXPECTED; } else { ObMetaObjBufferHelper::new_meta_obj(buf, meta_obj.ptr_); + meta_obj.ptr_->bind_block_file(block_file_); tablet_handle.set_obj(meta_obj); SpinWLockGuard guard(wash_lock_); if (OB_UNLIKELY(!header->add_last(static_cast(buf)))) { @@ -1219,6 +1222,7 @@ int ObStorageMetaMemMgr::acquire_tablet(ObIStorageMetaObjPool *pool, ObTablet *& ret = OB_ERR_UNEXPECTED; } else { ObMetaObjBufferHelper::new_meta_obj(buf, tablet); + tablet->bind_block_file(block_file_); SpinWLockGuard guard(wash_lock_); if (OB_UNLIKELY(!header->add_last(static_cast(buf)))) { ret = OB_ERR_UNEXPECTED; @@ -1246,6 +1250,7 @@ int ObStorageMetaMemMgr::acquire_tmp_tablet( STORAGE_LOG(WARN, "fail to allocate memory", K(ret), KP(buf)); } else { tablet_handle.set_obj(new (buf) ObTablet(), &allocator, this); + tablet_handle.get_obj()->bind_block_file(block_file_); tablet_handle.set_wash_priority(priority); tablet_handle.get_obj()->set_allocator(&allocator); tablet_handle.disallow_copy_and_assign(); @@ -1712,7 +1717,8 @@ int ObStorageMetaMemMgr::compare_and_swap_tablet( const ObMetaDiskAddr &old_addr, const ObMetaDiskAddr &new_addr, const ObTabletPoolType &pool_type, - const bool set_pool /* whether to set tablet pool */) + const bool set_pool, + const std::shared_ptr &block_group) { int ret = OB_SUCCESS; bool is_exist = false; @@ -1742,7 +1748,8 @@ int ObStorageMetaMemMgr::compare_and_swap_tablet( old_addr, new_addr, set_pool, - pool))) { + pool, + block_group))) { } } LOG_DEBUG("compare and swap object", K(ret), K(old_addr), K(new_addr), K(lbt())); diff --git a/src/storage/meta_mem/ob_storage_meta_mem_mgr.h b/src/storage/meta_mem/ob_storage_meta_mem_mgr.h index 277295e5f6..e449f6bcf2 100644 --- a/src/storage/meta_mem/ob_storage_meta_mem_mgr.h +++ b/src/storage/meta_mem/ob_storage_meta_mem_mgr.h @@ -180,10 +180,11 @@ class ObStorageMetaMemMgr final static const int64_t DEFAULT_TABLET_CNT_PER_GB = 20000; private: - explicit ObStorageMetaMemMgr(); + explicit ObStorageMetaMemMgr(storage_io::BlockOwner &block_file); public: ~ObStorageMetaMemMgr(); - static int server_module_new(ObStorageMetaMemMgr *&meta_mem_mgr); + static int server_module_new(storage_io::BlockOwner &block_file, ObStorageMetaMemMgr *&meta_mem_mgr); + storage_io::BlockOwner &block_file() const { return block_file_; } int init(); int start(); @@ -269,8 +270,9 @@ class ObStorageMetaMemMgr final const ObTabletMapKey &key, const ObMetaDiskAddr &old_addr, const ObMetaDiskAddr &new_addr, - const ObTabletPoolType &pool_type = ObTabletPoolType::TP_MAX, - const bool set_pool = false /* whether to set tablet pool */); + const ObTabletPoolType &pool_type, + const bool set_pool, + const std::shared_ptr &block_group); int compare_and_swap_tablet( const ObTabletMapKey &key, const ObTabletHandle &old_handle, @@ -472,6 +474,7 @@ class ObStorageMetaMemMgr final common::SpinRWLock wash_lock_; TryWashTabletFunc wash_func_; ObBucketLock bucket_lock_; + storage_io::BlockOwner &block_file_; ObFullTabletCreator full_tablet_creator_; ObTabletPointerMap tablet_map_; ObFlyingTabletPointerMap flying_tablet_map_; diff --git a/src/storage/meta_mem/ob_tablet_handle.cpp b/src/storage/meta_mem/ob_tablet_handle.cpp index 0e4f94905a..2682d16b4d 100644 --- a/src/storage/meta_mem/ob_tablet_handle.cpp +++ b/src/storage/meta_mem/ob_tablet_handle.cpp @@ -98,7 +98,6 @@ void ObTabletHandle::reset() ob_usleep(1000 * 1000); ob_abort(); } - obj_->dec_macro_ref_cnt(); obj_->~ObTablet(); allocator_->free(obj_); } else if (OB_FAIL(t3m_->push_tablet_into_gc_queue(obj_))) { diff --git a/src/storage/meta_mem/ob_tablet_pointer.cpp b/src/storage/meta_mem/ob_tablet_pointer.cpp index 78cb069687..ef43f216af 100644 --- a/src/storage/meta_mem/ob_tablet_pointer.cpp +++ b/src/storage/meta_mem/ob_tablet_pointer.cpp @@ -45,7 +45,7 @@ ObTabletPointer::ObTabletPointer() attr_() { #if defined(__x86_64__) - static_assert(sizeof(ObTabletPointer) == 320, "The size of ObTabletPointer will affect the meta memory manager, and the necessity of adding new fields needs to be considered."); + static_assert(sizeof(ObTabletPointer) == 328, "The size of ObTabletPointer will affect the meta memory manager, and the necessity of adding new fields needs to be considered."); #endif } @@ -84,6 +84,7 @@ void ObTabletPointer::reset() old_version_chain_ = nullptr; reset_obj(); phy_addr_.reset(); + block_group_.reset(); ls_ = nullptr; flying_ = false; } @@ -336,6 +337,7 @@ int ObTabletPointer::deep_copy(char *buf, const int64_t buf_len, ObTabletPointer } else { ObTabletPointer *pvalue = new (buf) ObTabletPointer(); pvalue->phy_addr_ = phy_addr_; + pvalue->block_group_ = block_group_; pvalue->obj_.pool_ = obj_.pool_; pvalue->obj_.ptr_ = obj_.ptr_; pvalue->obj_.allocator_ = obj_.allocator_; diff --git a/src/storage/meta_mem/ob_tablet_pointer.h b/src/storage/meta_mem/ob_tablet_pointer.h index 2582be13fc..940103d329 100644 --- a/src/storage/meta_mem/ob_tablet_pointer.h +++ b/src/storage/meta_mem/ob_tablet_pointer.h @@ -17,6 +17,7 @@ #ifndef OCEANBASE_STORAGE_OB_TABLET_POINTER #define OCEANBASE_STORAGE_OB_TABLET_POINTER +#include #include "lib/lock/ob_mutex.h" #include "storage/meta_mem/ob_meta_obj_struct.h" #include "storage/multi_data_source/runtime_utility/mds_lock.h" @@ -32,6 +33,7 @@ namespace storage { class ObLS; class ObTablet; +class TabletBlockGroup; class ObTabletDDLKvMgr; struct ObTabletResidentInfo; typedef ObMetaObjGuard ObDDLKvMgrHandle; @@ -171,8 +173,8 @@ class ObTabletPointer final mds::ObMdsTableHandler mds_table_handler_;// 48B ObTablet *old_version_chain_; // 8B ObTabletAttr attr_; // 32B // protected by rw lock of tablet_map_ - int64_t auto_part_size_; // 8B - DISALLOW_COPY_AND_ASSIGN(ObTabletPointer); // 344B, 360B with ENABLE_OBJ_LEAK_CHECK + std::shared_ptr block_group_; + DISALLOW_COPY_AND_ASSIGN(ObTabletPointer); }; struct ObTabletResidentInfo final diff --git a/src/storage/meta_mem/ob_tablet_pointer_map.cpp b/src/storage/meta_mem/ob_tablet_pointer_map.cpp index 02741dd642..3ce967cbf0 100644 --- a/src/storage/meta_mem/ob_tablet_pointer_map.cpp +++ b/src/storage/meta_mem/ob_tablet_pointer_map.cpp @@ -25,8 +25,8 @@ using namespace blocksstable; namespace storage { -ObTabletPointerMap::ObTabletPointerMap() - : ObResourceMap(), max_count_(0) +ObTabletPointerMap::ObTabletPointerMap(ObStorageMetaMemMgr &meta_mem_mgr) + : ObResourceMap(), meta_mem_mgr_(meta_mem_mgr), max_count_(0) { } @@ -392,6 +392,7 @@ int ObTabletPointerMap::load_meta_obj( } else if (OB_FAIL(t->assign_pointer_handle(tmp_ptr_hdl))) { } else { t->tablet_addr_ = load_addr; + t->block_group_ = meta_pointer->block_group_; if (OB_FAIL(meta_pointer->deserialize(allocator, buf, buf_len, t))) { } } @@ -462,6 +463,7 @@ int ObTabletPointerMap::load_meta_obj( } else if (OB_FAIL(t->assign_pointer_handle(tmp_ptr_hdl))) { } else { t->tablet_addr_ = load_addr; + t->block_group_ = meta_pointer->block_group_; if (OB_FAIL(meta_pointer->deserialize(buf, buf_len, t))) { } else if (OB_FAIL(t->get_updating_tablet_pointer_param(update_pointer_param))) { } @@ -524,12 +526,12 @@ int ObTabletPointerMap::get_meta_obj_with_external_memory( } else { bool need_free_obj = false; ObTablet *t = new (buf) ObTablet(true /*is_external_tablet*/); + t->bind_block_file(meta_mem_mgr_.block_file()); do { t->reset(); if (CLICK_FAIL(load_meta_obj(key, t_ptr, allocator, disk_addr, t))) { STORAGE_LOG(WARN, "load obj from disk fail", K(ret), K(key), KPC(t_ptr), K(lbt())); } else { - ObStorageMetaMemMgr *t3m = ::oceanbase::share::server_service<::oceanbase::storage::ObStorageMetaMemMgr>(); ObTabletPointerHandle tmp_ptr_hdl(*this); common::ObBucketHashWLockGuard lock_guard(ResourceMap::bucket_lock_, hash_val); // some other thread finish loading @@ -558,17 +560,14 @@ int ObTabletPointerMap::get_meta_obj_with_external_memory( } } else if (CLICK_FAIL(t->deserialize_post_work(allocator))) { STORAGE_LOG(WARN, "fail to deserialize post work", K(ret), KP(t)); - } else if (CLICK_FAIL(t3m->inc_external_tablet_cnt(t->get_tablet_id().id()))) { + } else if (CLICK_FAIL(meta_mem_mgr_.inc_external_tablet_cnt(t->get_tablet_id().id()))) { // TODO FEIDU t->pointer_hdl_.reset(); (external tablet should not hold tablet_pointer) // !CAUTION: t3m->inc_external_tablet_cnt must be the last step which can modify ret; or, we have to dec_external_tablet_cnt in the failure process STORAGE_LOG(WARN, "fail to inc external tablet cnt", K(ret), KP(t), KPC(t)); } else { - guard.set_obj(t, &allocator, t3m); + guard.set_obj(t, &allocator, &meta_mem_mgr_); } } // write lock end - if ((CLICK_FAIL(ret) && OB_NOT_NULL(t)) || need_free_obj) { - t->dec_macro_ref_cnt(); - } } while (OB_ITEM_NOT_MATCH == ret); if ((CLICK_FAIL(ret) && OB_NOT_NULL(t)) || need_free_obj) { t->~ObTablet(); @@ -683,6 +682,7 @@ int ObTabletPointerMap::compare_and_swap_addr_and_object( if (OB_SUCC(ret)) { t_ptr->set_addr_with_reset_obj(new_addr); t_ptr->set_obj(new_guard); + t_ptr->block_group_ = new_addr.is_block() ? new_guard.get_obj()->block_group_ : nullptr; } } } @@ -695,7 +695,8 @@ int ObTabletPointerMap::compare_and_swap_address_without_object( const ObMetaDiskAddr &old_addr, const ObMetaDiskAddr &new_addr, const bool set_pool /* whether to set pool */, - ObIStorageMetaObjPool *pool) + ObIStorageMetaObjPool *pool, + const std::shared_ptr &block_group) { int ret = common::OB_SUCCESS; uint64_t hash_val = 0; @@ -720,6 +721,7 @@ int ObTabletPointerMap::compare_and_swap_address_without_object( STORAGE_LOG(WARN, "old address has changed, need to get again", K(ret), KPC(t_ptr), K(old_addr)); } else { t_ptr->set_addr_with_reset_obj(new_addr); + t_ptr->block_group_ = block_group; if (set_pool) { t_ptr->set_obj_pool(*pool); } diff --git a/src/storage/meta_mem/ob_tablet_pointer_map.h b/src/storage/meta_mem/ob_tablet_pointer_map.h index a60fb5dde8..72db0ce288 100644 --- a/src/storage/meta_mem/ob_tablet_pointer_map.h +++ b/src/storage/meta_mem/ob_tablet_pointer_map.h @@ -41,11 +41,13 @@ struct ObUpdateTabletPointerParam final ObTabletAttr tablet_attr_; }; +class ObStorageMetaMemMgr; + class ObTabletPointerMap : public ObResourceMap { public: typedef ObResourceMap ResourceMap; - ObTabletPointerMap(); + explicit ObTabletPointerMap(ObStorageMetaMemMgr &meta_mem_mgr); int set(const ObTabletMapKey &key, ObTabletPointer &ptr); // overwrite int erase(const ObTabletMapKey &key, ObMetaObjGuard &guard); int exist(const ObTabletMapKey &key, bool &is_exist); @@ -73,7 +75,8 @@ class ObTabletPointerMap : public ObResourceMap const ObMetaDiskAddr &old_addr, const ObMetaDiskAddr &new_addr, const bool set_pool /* whether to set pool */, - ObIStorageMetaObjPool *pool); + ObIStorageMetaObjPool *pool, + const std::shared_ptr &block_group); template int for_each_value_store(Operator &op); int wash_meta_obj(const ObTabletMapKey &key, ObMetaObjGuard &guard, void *&free_obj); int64_t count() const { return ResourceMap::map_.size(); } @@ -114,10 +117,8 @@ class ObTabletPointerMap : public ObResourceMap bool &is_in_memory); int inner_erase(const ObTabletMapKey &key); -public: - using ObResourceMap::ObResourceMap; - private: + ObStorageMetaMemMgr &meta_mem_mgr_; int64_t max_count_; }; diff --git a/src/storage/meta_store/ob_local_storage_meta_service.cpp b/src/storage/meta_store/ob_local_storage_meta_service.cpp index 37ab340e64..5c4b8e4812 100644 --- a/src/storage/meta_store/ob_local_storage_meta_service.cpp +++ b/src/storage/meta_store/ob_local_storage_meta_service.cpp @@ -24,20 +24,21 @@ namespace oceanbase namespace storage { -int ObLocalStorageMetaService::server_module_init(ObLocalStorageMetaService *&meta_service) +int ObLocalStorageMetaService::server_module_init(ObLocalStorageMetaService *&meta_service, storage_io::BlockOwner &blocks) { - return meta_service->init(); + return meta_service->init(blocks); } -int ObLocalStorageMetaService::init() +int ObLocalStorageMetaService::init(storage_io::BlockOwner &blocks) { int ret = OB_SUCCESS; if (OB_UNLIKELY(is_inited_)) { ret = OB_INIT_TWICE; - } else if (OB_FAIL(object_rwriter_.init())) { - } else if (OB_FAIL(object_raw_rwriter_.init())) { + } else if (OB_FAIL(object_rwriter_.init(blocks))) { + } else if (OB_FAIL(object_raw_rwriter_.init(blocks))) { } else { + blocks_ = &blocks; is_inited_ = true; } return ret; @@ -48,6 +49,7 @@ void ObLocalStorageMetaService::destroy() object_rwriter_.reset(); object_raw_rwriter_.reset(); + blocks_ = nullptr; is_inited_ = false; } @@ -65,7 +67,9 @@ int ObLocalStorageMetaService::read_from_disk( ObObjectReadInfo read_info; read_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000; read_info.addr_ = addr; - if (OB_FAIL(ObObjectReaderWriter::async_read(read_info, read_handle))) { + if (IS_NOT_INIT) { + ret = OB_NOT_INIT; + } else if (OB_FAIL(ObObjectReaderWriter::async_read(*blocks_, read_info, read_handle))) { } else if (OB_FAIL(read_handle.wait())) { } else if (OB_FAIL(read_handle.get_data(allocator, buf, buf_len))) { } diff --git a/src/storage/meta_store/ob_local_storage_meta_service.h b/src/storage/meta_store/ob_local_storage_meta_service.h index 3361d5bae6..59e5766e20 100644 --- a/src/storage/meta_store/ob_local_storage_meta_service.h +++ b/src/storage/meta_store/ob_local_storage_meta_service.h @@ -31,8 +31,8 @@ class ObLocalStorageMetaService ObLocalStorageMetaService(const ObLocalStorageMetaService &) = delete; ObLocalStorageMetaService &operator=(const ObLocalStorageMetaService &) = delete; - static int server_module_init(ObLocalStorageMetaService *&meta_service); - int init(); + static int server_module_init(ObLocalStorageMetaService *&meta_service, storage_io::BlockOwner &blocks); + int init(storage_io::BlockOwner &blocks); void destroy(); int read_from_disk( const ObMetaDiskAddr &addr, @@ -43,6 +43,7 @@ class ObLocalStorageMetaService ObObjectReaderWriter &get_object_raw_reader_writer() { return object_raw_rwriter_; } private: + storage_io::BlockOwner *blocks_ = nullptr; bool is_inited_ = false; ObObjectReaderWriter object_rwriter_; ObObjectReaderWriter object_raw_rwriter_; diff --git a/src/storage/meta_store/storage_meta_service.cpp b/src/storage/meta_store/storage_meta_service.cpp index d426c7394d..bd457f6260 100644 --- a/src/storage/meta_store/storage_meta_service.cpp +++ b/src/storage/meta_store/storage_meta_service.cpp @@ -23,9 +23,10 @@ #include "storage/meta_store/ob_server_runtime_meta.h" #include "storage/meta_store/tablet_loader.h" #include "storage/ob_file_system_router.h" -#include "storage/blocksstable/ob_block_manager.h" +#include "share/io_request.h" #include "storage/tx_storage/ob_ls_service.h" #include "storage/ls/ob_ls.h" +#include "storage/tablet/ob_tablet.h" #include "lib/checksum/ob_crc64.h" namespace oceanbase { namespace storage { @@ -75,7 +76,8 @@ StorageMetaService &StorageMetaService::get_instance() return service; } -int StorageMetaService::init(ObIServerRuntime &runtime, LocalStore &store) +int StorageMetaService::init(ObIServerRuntime &runtime, LocalStore &store, + storage_io::BlockOwner &blocks) { int ret = OB_SUCCESS; if (store_ != nullptr) { @@ -95,6 +97,7 @@ int StorageMetaService::init(ObIServerRuntime &runtime, LocalStore &store) if (OB_SUCC(ret)) { store_ = &store; runtime_ = &runtime; + blocks_ = &blocks; } } return ret; @@ -122,8 +125,13 @@ int StorageMetaService::start(bool bootstrap) void StorageMetaService::destroy() { stop(); + for (const auto &entry : tablet_roots_) { + ObTablet::set_group_published(entry.second, false); + } + tablet_roots_.clear(); store_ = nullptr; runtime_ = nullptr; + blocks_ = nullptr; need_reserved_ = false; } @@ -208,16 +216,76 @@ int StorageMetaService::write_tablet(const ObTabletID &id, int64_t kind, const L .set(Kind, kind).set(Payload, payload))); } -int StorageMetaService::update_tablet(const ObTabletID &id, const ObMetaDiskAddr &addr) +// Tablet updates are serialized by the Tablet service across the local-store commit. +int StorageMetaService::stage_tablet_root(uint64_t id, bool &inserted) +{ + std::lock_guard lock(roots_mutex_); + try { + inserted = tablet_roots_.try_emplace(id).second; + } catch (const std::bad_alloc &) { + return OB_ALLOCATE_MEMORY_FAILED; + } + return OB_SUCCESS; +} + +void StorageMetaService::set_tablet_root(uint64_t id, const std::shared_ptr &group) +{ + std::shared_ptr previous; + { + std::lock_guard lock(roots_mutex_); + const auto pos = tablet_roots_.find(id); + if (pos == tablet_roots_.end()) { + abort_unless(!group); + } else if (pos->second != group) { + ObTablet::set_group_published(group, true); + ObTablet::set_group_published(pos->second, false); + previous = std::move(pos->second); + if (group) { + pos->second = group; + } else { + tablet_roots_.erase(pos); + } + } + } +} + +void StorageMetaService::discard_tablet_root(uint64_t id) +{ + std::lock_guard lock(roots_mutex_); + const auto pos = tablet_roots_.find(id); + abort_unless(pos != tablet_roots_.end() && !pos->second); + tablet_roots_.erase(pos); +} + +int StorageMetaService::register_recovered_tablet(const ObTablet &tablet) +{ + if (!tablet.block_group_) { return OB_SUCCESS; } + const uint64_t id = tablet.get_tablet_id().id(); + bool inserted = false; + const int ret = stage_tablet_root(id, inserted); + if (OB_SUCCESS == ret) { + set_tablet_root(id, tablet.block_group_); + } + return ret; +} + +int StorageMetaService::update_tablet(const ObTablet &tablet, const ObMetaDiskAddr &addr) { int ret = OB_SUCCESS; + const ObTabletID &id = tablet.get_tablet_id(); LocalValue payload; - if (!id.is_valid() || !addr.is_valid() || !addr.is_block()) { + bool inserted = false; + if (!id.is_valid() || !addr.is_block() || addr != tablet.get_tablet_addr() || !tablet.block_group_) { ret = OB_INVALID_ARGUMENT; } else if (OB_FAIL(encode_record(addr, payload))) { - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.fsync_block())) { + } else if (OB_FAIL(stage_tablet_root(id.id(), inserted))) { + } else if (OB_FAIL(common::convert_block_status(blocks_->sync_blocks()))) { + } else if (OB_FAIL(write_tablet(id, NORMAL_TABLET, payload))) { } else { - ret = write_tablet(id, NORMAL_TABLET, payload); + set_tablet_root(id.id(), tablet.block_group_); + } + if (OB_FAIL(ret) && inserted) { + discard_tablet_root(id.id()); } return ret; } @@ -231,8 +299,9 @@ int StorageMetaService::write_empty_shell_tablet(ObTablet *tablet, ObMetaDiskAdd } else if (OB_FAIL(encode_record(*tablet, payload))) { } else if (OB_FAIL(addr.set_local_addr(tablet->get_tablet_meta().tablet_id_.id(), payload.bytes.size(), ob_crc64(payload.bytes.data(), payload.bytes.size())))) { + } else if (OB_FAIL(write_tablet(tablet->get_tablet_meta().tablet_id_, EMPTY_TABLET, payload))) { } else { - ret = write_tablet(tablet->get_tablet_meta().tablet_id_, EMPTY_TABLET, payload); + set_tablet_root(tablet->get_tablet_meta().tablet_id_.id(), nullptr); } return ret; } @@ -245,9 +314,10 @@ int StorageMetaService::remove_tablet(const ObTabletID &id) ret = OB_NOT_INIT; } else if (!id.is_valid()) { ret = OB_INVALID_ARGUMENT; + } else if (OB_FAIL(check_commit(store_->execute(LocalRequest::erase(storage_tablet::schema()) + .eq(TabletId, static_cast(id.id())))))) { } else { - ret = check_commit(store_->execute(LocalRequest::erase(storage_tablet::schema()) - .eq(TabletId, static_cast(id.id())))); + set_tablet_root(id.id(), nullptr); } return ret; } @@ -285,6 +355,18 @@ int StorageMetaService::read_empty_shell(const ObMetaDiskAddr &addr, ObArenaAllo return ret; } +int StorageMetaService::finish_block_recovery() +{ + const int ret = common::convert_block_status(blocks_->finish_marking()); + storage_io::BlockStats stats{}; + if (ret == OB_SUCCESS && + common::convert_block_status(blocks_->block_stats(stats)) == OB_SUCCESS && + stats.reclamation_failures > 0) { + LOG_WARN("block reclamation failed during recovery", "failures", stats.reclamation_failures); + } + return ret; +} + int StorageMetaService::recover(bool bootstrap) { int ret = OB_SUCCESS; @@ -302,7 +384,7 @@ int StorageMetaService::recover(bool bootstrap) [](LocalRowReader &) { return OB_SUCCESS; }); if (OB_ENTRY_NOT_EXIST != found) { ret = OB_SUCCESS == found ? OB_STATE_NOT_MATCH : found; break; } } - if (OB_SUCC(ret)) { ret = OB_SERVER_BLOCK_MGR.first_mark_device(); } + if (OB_SUCC(ret)) { ret = finish_block_recovery(); } } else if (OB_SUCCESS == ret) { ret = OB_STATE_NOT_MATCH; } @@ -342,11 +424,11 @@ int StorageMetaService::recover(bool bootstrap) }); if (OB_ENTRY_NOT_EXIST == ret) { ret = OB_SUCCESS; } } - TabletLoader loader(tablets); + TabletLoader loader(tablets, *blocks_); ObLS *ls = nullptr; if (OB_FAIL(ret)) { } else if (OB_FAIL(loader.load(server_service()))) { - } else if (OB_FAIL(OB_SERVER_BLOCK_MGR.first_mark_device())) { + } else if (OB_FAIL(finish_block_recovery())) { } else if (OB_FAIL(server_service()->get_ls(ls))) { } else if (OB_FAIL(ls->finish_storage_meta_replay())) { } else if (OB_FAIL(server_service()->finish_ls_recovery())) { diff --git a/src/storage/meta_store/storage_meta_service.h b/src/storage/meta_store/storage_meta_service.h index 1cb10a2f38..c165260299 100644 --- a/src/storage/meta_store/storage_meta_service.h +++ b/src/storage/meta_store/storage_meta_service.h @@ -15,21 +15,27 @@ */ #pragma once +#include +#include +#include #include "share/storage/local_store.h" #include "share/resource/ob_server_runtime_config.h" #include "storage/meta_mem/ob_meta_obj_struct.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace storage { class ObIServerRuntime; class ObLSMeta; class ObTablet; +class TabletBlockGroup; // Process-owned recovery state; the LocalStore is supplied by Observer. class StorageMetaService { public: static StorageMetaService &get_instance(); - int init(ObIServerRuntime &runtime, share::LocalStore &store); + int init(ObIServerRuntime &runtime, share::LocalStore &store, storage_io::BlockOwner &blocks); int start(bool bootstrap); void stop() { ATOMIC_STORE(&is_started_, false); } void destroy(); @@ -38,7 +44,8 @@ class StorageMetaService int commit_bootstrap(); int write_resources(const share::ObServerRuntimeConfig &config); int update_ls_meta(const ObLSMeta &meta); - int update_tablet(const common::ObTabletID &id, const ObMetaDiskAddr &addr); + int update_tablet(const ObTablet &tablet, const ObMetaDiskAddr &addr); + int register_recovered_tablet(const ObTablet &tablet); int write_empty_shell_tablet(ObTablet *tablet, ObMetaDiskAddr &addr); int remove_tablet(const common::ObTabletID &id); int read_empty_shell(const ObMetaDiskAddr &addr, common::ObArenaAllocator &allocator, @@ -46,9 +53,16 @@ class StorageMetaService private: StorageMetaService() = default; int recover(bool bootstrap); + int finish_block_recovery(); int write_tablet(const common::ObTabletID &id, int64_t kind, const share::LocalValue &payload); static int check_commit(int ret); + int stage_tablet_root(uint64_t id, bool &inserted); + void set_tablet_root(uint64_t id, const std::shared_ptr &group); + void discard_tablet_root(uint64_t id); + std::mutex roots_mutex_; + std::map> tablet_roots_; share::LocalStore *store_ = nullptr; + storage_io::BlockOwner *blocks_ = nullptr; ObIServerRuntime *runtime_ = nullptr; bool is_started_ = false; bool need_reserved_ = false; diff --git a/src/storage/meta_store/tablet_loader.cpp b/src/storage/meta_store/tablet_loader.cpp index eb4c2a999d..824e31b9af 100644 --- a/src/storage/meta_store/tablet_loader.cpp +++ b/src/storage/meta_store/tablet_loader.cpp @@ -17,6 +17,9 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" +#include "storage/blocksstable/ob_block_sstable_struct.h" #include "tablet_loader.h" #include "share/rc/ob_server_runtime.h" #include "storage/tx_storage/ob_ls_service.h" @@ -114,8 +117,9 @@ bool TabletLoadItem::operator<(const TabletLoadItem &r) const } //============================= TabletLoader ==============================// -TabletLoader::TabletLoader(ObIArray &tablets) - : task_idx_(0), +TabletLoader::TabletLoader(ObIArray &tablets, storage_io::BlockOwner &blocks) + : blocks_(blocks), + task_idx_(0), inflight_task_cnt_(0), finished_tablet_cnt_(0), errcode_(OB_SUCCESS), @@ -301,7 +305,7 @@ int TabletLoader::load_aggregate_tablets(const ObIArray &range_ int ret = OB_SUCCESS; char *buf = nullptr; int64_t buf_len = 0; - const int64_t io_buf_size = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + const int64_t io_buf_size = OB_DEFAULT_MACRO_BLOCK_SIZE; for (int64_t i = 0; OB_SUCC(ret) && i < range_arr.count(); i++) { ObStorageObjectReadInfo read_info; ObStorageObjectHandle object_handle; @@ -312,7 +316,7 @@ int TabletLoader::load_aggregate_tablets(const ObIArray &range_ read_info.io_desc_.set_sys_module_id(ObIOModule::LINKED_MACRO_BLOCK_IO); read_info.macro_block_id_ = total_tablet_item_arr_[range_arr.at(i).first].addr_.block_id(); - if (OB_FAIL(ObObjectManager::read_object(read_info, object_handle))) { + if (OB_FAIL(object_handle.read(blocks_, read_info))) { } for (int64_t idx = range_arr.at(i).first; OB_SUCC(ret) && idx < range_arr.at(i).second; idx++) { const TabletLoadItem &item = total_tablet_item_arr_[idx]; diff --git a/src/storage/meta_store/tablet_loader.h b/src/storage/meta_store/tablet_loader.h index 4db6cd607a..9cab620329 100644 --- a/src/storage/meta_store/tablet_loader.h +++ b/src/storage/meta_store/tablet_loader.h @@ -21,6 +21,8 @@ #include "storage/meta_store/ob_startup_accel_task_handler.h" #include "storage/meta_mem/ob_meta_obj_struct.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { @@ -97,7 +99,7 @@ class TabletLoader { public: // The caller owns the array; load() waits for every task before returning. - explicit TabletLoader(common::ObIArray &tablets); + TabletLoader(common::ObIArray &tablets, storage_io::BlockOwner &blocks); int load(storage::ObStartupAccelTaskHandler* startup_accel_handler); int load_discrete_tablets(const ObIArray &range_arr); @@ -126,6 +128,7 @@ class TabletLoader static const int64_t AGGREGATE_CNT_THRESHOLD = 16; static const int64_t AGGREGATE_SIZE_THRESHOLD = 256 << 10; // 256K + storage_io::BlockOwner &blocks_; int64_t task_idx_; int64_t inflight_task_cnt_; int64_t finished_tablet_cnt_; diff --git a/src/storage/ob_bloom_filter_task.cpp b/src/storage/ob_bloom_filter_task.cpp index 54fbb8ef01..2c31f241de 100644 --- a/src/storage/ob_bloom_filter_task.cpp +++ b/src/storage/ob_bloom_filter_task.cpp @@ -37,17 +37,19 @@ using namespace share; * */ ObBloomFilterBuildTask::ObBloomFilterBuildTask( + storage_io::BlockOwner &blocks, const uint64_t table_id, const blocksstable::MacroBlockId ¯o_id, const int64_t prefix_len) : IObDedupTask(T_BLOOMFILTER), + blocks_(blocks), table_id_(table_id), macro_id_(macro_id), macro_handle_(), prefix_len_(prefix_len), allocator_(ObModIds::OB_BLOOM_FILTER) { - abort_unless(OB_SUCCESS == macro_handle_.set_macro_block_id(macro_id)); + abort_unless(OB_SUCCESS == macro_handle_.set_macro_block_id(blocks_, macro_id)); } ObBloomFilterBuildTask::~ObBloomFilterBuildTask() @@ -88,6 +90,7 @@ IObDedupTask *ObBloomFilterBuildTask::deep_copy(char *buffer, const int64_t buf_ ObBloomFilterBuildTask *task = NULL; if (NULL != buffer && buf_size >= get_deep_copy_size()) { task = new (buffer) ObBloomFilterBuildTask( + blocks_, table_id_, macro_id_, prefix_len_); @@ -145,7 +148,7 @@ int ObBloomFilterBuildTask::build_bloom_filter() read_info.io_timeout_ms_ = std::max(config::_data_storage_io_timeout() / 1000, DEFAULT_IO_WAIT_TIME_MS); if (OB_FAIL(ret)) { - } else if (OB_FAIL(ObObjectManager::read_object(read_info, macro_handle))) { + } else if (OB_FAIL(macro_handle.read(blocks_, read_info))) { } else if (OB_FAIL(macro_bare_iter->open( macro_handle.get_buffer(), macro_handle.get_data_size(), true /*check*/))) { } else if (OB_FAIL(macro_bare_iter->get_macro_block_header(macro_header))) { diff --git a/src/storage/ob_bloom_filter_task.h b/src/storage/ob_bloom_filter_task.h index e1641e12ad..e0a29cec0b 100644 --- a/src/storage/ob_bloom_filter_task.h +++ b/src/storage/ob_bloom_filter_task.h @@ -31,6 +31,7 @@ class ObBloomFilterBuildTask: public common::IObDedupTask { public: ObBloomFilterBuildTask( + storage_io::BlockOwner &blocks, const uint64_t table_id, const blocksstable::MacroBlockId ¯o_id, const int64_t prefix_len); @@ -44,6 +45,7 @@ class ObBloomFilterBuildTask: public common::IObDedupTask private: int build_bloom_filter(); + storage_io::BlockOwner &blocks_; uint64_t table_id_; blocksstable::MacroBlockId macro_id_; blocksstable::ObStorageObjectHandle macro_handle_; diff --git a/src/storage/ob_i_table.cpp b/src/storage/ob_i_table.cpp index cff83b893d..a82228074d 100644 --- a/src/storage/ob_i_table.cpp +++ b/src/storage/ob_i_table.cpp @@ -545,7 +545,7 @@ int ObTablesHandleArray::add_sstable(ObITable *table, const ObStorageMetaHandle ObSSTable *sstable = nullptr; ObStorageMetaValue::MetaType meta_type = ObStorageMetaValue::MetaType::SSTABLE; - if (OB_FAIL(meta_cache.get_meta(meta_type, meta_key, handle, nullptr))) { + if (OB_FAIL(meta_cache.get_meta(static_cast(table)->block_file(), meta_type, meta_key, handle, nullptr))) { } else if (OB_FAIL(handle.get_sstable(sstable))) { } else if (OB_FAIL(table_handle.set_sstable(sstable, handle))) { } diff --git a/src/storage/ob_micro_block_handle_mgr.h b/src/storage/ob_micro_block_handle_mgr.h index 2c1537e228..ce2ec8ee22 100644 --- a/src/storage/ob_micro_block_handle_mgr.h +++ b/src/storage/ob_micro_block_handle_mgr.h @@ -17,7 +17,8 @@ #ifndef OB_MICRO_BLOCK_HANDLE_MGR_H_ #define OB_MICRO_BLOCK_HANDLE_MGR_H_ -#include "blocksstable/ob_block_manager.h" +#include "storage/blocksstable/ob_storage_object_handle.h" +#include "storage/blocksstable/ob_storage_object_rw_info.h" #include "blocksstable/ob_block_sstable_struct.h" #include "blocksstable/ob_imicro_block_reader.h" #include "blocksstable/ob_macro_block_reader.h" @@ -56,7 +57,7 @@ struct ObMicroBlockDataHandle { blocksstable::ObMicroBlockInfo micro_info_; blocksstable::ObMicroBlockDesMeta des_meta_; blocksstable::ObMicroBlockBufferHandle cache_handle_; - blocksstable::ObMacroBlockHandle io_handle_; + blocksstable::ObStorageObjectHandle io_handle_; ObIAllocator *allocator_; blocksstable::ObMicroBlockData loaded_index_block_data_; bool is_loaded_index_block_; diff --git a/src/storage/ob_parallel_external_sort.h b/src/storage/ob_parallel_external_sort.h index c52698d0c7..1550bcb6fd 100644 --- a/src/storage/ob_parallel_external_sort.h +++ b/src/storage/ob_parallel_external_sort.h @@ -18,7 +18,6 @@ #define OCEANBASE_STORAGE_OB_PARALLEL_EXTERNAL_SORT_H_ #include "rust/config.h" -#include "blocksstable/ob_block_manager.h" #include "share/ob_define.h" #include "share/rc/ob_server_runtime.h" #include "lib/container/ob_array.h" @@ -223,14 +222,14 @@ int ObFragmentWriterV2::open(const int64_t buf_size, const int64_t expire_tim if (OB_UNLIKELY(is_inited_)) { ret = common::OB_INIT_TWICE; STORAGE_LOG(WARN, "ObFragmentWriter has already been inited", K(ret)); - } else if (buf_size (allocator_.alloc(align_buf_size)))) { ret = common::OB_ALLOCATE_MEMORY_FAILED; STORAGE_LOG(WARN, "fail to allocate buffer", K(ret), K(align_buf_size)); @@ -506,7 +505,7 @@ int ObFragmentReaderV2::init(const int64_t fd, const int64_t dir_id, const in dir_id_ = dir_id; is_first_prefetch_ = true; - buf_size_ = common::lower_align(buf_size,OB_STORAGE_OBJECT_MGR.get_macro_block_size()); + buf_size_ = common::lower_align(buf_size,OB_DEFAULT_MACRO_BLOCK_SIZE); is_inited_ = true; } } @@ -1742,7 +1741,7 @@ int ObExternalSort::init( const int64_t mem_limit, const int64_t file_buf_size, const int64_t expire_timestamp, Compare *compare) { int ret = common::OB_SUCCESS; - int64_t macro_block_size = OB_STORAGE_OBJECT_MGR.get_macro_block_size(); + int64_t macro_block_size = OB_DEFAULT_MACRO_BLOCK_SIZE; if (OB_UNLIKELY(is_inited_)) { ret = common::OB_INIT_TWICE; STORAGE_LOG(WARN, "ObExternalSort has already been inited", K(ret)); diff --git a/src/storage/ob_partition_range_spliter.cpp b/src/storage/ob_partition_range_spliter.cpp index 5b4b10bef3..58d009a656 100644 --- a/src/storage/ob_partition_range_spliter.cpp +++ b/src/storage/ob_partition_range_spliter.cpp @@ -372,7 +372,7 @@ int ObIndexBlockTreeTraverser::PathNodeCaches::get(const int64_t level, } if (OB_FAIL(ret)) { - } else if (OB_FAIL(prefetch(*micro_index_info, cache_node->micro_handle_))) { + } else if (OB_FAIL(prefetch(traverser.get_sstable()->block_file(), *micro_index_info, cache_node->micro_handle_))) { } else if (OB_FAIL(cache_node->micro_handle_.get_micro_block_data( nullptr, cache_node->micro_data_, micro_index_info->is_data_block()))) { } else if (!micro_index_info->is_data_block() @@ -390,7 +390,7 @@ int ObIndexBlockTreeTraverser::PathNodeCaches::get(const int64_t level, return ret; } -int ObIndexBlockTreeTraverser::PathNodeCaches::prefetch(const ObMicroIndexInfo µ_index_info, +int ObIndexBlockTreeTraverser::PathNodeCaches::prefetch(storage_io::BlockOwner &block_file, const ObMicroIndexInfo µ_index_info, ObMicroBlockDataHandle µ_handle) { int ret = OB_SUCCESS; @@ -398,6 +398,7 @@ int ObIndexBlockTreeTraverser::PathNodeCaches::prefetch(const ObMicroIndexInfo & bool found = false; micro_handle.reset(); micro_handle.allocator_ = &allocator_; + micro_handle.block_file_ = &block_file; ObMicroBlockCacheKey key(micro_index_info); ObIMicroBlockCache *cache @@ -419,7 +420,7 @@ int ObIndexBlockTreeTraverser::PathNodeCaches::prefetch(const ObMicroIndexInfo & if (OB_SUCC(ret) && !found) { if (OB_FAIL(micro_index_info.row_header_->fill_micro_des_meta(micro_handle.des_meta_))) { - } else if (OB_FAIL(cache->prefetch(micro_index_info.get_macro_id(), + } else if (OB_FAIL(cache->prefetch(block_file, micro_index_info.get_macro_id(), micro_index_info, /* use_cache */ true, micro_handle.io_handle_, diff --git a/src/storage/ob_partition_range_spliter.h b/src/storage/ob_partition_range_spliter.h index a3063c0080..f5d59ce923 100644 --- a/src/storage/ob_partition_range_spliter.h +++ b/src/storage/ob_partition_range_spliter.h @@ -190,7 +190,7 @@ class ObIndexBlockTreeTraverser CacheNode *&cache_node, bool &is_in_cache); - int prefetch(const ObMicroIndexInfo µ_index_info, ObMicroBlockDataHandle µ_handle); + int prefetch(storage_io::BlockOwner &block_file, const ObMicroIndexInfo µ_index_info, ObMicroBlockDataHandle µ_handle); private: ObArenaAllocator allocator_; diff --git a/src/storage/storage_header_inventory.bzl b/src/storage/storage_header_inventory.bzl index 169ccb83ef..510a5148de 100644 --- a/src/storage/storage_header_inventory.bzl +++ b/src/storage/storage_header_inventory.bzl @@ -12,7 +12,6 @@ STORAGE_PUBLIC_HEADER_ROOTS = [ "api/storage/vector/ob_i_vector_index_runtime.h", "blocksstable/index_block/ob_index_block_dual_meta_iterator.h", "blocksstable/index_block/ob_index_block_macro_iterator.h", - "blocksstable/ob_block_manager.h", "blocksstable/ob_block_sstable_struct.h", "blocksstable/ob_datum_range.h", "blocksstable/ob_datum_row.h", @@ -229,7 +228,6 @@ STORAGE_INTERFACE_CLOSURE_HEADERS = [ "blocksstable/ob_macro_block_checker.h", "blocksstable/ob_macro_block_common_header.h", "blocksstable/ob_macro_block_flusher.h", - "blocksstable/ob_macro_block_handle.h", "blocksstable/ob_macro_block_id.h", "blocksstable/ob_macro_block_meta.h", "blocksstable/ob_macro_block_reader.h", @@ -245,7 +243,6 @@ STORAGE_INTERFACE_CLOSURE_HEADERS = [ "blocksstable/ob_micro_block_reader_helper.h", "blocksstable/ob_micro_block_row_scanner.h", "blocksstable/ob_micro_block_writer.h", - "blocksstable/ob_object_manager.h", "blocksstable/ob_row_cache.h", "blocksstable/ob_row_queue.h", "blocksstable/ob_row_writer.h", diff --git a/src/storage/storage_source_inventory.bzl b/src/storage/storage_source_inventory.bzl index f473ff5fcf..4b8bae8cda 100644 --- a/src/storage/storage_source_inventory.bzl +++ b/src/storage/storage_source_inventory.bzl @@ -79,9 +79,7 @@ STORAGE_UNITY_GROUPS = [ srcs = [ "src/storage/blocksstable/ob_kvcache_pointer_swizzle.cpp", "src/storage/blocksstable/ob_kvcache_pre_warmer.cpp", - "src/storage/blocksstable/ob_block_manager.cpp", "src/storage/blocksstable/ob_macro_seq_generator.cpp", - "src/storage/blocksstable/ob_object_manager.cpp", "src/storage/blocksstable/ob_block_sstable_struct.cpp", "src/storage/blocksstable/ob_bloom_filter_cache.cpp", "src/storage/blocksstable/ob_data_buffer.cpp", @@ -94,7 +92,6 @@ STORAGE_UNITY_GROUPS = [ "src/storage/blocksstable/ob_macro_block_checker.cpp", "src/storage/blocksstable/ob_macro_block_common_header.cpp", "src/storage/blocksstable/ob_macro_block_flusher.cpp", - "src/storage/blocksstable/ob_macro_block_handle.cpp", "src/storage/blocksstable/ob_macro_block_id.cpp", "src/storage/blocksstable/ob_macro_block_meta_mgr.cpp", "src/storage/blocksstable/ob_macro_block_meta.cpp", diff --git a/src/storage/tablet/ob_full_tablet_creator.cpp b/src/storage/tablet/ob_full_tablet_creator.cpp index 99ab59a639..ccf128c6ea 100644 --- a/src/storage/tablet/ob_full_tablet_creator.cpp +++ b/src/storage/tablet/ob_full_tablet_creator.cpp @@ -15,7 +15,7 @@ */ #include "ob_full_tablet_creator.h" -#include "share/rc/ob_server_runtime.h" +#include "storage/meta_mem/ob_storage_meta_mem_mgr.h" #include "storage/tablet/ob_tablet.h" #define USING_LOG_PREFIX STORAGE @@ -24,8 +24,9 @@ namespace oceanbase { namespace storage { -ObFullTabletCreator::ObFullTabletCreator() - : is_inited_(false), +ObFullTabletCreator::ObFullTabletCreator(ObStorageMetaMemMgr &meta_mem_mgr) + : meta_mem_mgr_(meta_mem_mgr), + is_inited_(false), tiny_allocator_(), created_tablets_cnt_(0), mstx_mem_ctx_(nullptr) @@ -99,13 +100,13 @@ int ObFullTabletCreator::create_tablet(ObTabletHandle &tablet_handle) ret = OB_ALLOCATE_MEMORY_FAILED; } else if (OB_FAIL(mem_addr.set_mem_addr(0, sizeof(ObTablet)))) { } else { + tablet->bind_block_file(meta_mem_mgr_.block_file()); tablet->set_allocator(allocator); tablet->set_tablet_addr(mem_addr); ATOMIC_INC(&created_tablets_cnt_); } if (OB_SUCC(ret)) { - ObStorageMetaMemMgr *t3m = ::oceanbase::share::server_service<::oceanbase::storage::ObStorageMetaMemMgr>(); - tablet_handle.set_obj(tablet, allocator, t3m); + tablet_handle.set_obj(tablet, allocator, &meta_mem_mgr_); tablet_handle.set_wash_priority(WashTabletPriority::WTP_LOW); } else { if (OB_NOT_NULL(tablet)) { diff --git a/src/storage/tablet/ob_full_tablet_creator.h b/src/storage/tablet/ob_full_tablet_creator.h index 7f15bab565..9da3dc81da 100644 --- a/src/storage/tablet/ob_full_tablet_creator.h +++ b/src/storage/tablet/ob_full_tablet_creator.h @@ -33,10 +33,12 @@ class ObIAllocator; namespace storage { +class ObStorageMetaMemMgr; + class ObFullTabletCreator final { public: - ObFullTabletCreator(); + explicit ObFullTabletCreator(ObStorageMetaMemMgr &meta_mem_mgr); ~ObFullTabletCreator() = default; public: int init(); @@ -53,6 +55,7 @@ class ObFullTabletCreator final private: common::ObIAllocator &get_allocator() { return mstx_mem_ctx_->get_malloc_allocator(); } private: + ObStorageMetaMemMgr &meta_mem_mgr_; bool is_inited_; common::ObFIFOAllocator tiny_allocator_; int64_t created_tablets_cnt_; // tablets has been created diff --git a/src/storage/tablet/ob_table_store_util.cpp b/src/storage/tablet/ob_table_store_util.cpp index 93994c8434..aa5eb7556a 100644 --- a/src/storage/tablet/ob_table_store_util.cpp +++ b/src/storage/tablet/ob_table_store_util.cpp @@ -242,6 +242,7 @@ int ObSSTableArray::serialize(char *buf, const int64_t buf_len, int64_t &pos) co } int ObSSTableArray::deserialize( + storage_io::BlockOwner &block_file, ObArenaAllocator &allocator, const char *buf, const int64_t data_len, @@ -259,7 +260,7 @@ int ObSSTableArray::deserialize( ret = OB_ERR_UNEXPECTED; } if (OB_FAIL(ret) || cnt_ <= 0) { - } else if (OB_FAIL(inner_deserialize_tables(allocator, buf, data_len, pos))) { + } else if (OB_FAIL(inner_deserialize_tables(block_file, allocator, buf, data_len, pos))) { } if (OB_FAIL(ret)) { @@ -271,6 +272,7 @@ int ObSSTableArray::deserialize( } int ObSSTableArray::inner_deserialize_tables( + storage_io::BlockOwner &block_file, ObArenaAllocator &allocator, const char *buf, const int64_t data_len, @@ -287,7 +289,7 @@ int ObSSTableArray::inner_deserialize_tables( sstable_array_ = reinterpret_cast(tmp_buf); for (int64_t i = 0; OB_SUCC(ret) && i < cnt_; ++i) { - if (OB_FAIL(deserialize_table(allocator, buf, data_len, pos, sstable_array_[i]))) { + if (OB_FAIL(deserialize_table(block_file, allocator, buf, data_len, pos, sstable_array_[i]))) { } } } @@ -296,6 +298,7 @@ int ObSSTableArray::inner_deserialize_tables( template int ObSSTableArray::deserialize_table( + storage_io::BlockOwner &block_file, ObArenaAllocator &allocator, const char *buf, const int64_t data_len, @@ -309,6 +312,7 @@ int ObSSTableArray::deserialize_table( } else { T *table = nullptr; table = new (tmp_buf) T; + table->bind_block_file(block_file); if (OB_FAIL(table->deserialize(allocator, buf, data_len, pos))) { } else { sstable = table; @@ -452,201 +456,6 @@ int ObSSTableArray::get_table( return ret; } -int ObSSTableArray::inc_macro_ref(bool &is_success) const -{ - int ret = OB_SUCCESS; - is_success = false; - bool inc_data_success = false; - bool inc_meta_success = false; - if (OB_UNLIKELY(!is_valid())) { - ret = OB_NOT_INIT; - } else if (OB_FAIL(inc_data_ref_cnt(inc_data_success))) { - } else if (OB_FAIL(inc_meta_ref_cnt(inc_meta_success))) { - } - - if (OB_FAIL(ret)) { - if (inc_data_success) { - dec_data_ref_cnt(); - } - if (inc_meta_success) { - dec_meta_ref_cnt(); - } - } else { - is_success = true; - } - return ret; -} - -void ObSSTableArray::dec_macro_ref() const -{ - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!is_valid())) { - ret = OB_NOT_INIT; - } else { - dec_data_ref_cnt(); - dec_meta_ref_cnt(); - } -} - -int ObSSTableArray::inc_meta_ref_cnt(bool &inc_success) const -{ - int ret = OB_SUCCESS; - inc_success = false; - ObITable *table = nullptr; - int64_t sstable_cnt = 0; - ObMetaDiskAddr addr; - MacroBlockId macro_id; - int64_t offset = 0; - int64_t size = 0; - - for (int64_t i = 0; OB_SUCC(ret) && i < cnt_; i++) { - table = sstable_array_[i]; - if (OB_ISNULL(table) || OB_UNLIKELY(!table->is_sstable())) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("table is invalid", K(ret), KPC(table)); - } else { - ObSSTable *sstable = reinterpret_cast(table); - addr = sstable->get_addr(); - if (addr.is_memory()) { - // full/old tablet, skip increase - sstable_cnt++; - } else if (OB_UNLIKELY(!addr.is_block() || !addr.is_valid())) { - ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(addr.get_block_addr(macro_id, offset, size))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(macro_id))) { - } else { - sstable_cnt++; - } - } - } - - if (OB_FAIL(ret) && 0 != sstable_cnt) { - int tmp_ret = OB_SUCCESS; - for (int64_t i = 0; i < sstable_cnt; i++) { - table = sstable_array_[i]; - if (OB_ISNULL(table) || OB_UNLIKELY(!table->is_sstable())) { - tmp_ret = OB_ERR_UNEXPECTED; - LOG_ERROR("table is invalid", K(tmp_ret), KPC(table)); - } else { - ObSSTable *sstable = reinterpret_cast(table); - addr = sstable->get_addr(); - if (addr.is_memory()) { - // full/old tablet, skip increase - } else if (OB_UNLIKELY(!addr.is_block() || !addr.is_valid())) { - tmp_ret = OB_ERR_UNEXPECTED; - LOG_ERROR("addr is invalid", K(tmp_ret), K(addr)); - } else if (OB_TMP_FAIL(addr.get_block_addr(macro_id, offset, size))) { - } else if (OB_TMP_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } else { - } - } - } - } - - if (OB_SUCC(ret)) { - inc_success = true; - } - - LOG_DEBUG("the number of sstables that increase meta ref cnt", K(ret), K(sstable_cnt), K(lbt())); - - return ret; -} - -int ObSSTableArray::inc_data_ref_cnt(bool &inc_success) const -{ - int ret = OB_SUCCESS; - inc_success = false; - ObITable *table = nullptr; - int64_t sstable_cnt = 0; - - for (int64_t i = 0; OB_SUCC(ret) && i < cnt_; i++) { - bool inc_data_block_success = false; - table = sstable_array_[i]; - if (OB_ISNULL(table) || OB_UNLIKELY(!table->is_sstable())) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("table is invalid", K(ret), KPC(table)); - } else { - ObSSTable *sstable = reinterpret_cast(table); - if (OB_FAIL(sstable->inc_macro_ref(inc_data_block_success))) { - } else { - sstable_cnt++; - } - } - } - - if (OB_FAIL(ret) && 0 != sstable_cnt) { - int tmp_ret = OB_SUCCESS; - for (int64_t i = 0; i < sstable_cnt; i++) { - table = sstable_array_[i]; - if (OB_ISNULL(table) || OB_UNLIKELY(!table->is_sstable())) { - tmp_ret = OB_ERR_UNEXPECTED; - LOG_ERROR("table is invalid", K(tmp_ret), KPC(table)); - } else { - ObSSTable *sstable = reinterpret_cast(table); - sstable->dec_macro_ref(); - } - } - } - - if (OB_SUCC(ret)) { - inc_success = true; - } - - return ret; -} - -void ObSSTableArray::dec_meta_ref_cnt() const -{ - int ret = OB_SUCCESS; - ObITable *table = nullptr; - ObMetaDiskAddr addr; - MacroBlockId macro_id; - int64_t offset = 0; - int64_t size = 0; - int64_t sstable_cnt = 0; - - for (int64_t i = 0; i < cnt_; i++) { - table = sstable_array_[i]; - if (OB_ISNULL(table) || OB_UNLIKELY(!table->is_sstable())) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("table is invalid", K(ret), KPC(table)); - } else { - ObSSTable *sstable = reinterpret_cast(table); - addr = sstable->get_addr(); - if (addr.is_memory()) { - // full/old tablet, skip decrease - } else if (OB_UNLIKELY(!addr.is_block() || !addr.is_valid())) { - LOG_ERROR("addr is invalid", K(ret), K(addr)); - } else if (OB_FAIL(addr.get_block_addr(macro_id, offset, size))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } else { - sstable_cnt++; - } - } - } - - LOG_DEBUG("the number of sstables that decrease meta ref cnt", K(ret), K(sstable_cnt), K(lbt())); -} - -void ObSSTableArray::dec_data_ref_cnt() const -{ - int ret = OB_SUCCESS; - ObITable *table = nullptr; - int64_t sstable_cnt = 0; - - for (int64_t i = 0; i < cnt_; i++) { - table = sstable_array_[i]; - if (OB_ISNULL(table) || OB_UNLIKELY(!table->is_sstable())) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("table is invalid", K(ret), KPC(table)); - } else { - sstable_cnt++; - ObSSTable *sstable = reinterpret_cast(table); - sstable->dec_macro_ref(); - } - } -} - int ObMemtableArray::assign(ObMemtableArray &dst_array) const { int ret = OB_SUCCESS; @@ -1042,6 +851,7 @@ bool ObTableStoreUtil::check_intersect_by_scn_range(const ObITable &a, const ObI int ObCacheSSTableHelper::load_sstable( + storage_io::BlockOwner &block_file, const ObMetaDiskAddr &addr, ObStorageMetaHandle &handle) { @@ -1052,7 +862,7 @@ int ObCacheSSTableHelper::load_sstable( } else { ObStorageMetaCache &meta_cache = OB_STORE_CACHE.get_storage_meta_cache(); ObStorageMetaKey meta_key(addr); - if (OB_FAIL(meta_cache.get_meta(ObStorageMetaValue::MetaType::SSTABLE, meta_key, handle, nullptr))) { + if (OB_FAIL(meta_cache.get_meta(block_file, ObStorageMetaValue::MetaType::SSTABLE, meta_key, handle, nullptr))) { } } return ret; @@ -1069,7 +879,7 @@ int ObCacheSSTableHelper::load_sstable_on_demand( // sstable is already loaded, life time guaranteed by table store. loaded_sstable = &orig_sstable; loaded_sstable_handle = table_store_handle; - } else if (OB_FAIL(load_sstable(orig_sstable.get_addr(), loaded_sstable_handle))) { + } else if (OB_FAIL(load_sstable(orig_sstable.block_file(), orig_sstable.get_addr(), loaded_sstable_handle))) { } else if (OB_FAIL(loaded_sstable_handle.get_sstable(loaded_sstable))) { } return ret; @@ -1097,7 +907,7 @@ int ObCacheSSTableHelper::try_cache_local_sstable_meta( ret = OB_ERR_UNEXPECTED; } else if (array_sstable->is_loaded()) { // sstable is already loaded to memory - } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(array_sstable->get_addr(), sstable_handle))) { + } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(array_sstable->block_file(), array_sstable->get_addr(), sstable_handle))) { } else if (OB_FAIL(sstable_handle.get_sstable(loaded_sstable))) { } else if (OB_FAIL(ObCacheSSTableHelper::cache_local_sstable_meta( allocator, @@ -1214,7 +1024,7 @@ int ObCacheSSTableHelper::batch_cache_sstable_meta( ret = OB_ERR_UNEXPECTED; } else if (OB_UNLIKELY(0 == cache_keys.count())) { } else if (OB_FAIL(OB_STORE_CACHE.get_storage_meta_cache().batch_get_meta_and_bypass_cache( - meta_types, cache_keys, safe_allocator, cache_handles))) { + sstables.at(0)->block_file(), meta_types, cache_keys, safe_allocator, cache_handles))) { } else if (OB_FAIL(batch_cache_sstable_meta_(allocator, remain_size, sstables, cache_handles))) { } } diff --git a/src/storage/tablet/ob_table_store_util.h b/src/storage/tablet/ob_table_store_util.h index b76ce45d77..675c7b0405 100644 --- a/src/storage/tablet/ob_table_store_util.h +++ b/src/storage/tablet/ob_table_store_util.h @@ -86,6 +86,7 @@ class ObSSTableArray int64_t get_serialize_size() const; int serialize(char *buf, const int64_t buf_len, int64_t &pos) const; int deserialize( + storage_io::BlockOwner &block_file, ObArenaAllocator &allocator, const char *buf, const int64_t data_len, @@ -94,8 +95,6 @@ class ObSSTableArray blocksstable::ObSSTable *at(const int64_t pos) const; ObITable *get_boundary_table(const bool is_last) const; int get_table(const ObITable::TableKey &table_key, ObSSTableWrapper &wrapper) const; - int inc_macro_ref(bool &is_success) const; - void dec_macro_ref() const; OB_INLINE bool is_valid() const { @@ -106,22 +105,20 @@ class ObSSTableArray TO_STRING_KV(K_(cnt), KP_(sstable_array), K_(is_inited)); private: int get_all_tables(ObIArray &tables) const; - int inc_meta_ref_cnt(bool &inc_success) const; - int inc_data_ref_cnt(bool &inc_success) const; - void dec_meta_ref_cnt() const; - void dec_data_ref_cnt() const; int inner_init( ObArenaAllocator &allocator, const ObIArray &tables, const int64_t start_pos, const int64_t end_pos); int inner_deserialize_tables( + storage_io::BlockOwner &block_file, ObArenaAllocator &allocator, const char *buf, const int64_t data_len, int64_t &pos); template int deserialize_table( + storage_io::BlockOwner &block_file, ObArenaAllocator &allocator, const char *buf, const int64_t data_len, @@ -268,6 +265,7 @@ struct ObCacheSSTableHelper public: // Load sstable with @addr, loaded object lifetime guaranteed by @handle static int load_sstable( + storage_io::BlockOwner &block_file, const ObMetaDiskAddr &addr, ObStorageMetaHandle &handle); diff --git a/src/storage/tablet/ob_tablet.cpp b/src/storage/tablet/ob_tablet.cpp index 7f5ef76cf9..537ca0aff9 100644 --- a/src/storage/tablet/ob_tablet.cpp +++ b/src/storage/tablet/ob_tablet.cpp @@ -17,6 +17,7 @@ #define USING_LOG_PREFIX STORAGE #include "rust/config.h" +#include "share/io_request.h" #include "ob_tablet.h" #include "storage/tx/ob_ts_mgr.h" #include "share/rc/ob_server_runtime.h" @@ -47,6 +48,7 @@ #include "storage/tablet/ob_tablet_mds_table_mini_merger.h" #include "share/ob_tablet_local_checksum_operator.h" #include "share/ob_structured_event_logger.h" +#include namespace oceanbase { using namespace memtable; @@ -78,7 +80,7 @@ namespace storage char *io_buf = nullptr; \ int64_t buf_len = -1; \ int64_t io_pos = 0; \ - if (OB_FAIL(ObTabletObjLoadHelper::read_from_addr(io_allocator, meta_addr, io_buf, buf_len))) { \ + if (OB_FAIL(ObTabletObjLoadHelper::read_from_addr(block_file(), io_allocator, meta_addr, io_buf, buf_len))) { \ LOG_WARN("read table store failed", K(ret)); \ } else if (OB_FAIL(ObTabletObjLoadHelper::alloc_and_new(allocator, meta_ptr))) { \ LOG_WARN("alloc and new table store ptr failed", K(ret), K(buf_len), K(io_pos)); \ @@ -152,6 +154,72 @@ int ObTableStoreCache::init( return ret; } +class TabletBlockGroup final +{ +public: + TabletBlockGroup() : blocks_(storage_io::new_block_group()) {} + ~TabletBlockGroup() + { + if (counted_shared_ == 0) { + return; + } + auto *manager = server_service(); + if (manager != nullptr) { + for (size_t i = 0; i < counted_shared_; ++i) { + const auto &entry = shared_[i]; + const int ret = manager->free_block(entry.shared_macro_id_, entry.occupy_size_); + if (OB_SUCCESS != ret) { + LOG_ERROR_RET(ret, "failed to release shared block occupancy", K(entry)); + } + } + } + } + + int add_shared(const ObTabletBlockInfo &entry) + { + try { + shared_.emplace_back(entry.macro_id_, entry.occupy_size_); + } catch (const std::bad_alloc &) { + return OB_ALLOCATE_MEMORY_FAILED; + } + return OB_SUCCESS; + } + + int hold(const storage_io::BlockOwner &block_file, rust::Slice members) + { + int ret = convert_block_status(block_file.hold_blocks(members, *blocks_)); + if (OB_SUCC(ret) && !shared_.empty()) { + auto *manager = server_service(); + if (OB_ISNULL(manager)) { + ret = OB_ERR_UNEXPECTED; + } else { + while (OB_SUCC(ret) && counted_shared_ < shared_.size()) { + const auto &entry = shared_[counted_shared_]; + if (OB_FAIL(manager->add_block(entry.shared_macro_id_, entry.occupy_size_))) { + } else { + ++counted_shared_; + } + } + } + } + return ret; + } + + void set_published(bool published) { blocks_->set_published(published); } + +private: + rust::Box blocks_; + std::vector shared_; + size_t counted_shared_ = 0; +}; + +void ObTablet::set_group_published(const std::shared_ptr &group, bool published) +{ + if (group) { + group->set_published(published); + } +} + template (); + check_size(); #endif MEMSET(memtables_, 0x0, sizeof(memtables_)); } @@ -233,7 +301,7 @@ void ObTablet::reset() version_ = TABLET_PAYLOAD_VERSION; length_ = 0; next_tablet_ = nullptr; - hold_ref_cnt_ = false; + block_group_.reset(); is_inited_ = false; } @@ -298,7 +366,7 @@ int ObTablet::init_for_first_time_creation( if (OB_FAIL(ret)) { } else if (need_create_empty_major_sstable && OB_FAIL(ObTabletCreateDeleteHelper::create_empty_sstable( - allocator, *storage_schema_addr_.get_ptr(), tablet_id, snapshot_version, table_handle))) { + block_file(), allocator, *storage_schema_addr_.get_ptr(), tablet_id, snapshot_version, table_handle))) { } else { ALLOC_AND_INIT(allocator, table_store_addr_, (*this), static_cast(table_handle.get_table())); } @@ -311,7 +379,7 @@ int ObTablet::init_for_first_time_creation( } else if (OB_FAIL(build_read_info(allocator, nullptr /*tablet*/))) { } else if (OB_FAIL(init_aggregated_info(allocator, nullptr/* link_writer, tmp_tablet do no write */))) { } else if (FALSE_IT(set_initial_addr())) { - } else if (OB_FAIL(inner_inc_macro_ref_cnt())) { + } else if (OB_FAIL(hold_macro_blocks())) { } else { is_inited_ = true; LOG_INFO("succeeded to init tablet for first time creation", K(ret), K(*this)); @@ -369,8 +437,8 @@ int ObTablet::init_for_physical_restore( } else if (FALSE_IT(set_initial_addr())) { } else if (OB_FAIL(check_table_store_flag_match_with_table_store_(table_store_addr_.get_ptr()))) { LOG_WARN("restore tablet table store flag mismatch", K(ret), K(tablet_meta)); - } else if (OB_FAIL(inner_inc_macro_ref_cnt())) { - LOG_WARN("failed to increase restored tablet macro ref count", K(ret), K(tablet_meta)); + } else if (OB_FAIL(hold_macro_blocks())) { + LOG_WARN("failed to hold restored Tablet blocks", K(ret), K(tablet_meta)); } else { is_inited_ = true; LOG_INFO("initialized tablet for physical restore", K(tablet_meta)); @@ -451,7 +519,7 @@ int ObTablet::init_for_merge( } else if (OB_FAIL(init_aggregated_info(allocator, nullptr/* link_writer, tmp_tablet do no write */))) { } else if (FALSE_IT(set_initial_addr())) { } else if (OB_FAIL(check_table_store_flag_match_with_table_store_(table_store_addr_.get_ptr()))) { - } else if (OB_FAIL(inner_inc_macro_ref_cnt())) { + } else if (OB_FAIL(hold_macro_blocks())) { } else { if (old_tablet.get_tablet_meta().has_next_tablet_) { set_next_tablet_guard(old_tablet.next_tablet_guard_); @@ -519,7 +587,7 @@ int ObTablet::init_for_defragment( } else if (OB_FAIL(table_store_cache_.init(table_store_addr_.get_ptr()->get_major_sstables(), table_store_addr_.get_ptr()->get_minor_sstables()))) { } else if (OB_FAIL(check_table_store_flag_match_with_table_store_(table_store_addr_.get_ptr()))) { - } else if (OB_FAIL(inner_inc_macro_ref_cnt())) { + } else if (OB_FAIL(hold_macro_blocks())) { } else { if (old_tablet.get_tablet_meta().has_next_tablet_) { set_next_tablet_guard(old_tablet.next_tablet_guard_); @@ -590,7 +658,7 @@ int ObTablet::init_for_sstable_replace( } else if (OB_FAIL(init_aggregated_info(allocator, nullptr/* link_writer, tmp_tablet do no write */))) { } else if (FALSE_IT(set_initial_addr())) { } else if (OB_FAIL(check_table_store_flag_match_with_table_store_(table_store_addr_.get_ptr()))) { - } else if (OB_FAIL(inner_inc_macro_ref_cnt())) { + } else if (OB_FAIL(hold_macro_blocks())) { } else { if (old_tablet.get_tablet_meta().has_next_tablet_) { set_next_tablet_guard(old_tablet.next_tablet_guard_); @@ -633,7 +701,7 @@ int ObTablet::fetch_table_store(ObTabletMemberWrapper &wrapp ObStorageMetaHandle handle; ObStorageMetaKey meta_key(table_store_addr_.addr_); if (CLICK_FAIL(OB_STORE_CACHE.get_storage_meta_cache().get_meta( - ObStorageMetaValue::MetaType::TABLE_STORE, meta_key, handle, this))) { + block_file(), ObStorageMetaValue::MetaType::TABLE_STORE, meta_key, handle, this))) { } else if (CLICK_FAIL(wrapper.set_cache_handle(handle))) { } } @@ -979,7 +1047,7 @@ int ObTablet::init_with_update_medium_info( } else { if (OB_FAIL(ret)) { } else if (OB_FAIL(build_read_info(allocator, nullptr /*tablet*/))) { - } else if (OB_FAIL(inner_inc_macro_ref_cnt())) { + } else if (OB_FAIL(hold_macro_blocks())) { } else { if (old_tablet.get_tablet_meta().has_next_tablet_) { set_next_tablet_guard(old_tablet.next_tablet_guard_); @@ -1091,7 +1159,7 @@ int ObTablet::init_with_updated_members( if (FAILEDx(build_read_info(allocator, nullptr /*tablet*/))) { } else if (OB_FAIL(table_store_cache_.init(table_store_addr_.get_ptr()->get_major_sstables(), table_store_addr_.get_ptr()->get_minor_sstables()))) { - } else if (OB_FAIL(inner_inc_macro_ref_cnt())) { + } else if (OB_FAIL(hold_macro_blocks())) { } else { if (old_tablet.get_tablet_meta().has_next_tablet_) { set_next_tablet_guard(old_tablet.next_tablet_guard_); @@ -1157,10 +1225,7 @@ int ObTablet::init_with_mds_sstable( } else if (OB_FAIL(init_aggregated_info(allocator, nullptr))) { } else if (FALSE_IT(set_initial_addr())) { } else if (OB_FAIL(check_table_store_flag_match_with_table_store_(table_store_addr_.get_ptr()))) { - } else if (CLICK_FAIL(inner_inc_macro_ref_cnt())) { - /* NOTICE!!! - * Subsequently, skipping `is_inited_ = true` is prohibited (i.e., OB_FAIL must not occur), otherwise - * it will lead to a macro block refcnt leak. */ + } else if (CLICK_FAIL(hold_macro_blocks())) { } else { if (old_tablet.get_tablet_meta().has_next_tablet_) { set_next_tablet_guard(old_tablet.next_tablet_guard_); @@ -1332,42 +1397,6 @@ int ObTablet::self_serialize(char *buf, const int64_t len, int64_t &pos) const return ret; } -int ObTablet::partial_deserialize( - common::ObArenaAllocator &allocator, - const char *buf, - const int64_t len, - int64_t &pos) -{ - int ret = OB_SUCCESS; - int64_t new_pos = pos; - if (OB_UNLIKELY(is_inited_)) { - ret = OB_INIT_TWICE; - } else if (OB_ISNULL(buf) - || OB_UNLIKELY(len <= 0) - || OB_UNLIKELY(pos < 0) - || OB_UNLIKELY(len <= pos)) { - ret = OB_INVALID_ARGUMENT; - } else { - do { - if (OB_FAIL(load_deserialize_current(allocator, buf, len, new_pos, false/*pull memtable*/))) { - } - } while (is_retryable_macro_ref_error(ret)); - } - - if (OB_FAIL(ret)) { - // do nothing - } else if (tablet_meta_.has_next_tablet_) { - ObTablet next_tablet; - next_tablet.set_tablet_addr(tablet_addr_); - if (OB_FAIL(next_tablet.partial_deserialize(allocator, buf, len, new_pos))) { - } - } - if (OB_SUCC(ret)) { - pos = new_pos; - } - return ret; -} - int ObTablet::deserialize_for_replay( common::ObArenaAllocator &allocator, const char *buf, @@ -1385,10 +1414,8 @@ int ObTablet::deserialize_for_replay( ret = OB_INVALID_ARGUMENT; } else if (OB_FAIL(load_deserialize_current( allocator, buf, len, new_pos, false/*prepare_memtable*/))) { - } else if (OB_FAIL(inner_inc_macro_ref_cnt())) { + } else if (OB_FAIL(hold_macro_blocks())) { } else { - /* No failing operation may be added after increasing macro references, - * otherwise replay failure would leak those references. */ pos = new_pos; is_inited_ = true; LOG_INFO("succeed to deserialize tablet for replay", K(ret), KPC(this)); @@ -1486,11 +1513,8 @@ int ObTablet::deserialize_post_work(common::ObArenaAllocator &allocator) if (OB_SUCC(ret) && tablet_meta_.has_next_tablet_ && OB_FAIL(next_tablet_guard_.get_obj()->deserialize_post_work(allocator))) { } - if (FAILEDx(inner_inc_macro_ref_cnt())) { + if (FAILEDx(hold_macro_blocks())) { } - /* NOTICE!!! - * Subsequently, skipping `is_inited_ = true` is prohibited (i.e., OB_FAIL must not occur), otherwise - * it will lead to a macro block refcnt leak. */ if (OB_SUCC(ret)) { is_inited_ = true; LOG_INFO("succeed to load current tablet format", K(ret), KPC(this)); @@ -1768,8 +1792,6 @@ int ObTablet::deserialize( if (OB_SUCC(ret)) { pos = new_pos; is_inited_ = true; - // must succeed if hold_ref_cnt_ has been set to true - hold_ref_cnt_ = true; LOG_INFO("succeed to deserialize current tablet format", K(ret), KPC(this), K(header)); } } @@ -1872,355 +1894,85 @@ int ObTablet::load_macro_info( return ret; } -int ObTablet::inc_macro_ref_cnt() +int ObTablet::hold_macro_blocks() { int ret = OB_SUCCESS; - if (OB_UNLIKELY(!is_inited_)) { - ret = OB_NOT_INIT; - } else if (OB_FAIL(inner_inc_macro_ref_cnt())) { - } else if (tablet_meta_.has_next_tablet_ - && OB_FAIL(next_tablet_guard_.get_obj()->inc_macro_ref_cnt())) { - } - return ret; -} - -int ObTablet::inner_inc_macro_ref_cnt() -{ - int ret = OB_SUCCESS; - if (OB_FAIL(check_meta_addr())) { - } else if (OB_UNLIKELY(!is_empty_shell() && macro_info_addr_.is_none_object())) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("normal tablet's macro_info_addr_ shouldn't be none object", K(ret), KPC(this)); - } else if (macro_info_addr_.is_none_object() || is_empty_shell()) { - if (OB_FAIL(inc_ref_without_aggregated_info())) { - } - } else { - if (OB_FAIL(inc_ref_with_aggregated_info())) { + if (block_group_) { + // A persisted Tablet reloads with the ownership of the same disk version. + } else if (OB_FAIL(check_meta_addr())) { + } else if (is_empty_shell()) { + if (OB_UNLIKELY(tablet_addr_.is_block() || !table_store_addr_.addr_.is_none() + || !storage_schema_addr_.addr_.is_none())) { + ret = OB_INVALID_DATA; + LOG_ERROR("empty shell has data file addresses", K(ret), KPC(this)); } - } - if (OB_SUCC(ret)) { - hold_ref_cnt_ = true; + } else if (OB_UNLIKELY(macro_info_addr_.is_none_object())) { + ret = OB_INVALID_DATA; + LOG_ERROR("normal tablet has no macro info", K(ret), KPC(this)); + } else if (OB_FAIL(hold_blocks_from_metadata())) { } return ret; } -int ObTablet::inc_ref_with_aggregated_info() +int ObTablet::hold_blocks_from_metadata() { int ret = OB_SUCCESS; - ObArenaAllocator allocator("IncMacroRef", OB_MALLOC_NORMAL_BLOCK_SIZE); - ObTabletMacroInfo *macro_info = nullptr; - bool in_memory = true; - bool inc_tablet_ref = false; - bool inc_other_ref = false; - ObMacroInfoIterator info_iter; - - if (OB_FAIL(load_macro_info(allocator, macro_info, in_memory))) { - } else if (OB_FAIL(info_iter.init(ObTabletMacroType::MAX, *macro_info))) { - } else if (OB_FAIL(inc_addr_ref_cnt(tablet_addr_, inc_tablet_ref))) { - } else if (OB_FAIL(inc_ref_with_macro_iter(info_iter, inc_other_ref))) { - } - if (OB_FAIL(ret)) { - if (inc_tablet_ref) { - dec_addr_ref_cnt(tablet_addr_); - } - if (inc_other_ref) { - int tmp_ret = OB_SUCCESS; - if (OB_TMP_FAIL(info_iter.reuse())) { - } else { - dec_ref_with_macro_iter(info_iter); - } - } - } - if (OB_NOT_NULL(macro_info) && !in_memory) { - macro_info->reset(); - } - - return ret; -} - -int ObTablet::inc_ref_with_macro_iter(ObMacroInfoIterator ¯o_iter, bool &inc_success) const -{ - int ret = OB_SUCCESS; - int inc_other_ref_cnt = 0; - ObTabletBlockInfo block_info; - inc_success = false; - ObSArray print_arr; - print_arr.set_attr(ObMemAttr("PrintId", ObCtxIds::DEFAULT_CTX_ID)); - while (OB_SUCC(ret)) { - block_info.reset(); - if (OB_FAIL(macro_iter.get_next(block_info))) { - if (OB_ITER_END != ret) { - } - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(block_info.macro_id_))) { - } else if (FALSE_IT(inc_other_ref_cnt++)) { - } else if (ObTabletMacroType::SHARED_DATA_BLOCK == block_info.block_type_ - && (OB_ISNULL(::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>()) - || OB_FAIL(::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>()->add_block( - block_info.macro_id_, block_info.occupy_size_)))) { - if (OB_SUCC(ret)) { - ret = OB_ERR_UNEXPECTED; - } - } - int tmp_ret = OB_SUCCESS; - if (OB_FAIL(ret)) { - // do nothing - } else if (OB_TMP_FAIL(print_arr.push_back(block_info.macro_id_))) { - } else if (MAX_PRINT_COUNT == print_arr.size()) { - print_arr.reuse(); - } + ObArenaAllocator allocator("TabletBlocks"); + ObTabletMacroInfo *macro_info = nullptr; + bool in_memory = true; + ObMacroInfoIterator iter; + if (OB_FAIL(load_macro_info(allocator, macro_info, in_memory))) { + } else if (OB_FAIL(iter.init(block_file(), ObTabletMacroType::MAX, *macro_info))) { + } else if (OB_FAIL(hold_aggregated_blocks(iter))) { } - if (0 != print_arr.count()) { - print_arr.reuse(); + if (macro_info != nullptr && !in_memory) { + macro_info->reset(); } - - if (OB_LIKELY(OB_ITER_END == ret) || OB_SUCC(ret)) { - inc_success = true; - ret = OB_SUCCESS; - } else if (inc_other_ref_cnt > 0) { - int tmp_ret = OB_SUCCESS; - if (OB_TMP_FAIL(macro_iter.reuse())) { - } else { - for (int64_t i = 0; i < inc_other_ref_cnt; i++) { - block_info.reset(); - if (OB_TMP_FAIL(macro_iter.get_next(block_info))) { - } else if (OB_TMP_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(block_info.macro_id_))) { - } else if (ObTabletMacroType::SHARED_DATA_BLOCK == block_info.block_type_ - && OB_NOT_NULL(::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>()) - && OB_TMP_FAIL(::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>()->free_block( - block_info.macro_id_, block_info.occupy_size_))) { - LOG_WARN("fail to rollback shared macro block accounting", K(tmp_ret), K(block_info)); - } - if (OB_TMP_FAIL(tmp_ret)) { - // do nothing - } else if (OB_TMP_FAIL(print_arr.push_back(block_info.macro_id_))) { - } else if (MAX_PRINT_COUNT == print_arr.size()) { - print_arr.reuse(); - } - } - if (0 != print_arr.count()) { - print_arr.reuse(); - } - } - } - - FLOG_INFO("the tablet that inner increases ref cnt is", - K(ret), K(hold_ref_cnt_), "tablet_id", tablet_meta_.tablet_id_, - K(table_store_addr_.addr_), K(storage_schema_addr_.addr_), - K(tablet_addr_), KP(this), K(macro_iter), K(lbt())); - return ret; } -int ObTablet::inc_ref_without_aggregated_info() +int ObTablet::hold_aggregated_blocks(ObMacroInfoIterator &iter) { int ret = OB_SUCCESS; - bool inc_table_store_ref = false; - bool inc_storage_schema_ref = false; - bool inc_tablet_ref = false; - bool inc_table_store_member_ref = false; - - if (OB_FAIL(inc_addr_ref_cnt(table_store_addr_.addr_, inc_table_store_ref))) { - } else if (OB_FAIL(inc_addr_ref_cnt(storage_schema_addr_.addr_, inc_storage_schema_ref))) { - } else if (OB_FAIL(inc_addr_ref_cnt(tablet_addr_, inc_tablet_ref))) { - } else if (OB_FAIL(inc_table_store_ref_cnt(inc_table_store_member_ref))) { + std::shared_ptr group; + ObSEArray members; + try { + group = std::make_shared(); + } catch (const std::bad_alloc &) { + return OB_ALLOCATE_MEMORY_FAILED; } - if (OB_FAIL(ret)) { - if (inc_table_store_ref) { - dec_addr_ref_cnt(table_store_addr_.addr_); - } - if (inc_storage_schema_ref) { - dec_addr_ref_cnt(storage_schema_addr_.addr_); - } - if (inc_tablet_ref) { - dec_addr_ref_cnt(tablet_addr_); + const auto add = [&](const MacroBlockId &id, storage_io::BlockKind kind) -> int { + if (id.block_index() <= 0) { + return OB_INVALID_DATA; } - if (inc_table_store_member_ref) { - dec_table_store_ref_cnt(); - } - } - return ret; -} - -void ObTablet::dec_macro_ref_cnt() -{ - int ret = OB_SUCCESS; - if (OB_UNLIKELY(!hold_ref_cnt_)) { - FLOG_INFO("tablet doesn't hold ref cnt, no need to dec ref cnt", - K(is_inited_), K(tablet_meta_.tablet_id_), - K(table_store_addr_.addr_), K(tablet_addr_), KP(this), K(lbt())); - } else if (OB_FAIL(check_meta_addr())) { - } else if (OB_UNLIKELY(!is_empty_shell() && macro_info_addr_.is_none_object())) { - ret = OB_ERR_UNEXPECTED; - LOG_ERROR("normal tablet's macro_info_addr_ shouldn't be none object", K(ret), KPC(this)); - } else if (macro_info_addr_.is_none_object() || is_empty_shell()) { - dec_ref_without_aggregated_info(); - } else { - dec_ref_with_aggregated_info(); + return members.push_back(storage_io::BlockMember{ + {static_cast(id.block_index()), id.write_seq()}, kind}); + }; + if (tablet_addr_.is_block()) { + ret = add(tablet_addr_.block_id(), storage_io::BlockKind::Metadata); } -} -void ObTablet::dec_ref_without_aggregated_info() -{ - // 1. We don't need to recursively decrease macro ref cnt, since we will push both them to gc queue - // 2. the order can't be changed, must be sstable blocks' ref cnt -> tablet meta blocks' ref cnt - - dec_table_store_ref_cnt(); - dec_addr_ref_cnt(table_store_addr_.addr_); - dec_addr_ref_cnt(storage_schema_addr_.addr_); - dec_addr_ref_cnt(tablet_addr_); -} - -void ObTablet::dec_ref_with_aggregated_info() -{ - int ret = OB_SUCCESS; - ObArenaAllocator allocator("DecMacroRef", OB_MALLOC_NORMAL_BLOCK_SIZE); - ObTabletMacroInfo *macro_info = nullptr; - bool in_memory = true; - ObMacroInfoIterator info_iter; - if (OB_FAIL(load_macro_info(allocator, macro_info, in_memory))) { - } else if (OB_FAIL(info_iter.init(ObTabletMacroType::MAX, *macro_info))) { - } else { - dec_addr_ref_cnt(tablet_addr_); - dec_ref_with_macro_iter(info_iter); - } - if (OB_NOT_NULL(macro_info) && !in_memory) { - macro_info->reset(); - } - - FLOG_INFO("the tablet that decreases ref cnt is", - K(is_inited_), K(tablet_meta_.tablet_id_), K(table_store_addr_.addr_), - K(storage_schema_addr_.addr_), K(tablet_addr_), KP(this), K(info_iter), K(lbt())); -} - -void ObTablet::dec_ref_with_macro_iter(ObMacroInfoIterator ¯o_iter) const -{ - int ret = OB_SUCCESS; - ObTabletBlockInfo block_info; - ObSArray print_arr; - print_arr.set_attr(ObMemAttr("PrintId", ObCtxIds::DEFAULT_CTX_ID)); + ObTabletBlockInfo entry; while (OB_SUCC(ret)) { - block_info.reset(); - if (OB_FAIL(macro_iter.get_next(block_info))) { - if (OB_ITER_END != ret) { - LOG_ERROR("fail to get next block info, macro block may leak", K(ret)); - } - } else { - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(block_info.macro_id_))) { - } else if (ObTabletMacroType::SHARED_DATA_BLOCK == block_info.block_type_ - && (OB_ISNULL(::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>()) - || OB_FAIL(::oceanbase::share::server_service<::oceanbase::blocksstable::ObSharedMacroBlockMgr>()->free_block( - block_info.macro_id_, block_info.occupy_size_)))) { - if (OB_SUCC(ret)) { - ret = OB_ERR_UNEXPECTED; - } - } - int tmp_ret = OB_SUCCESS; - if (OB_FAIL(ret)) { + if (OB_FAIL(iter.get_next(entry))) { + if (OB_ITER_END == ret) { ret = OB_SUCCESS; - // ignore ret, continue - } else { - if (OB_TMP_FAIL(print_arr.push_back(block_info.macro_id_))) { - } else if (MAX_PRINT_COUNT == print_arr.size()) { - print_arr.reuse(); - } } + break; } - } - if (0 != print_arr.size()) { - print_arr.reuse(); - } -} - -int ObTablet::inc_table_store_ref_cnt(bool &inc_success) -{ - int ret = OB_SUCCESS; - inc_success = false; - ObTabletMemberWrapper table_store_wrapper; - - if (table_store_addr_.addr_.is_none()) { - // skip empty shell - } else if (OB_FAIL(fetch_table_store(table_store_wrapper))) { - } else if (OB_FAIL(table_store_wrapper.get_member()->inc_macro_ref())) { - } else { - inc_success = true; - } - return ret; -} - -void ObTablet::dec_table_store_ref_cnt() -{ - int ret = OB_SUCCESS; - ObTabletMemberWrapper table_store_wrapper; - if (table_store_addr_.addr_.is_none()) { - // skip empty shell - } else { - do { - ret = fetch_table_store(table_store_wrapper); - } while (is_retryable_macro_ref_error(ret)); - if (OB_FAIL(ret)) { - } else { - table_store_wrapper.get_member()->dec_macro_ref(); + const bool shared = entry.block_type_ == ObTabletMacroType::SHARED_DATA_BLOCK; + const bool data = shared || entry.block_type_ == ObTabletMacroType::DATA_BLOCK; + if (OB_FAIL(add(entry.macro_id_, data ? storage_io::BlockKind::Data : storage_io::BlockKind::Metadata))) { + } else if (shared && OB_FAIL(group->add_shared(entry))) { } } -} - -int ObTablet::inc_addr_ref_cnt(const ObMetaDiskAddr &addr, bool &inc_success) -{ - int ret = OB_SUCCESS; - inc_success = false; - MacroBlockId macro_id; - int64_t offset; - int64_t size; - if (addr.is_block()) { // skip full/old/empty_shell tablet - if (OB_FAIL(addr.get_block_addr(macro_id, offset, size))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.inc_ref(macro_id))) { - } else { - inc_success = true; - } + if (OB_SUCC(ret) && OB_SUCC(ret = group->hold(block_file(), {members.get_data(), static_cast(members.count())}))) { + block_group_ = std::move(group); } return ret; } -void ObTablet::dec_addr_ref_cnt(const ObMetaDiskAddr &addr) -{ - int ret = OB_SUCCESS; - MacroBlockId macro_id; - int64_t offset; - int64_t size; - if (addr.is_block()) { // skip full/old/empty_shell tablet - if (OB_FAIL(addr.get_block_addr(macro_id, offset, size))) { - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } - } -} - -void ObTablet::dec_linked_block_ref_cnt(const ObMetaDiskAddr &head_addr) -{ - int ret = OB_SUCCESS; - ObObjectLinkIter iter; - MacroBlockId macro_id; - if (head_addr.is_block()) { - if (OB_FAIL(iter.init(head_addr))) { - } else { - while (OB_SUCC(ret)) { - if (OB_FAIL(iter.get_next_macro_id(macro_id))) { - if (OB_ITER_END == ret) { - ret = OB_SUCCESS; - break; - } else if (is_retryable_macro_ref_error(ret)) { - ret = OB_SUCCESS; - // retry - } else { - LOG_ERROR("fail to get next macro id, macro block leaks", K(ret)); - } - } else if (OB_FAIL(OB_STORAGE_OBJECT_MGR.dec_ref(macro_id))) { - } - } - } - } -} - void ObTablet::set_initial_addr() { if (!table_store_addr_.addr_.is_none() && !storage_schema_addr_.addr_.is_none()) { @@ -2613,7 +2365,7 @@ int ObTablet::get_read_tables_( ObStorageMetaKey meta_key(table_store_addr_.addr_); const ObStorageMetaValue *value = nullptr; if (OB_FAIL(OB_STORE_CACHE.get_storage_meta_cache().get_meta( - ObStorageMetaValue::MetaType::TABLE_STORE, meta_key, table_store_handle, this))) { + block_file(), ObStorageMetaValue::MetaType::TABLE_STORE, meta_key, table_store_handle, this))) { } else if (OB_FAIL(table_store_handle.get_value(value))) { } else if (OB_FAIL(value->get_table_store(table_store))) { } @@ -4387,7 +4139,7 @@ int64_t ObTablet::to_string(char *buf, const int64_t buf_len) const J_KV(KP(this), K_(is_inited), K_(wash_score), - K_(hold_ref_cnt), + "owns_macro_blocks", static_cast(block_group_), K_(ref_cnt), K_(version), K_(length), diff --git a/src/storage/tablet/ob_tablet.h b/src/storage/tablet/ob_tablet.h index 72392bc370..e0aba89860 100644 --- a/src/storage/tablet/ob_tablet.h +++ b/src/storage/tablet/ob_tablet.h @@ -41,6 +41,7 @@ #include "storage/tx/ob_trans_define.h" #include "share/scn.h" #include "ob_i_tablet_mds_customized_interface.h" +#include #include namespace oceanbase @@ -81,6 +82,8 @@ class ObTransID; namespace storage { class ObTabletReplayExecutor; +class StorageMetaService; +class TabletBlockGroup; class ObLS; class ObIMemtable; class ObStoreCtx; @@ -134,6 +137,7 @@ class ObTablet final : public ObITabletMdsCustomizedInterface friend class ObTabletTruncateInfoReader; friend class ObTabletReplayExecutor; friend class ObTabletPersister; + friend class StorageMetaService; friend class ObTabletPointerMap; friend class ObTabletTableIterator; public: @@ -243,8 +247,6 @@ class ObTablet final : public ObITabletMdsCustomizedInterface bool is_valid() const; int32_t get_version() const { return version_; } - void dec_macro_ref_cnt(); - int inc_macro_ref_cnt(); // these interfaces is only for tiny mode // load_$member: member will always exist in disk (local storage/macro block), so read from disk then deserialize // fetch_$member: member may exist in memory or disk, if in memory, get it directly, if in disk, @@ -276,6 +278,8 @@ class ObTablet final : public ObITabletMdsCustomizedInterface void set_next_tablet(ObTablet* tablet) { next_tablet_ = tablet; } ObTablet *get_next_tablet() { return next_tablet_; } ObArenaAllocator *get_allocator() const { return allocator_; } + void bind_block_file(storage_io::BlockOwner &block_file) { block_file_ = &block_file; } + storage_io::BlockOwner &block_file() const { return *block_file_; } bool is_empty_shell() const; // major merge or medium merge call bool is_data_complete() const; @@ -538,11 +542,6 @@ class ObTablet final : public ObITabletMdsCustomizedInterface const ObUpdateTableStoreParam ¶m, const ObTabletCreateDeleteMdsUserData &last_tablet_status); int update_tablet_status_from_sstable(const bool expect_persist_status); - int partial_deserialize( - common::ObArenaAllocator &allocator, - const char *buf, - const int64_t len, - int64_t &pos); static int deserialize_macro_info( common::ObArenaAllocator &allocator, const char *buf, @@ -555,18 +554,11 @@ class ObTablet final : public ObITabletMdsCustomizedInterface void set_initial_addr(); int check_meta_addr() const; static int parse_meta_addr(const ObMetaDiskAddr &addr, ObIArray &meta_ids); - void dec_ref_with_aggregated_info(); - void dec_ref_without_aggregated_info(); - void dec_ref_with_macro_iter(ObMacroInfoIterator ¯o_iter) const; - int inner_inc_macro_ref_cnt(); - int inc_ref_with_aggregated_info(); - int inc_ref_without_aggregated_info(); - int inc_ref_with_macro_iter(ObMacroInfoIterator ¯o_iter, bool &inc_success) const; - void dec_table_store_ref_cnt(); - int inc_table_store_ref_cnt(bool &inc_success); - static int inc_addr_ref_cnt(const ObMetaDiskAddr &addr, bool &inc_success); - static void dec_addr_ref_cnt(const ObMetaDiskAddr &addr); - static void dec_linked_block_ref_cnt(const ObMetaDiskAddr &head_addr); + int hold_macro_blocks(); + int hold_blocks_from_metadata(); + int hold_aggregated_blocks(ObMacroInfoIterator ¯o_iter); + bool holds_macro_blocks() const { return block_group_ || is_empty_shell(); } + static void set_group_published(const std::shared_ptr &group, bool published); int64_t get_try_cache_size() const; int inner_release_memtables(const share::SCN scn); int calc_sstable_occupy_size(int64_t &all_sstable_occupy_size); @@ -730,7 +722,6 @@ class ObTablet final : public ObITabletMdsCustomizedInterface // ObTabletDDLKvMgr::MAX_DDL_KV_CNT_IN_STORAGE // Array size is too large, need to shrink it if possible static const int64_t DDL_KV_ARRAY_SIZE = 64; - static const int64_t MAX_PRINT_COUNT = 100; private: int32_t version_; // size: 4B, alignment: 4B int32_t length_; // size: 4B, alignment: 4B @@ -768,11 +759,9 @@ class ObTablet final : public ObITabletMdsCustomizedInterface ObTruncateInfoCache truncate_info_cache_; // size: 8B, alignment: 8B ObTableStoreCache table_store_cache_; // no need to serialize, should be initialized after table store is initialized. // size: 48B, alignment: 8B - // whether hold ref cnt - // when destroying tablet, only if hold_ref_cnt_ is true do we decrease meta blocks' ref cnt - // we need to set it to true after increasing meta blocks' ref cnt or deserializing tablet + std::shared_ptr block_group_; + storage_io::BlockOwner *block_file_ = nullptr; bool gc_occupy_flag_; // size: 4B, alignment: 1B - bool hold_ref_cnt_; // size: 4B, alignment: 1B bool is_inited_; // size: 4B, alignment: 1B const bool is_external_tablet_; // size: 4B, alignment: 1B }; diff --git a/src/storage/tablet/ob_tablet_create_delete_helper.cpp b/src/storage/tablet/ob_tablet_create_delete_helper.cpp index 87e4872b35..5a2bc5a8d5 100644 --- a/src/storage/tablet/ob_tablet_create_delete_helper.cpp +++ b/src/storage/tablet/ob_tablet_create_delete_helper.cpp @@ -415,6 +415,7 @@ int ObTabletCreateDeleteHelper::acquire_tablet_from_pool( } int ObTabletCreateDeleteHelper::create_empty_sstable( + storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator, const ObStorageSchema &storage_schema, const common::ObTabletID &tablet_id, @@ -428,7 +429,7 @@ int ObTabletCreateDeleteHelper::create_empty_sstable( if (OB_UNLIKELY(!storage_schema.is_valid() || snapshot_version < 0)) { ret = OB_INVALID_ARGUMENT; } else if (OB_FAIL(param.init_for_empty_major_sstable(tablet_id, storage_schema, snapshot_version))) { - } else if (OB_FAIL(create_sstable(param, allocator, table_handle))) { + } else if (OB_FAIL(create_sstable(block_file, param, allocator, table_handle))) { } if (OB_FAIL(ret)) { diff --git a/src/storage/tablet/ob_tablet_create_delete_helper.h b/src/storage/tablet/ob_tablet_create_delete_helper.h index 256b7b8acf..037d96764a 100644 --- a/src/storage/tablet/ob_tablet_create_delete_helper.h +++ b/src/storage/tablet/ob_tablet_create_delete_helper.h @@ -128,6 +128,7 @@ class ObTabletCreateDeleteHelper ObTabletHandle &handle); // Attention !!! only used when first creating tablet static int create_empty_sstable( + storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator, const ObStorageSchema &storage_schema, const common::ObTabletID &tablet_id, @@ -136,11 +137,13 @@ class ObTabletCreateDeleteHelper template static int create_sstable( + storage_io::BlockOwner &block_file, const ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator &allocator, ObTableHandleV2 &table_handle); template static int create_sstable( + storage_io::BlockOwner &block_file, const ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator &allocator, T &sstable); @@ -157,6 +160,7 @@ class ObTabletCreateDeleteHelper template int ObTabletCreateDeleteHelper::create_sstable( + storage_io::BlockOwner &block_file, const ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator &allocator, ObTableHandleV2 &table_handle) @@ -168,7 +172,7 @@ int ObTabletCreateDeleteHelper::create_sstable( ret = common::OB_ALLOCATE_MEMORY_FAILED; STORAGE_LOG(WARN, "fail to allocate sstable memory", K(ret)); } else if (FALSE_IT(sstable = new (buf) T())) { - } else if (OB_FAIL(create_sstable(param, allocator, *sstable))) { + } else if (OB_FAIL(create_sstable(block_file, param, allocator, *sstable))) { } else if (OB_FAIL(table_handle.set_sstable(sstable, &allocator))) { } return ret; @@ -176,6 +180,7 @@ int ObTabletCreateDeleteHelper::create_sstable( template int ObTabletCreateDeleteHelper::create_sstable( + storage_io::BlockOwner &block_file, const ObTabletCreateSSTableParam ¶m, common::ObArenaAllocator &allocator, T &sstable) @@ -184,7 +189,9 @@ int ObTabletCreateDeleteHelper::create_sstable( if (OB_UNLIKELY(!param.is_valid())) { ret = common::OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "invalid args", K(ret), K(param)); - } else if (OB_FAIL(sstable.init(param, &allocator))) { + } else { + sstable.bind_block_file(block_file); + ret = sstable.init(param, &allocator); } return ret; } diff --git a/src/storage/tablet/ob_tablet_macro_info_iterator.cpp b/src/storage/tablet/ob_tablet_macro_info_iterator.cpp index aa21d102de..b2ab2f26af 100644 --- a/src/storage/tablet/ob_tablet_macro_info_iterator.cpp +++ b/src/storage/tablet/ob_tablet_macro_info_iterator.cpp @@ -71,11 +71,13 @@ void ObMacroInfoIterator::destroy() target_type_ = ObTabletMacroType::INVALID_TYPE; block_info_arr_.reset(); is_linked_ = false; + block_file_ = nullptr; macro_info_ = nullptr; is_inited_ = false; } -int ObMacroInfoIterator::init(const ObTabletMacroType target_type, const ObTabletMacroInfo ¯o_info) +int ObMacroInfoIterator::init( + storage_io::BlockOwner &block_file, const ObTabletMacroType target_type, const ObTabletMacroInfo ¯o_info) { int ret = OB_SUCCESS; if (OB_UNLIKELY(is_inited_)) { @@ -86,7 +88,7 @@ int ObMacroInfoIterator::init(const ObTabletMacroType target_type, const ObTable const MacroBlockId &entry_block = macro_info.entry_block_; ObMemAttr mem_attr("TabletBlockId"); if (!entry_block.is_empty_list_entry()) { - if (OB_FAIL(block_reader_.init(entry_block, mem_attr))) { + if (OB_FAIL(block_reader_.init(block_file, entry_block, mem_attr))) { } else { is_linked_ = true; } @@ -100,6 +102,7 @@ int ObMacroInfoIterator::init(const ObTabletMacroType target_type, const ObTable cur_size_ = 0; cur_type_ = ObTabletMacroType::MAX; target_type_ = target_type; + block_file_ = &block_file; macro_info_ = ¯o_info; is_inited_ = true; } @@ -124,7 +127,7 @@ int ObMacroInfoIterator::reuse() ObMemAttr mem_attr("TabletBlockId"); if (OB_UNLIKELY(!entry_block.is_valid() || entry_block.is_empty_list_entry())) { ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(block_reader_.init(entry_block, mem_attr))) { + } else if (OB_FAIL(block_reader_.init(*block_file_, entry_block, mem_attr))) { } } } @@ -239,22 +242,16 @@ int ObMacroInfoIterator::read_from_disk() ret = OB_ERR_UNEXPECTED; } else if (OB_UNLIKELY(ObTabletMacroType::LINKED_BLOCK == target_type_)) { ret = OB_NOT_SUPPORTED; - } else if (ObTabletMacroType::SHARED_DATA_BLOCK == cur_type_) { - ObTabletMacroInfo::ObBlockInfoArray tmp_arr; - if (OB_FAIL(tmp_arr.deserialize(allocator, buf, buf_len, pos))) { - } else if (OB_FAIL(reuse_info_arr(tmp_arr.cnt_))) { - } else if (OB_FAIL(convert_to_block_info(tmp_arr))) { - } } else { do { pos = 0; buf = nullptr; buf_len = 0; + int16_t type = 0; if (OB_FAIL(block_reader_.get_next_item(buf, buf_len, addr))) { - if (OB_ITER_END != ret) { - } - } else if (OB_FAIL(serialization::decode_i16(buf, buf_len, pos, reinterpret_cast(&cur_type_)))) { - } else if (OB_UNLIKELY(ObTabletMacroType::INVALID_TYPE == cur_type_ || ObTabletMacroType::MAX == cur_type_)) { + } else if (OB_FAIL(serialization::decode_i16(buf, buf_len, pos, &type))) { + } else if (FALSE_IT(cur_type_ = static_cast(type))) { + } else if (OB_UNLIKELY(cur_type_ < ObTabletMacroType::META_BLOCK || cur_type_ > ObTabletMacroType::SHARED_DATA_BLOCK)) { ret = OB_ERR_UNEXPECTED; } else if (target_iter && prev_type == target_type_ && cur_type_ != target_type_) { ret = OB_ITER_END; // if ObTabletMacroType::MAX is not equal to target_type_, we only need to iterate targeted ids @@ -263,7 +260,12 @@ int ObMacroInfoIterator::read_from_disk() } if (OB_FAIL(ret)) { - // do nothing + } else if (ObTabletMacroType::SHARED_DATA_BLOCK == cur_type_) { + ObTabletMacroInfo::ObBlockInfoArray tmp_arr; + if (OB_FAIL(tmp_arr.deserialize(allocator, buf, buf_len, pos))) { + } else if (OB_FAIL(reuse_info_arr(tmp_arr.cnt_))) { + } else if (OB_FAIL(convert_to_block_info(tmp_arr))) { + } } else { ObTabletMacroInfo::ObBlockInfoArray tmp_arr; if (OB_FAIL(tmp_arr.deserialize(allocator, buf, buf_len, pos))) { diff --git a/src/storage/tablet/ob_tablet_macro_info_iterator.h b/src/storage/tablet/ob_tablet_macro_info_iterator.h index 8fe5dbf3a1..c5c7d330e7 100644 --- a/src/storage/tablet/ob_tablet_macro_info_iterator.h +++ b/src/storage/tablet/ob_tablet_macro_info_iterator.h @@ -52,7 +52,8 @@ class ObMacroInfoIterator final void destroy(); int reuse(); // ObTabletMacroType::MAX means iterate all kinds of ids - int init(const ObTabletMacroType target_type, const ObTabletMacroInfo ¯o_info); + int init(storage_io::BlockOwner &block_file, const ObTabletMacroType target_type, + const ObTabletMacroInfo ¯o_info); int get_next(ObTabletBlockInfo &block_info); TO_STRING_KV(KPC_(macro_info), K_(cur_type), K_(target_type), K_(is_linked)); private: @@ -62,6 +63,7 @@ class ObMacroInfoIterator final int convert_to_block_info(const ObTabletMacroInfo::ObBlockInfoArray &tmp_arr); int convert_to_block_info(const ObTabletMacroInfo::ObBlockInfoArray &tmp_arr); private: + storage_io::BlockOwner *block_file_ = nullptr; const ObTabletMacroInfo *macro_info_; ObLinkedMacroBlockItemReader block_reader_; int64_t cur_pos_; diff --git a/src/storage/tablet/ob_tablet_mds_data.cpp b/src/storage/tablet/ob_tablet_mds_data.cpp index f6154f8944..b599a7fff6 100644 --- a/src/storage/tablet/ob_tablet_mds_data.cpp +++ b/src/storage/tablet/ob_tablet_mds_data.cpp @@ -134,6 +134,7 @@ int ObTabletMdsData::init_for_first_creation() // not used int ObTabletMdsData::init_for_mds_table_dump( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletMdsData &mds_table_data, const ObTabletMdsData &base_data, @@ -144,12 +145,12 @@ int ObTabletMdsData::init_for_mds_table_dump( if (OB_UNLIKELY(is_inited_)) { ret = OB_INIT_TWICE; } else { - if (OB_FAIL(init_single_complex_addr(allocator, mds_table_data.tablet_status_.uncommitted_kv_, base_data.tablet_status_.uncommitted_kv_, tablet_status_.uncommitted_kv_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, mds_table_data.tablet_status_.committed_kv_, base_data.tablet_status_.committed_kv_, tablet_status_.committed_kv_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, mds_table_data.aux_tablet_info_.uncommitted_kv_, base_data.aux_tablet_info_.uncommitted_kv_, aux_tablet_info_.uncommitted_kv_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, mds_table_data.aux_tablet_info_.committed_kv_, base_data.aux_tablet_info_.committed_kv_, aux_tablet_info_.committed_kv_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, mds_table_data.auto_inc_seq_, base_data.auto_inc_seq_, auto_inc_seq_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, mds_table_data.medium_info_list_, base_data.medium_info_list_, finish_medium_scn, medium_info_list_))) { + if (OB_FAIL(init_single_complex_addr(block_file, allocator, mds_table_data.tablet_status_.uncommitted_kv_, base_data.tablet_status_.uncommitted_kv_, tablet_status_.uncommitted_kv_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, mds_table_data.tablet_status_.committed_kv_, base_data.tablet_status_.committed_kv_, tablet_status_.committed_kv_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, mds_table_data.aux_tablet_info_.uncommitted_kv_, base_data.aux_tablet_info_.uncommitted_kv_, aux_tablet_info_.uncommitted_kv_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, mds_table_data.aux_tablet_info_.committed_kv_, base_data.aux_tablet_info_.committed_kv_, aux_tablet_info_.committed_kv_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, mds_table_data.auto_inc_seq_, base_data.auto_inc_seq_, auto_inc_seq_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, mds_table_data.medium_info_list_, base_data.medium_info_list_, finish_medium_scn, medium_info_list_))) { } else if (OB_FAIL(update_user_data_from_complex_addr(tablet_status_.committed_kv_, tablet_status_cache_))) { } else { // always use base data to set extra medium info @@ -170,6 +171,7 @@ int ObTabletMdsData::init_for_mds_table_dump( } int ObTabletMdsData::init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &mds_table_data, const ObTabletComplexAddr &base_data, @@ -181,8 +183,8 @@ int ObTabletMdsData::init_single_complex_addr( mds::MdsDumpKV *mds_table_ptr = nullptr; mds::MdsDumpKV *base_ptr = nullptr; - if (OB_FAIL(load_mds_dump_kv(allocator, mds_table_data, mds_table_ptr))) { - } else if (OB_FAIL(load_mds_dump_kv(allocator, base_data, base_ptr))) { + if (OB_FAIL(load_mds_dump_kv(block_file, allocator, mds_table_data, mds_table_ptr))) { + } else if (OB_FAIL(load_mds_dump_kv(block_file, allocator, base_data, base_ptr))) { } else if (nullptr == mds_table_ptr && nullptr == base_ptr) { // data in mds table and base is both empty, so set addr to NONE fused_data.addr_.set_none_addr(); @@ -206,6 +208,7 @@ int ObTabletMdsData::init_single_complex_addr( } int ObTabletMdsData::init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &mds_table_data, const ObTabletComplexAddr &base_data, @@ -217,8 +220,8 @@ int ObTabletMdsData::init_single_complex_addr( ObTabletAutoincSeq *mds_table_ptr = nullptr; ObTabletAutoincSeq *base_ptr = nullptr; - if (OB_FAIL(load_auto_inc_seq(allocator, mds_table_data, mds_table_ptr))) { - } else if (OB_FAIL(load_auto_inc_seq(allocator, base_data, base_ptr))) { + if (OB_FAIL(load_auto_inc_seq(block_file, allocator, mds_table_data, mds_table_ptr))) { + } else if (OB_FAIL(load_auto_inc_seq(block_file, allocator, base_data, base_ptr))) { } else if (nullptr == mds_table_ptr && nullptr == base_ptr) { // both data in mds table and base is invalid, no need to fuse, set fused data to NONE fused_data.addr_.set_none_addr(); @@ -242,6 +245,7 @@ int ObTabletMdsData::init_single_complex_addr( } int ObTabletMdsData::init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &mds_table_data, const ObTabletComplexAddr &base_data, @@ -254,8 +258,8 @@ int ObTabletMdsData::init_single_complex_addr( ObTabletDumpedMediumInfo *mds_table_ptr = nullptr; ObTabletDumpedMediumInfo *base_ptr = nullptr; - if (OB_FAIL(load_array(allocator, mds_table_data, mds_table_ptr))) { - } else if (OB_FAIL(load_array(allocator, base_data, base_ptr))) { + if (OB_FAIL(load_array(block_file, allocator, mds_table_data, mds_table_ptr))) { + } else if (OB_FAIL(load_array(block_file, allocator, base_data, base_ptr))) { } else if (nullptr == mds_table_ptr && nullptr == base_ptr) { // data in mds table and base is both empty, set fused data to NONE fused_data.addr_.set_none_addr(); @@ -288,6 +292,7 @@ int ObTabletMdsData::init_single_complex_addr( // not used int ObTabletMdsData::init_for_evict_medium_info( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletMdsData &other, const int64_t finish_medium_scn, @@ -298,12 +303,12 @@ int ObTabletMdsData::init_for_evict_medium_info( if (OB_UNLIKELY(is_inited_)) { ret = OB_INIT_TWICE; } else { - if (OB_FAIL(init_single_complex_addr(allocator, other.tablet_status_.uncommitted_kv_, tablet_status_.uncommitted_kv_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, other.tablet_status_.committed_kv_, tablet_status_.committed_kv_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, other.aux_tablet_info_.uncommitted_kv_, aux_tablet_info_.uncommitted_kv_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, other.aux_tablet_info_.committed_kv_, aux_tablet_info_.committed_kv_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, other.auto_inc_seq_, auto_inc_seq_))) { - } else if (OB_FAIL(init_single_complex_addr(allocator, other.medium_info_list_, finish_medium_scn, medium_info_list_))) { + if (OB_FAIL(init_single_complex_addr(block_file, allocator, other.tablet_status_.uncommitted_kv_, tablet_status_.uncommitted_kv_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, other.tablet_status_.committed_kv_, tablet_status_.committed_kv_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, other.aux_tablet_info_.uncommitted_kv_, aux_tablet_info_.uncommitted_kv_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, other.aux_tablet_info_.committed_kv_, aux_tablet_info_.committed_kv_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, other.auto_inc_seq_, auto_inc_seq_))) { + } else if (OB_FAIL(init_single_complex_addr(block_file, allocator, other.medium_info_list_, finish_medium_scn, medium_info_list_))) { } else if (OB_FAIL(update_user_data_from_complex_addr(tablet_status_.committed_kv_, tablet_status_cache_))) { } else if (is_major_merge_type(merge_type)) { extra_medium_info_.last_compaction_type_ = is_major_merge(merge_type) ? compaction::ObMediumCompactionInfo::MAJOR_COMPACTION : compaction::ObMediumCompactionInfo::MEDIUM_COMPACTION; @@ -329,6 +334,7 @@ int ObTabletMdsData::init_for_evict_medium_info( } int ObTabletMdsData::init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &src_addr, ObTabletComplexAddr &dst_addr) @@ -337,7 +343,7 @@ int ObTabletMdsData::init_single_complex_addr( dst_addr.reset(); mds::MdsDumpKV *ptr = nullptr; - if (OB_FAIL(load_mds_dump_kv(allocator, src_addr, ptr))) { + if (OB_FAIL(load_mds_dump_kv(block_file, allocator, src_addr, ptr))) { } else if (nullptr == ptr) { dst_addr.addr_.set_none_addr(); } else { @@ -349,6 +355,7 @@ int ObTabletMdsData::init_single_complex_addr( } int ObTabletMdsData::init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &src_addr, ObTabletComplexAddr &dst_addr) @@ -358,7 +365,7 @@ int ObTabletMdsData::init_single_complex_addr( ObTabletAutoincSeq *ptr = nullptr; ObTabletAutoincSeq *&dst_data = dst_addr.ptr_; - if (OB_FAIL(load_auto_inc_seq(allocator, src_addr, ptr))) { + if (OB_FAIL(load_auto_inc_seq(block_file, allocator, src_addr, ptr))) { } else if (nullptr == ptr) { // ptr is emtpy, no need to copy it, set dst addr to NONE dst_addr.addr_.set_none_addr(); @@ -371,6 +378,7 @@ int ObTabletMdsData::init_single_complex_addr( } int ObTabletMdsData::init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &src_addr, const int64_t finish_medium_scn, @@ -381,7 +389,7 @@ int ObTabletMdsData::init_single_complex_addr( ObTabletDumpedMediumInfo *ptr = nullptr; ObTabletDumpedMediumInfo *&dst_data = dst_addr.ptr_; - if (OB_FAIL(load_array(allocator, src_addr, ptr))) { + if (OB_FAIL(load_array(block_file, allocator, src_addr, ptr))) { } else if (nullptr == ptr) { dst_addr.addr_.set_none_addr(); } else if (OB_FAIL(ObTabletObjLoadHelper::alloc_and_new(allocator, dst_data))) { @@ -424,6 +432,7 @@ void ObTabletMdsData::set_mem_addr() int ObTabletMdsData::load_mds_dump_kv( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &complex_addr, mds::MdsDumpKV *&kv) @@ -451,7 +460,7 @@ int ObTabletMdsData::load_mds_dump_kv( char *buf = nullptr; int64_t len = 0; int64_t pos = 0; - if (OB_FAIL(ObTabletObjLoadHelper::read_from_addr(arena_allocator, addr, buf, len))) { + if (OB_FAIL(ObTabletObjLoadHelper::read_from_addr(block_file, arena_allocator, addr, buf, len))) { } else if (OB_FAIL(ptr->deserialize(allocator, buf, len, pos))) { } else { // for compat logic @@ -479,6 +488,7 @@ int ObTabletMdsData::load_mds_dump_kv( template int ObTabletMdsData::load_array( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &complex_addr, ARRAY *&ret_array) @@ -502,7 +512,7 @@ int ObTabletMdsData::load_array( } } else if (complex_addr.is_disk_object()) { ptr->allocator_ = &allocator; - if (OB_FAIL(read_items(complex_addr.addr_, *ptr, ptr->get_array()))) { + if (OB_FAIL(read_items(block_file, complex_addr.addr_, *ptr, ptr->get_array()))) { } else if (ptr->empty()) { ObTabletObjLoadHelper::free(allocator, ptr); ptr = nullptr; @@ -525,6 +535,7 @@ int ObTabletMdsData::load_array( } int ObTabletMdsData::load_auto_inc_seq( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &complex_addr, ObTabletAutoincSeq *&auto_inc_seq) @@ -551,7 +562,7 @@ int ObTabletMdsData::load_auto_inc_seq( char *io_buf = nullptr; int64_t buf_len = -1; int64_t io_pos = 0; - if (OB_FAIL(ObTabletObjLoadHelper::read_from_addr(io_allocator, complex_addr.addr_, io_buf, buf_len))) { + if (OB_FAIL(ObTabletObjLoadHelper::read_from_addr(block_file, io_allocator, complex_addr.addr_, io_buf, buf_len))) { } else if (OB_FAIL(ptr->deserialize(allocator, io_buf, buf_len, io_pos))) { } else if (!ptr->is_valid()) { // no need to copy @@ -574,6 +585,7 @@ int ObTabletMdsData::load_auto_inc_seq( template int ObTabletMdsData::read_items( + storage_io::BlockOwner &block_file, const ObMetaDiskAddr &addr, ARRAY_STRUCT &input_array_struct, common::ObIArray &array) @@ -587,7 +599,7 @@ int ObTabletMdsData::read_items( if (OB_UNLIKELY(!addr.is_block() || nullptr == allocator)) { ret = OB_INVALID_ARGUMENT; - } else if (OB_FAIL(iter.init(addr))) { + } else if (OB_FAIL(iter.init(block_file, addr))) { } else { while (OB_SUCC(ret)) { info = nullptr; diff --git a/src/storage/tablet/ob_tablet_mds_data.h b/src/storage/tablet/ob_tablet_mds_data.h index 21f92c6bb7..41f0614c84 100644 --- a/src/storage/tablet/ob_tablet_mds_data.h +++ b/src/storage/tablet/ob_tablet_mds_data.h @@ -28,6 +28,8 @@ #include "storage/tablet/ob_tablet_member_wrapper.h" #include "storage/tablet/ob_tablet_full_medium_info.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace common @@ -74,11 +76,13 @@ class ObTabletMdsData void reset(); int init_for_first_creation(); int init_for_mds_table_dump( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletMdsData &mds_table_data, const ObTabletMdsData &base_data, const int64_t finish_medium_scn); int init_for_evict_medium_info( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletMdsData &other, const int64_t finish_medium_scn, @@ -97,15 +101,18 @@ class ObTabletMdsData K_(tablet_status_cache)); public: static int load_mds_dump_kv( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &complex_addr, mds::MdsDumpKV *&kv); template static int load_array( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &complex_addr, ARRAY_STRUCT *&list); static int load_auto_inc_seq( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &complex_addr, ObTabletAutoincSeq *&auto_inc_seq); @@ -131,29 +138,35 @@ class ObTabletMdsData const ObTabletStatus::Status &tablet_status, const ObTabletMdsUserDataType &data_type); static int init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &src_addr, ObTabletComplexAddr &dst_addr); static int init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &src_addr, ObTabletComplexAddr &dst_addr); static int init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &src_addr, const int64_t finish_medium_scn, ObTabletComplexAddr &dst_addr); static int init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &mds_table_data, const ObTabletComplexAddr &base_data, ObTabletComplexAddr &fused_data); static int init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &mds_table_data, const ObTabletComplexAddr &base_data, ObTabletComplexAddr &fused_data); static int init_single_complex_addr( + storage_io::BlockOwner &block_file, common::ObIAllocator &allocator, const ObTabletComplexAddr &mds_table_data, const ObTabletComplexAddr &base_data, @@ -161,6 +174,7 @@ class ObTabletMdsData ObTabletComplexAddr &fused_data); template static int read_items( + storage_io::BlockOwner &block_file, const ObMetaDiskAddr &addr, ARRAY_STRUCT &input_array_struct, common::ObIArray &array); diff --git a/src/storage/tablet/ob_tablet_mds_table_mini_merger.cpp b/src/storage/tablet/ob_tablet_mds_table_mini_merger.cpp index 684c2592a4..815188fac7 100644 --- a/src/storage/tablet/ob_tablet_mds_table_mini_merger.cpp +++ b/src/storage/tablet/ob_tablet_mds_table_mini_merger.cpp @@ -312,7 +312,7 @@ int ObMdsTableMiniMerger::init(compaction::ObTabletMergeCtx &ctx, ObMdsMiniMerge ret = OB_ERR_UNEXPECTED; } else if (OB_UNLIKELY(!storage_schema->is_valid())) { ret = OB_ERR_UNEXPECTED; - } else if (OB_FAIL(data_desc_.init(false/*is ddl*/, *storage_schema, tablet_id, + } else if (OB_FAIL(data_desc_.init(ctx.get_tablet()->block_file(), false/*is ddl*/, *storage_schema, tablet_id, ctx.get_merge_type(), ctx.get_snapshot(), data_version, ctx.static_desc_.micro_index_clustered_, ctx.get_concurrent_cnt(), ctx.static_param_.scn_range_.end_scn_))) { } else if (OB_FAIL(macro_start_seq.set_parallel_degree(0))) { @@ -349,7 +349,7 @@ int ObMdsTableMiniMerger::generate_mds_mini_sstable( } else if (OB_FAIL(sstable_builder_.close(res))) { } else if (CLICK_FAIL(param.init_for_mds(*ctx_, res, *storage_schema_))) { LOG_ERROR("fail to create sstable param for mds", K(ret)); - } else if (CLICK_FAIL(ObTabletCreateDeleteHelper::create_sstable(param, allocator, table_handle))) { + } else if (CLICK_FAIL(ObTabletCreateDeleteHelper::create_sstable(ctx_->get_tablet()->block_file(), param, allocator, table_handle))) { LOG_ERROR("fail to create sstable", K(ret), K(param)); CTX_SET_DIAGNOSE_LOCATION(*ctx_); } else { diff --git a/src/storage/tablet/ob_tablet_obj_load_helper.cpp b/src/storage/tablet/ob_tablet_obj_load_helper.cpp index 9bc46298e8..0835a3e949 100644 --- a/src/storage/tablet/ob_tablet_obj_load_helper.cpp +++ b/src/storage/tablet/ob_tablet_obj_load_helper.cpp @@ -27,6 +27,7 @@ namespace oceanbase namespace storage { int ObTabletObjLoadHelper::read_from_addr( + storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator, const ObMetaDiskAddr &meta_addr, char *&buf, @@ -44,7 +45,7 @@ int ObTabletObjLoadHelper::read_from_addr( read_info.io_desc_.set_mode(ObIOMode::READ); read_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000; ObObjectReadHandle io_handle; - if (OB_FAIL(ObObjectReaderWriter::async_read(read_info, io_handle))) { + if (OB_FAIL(ObObjectReaderWriter::async_read(block_file, read_info, io_handle))) { } else if (OB_FAIL(io_handle.wait())) { } else if (OB_FAIL(io_handle.get_data(allocator, buf, buf_len))) { } diff --git a/src/storage/tablet/ob_tablet_obj_load_helper.h b/src/storage/tablet/ob_tablet_obj_load_helper.h index 0a68dfbc67..4cb8b741de 100644 --- a/src/storage/tablet/ob_tablet_obj_load_helper.h +++ b/src/storage/tablet/ob_tablet_obj_load_helper.h @@ -22,6 +22,8 @@ #include "lib/allocator/ob_allocator.h" #include "lib/oblog/ob_log.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace common @@ -43,6 +45,7 @@ class ObTabletObjLoadHelper static void free(common::ObIAllocator &allocator, T *&ptr); static int read_from_addr( + storage_io::BlockOwner &block_file, common::ObArenaAllocator &allocator, const ObMetaDiskAddr &meta_addr, char *&buf, diff --git a/src/storage/tablet/ob_tablet_persister.cpp b/src/storage/tablet/ob_tablet_persister.cpp index ad4de54995..65af98f812 100644 --- a/src/storage/tablet/ob_tablet_persister.cpp +++ b/src/storage/tablet/ob_tablet_persister.cpp @@ -332,7 +332,7 @@ int ObTabletPersister::inner_persist_and_transform_tablet( ret = OB_INVALID_ARGUMENT; } else if (OB_UNLIKELY(old_tablet.allocator_)) { ret = OB_NOT_SUPPORTED; - } else if (OB_UNLIKELY(!old_tablet.hold_ref_cnt_)) { + } else if (OB_UNLIKELY(!old_tablet.holds_macro_blocks())) { ret = OB_ERR_UNEXPECTED; } else if (OB_FAIL(persister.multi_stats_.acquire_stats("persist_and_transform_only_tablet_meta", time_stats))) { } else if (OB_FAIL(old_tablet.load_macro_info(persister.allocator_, macro_info, in_memory))) { @@ -393,7 +393,7 @@ int ObTabletPersister::modify_and_fill_tablet( int ret = OB_SUCCESS; if (OB_NOT_NULL(old_tablet.allocator_)) { ret = OB_NOT_SUPPORTED; - } else if (OB_UNLIKELY(!old_tablet.hold_ref_cnt_)) { + } else if (OB_UNLIKELY(!old_tablet.holds_macro_blocks())) { ret = OB_ERR_UNEXPECTED; } else { const ObTabletMeta &tablet_meta = old_tablet.get_tablet_meta(); @@ -418,7 +418,8 @@ int ObTabletPersister::modify_and_fill_tablet( persister.print_time_stats(*time_stats, 20_ms, 1_s); new_handle.get_obj()->set_next_tablet_guard(old_tablet.next_tablet_guard_); new_handle.get_obj()->set_tablet_addr(old_tablet.get_tablet_addr()); - if (OB_FAIL(new_handle.get_obj()->inc_macro_ref_cnt())) { + if (old_tablet.block_group_) { + new_handle.get_obj()->block_group_ = old_tablet.block_group_; } } } @@ -534,7 +535,7 @@ int ObTabletPersister::persist_and_fill_tablet( } if (OB_FAIL(ret)) { - } else if (OB_FAIL(linked_writer.init(false, ObMemAttr("ObjLinkWriter")))) { + } else if (OB_FAIL(linked_writer.init(old_tablet.block_file(), false, ObMemAttr("ObjLinkWriter")))) { } else if (OB_FAIL(tablet_macro_info.init(allocator_, block_info_set, &linked_writer))) { } else { arg.tablet_macro_info_addr_.set_none_addr(); @@ -666,21 +667,19 @@ int ObTabletPersister::persist_aggregated_meta( ObObjectWriteInfo write_info; ObObjectWriteHandle handle; ObObjectsWriteCtx write_ctx; - blocksstable::ObStorageObjectOpt curr_opt; const int64_t secondary_meta_size = tablet_macro_info.get_serialize_size(); MacroBlockId macro_id; int64_t offset = 0; int64_t size = 0; if (OB_FAIL(fill_tablet_write_info(allocator_, new_tablet, tablet_macro_info, write_info))) { - } else if (FALSE_IT(build_async_write_start_opt_(curr_opt))) { - } else if (OB_FAIL(meta_service->get_object_raw_reader_writer().async_write(write_info, curr_opt, handle))) { + } else if (OB_FAIL(meta_service->get_object_raw_reader_writer().async_write(write_info, handle))) { } else if (OB_FAIL(handle.get_write_ctx(write_ctx))) { } else if (FALSE_IT(new_tablet->set_tablet_addr(write_ctx.addr_))) { } else if (OB_FAIL(write_ctx.addr_.get_block_addr(macro_id, offset, size))) { } else if (OB_FAIL(new_tablet->set_macro_info_addr(macro_id, offset + (size - secondary_meta_size), secondary_meta_size, ObMetaDiskAddr::DiskType::RAW_BLOCK))) { - } else if (OB_FAIL(macro_iter.init(ObTabletMacroType::MAX, tablet_macro_info))) { - } else if (OB_FAIL(inc_ref_with_macro_iter(*new_tablet, macro_iter))) { + } else if (OB_FAIL(macro_iter.init(new_tablet->block_file(), ObTabletMacroType::MAX, tablet_macro_info))) { + } else if (OB_FAIL(new_tablet->hold_aggregated_blocks(macro_iter))) { } else { space_usage.tablet_clustered_meta_size_ += upper_align(write_ctx.addr_.size(), DIO_READ_ALIGN_SIZE); new_tablet->tablet_meta_.space_usage_ = space_usage; @@ -688,33 +687,6 @@ int ObTabletPersister::persist_aggregated_meta( return ret; } -int ObTabletPersister::inc_ref_with_macro_iter(ObTablet &tablet, ObMacroInfoIterator ¯o_iter) -{ - int ret = OB_SUCCESS; - bool inc_tablet_macro_ref_success = false; - bool inc_other_macro_ref_success = false; - const ObMetaDiskAddr &tablet_addr = tablet.tablet_addr_; - - if (OB_FAIL(ObTablet::inc_addr_ref_cnt(tablet_addr, inc_tablet_macro_ref_success))) { - } else if (OB_FAIL(tablet.inc_ref_with_macro_iter(macro_iter, inc_other_macro_ref_success))) { - } - if (OB_FAIL(ret)) { - if (inc_tablet_macro_ref_success) { - ObTablet::dec_addr_ref_cnt(tablet_addr); - } - if (inc_other_macro_ref_success) { - int tmp_ret = OB_SUCCESS; - if (OB_TMP_FAIL(macro_iter.reuse())) { - } else { - tablet.dec_ref_with_macro_iter(macro_iter); - } - } - } else { - tablet.hold_ref_cnt_ = true; - } - return ret; -} - int ObTabletPersister::fill_tablet_write_info( common::ObArenaAllocator &allocator, const ObTablet *tablet, @@ -900,9 +872,7 @@ int ObTabletPersister::batch_write_sstable_info( int ret = OB_SUCCESS; ObObjectBatchHandle handle; ObLocalStorageMetaService *meta_service = ::oceanbase::share::server_service<::oceanbase::storage::ObLocalStorageMetaService>(); - blocksstable::ObStorageObjectOpt curr_opt; - build_async_write_start_opt_(curr_opt); - if (OB_FAIL(meta_service->get_object_reader_writer().async_batch_write(write_infos, handle, curr_opt/*OUTPUT*/))) { + if (OB_FAIL(meta_service->get_object_reader_writer().async_batch_write(write_infos, handle))) { } else if (OB_FAIL(handle.batch_get_write_ctx(write_ctxs))) { } else { for (int64_t i = 0; OB_SUCC(ret) && i < write_ctxs.count(); ++i) { @@ -923,12 +893,6 @@ int ObTabletPersister::batch_write_sstable_info( return ret; } -void ObTabletPersister::build_async_write_start_opt_( - blocksstable::ObStorageObjectOpt &start_opt) const -{ - start_opt.set_meta_macro_object_opt(); -} - int ObTabletPersister::persist_sstable_linked_block_if_need( ObArenaAllocator &allocator, ObITable * const table, @@ -1228,12 +1192,10 @@ int ObTabletPersister::write_and_fill_args( ? ObCtxIds::MERGE_RESERVE_CTX_ID : ObCtxIds::DEFAULT_CTX_ID; write_ctxs.set_attr(lib::ObMemAttr("WriteCtxs", ctx_id)); - blocksstable::ObStorageObjectOpt curr_opt; if (OB_UNLIKELY(total_addr_cnt != write_infos.count() + none_addr_cnt)) { ret = OB_INVALID_ARGUMENT; - } else if (FALSE_IT(build_async_write_start_opt_(curr_opt))) { - } else if (OB_FAIL(reader_writer.async_batch_write(write_infos, handle, curr_opt))) { + } else if (OB_FAIL(reader_writer.async_batch_write(write_infos, handle))) { } else if (OB_FAIL(handle.batch_get_write_ctx(write_ctxs))) { } else if (OB_UNLIKELY(write_infos.count() != write_ctxs.count())) { ret = OB_ERR_UNEXPECTED; @@ -1300,7 +1262,7 @@ int ObTabletPersister::load_table_store( read_info.io_desc_.set_mode(ObIOMode::READ); read_info.io_timeout_ms_ = config::_data_storage_io_timeout() / 1000; if (OB_FAIL(multi_stats_.acquire_stats("load_table_store", time_stats))) { - } else if (OB_FAIL(ObObjectReaderWriter::async_read(read_info, io_handle))) { + } else if (OB_FAIL(ObObjectReaderWriter::async_read(tablet.block_file(), read_info, io_handle))) { } else if (OB_FAIL(io_handle.wait())) { } else if (FALSE_IT(time_stats->click("read_io"))) { } else if (OB_FAIL(io_handle.get_data(io_allocator, io_buf, buf_len))) { @@ -1334,7 +1296,7 @@ int ObTabletPersister::transform_tablet_memory_footprint( ObTabletPersister persister(param, DEFAULT_CTX_ID); ObMultiTimeStats::TimeStats *time_stats = nullptr; if (OB_FAIL(persister.multi_stats_.acquire_stats("transform_tablet_memory_footprint", time_stats))) { - } else if (OB_UNLIKELY(!old_tablet.hold_ref_cnt_)) { + } else if (OB_UNLIKELY(!old_tablet.holds_macro_blocks())) { ret = OB_ERR_UNEXPECTED; } else if (OB_FAIL(convert_tablet_to_mem_arg(old_tablet, arg))) { } else if (FALSE_IT(time_stats->click("convert_tablet_to_mem_arg"))) { @@ -1344,7 +1306,7 @@ int ObTabletPersister::transform_tablet_memory_footprint( ObTablet *tablet = reinterpret_cast(buf); tablet->set_next_tablet_guard(old_tablet.next_tablet_guard_); tablet->set_tablet_addr(old_tablet.get_tablet_addr()); - tablet->hold_ref_cnt_ = old_tablet.hold_ref_cnt_; + tablet->block_group_ = old_tablet.block_group_; persister.print_time_stats(*time_stats, 20_ms, 1_s); } return ret; diff --git a/src/storage/tablet/ob_tablet_persister.h b/src/storage/tablet/ob_tablet_persister.h index 00c387979b..121151502a 100644 --- a/src/storage/tablet/ob_tablet_persister.h +++ b/src/storage/tablet/ob_tablet_persister.h @@ -24,7 +24,6 @@ #include "storage/blockstore/ob_object_reader_writer.h" #include "storage/tablet/ob_tablet_complex_addr.h" #include "storage/tablet/ob_tablet_dumped_medium_info.h" -#include "storage/blocksstable/ob_object_manager.h" #include "storage/blocksstable/ob_macro_block_id.h" namespace oceanbase @@ -256,12 +255,10 @@ class ObTabletPersister final ObBlockInfoSet &block_info_set); static int transform_empty_shell(const ObTabletPersisterParam ¶m, const ObTablet &old_tablet, ObTabletHandle &new_handle); private: - void build_async_write_start_opt_(blocksstable::ObStorageObjectOpt &start_opt) const; static int inner_persist_and_transform_tablet( const ObTabletPersisterParam ¶m, const ObTablet &old_tablet, ObTabletHandle &new_handle); - static int inc_ref_with_macro_iter(ObTablet &tablet, ObMacroInfoIterator ¯o_iter); static int do_copy_ids( blocksstable::ObMacroIdIterator &iter, ObBlockInfoSet::TabletMacroSet &id_set); diff --git a/src/storage/tablet/ob_tablet_table_store.cpp b/src/storage/tablet/ob_tablet_table_store.cpp index 077abb2665..62eaa1ff00 100644 --- a/src/storage/tablet/ob_tablet_table_store.cpp +++ b/src/storage/tablet/ob_tablet_table_store.cpp @@ -113,11 +113,11 @@ int ObTabletTableStore::deserialize( } else if (OB_UNLIKELY(version_ != TABLE_STORE_VERSION)) { ret = OB_ERR_UNEXPECTED; } else if (OB_FAIL(serialization::decode_i64(buf, data_len, pos, &serialized_length))) { - } else if (pos - start_pos < serialized_length && OB_FAIL(major_tables_.deserialize(allocator, buf, data_len, pos))) { - } else if (pos - start_pos < serialized_length && OB_FAIL(minor_tables_.deserialize(allocator, buf, data_len, pos))) { - } else if (pos - start_pos < serialized_length && OB_FAIL(ddl_sstables_.deserialize(allocator, buf, data_len, pos))) { - } else if (pos - start_pos < serialized_length && OB_FAIL(meta_major_tables_.deserialize(allocator, buf, data_len, pos))) { - } else if (pos - start_pos < serialized_length && OB_FAIL(mds_sstables_.deserialize(allocator, buf, data_len, pos))) { + } else if (pos - start_pos < serialized_length && OB_FAIL(major_tables_.deserialize(tablet.block_file(), allocator, buf, data_len, pos))) { + } else if (pos - start_pos < serialized_length && OB_FAIL(minor_tables_.deserialize(tablet.block_file(), allocator, buf, data_len, pos))) { + } else if (pos - start_pos < serialized_length && OB_FAIL(ddl_sstables_.deserialize(tablet.block_file(), allocator, buf, data_len, pos))) { + } else if (pos - start_pos < serialized_length && OB_FAIL(meta_major_tables_.deserialize(tablet.block_file(), allocator, buf, data_len, pos))) { + } else if (pos - start_pos < serialized_length && OB_FAIL(mds_sstables_.deserialize(tablet.block_file(), allocator, buf, data_len, pos))) { } else if (OB_FAIL(build_memtable_array(tablet))) { } else if (OB_FAIL(pull_ddl_memtables(allocator, tablet))) { } else if (pos - start_pos < serialized_length) { @@ -420,69 +420,6 @@ void ObTabletTableStore::try_cache_local_sstables(common::ObArenaAllocator &allo } #undef TRY_CACHE_SSTABLE_META -int ObTabletTableStore::inc_macro_ref() const -{ - int ret = OB_SUCCESS; - bool major_success = false; - bool meta_major_success = false; - bool minor_success = false; - bool ddl_success = false; - bool mds_success = false; - - if (OB_UNLIKELY(!is_inited_)) { - ret = OB_NOT_INIT; - } else if (!major_tables_.empty() - && OB_FAIL(major_tables_.inc_macro_ref(major_success))) { - } else if (!minor_tables_.empty() - && OB_FAIL(minor_tables_.inc_macro_ref(minor_success))) { - } else if (!ddl_sstables_.empty() - && OB_FAIL(ddl_sstables_.inc_macro_ref(ddl_success))) { - } else if (!meta_major_tables_.empty() - && OB_FAIL(meta_major_tables_.inc_macro_ref(meta_major_success))) { - } else if (!mds_sstables_.empty() - && OB_FAIL(mds_sstables_.inc_macro_ref(mds_success))) { - } - - if (OB_FAIL(ret)) { - if (major_success) { - major_tables_.dec_macro_ref(); - } - if (minor_success) { - minor_tables_.dec_macro_ref(); - } - if (ddl_success) { - ddl_sstables_.dec_macro_ref(); - } - if (meta_major_success) { - meta_major_tables_.dec_macro_ref(); - } - if (mds_success) { - mds_sstables_.dec_macro_ref(); - } - } - - return ret; -} - -void ObTabletTableStore::dec_macro_ref() const -{ - if (!major_tables_.empty()) { - major_tables_.dec_macro_ref(); - } - if (!minor_tables_.empty()) { - minor_tables_.dec_macro_ref(); - } - if (!ddl_sstables_.empty()) { - ddl_sstables_.dec_macro_ref(); - } - if (!meta_major_tables_.empty()) { - meta_major_tables_.dec_macro_ref(); - } - if (!mds_sstables_.empty()) { - mds_sstables_.dec_macro_ref(); - } -} - bool ObTabletTableStore::check_read_tables( const ObTablet &tablet, const int64_t snapshot_version, @@ -665,6 +602,7 @@ int ObTabletTableStore::get_table( ObStorageMetaHandle sst_handle; ObSSTable *sstable = nullptr; if (OB_FAIL(ObCacheSSTableHelper::load_sstable( + static_cast(table)->block_file(), static_cast(table)->get_addr(), sst_handle))) { } else if (OB_FAIL(sst_handle.get_sstable(sstable))) { } else if (OB_FAIL(handle.set_sstable(sstable, sst_handle))) { diff --git a/src/storage/tablet/ob_tablet_table_store.h b/src/storage/tablet/ob_tablet_table_store.h index a79b09bb10..7635603ecc 100644 --- a/src/storage/tablet/ob_tablet_table_store.h +++ b/src/storage/tablet/ob_tablet_table_store.h @@ -150,8 +150,6 @@ class ObTabletTableStore : public ObIStorageMetaObj return (is_mds && table.is_mds_sstable()) || (!is_mds && table.is_minor_sstable()); } - int inc_macro_ref() const; - void dec_macro_ref() const; // called by SSTable Garbage Collector Thread int need_remove_old_table( const int64_t multi_version_start, diff --git a/src/storage/tablet/ob_tablet_table_store_iterator.cpp b/src/storage/tablet/ob_tablet_table_store_iterator.cpp index 42d08c632c..15fcabe4d2 100644 --- a/src/storage/tablet/ob_tablet_table_store_iterator.cpp +++ b/src/storage/tablet/ob_tablet_table_store_iterator.cpp @@ -210,7 +210,7 @@ int ObTableStoreIterator::get_table_ptr_with_meta_handle( ObStorageMetaHandle sstable_meta_hdl; ObSSTable *sstable = nullptr; - if (OB_FAIL(ObCacheSSTableHelper::load_sstable(table->get_addr(), sstable_meta_hdl))) { + if (OB_FAIL(ObCacheSSTableHelper::load_sstable(table->block_file(), table->get_addr(), sstable_meta_hdl))) { } else if (OB_FAIL(sstable_handle_array_.push_back(sstable_meta_hdl))) { } else if (OB_FAIL(sstable_meta_hdl.get_sstable(sstable))) { } else { diff --git a/src/storage/tx_storage/ob_access_service.cpp b/src/storage/tx_storage/ob_access_service.cpp index 864370fb6c..06c0f5de35 100644 --- a/src/storage/tx_storage/ob_access_service.cpp +++ b/src/storage/tx_storage/ob_access_service.cpp @@ -16,6 +16,7 @@ #define USING_LOG_PREFIX STORAGE +#include "storage/blocksstable/ob_storage_object_handle.h" #include #include "ob_access_service.h" #include "storage/tablelock/ob_table_lock_rpc_struct.h" @@ -147,15 +148,8 @@ ObAccessService::~ObAccessService() destroy(); } -int ObAccessService::server_module_init(ObAccessService* &access_service) -{ - int ret = OB_SUCCESS; - - return access_service->init(::oceanbase::share::server_service<::oceanbase::storage::ObLSService>()); -} - int ObAccessService::init( - ObLSService *ls_service) + ObLSService *ls_service, storage_io::BlockOwner &blocks) { int ret = OB_SUCCESS; if (IS_INIT) { @@ -164,6 +158,7 @@ int ObAccessService::init( ret = OB_INVALID_ARGUMENT; } else { ls_svr_ = ls_service; + blocks_ = &blocks; is_inited_ = true; } return ret; @@ -173,6 +168,7 @@ void ObAccessService::destroy() { if (IS_INIT) { ls_svr_ = nullptr; + blocks_ = nullptr; is_inited_ = false; } } @@ -1254,10 +1250,17 @@ int ObAccessService::run_io_benchmark( 1024L * 1024L * 1024L / OB_DEFAULT_MACRO_BLOCK_SIZE; const int64_t max_calibration_block_count = 20LL * 1024LL * 1024LL * 1024LL / OB_DEFAULT_MACRO_BLOCK_SIZE; - const int64_t free_block_count = - OB_STORAGE_OBJECT_MGR.get_free_macro_block_count(); - const int64_t total_block_count = - OB_STORAGE_OBJECT_MGR.get_total_macro_block_count(); + if (blocks_ == nullptr) { return OB_NOT_INIT; } + storage_io::BlockStats stats{}; + const bool has_stats = common::convert_block_status(blocks_->block_stats(stats)) == OB_SUCCESS; + const int64_t free_block_count = has_stats ? stats.free_blocks : 0; + const int64_t total_block_count = has_stats ? stats.total_blocks : 0; + const auto read_block = [&](const blocksstable::MacroBlockId &id, int64_t offset, int64_t size) { + const auto request = common::make_request_options( + descriptor, storage_io::RequestMode::Read, offset, size, MAX_IO_WAIT_TIME_MS); + return common::accept_io_request(blocks_->submit_block( + {static_cast(id.block_index()), id.write_seq()}, request, {}, nullptr), io_handle); + }; int64_t benchmark_block_count = free_block_count * 0.2; const int64_t max_random_read_offset = OB_DEFAULT_MACRO_BLOCK_SIZE - load_size; @@ -1276,11 +1279,8 @@ int ObAccessService::run_io_benchmark( } for (int64_t i = 0; OB_SUCC(ret) && i < benchmark_block_count; ++i) { - blocksstable::ObStorageObjectOpt object_opt; - object_opt.set_data_macro_object_opt(); blocksstable::ObStorageObjectHandle block_handle; - if (OB_FAIL(OB_STORAGE_OBJECT_MGR.alloc_object( - object_opt, block_handle))) { + if (OB_FAIL(block_handle.allocate(*blocks_))) { } else if (OB_FAIL(block_handles.push_back(block_handle))) { } } @@ -1292,8 +1292,7 @@ int ObAccessService::run_io_benchmark( benchmark_block_count - 1); const int64_t offset = ObRandom::rand(0, max_random_read_offset); const int64_t begin_ts = ObTimeUtility::fast_current_time(); - if (OB_FAIL(OB_SERVER_BLOCK_MGR.submit_read(block_handles[block_idx].get_macro_id(), offset, load_size, - descriptor, MAX_IO_WAIT_TIME_MS, nullptr, io_handle))) { + if (OB_FAIL(read_block(block_handles[block_idx].get_macro_id(), offset, load_size))) { } else if (OB_FAIL(io_handle.wait())) { } else { ++io_count; @@ -1315,8 +1314,7 @@ int ObAccessService::run_io_benchmark( io_handle.reset(); const int64_t block_idx = io_count; const int64_t begin_ts = ObTimeUtility::fast_current_time(); - if (OB_FAIL(OB_SERVER_BLOCK_MGR.submit_read(block_handles[block_idx].get_macro_id(), 0, OB_DEFAULT_MACRO_BLOCK_SIZE, - descriptor, MAX_IO_WAIT_TIME_MS, nullptr, io_handle))) { + if (OB_FAIL(read_block(block_handles[block_idx].get_macro_id(), 0, OB_DEFAULT_MACRO_BLOCK_SIZE))) { } else if (OB_FAIL(io_handle.wait())) { } else { ++io_count; diff --git a/src/storage/tx_storage/ob_access_service.h b/src/storage/tx_storage/ob_access_service.h index 790be78960..ad2f686194 100644 --- a/src/storage/tx_storage/ob_access_service.h +++ b/src/storage/tx_storage/ob_access_service.h @@ -27,6 +27,8 @@ #include "storage/ls/ob_ls_tablet_service.h" #include "storage/access/ob_table_scan_range.h" +namespace oceanbase::storage_io { struct BlockOwner; } + namespace oceanbase { namespace common { @@ -76,8 +78,7 @@ class ObAccessService : public common::ObITabletScan, public: ObAccessService(); virtual ~ObAccessService(); - int init(ObLSService *ls_service); - static int server_module_init(ObAccessService* &access_service); + int init(ObLSService *ls_service, storage_io::BlockOwner &blocks); void destroy(); public: @@ -329,6 +330,7 @@ class ObAccessService : public common::ObITabletScan, ObNewRowIterator *&result); private: + storage_io::BlockOwner *blocks_ = nullptr; bool is_inited_; ObLSService *ls_svr_; }; diff --git a/src/storage/tx_storage/ob_ls_service.cpp b/src/storage/tx_storage/ob_ls_service.cpp index 261348716d..0417148cc7 100644 --- a/src/storage/tx_storage/ob_ls_service.cpp +++ b/src/storage/tx_storage/ob_ls_service.cpp @@ -137,12 +137,7 @@ int ObLSService::wait() return ret; } -int ObLSService::server_module_init(ObLSService* &ls_service) -{ - return ls_service->init(); -} - -int ObLSService::init() +int ObLSService::init(storage_io::BlockOwner &block_file) { int ret = OB_SUCCESS; const char *OB_LS_SERVICE = "LSSvr"; @@ -154,6 +149,7 @@ int ObLSService::init() OB_LS_SERVICE, LS_ALLOC_TOTAL_LIMIT))) { } else { + block_file_ = &block_file; is_inited_ = true; } if (OB_FAIL(ret)) { @@ -191,7 +187,7 @@ int ObLSService::inner_create_ls_(const ObRestoreStatus &restore_status, void *buf = NULL; if (OB_ISNULL(buf = ls_allocator_.alloc(sizeof(ObLS), memattr))) { ret = OB_ALLOCATE_MEMORY_FAILED; - } else if (FALSE_IT(ls = new (buf) ObLS())) { + } else if (FALSE_IT(ls = new (buf) ObLS(*block_file_))) { } else if (OB_FAIL(ls->init(restore_status, create_scn, clog_base_lsn))) { } diff --git a/src/storage/tx_storage/ob_ls_service.h b/src/storage/tx_storage/ob_ls_service.h index f3dd61e6bf..cfe7261306 100644 --- a/src/storage/tx_storage/ob_ls_service.h +++ b/src/storage/tx_storage/ob_ls_service.h @@ -39,8 +39,7 @@ class ObLSService ObLSService(); ~ObLSService(); - static int server_module_init(ObLSService* &ls_service); - int init(); + int init(storage_io::BlockOwner &block_file); int start(); int stop(); int wait(); @@ -123,6 +122,7 @@ class ObLSService void del_ls_after_create_ls_failed_(ObLSCreateState& ls_create_state, ObLS *ls); private: + storage_io::BlockOwner *block_file_ = nullptr; bool is_inited_; bool is_running_; // used by create/remove, only can be used after start and before stop. bool is_stopped_; diff --git a/src/storage/tx_table/ob_tx_data_memtable.cpp b/src/storage/tx_table/ob_tx_data_memtable.cpp index dc5db9e8ee..e094cb89a0 100644 --- a/src/storage/tx_table/ob_tx_data_memtable.cpp +++ b/src/storage/tx_table/ob_tx_data_memtable.cpp @@ -483,7 +483,7 @@ int ObTxDataMemtable::get_past_commit_versions_(ObCommitVersionsArray &past_comm ObSSTable *tmp_sstable = nullptr; if (sstable->is_loaded()) { tmp_sstable = sstable; - } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(sstable->get_addr(), sstable_handle))) { + } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(sstable->block_file(), sstable->get_addr(), sstable_handle))) { } else if (OB_FAIL(sstable_handle.get_sstable(tmp_sstable))) { } if (OB_SUCC(ret)) { diff --git a/src/storage/tx_table/ob_tx_data_table.cpp b/src/storage/tx_table/ob_tx_data_table.cpp index ad4f191673..9547b6c212 100644 --- a/src/storage/tx_table/ob_tx_data_table.cpp +++ b/src/storage/tx_table/ob_tx_data_table.cpp @@ -996,7 +996,7 @@ int ObTxDataTable::update_calc_upper_trans_version_cache_(ObITable *table) ObStorageMetaHandle sstable_handle; ObSSTable *sstable = static_cast(table); if (sstable->is_loaded()) { - } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(sstable->get_addr(), sstable_handle))) { + } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(sstable->block_file(), sstable->get_addr(), sstable_handle))) { } else if (OB_FAIL(sstable_handle.get_sstable(sstable))) { } if (OB_SUCC(ret)) { diff --git a/src/storage/tx_table/ob_tx_table.cpp b/src/storage/tx_table/ob_tx_table.cpp index a3fb97d721..88d5809a5a 100644 --- a/src/storage/tx_table/ob_tx_table.cpp +++ b/src/storage/tx_table/ob_tx_table.cpp @@ -418,7 +418,7 @@ int ObTxTable::load_tx_ctx_table_() ObStorageMetaHandle sstable_handle; ObSSTable *sstable = static_cast(sstables[0]); if (sstable->is_loaded()) { - } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(sstable->get_addr(), sstable_handle))) { + } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(sstable->block_file(), sstable->get_addr(), sstable_handle))) { } else if (OB_FAIL(sstable_handle.get_sstable(sstable))) { } if (FAILEDx(restore_tx_ctx_table_(*sstable))) { diff --git a/src/storage/tx_table/ob_tx_table_iterator.cpp b/src/storage/tx_table/ob_tx_table_iterator.cpp index 2986383686..cb75467384 100644 --- a/src/storage/tx_table/ob_tx_table_iterator.cpp +++ b/src/storage/tx_table/ob_tx_table_iterator.cpp @@ -513,7 +513,7 @@ int ObTxDataSingleRowGetter::get_row_from_sstables_(blocksstable::ObDatumRowkey ret = OB_ERR_SYS; STORAGE_LOG(ERROR, "Unexpected null table", KR(ret), K(i), K(sstables)); } else if (table->is_loaded()) { - } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(table->get_addr(), sstable_handle))) { + } else if (OB_FAIL(ObCacheSSTableHelper::load_sstable(table->block_file(), table->get_addr(), sstable_handle))) { } else if (OB_FAIL(sstable_handle.get_sstable(table))) { } if (FAILEDx(table->get(iter_param, access_context, row_key, row_iter))) {