Line data Source code
1 : use std::{
2 : collections::HashMap,
3 : pin::Pin,
4 : sync::{Arc, Weak},
5 : time::{Duration, Instant},
6 : };
7 :
8 : use crate::{
9 : metrics::SECONDARY_MODE,
10 : tenant::{
11 : config::AttachmentMode,
12 : mgr::GetTenantError,
13 : mgr::TenantManager,
14 : remote_timeline_client::remote_heatmap_path,
15 : span::debug_assert_current_span_has_tenant_id,
16 : tasks::{warn_when_period_overrun, BackgroundLoopKind},
17 : Tenant,
18 : },
19 : };
20 :
21 : use futures::Future;
22 : use pageserver_api::shard::TenantShardId;
23 : use remote_storage::{GenericRemoteStorage, TimeoutOrCancel};
24 :
25 : use super::{
26 : heatmap::HeatMapTenant,
27 : scheduler::{
28 : self, period_jitter, period_warmup, JobGenerator, RunningJob, SchedulingResult,
29 : TenantBackgroundJobs,
30 : },
31 : CommandRequest, UploadCommand,
32 : };
33 : use tokio_util::sync::CancellationToken;
34 : use tracing::{info_span, instrument, Instrument};
35 : use utils::{backoff, completion::Barrier, yielding_loop::yielding_loop};
36 :
37 0 : pub(super) async fn heatmap_uploader_task(
38 0 : tenant_manager: Arc<TenantManager>,
39 0 : remote_storage: GenericRemoteStorage,
40 0 : command_queue: tokio::sync::mpsc::Receiver<CommandRequest<UploadCommand>>,
41 0 : background_jobs_can_start: Barrier,
42 0 : cancel: CancellationToken,
43 0 : ) {
44 0 : let concurrency = tenant_manager.get_conf().heatmap_upload_concurrency;
45 0 :
46 0 : let generator = HeatmapUploader {
47 0 : tenant_manager,
48 0 : remote_storage,
49 0 : cancel: cancel.clone(),
50 0 : tenants: HashMap::new(),
51 0 : };
52 0 : let mut scheduler = Scheduler::new(generator, concurrency);
53 0 :
54 0 : scheduler
55 0 : .run(command_queue, background_jobs_can_start, cancel)
56 0 : .instrument(info_span!("heatmap_uploader"))
57 0 : .await
58 0 : }
59 :
60 : /// This type is owned by a single task ([`heatmap_uploader_task`]) which runs an event
61 : /// handling loop and mutates it as needed: there are no locks here, because that event loop
62 : /// can hold &mut references to this type throughout.
63 : struct HeatmapUploader {
64 : tenant_manager: Arc<TenantManager>,
65 : remote_storage: GenericRemoteStorage,
66 : cancel: CancellationToken,
67 :
68 : tenants: HashMap<TenantShardId, UploaderTenantState>,
69 : }
70 :
71 : struct WriteInProgress {
72 : barrier: Barrier,
73 : }
74 :
75 : impl RunningJob for WriteInProgress {
76 0 : fn get_barrier(&self) -> Barrier {
77 0 : self.barrier.clone()
78 0 : }
79 : }
80 :
81 : struct UploadPending {
82 : tenant: Arc<Tenant>,
83 : last_digest: Option<md5::Digest>,
84 : target_time: Option<Instant>,
85 : period: Option<Duration>,
86 : }
87 :
88 : impl scheduler::PendingJob for UploadPending {
89 0 : fn get_tenant_shard_id(&self) -> &TenantShardId {
90 0 : self.tenant.get_tenant_shard_id()
91 0 : }
92 : }
93 :
94 : struct WriteComplete {
95 : tenant_shard_id: TenantShardId,
96 : completed_at: Instant,
97 : digest: Option<md5::Digest>,
98 : next_upload: Option<Instant>,
99 : }
100 :
101 : impl scheduler::Completion for WriteComplete {
102 0 : fn get_tenant_shard_id(&self) -> &TenantShardId {
103 0 : &self.tenant_shard_id
104 0 : }
105 : }
106 :
107 : /// The heatmap uploader keeps a little bit of per-tenant state, mainly to remember
108 : /// when we last did a write. We only populate this after doing at least one
109 : /// write for a tenant -- this avoids holding state for tenants that have
110 : /// uploads disabled.
111 :
112 : struct UploaderTenantState {
113 : // This Weak only exists to enable culling idle instances of this type
114 : // when the Tenant has been deallocated.
115 : tenant: Weak<Tenant>,
116 :
117 : /// Digest of the serialized heatmap that we last successfully uploaded
118 : ///
119 : /// md5 is generally a bad hash. We use it because it's convenient for interop with AWS S3's ETag,
120 : /// which is also an md5sum.
121 : last_digest: Option<md5::Digest>,
122 :
123 : /// When the last upload attempt completed (may have been successful or failed)
124 : last_upload: Option<Instant>,
125 :
126 : /// When should we next do an upload? None means never.
127 : next_upload: Option<Instant>,
128 : }
129 :
130 : type Scheduler = TenantBackgroundJobs<
131 : HeatmapUploader,
132 : UploadPending,
133 : WriteInProgress,
134 : WriteComplete,
135 : UploadCommand,
136 : >;
137 :
138 : impl JobGenerator<UploadPending, WriteInProgress, WriteComplete, UploadCommand>
139 : for HeatmapUploader
140 : {
141 0 : async fn schedule(&mut self) -> SchedulingResult<UploadPending> {
142 0 : // Cull any entries in self.tenants whose Arc<Tenant> is gone
143 0 : self.tenants
144 0 : .retain(|_k, v| v.tenant.upgrade().is_some() && v.next_upload.is_some());
145 0 :
146 0 : let now = Instant::now();
147 0 :
148 0 : let mut result = SchedulingResult {
149 0 : jobs: Vec::new(),
150 0 : want_interval: None,
151 0 : };
152 0 :
153 0 : let tenants = self.tenant_manager.get_attached_active_tenant_shards();
154 0 :
155 0 : yielding_loop(1000, &self.cancel, tenants.into_iter(), |tenant| {
156 0 : let period = match tenant.get_heatmap_period() {
157 : None => {
158 : // Heatmaps are disabled for this tenant
159 0 : return;
160 : }
161 0 : Some(period) => {
162 0 : // If any tenant has asked for uploads more frequent than our scheduling interval,
163 0 : // reduce it to match so that we can keep up. This is mainly useful in testing, where
164 0 : // we may set rather short intervals.
165 0 : result.want_interval = match result.want_interval {
166 0 : None => Some(period),
167 0 : Some(existing) => Some(std::cmp::min(period, existing)),
168 : };
169 :
170 0 : period
171 0 : }
172 0 : };
173 0 :
174 0 : // Stale attachments do not upload anything: if we are in this state, there is probably some
175 0 : // other attachment in mode Single or Multi running on another pageserver, and we don't
176 0 : // want to thrash and overwrite their heatmap uploads.
177 0 : if tenant.get_attach_mode() == AttachmentMode::Stale {
178 0 : return;
179 0 : }
180 0 :
181 0 : // Create an entry in self.tenants if one doesn't already exist: this will later be updated
182 0 : // with the completion time in on_completion.
183 0 : let state = self
184 0 : .tenants
185 0 : .entry(*tenant.get_tenant_shard_id())
186 0 : .or_insert_with(|| UploaderTenantState {
187 0 : tenant: Arc::downgrade(&tenant),
188 0 : last_upload: None,
189 0 : next_upload: Some(now.checked_add(period_warmup(period)).unwrap_or(now)),
190 0 : last_digest: None,
191 0 : });
192 0 :
193 0 : // Decline to do the upload if insufficient time has passed
194 0 : if state.next_upload.map(|nu| nu > now).unwrap_or(false) {
195 0 : return;
196 0 : }
197 0 :
198 0 : let last_digest = state.last_digest;
199 0 : result.jobs.push(UploadPending {
200 0 : tenant,
201 0 : last_digest,
202 0 : target_time: state.next_upload,
203 0 : period: Some(period),
204 0 : });
205 0 : })
206 0 : .await
207 0 : .ok();
208 0 :
209 0 : result
210 0 : }
211 :
212 0 : fn spawn(
213 0 : &mut self,
214 0 : job: UploadPending,
215 0 : ) -> (
216 0 : WriteInProgress,
217 0 : Pin<Box<dyn Future<Output = WriteComplete> + Send>>,
218 0 : ) {
219 0 : let UploadPending {
220 0 : tenant,
221 0 : last_digest,
222 0 : target_time,
223 0 : period,
224 0 : } = job;
225 0 :
226 0 : let remote_storage = self.remote_storage.clone();
227 0 : let (completion, barrier) = utils::completion::channel();
228 0 : let tenant_shard_id = *tenant.get_tenant_shard_id();
229 0 : (WriteInProgress { barrier }, Box::pin(async move {
230 0 : // Guard for the barrier in [`WriteInProgress`]
231 0 : let _completion = completion;
232 0 :
233 0 : let started_at = Instant::now();
234 0 : let digest = match upload_tenant_heatmap(remote_storage, &tenant, last_digest).await {
235 0 : Ok(UploadHeatmapOutcome::Uploaded(digest)) => {
236 0 : let duration = Instant::now().duration_since(started_at);
237 0 : SECONDARY_MODE
238 0 : .upload_heatmap_duration
239 0 : .observe(duration.as_secs_f64());
240 0 : SECONDARY_MODE.upload_heatmap.inc();
241 0 : Some(digest)
242 : }
243 0 : Ok(UploadHeatmapOutcome::NoChange | UploadHeatmapOutcome::Skipped) => last_digest,
244 0 : Err(UploadHeatmapError::Upload(e)) => {
245 0 : tracing::warn!(
246 0 : "Failed to upload heatmap for tenant {}: {e:#}",
247 0 : tenant.get_tenant_shard_id(),
248 : );
249 0 : let duration = Instant::now().duration_since(started_at);
250 0 : SECONDARY_MODE
251 0 : .upload_heatmap_duration
252 0 : .observe(duration.as_secs_f64());
253 0 : SECONDARY_MODE.upload_heatmap_errors.inc();
254 0 : last_digest
255 : }
256 : Err(UploadHeatmapError::Cancelled) => {
257 0 : tracing::info!("Cancelled heatmap upload, shutting down");
258 0 : last_digest
259 : }
260 : };
261 :
262 0 : let now = Instant::now();
263 :
264 : // If the job had a target execution time, we may check our final execution
265 : // time against that for observability purposes.
266 0 : if let (Some(target_time), Some(period)) = (target_time, period) {
267 0 : // Elapsed time includes any scheduling lag as well as the execution of the job
268 0 : let elapsed = now.duration_since(target_time);
269 0 :
270 0 : warn_when_period_overrun(elapsed, period, BackgroundLoopKind::HeatmapUpload);
271 0 : }
272 :
273 0 : let next_upload = tenant
274 0 : .get_heatmap_period()
275 0 : .and_then(|period| now.checked_add(period_jitter(period, 5)));
276 0 :
277 0 : WriteComplete {
278 0 : tenant_shard_id: *tenant.get_tenant_shard_id(),
279 0 : completed_at: now,
280 0 : digest,
281 0 : next_upload,
282 0 : }
283 0 : }.instrument(info_span!(parent: None, "heatmap_upload", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))))
284 0 : }
285 :
286 0 : fn on_command(&mut self, command: UploadCommand) -> anyhow::Result<UploadPending> {
287 0 : let tenant_shard_id = command.get_tenant_shard_id();
288 0 :
289 0 : tracing::info!(
290 0 : tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
291 0 : "Starting heatmap write on command");
292 0 : let tenant = self
293 0 : .tenant_manager
294 0 : .get_attached_tenant_shard(*tenant_shard_id)
295 0 : .map_err(|e| anyhow::anyhow!(e))?;
296 0 : if !tenant.is_active() {
297 0 : return Err(GetTenantError::NotActive(*tenant_shard_id).into());
298 0 : }
299 0 :
300 0 : Ok(UploadPending {
301 0 : // Ignore our state for last digest: this forces an upload even if nothing has changed
302 0 : last_digest: None,
303 0 : tenant,
304 0 : target_time: None,
305 0 : period: None,
306 0 : })
307 0 : }
308 :
309 0 : #[instrument(skip_all, fields(tenant_id=%completion.tenant_shard_id.tenant_id, shard_id=%completion.tenant_shard_id.shard_slug()))]
310 : fn on_completion(&mut self, completion: WriteComplete) {
311 : tracing::debug!("Heatmap upload completed");
312 : let WriteComplete {
313 : tenant_shard_id,
314 : completed_at,
315 : digest,
316 : next_upload,
317 : } = completion;
318 : use std::collections::hash_map::Entry;
319 : match self.tenants.entry(tenant_shard_id) {
320 : Entry::Vacant(_) => {
321 : // Tenant state was dropped, nothing to update.
322 : }
323 : Entry::Occupied(mut entry) => {
324 : entry.get_mut().last_upload = Some(completed_at);
325 : entry.get_mut().last_digest = digest;
326 : entry.get_mut().next_upload = next_upload
327 : }
328 : }
329 : }
330 : }
331 :
332 : enum UploadHeatmapOutcome {
333 : /// We successfully wrote to remote storage, with this digest.
334 : Uploaded(md5::Digest),
335 : /// We did not upload because the heatmap digest was unchanged since the last upload
336 : NoChange,
337 : /// We skipped the upload for some reason, such as tenant/timeline not ready
338 : Skipped,
339 : }
340 :
341 0 : #[derive(thiserror::Error, Debug)]
342 : enum UploadHeatmapError {
343 : #[error("Cancelled")]
344 : Cancelled,
345 :
346 : #[error(transparent)]
347 : Upload(#[from] anyhow::Error),
348 : }
349 :
350 : /// The inner upload operation. This will skip if `last_digest` is Some and matches the digest
351 : /// of the object we would have uploaded.
352 0 : async fn upload_tenant_heatmap(
353 0 : remote_storage: GenericRemoteStorage,
354 0 : tenant: &Arc<Tenant>,
355 0 : last_digest: Option<md5::Digest>,
356 0 : ) -> Result<UploadHeatmapOutcome, UploadHeatmapError> {
357 0 : debug_assert_current_span_has_tenant_id();
358 0 :
359 0 : let generation = tenant.get_generation();
360 0 : if generation.is_none() {
361 : // We do not expect this: generations were implemented before heatmap uploads. However,
362 : // handle it so that we don't have to make the generation in the heatmap an Option<>
363 : // (Generation::none is not serializable)
364 0 : tracing::warn!("Skipping heatmap upload for tenant with generation==None");
365 0 : return Ok(UploadHeatmapOutcome::Skipped);
366 0 : }
367 0 :
368 0 : let mut heatmap = HeatMapTenant {
369 0 : timelines: Vec::new(),
370 0 : generation,
371 0 : };
372 0 : let timelines = tenant.timelines.lock().unwrap().clone();
373 :
374 : // Ensure that Tenant::shutdown waits for any upload in flight: this is needed because otherwise
375 : // when we delete a tenant, we might race with an upload in flight and end up leaving a heatmap behind
376 : // in remote storage.
377 0 : let Ok(_guard) = tenant.gate.enter() else {
378 0 : tracing::info!("Skipping heatmap upload for tenant which is shutting down");
379 0 : return Err(UploadHeatmapError::Cancelled);
380 : };
381 :
382 0 : for (timeline_id, timeline) in timelines {
383 0 : let heatmap_timeline = timeline.generate_heatmap().await;
384 0 : match heatmap_timeline {
385 : None => {
386 0 : tracing::debug!(
387 0 : "Skipping heatmap upload because timeline {timeline_id} is not ready"
388 : );
389 0 : return Ok(UploadHeatmapOutcome::Skipped);
390 : }
391 0 : Some(heatmap_timeline) => {
392 0 : heatmap.timelines.push(heatmap_timeline);
393 0 : }
394 : }
395 : }
396 :
397 : // Serialize the heatmap
398 0 : let bytes = serde_json::to_vec(&heatmap).map_err(|e| anyhow::anyhow!(e))?;
399 0 : let bytes = bytes::Bytes::from(bytes);
400 0 : let size = bytes.len();
401 0 :
402 0 : // Drop out early if nothing changed since our last upload
403 0 : let digest = md5::compute(&bytes);
404 0 : if Some(digest) == last_digest {
405 0 : return Ok(UploadHeatmapOutcome::NoChange);
406 0 : }
407 0 :
408 0 : let path = remote_heatmap_path(tenant.get_tenant_shard_id());
409 0 :
410 0 : let cancel = &tenant.cancel;
411 0 :
412 0 : tracing::debug!("Uploading {size} byte heatmap to {path}");
413 0 : if let Err(e) = backoff::retry(
414 0 : || async {
415 0 : let bytes = futures::stream::once(futures::future::ready(Ok(bytes.clone())));
416 0 : remote_storage
417 0 : .upload_storage_object(bytes, size, &path, cancel)
418 0 : .await
419 0 : },
420 0 : TimeoutOrCancel::caused_by_cancel,
421 0 : 3,
422 0 : u32::MAX,
423 0 : "Uploading heatmap",
424 0 : cancel,
425 0 : )
426 0 : .await
427 0 : .ok_or_else(|| anyhow::anyhow!("Shutting down"))
428 0 : .and_then(|x| x)
429 : {
430 0 : if cancel.is_cancelled() {
431 0 : return Err(UploadHeatmapError::Cancelled);
432 : } else {
433 0 : return Err(e.into());
434 : }
435 0 : }
436 0 :
437 0 : tracing::info!("Successfully uploaded {size} byte heatmap to {path}");
438 :
439 0 : Ok(UploadHeatmapOutcome::Uploaded(digest))
440 0 : }
|