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