Line data Source code
1 : use anyhow::{bail, ensure, Context, Result};
2 : use pageserver_api::shard::TenantShardId;
3 : use std::{collections::HashMap, sync::Arc};
4 : use tracing::trace;
5 : use utils::{
6 : id::TimelineId,
7 : lsn::{AtomicLsn, Lsn},
8 : };
9 :
10 : use crate::{
11 : config::PageServerConf,
12 : metrics::TimelineMetrics,
13 : tenant::{
14 : layer_map::{BatchedUpdates, LayerMap},
15 : storage_layer::{
16 : AsLayerDesc, InMemoryLayer, Layer, PersistentLayerDesc, PersistentLayerKey,
17 : ResidentLayer,
18 : },
19 : },
20 : };
21 :
22 : /// Provides semantic APIs to manipulate the layer map.
23 : #[derive(Default)]
24 : pub(crate) struct LayerManager {
25 : layer_map: LayerMap,
26 : layer_fmgr: LayerFileManager<Layer>,
27 : }
28 :
29 : impl LayerManager {
30 126150 : pub(crate) fn get_from_desc(&self, desc: &PersistentLayerDesc) -> Layer {
31 126150 : self.layer_fmgr.get_from_desc(desc)
32 126150 : }
33 :
34 : /// Get an immutable reference to the layer map.
35 : ///
36 : /// We expect users only to be able to get an immutable layer map. If users want to make modifications,
37 : /// they should use the below semantic APIs. This design makes us step closer to immutable storage state.
38 630305 : pub(crate) fn layer_map(&self) -> &LayerMap {
39 630305 : &self.layer_map
40 630305 : }
41 :
42 : /// Called from `load_layer_map`. Initialize the layer manager with:
43 : /// 1. all on-disk layers
44 : /// 2. next open layer (with disk disk_consistent_lsn LSN)
45 6 : pub(crate) fn initialize_local_layers(
46 6 : &mut self,
47 6 : on_disk_layers: Vec<Layer>,
48 6 : next_open_layer_at: Lsn,
49 6 : ) {
50 6 : let mut updates = self.layer_map.batch_update();
51 22 : for layer in on_disk_layers {
52 16 : Self::insert_historic_layer(layer, &mut updates, &mut self.layer_fmgr);
53 16 : }
54 6 : updates.flush();
55 6 : self.layer_map.next_open_layer_at = Some(next_open_layer_at);
56 6 : }
57 :
58 : /// Initialize when creating a new timeline, called in `init_empty_layer_map`.
59 314 : pub(crate) fn initialize_empty(&mut self, next_open_layer_at: Lsn) {
60 314 : self.layer_map.next_open_layer_at = Some(next_open_layer_at);
61 314 : }
62 :
63 : /// Open a new writable layer to append data if there is no open layer, otherwise return the current open layer,
64 : /// called within `get_layer_for_write`.
65 3648020 : pub(crate) async fn get_layer_for_write(
66 3648020 : &mut self,
67 3648020 : lsn: Lsn,
68 3648020 : last_record_lsn: Lsn,
69 3648020 : conf: &'static PageServerConf,
70 3648020 : timeline_id: TimelineId,
71 3648020 : tenant_shard_id: TenantShardId,
72 3648020 : ) -> Result<Arc<InMemoryLayer>> {
73 3648020 : ensure!(lsn.is_aligned());
74 :
75 3648020 : ensure!(
76 3648020 : lsn > last_record_lsn,
77 0 : "cannot modify relation after advancing last_record_lsn (incoming_lsn={}, last_record_lsn={})",
78 : lsn,
79 : last_record_lsn,
80 : );
81 :
82 : // Do we have a layer open for writing already?
83 3648020 : let layer = if let Some(open_layer) = &self.layer_map.open_layer {
84 3647208 : if open_layer.get_lsn_range().start > lsn {
85 0 : bail!(
86 0 : "unexpected open layer in the future: open layers starts at {}, write lsn {}",
87 0 : open_layer.get_lsn_range().start,
88 0 : lsn
89 0 : );
90 3647208 : }
91 3647208 :
92 3647208 : Arc::clone(open_layer)
93 : } else {
94 : // No writeable layer yet. Create one.
95 812 : let start_lsn = self
96 812 : .layer_map
97 812 : .next_open_layer_at
98 812 : .context("No next open layer found")?;
99 :
100 812 : trace!(
101 0 : "creating in-memory layer at {}/{} for record at {}",
102 0 : timeline_id,
103 0 : start_lsn,
104 0 : lsn
105 0 : );
106 :
107 812 : let new_layer =
108 812 : InMemoryLayer::create(conf, timeline_id, tenant_shard_id, start_lsn).await?;
109 812 : let layer = Arc::new(new_layer);
110 812 :
111 812 : self.layer_map.open_layer = Some(layer.clone());
112 812 : self.layer_map.next_open_layer_at = None;
113 812 :
114 812 : layer
115 : };
116 :
117 3648020 : Ok(layer)
118 3648020 : }
119 :
120 : /// Called from `freeze_inmem_layer`, returns true if successfully frozen.
121 698 : pub(crate) async fn try_freeze_in_memory_layer(
122 698 : &mut self,
123 698 : lsn: Lsn,
124 698 : last_freeze_at: &AtomicLsn,
125 698 : ) {
126 698 : let Lsn(last_record_lsn) = lsn;
127 698 : let end_lsn = Lsn(last_record_lsn + 1);
128 :
129 698 : if let Some(open_layer) = &self.layer_map.open_layer {
130 692 : let open_layer_rc = Arc::clone(open_layer);
131 692 : // Does this layer need freezing?
132 692 : open_layer.freeze(end_lsn).await;
133 :
134 : // The layer is no longer open, update the layer map to reflect this.
135 : // We will replace it with on-disk historics below.
136 692 : self.layer_map.frozen_layers.push_back(open_layer_rc);
137 692 : self.layer_map.open_layer = None;
138 692 : self.layer_map.next_open_layer_at = Some(end_lsn);
139 6 : }
140 :
141 : // Even if there was no layer to freeze, advance last_freeze_at to last_record_lsn+1: this
142 : // accounts for regions in the LSN range where we might have ingested no data due to sharding.
143 698 : last_freeze_at.store(end_lsn);
144 698 : }
145 :
146 : /// Add image layers to the layer map, called from `create_image_layers`.
147 604 : pub(crate) fn track_new_image_layers(
148 604 : &mut self,
149 604 : image_layers: &[ResidentLayer],
150 604 : metrics: &TimelineMetrics,
151 604 : ) {
152 604 : let mut updates = self.layer_map.batch_update();
153 712 : for layer in image_layers {
154 108 : Self::insert_historic_layer(layer.as_ref().clone(), &mut updates, &mut self.layer_fmgr);
155 108 :
156 108 : // record these here instead of Layer::finish_creating because otherwise partial
157 108 : // failure with create_image_layers would balloon up the physical size gauge. downside
158 108 : // is that all layers need to be created before metrics are updated.
159 108 : metrics.record_new_file_metrics(layer.layer_desc().file_size);
160 108 : }
161 604 : updates.flush();
162 604 : }
163 :
164 : /// Flush a frozen layer and add the written delta layer to the layer map.
165 692 : pub(crate) fn finish_flush_l0_layer(
166 692 : &mut self,
167 692 : delta_layer: Option<&ResidentLayer>,
168 692 : frozen_layer_for_check: &Arc<InMemoryLayer>,
169 692 : metrics: &TimelineMetrics,
170 692 : ) {
171 692 : let inmem = self
172 692 : .layer_map
173 692 : .frozen_layers
174 692 : .pop_front()
175 692 : .expect("there must be a inmem layer to flush");
176 692 :
177 692 : // Only one task may call this function at a time (for this
178 692 : // timeline). If two tasks tried to flush the same frozen
179 692 : // layer to disk at the same time, that would not work.
180 692 : assert_eq!(Arc::as_ptr(&inmem), Arc::as_ptr(frozen_layer_for_check));
181 :
182 692 : if let Some(l) = delta_layer {
183 598 : let mut updates = self.layer_map.batch_update();
184 598 : Self::insert_historic_layer(l.as_ref().clone(), &mut updates, &mut self.layer_fmgr);
185 598 : metrics.record_new_file_metrics(l.layer_desc().file_size);
186 598 : updates.flush();
187 598 : }
188 692 : }
189 :
190 : /// Called when compaction is completed.
191 42 : pub(crate) fn finish_compact_l0(
192 42 : &mut self,
193 42 : compact_from: &[Layer],
194 42 : compact_to: &[ResidentLayer],
195 42 : metrics: &TimelineMetrics,
196 42 : ) {
197 42 : let mut updates = self.layer_map.batch_update();
198 284 : for l in compact_to {
199 242 : Self::insert_historic_layer(l.as_ref().clone(), &mut updates, &mut self.layer_fmgr);
200 242 : metrics.record_new_file_metrics(l.layer_desc().file_size);
201 242 : }
202 484 : for l in compact_from {
203 442 : Self::delete_historic_layer(l, &mut updates, &mut self.layer_fmgr);
204 442 : }
205 42 : updates.flush();
206 42 : }
207 :
208 : /// Called when garbage collect has selected the layers to be removed.
209 6 : pub(crate) fn finish_gc_timeline(&mut self, gc_layers: &[Layer]) {
210 6 : let mut updates = self.layer_map.batch_update();
211 14 : for doomed_layer in gc_layers {
212 8 : Self::delete_historic_layer(doomed_layer, &mut updates, &mut self.layer_fmgr);
213 8 : }
214 6 : updates.flush()
215 6 : }
216 :
217 : /// Helper function to insert a layer into the layer map and file manager.
218 964 : fn insert_historic_layer(
219 964 : layer: Layer,
220 964 : updates: &mut BatchedUpdates<'_>,
221 964 : mapping: &mut LayerFileManager<Layer>,
222 964 : ) {
223 964 : updates.insert_historic(layer.layer_desc().clone());
224 964 : mapping.insert(layer);
225 964 : }
226 :
227 : /// Removes the layer from local FS (if present) and from memory.
228 : /// Remote storage is not affected by this operation.
229 450 : fn delete_historic_layer(
230 450 : // we cannot remove layers otherwise, since gc and compaction will race
231 450 : layer: &Layer,
232 450 : updates: &mut BatchedUpdates<'_>,
233 450 : mapping: &mut LayerFileManager<Layer>,
234 450 : ) {
235 450 : let desc = layer.layer_desc();
236 450 :
237 450 : // TODO Removing from the bottom of the layer map is expensive.
238 450 : // Maybe instead discard all layer map historic versions that
239 450 : // won't be needed for page reconstruction for this timeline,
240 450 : // and mark what we can't delete yet as deleted from the layer
241 450 : // map index without actually rebuilding the index.
242 450 : updates.remove_historic(desc);
243 450 : mapping.remove(layer);
244 450 : layer.delete_on_drop();
245 450 : }
246 :
247 20 : pub(crate) fn likely_resident_layers(&self) -> impl Iterator<Item = Layer> + '_ {
248 20 : // for small layer maps, we most likely have all resident, but for larger more are likely
249 20 : // to be evicted assuming lots of layers correlated with longer lifespan.
250 20 :
251 24 : self.layer_map().iter_historic_layers().filter_map(|desc| {
252 24 : self.layer_fmgr
253 24 : .0
254 24 : .get(&desc.key())
255 24 : .filter(|l| l.is_likely_resident())
256 24 : .cloned()
257 24 : })
258 20 : }
259 :
260 242 : pub(crate) fn contains(&self, layer: &Layer) -> bool {
261 242 : self.layer_fmgr.contains(layer)
262 242 : }
263 : }
264 :
265 : pub(crate) struct LayerFileManager<T>(HashMap<PersistentLayerKey, T>);
266 :
267 : impl<T> Default for LayerFileManager<T> {
268 320 : fn default() -> Self {
269 320 : Self(HashMap::default())
270 320 : }
271 : }
272 :
273 : impl<T: AsLayerDesc + Clone> LayerFileManager<T> {
274 126150 : fn get_from_desc(&self, desc: &PersistentLayerDesc) -> T {
275 126150 : // The assumption for the `expect()` is that all code maintains the following invariant:
276 126150 : // A layer's descriptor is present in the LayerMap => the LayerFileManager contains a layer for the descriptor.
277 126150 : self.0
278 126150 : .get(&desc.key())
279 126150 : .with_context(|| format!("get layer from desc: {}", desc.filename()))
280 126150 : .expect("not found")
281 126150 : .clone()
282 126150 : }
283 :
284 964 : pub(crate) fn insert(&mut self, layer: T) {
285 964 : let present = self.0.insert(layer.layer_desc().key(), layer.clone());
286 964 : if present.is_some() && cfg!(debug_assertions) {
287 0 : panic!("overwriting a layer: {:?}", layer.layer_desc())
288 964 : }
289 964 : }
290 :
291 242 : pub(crate) fn contains(&self, layer: &T) -> bool {
292 242 : self.0.contains_key(&layer.layer_desc().key())
293 242 : }
294 :
295 450 : pub(crate) fn remove(&mut self, layer: &T) {
296 450 : let present = self.0.remove(&layer.layer_desc().key());
297 450 : if present.is_none() && cfg!(debug_assertions) {
298 0 : panic!(
299 0 : "removing layer that is not present in layer mapping: {:?}",
300 0 : layer.layer_desc()
301 0 : )
302 450 : }
303 450 : }
304 : }
|