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