Line data Source code
1 : use crate::pageserver_client::PageserverClient;
2 : use crate::persistence::Persistence;
3 : use crate::{compute_hook, service};
4 : use pageserver_api::controller_api::{AvailabilityZone, MigrationConfig, PlacementPolicy};
5 : use pageserver_api::models::{
6 : LocationConfig, LocationConfigMode, LocationConfigSecondary, TenantConfig, TenantWaitLsnRequest,
7 : };
8 : use pageserver_api::shard::{ShardIdentity, TenantShardId};
9 : use pageserver_client::mgmt_api;
10 : use reqwest::StatusCode;
11 : use std::borrow::Cow;
12 : use std::collections::HashMap;
13 : use std::sync::Arc;
14 : use std::time::{Duration, Instant};
15 : use tokio_util::sync::CancellationToken;
16 : use utils::backoff::exponential_backoff;
17 : use utils::generation::Generation;
18 : use utils::id::{NodeId, TimelineId};
19 : use utils::lsn::Lsn;
20 : use utils::pausable_failpoint;
21 : use utils::sync::gate::GateGuard;
22 :
23 : use crate::compute_hook::{ComputeHook, NotifyError};
24 : use crate::node::Node;
25 : use crate::tenant_shard::{IntentState, ObservedState, ObservedStateDelta, ObservedStateLocation};
26 :
27 : const DEFAULT_HEATMAP_PERIOD: &str = "60s";
28 :
29 : /// Object with the lifetime of the background reconcile task that is created
30 : /// for tenants which have a difference between their intent and observed states.
31 : pub(super) struct Reconciler {
32 : /// See [`crate::tenant_shard::TenantShard`] for the meanings of these fields: they are a snapshot
33 : /// of a tenant's state from when we spawned a reconcile task.
34 : pub(super) tenant_shard_id: TenantShardId,
35 : pub(crate) shard: ShardIdentity,
36 : pub(crate) placement_policy: PlacementPolicy,
37 : pub(crate) generation: Option<Generation>,
38 : pub(crate) intent: TargetState,
39 :
40 : /// Nodes not referenced by [`Self::intent`], from which we should try
41 : /// to detach this tenant shard.
42 : pub(crate) detach: Vec<Node>,
43 :
44 : /// Configuration specific to this reconciler
45 : pub(crate) reconciler_config: ReconcilerConfig,
46 :
47 : pub(crate) config: TenantConfig,
48 : pub(crate) preferred_az: Option<AvailabilityZone>,
49 :
50 : /// Observed state from the point of view of the reconciler.
51 : /// This gets updated as the reconciliation makes progress.
52 : pub(crate) observed: ObservedState,
53 :
54 : /// Snapshot of the observed state at the point when the reconciler
55 : /// was spawned.
56 : pub(crate) original_observed: ObservedState,
57 :
58 : pub(crate) service_config: service::Config,
59 :
60 : /// A hook to notify the running postgres instances when we change the location
61 : /// of a tenant. Use this via [`Self::compute_notify`] to update our failure flag
62 : /// and guarantee eventual retries.
63 : pub(crate) compute_hook: Arc<ComputeHook>,
64 :
65 : /// To avoid stalling if the cloud control plane is unavailable, we may proceed
66 : /// past failures in [`ComputeHook::notify`], but we _must_ remember that we failed
67 : /// so that we can set [`crate::tenant_shard::TenantShard::pending_compute_notification`] to ensure a later retry.
68 : pub(crate) compute_notify_failure: bool,
69 :
70 : /// Reconciler is responsible for keeping alive semaphore units that limit concurrency on how many
71 : /// we will spawn.
72 : pub(crate) _resource_units: ReconcileUnits,
73 :
74 : /// A means to abort background reconciliation: it is essential to
75 : /// call this when something changes in the original TenantShard that
76 : /// will make this reconciliation impossible or unnecessary, for
77 : /// example when a pageserver node goes offline, or the PlacementPolicy for
78 : /// the tenant is changed.
79 : pub(crate) cancel: CancellationToken,
80 :
81 : /// Reconcilers are registered with a Gate so that during a graceful shutdown we
82 : /// can wait for all the reconcilers to respond to their cancellation tokens.
83 : pub(crate) _gate_guard: GateGuard,
84 :
85 : /// Access to persistent storage for updating generation numbers
86 : pub(crate) persistence: Arc<Persistence>,
87 : }
88 :
89 : pub(crate) struct ReconcilerConfigBuilder {
90 : config: ReconcilerConfig,
91 : }
92 :
93 : impl ReconcilerConfigBuilder {
94 0 : pub(crate) fn new() -> Self {
95 0 : Self {
96 0 : config: ReconcilerConfig::default(),
97 0 : }
98 0 : }
99 :
100 0 : pub(crate) fn secondary_warmup_timeout(self, value: Duration) -> Self {
101 0 : Self {
102 0 : config: ReconcilerConfig {
103 0 : secondary_warmup_timeout: Some(value),
104 0 : ..self.config
105 0 : },
106 0 : }
107 0 : }
108 :
109 0 : pub(crate) fn secondary_download_request_timeout(self, value: Duration) -> Self {
110 0 : Self {
111 0 : config: ReconcilerConfig {
112 0 : secondary_download_request_timeout: Some(value),
113 0 : ..self.config
114 0 : },
115 0 : }
116 0 : }
117 :
118 0 : pub(crate) fn tenant_creation_hint(self, hint: bool) -> Self {
119 0 : Self {
120 0 : config: ReconcilerConfig {
121 0 : tenant_creation_hint: hint,
122 0 : ..self.config
123 0 : },
124 0 : }
125 0 : }
126 :
127 0 : pub(crate) fn build(self) -> ReconcilerConfig {
128 0 : self.config
129 0 : }
130 : }
131 :
132 : #[derive(Default, Debug, Copy, Clone)]
133 : pub(crate) struct ReconcilerConfig {
134 : // During live migration give up on warming-up the secondary
135 : // after this timeout.
136 : secondary_warmup_timeout: Option<Duration>,
137 :
138 : // During live migrations this is the amount of time that
139 : // the pagserver will hold our poll.
140 : secondary_download_request_timeout: Option<Duration>,
141 :
142 : // A hint indicating whether this reconciliation is done on the
143 : // creation of a new tenant. This only informs logging behaviour.
144 : tenant_creation_hint: bool,
145 : }
146 :
147 : impl ReconcilerConfig {
148 0 : pub(crate) fn get_secondary_warmup_timeout(&self) -> Duration {
149 : const SECONDARY_WARMUP_TIMEOUT_DEFAULT: Duration = Duration::from_secs(300);
150 0 : self.secondary_warmup_timeout
151 0 : .unwrap_or(SECONDARY_WARMUP_TIMEOUT_DEFAULT)
152 0 : }
153 :
154 0 : pub(crate) fn get_secondary_download_request_timeout(&self) -> Duration {
155 : const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT_DEFAULT: Duration = Duration::from_secs(20);
156 0 : self.secondary_download_request_timeout
157 0 : .unwrap_or(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT_DEFAULT)
158 0 : }
159 :
160 0 : pub(crate) fn tenant_creation_hint(&self) -> bool {
161 0 : self.tenant_creation_hint
162 0 : }
163 : }
164 :
165 : impl From<&MigrationConfig> for ReconcilerConfig {
166 0 : fn from(value: &MigrationConfig) -> Self {
167 0 : let mut builder = ReconcilerConfigBuilder::new();
168 :
169 0 : if let Some(timeout) = value.secondary_warmup_timeout {
170 0 : builder = builder.secondary_warmup_timeout(timeout)
171 0 : }
172 :
173 0 : if let Some(timeout) = value.secondary_download_request_timeout {
174 0 : builder = builder.secondary_download_request_timeout(timeout)
175 0 : }
176 :
177 0 : builder.build()
178 0 : }
179 : }
180 :
181 : /// RAII resource units granted to a Reconciler, which it should keep alive until it finishes doing I/O
182 : pub(crate) struct ReconcileUnits {
183 : _sem_units: tokio::sync::OwnedSemaphorePermit,
184 : }
185 :
186 : impl ReconcileUnits {
187 0 : pub(crate) fn new(sem_units: tokio::sync::OwnedSemaphorePermit) -> Self {
188 0 : Self {
189 0 : _sem_units: sem_units,
190 0 : }
191 0 : }
192 : }
193 :
194 : /// This is a snapshot of [`crate::tenant_shard::IntentState`], but it does not do any
195 : /// reference counting for Scheduler. The IntentState is what the scheduler works with,
196 : /// and the TargetState is just the instruction for a particular Reconciler run.
197 : #[derive(Debug)]
198 : pub(crate) struct TargetState {
199 : pub(crate) attached: Option<Node>,
200 : pub(crate) secondary: Vec<Node>,
201 : }
202 :
203 : impl TargetState {
204 0 : pub(crate) fn from_intent(nodes: &HashMap<NodeId, Node>, intent: &IntentState) -> Self {
205 0 : Self {
206 0 : attached: intent.get_attached().map(|n| {
207 0 : nodes
208 0 : .get(&n)
209 0 : .expect("Intent attached referenced non-existent node")
210 0 : .clone()
211 0 : }),
212 0 : secondary: intent
213 0 : .get_secondary()
214 0 : .iter()
215 0 : .map(|n| {
216 0 : nodes
217 0 : .get(n)
218 0 : .expect("Intent secondary referenced non-existent node")
219 0 : .clone()
220 0 : })
221 0 : .collect(),
222 0 : }
223 0 : }
224 : }
225 :
226 : #[derive(thiserror::Error, Debug)]
227 : pub(crate) enum ReconcileError {
228 : #[error(transparent)]
229 : Remote(#[from] mgmt_api::Error),
230 : #[error(transparent)]
231 : Notify(#[from] NotifyError),
232 : #[error("Cancelled")]
233 : Cancel,
234 : #[error(transparent)]
235 : Other(#[from] anyhow::Error),
236 : }
237 :
238 : impl Reconciler {
239 0 : async fn location_config(
240 0 : &mut self,
241 0 : node: &Node,
242 0 : config: LocationConfig,
243 0 : flush_ms: Option<Duration>,
244 0 : lazy: bool,
245 0 : ) -> Result<(), ReconcileError> {
246 0 : if !node.is_available() && config.mode == LocationConfigMode::Detached {
247 : // [`crate::service::Service::node_activate_reconcile`] will update the observed state
248 : // when the node comes back online. At that point, the intent and observed states will
249 : // be mismatched and a background reconciliation will detach.
250 0 : tracing::info!(
251 0 : "Node {node} is unavailable during detach: proceeding anyway, it will be detached via background reconciliation"
252 : );
253 0 : return Ok(());
254 0 : }
255 0 :
256 0 : self.observed
257 0 : .locations
258 0 : .insert(node.get_id(), ObservedStateLocation { conf: None });
259 0 :
260 0 : // TODO: amend locations that use long-polling: they will hit this timeout.
261 0 : let timeout = Duration::from_secs(25);
262 0 :
263 0 : tracing::info!("location_config({node}) calling: {:?}", config);
264 0 : let tenant_shard_id = self.tenant_shard_id;
265 0 : let config_ref = &config;
266 0 : match node
267 0 : .with_client_retries(
268 0 : |client| async move {
269 0 : let config = config_ref.clone();
270 0 : client
271 0 : .location_config(tenant_shard_id, config.clone(), flush_ms, lazy)
272 0 : .await
273 0 : },
274 0 : &self.service_config.jwt_token,
275 0 : 1,
276 0 : 3,
277 0 : timeout,
278 0 : &self.cancel,
279 0 : )
280 0 : .await
281 : {
282 0 : Some(Ok(_)) => {}
283 0 : Some(Err(e)) => return Err(e.into()),
284 0 : None => return Err(ReconcileError::Cancel),
285 : };
286 0 : tracing::info!("location_config({node}) complete: {:?}", config);
287 :
288 0 : match config.mode {
289 0 : LocationConfigMode::Detached => {
290 0 : self.observed.locations.remove(&node.get_id());
291 0 : }
292 0 : _ => {
293 0 : self.observed
294 0 : .locations
295 0 : .insert(node.get_id(), ObservedStateLocation { conf: Some(config) });
296 0 : }
297 : }
298 :
299 0 : Ok(())
300 0 : }
301 :
302 0 : fn get_node(&self, node_id: &NodeId) -> Option<&Node> {
303 0 : if let Some(node) = self.intent.attached.as_ref() {
304 0 : if node.get_id() == *node_id {
305 0 : return Some(node);
306 0 : }
307 0 : }
308 :
309 0 : if let Some(node) = self
310 0 : .intent
311 0 : .secondary
312 0 : .iter()
313 0 : .find(|n| n.get_id() == *node_id)
314 : {
315 0 : return Some(node);
316 0 : }
317 :
318 0 : if let Some(node) = self.detach.iter().find(|n| n.get_id() == *node_id) {
319 0 : return Some(node);
320 0 : }
321 0 :
322 0 : None
323 0 : }
324 :
325 0 : async fn maybe_live_migrate(&mut self) -> Result<(), ReconcileError> {
326 0 : let destination = if let Some(node) = &self.intent.attached {
327 0 : match self.observed.locations.get(&node.get_id()) {
328 0 : Some(conf) => {
329 : // We will do a live migration only if the intended destination is not
330 : // currently in an attached state.
331 0 : match &conf.conf {
332 0 : Some(conf) if conf.mode == LocationConfigMode::Secondary => {
333 0 : // Fall through to do a live migration
334 0 : node
335 : }
336 : None | Some(_) => {
337 : // Attached or uncertain: don't do a live migration, proceed
338 : // with a general-case reconciliation
339 0 : tracing::info!("maybe_live_migrate: destination is None or attached");
340 0 : return Ok(());
341 : }
342 : }
343 : }
344 : None => {
345 : // Our destination is not attached: maybe live migrate if some other
346 : // node is currently attached. Fall through.
347 0 : node
348 : }
349 : }
350 : } else {
351 : // No intent to be attached
352 0 : tracing::info!("maybe_live_migrate: no attached intent");
353 0 : return Ok(());
354 : };
355 :
356 0 : let mut origin = None;
357 0 : for (node_id, state) in &self.observed.locations {
358 0 : if let Some(observed_conf) = &state.conf {
359 0 : if observed_conf.mode == LocationConfigMode::AttachedSingle {
360 : // We will only attempt live migration if the origin is not offline: this
361 : // avoids trying to do it while reconciling after responding to an HA failover.
362 0 : if let Some(node) = self.get_node(node_id) {
363 0 : if node.is_available() {
364 0 : origin = Some(node.clone());
365 0 : break;
366 0 : }
367 0 : }
368 0 : }
369 0 : }
370 : }
371 :
372 0 : let Some(origin) = origin else {
373 0 : tracing::info!("maybe_live_migrate: no origin found");
374 0 : return Ok(());
375 : };
376 :
377 : // We have an origin and a destination: proceed to do the live migration
378 0 : tracing::info!("Live migrating {}->{}", origin, destination);
379 0 : self.live_migrate(origin, destination.clone()).await?;
380 :
381 0 : Ok(())
382 0 : }
383 :
384 0 : async fn wait_lsn(
385 0 : &self,
386 0 : node: &Node,
387 0 : tenant_shard_id: TenantShardId,
388 0 : timelines: HashMap<TimelineId, Lsn>,
389 0 : ) -> Result<StatusCode, ReconcileError> {
390 : const TIMEOUT: Duration = Duration::from_secs(10);
391 :
392 0 : let client = PageserverClient::new(
393 0 : node.get_id(),
394 0 : node.base_url(),
395 0 : self.service_config.jwt_token.as_deref(),
396 0 : );
397 0 :
398 0 : client
399 0 : .wait_lsn(
400 0 : tenant_shard_id,
401 0 : TenantWaitLsnRequest {
402 0 : timelines,
403 0 : timeout: TIMEOUT,
404 0 : },
405 0 : )
406 0 : .await
407 0 : .map_err(|e| e.into())
408 0 : }
409 :
410 0 : async fn get_lsns(
411 0 : &self,
412 0 : tenant_shard_id: TenantShardId,
413 0 : node: &Node,
414 0 : ) -> anyhow::Result<HashMap<TimelineId, Lsn>> {
415 0 : let client = PageserverClient::new(
416 0 : node.get_id(),
417 0 : node.base_url(),
418 0 : self.service_config.jwt_token.as_deref(),
419 0 : );
420 :
421 0 : let timelines = client.timeline_list(&tenant_shard_id).await?;
422 0 : Ok(timelines
423 0 : .into_iter()
424 0 : .map(|t| (t.timeline_id, t.last_record_lsn))
425 0 : .collect())
426 0 : }
427 :
428 0 : async fn secondary_download(
429 0 : &self,
430 0 : tenant_shard_id: TenantShardId,
431 0 : node: &Node,
432 0 : ) -> Result<(), ReconcileError> {
433 0 : // This is not the timeout for a request, but the total amount of time we're willing to wait
434 0 : // for a secondary location to get up to date before
435 0 : let total_download_timeout = self.reconciler_config.get_secondary_warmup_timeout();
436 0 :
437 0 : // This the long-polling interval for the secondary download requests we send to destination pageserver
438 0 : // during a migration.
439 0 : let request_download_timeout = self
440 0 : .reconciler_config
441 0 : .get_secondary_download_request_timeout();
442 0 :
443 0 : let started_at = Instant::now();
444 :
445 : loop {
446 0 : let (status, progress) = match node
447 0 : .with_client_retries(
448 0 : |client| async move {
449 0 : client
450 0 : .tenant_secondary_download(
451 0 : tenant_shard_id,
452 0 : Some(request_download_timeout),
453 0 : )
454 0 : .await
455 0 : },
456 0 : &self.service_config.jwt_token,
457 0 : 1,
458 0 : 3,
459 0 : request_download_timeout * 2,
460 0 : &self.cancel,
461 0 : )
462 0 : .await
463 : {
464 0 : None => Err(ReconcileError::Cancel),
465 0 : Some(Ok(v)) => Ok(v),
466 0 : Some(Err(e)) => {
467 0 : // Give up, but proceed: it's unfortunate if we couldn't freshen the destination before
468 0 : // attaching, but we should not let an issue with a secondary location stop us proceeding
469 0 : // with a live migration.
470 0 : tracing::warn!("Failed to prepare by downloading layers on node {node}: {e})");
471 0 : return Ok(());
472 : }
473 0 : }?;
474 :
475 0 : if status == StatusCode::OK {
476 0 : tracing::info!(
477 0 : "Downloads to {} complete: {}/{} layers, {}/{} bytes",
478 : node,
479 : progress.layers_downloaded,
480 : progress.layers_total,
481 : progress.bytes_downloaded,
482 : progress.bytes_total
483 : );
484 0 : return Ok(());
485 0 : } else if status == StatusCode::ACCEPTED {
486 0 : let total_runtime = started_at.elapsed();
487 0 : if total_runtime > total_download_timeout {
488 0 : tracing::warn!("Timed out after {}ms downloading layers to {node}. Progress so far: {}/{} layers, {}/{} bytes",
489 0 : total_runtime.as_millis(),
490 : progress.layers_downloaded,
491 : progress.layers_total,
492 : progress.bytes_downloaded,
493 : progress.bytes_total
494 : );
495 : // Give up, but proceed: an incompletely warmed destination doesn't prevent migration working,
496 : // it just makes the I/O performance for users less good.
497 0 : return Ok(());
498 0 : }
499 0 :
500 0 : // Log and proceed around the loop to retry. We don't sleep between requests, because our HTTP call
501 0 : // to the pageserver is a long-poll.
502 0 : tracing::info!(
503 0 : "Downloads to {} not yet complete: {}/{} layers, {}/{} bytes",
504 : node,
505 : progress.layers_downloaded,
506 : progress.layers_total,
507 : progress.bytes_downloaded,
508 : progress.bytes_total
509 : );
510 0 : }
511 : }
512 0 : }
513 :
514 : /// This function does _not_ mutate any state, so it is cancellation safe.
515 : ///
516 : /// This function does not respect [`Self::cancel`], callers should handle that.
517 0 : async fn await_lsn(
518 0 : &self,
519 0 : tenant_shard_id: TenantShardId,
520 0 : node: &Node,
521 0 : baseline: HashMap<TimelineId, Lsn>,
522 0 : ) -> anyhow::Result<()> {
523 : // Signal to the pageserver that it should ingest up to the baseline LSNs.
524 : loop {
525 0 : match self.wait_lsn(node, tenant_shard_id, baseline.clone()).await {
526 : Ok(StatusCode::OK) => {
527 : // Everything is caught up
528 0 : return Ok(());
529 : }
530 : Ok(StatusCode::ACCEPTED) => {
531 : // Some timelines are not caught up yet.
532 : // They'll be polled below.
533 0 : break;
534 : }
535 : Ok(StatusCode::NOT_FOUND) => {
536 : // None of the timelines are present on the pageserver.
537 : // This is correct if they've all been deleted, but
538 : // let let the polling loop below cross check.
539 0 : break;
540 : }
541 0 : Ok(status_code) => {
542 0 : tracing::warn!(
543 0 : "Unexpected status code ({status_code}) returned by wait_lsn endpoint"
544 : );
545 0 : break;
546 : }
547 0 : Err(e) => {
548 0 : tracing::info!("🕑 Can't trigger LSN wait on {node} yet, waiting ({e})",);
549 0 : tokio::time::sleep(Duration::from_millis(500)).await;
550 0 : continue;
551 : }
552 : }
553 : }
554 :
555 : // Poll the LSNs until they catch up
556 : loop {
557 0 : let latest = match self.get_lsns(tenant_shard_id, node).await {
558 0 : Ok(l) => l,
559 0 : Err(e) => {
560 0 : tracing::info!("🕑 Can't get LSNs on node {node} yet, waiting ({e})",);
561 0 : tokio::time::sleep(Duration::from_millis(500)).await;
562 0 : continue;
563 : }
564 : };
565 :
566 0 : let mut any_behind: bool = false;
567 0 : for (timeline_id, baseline_lsn) in &baseline {
568 0 : match latest.get(timeline_id) {
569 0 : Some(latest_lsn) => {
570 0 : tracing::info!(timeline_id = %timeline_id, "🕑 LSN origin {baseline_lsn} vs destination {latest_lsn}");
571 0 : if latest_lsn < baseline_lsn {
572 0 : any_behind = true;
573 0 : }
574 : }
575 0 : None => {
576 0 : // Timeline was deleted in the meantime - ignore it
577 0 : }
578 : }
579 : }
580 :
581 0 : if !any_behind {
582 0 : tracing::info!("✅ LSN caught up. Proceeding...");
583 0 : break;
584 : } else {
585 0 : tokio::time::sleep(Duration::from_millis(500)).await;
586 : }
587 : }
588 :
589 0 : Ok(())
590 0 : }
591 :
592 0 : pub async fn live_migrate(
593 0 : &mut self,
594 0 : origin_ps: Node,
595 0 : dest_ps: Node,
596 0 : ) -> Result<(), ReconcileError> {
597 0 : // `maybe_live_migrate` is responsibble for sanity of inputs
598 0 : assert!(origin_ps.get_id() != dest_ps.get_id());
599 :
600 0 : fn build_location_config(
601 0 : shard: &ShardIdentity,
602 0 : config: &TenantConfig,
603 0 : mode: LocationConfigMode,
604 0 : generation: Option<Generation>,
605 0 : secondary_conf: Option<LocationConfigSecondary>,
606 0 : ) -> LocationConfig {
607 0 : LocationConfig {
608 0 : mode,
609 0 : generation: generation.map(|g| g.into().unwrap()),
610 0 : secondary_conf,
611 0 : tenant_conf: config.clone(),
612 0 : shard_number: shard.number.0,
613 0 : shard_count: shard.count.literal(),
614 0 : shard_stripe_size: shard.stripe_size.0,
615 0 : }
616 0 : }
617 :
618 0 : tracing::info!("🔁 Switching origin node {origin_ps} to stale mode",);
619 :
620 : // FIXME: it is incorrect to use self.generation here, we should use the generation
621 : // from the ObservedState of the origin pageserver (it might be older than self.generation)
622 0 : let stale_conf = build_location_config(
623 0 : &self.shard,
624 0 : &self.config,
625 0 : LocationConfigMode::AttachedStale,
626 0 : self.generation,
627 0 : None,
628 0 : );
629 0 : self.location_config(&origin_ps, stale_conf, Some(Duration::from_secs(10)), false)
630 0 : .await?;
631 :
632 0 : let baseline_lsns = Some(self.get_lsns(self.tenant_shard_id, &origin_ps).await?);
633 :
634 : // If we are migrating to a destination that has a secondary location, warm it up first
635 0 : if let Some(destination_conf) = self.observed.locations.get(&dest_ps.get_id()) {
636 0 : if let Some(destination_conf) = &destination_conf.conf {
637 0 : if destination_conf.mode == LocationConfigMode::Secondary {
638 0 : tracing::info!("🔁 Downloading latest layers to destination node {dest_ps}",);
639 0 : self.secondary_download(self.tenant_shard_id, &dest_ps)
640 0 : .await?;
641 0 : }
642 0 : }
643 0 : }
644 :
645 0 : pausable_failpoint!("reconciler-live-migrate-pre-generation-inc");
646 :
647 : // Increment generation before attaching to new pageserver
648 : self.generation = Some(
649 0 : self.persistence
650 0 : .increment_generation(self.tenant_shard_id, dest_ps.get_id())
651 0 : .await?,
652 : );
653 :
654 0 : let dest_conf = build_location_config(
655 0 : &self.shard,
656 0 : &self.config,
657 0 : LocationConfigMode::AttachedMulti,
658 0 : self.generation,
659 0 : None,
660 0 : );
661 0 :
662 0 : tracing::info!("🔁 Attaching to pageserver {dest_ps}");
663 0 : self.location_config(&dest_ps, dest_conf, None, false)
664 0 : .await?;
665 :
666 0 : pausable_failpoint!("reconciler-live-migrate-pre-await-lsn");
667 :
668 0 : if let Some(baseline) = baseline_lsns {
669 0 : tracing::info!("🕑 Waiting for LSN to catch up...");
670 0 : tokio::select! {
671 0 : r = self.await_lsn(self.tenant_shard_id, &dest_ps, baseline) => {r?;}
672 0 : _ = self.cancel.cancelled() => {return Err(ReconcileError::Cancel)}
673 : };
674 0 : }
675 :
676 0 : tracing::info!("🔁 Notifying compute to use pageserver {dest_ps}");
677 :
678 : // During a live migration it is unhelpful to proceed if we couldn't notify compute: if we detach
679 : // the origin without notifying compute, we will render the tenant unavailable.
680 0 : self.compute_notify_blocking(&origin_ps).await?;
681 0 : pausable_failpoint!("reconciler-live-migrate-post-notify");
682 :
683 : // Downgrade the origin to secondary. If the tenant's policy is PlacementPolicy::Attached(0), then
684 : // this location will be deleted in the general case reconciliation that runs after this.
685 0 : let origin_secondary_conf = build_location_config(
686 0 : &self.shard,
687 0 : &self.config,
688 0 : LocationConfigMode::Secondary,
689 0 : None,
690 0 : Some(LocationConfigSecondary { warm: true }),
691 0 : );
692 0 : self.location_config(&origin_ps, origin_secondary_conf.clone(), None, false)
693 0 : .await?;
694 : // TODO: we should also be setting the ObservedState on earlier API calls, in case we fail
695 : // partway through. In fact, all location conf API calls should be in a wrapper that sets
696 : // the observed state to None, then runs, then sets it to what we wrote.
697 0 : self.observed.locations.insert(
698 0 : origin_ps.get_id(),
699 0 : ObservedStateLocation {
700 0 : conf: Some(origin_secondary_conf),
701 0 : },
702 0 : );
703 0 :
704 0 : pausable_failpoint!("reconciler-live-migrate-post-detach");
705 :
706 0 : tracing::info!("🔁 Switching to AttachedSingle mode on node {dest_ps}",);
707 0 : let dest_final_conf = build_location_config(
708 0 : &self.shard,
709 0 : &self.config,
710 0 : LocationConfigMode::AttachedSingle,
711 0 : self.generation,
712 0 : None,
713 0 : );
714 0 : self.location_config(&dest_ps, dest_final_conf.clone(), None, false)
715 0 : .await?;
716 0 : self.observed.locations.insert(
717 0 : dest_ps.get_id(),
718 0 : ObservedStateLocation {
719 0 : conf: Some(dest_final_conf),
720 0 : },
721 0 : );
722 0 :
723 0 : tracing::info!("✅ Migration complete");
724 :
725 0 : Ok(())
726 0 : }
727 :
728 0 : async fn maybe_refresh_observed(&mut self) -> Result<(), ReconcileError> {
729 : // If the attached node has uncertain state, read it from the pageserver before proceeding: this
730 : // is important to avoid spurious generation increments.
731 : //
732 : // We don't need to do this for secondary/detach locations because it's harmless to just PUT their
733 : // location conf, whereas for attached locations it can interrupt clients if we spuriously destroy/recreate
734 : // the `Timeline` object in the pageserver.
735 :
736 0 : let Some(attached_node) = self.intent.attached.as_ref() else {
737 : // Nothing to do
738 0 : return Ok(());
739 : };
740 :
741 0 : if matches!(
742 0 : self.observed.locations.get(&attached_node.get_id()),
743 : Some(ObservedStateLocation { conf: None })
744 : ) {
745 0 : let tenant_shard_id = self.tenant_shard_id;
746 0 : let observed_conf = match attached_node
747 0 : .with_client_retries(
748 0 : |client| async move { client.get_location_config(tenant_shard_id).await },
749 0 : &self.service_config.jwt_token,
750 0 : 1,
751 0 : 1,
752 0 : Duration::from_secs(5),
753 0 : &self.cancel,
754 0 : )
755 0 : .await
756 : {
757 0 : Some(Ok(observed)) => Some(observed),
758 0 : Some(Err(mgmt_api::Error::ApiError(status, _msg)))
759 0 : if status == StatusCode::NOT_FOUND =>
760 0 : {
761 0 : None
762 : }
763 0 : Some(Err(e)) => return Err(e.into()),
764 0 : None => return Err(ReconcileError::Cancel),
765 : };
766 0 : tracing::info!("Scanned location configuration on {attached_node}: {observed_conf:?}");
767 0 : match observed_conf {
768 0 : Some(conf) => {
769 0 : // Pageserver returned a state: update it in observed. This may still be an indeterminate (None) state,
770 0 : // if internally the pageserver's TenantSlot was being mutated (e.g. some long running API call is still running)
771 0 : self.observed
772 0 : .locations
773 0 : .insert(attached_node.get_id(), ObservedStateLocation { conf });
774 0 : }
775 0 : None => {
776 0 : // Pageserver returned 404: we have confirmation that there is no state for this shard on that pageserver.
777 0 : self.observed.locations.remove(&attached_node.get_id());
778 0 : }
779 : }
780 0 : }
781 :
782 0 : Ok(())
783 0 : }
784 :
785 : /// Reconciling a tenant makes API calls to pageservers until the observed state
786 : /// matches the intended state.
787 : ///
788 : /// First we apply special case handling (e.g. for live migrations), and then a
789 : /// general case reconciliation where we walk through the intent by pageserver
790 : /// and call out to the pageserver to apply the desired state.
791 : ///
792 : /// An Ok(()) result indicates that we successfully attached the tenant, but _not_ that
793 : /// all locations for the tenant are in the expected state. When nodes that are to be detached
794 : /// or configured as secondary are unavailable, we may return Ok(()) but leave the shard in a
795 : /// state where it still requires later reconciliation.
796 0 : pub(crate) async fn reconcile(&mut self) -> Result<(), ReconcileError> {
797 0 : // Prepare: if we have uncertain `observed` state for our would-be attachement location, then refresh it
798 0 : self.maybe_refresh_observed().await?;
799 :
800 : // Special case: live migration
801 0 : self.maybe_live_migrate().await?;
802 :
803 : // If the attached pageserver is not attached, do so now.
804 0 : if let Some(node) = self.intent.attached.as_ref() {
805 : // If we are in an attached policy, then generation must have been set (null generations
806 : // are only present when a tenant is initially loaded with a secondary policy)
807 0 : debug_assert!(self.generation.is_some());
808 0 : let Some(generation) = self.generation else {
809 0 : return Err(ReconcileError::Other(anyhow::anyhow!(
810 0 : "Attempted to attach with NULL generation"
811 0 : )));
812 : };
813 :
814 0 : let mut wanted_conf = attached_location_conf(
815 0 : generation,
816 0 : &self.shard,
817 0 : &self.config,
818 0 : &self.placement_policy,
819 0 : );
820 0 : match self.observed.locations.get(&node.get_id()) {
821 0 : Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {
822 0 : // Nothing to do
823 0 : tracing::info!(node_id=%node.get_id(), "Observed configuration already correct.")
824 : }
825 0 : observed => {
826 : // In all cases other than a matching observed configuration, we will
827 : // reconcile this location. This includes locations with different configurations, as well
828 : // as locations with unknown (None) observed state.
829 :
830 : // Incrementing generation is the safe general case, but is inefficient for changes that only
831 : // modify some details (e.g. the tenant's config).
832 0 : let increment_generation = match observed {
833 0 : None => true,
834 0 : Some(ObservedStateLocation { conf: None }) => true,
835 : Some(ObservedStateLocation {
836 0 : conf: Some(observed),
837 0 : }) => {
838 0 : let generations_match = observed.generation == wanted_conf.generation;
839 0 :
840 0 : // We may skip incrementing the generation if the location is already in the expected mode and
841 0 : // generation. In principle it would also be safe to skip from certain other modes (e.g. AttachedStale),
842 0 : // but such states are handled inside `live_migrate`, and if we see that state here we're cleaning up
843 0 : // after a restart/crash, so fall back to the universally safe path of incrementing generation.
844 0 : !generations_match || (observed.mode != wanted_conf.mode)
845 : }
846 : };
847 :
848 0 : if increment_generation {
849 0 : pausable_failpoint!("reconciler-pre-increment-generation");
850 :
851 0 : let generation = self
852 0 : .persistence
853 0 : .increment_generation(self.tenant_shard_id, node.get_id())
854 0 : .await?;
855 0 : self.generation = Some(generation);
856 0 : wanted_conf.generation = generation.into();
857 0 : }
858 0 : tracing::info!(node_id=%node.get_id(), "Observed configuration requires update.");
859 :
860 : // Because `node` comes from a ref to &self, clone it before calling into a &mut self
861 : // function: this could be avoided by refactoring the state mutated by location_config into
862 : // a separate type to Self.
863 0 : let node = node.clone();
864 0 :
865 0 : // Use lazy=true, because we may run many of Self concurrently, and do not want to
866 0 : // overload the pageserver with logical size calculations.
867 0 : self.location_config(&node, wanted_conf, None, true).await?;
868 0 : self.compute_notify().await?;
869 : }
870 : }
871 0 : }
872 :
873 : // Configure secondary locations: if these were previously attached this
874 : // implicitly downgrades them from attached to secondary.
875 0 : let mut changes = Vec::new();
876 0 : for node in &self.intent.secondary {
877 0 : let wanted_conf = secondary_location_conf(&self.shard, &self.config);
878 0 : match self.observed.locations.get(&node.get_id()) {
879 0 : Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {
880 0 : // Nothing to do
881 0 : tracing::info!(node_id=%node.get_id(), "Observed configuration already correct.")
882 : }
883 : _ => {
884 : // Only try and configure secondary locations on nodes that are available. This
885 : // allows the reconciler to "succeed" while some secondaries are offline (e.g. after
886 : // a node failure, where the failed node will have a secondary intent)
887 0 : if node.is_available() {
888 0 : tracing::info!(node_id=%node.get_id(), "Observed configuration requires update.");
889 0 : changes.push((node.clone(), wanted_conf))
890 : } else {
891 0 : tracing::info!(node_id=%node.get_id(), "Skipping configuration as secondary, node is unavailable");
892 0 : self.observed
893 0 : .locations
894 0 : .insert(node.get_id(), ObservedStateLocation { conf: None });
895 : }
896 : }
897 : }
898 : }
899 :
900 : // Detach any extraneous pageservers that are no longer referenced
901 : // by our intent.
902 0 : for node in &self.detach {
903 0 : changes.push((
904 0 : node.clone(),
905 0 : LocationConfig {
906 0 : mode: LocationConfigMode::Detached,
907 0 : generation: None,
908 0 : secondary_conf: None,
909 0 : shard_number: self.shard.number.0,
910 0 : shard_count: self.shard.count.literal(),
911 0 : shard_stripe_size: self.shard.stripe_size.0,
912 0 : tenant_conf: self.config.clone(),
913 0 : },
914 0 : ));
915 0 : }
916 :
917 0 : for (node, conf) in changes {
918 0 : if self.cancel.is_cancelled() {
919 0 : return Err(ReconcileError::Cancel);
920 0 : }
921 0 : // We only try to configure secondary locations if the node is available. This does
922 0 : // not stop us succeeding with the reconcile, because our core goal is to make the
923 0 : // shard _available_ (the attached location), and configuring secondary locations
924 0 : // can be done lazily when the node becomes available (via background reconciliation).
925 0 : if node.is_available() {
926 0 : self.location_config(&node, conf, None, false).await?;
927 : } else {
928 : // If the node is unavailable, we skip and consider the reconciliation successful: this
929 : // is a common case where a pageserver is marked unavailable: we demote a location on
930 : // that unavailable pageserver to secondary.
931 0 : tracing::info!("Skipping configuring secondary location {node}, it is unavailable");
932 0 : self.observed
933 0 : .locations
934 0 : .insert(node.get_id(), ObservedStateLocation { conf: None });
935 : }
936 : }
937 :
938 : // The condition below identifies a detach. We must have no attached intent and
939 : // must have been attached to something previously. Pass this information to
940 : // the [`ComputeHook`] such that it can update its tenant-wide state.
941 0 : if self.intent.attached.is_none() && !self.detach.is_empty() {
942 0 : // TODO: Consider notifying control plane about detaches. This would avoid situations
943 0 : // where the compute tries to start-up with a stale set of pageservers.
944 0 : self.compute_hook
945 0 : .handle_detach(self.tenant_shard_id, self.shard.stripe_size);
946 0 : }
947 :
948 0 : pausable_failpoint!("reconciler-epilogue");
949 :
950 0 : Ok(())
951 0 : }
952 :
953 0 : pub(crate) async fn compute_notify(&mut self) -> Result<(), NotifyError> {
954 : // Whenever a particular Reconciler emits a notification, it is always notifying for the intended
955 : // destination.
956 0 : if let Some(node) = &self.intent.attached {
957 0 : let result = self
958 0 : .compute_hook
959 0 : .notify(
960 0 : compute_hook::ShardUpdate {
961 0 : tenant_shard_id: self.tenant_shard_id,
962 0 : node_id: node.get_id(),
963 0 : stripe_size: self.shard.stripe_size,
964 0 : preferred_az: self.preferred_az.as_ref().map(Cow::Borrowed),
965 0 : },
966 0 : &self.cancel,
967 0 : )
968 0 : .await;
969 0 : if let Err(e) = &result {
970 : // Set this flag so that in our ReconcileResult we will set the flag on the shard that it
971 : // needs to retry at some point.
972 0 : self.compute_notify_failure = true;
973 :
974 : // It is up to the caller whether they want to drop out on this error, but they don't have to:
975 : // in general we should avoid letting unavailability of the cloud control plane stop us from
976 : // making progress.
977 0 : match e {
978 0 : // 404s from cplane during tenant creation are expected.
979 0 : // Cplane only persists the shards to the database after
980 0 : // creating the tenant and the timeline. If we notify before
981 0 : // that, we'll get a 404.
982 0 : //
983 0 : // This is fine because tenant creations happen via /location_config
984 0 : // and that returns the list of locations in the response. Hence, we
985 0 : // silence the error and return Ok(()) here. Reconciliation will still
986 0 : // be retried because we set [`Reconciler::compute_notify_failure`] above.
987 0 : NotifyError::Unexpected(hyper::StatusCode::NOT_FOUND)
988 0 : if self.reconciler_config.tenant_creation_hint() =>
989 0 : {
990 0 : return Ok(());
991 : }
992 0 : NotifyError::ShuttingDown => {}
993 : _ => {
994 0 : tracing::warn!(
995 0 : "Failed to notify compute of attached pageserver {node}: {e}"
996 : );
997 : }
998 : }
999 0 : }
1000 0 : result
1001 : } else {
1002 0 : Ok(())
1003 : }
1004 0 : }
1005 :
1006 : /// Compare the observed state snapshot from when the reconcile was created
1007 : /// with the final observed state in order to generate observed state deltas.
1008 0 : pub(crate) fn observed_deltas(&self) -> Vec<ObservedStateDelta> {
1009 0 : let mut deltas = Vec::default();
1010 :
1011 0 : for (node_id, location) in &self.observed.locations {
1012 0 : let previous_location = self.original_observed.locations.get(node_id);
1013 0 : let do_upsert = match previous_location {
1014 : // Location config changed for node
1015 0 : Some(prev) if location.conf != prev.conf => true,
1016 : // New location config for node
1017 0 : None => true,
1018 : // Location config has not changed for node
1019 0 : _ => false,
1020 : };
1021 :
1022 0 : if do_upsert {
1023 0 : deltas.push(ObservedStateDelta::Upsert(Box::new((
1024 0 : *node_id,
1025 0 : location.clone(),
1026 0 : ))));
1027 0 : }
1028 : }
1029 :
1030 0 : for node_id in self.original_observed.locations.keys() {
1031 0 : if !self.observed.locations.contains_key(node_id) {
1032 0 : deltas.push(ObservedStateDelta::Delete(*node_id));
1033 0 : }
1034 : }
1035 :
1036 0 : deltas
1037 0 : }
1038 :
1039 : /// Keep trying to notify the compute indefinitely, only dropping out if:
1040 : /// - the node `origin` becomes unavailable -> Ok(())
1041 : /// - the node `origin` no longer has our tenant shard attached -> Ok(())
1042 : /// - our cancellation token fires -> Err(ReconcileError::Cancelled)
1043 : ///
1044 : /// This is used during live migration, where we do not wish to detach
1045 : /// an origin location until the compute definitely knows about the new
1046 : /// location.
1047 : ///
1048 : /// In cases where the origin node becomes unavailable, we return success, indicating
1049 : /// to the caller that they should continue irrespective of whether the compute was notified,
1050 : /// because the origin node is unusable anyway. Notification will be retried later via the
1051 : /// [`Self::compute_notify_failure`] flag.
1052 0 : async fn compute_notify_blocking(&mut self, origin: &Node) -> Result<(), ReconcileError> {
1053 0 : let mut notify_attempts = 0;
1054 0 : while let Err(e) = self.compute_notify().await {
1055 0 : match e {
1056 0 : NotifyError::Fatal(_) => return Err(ReconcileError::Notify(e)),
1057 0 : NotifyError::ShuttingDown => return Err(ReconcileError::Cancel),
1058 : _ => {
1059 0 : tracing::warn!(
1060 0 : "Live migration blocked by compute notification error, retrying: {e}"
1061 : );
1062 : }
1063 : }
1064 :
1065 : // Did the origin pageserver become unavailable?
1066 0 : if !origin.is_available() {
1067 0 : tracing::info!("Giving up on compute notification because {origin} is unavailable");
1068 0 : break;
1069 0 : }
1070 0 :
1071 0 : // Does the origin pageserver still host the shard we are interested in? We should only
1072 0 : // continue waiting for compute notification to be acked if the old location is still usable.
1073 0 : let tenant_shard_id = self.tenant_shard_id;
1074 0 : match origin
1075 0 : .with_client_retries(
1076 0 : |client| async move { client.get_location_config(tenant_shard_id).await },
1077 0 : &self.service_config.jwt_token,
1078 0 : 1,
1079 0 : 3,
1080 0 : Duration::from_secs(5),
1081 0 : &self.cancel,
1082 0 : )
1083 0 : .await
1084 : {
1085 0 : Some(Ok(Some(location_conf))) => {
1086 0 : if matches!(
1087 0 : location_conf.mode,
1088 : LocationConfigMode::AttachedMulti
1089 : | LocationConfigMode::AttachedSingle
1090 : | LocationConfigMode::AttachedStale
1091 : ) {
1092 0 : tracing::debug!(
1093 0 : "Still attached to {origin}, will wait & retry compute notification"
1094 : );
1095 : } else {
1096 0 : tracing::info!(
1097 0 : "Giving up on compute notification because {origin} is in state {:?}",
1098 : location_conf.mode
1099 : );
1100 0 : return Ok(());
1101 : }
1102 : // Fall through
1103 : }
1104 : Some(Ok(None)) => {
1105 0 : tracing::info!(
1106 0 : "No longer attached to {origin}, giving up on compute notification"
1107 : );
1108 0 : return Ok(());
1109 : }
1110 0 : Some(Err(e)) => {
1111 0 : match e {
1112 : mgmt_api::Error::Cancelled => {
1113 0 : tracing::info!(
1114 0 : "Giving up on compute notification because {origin} is unavailable"
1115 : );
1116 0 : return Ok(());
1117 : }
1118 : mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _) => {
1119 0 : tracing::info!(
1120 0 : "No longer attached to {origin}, giving up on compute notification"
1121 : );
1122 0 : return Ok(());
1123 : }
1124 0 : e => {
1125 0 : // Other API errors are unexpected here.
1126 0 : tracing::warn!("Unexpected error checking location on {origin}: {e}");
1127 :
1128 : // Fall through, we will retry compute notification.
1129 : }
1130 : }
1131 : }
1132 0 : None => return Err(ReconcileError::Cancel),
1133 : };
1134 :
1135 0 : exponential_backoff(
1136 0 : notify_attempts,
1137 0 : // Generous waits: control plane operations which might be blocking us usually complete on the order
1138 0 : // of hundreds to thousands of milliseconds, so no point busy polling.
1139 0 : 1.0,
1140 0 : 10.0,
1141 0 : &self.cancel,
1142 0 : )
1143 0 : .await;
1144 0 : notify_attempts += 1;
1145 : }
1146 :
1147 0 : Ok(())
1148 0 : }
1149 : }
1150 :
1151 : /// We tweak the externally-set TenantConfig while configuring
1152 : /// locations, using our awareness of whether secondary locations
1153 : /// are in use to automatically enable/disable heatmap uploads.
1154 0 : fn ha_aware_config(config: &TenantConfig, has_secondaries: bool) -> TenantConfig {
1155 0 : let mut config = config.clone();
1156 0 : if has_secondaries {
1157 0 : if config.heatmap_period.is_none() {
1158 0 : config.heatmap_period = Some(DEFAULT_HEATMAP_PERIOD.to_string());
1159 0 : }
1160 0 : } else {
1161 0 : config.heatmap_period = None;
1162 0 : }
1163 0 : config
1164 0 : }
1165 :
1166 0 : pub(crate) fn attached_location_conf(
1167 0 : generation: Generation,
1168 0 : shard: &ShardIdentity,
1169 0 : config: &TenantConfig,
1170 0 : policy: &PlacementPolicy,
1171 0 : ) -> LocationConfig {
1172 0 : let has_secondaries = match policy {
1173 : PlacementPolicy::Attached(0) | PlacementPolicy::Detached | PlacementPolicy::Secondary => {
1174 0 : false
1175 : }
1176 0 : PlacementPolicy::Attached(_) => true,
1177 : };
1178 :
1179 0 : LocationConfig {
1180 0 : mode: LocationConfigMode::AttachedSingle,
1181 0 : generation: generation.into(),
1182 0 : secondary_conf: None,
1183 0 : shard_number: shard.number.0,
1184 0 : shard_count: shard.count.literal(),
1185 0 : shard_stripe_size: shard.stripe_size.0,
1186 0 : tenant_conf: ha_aware_config(config, has_secondaries),
1187 0 : }
1188 0 : }
1189 :
1190 0 : pub(crate) fn secondary_location_conf(
1191 0 : shard: &ShardIdentity,
1192 0 : config: &TenantConfig,
1193 0 : ) -> LocationConfig {
1194 0 : LocationConfig {
1195 0 : mode: LocationConfigMode::Secondary,
1196 0 : generation: None,
1197 0 : secondary_conf: Some(LocationConfigSecondary { warm: true }),
1198 0 : shard_number: shard.number.0,
1199 0 : shard_count: shard.count.literal(),
1200 0 : shard_stripe_size: shard.stripe_size.0,
1201 0 : tenant_conf: ha_aware_config(config, true),
1202 0 : }
1203 0 : }
|