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