Line data Source code
1 : mod downloader;
2 : pub mod heatmap;
3 : mod heatmap_uploader;
4 : mod scheduler;
5 :
6 : use std::{sync::Arc, time::SystemTime};
7 :
8 : use crate::{
9 : config::PageServerConf,
10 : disk_usage_eviction_task::DiskUsageEvictionInfo,
11 : task_mgr::{self, TaskKind, BACKGROUND_RUNTIME},
12 : virtual_file::MaybeFatalIo,
13 : };
14 :
15 : use self::{
16 : downloader::{downloader_task, SecondaryDetail},
17 : heatmap_uploader::heatmap_uploader_task,
18 : };
19 :
20 : use super::{
21 : config::{SecondaryLocationConfig, TenantConfOpt},
22 : mgr::TenantManager,
23 : span::debug_assert_current_span_has_tenant_id,
24 : storage_layer::LayerFileName,
25 : };
26 :
27 : use pageserver_api::{
28 : models,
29 : shard::{ShardIdentity, TenantShardId},
30 : };
31 : use remote_storage::GenericRemoteStorage;
32 :
33 : use tokio_util::sync::CancellationToken;
34 : use tracing::instrument;
35 : use utils::{completion::Barrier, id::TimelineId, sync::gate::Gate};
36 :
37 : enum DownloadCommand {
38 : Download(TenantShardId),
39 : }
40 : enum UploadCommand {
41 : Upload(TenantShardId),
42 : }
43 :
44 : impl UploadCommand {
45 0 : fn get_tenant_shard_id(&self) -> &TenantShardId {
46 0 : match self {
47 0 : Self::Upload(id) => id,
48 0 : }
49 0 : }
50 : }
51 :
52 : impl DownloadCommand {
53 0 : fn get_tenant_shard_id(&self) -> &TenantShardId {
54 0 : match self {
55 0 : Self::Download(id) => id,
56 0 : }
57 0 : }
58 : }
59 :
60 : struct CommandRequest<T> {
61 : payload: T,
62 : response_tx: tokio::sync::oneshot::Sender<CommandResponse>,
63 : }
64 :
65 : struct CommandResponse {
66 : result: anyhow::Result<()>,
67 : }
68 :
69 : // Whereas [`Tenant`] represents an attached tenant, this type represents the work
70 : // we do for secondary tenant locations: where we are not serving clients or
71 : // ingesting WAL, but we are maintaining a warm cache of layer files.
72 : //
73 : // This type is all about the _download_ path for secondary mode. The upload path
74 : // runs separately (see [`heatmap_uploader`]) while a regular attached `Tenant` exists.
75 : //
76 : // This structure coordinates TenantManager and SecondaryDownloader,
77 : // so that the downloader can indicate which tenants it is currently
78 : // operating on, and the manager can indicate when a particular
79 : // secondary tenant should cancel any work in flight.
80 : #[derive(Debug)]
81 : pub(crate) struct SecondaryTenant {
82 : /// Carrying a tenant shard ID simplifies callers such as the downloader
83 : /// which need to organize many of these objects by ID.
84 : tenant_shard_id: TenantShardId,
85 :
86 : /// Cancellation token indicates to SecondaryDownloader that it should stop doing
87 : /// any work for this tenant at the next opportunity.
88 : pub(crate) cancel: CancellationToken,
89 :
90 : pub(crate) gate: Gate,
91 :
92 : // Secondary mode does not need the full shard identity or the TenantConfOpt. However,
93 : // storing these enables us to report our full LocationConf, enabling convenient reconciliation
94 : // by the control plane (see [`Self::get_location_conf`])
95 : shard_identity: ShardIdentity,
96 : tenant_conf: std::sync::Mutex<TenantConfOpt>,
97 :
98 : // Internal state used by the Downloader.
99 : detail: std::sync::Mutex<SecondaryDetail>,
100 :
101 : // Public state indicating overall progress of downloads relative to the last heatmap seen
102 : pub(crate) progress: std::sync::Mutex<models::SecondaryProgress>,
103 : }
104 :
105 : impl SecondaryTenant {
106 0 : pub(crate) fn new(
107 0 : tenant_shard_id: TenantShardId,
108 0 : shard_identity: ShardIdentity,
109 0 : tenant_conf: TenantConfOpt,
110 0 : config: &SecondaryLocationConfig,
111 0 : ) -> Arc<Self> {
112 0 : Arc::new(Self {
113 0 : tenant_shard_id,
114 0 : // todo: shall we make this a descendent of the
115 0 : // main cancellation token, or is it sufficient that
116 0 : // on shutdown we walk the tenants and fire their
117 0 : // individual cancellations?
118 0 : cancel: CancellationToken::new(),
119 0 : gate: Gate::default(),
120 0 :
121 0 : shard_identity,
122 0 : tenant_conf: std::sync::Mutex::new(tenant_conf),
123 0 :
124 0 : detail: std::sync::Mutex::new(SecondaryDetail::new(config.clone())),
125 0 :
126 0 : progress: std::sync::Mutex::default(),
127 0 : })
128 0 : }
129 :
130 0 : pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
131 0 : self.tenant_shard_id
132 0 : }
133 :
134 0 : pub(crate) async fn shutdown(&self) {
135 0 : self.cancel.cancel();
136 0 :
137 0 : // Wait for any secondary downloader work to complete
138 0 : self.gate.close().await;
139 0 : }
140 :
141 0 : pub(crate) fn set_config(&self, config: &SecondaryLocationConfig) {
142 0 : self.detail.lock().unwrap().config = config.clone();
143 0 : }
144 :
145 0 : pub(crate) fn set_tenant_conf(&self, config: &TenantConfOpt) {
146 0 : *(self.tenant_conf.lock().unwrap()) = config.clone();
147 0 : }
148 :
149 : /// For API access: generate a LocationConfig equivalent to the one that would be used to
150 : /// create a Tenant in the same state. Do not use this in hot paths: it's for relatively
151 : /// rare external API calls, like a reconciliation at startup.
152 0 : pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
153 0 : let conf = self.detail.lock().unwrap().config.clone();
154 0 :
155 0 : let conf = models::LocationConfigSecondary { warm: conf.warm };
156 0 :
157 0 : let tenant_conf = self.tenant_conf.lock().unwrap().clone();
158 0 : models::LocationConfig {
159 0 : mode: models::LocationConfigMode::Secondary,
160 0 : generation: None,
161 0 : secondary_conf: Some(conf),
162 0 : shard_number: self.tenant_shard_id.shard_number.0,
163 0 : shard_count: self.tenant_shard_id.shard_count.literal(),
164 0 : shard_stripe_size: self.shard_identity.stripe_size.0,
165 0 : tenant_conf: tenant_conf.into(),
166 0 : }
167 0 : }
168 :
169 0 : pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
170 0 : &self.tenant_shard_id
171 0 : }
172 :
173 0 : pub(crate) fn get_layers_for_eviction(self: &Arc<Self>) -> (DiskUsageEvictionInfo, usize) {
174 0 : self.detail.lock().unwrap().get_layers_for_eviction(self)
175 0 : }
176 :
177 : /// Cancellation safe, but on cancellation the eviction will go through
178 0 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline_id, name=%name))]
179 : pub(crate) async fn evict_layer(
180 : self: &Arc<Self>,
181 : conf: &PageServerConf,
182 : timeline_id: TimelineId,
183 : name: LayerFileName,
184 : ) {
185 : debug_assert_current_span_has_tenant_id();
186 :
187 : let guard = match self.gate.enter() {
188 : Ok(g) => g,
189 : Err(_) => {
190 0 : tracing::debug!("Dropping layer evictions, secondary tenant shutting down",);
191 : return;
192 : }
193 : };
194 :
195 : let now = SystemTime::now();
196 :
197 : let path = conf
198 : .timeline_path(&self.tenant_shard_id, &timeline_id)
199 : .join(name.file_name());
200 :
201 : let this = self.clone();
202 :
203 : // spawn it to be cancellation safe
204 0 : tokio::task::spawn_blocking(move || {
205 0 : let _guard = guard;
206 0 : // We tolerate ENOENT, because between planning eviction and executing
207 0 : // it, the secondary downloader could have seen an updated heatmap that
208 0 : // resulted in a layer being deleted.
209 0 : // Other local I/O errors are process-fatal: these should never happen.
210 0 : let deleted = std::fs::remove_file(path);
211 0 :
212 0 : let not_found = deleted
213 0 : .as_ref()
214 0 : .is_err_and(|x| x.kind() == std::io::ErrorKind::NotFound);
215 :
216 0 : let deleted = if not_found {
217 0 : false
218 : } else {
219 0 : deleted
220 0 : .map(|()| true)
221 0 : .fatal_err("Deleting layer during eviction")
222 : };
223 :
224 0 : if !deleted {
225 : // skip updating accounting and putting perhaps later timestamp
226 0 : return;
227 0 : }
228 0 :
229 0 : // Update the timeline's state. This does not have to be synchronized with
230 0 : // the download process, because:
231 0 : // - If downloader is racing with us to remove a file (e.g. because it is
232 0 : // removed from heatmap), then our mutual .remove() operations will both
233 0 : // succeed.
234 0 : // - If downloader is racing with us to download the object (this would require
235 0 : // multiple eviction iterations to race with multiple download iterations), then
236 0 : // if we remove it from the state, the worst that happens is the downloader
237 0 : // downloads it again before re-inserting, or we delete the file but it remains
238 0 : // in the state map (in which case it will be downloaded if this secondary
239 0 : // tenant transitions to attached and tries to access it)
240 0 : //
241 0 : // The important assumption here is that the secondary timeline state does not
242 0 : // have to 100% match what is on disk, because it's a best-effort warming
243 0 : // of the cache.
244 0 : let mut detail = this.detail.lock().unwrap();
245 0 : if let Some(timeline_detail) = detail.timelines.get_mut(&timeline_id) {
246 0 : timeline_detail.on_disk_layers.remove(&name);
247 0 : timeline_detail.evicted_at.insert(name, now);
248 0 : }
249 0 : })
250 : .await
251 : .expect("secondary eviction should not have panicked");
252 : }
253 : }
254 :
255 : /// The SecondaryController is a pseudo-rpc client for administrative control of secondary mode downloads,
256 : /// and heatmap uploads. This is not a hot data path: it's used for:
257 : /// - Live migrations, where we want to ensure a migration destination has the freshest possible
258 : /// content before trying to cut over.
259 : /// - Tests, where we want to immediately upload/download for a particular tenant.
260 : ///
261 : /// In normal operations, outside of migrations, uploads & downloads are autonomous and not driven by this interface.
262 : pub struct SecondaryController {
263 : upload_req_tx: tokio::sync::mpsc::Sender<CommandRequest<UploadCommand>>,
264 : download_req_tx: tokio::sync::mpsc::Sender<CommandRequest<DownloadCommand>>,
265 : }
266 :
267 : impl SecondaryController {
268 0 : async fn dispatch<T>(
269 0 : &self,
270 0 : queue: &tokio::sync::mpsc::Sender<CommandRequest<T>>,
271 0 : payload: T,
272 0 : ) -> anyhow::Result<()> {
273 0 : let (response_tx, response_rx) = tokio::sync::oneshot::channel();
274 0 :
275 0 : queue
276 0 : .send(CommandRequest {
277 0 : payload,
278 0 : response_tx,
279 0 : })
280 0 : .await
281 0 : .map_err(|_| anyhow::anyhow!("Receiver shut down"))?;
282 :
283 0 : let response = response_rx
284 0 : .await
285 0 : .map_err(|_| anyhow::anyhow!("Request dropped"))?;
286 :
287 0 : response.result
288 0 : }
289 :
290 0 : pub async fn upload_tenant(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
291 0 : self.dispatch(&self.upload_req_tx, UploadCommand::Upload(tenant_shard_id))
292 0 : .await
293 0 : }
294 0 : pub async fn download_tenant(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
295 0 : self.dispatch(
296 0 : &self.download_req_tx,
297 0 : DownloadCommand::Download(tenant_shard_id),
298 0 : )
299 0 : .await
300 0 : }
301 : }
302 :
303 0 : pub fn spawn_tasks(
304 0 : tenant_manager: Arc<TenantManager>,
305 0 : remote_storage: GenericRemoteStorage,
306 0 : background_jobs_can_start: Barrier,
307 0 : cancel: CancellationToken,
308 0 : ) -> SecondaryController {
309 0 : let mgr_clone = tenant_manager.clone();
310 0 : let storage_clone = remote_storage.clone();
311 0 : let cancel_clone = cancel.clone();
312 0 : let bg_jobs_clone = background_jobs_can_start.clone();
313 0 :
314 0 : let (download_req_tx, download_req_rx) =
315 0 : tokio::sync::mpsc::channel::<CommandRequest<DownloadCommand>>(16);
316 0 : let (upload_req_tx, upload_req_rx) =
317 0 : tokio::sync::mpsc::channel::<CommandRequest<UploadCommand>>(16);
318 0 :
319 0 : task_mgr::spawn(
320 0 : BACKGROUND_RUNTIME.handle(),
321 0 : TaskKind::SecondaryDownloads,
322 0 : None,
323 0 : None,
324 0 : "secondary tenant downloads",
325 0 : false,
326 0 : async move {
327 0 : downloader_task(
328 0 : mgr_clone,
329 0 : storage_clone,
330 0 : download_req_rx,
331 0 : bg_jobs_clone,
332 0 : cancel_clone,
333 0 : )
334 0 : .await;
335 :
336 0 : Ok(())
337 0 : },
338 0 : );
339 0 :
340 0 : task_mgr::spawn(
341 0 : BACKGROUND_RUNTIME.handle(),
342 0 : TaskKind::SecondaryUploads,
343 0 : None,
344 0 : None,
345 0 : "heatmap uploads",
346 0 : false,
347 0 : async move {
348 0 : heatmap_uploader_task(
349 0 : tenant_manager,
350 0 : remote_storage,
351 0 : upload_req_rx,
352 0 : background_jobs_can_start,
353 0 : cancel,
354 0 : )
355 0 : .await;
356 :
357 0 : Ok(())
358 0 : },
359 0 : );
360 0 :
361 0 : SecondaryController {
362 0 : download_req_tx,
363 0 : upload_req_tx,
364 0 : }
365 0 : }
366 :
367 : /// For running with remote storage disabled: a SecondaryController that is connected to nothing.
368 0 : pub fn null_controller() -> SecondaryController {
369 0 : let (download_req_tx, _download_req_rx) =
370 0 : tokio::sync::mpsc::channel::<CommandRequest<DownloadCommand>>(16);
371 0 : let (upload_req_tx, _upload_req_rx) =
372 0 : tokio::sync::mpsc::channel::<CommandRequest<UploadCommand>>(16);
373 0 : SecondaryController {
374 0 : upload_req_tx,
375 0 : download_req_tx,
376 0 : }
377 0 : }
|