Line data Source code
1 : use crate::pageserver_client::PageserverClient;
2 : use crate::persistence::Persistence;
3 : use crate::service;
4 : use pageserver_api::controller_api::PlacementPolicy;
5 : use pageserver_api::models::{
6 : LocationConfig, LocationConfigMode, LocationConfigSecondary, TenantConfig,
7 : };
8 : use pageserver_api::shard::{ShardIdentity, TenantShardId};
9 : use pageserver_client::mgmt_api;
10 : use reqwest::StatusCode;
11 : use std::collections::HashMap;
12 : use std::sync::Arc;
13 : use std::time::{Duration, Instant};
14 : use tokio_util::sync::CancellationToken;
15 : use utils::failpoint_support;
16 : use utils::generation::Generation;
17 : use utils::id::{NodeId, TimelineId};
18 : use utils::lsn::Lsn;
19 : use utils::sync::gate::GateGuard;
20 :
21 : use crate::compute_hook::{ComputeHook, NotifyError};
22 : use crate::node::Node;
23 : use crate::tenant_shard::{IntentState, ObservedState, ObservedStateLocation};
24 :
25 : const DEFAULT_HEATMAP_PERIOD: &str = "60s";
26 :
27 : /// Object with the lifetime of the background reconcile task that is created
28 : /// for tenants which have a difference between their intent and observed states.
29 : pub(super) struct Reconciler {
30 : /// See [`crate::tenant_shard::TenantShard`] for the meanings of these fields: they are a snapshot
31 : /// of a tenant's state from when we spawned a reconcile task.
32 : pub(super) tenant_shard_id: TenantShardId,
33 : pub(crate) shard: ShardIdentity,
34 : pub(crate) placement_policy: PlacementPolicy,
35 : pub(crate) generation: Option<Generation>,
36 : pub(crate) intent: TargetState,
37 :
38 : /// Nodes not referenced by [`Self::intent`], from which we should try
39 : /// to detach this tenant shard.
40 : pub(crate) detach: Vec<Node>,
41 :
42 : pub(crate) config: TenantConfig,
43 : pub(crate) observed: ObservedState,
44 :
45 : pub(crate) service_config: service::Config,
46 :
47 : /// A hook to notify the running postgres instances when we change the location
48 : /// of a tenant. Use this via [`Self::compute_notify`] to update our failure flag
49 : /// and guarantee eventual retries.
50 : pub(crate) compute_hook: Arc<ComputeHook>,
51 :
52 : /// To avoid stalling if the cloud control plane is unavailable, we may proceed
53 : /// past failures in [`ComputeHook::notify`], but we _must_ remember that we failed
54 : /// so that we can set [`crate::tenant_shard::TenantShard::pending_compute_notification`] to ensure a later retry.
55 : pub(crate) compute_notify_failure: bool,
56 :
57 : /// Reconciler is responsible for keeping alive semaphore units that limit concurrency on how many
58 : /// we will spawn.
59 : pub(crate) _resource_units: ReconcileUnits,
60 :
61 : /// A means to abort background reconciliation: it is essential to
62 : /// call this when something changes in the original TenantShard that
63 : /// will make this reconciliation impossible or unnecessary, for
64 : /// example when a pageserver node goes offline, or the PlacementPolicy for
65 : /// the tenant is changed.
66 : pub(crate) cancel: CancellationToken,
67 :
68 : /// Reconcilers are registered with a Gate so that during a graceful shutdown we
69 : /// can wait for all the reconcilers to respond to their cancellation tokens.
70 : pub(crate) _gate_guard: GateGuard,
71 :
72 : /// Access to persistent storage for updating generation numbers
73 : pub(crate) persistence: Arc<Persistence>,
74 : }
75 :
76 : /// RAII resource units granted to a Reconciler, which it should keep alive until it finishes doing I/O
77 : pub(crate) struct ReconcileUnits {
78 : _sem_units: tokio::sync::OwnedSemaphorePermit,
79 : }
80 :
81 : impl ReconcileUnits {
82 0 : pub(crate) fn new(sem_units: tokio::sync::OwnedSemaphorePermit) -> Self {
83 0 : Self {
84 0 : _sem_units: sem_units,
85 0 : }
86 0 : }
87 : }
88 :
89 : /// This is a snapshot of [`crate::tenant_shard::IntentState`], but it does not do any
90 : /// reference counting for Scheduler. The IntentState is what the scheduler works with,
91 : /// and the TargetState is just the instruction for a particular Reconciler run.
92 : #[derive(Debug)]
93 : pub(crate) struct TargetState {
94 : pub(crate) attached: Option<Node>,
95 : pub(crate) secondary: Vec<Node>,
96 : }
97 :
98 : impl TargetState {
99 0 : pub(crate) fn from_intent(nodes: &HashMap<NodeId, Node>, intent: &IntentState) -> Self {
100 0 : Self {
101 0 : attached: intent.get_attached().map(|n| {
102 0 : nodes
103 0 : .get(&n)
104 0 : .expect("Intent attached referenced non-existent node")
105 0 : .clone()
106 0 : }),
107 0 : secondary: intent
108 0 : .get_secondary()
109 0 : .iter()
110 0 : .map(|n| {
111 0 : nodes
112 0 : .get(n)
113 0 : .expect("Intent secondary referenced non-existent node")
114 0 : .clone()
115 0 : })
116 0 : .collect(),
117 0 : }
118 0 : }
119 : }
120 :
121 0 : #[derive(thiserror::Error, Debug)]
122 : pub(crate) enum ReconcileError {
123 : #[error(transparent)]
124 : Remote(#[from] mgmt_api::Error),
125 : #[error(transparent)]
126 : Notify(#[from] NotifyError),
127 : #[error("Cancelled")]
128 : Cancel,
129 : #[error(transparent)]
130 : Other(#[from] anyhow::Error),
131 : }
132 :
133 : impl Reconciler {
134 0 : async fn location_config(
135 0 : &mut self,
136 0 : node: &Node,
137 0 : config: LocationConfig,
138 0 : flush_ms: Option<Duration>,
139 0 : lazy: bool,
140 0 : ) -> Result<(), ReconcileError> {
141 0 : if !node.is_available() && config.mode == LocationConfigMode::Detached {
142 : // Attempts to detach from offline nodes may be imitated without doing I/O: a node which is offline
143 : // will get fully reconciled wrt the shard's intent state when it is reactivated, irrespective of
144 : // what we put into `observed`, in [`crate::service::Service::node_activate_reconcile`]
145 0 : tracing::info!("Node {node} is unavailable during detach: proceeding anyway, it will be detached on next activation");
146 0 : self.observed.locations.remove(&node.get_id());
147 0 : return Ok(());
148 0 : }
149 0 :
150 0 : self.observed
151 0 : .locations
152 0 : .insert(node.get_id(), ObservedStateLocation { conf: None });
153 0 :
154 0 : // TODO: amend locations that use long-polling: they will hit this timeout.
155 0 : let timeout = Duration::from_secs(25);
156 0 :
157 0 : tracing::info!("location_config({node}) calling: {:?}", config);
158 0 : let tenant_shard_id = self.tenant_shard_id;
159 0 : let config_ref = &config;
160 0 : match node
161 0 : .with_client_retries(
162 0 : |client| async move {
163 0 : let config = config_ref.clone();
164 0 : client
165 0 : .location_config(tenant_shard_id, config.clone(), flush_ms, lazy)
166 0 : .await
167 0 : },
168 0 : &self.service_config.jwt_token,
169 0 : 1,
170 0 : 3,
171 0 : timeout,
172 0 : &self.cancel,
173 0 : )
174 0 : .await
175 : {
176 0 : Some(Ok(_)) => {}
177 0 : Some(Err(e)) => return Err(e.into()),
178 0 : None => return Err(ReconcileError::Cancel),
179 : };
180 0 : tracing::info!("location_config({node}) complete: {:?}", config);
181 :
182 0 : match config.mode {
183 0 : LocationConfigMode::Detached => {
184 0 : self.observed.locations.remove(&node.get_id());
185 0 : }
186 0 : _ => {
187 0 : self.observed
188 0 : .locations
189 0 : .insert(node.get_id(), ObservedStateLocation { conf: Some(config) });
190 0 : }
191 : }
192 :
193 0 : Ok(())
194 0 : }
195 :
196 0 : fn get_node(&self, node_id: &NodeId) -> Option<&Node> {
197 0 : if let Some(node) = self.intent.attached.as_ref() {
198 0 : if node.get_id() == *node_id {
199 0 : return Some(node);
200 0 : }
201 0 : }
202 :
203 0 : if let Some(node) = self
204 0 : .intent
205 0 : .secondary
206 0 : .iter()
207 0 : .find(|n| n.get_id() == *node_id)
208 : {
209 0 : return Some(node);
210 0 : }
211 :
212 0 : if let Some(node) = self.detach.iter().find(|n| n.get_id() == *node_id) {
213 0 : return Some(node);
214 0 : }
215 0 :
216 0 : None
217 0 : }
218 :
219 0 : async fn maybe_live_migrate(&mut self) -> Result<(), ReconcileError> {
220 0 : let destination = if let Some(node) = &self.intent.attached {
221 0 : match self.observed.locations.get(&node.get_id()) {
222 0 : Some(conf) => {
223 : // We will do a live migration only if the intended destination is not
224 : // currently in an attached state.
225 0 : match &conf.conf {
226 0 : Some(conf) if conf.mode == LocationConfigMode::Secondary => {
227 0 : // Fall through to do a live migration
228 0 : node
229 : }
230 : None | Some(_) => {
231 : // Attached or uncertain: don't do a live migration, proceed
232 : // with a general-case reconciliation
233 0 : tracing::info!("maybe_live_migrate: destination is None or attached");
234 0 : return Ok(());
235 : }
236 : }
237 : }
238 : None => {
239 : // Our destination is not attached: maybe live migrate if some other
240 : // node is currently attached. Fall through.
241 0 : node
242 : }
243 : }
244 : } else {
245 : // No intent to be attached
246 0 : tracing::info!("maybe_live_migrate: no attached intent");
247 0 : return Ok(());
248 : };
249 :
250 0 : let mut origin = None;
251 0 : for (node_id, state) in &self.observed.locations {
252 0 : if let Some(observed_conf) = &state.conf {
253 0 : if observed_conf.mode == LocationConfigMode::AttachedSingle {
254 : // We will only attempt live migration if the origin is not offline: this
255 : // avoids trying to do it while reconciling after responding to an HA failover.
256 0 : if let Some(node) = self.get_node(node_id) {
257 0 : if node.is_available() {
258 0 : origin = Some(node.clone());
259 0 : break;
260 0 : }
261 0 : }
262 0 : }
263 0 : }
264 : }
265 :
266 0 : let Some(origin) = origin else {
267 0 : tracing::info!("maybe_live_migrate: no origin found");
268 0 : return Ok(());
269 : };
270 :
271 : // We have an origin and a destination: proceed to do the live migration
272 0 : tracing::info!("Live migrating {}->{}", origin, destination);
273 0 : self.live_migrate(origin, destination.clone()).await?;
274 :
275 0 : Ok(())
276 0 : }
277 :
278 0 : async fn get_lsns(
279 0 : &self,
280 0 : tenant_shard_id: TenantShardId,
281 0 : node: &Node,
282 0 : ) -> anyhow::Result<HashMap<TimelineId, Lsn>> {
283 0 : let client = PageserverClient::new(
284 0 : node.get_id(),
285 0 : node.base_url(),
286 0 : self.service_config.jwt_token.as_deref(),
287 0 : );
288 :
289 0 : let timelines = client.timeline_list(&tenant_shard_id).await?;
290 0 : Ok(timelines
291 0 : .into_iter()
292 0 : .map(|t| (t.timeline_id, t.last_record_lsn))
293 0 : .collect())
294 0 : }
295 :
296 0 : async fn secondary_download(
297 0 : &self,
298 0 : tenant_shard_id: TenantShardId,
299 0 : node: &Node,
300 0 : ) -> Result<(), ReconcileError> {
301 0 : // This is not the timeout for a request, but the total amount of time we're willing to wait
302 0 : // for a secondary location to get up to date before
303 0 : const TOTAL_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);
304 0 :
305 0 : // This the long-polling interval for the secondary download requests we send to destination pageserver
306 0 : // during a migration.
307 0 : const REQUEST_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(20);
308 0 :
309 0 : let started_at = Instant::now();
310 :
311 : loop {
312 0 : let (status, progress) = match node
313 0 : .with_client_retries(
314 0 : |client| async move {
315 0 : client
316 0 : .tenant_secondary_download(
317 0 : tenant_shard_id,
318 0 : Some(REQUEST_DOWNLOAD_TIMEOUT),
319 0 : )
320 0 : .await
321 0 : },
322 0 : &self.service_config.jwt_token,
323 0 : 1,
324 0 : 3,
325 0 : REQUEST_DOWNLOAD_TIMEOUT * 2,
326 0 : &self.cancel,
327 0 : )
328 0 : .await
329 : {
330 0 : None => Err(ReconcileError::Cancel),
331 0 : Some(Ok(v)) => Ok(v),
332 0 : Some(Err(e)) => {
333 0 : // Give up, but proceed: it's unfortunate if we couldn't freshen the destination before
334 0 : // attaching, but we should not let an issue with a secondary location stop us proceeding
335 0 : // with a live migration.
336 0 : tracing::warn!("Failed to prepare by downloading layers on node {node}: {e})");
337 0 : return Ok(());
338 : }
339 0 : }?;
340 :
341 0 : if status == StatusCode::OK {
342 0 : tracing::info!(
343 0 : "Downloads to {} complete: {}/{} layers, {}/{} bytes",
344 : node,
345 : progress.layers_downloaded,
346 : progress.layers_total,
347 : progress.bytes_downloaded,
348 : progress.bytes_total
349 : );
350 0 : return Ok(());
351 0 : } else if status == StatusCode::ACCEPTED {
352 0 : let total_runtime = started_at.elapsed();
353 0 : if total_runtime > TOTAL_DOWNLOAD_TIMEOUT {
354 0 : tracing::warn!("Timed out after {}ms downloading layers to {node}. Progress so far: {}/{} layers, {}/{} bytes",
355 0 : total_runtime.as_millis(),
356 : progress.layers_downloaded,
357 : progress.layers_total,
358 : progress.bytes_downloaded,
359 : progress.bytes_total
360 : );
361 : // Give up, but proceed: an incompletely warmed destination doesn't prevent migration working,
362 : // it just makes the I/O performance for users less good.
363 0 : return Ok(());
364 0 : }
365 0 :
366 0 : // Log and proceed around the loop to retry. We don't sleep between requests, because our HTTP call
367 0 : // to the pageserver is a long-poll.
368 0 : tracing::info!(
369 0 : "Downloads to {} not yet complete: {}/{} layers, {}/{} bytes",
370 : node,
371 : progress.layers_downloaded,
372 : progress.layers_total,
373 : progress.bytes_downloaded,
374 : progress.bytes_total
375 : );
376 0 : }
377 : }
378 0 : }
379 :
380 0 : async fn await_lsn(
381 0 : &self,
382 0 : tenant_shard_id: TenantShardId,
383 0 : node: &Node,
384 0 : baseline: HashMap<TimelineId, Lsn>,
385 0 : ) -> anyhow::Result<()> {
386 : loop {
387 0 : let latest = match self.get_lsns(tenant_shard_id, node).await {
388 0 : Ok(l) => l,
389 0 : Err(e) => {
390 0 : tracing::info!("🕑 Can't get LSNs on node {node} yet, waiting ({e})",);
391 0 : std::thread::sleep(Duration::from_millis(500));
392 0 : continue;
393 : }
394 : };
395 :
396 0 : let mut any_behind: bool = false;
397 0 : for (timeline_id, baseline_lsn) in &baseline {
398 0 : match latest.get(timeline_id) {
399 0 : Some(latest_lsn) => {
400 0 : tracing::info!("🕑 LSN origin {baseline_lsn} vs destination {latest_lsn}");
401 0 : if latest_lsn < baseline_lsn {
402 0 : any_behind = true;
403 0 : }
404 : }
405 0 : None => {
406 0 : // Expected timeline isn't yet visible on migration destination.
407 0 : // (IRL we would have to account for timeline deletion, but this
408 0 : // is just test helper)
409 0 : any_behind = true;
410 0 : }
411 : }
412 : }
413 :
414 0 : if !any_behind {
415 0 : tracing::info!("✅ LSN caught up. Proceeding...");
416 0 : break;
417 0 : } else {
418 0 : std::thread::sleep(Duration::from_millis(500));
419 0 : }
420 : }
421 :
422 0 : Ok(())
423 0 : }
424 :
425 0 : pub async fn live_migrate(
426 0 : &mut self,
427 0 : origin_ps: Node,
428 0 : dest_ps: Node,
429 0 : ) -> Result<(), ReconcileError> {
430 0 : // `maybe_live_migrate` is responsibble for sanity of inputs
431 0 : assert!(origin_ps.get_id() != dest_ps.get_id());
432 :
433 0 : fn build_location_config(
434 0 : shard: &ShardIdentity,
435 0 : config: &TenantConfig,
436 0 : mode: LocationConfigMode,
437 0 : generation: Option<Generation>,
438 0 : secondary_conf: Option<LocationConfigSecondary>,
439 0 : ) -> LocationConfig {
440 0 : LocationConfig {
441 0 : mode,
442 0 : generation: generation.map(|g| g.into().unwrap()),
443 0 : secondary_conf,
444 0 : tenant_conf: config.clone(),
445 0 : shard_number: shard.number.0,
446 0 : shard_count: shard.count.literal(),
447 0 : shard_stripe_size: shard.stripe_size.0,
448 0 : }
449 0 : }
450 :
451 0 : tracing::info!("🔁 Switching origin node {origin_ps} to stale mode",);
452 :
453 : // FIXME: it is incorrect to use self.generation here, we should use the generation
454 : // from the ObservedState of the origin pageserver (it might be older than self.generation)
455 0 : let stale_conf = build_location_config(
456 0 : &self.shard,
457 0 : &self.config,
458 0 : LocationConfigMode::AttachedStale,
459 0 : self.generation,
460 0 : None,
461 0 : );
462 0 : self.location_config(&origin_ps, stale_conf, Some(Duration::from_secs(10)), false)
463 0 : .await?;
464 :
465 0 : let baseline_lsns = Some(self.get_lsns(self.tenant_shard_id, &origin_ps).await?);
466 :
467 : // If we are migrating to a destination that has a secondary location, warm it up first
468 0 : if let Some(destination_conf) = self.observed.locations.get(&dest_ps.get_id()) {
469 0 : if let Some(destination_conf) = &destination_conf.conf {
470 0 : if destination_conf.mode == LocationConfigMode::Secondary {
471 0 : tracing::info!("🔁 Downloading latest layers to destination node {dest_ps}",);
472 0 : self.secondary_download(self.tenant_shard_id, &dest_ps)
473 0 : .await?;
474 0 : }
475 0 : }
476 0 : }
477 :
478 : // Increment generation before attaching to new pageserver
479 : self.generation = Some(
480 0 : self.persistence
481 0 : .increment_generation(self.tenant_shard_id, dest_ps.get_id())
482 0 : .await?,
483 : );
484 :
485 0 : let dest_conf = build_location_config(
486 0 : &self.shard,
487 0 : &self.config,
488 0 : LocationConfigMode::AttachedMulti,
489 0 : self.generation,
490 0 : None,
491 0 : );
492 0 :
493 0 : tracing::info!("🔁 Attaching to pageserver {dest_ps}");
494 0 : self.location_config(&dest_ps, dest_conf, None, false)
495 0 : .await?;
496 :
497 0 : if let Some(baseline) = baseline_lsns {
498 0 : tracing::info!("🕑 Waiting for LSN to catch up...");
499 0 : self.await_lsn(self.tenant_shard_id, &dest_ps, baseline)
500 0 : .await?;
501 0 : }
502 :
503 0 : tracing::info!("🔁 Notifying compute to use pageserver {dest_ps}");
504 :
505 : // During a live migration it is unhelpful to proceed if we couldn't notify compute: if we detach
506 : // the origin without notifying compute, we will render the tenant unavailable.
507 0 : while let Err(e) = self.compute_notify().await {
508 0 : match e {
509 0 : NotifyError::Fatal(_) => return Err(ReconcileError::Notify(e)),
510 0 : NotifyError::ShuttingDown => return Err(ReconcileError::Cancel),
511 : _ => {
512 0 : tracing::warn!(
513 0 : "Live migration blocked by compute notification error, retrying: {e}"
514 : );
515 : }
516 : }
517 : }
518 :
519 : // Downgrade the origin to secondary. If the tenant's policy is PlacementPolicy::Attached(0), then
520 : // this location will be deleted in the general case reconciliation that runs after this.
521 0 : let origin_secondary_conf = build_location_config(
522 0 : &self.shard,
523 0 : &self.config,
524 0 : LocationConfigMode::Secondary,
525 0 : None,
526 0 : Some(LocationConfigSecondary { warm: true }),
527 0 : );
528 0 : self.location_config(&origin_ps, origin_secondary_conf.clone(), None, false)
529 0 : .await?;
530 : // TODO: we should also be setting the ObservedState on earlier API calls, in case we fail
531 : // partway through. In fact, all location conf API calls should be in a wrapper that sets
532 : // the observed state to None, then runs, then sets it to what we wrote.
533 0 : self.observed.locations.insert(
534 0 : origin_ps.get_id(),
535 0 : ObservedStateLocation {
536 0 : conf: Some(origin_secondary_conf),
537 0 : },
538 0 : );
539 0 :
540 0 : tracing::info!("🔁 Switching to AttachedSingle mode on node {dest_ps}",);
541 0 : let dest_final_conf = build_location_config(
542 0 : &self.shard,
543 0 : &self.config,
544 0 : LocationConfigMode::AttachedSingle,
545 0 : self.generation,
546 0 : None,
547 0 : );
548 0 : self.location_config(&dest_ps, dest_final_conf.clone(), None, false)
549 0 : .await?;
550 0 : self.observed.locations.insert(
551 0 : dest_ps.get_id(),
552 0 : ObservedStateLocation {
553 0 : conf: Some(dest_final_conf),
554 0 : },
555 0 : );
556 0 :
557 0 : tracing::info!("✅ Migration complete");
558 :
559 0 : Ok(())
560 0 : }
561 :
562 0 : async fn maybe_refresh_observed(&mut self) -> Result<(), ReconcileError> {
563 : // If the attached node has uncertain state, read it from the pageserver before proceeding: this
564 : // is important to avoid spurious generation increments.
565 : //
566 : // We don't need to do this for secondary/detach locations because it's harmless to just PUT their
567 : // location conf, whereas for attached locations it can interrupt clients if we spuriously destroy/recreate
568 : // the `Timeline` object in the pageserver.
569 :
570 0 : let Some(attached_node) = self.intent.attached.as_ref() else {
571 : // Nothing to do
572 0 : return Ok(());
573 : };
574 :
575 0 : if matches!(
576 0 : self.observed.locations.get(&attached_node.get_id()),
577 : Some(ObservedStateLocation { conf: None })
578 : ) {
579 0 : let tenant_shard_id = self.tenant_shard_id;
580 0 : let observed_conf = match attached_node
581 0 : .with_client_retries(
582 0 : |client| async move { client.get_location_config(tenant_shard_id).await },
583 0 : &self.service_config.jwt_token,
584 0 : 1,
585 0 : 1,
586 0 : Duration::from_secs(5),
587 0 : &self.cancel,
588 0 : )
589 0 : .await
590 : {
591 0 : Some(Ok(observed)) => Some(observed),
592 0 : Some(Err(mgmt_api::Error::ApiError(status, _msg)))
593 0 : if status == StatusCode::NOT_FOUND =>
594 0 : {
595 0 : None
596 : }
597 0 : Some(Err(e)) => return Err(e.into()),
598 0 : None => return Err(ReconcileError::Cancel),
599 : };
600 0 : tracing::info!("Scanned location configuration on {attached_node}: {observed_conf:?}");
601 0 : match observed_conf {
602 0 : Some(conf) => {
603 0 : // Pageserver returned a state: update it in observed. This may still be an indeterminate (None) state,
604 0 : // if internally the pageserver's TenantSlot was being mutated (e.g. some long running API call is still running)
605 0 : self.observed
606 0 : .locations
607 0 : .insert(attached_node.get_id(), ObservedStateLocation { conf });
608 0 : }
609 0 : None => {
610 0 : // Pageserver returned 404: we have confirmation that there is no state for this shard on that pageserver.
611 0 : self.observed.locations.remove(&attached_node.get_id());
612 0 : }
613 : }
614 0 : }
615 :
616 0 : Ok(())
617 0 : }
618 :
619 : /// Reconciling a tenant makes API calls to pageservers until the observed state
620 : /// matches the intended state.
621 : ///
622 : /// First we apply special case handling (e.g. for live migrations), and then a
623 : /// general case reconciliation where we walk through the intent by pageserver
624 : /// and call out to the pageserver to apply the desired state.
625 0 : pub(crate) async fn reconcile(&mut self) -> Result<(), ReconcileError> {
626 0 : // Prepare: if we have uncertain `observed` state for our would-be attachement location, then refresh it
627 0 : self.maybe_refresh_observed().await?;
628 :
629 : // Special case: live migration
630 0 : self.maybe_live_migrate().await?;
631 :
632 : // If the attached pageserver is not attached, do so now.
633 0 : if let Some(node) = self.intent.attached.as_ref() {
634 : // If we are in an attached policy, then generation must have been set (null generations
635 : // are only present when a tenant is initially loaded with a secondary policy)
636 0 : debug_assert!(self.generation.is_some());
637 0 : let Some(generation) = self.generation else {
638 0 : return Err(ReconcileError::Other(anyhow::anyhow!(
639 0 : "Attempted to attach with NULL generation"
640 0 : )));
641 : };
642 :
643 0 : let mut wanted_conf = attached_location_conf(
644 0 : generation,
645 0 : &self.shard,
646 0 : &self.config,
647 0 : &self.placement_policy,
648 0 : );
649 0 : match self.observed.locations.get(&node.get_id()) {
650 0 : Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {
651 0 : // Nothing to do
652 0 : tracing::info!(node_id=%node.get_id(), "Observed configuration already correct.")
653 : }
654 0 : observed => {
655 : // In all cases other than a matching observed configuration, we will
656 : // reconcile this location. This includes locations with different configurations, as well
657 : // as locations with unknown (None) observed state.
658 :
659 : // Incrementing generation is the safe general case, but is inefficient for changes that only
660 : // modify some details (e.g. the tenant's config).
661 0 : let increment_generation = match observed {
662 0 : None => true,
663 0 : Some(ObservedStateLocation { conf: None }) => true,
664 : Some(ObservedStateLocation {
665 0 : conf: Some(observed),
666 0 : }) => {
667 0 : let generations_match = observed.generation == wanted_conf.generation;
668 0 :
669 0 : // We may skip incrementing the generation if the location is already in the expected mode and
670 0 : // generation. In principle it would also be safe to skip from certain other modes (e.g. AttachedStale),
671 0 : // but such states are handled inside `live_migrate`, and if we see that state here we're cleaning up
672 0 : // after a restart/crash, so fall back to the universally safe path of incrementing generation.
673 0 : !generations_match || (observed.mode != wanted_conf.mode)
674 : }
675 : };
676 :
677 0 : if increment_generation {
678 0 : let generation = self
679 0 : .persistence
680 0 : .increment_generation(self.tenant_shard_id, node.get_id())
681 0 : .await?;
682 0 : self.generation = Some(generation);
683 0 : wanted_conf.generation = generation.into();
684 0 : }
685 0 : tracing::info!(node_id=%node.get_id(), "Observed configuration requires update.");
686 :
687 : // Because `node` comes from a ref to &self, clone it before calling into a &mut self
688 : // function: this could be avoided by refactoring the state mutated by location_config into
689 : // a separate type to Self.
690 0 : let node = node.clone();
691 0 :
692 0 : // Use lazy=true, because we may run many of Self concurrently, and do not want to
693 0 : // overload the pageserver with logical size calculations.
694 0 : self.location_config(&node, wanted_conf, None, true).await?;
695 0 : self.compute_notify().await?;
696 : }
697 : }
698 0 : }
699 :
700 : // Configure secondary locations: if these were previously attached this
701 : // implicitly downgrades them from attached to secondary.
702 0 : let mut changes = Vec::new();
703 0 : for node in &self.intent.secondary {
704 0 : let wanted_conf = secondary_location_conf(&self.shard, &self.config);
705 0 : match self.observed.locations.get(&node.get_id()) {
706 0 : Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {
707 0 : // Nothing to do
708 0 : tracing::info!(node_id=%node.get_id(), "Observed configuration already correct.")
709 : }
710 : _ => {
711 : // In all cases other than a matching observed configuration, we will
712 : // reconcile this location.
713 0 : tracing::info!(node_id=%node.get_id(), "Observed configuration requires update.");
714 0 : changes.push((node.clone(), wanted_conf))
715 : }
716 : }
717 : }
718 :
719 : // Detach any extraneous pageservers that are no longer referenced
720 : // by our intent.
721 0 : for node in &self.detach {
722 0 : changes.push((
723 0 : node.clone(),
724 0 : LocationConfig {
725 0 : mode: LocationConfigMode::Detached,
726 0 : generation: None,
727 0 : secondary_conf: None,
728 0 : shard_number: self.shard.number.0,
729 0 : shard_count: self.shard.count.literal(),
730 0 : shard_stripe_size: self.shard.stripe_size.0,
731 0 : tenant_conf: self.config.clone(),
732 0 : },
733 0 : ));
734 0 : }
735 :
736 0 : for (node, conf) in changes {
737 0 : if self.cancel.is_cancelled() {
738 0 : return Err(ReconcileError::Cancel);
739 0 : }
740 0 : self.location_config(&node, conf, None, false).await?;
741 : }
742 :
743 0 : failpoint_support::sleep_millis_async!("sleep-on-reconcile-epilogue");
744 :
745 0 : Ok(())
746 0 : }
747 :
748 0 : pub(crate) async fn compute_notify(&mut self) -> Result<(), NotifyError> {
749 : // Whenever a particular Reconciler emits a notification, it is always notifying for the intended
750 : // destination.
751 0 : if let Some(node) = &self.intent.attached {
752 0 : let result = self
753 0 : .compute_hook
754 0 : .notify(
755 0 : self.tenant_shard_id,
756 0 : node.get_id(),
757 0 : self.shard.stripe_size,
758 0 : &self.cancel,
759 0 : )
760 0 : .await;
761 0 : if let Err(e) = &result {
762 : // It is up to the caller whether they want to drop out on this error, but they don't have to:
763 : // in general we should avoid letting unavailability of the cloud control plane stop us from
764 : // making progress.
765 0 : if !matches!(e, NotifyError::ShuttingDown) {
766 0 : tracing::warn!("Failed to notify compute of attached pageserver {node}: {e}");
767 0 : }
768 :
769 : // Set this flag so that in our ReconcileResult we will set the flag on the shard that it
770 : // needs to retry at some point.
771 0 : self.compute_notify_failure = true;
772 0 : }
773 0 : result
774 : } else {
775 0 : Ok(())
776 : }
777 0 : }
778 : }
779 :
780 : /// We tweak the externally-set TenantConfig while configuring
781 : /// locations, using our awareness of whether secondary locations
782 : /// are in use to automatically enable/disable heatmap uploads.
783 0 : fn ha_aware_config(config: &TenantConfig, has_secondaries: bool) -> TenantConfig {
784 0 : let mut config = config.clone();
785 0 : if has_secondaries {
786 0 : if config.heatmap_period.is_none() {
787 0 : config.heatmap_period = Some(DEFAULT_HEATMAP_PERIOD.to_string());
788 0 : }
789 0 : } else {
790 0 : config.heatmap_period = None;
791 0 : }
792 0 : config
793 0 : }
794 :
795 0 : pub(crate) fn attached_location_conf(
796 0 : generation: Generation,
797 0 : shard: &ShardIdentity,
798 0 : config: &TenantConfig,
799 0 : policy: &PlacementPolicy,
800 0 : ) -> LocationConfig {
801 0 : let has_secondaries = match policy {
802 : PlacementPolicy::Attached(0) | PlacementPolicy::Detached | PlacementPolicy::Secondary => {
803 0 : false
804 : }
805 0 : PlacementPolicy::Attached(_) => true,
806 : };
807 :
808 0 : LocationConfig {
809 0 : mode: LocationConfigMode::AttachedSingle,
810 0 : generation: generation.into(),
811 0 : secondary_conf: None,
812 0 : shard_number: shard.number.0,
813 0 : shard_count: shard.count.literal(),
814 0 : shard_stripe_size: shard.stripe_size.0,
815 0 : tenant_conf: ha_aware_config(config, has_secondaries),
816 0 : }
817 0 : }
818 :
819 0 : pub(crate) fn secondary_location_conf(
820 0 : shard: &ShardIdentity,
821 0 : config: &TenantConfig,
822 0 : ) -> LocationConfig {
823 0 : LocationConfig {
824 0 : mode: LocationConfigMode::Secondary,
825 0 : generation: None,
826 0 : secondary_conf: Some(LocationConfigSecondary { warm: true }),
827 0 : shard_number: shard.number.0,
828 0 : shard_count: shard.count.literal(),
829 0 : shard_stripe_size: shard.stripe_size.0,
830 0 : tenant_conf: ha_aware_config(config, true),
831 0 : }
832 0 : }
|