Line data Source code
1 : pub mod chaos_injector;
2 : mod context_iterator;
3 :
4 : use hyper::Uri;
5 : use std::{
6 : borrow::Cow,
7 : cmp::Ordering,
8 : collections::{BTreeMap, HashMap, HashSet},
9 : error::Error,
10 : ops::Deref,
11 : path::PathBuf,
12 : str::FromStr,
13 : sync::Arc,
14 : time::{Duration, Instant},
15 : };
16 :
17 : use crate::{
18 : background_node_operations::{
19 : Drain, Fill, Operation, OperationError, OperationHandler, MAX_RECONCILES_PER_OPERATION,
20 : },
21 : compute_hook::{self, NotifyError},
22 : drain_utils::{self, TenantShardDrain, TenantShardIterator},
23 : id_lock_map::{trace_exclusive_lock, trace_shared_lock, IdLockMap, TracingExclusiveGuard},
24 : leadership::Leadership,
25 : metrics,
26 : peer_client::GlobalObservedState,
27 : persistence::{
28 : AbortShardSplitStatus, ControllerPersistence, DatabaseResult, MetadataHealthPersistence,
29 : ShardGenerationState, TenantFilter,
30 : },
31 : reconciler::{ReconcileError, ReconcileUnits, ReconcilerConfig, ReconcilerConfigBuilder},
32 : scheduler::{MaySchedule, ScheduleContext, ScheduleError, ScheduleMode},
33 : tenant_shard::{
34 : MigrateAttachment, ObservedStateDelta, ReconcileNeeded, ReconcilerStatus,
35 : ScheduleOptimization, ScheduleOptimizationAction,
36 : },
37 : };
38 : use anyhow::Context;
39 : use control_plane::storage_controller::{
40 : AttachHookRequest, AttachHookResponse, InspectRequest, InspectResponse,
41 : };
42 : use diesel::result::DatabaseErrorKind;
43 : use futures::{stream::FuturesUnordered, StreamExt};
44 : use itertools::Itertools;
45 : use pageserver_api::{
46 : controller_api::{
47 : AvailabilityZone, MetadataHealthRecord, MetadataHealthUpdateRequest, NodeAvailability,
48 : NodeRegisterRequest, NodeSchedulingPolicy, NodeShard, NodeShardResponse, PlacementPolicy,
49 : SafekeeperDescribeResponse, ShardSchedulingPolicy, ShardsPreferredAzsRequest,
50 : ShardsPreferredAzsResponse, TenantCreateRequest, TenantCreateResponse,
51 : TenantCreateResponseShard, TenantDescribeResponse, TenantDescribeResponseShard,
52 : TenantLocateResponse, TenantPolicyRequest, TenantShardMigrateRequest,
53 : TenantShardMigrateResponse,
54 : },
55 : models::{
56 : SecondaryProgress, TenantConfigPatchRequest, TenantConfigRequest,
57 : TimelineArchivalConfigRequest, TopTenantShardsRequest,
58 : },
59 : };
60 : use reqwest::StatusCode;
61 : use tracing::{instrument, Instrument};
62 :
63 : use crate::pageserver_client::PageserverClient;
64 : use pageserver_api::{
65 : models::{
66 : self, LocationConfig, LocationConfigListResponse, LocationConfigMode,
67 : PageserverUtilization, ShardParameters, TenantConfig, TenantLocationConfigRequest,
68 : TenantLocationConfigResponse, TenantShardLocation, TenantShardSplitRequest,
69 : TenantShardSplitResponse, TenantTimeTravelRequest, TimelineCreateRequest, TimelineInfo,
70 : },
71 : shard::{ShardCount, ShardIdentity, ShardNumber, ShardStripeSize, TenantShardId},
72 : upcall_api::{
73 : ReAttachRequest, ReAttachResponse, ReAttachResponseTenant, ValidateRequest,
74 : ValidateResponse, ValidateResponseTenant,
75 : },
76 : };
77 : use pageserver_client::{mgmt_api, BlockUnblock};
78 : use tokio::sync::mpsc::error::TrySendError;
79 : use tokio_util::sync::CancellationToken;
80 : use utils::{
81 : completion::Barrier,
82 : failpoint_support,
83 : generation::Generation,
84 : http::error::ApiError,
85 : id::{NodeId, TenantId, TimelineId},
86 : pausable_failpoint,
87 : sync::gate::Gate,
88 : };
89 :
90 : use crate::{
91 : compute_hook::ComputeHook,
92 : heartbeater::{Heartbeater, PageserverState},
93 : node::{AvailabilityTransition, Node},
94 : persistence::{split_state::SplitState, DatabaseError, Persistence, TenantShardPersistence},
95 : reconciler::attached_location_conf,
96 : scheduler::Scheduler,
97 : tenant_shard::{
98 : IntentState, ObservedState, ObservedStateLocation, ReconcileResult, ReconcileWaitError,
99 : ReconcilerWaiter, TenantShard,
100 : },
101 : };
102 :
103 : use context_iterator::TenantShardContextIterator;
104 :
105 : const WAITER_FILL_DRAIN_POLL_TIMEOUT: Duration = Duration::from_millis(500);
106 :
107 : // For operations that should be quick, like attaching a new tenant
108 : const SHORT_RECONCILE_TIMEOUT: Duration = Duration::from_secs(5);
109 :
110 : // For operations that might be slow, like migrating a tenant with
111 : // some data in it.
112 : pub const RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
113 :
114 : // If we receive a call using Secondary mode initially, it will omit generation. We will initialize
115 : // tenant shards into this generation, and as long as it remains in this generation, we will accept
116 : // input generation from future requests as authoritative.
117 : const INITIAL_GENERATION: Generation = Generation::new(0);
118 :
119 : /// How long [`Service::startup_reconcile`] is allowed to take before it should give
120 : /// up on unresponsive pageservers and proceed.
121 : pub(crate) const STARTUP_RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
122 :
123 : /// How long a node may be unresponsive to heartbeats before we declare it offline.
124 : /// This must be long enough to cover node restarts as well as normal operations: in future
125 : pub const MAX_OFFLINE_INTERVAL_DEFAULT: Duration = Duration::from_secs(30);
126 :
127 : /// How long a node may be unresponsive to heartbeats during start up before we declare it
128 : /// offline.
129 : ///
130 : /// This is much more lenient than [`MAX_OFFLINE_INTERVAL_DEFAULT`] since the pageserver's
131 : /// handling of the re-attach response may take a long time and blocks heartbeats from
132 : /// being handled on the pageserver side.
133 : pub const MAX_WARMING_UP_INTERVAL_DEFAULT: Duration = Duration::from_secs(300);
134 :
135 : /// How often to send heartbeats to registered nodes?
136 : pub const HEARTBEAT_INTERVAL_DEFAULT: Duration = Duration::from_secs(5);
137 :
138 : /// How long is too long for a reconciliation?
139 : pub const LONG_RECONCILE_THRESHOLD_DEFAULT: Duration = Duration::from_secs(120);
140 :
141 : #[derive(Clone, strum_macros::Display)]
142 : enum TenantOperations {
143 : Create,
144 : LocationConfig,
145 : ConfigSet,
146 : ConfigPatch,
147 : TimeTravelRemoteStorage,
148 : Delete,
149 : UpdatePolicy,
150 : ShardSplit,
151 : SecondaryDownload,
152 : TimelineCreate,
153 : TimelineDelete,
154 : AttachHook,
155 : TimelineArchivalConfig,
156 : TimelineDetachAncestor,
157 : TimelineGcBlockUnblock,
158 : DropDetached,
159 : }
160 :
161 : #[derive(Clone, strum_macros::Display)]
162 : enum NodeOperations {
163 : Register,
164 : Configure,
165 : Delete,
166 : }
167 :
168 : /// The leadership status for the storage controller process.
169 : /// Allowed transitions are:
170 : /// 1. Leader -> SteppedDown
171 : /// 2. Candidate -> Leader
172 : #[derive(
173 : Eq,
174 : PartialEq,
175 : Copy,
176 : Clone,
177 : strum_macros::Display,
178 0 : strum_macros::EnumIter,
179 : measured::FixedCardinalityLabel,
180 : )]
181 : #[strum(serialize_all = "snake_case")]
182 : pub(crate) enum LeadershipStatus {
183 : /// This is the steady state where the storage controller can produce
184 : /// side effects in the cluster.
185 : Leader,
186 : /// We've been notified to step down by another candidate. No reconciliations
187 : /// take place in this state.
188 : SteppedDown,
189 : /// Initial state for a new storage controller instance. Will attempt to assume leadership.
190 : #[allow(unused)]
191 : Candidate,
192 : }
193 :
194 : pub const RECONCILER_CONCURRENCY_DEFAULT: usize = 128;
195 :
196 : // Depth of the channel used to enqueue shards for reconciliation when they can't do it immediately.
197 : // This channel is finite-size to avoid using excessive memory if we get into a state where reconciles are finishing more slowly
198 : // than they're being pushed onto the queue.
199 : const MAX_DELAYED_RECONCILES: usize = 10000;
200 :
201 : // Top level state available to all HTTP handlers
202 : struct ServiceState {
203 : leadership_status: LeadershipStatus,
204 :
205 : tenants: BTreeMap<TenantShardId, TenantShard>,
206 :
207 : nodes: Arc<HashMap<NodeId, Node>>,
208 :
209 : scheduler: Scheduler,
210 :
211 : /// Ongoing background operation on the cluster if any is running.
212 : /// Note that only one such operation may run at any given time,
213 : /// hence the type choice.
214 : ongoing_operation: Option<OperationHandler>,
215 :
216 : /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
217 : delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
218 : }
219 :
220 : /// Transform an error from a pageserver into an error to return to callers of a storage
221 : /// controller API.
222 0 : fn passthrough_api_error(node: &Node, e: mgmt_api::Error) -> ApiError {
223 0 : match e {
224 0 : mgmt_api::Error::SendRequest(e) => {
225 0 : // Presume errors sending requests are connectivity/availability issues
226 0 : ApiError::ResourceUnavailable(format!("{node} error sending request: {e}").into())
227 : }
228 0 : mgmt_api::Error::ReceiveErrorBody(str) => {
229 0 : // Presume errors receiving body are connectivity/availability issues
230 0 : ApiError::ResourceUnavailable(
231 0 : format!("{node} error receiving error body: {str}").into(),
232 0 : )
233 : }
234 0 : mgmt_api::Error::ReceiveBody(err) if err.is_decode() => {
235 0 : // Return 500 for decoding errors.
236 0 : ApiError::InternalServerError(anyhow::Error::from(err).context("error decoding body"))
237 : }
238 0 : mgmt_api::Error::ReceiveBody(err) => {
239 0 : // Presume errors receiving body are connectivity/availability issues except for decoding errors
240 0 : let src_str = err.source().map(|e| e.to_string()).unwrap_or_default();
241 0 : ApiError::ResourceUnavailable(
242 0 : format!("{node} error receiving error body: {err} {}", src_str).into(),
243 0 : )
244 : }
245 0 : mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, msg) => {
246 0 : ApiError::NotFound(anyhow::anyhow!(format!("{node}: {msg}")).into())
247 : }
248 0 : mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg) => {
249 0 : ApiError::ResourceUnavailable(format!("{node}: {msg}").into())
250 : }
251 0 : mgmt_api::Error::ApiError(status @ StatusCode::UNAUTHORIZED, msg)
252 0 : | mgmt_api::Error::ApiError(status @ StatusCode::FORBIDDEN, msg) => {
253 : // Auth errors talking to a pageserver are not auth errors for the caller: they are
254 : // internal server errors, showing that something is wrong with the pageserver or
255 : // storage controller's auth configuration.
256 0 : ApiError::InternalServerError(anyhow::anyhow!("{node} {status}: {msg}"))
257 : }
258 0 : mgmt_api::Error::ApiError(status @ StatusCode::TOO_MANY_REQUESTS, msg) => {
259 0 : // Pass through 429 errors: if pageserver is asking us to wait + retry, we in
260 0 : // turn ask our clients to wait + retry
261 0 : ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
262 : }
263 0 : mgmt_api::Error::ApiError(status, msg) => {
264 0 : // Presume general case of pageserver API errors is that we tried to do something
265 0 : // that can't be done right now.
266 0 : ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
267 : }
268 0 : mgmt_api::Error::Cancelled => ApiError::ShuttingDown,
269 : }
270 0 : }
271 :
272 : impl ServiceState {
273 0 : fn new(
274 0 : nodes: HashMap<NodeId, Node>,
275 0 : tenants: BTreeMap<TenantShardId, TenantShard>,
276 0 : scheduler: Scheduler,
277 0 : delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
278 0 : initial_leadership_status: LeadershipStatus,
279 0 : ) -> Self {
280 0 : metrics::update_leadership_status(initial_leadership_status);
281 0 :
282 0 : Self {
283 0 : leadership_status: initial_leadership_status,
284 0 : tenants,
285 0 : nodes: Arc::new(nodes),
286 0 : scheduler,
287 0 : ongoing_operation: None,
288 0 : delayed_reconcile_rx,
289 0 : }
290 0 : }
291 :
292 0 : fn parts_mut(
293 0 : &mut self,
294 0 : ) -> (
295 0 : &mut Arc<HashMap<NodeId, Node>>,
296 0 : &mut BTreeMap<TenantShardId, TenantShard>,
297 0 : &mut Scheduler,
298 0 : ) {
299 0 : (&mut self.nodes, &mut self.tenants, &mut self.scheduler)
300 0 : }
301 :
302 0 : fn get_leadership_status(&self) -> LeadershipStatus {
303 0 : self.leadership_status
304 0 : }
305 :
306 0 : fn step_down(&mut self) {
307 0 : self.leadership_status = LeadershipStatus::SteppedDown;
308 0 : metrics::update_leadership_status(self.leadership_status);
309 0 : }
310 :
311 0 : fn become_leader(&mut self) {
312 0 : self.leadership_status = LeadershipStatus::Leader;
313 0 : metrics::update_leadership_status(self.leadership_status);
314 0 : }
315 : }
316 :
317 : #[derive(Clone)]
318 : pub struct Config {
319 : // All pageservers managed by one instance of this service must have
320 : // the same public key. This JWT token will be used to authenticate
321 : // this service to the pageservers it manages.
322 : pub jwt_token: Option<String>,
323 :
324 : // This JWT token will be used to authenticate this service to the control plane.
325 : pub control_plane_jwt_token: Option<String>,
326 :
327 : // This JWT token will be used to authenticate with other storage controller instances
328 : pub peer_jwt_token: Option<String>,
329 :
330 : /// Where the compute hook should send notifications of pageserver attachment locations
331 : /// (this URL points to the control plane in prod). If this is None, the compute hook will
332 : /// assume it is running in a test environment and try to update neon_local.
333 : pub compute_hook_url: Option<String>,
334 :
335 : /// Grace period within which a pageserver does not respond to heartbeats, but is still
336 : /// considered active. Once the grace period elapses, the next heartbeat failure will
337 : /// mark the pagseserver offline.
338 : pub max_offline_interval: Duration,
339 :
340 : /// Extended grace period within which pageserver may not respond to heartbeats.
341 : /// This extended grace period kicks in after the node has been drained for restart
342 : /// and/or upon handling the re-attach request from a node.
343 : pub max_warming_up_interval: Duration,
344 :
345 : /// How many Reconcilers may be spawned concurrently
346 : pub reconciler_concurrency: usize,
347 :
348 : /// How large must a shard grow in bytes before we split it?
349 : /// None disables auto-splitting.
350 : pub split_threshold: Option<u64>,
351 :
352 : // TODO: make this cfg(feature = "testing")
353 : pub neon_local_repo_dir: Option<PathBuf>,
354 :
355 : // Maximum acceptable download lag for the secondary location
356 : // while draining a node. If the secondary location is lagging
357 : // by more than the configured amount, then the secondary is not
358 : // upgraded to primary.
359 : pub max_secondary_lag_bytes: Option<u64>,
360 :
361 : pub heartbeat_interval: Duration,
362 :
363 : pub address_for_peers: Option<Uri>,
364 :
365 : pub start_as_candidate: bool,
366 :
367 : pub http_service_port: i32,
368 :
369 : pub long_reconcile_threshold: Duration,
370 : }
371 :
372 : impl From<DatabaseError> for ApiError {
373 0 : fn from(err: DatabaseError) -> ApiError {
374 0 : match err {
375 0 : DatabaseError::Query(e) => ApiError::InternalServerError(e.into()),
376 : // FIXME: ApiError doesn't have an Unavailable variant, but ShuttingDown maps to 503.
377 : DatabaseError::Connection(_) | DatabaseError::ConnectionPool(_) => {
378 0 : ApiError::ShuttingDown
379 : }
380 0 : DatabaseError::Logical(reason) | DatabaseError::Migration(reason) => {
381 0 : ApiError::InternalServerError(anyhow::anyhow!(reason))
382 : }
383 : }
384 0 : }
385 : }
386 :
387 : enum InitialShardScheduleOutcome {
388 : Scheduled(TenantCreateResponseShard),
389 : NotScheduled,
390 : ShardScheduleError(ScheduleError),
391 : }
392 :
393 : pub struct Service {
394 : inner: Arc<std::sync::RwLock<ServiceState>>,
395 : config: Config,
396 : persistence: Arc<Persistence>,
397 : compute_hook: Arc<ComputeHook>,
398 : result_tx: tokio::sync::mpsc::UnboundedSender<ReconcileResultRequest>,
399 :
400 : heartbeater: Heartbeater,
401 :
402 : // Channel for background cleanup from failed operations that require cleanup, such as shard split
403 : abort_tx: tokio::sync::mpsc::UnboundedSender<TenantShardSplitAbort>,
404 :
405 : // Locking on a tenant granularity (covers all shards in the tenant):
406 : // - Take exclusively for rare operations that mutate the tenant's persistent state (e.g. create/delete/split)
407 : // - Take in shared mode for operations that need the set of shards to stay the same to complete reliably (e.g. timeline CRUD)
408 : tenant_op_locks: IdLockMap<TenantId, TenantOperations>,
409 :
410 : // Locking for node-mutating operations: take exclusively for operations that modify the node's persistent state, or
411 : // that transition it to/from Active.
412 : node_op_locks: IdLockMap<NodeId, NodeOperations>,
413 :
414 : // Limit how many Reconcilers we will spawn concurrently
415 : reconciler_concurrency: Arc<tokio::sync::Semaphore>,
416 :
417 : /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
418 : /// Send into this queue to promptly attempt to reconcile this shard next time units are available.
419 : ///
420 : /// Note that this state logically lives inside ServiceState, but carrying Sender here makes the code simpler
421 : /// by avoiding needing a &mut ref to something inside the ServiceState. This could be optimized to
422 : /// use a VecDeque instead of a channel to reduce synchronization overhead, at the cost of some code complexity.
423 : delayed_reconcile_tx: tokio::sync::mpsc::Sender<TenantShardId>,
424 :
425 : // Process shutdown will fire this token
426 : cancel: CancellationToken,
427 :
428 : // Child token of [`Service::cancel`] used by reconcilers
429 : reconcilers_cancel: CancellationToken,
430 :
431 : // Background tasks will hold this gate
432 : gate: Gate,
433 :
434 : // Reconcilers background tasks will hold this gate
435 : reconcilers_gate: Gate,
436 :
437 : /// This waits for initial reconciliation with pageservers to complete. Until this barrier
438 : /// passes, it isn't safe to do any actions that mutate tenants.
439 : pub(crate) startup_complete: Barrier,
440 : }
441 :
442 : impl From<ReconcileWaitError> for ApiError {
443 0 : fn from(value: ReconcileWaitError) -> Self {
444 0 : match value {
445 0 : ReconcileWaitError::Shutdown => ApiError::ShuttingDown,
446 0 : e @ ReconcileWaitError::Timeout(_) => ApiError::Timeout(format!("{e}").into()),
447 0 : e @ ReconcileWaitError::Failed(..) => ApiError::InternalServerError(anyhow::anyhow!(e)),
448 : }
449 0 : }
450 : }
451 :
452 : impl From<OperationError> for ApiError {
453 0 : fn from(value: OperationError) -> Self {
454 0 : match value {
455 0 : OperationError::NodeStateChanged(err) | OperationError::FinalizeError(err) => {
456 0 : ApiError::InternalServerError(anyhow::anyhow!(err))
457 : }
458 0 : OperationError::Cancelled => ApiError::Conflict("Operation was cancelled".into()),
459 : }
460 0 : }
461 : }
462 :
463 : #[allow(clippy::large_enum_variant)]
464 : enum TenantCreateOrUpdate {
465 : Create(TenantCreateRequest),
466 : Update(Vec<ShardUpdate>),
467 : }
468 :
469 : struct ShardSplitParams {
470 : old_shard_count: ShardCount,
471 : new_shard_count: ShardCount,
472 : new_stripe_size: Option<ShardStripeSize>,
473 : targets: Vec<ShardSplitTarget>,
474 : policy: PlacementPolicy,
475 : config: TenantConfig,
476 : shard_ident: ShardIdentity,
477 : preferred_az_id: Option<AvailabilityZone>,
478 : }
479 :
480 : // When preparing for a shard split, we may either choose to proceed with the split,
481 : // or find that the work is already done and return NoOp.
482 : enum ShardSplitAction {
483 : Split(Box<ShardSplitParams>),
484 : NoOp(TenantShardSplitResponse),
485 : }
486 :
487 : // A parent shard which will be split
488 : struct ShardSplitTarget {
489 : parent_id: TenantShardId,
490 : node: Node,
491 : child_ids: Vec<TenantShardId>,
492 : }
493 :
494 : /// When we tenant shard split operation fails, we may not be able to clean up immediately, because nodes
495 : /// might not be available. We therefore use a queue of abort operations processed in the background.
496 : struct TenantShardSplitAbort {
497 : tenant_id: TenantId,
498 : /// The target values from the request that failed
499 : new_shard_count: ShardCount,
500 : new_stripe_size: Option<ShardStripeSize>,
501 : /// Until this abort op is complete, no other operations may be done on the tenant
502 : _tenant_lock: TracingExclusiveGuard<TenantOperations>,
503 : }
504 :
505 : #[derive(thiserror::Error, Debug)]
506 : enum TenantShardSplitAbortError {
507 : #[error(transparent)]
508 : Database(#[from] DatabaseError),
509 : #[error(transparent)]
510 : Remote(#[from] mgmt_api::Error),
511 : #[error("Unavailable")]
512 : Unavailable,
513 : }
514 :
515 : struct ShardUpdate {
516 : tenant_shard_id: TenantShardId,
517 : placement_policy: PlacementPolicy,
518 : tenant_config: TenantConfig,
519 :
520 : /// If this is None, generation is not updated.
521 : generation: Option<Generation>,
522 :
523 : /// If this is None, scheduling policy is not updated.
524 : scheduling_policy: Option<ShardSchedulingPolicy>,
525 : }
526 :
527 : enum StopReconciliationsReason {
528 : ShuttingDown,
529 : SteppingDown,
530 : }
531 :
532 : impl std::fmt::Display for StopReconciliationsReason {
533 0 : fn fmt(&self, writer: &mut std::fmt::Formatter) -> std::fmt::Result {
534 0 : let s = match self {
535 0 : Self::ShuttingDown => "Shutting down",
536 0 : Self::SteppingDown => "Stepping down",
537 : };
538 0 : write!(writer, "{}", s)
539 0 : }
540 : }
541 :
542 : pub(crate) enum ReconcileResultRequest {
543 : ReconcileResult(ReconcileResult),
544 : Stop,
545 : }
546 :
547 : #[derive(Clone)]
548 : struct MutationLocation {
549 : node: Node,
550 : generation: Generation,
551 : }
552 :
553 : #[derive(Clone)]
554 : struct ShardMutationLocations {
555 : latest: MutationLocation,
556 : other: Vec<MutationLocation>,
557 : }
558 :
559 : #[derive(Default, Clone)]
560 : struct TenantMutationLocations(BTreeMap<TenantShardId, ShardMutationLocations>);
561 :
562 : impl Service {
563 0 : pub fn get_config(&self) -> &Config {
564 0 : &self.config
565 0 : }
566 :
567 : /// Called once on startup, this function attempts to contact all pageservers to build an up-to-date
568 : /// view of the world, and determine which pageservers are responsive.
569 : #[instrument(skip_all)]
570 : async fn startup_reconcile(
571 : self: &Arc<Service>,
572 : current_leader: Option<ControllerPersistence>,
573 : leader_step_down_state: Option<GlobalObservedState>,
574 : bg_compute_notify_result_tx: tokio::sync::mpsc::Sender<
575 : Result<(), (TenantShardId, NotifyError)>,
576 : >,
577 : ) {
578 : // Startup reconciliation does I/O to other services: whether they
579 : // are responsive or not, we should aim to finish within our deadline, because:
580 : // - If we don't, a k8s readiness hook watching /ready will kill us.
581 : // - While we're waiting for startup reconciliation, we are not fully
582 : // available for end user operations like creating/deleting tenants and timelines.
583 : //
584 : // We set multiple deadlines to break up the time available between the phases of work: this is
585 : // arbitrary, but avoids a situation where the first phase could burn our entire timeout period.
586 : let start_at = Instant::now();
587 : let node_scan_deadline = start_at
588 : .checked_add(STARTUP_RECONCILE_TIMEOUT / 2)
589 : .expect("Reconcile timeout is a modest constant");
590 :
591 : let observed = if let Some(state) = leader_step_down_state {
592 : tracing::info!(
593 : "Using observed state received from leader at {}",
594 : current_leader.as_ref().unwrap().address
595 : );
596 :
597 : state
598 : } else {
599 : self.build_global_observed_state(node_scan_deadline).await
600 : };
601 :
602 : // Accumulate a list of any tenant locations that ought to be detached
603 : let mut cleanup = Vec::new();
604 :
605 : // Send initial heartbeat requests to all nodes loaded from the database
606 : let all_nodes = {
607 : let locked = self.inner.read().unwrap();
608 : locked.nodes.clone()
609 : };
610 : let mut nodes_online = self.initial_heartbeat_round(all_nodes.keys()).await;
611 :
612 : // List of tenants for which we will attempt to notify compute of their location at startup
613 : let mut compute_notifications = Vec::new();
614 :
615 : // Populate intent and observed states for all tenants, based on reported state on pageservers
616 : tracing::info!("Populating tenant shards' states from initial pageserver scan...");
617 : let shard_count = {
618 : let mut locked = self.inner.write().unwrap();
619 : let (nodes, tenants, scheduler) = locked.parts_mut();
620 :
621 : // Mark nodes online if they responded to us: nodes are offline by default after a restart.
622 : let mut new_nodes = (**nodes).clone();
623 : for (node_id, node) in new_nodes.iter_mut() {
624 : if let Some(utilization) = nodes_online.remove(node_id) {
625 : node.set_availability(NodeAvailability::Active(utilization));
626 : scheduler.node_upsert(node);
627 : }
628 : }
629 : *nodes = Arc::new(new_nodes);
630 :
631 : for (tenant_shard_id, observed_state) in observed.0 {
632 : let Some(tenant_shard) = tenants.get_mut(&tenant_shard_id) else {
633 : for node_id in observed_state.locations.keys() {
634 : cleanup.push((tenant_shard_id, *node_id));
635 : }
636 :
637 : continue;
638 : };
639 :
640 : tenant_shard.observed = observed_state;
641 : }
642 :
643 : // Populate each tenant's intent state
644 : let mut schedule_context = ScheduleContext::default();
645 : for (tenant_shard_id, tenant_shard) in tenants.iter_mut() {
646 : if tenant_shard_id.shard_number == ShardNumber(0) {
647 : // Reset scheduling context each time we advance to the next Tenant
648 : schedule_context = ScheduleContext::default();
649 : }
650 :
651 : tenant_shard.intent_from_observed(scheduler);
652 : if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
653 : // Non-fatal error: we are unable to properly schedule the tenant, perhaps because
654 : // not enough pageservers are available. The tenant may well still be available
655 : // to clients.
656 : tracing::error!("Failed to schedule tenant {tenant_shard_id} at startup: {e}");
657 : } else {
658 : // If we're both intending and observed to be attached at a particular node, we will
659 : // emit a compute notification for this. In the case where our observed state does not
660 : // yet match our intent, we will eventually reconcile, and that will emit a compute notification.
661 : if let Some(attached_at) = tenant_shard.stably_attached() {
662 : compute_notifications.push(compute_hook::ShardUpdate {
663 : tenant_shard_id: *tenant_shard_id,
664 : node_id: attached_at,
665 : stripe_size: tenant_shard.shard.stripe_size,
666 : preferred_az: tenant_shard
667 : .preferred_az()
668 0 : .map(|az| Cow::Owned(az.clone())),
669 : });
670 : }
671 : }
672 : }
673 :
674 : tenants.len()
675 : };
676 :
677 : // Before making any obeservable changes to the cluster, persist self
678 : // as leader in database and memory.
679 : let leadership = Leadership::new(
680 : self.persistence.clone(),
681 : self.config.clone(),
682 : self.cancel.child_token(),
683 : );
684 :
685 : if let Err(e) = leadership.become_leader(current_leader).await {
686 : tracing::error!("Failed to persist self as leader: {e}. Aborting start-up ...");
687 : std::process::exit(1);
688 : }
689 :
690 : self.inner.write().unwrap().become_leader();
691 :
692 : // TODO: if any tenant's intent now differs from its loaded generation_pageserver, we should clear that
693 : // generation_pageserver in the database.
694 :
695 : // Emit compute hook notifications for all tenants which are already stably attached. Other tenants
696 : // will emit compute hook notifications when they reconcile.
697 : //
698 : // Ordering: our calls to notify_background synchronously establish a relative order for these notifications vs. any later
699 : // calls into the ComputeHook for the same tenant: we can leave these to run to completion in the background and any later
700 : // calls will be correctly ordered wrt these.
701 : //
702 : // Concurrency: we call notify_background for all tenants, which will create O(N) tokio tasks, but almost all of them
703 : // will just wait on the ComputeHook::API_CONCURRENCY semaphore immediately, so very cheap until they get that semaphore
704 : // unit and start doing I/O.
705 : tracing::info!(
706 : "Sending {} compute notifications",
707 : compute_notifications.len()
708 : );
709 : self.compute_hook.notify_background(
710 : compute_notifications,
711 : bg_compute_notify_result_tx.clone(),
712 : &self.cancel,
713 : );
714 :
715 : // Finally, now that the service is up and running, launch reconcile operations for any tenants
716 : // which require it: under normal circumstances this should only include tenants that were in some
717 : // transient state before we restarted, or any tenants whose compute hooks failed above.
718 : tracing::info!("Checking for shards in need of reconciliation...");
719 : let reconcile_tasks = self.reconcile_all();
720 : // We will not wait for these reconciliation tasks to run here: we're now done with startup and
721 : // normal operations may proceed.
722 :
723 : // Clean up any tenants that were found on pageservers but are not known to us. Do this in the
724 : // background because it does not need to complete in order to proceed with other work.
725 : if !cleanup.is_empty() {
726 : tracing::info!("Cleaning up {} locations in the background", cleanup.len());
727 : tokio::task::spawn({
728 : let cleanup_self = self.clone();
729 0 : async move { cleanup_self.cleanup_locations(cleanup).await }
730 : });
731 : }
732 :
733 : tracing::info!("Startup complete, spawned {reconcile_tasks} reconciliation tasks ({shard_count} shards total)");
734 : }
735 :
736 0 : async fn initial_heartbeat_round<'a>(
737 0 : &self,
738 0 : node_ids: impl Iterator<Item = &'a NodeId>,
739 0 : ) -> HashMap<NodeId, PageserverUtilization> {
740 0 : assert!(!self.startup_complete.is_ready());
741 :
742 0 : let all_nodes = {
743 0 : let locked = self.inner.read().unwrap();
744 0 : locked.nodes.clone()
745 0 : };
746 0 :
747 0 : let mut nodes_to_heartbeat = HashMap::new();
748 0 : for node_id in node_ids {
749 0 : match all_nodes.get(node_id) {
750 0 : Some(node) => {
751 0 : nodes_to_heartbeat.insert(*node_id, node.clone());
752 0 : }
753 : None => {
754 0 : tracing::warn!("Node {node_id} was removed during start-up");
755 : }
756 : }
757 : }
758 :
759 0 : tracing::info!("Sending initial heartbeats...");
760 0 : let res = self
761 0 : .heartbeater
762 0 : .heartbeat(Arc::new(nodes_to_heartbeat))
763 0 : .await;
764 :
765 0 : let mut online_nodes = HashMap::new();
766 0 : if let Ok(deltas) = res {
767 0 : for (node_id, status) in deltas.0 {
768 0 : match status {
769 0 : PageserverState::Available { utilization, .. } => {
770 0 : online_nodes.insert(node_id, utilization);
771 0 : }
772 0 : PageserverState::Offline => {}
773 : PageserverState::WarmingUp { .. } => {
774 0 : unreachable!("Nodes are never marked warming-up during startup reconcile")
775 : }
776 : }
777 : }
778 0 : }
779 :
780 0 : online_nodes
781 0 : }
782 :
783 : /// Used during [`Self::startup_reconcile`]: issue GETs to all nodes concurrently, with a deadline.
784 : ///
785 : /// The result includes only nodes which responded within the deadline
786 0 : async fn scan_node_locations(
787 0 : &self,
788 0 : deadline: Instant,
789 0 : ) -> HashMap<NodeId, LocationConfigListResponse> {
790 0 : let nodes = {
791 0 : let locked = self.inner.read().unwrap();
792 0 : locked.nodes.clone()
793 0 : };
794 0 :
795 0 : let mut node_results = HashMap::new();
796 0 :
797 0 : let mut node_list_futs = FuturesUnordered::new();
798 0 :
799 0 : tracing::info!("Scanning shards on {} nodes...", nodes.len());
800 0 : for node in nodes.values() {
801 0 : node_list_futs.push({
802 0 : async move {
803 0 : tracing::info!("Scanning shards on node {node}...");
804 0 : let timeout = Duration::from_secs(5);
805 0 : let response = node
806 0 : .with_client_retries(
807 0 : |client| async move { client.list_location_config().await },
808 0 : &self.config.jwt_token,
809 0 : 1,
810 0 : 5,
811 0 : timeout,
812 0 : &self.cancel,
813 0 : )
814 0 : .await;
815 0 : (node.get_id(), response)
816 0 : }
817 0 : });
818 0 : }
819 :
820 : loop {
821 0 : let (node_id, result) = tokio::select! {
822 0 : next = node_list_futs.next() => {
823 0 : match next {
824 0 : Some(result) => result,
825 : None =>{
826 : // We got results for all our nodes
827 0 : break;
828 : }
829 :
830 : }
831 : },
832 0 : _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
833 : // Give up waiting for anyone who hasn't responded: we will yield the results that we have
834 0 : tracing::info!("Reached deadline while waiting for nodes to respond to location listing requests");
835 0 : break;
836 : }
837 : };
838 :
839 0 : let Some(list_response) = result else {
840 0 : tracing::info!("Shutdown during startup_reconcile");
841 0 : break;
842 : };
843 :
844 0 : match list_response {
845 0 : Err(e) => {
846 0 : tracing::warn!("Could not scan node {} ({e})", node_id);
847 : }
848 0 : Ok(listing) => {
849 0 : node_results.insert(node_id, listing);
850 0 : }
851 : }
852 : }
853 :
854 0 : node_results
855 0 : }
856 :
857 0 : async fn build_global_observed_state(&self, deadline: Instant) -> GlobalObservedState {
858 0 : let node_listings = self.scan_node_locations(deadline).await;
859 0 : let mut observed = GlobalObservedState::default();
860 :
861 0 : for (node_id, location_confs) in node_listings {
862 0 : tracing::info!(
863 0 : "Received {} shard statuses from pageserver {}",
864 0 : location_confs.tenant_shards.len(),
865 : node_id
866 : );
867 :
868 0 : for (tid, location_conf) in location_confs.tenant_shards {
869 0 : let entry = observed.0.entry(tid).or_default();
870 0 : entry.locations.insert(
871 0 : node_id,
872 0 : ObservedStateLocation {
873 0 : conf: location_conf,
874 0 : },
875 0 : );
876 0 : }
877 : }
878 :
879 0 : observed
880 0 : }
881 :
882 : /// Used during [`Self::startup_reconcile`]: detach a list of unknown-to-us tenants from pageservers.
883 : ///
884 : /// This is safe to run in the background, because if we don't have this TenantShardId in our map of
885 : /// tenants, then it is probably something incompletely deleted before: we will not fight with any
886 : /// other task trying to attach it.
887 : #[instrument(skip_all)]
888 : async fn cleanup_locations(&self, cleanup: Vec<(TenantShardId, NodeId)>) {
889 : let nodes = self.inner.read().unwrap().nodes.clone();
890 :
891 : for (tenant_shard_id, node_id) in cleanup {
892 : // A node reported a tenant_shard_id which is unknown to us: detach it.
893 : let Some(node) = nodes.get(&node_id) else {
894 : // This is legitimate; we run in the background and [`Self::startup_reconcile`] might have identified
895 : // a location to clean up on a node that has since been removed.
896 : tracing::info!(
897 : "Not cleaning up location {node_id}/{tenant_shard_id}: node not found"
898 : );
899 : continue;
900 : };
901 :
902 : if self.cancel.is_cancelled() {
903 : break;
904 : }
905 :
906 : let client = PageserverClient::new(
907 : node.get_id(),
908 : node.base_url(),
909 : self.config.jwt_token.as_deref(),
910 : );
911 : match client
912 : .location_config(
913 : tenant_shard_id,
914 : LocationConfig {
915 : mode: LocationConfigMode::Detached,
916 : generation: None,
917 : secondary_conf: None,
918 : shard_number: tenant_shard_id.shard_number.0,
919 : shard_count: tenant_shard_id.shard_count.literal(),
920 : shard_stripe_size: 0,
921 : tenant_conf: models::TenantConfig::default(),
922 : },
923 : None,
924 : false,
925 : )
926 : .await
927 : {
928 : Ok(()) => {
929 : tracing::info!(
930 : "Detached unknown shard {tenant_shard_id} on pageserver {node_id}"
931 : );
932 : }
933 : Err(e) => {
934 : // Non-fatal error: leaving a tenant shard behind that we are not managing shouldn't
935 : // break anything.
936 : tracing::error!(
937 : "Failed to detach unknkown shard {tenant_shard_id} on pageserver {node_id}: {e}"
938 : );
939 : }
940 : }
941 : }
942 : }
943 :
944 : /// Long running background task that periodically wakes up and looks for shards that need
945 : /// reconciliation. Reconciliation is fallible, so any reconciliation tasks that fail during
946 : /// e.g. a tenant create/attach/migrate must eventually be retried: this task is responsible
947 : /// for those retries.
948 : #[instrument(skip_all)]
949 : async fn background_reconcile(self: &Arc<Self>) {
950 : self.startup_complete.clone().wait().await;
951 :
952 : const BACKGROUND_RECONCILE_PERIOD: Duration = Duration::from_secs(20);
953 : let mut interval = tokio::time::interval(BACKGROUND_RECONCILE_PERIOD);
954 : while !self.reconcilers_cancel.is_cancelled() {
955 : tokio::select! {
956 : _ = interval.tick() => {
957 : let reconciles_spawned = self.reconcile_all();
958 : if reconciles_spawned == 0 {
959 : // Run optimizer only when we didn't find any other work to do
960 : let optimizations = self.optimize_all().await;
961 : if optimizations == 0 {
962 : // Run new splits only when no optimizations are pending
963 : self.autosplit_tenants().await;
964 : }
965 : }
966 : }
967 : _ = self.reconcilers_cancel.cancelled() => return
968 : }
969 : }
970 : }
971 : #[instrument(skip_all)]
972 : async fn spawn_heartbeat_driver(&self) {
973 : self.startup_complete.clone().wait().await;
974 :
975 : let mut interval = tokio::time::interval(self.config.heartbeat_interval);
976 : while !self.cancel.is_cancelled() {
977 : tokio::select! {
978 : _ = interval.tick() => { }
979 : _ = self.cancel.cancelled() => return
980 : };
981 :
982 : let nodes = {
983 : let locked = self.inner.read().unwrap();
984 : locked.nodes.clone()
985 : };
986 :
987 : let res = self.heartbeater.heartbeat(nodes).await;
988 : if let Ok(deltas) = res {
989 : let mut to_handle = Vec::default();
990 :
991 : for (node_id, state) in deltas.0 {
992 : let new_availability = match state {
993 : PageserverState::Available { utilization, .. } => {
994 : NodeAvailability::Active(utilization)
995 : }
996 : PageserverState::WarmingUp { started_at } => {
997 : NodeAvailability::WarmingUp(started_at)
998 : }
999 : PageserverState::Offline => {
1000 : // The node might have been placed in the WarmingUp state
1001 : // while the heartbeat round was on-going. Hence, filter out
1002 : // offline transitions for WarmingUp nodes that are still within
1003 : // their grace period.
1004 : if let Ok(NodeAvailability::WarmingUp(started_at)) = self
1005 : .get_node(node_id)
1006 : .await
1007 : .as_ref()
1008 0 : .map(|n| n.get_availability())
1009 : {
1010 : let now = Instant::now();
1011 : if now - *started_at >= self.config.max_warming_up_interval {
1012 : NodeAvailability::Offline
1013 : } else {
1014 : NodeAvailability::WarmingUp(*started_at)
1015 : }
1016 : } else {
1017 : NodeAvailability::Offline
1018 : }
1019 : }
1020 : };
1021 :
1022 : let node_lock = trace_exclusive_lock(
1023 : &self.node_op_locks,
1024 : node_id,
1025 : NodeOperations::Configure,
1026 : )
1027 : .await;
1028 :
1029 : pausable_failpoint!("heartbeat-pre-node-state-configure");
1030 :
1031 : // This is the code path for geniune availability transitions (i.e node
1032 : // goes unavailable and/or comes back online).
1033 : let res = self
1034 : .node_state_configure(node_id, Some(new_availability), None, &node_lock)
1035 : .await;
1036 :
1037 : match res {
1038 : Ok(transition) => {
1039 : // Keep hold of the lock until the availability transitions
1040 : // have been handled in
1041 : // [`Service::handle_node_availability_transitions`] in order avoid
1042 : // racing with [`Service::external_node_configure`].
1043 : to_handle.push((node_id, node_lock, transition));
1044 : }
1045 : Err(ApiError::NotFound(_)) => {
1046 : // This should be rare, but legitimate since the heartbeats are done
1047 : // on a snapshot of the nodes.
1048 : tracing::info!("Node {} was not found after heartbeat round", node_id);
1049 : }
1050 : Err(ApiError::ShuttingDown) => {
1051 : // No-op: we're shutting down, no need to try and update any nodes' statuses
1052 : }
1053 : Err(err) => {
1054 : // Transition to active involves reconciling: if a node responds to a heartbeat then
1055 : // becomes unavailable again, we may get an error here.
1056 : tracing::error!(
1057 : "Failed to update node state {} after heartbeat round: {}",
1058 : node_id,
1059 : err
1060 : );
1061 : }
1062 : }
1063 : }
1064 :
1065 : // We collected all the transitions above and now we handle them.
1066 : let res = self.handle_node_availability_transitions(to_handle).await;
1067 : if let Err(errs) = res {
1068 : for (node_id, err) in errs {
1069 : match err {
1070 : ApiError::NotFound(_) => {
1071 : // This should be rare, but legitimate since the heartbeats are done
1072 : // on a snapshot of the nodes.
1073 : tracing::info!(
1074 : "Node {} was not found after heartbeat round",
1075 : node_id
1076 : );
1077 : }
1078 : err => {
1079 : tracing::error!(
1080 : "Failed to handle availability transition for {} after heartbeat round: {}",
1081 : node_id,
1082 : err
1083 : );
1084 : }
1085 : }
1086 : }
1087 : }
1088 : }
1089 : }
1090 : }
1091 :
1092 : /// Apply the contents of a [`ReconcileResult`] to our in-memory state: if the reconciliation
1093 : /// was successful and intent hasn't changed since the Reconciler was spawned, this will update
1094 : /// the observed state of the tenant such that subsequent calls to [`TenantShard::get_reconcile_needed`]
1095 : /// will indicate that reconciliation is not needed.
1096 : #[instrument(skip_all, fields(
1097 : seq=%result.sequence,
1098 : tenant_id=%result.tenant_shard_id.tenant_id,
1099 : shard_id=%result.tenant_shard_id.shard_slug(),
1100 : ))]
1101 : fn process_result(&self, result: ReconcileResult) {
1102 : let mut locked = self.inner.write().unwrap();
1103 : let (nodes, tenants, _scheduler) = locked.parts_mut();
1104 : let Some(tenant) = tenants.get_mut(&result.tenant_shard_id) else {
1105 : // A reconciliation result might race with removing a tenant: drop results for
1106 : // tenants that aren't in our map.
1107 : return;
1108 : };
1109 :
1110 : // Usually generation should only be updated via this path, so the max() isn't
1111 : // needed, but it is used to handle out-of-band updates via. e.g. test hook.
1112 : tenant.generation = std::cmp::max(tenant.generation, result.generation);
1113 :
1114 : // If the reconciler signals that it failed to notify compute, set this state on
1115 : // the shard so that a future [`TenantShard::maybe_reconcile`] will try again.
1116 : tenant.pending_compute_notification = result.pending_compute_notification;
1117 :
1118 : // Let the TenantShard know it is idle.
1119 : tenant.reconcile_complete(result.sequence);
1120 :
1121 : // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
1122 : // make to the tenant
1123 0 : let deltas = result.observed_deltas.into_iter().flat_map(|delta| {
1124 : // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
1125 : // make to the tenant
1126 0 : let node = nodes.get(delta.node_id())?;
1127 :
1128 0 : if node.is_available() {
1129 0 : return Some(delta);
1130 0 : }
1131 0 :
1132 0 : // In case a node became unavailable concurrently with the reconcile, observed
1133 0 : // locations on it are now uncertain. By convention, set them to None in order
1134 0 : // for them to get refreshed when the node comes back online.
1135 0 : Some(ObservedStateDelta::Upsert(Box::new((
1136 0 : node.get_id(),
1137 0 : ObservedStateLocation { conf: None },
1138 0 : ))))
1139 0 : });
1140 :
1141 : match result.result {
1142 : Ok(()) => {
1143 : tenant.apply_observed_deltas(deltas);
1144 : tenant.waiter.advance(result.sequence);
1145 : }
1146 : Err(e) => {
1147 : match e {
1148 : ReconcileError::Cancel => {
1149 : tracing::info!("Reconciler was cancelled");
1150 : }
1151 : ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
1152 : // This might be due to the reconciler getting cancelled, or it might
1153 : // be due to the `Node` being marked offline.
1154 : tracing::info!("Reconciler cancelled during pageserver API call");
1155 : }
1156 : _ => {
1157 : tracing::warn!("Reconcile error: {}", e);
1158 : }
1159 : }
1160 :
1161 : // Ordering: populate last_error before advancing error_seq,
1162 : // so that waiters will see the correct error after waiting.
1163 : tenant.set_last_error(result.sequence, e);
1164 :
1165 : // Skip deletions on reconcile failures
1166 : let upsert_deltas =
1167 0 : deltas.filter(|delta| matches!(delta, ObservedStateDelta::Upsert(_)));
1168 : tenant.apply_observed_deltas(upsert_deltas);
1169 : }
1170 : }
1171 :
1172 : // If we just finished detaching all shards for a tenant, it might be time to drop it from memory.
1173 : if tenant.policy == PlacementPolicy::Detached {
1174 : // We may only drop a tenant from memory while holding the exclusive lock on the tenant ID: this protects us
1175 : // from concurrent execution wrt a request handler that might expect the tenant to remain in memory for the
1176 : // duration of the request.
1177 : let guard = self.tenant_op_locks.try_exclusive(
1178 : tenant.tenant_shard_id.tenant_id,
1179 : TenantOperations::DropDetached,
1180 : );
1181 : if let Some(guard) = guard {
1182 : self.maybe_drop_tenant(tenant.tenant_shard_id.tenant_id, &mut locked, &guard);
1183 : }
1184 : }
1185 :
1186 : // Maybe some other work can proceed now that this job finished.
1187 : if self.reconciler_concurrency.available_permits() > 0 {
1188 : while let Ok(tenant_shard_id) = locked.delayed_reconcile_rx.try_recv() {
1189 : let (nodes, tenants, _scheduler) = locked.parts_mut();
1190 : if let Some(shard) = tenants.get_mut(&tenant_shard_id) {
1191 : shard.delayed_reconcile = false;
1192 : self.maybe_reconcile_shard(shard, nodes);
1193 : }
1194 :
1195 : if self.reconciler_concurrency.available_permits() == 0 {
1196 : break;
1197 : }
1198 : }
1199 : }
1200 : }
1201 :
1202 0 : async fn process_results(
1203 0 : &self,
1204 0 : mut result_rx: tokio::sync::mpsc::UnboundedReceiver<ReconcileResultRequest>,
1205 0 : mut bg_compute_hook_result_rx: tokio::sync::mpsc::Receiver<
1206 0 : Result<(), (TenantShardId, NotifyError)>,
1207 0 : >,
1208 0 : ) {
1209 : loop {
1210 : // Wait for the next result, or for cancellation
1211 0 : tokio::select! {
1212 0 : r = result_rx.recv() => {
1213 0 : match r {
1214 0 : Some(ReconcileResultRequest::ReconcileResult(result)) => {self.process_result(result);},
1215 0 : None | Some(ReconcileResultRequest::Stop) => {break;}
1216 : }
1217 : }
1218 0 : _ = async{
1219 0 : match bg_compute_hook_result_rx.recv().await {
1220 0 : Some(result) => {
1221 0 : if let Err((tenant_shard_id, notify_error)) = result {
1222 0 : tracing::warn!("Marking shard {tenant_shard_id} for notification retry, due to error {notify_error}");
1223 0 : let mut locked = self.inner.write().unwrap();
1224 0 : if let Some(shard) = locked.tenants.get_mut(&tenant_shard_id) {
1225 0 : shard.pending_compute_notification = true;
1226 0 : }
1227 :
1228 0 : }
1229 : },
1230 : None => {
1231 : // This channel is dead, but we don't want to terminate the outer loop{}: just wait for shutdown
1232 0 : self.cancel.cancelled().await;
1233 : }
1234 : }
1235 0 : } => {},
1236 0 : _ = self.cancel.cancelled() => {
1237 0 : break;
1238 : }
1239 : };
1240 : }
1241 0 : }
1242 :
1243 0 : async fn process_aborts(
1244 0 : &self,
1245 0 : mut abort_rx: tokio::sync::mpsc::UnboundedReceiver<TenantShardSplitAbort>,
1246 0 : ) {
1247 : loop {
1248 : // Wait for the next result, or for cancellation
1249 0 : let op = tokio::select! {
1250 0 : r = abort_rx.recv() => {
1251 0 : match r {
1252 0 : Some(op) => {op},
1253 0 : None => {break;}
1254 : }
1255 : }
1256 0 : _ = self.cancel.cancelled() => {
1257 0 : break;
1258 : }
1259 : };
1260 :
1261 : // Retry until shutdown: we must keep this request object alive until it is properly
1262 : // processed, as it holds a lock guard that prevents other operations trying to do things
1263 : // to the tenant while it is in a weird part-split state.
1264 0 : while !self.cancel.is_cancelled() {
1265 0 : match self.abort_tenant_shard_split(&op).await {
1266 0 : Ok(_) => break,
1267 0 : Err(e) => {
1268 0 : tracing::warn!(
1269 0 : "Failed to abort shard split on {}, will retry: {e}",
1270 : op.tenant_id
1271 : );
1272 :
1273 : // If a node is unavailable, we hope that it has been properly marked Offline
1274 : // when we retry, so that the abort op will succeed. If the abort op is failing
1275 : // for some other reason, we will keep retrying forever, or until a human notices
1276 : // and does something about it (either fixing a pageserver or restarting the controller).
1277 0 : tokio::time::timeout(Duration::from_secs(5), self.cancel.cancelled())
1278 0 : .await
1279 0 : .ok();
1280 : }
1281 : }
1282 : }
1283 : }
1284 0 : }
1285 :
1286 0 : pub async fn spawn(config: Config, persistence: Arc<Persistence>) -> anyhow::Result<Arc<Self>> {
1287 0 : let (result_tx, result_rx) = tokio::sync::mpsc::unbounded_channel();
1288 0 : let (abort_tx, abort_rx) = tokio::sync::mpsc::unbounded_channel();
1289 0 :
1290 0 : let leadership_cancel = CancellationToken::new();
1291 0 : let leadership = Leadership::new(persistence.clone(), config.clone(), leadership_cancel);
1292 0 : let (leader, leader_step_down_state) = leadership.step_down_current_leader().await?;
1293 :
1294 : // Apply the migrations **after** the current leader has stepped down
1295 : // (or we've given up waiting for it), but **before** reading from the
1296 : // database. The only exception is reading the current leader before
1297 : // migrating.
1298 0 : persistence.migration_run().await?;
1299 :
1300 0 : tracing::info!("Loading nodes from database...");
1301 0 : let nodes = persistence
1302 0 : .list_nodes()
1303 0 : .await?
1304 0 : .into_iter()
1305 0 : .map(Node::from_persistent)
1306 0 : .collect::<Vec<_>>();
1307 0 : let nodes: HashMap<NodeId, Node> = nodes.into_iter().map(|n| (n.get_id(), n)).collect();
1308 0 : tracing::info!("Loaded {} nodes from database.", nodes.len());
1309 0 : metrics::METRICS_REGISTRY
1310 0 : .metrics_group
1311 0 : .storage_controller_pageserver_nodes
1312 0 : .set(nodes.len() as i64);
1313 0 :
1314 0 : tracing::info!("Loading shards from database...");
1315 0 : let mut tenant_shard_persistence = persistence.load_active_tenant_shards().await?;
1316 0 : tracing::info!(
1317 0 : "Loaded {} shards from database.",
1318 0 : tenant_shard_persistence.len()
1319 : );
1320 :
1321 : // If any shard splits were in progress, reset the database state to abort them
1322 0 : let mut tenant_shard_count_min_max: HashMap<TenantId, (ShardCount, ShardCount)> =
1323 0 : HashMap::new();
1324 0 : for tsp in &mut tenant_shard_persistence {
1325 0 : let shard = tsp.get_shard_identity()?;
1326 0 : let tenant_shard_id = tsp.get_tenant_shard_id()?;
1327 0 : let entry = tenant_shard_count_min_max
1328 0 : .entry(tenant_shard_id.tenant_id)
1329 0 : .or_insert_with(|| (shard.count, shard.count));
1330 0 : entry.0 = std::cmp::min(entry.0, shard.count);
1331 0 : entry.1 = std::cmp::max(entry.1, shard.count);
1332 0 : }
1333 :
1334 0 : for (tenant_id, (count_min, count_max)) in tenant_shard_count_min_max {
1335 0 : if count_min != count_max {
1336 : // Aborting the split in the database and dropping the child shards is sufficient: the reconciliation in
1337 : // [`Self::startup_reconcile`] will implicitly drop the child shards on remote pageservers, or they'll
1338 : // be dropped later in [`Self::node_activate_reconcile`] if it isn't available right now.
1339 0 : tracing::info!("Aborting shard split {tenant_id} {count_min:?} -> {count_max:?}");
1340 0 : let abort_status = persistence.abort_shard_split(tenant_id, count_max).await?;
1341 :
1342 : // We may never see the Complete status here: if the split was complete, we wouldn't have
1343 : // identified this tenant has having mismatching min/max counts.
1344 0 : assert!(matches!(abort_status, AbortShardSplitStatus::Aborted));
1345 :
1346 : // Clear the splitting status in-memory, to reflect that we just aborted in the database
1347 0 : tenant_shard_persistence.iter_mut().for_each(|tsp| {
1348 0 : // Set idle split state on those shards that we will retain.
1349 0 : let tsp_tenant_id = TenantId::from_str(tsp.tenant_id.as_str()).unwrap();
1350 0 : if tsp_tenant_id == tenant_id
1351 0 : && tsp.get_shard_identity().unwrap().count == count_min
1352 0 : {
1353 0 : tsp.splitting = SplitState::Idle;
1354 0 : } else if tsp_tenant_id == tenant_id {
1355 : // Leave the splitting state on the child shards: this will be used next to
1356 : // drop them.
1357 0 : tracing::info!(
1358 0 : "Shard {tsp_tenant_id} will be dropped after shard split abort",
1359 : );
1360 0 : }
1361 0 : });
1362 0 :
1363 0 : // Drop shards for this tenant which we didn't just mark idle (i.e. child shards of the aborted split)
1364 0 : tenant_shard_persistence.retain(|tsp| {
1365 0 : TenantId::from_str(tsp.tenant_id.as_str()).unwrap() != tenant_id
1366 0 : || tsp.splitting == SplitState::Idle
1367 0 : });
1368 0 : }
1369 : }
1370 :
1371 0 : let mut tenants = BTreeMap::new();
1372 0 :
1373 0 : let mut scheduler = Scheduler::new(nodes.values());
1374 :
1375 : #[cfg(feature = "testing")]
1376 : {
1377 : use pageserver_api::controller_api::AvailabilityZone;
1378 :
1379 : // Hack: insert scheduler state for all nodes referenced by shards, as compatibility
1380 : // tests only store the shards, not the nodes. The nodes will be loaded shortly
1381 : // after when pageservers start up and register.
1382 0 : let mut node_ids = HashSet::new();
1383 0 : for tsp in &tenant_shard_persistence {
1384 0 : if let Some(node_id) = tsp.generation_pageserver {
1385 0 : node_ids.insert(node_id);
1386 0 : }
1387 : }
1388 0 : for node_id in node_ids {
1389 0 : tracing::info!("Creating node {} in scheduler for tests", node_id);
1390 0 : let node = Node::new(
1391 0 : NodeId(node_id as u64),
1392 0 : "".to_string(),
1393 0 : 123,
1394 0 : "".to_string(),
1395 0 : 123,
1396 0 : AvailabilityZone("test_az".to_string()),
1397 0 : );
1398 0 :
1399 0 : scheduler.node_upsert(&node);
1400 : }
1401 : }
1402 0 : for tsp in tenant_shard_persistence {
1403 0 : let tenant_shard_id = tsp.get_tenant_shard_id()?;
1404 :
1405 : // We will populate intent properly later in [`Self::startup_reconcile`], initially populate
1406 : // it with what we can infer: the node for which a generation was most recently issued.
1407 0 : let mut intent = IntentState::new();
1408 0 : if let Some(generation_pageserver) = tsp.generation_pageserver.map(|n| NodeId(n as u64))
1409 : {
1410 0 : if nodes.contains_key(&generation_pageserver) {
1411 0 : intent.set_attached(&mut scheduler, Some(generation_pageserver));
1412 0 : } else {
1413 : // If a node was removed before being completely drained, it is legal for it to leave behind a `generation_pageserver` referring
1414 : // to a non-existent node, because node deletion doesn't block on completing the reconciliations that will issue new generations
1415 : // on different pageservers.
1416 0 : tracing::warn!("Tenant shard {tenant_shard_id} references non-existent node {generation_pageserver} in database, will be rescheduled");
1417 : }
1418 0 : }
1419 0 : let new_tenant = TenantShard::from_persistent(tsp, intent)?;
1420 :
1421 0 : tenants.insert(tenant_shard_id, new_tenant);
1422 : }
1423 :
1424 0 : let (startup_completion, startup_complete) = utils::completion::channel();
1425 0 :
1426 0 : // This channel is continuously consumed by process_results, so doesn't need to be very large.
1427 0 : let (bg_compute_notify_result_tx, bg_compute_notify_result_rx) =
1428 0 : tokio::sync::mpsc::channel(512);
1429 0 :
1430 0 : let (delayed_reconcile_tx, delayed_reconcile_rx) =
1431 0 : tokio::sync::mpsc::channel(MAX_DELAYED_RECONCILES);
1432 0 :
1433 0 : let cancel = CancellationToken::new();
1434 0 : let reconcilers_cancel = cancel.child_token();
1435 0 :
1436 0 : let heartbeater = Heartbeater::new(
1437 0 : config.jwt_token.clone(),
1438 0 : config.max_offline_interval,
1439 0 : config.max_warming_up_interval,
1440 0 : cancel.clone(),
1441 0 : );
1442 :
1443 0 : let initial_leadership_status = if config.start_as_candidate {
1444 0 : LeadershipStatus::Candidate
1445 : } else {
1446 0 : LeadershipStatus::Leader
1447 : };
1448 :
1449 0 : let this = Arc::new(Self {
1450 0 : inner: Arc::new(std::sync::RwLock::new(ServiceState::new(
1451 0 : nodes,
1452 0 : tenants,
1453 0 : scheduler,
1454 0 : delayed_reconcile_rx,
1455 0 : initial_leadership_status,
1456 0 : ))),
1457 0 : config: config.clone(),
1458 0 : persistence,
1459 0 : compute_hook: Arc::new(ComputeHook::new(config.clone())),
1460 0 : result_tx,
1461 0 : heartbeater,
1462 0 : reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
1463 0 : config.reconciler_concurrency,
1464 0 : )),
1465 0 : delayed_reconcile_tx,
1466 0 : abort_tx,
1467 0 : startup_complete: startup_complete.clone(),
1468 0 : cancel,
1469 0 : reconcilers_cancel,
1470 0 : gate: Gate::default(),
1471 0 : reconcilers_gate: Gate::default(),
1472 0 : tenant_op_locks: Default::default(),
1473 0 : node_op_locks: Default::default(),
1474 0 : });
1475 0 :
1476 0 : let result_task_this = this.clone();
1477 0 : tokio::task::spawn(async move {
1478 : // Block shutdown until we're done (we must respect self.cancel)
1479 0 : if let Ok(_gate) = result_task_this.gate.enter() {
1480 0 : result_task_this
1481 0 : .process_results(result_rx, bg_compute_notify_result_rx)
1482 0 : .await
1483 0 : }
1484 0 : });
1485 0 :
1486 0 : tokio::task::spawn({
1487 0 : let this = this.clone();
1488 0 : async move {
1489 : // Block shutdown until we're done (we must respect self.cancel)
1490 0 : if let Ok(_gate) = this.gate.enter() {
1491 0 : this.process_aborts(abort_rx).await
1492 0 : }
1493 0 : }
1494 0 : });
1495 0 :
1496 0 : tokio::task::spawn({
1497 0 : let this = this.clone();
1498 0 : async move {
1499 0 : if let Ok(_gate) = this.gate.enter() {
1500 : loop {
1501 0 : tokio::select! {
1502 0 : _ = this.cancel.cancelled() => {
1503 0 : break;
1504 : },
1505 0 : _ = tokio::time::sleep(Duration::from_secs(60)) => {}
1506 0 : };
1507 0 : this.tenant_op_locks.housekeeping();
1508 : }
1509 0 : }
1510 0 : }
1511 0 : });
1512 0 :
1513 0 : tokio::task::spawn({
1514 0 : let this = this.clone();
1515 0 : // We will block the [`Service::startup_complete`] barrier until [`Self::startup_reconcile`]
1516 0 : // is done.
1517 0 : let startup_completion = startup_completion.clone();
1518 0 : async move {
1519 : // Block shutdown until we're done (we must respect self.cancel)
1520 0 : let Ok(_gate) = this.gate.enter() else {
1521 0 : return;
1522 : };
1523 :
1524 0 : this.startup_reconcile(leader, leader_step_down_state, bg_compute_notify_result_tx)
1525 0 : .await;
1526 :
1527 0 : drop(startup_completion);
1528 0 : }
1529 0 : });
1530 0 :
1531 0 : tokio::task::spawn({
1532 0 : let this = this.clone();
1533 0 : let startup_complete = startup_complete.clone();
1534 0 : async move {
1535 0 : startup_complete.wait().await;
1536 0 : this.background_reconcile().await;
1537 0 : }
1538 0 : });
1539 0 :
1540 0 : tokio::task::spawn({
1541 0 : let this = this.clone();
1542 0 : let startup_complete = startup_complete.clone();
1543 0 : async move {
1544 0 : startup_complete.wait().await;
1545 0 : this.spawn_heartbeat_driver().await;
1546 0 : }
1547 0 : });
1548 0 :
1549 0 : Ok(this)
1550 0 : }
1551 :
1552 0 : pub(crate) async fn attach_hook(
1553 0 : &self,
1554 0 : attach_req: AttachHookRequest,
1555 0 : ) -> anyhow::Result<AttachHookResponse> {
1556 0 : let _tenant_lock = trace_exclusive_lock(
1557 0 : &self.tenant_op_locks,
1558 0 : attach_req.tenant_shard_id.tenant_id,
1559 0 : TenantOperations::AttachHook,
1560 0 : )
1561 0 : .await;
1562 :
1563 : // This is a test hook. To enable using it on tenants that were created directly with
1564 : // the pageserver API (not via this service), we will auto-create any missing tenant
1565 : // shards with default state.
1566 0 : let insert = {
1567 0 : match self
1568 0 : .maybe_load_tenant(attach_req.tenant_shard_id.tenant_id, &_tenant_lock)
1569 0 : .await
1570 : {
1571 0 : Ok(_) => false,
1572 0 : Err(ApiError::NotFound(_)) => true,
1573 0 : Err(e) => return Err(e.into()),
1574 : }
1575 : };
1576 :
1577 0 : if insert {
1578 0 : let tsp = TenantShardPersistence {
1579 0 : tenant_id: attach_req.tenant_shard_id.tenant_id.to_string(),
1580 0 : shard_number: attach_req.tenant_shard_id.shard_number.0 as i32,
1581 0 : shard_count: attach_req.tenant_shard_id.shard_count.literal() as i32,
1582 0 : shard_stripe_size: 0,
1583 0 : generation: attach_req.generation_override.or(Some(0)),
1584 0 : generation_pageserver: None,
1585 0 : placement_policy: serde_json::to_string(&PlacementPolicy::Attached(0)).unwrap(),
1586 0 : config: serde_json::to_string(&TenantConfig::default()).unwrap(),
1587 0 : splitting: SplitState::default(),
1588 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
1589 0 : .unwrap(),
1590 0 : preferred_az_id: None,
1591 0 : };
1592 0 :
1593 0 : match self.persistence.insert_tenant_shards(vec![tsp]).await {
1594 0 : Err(e) => match e {
1595 : DatabaseError::Query(diesel::result::Error::DatabaseError(
1596 : DatabaseErrorKind::UniqueViolation,
1597 : _,
1598 : )) => {
1599 0 : tracing::info!(
1600 0 : "Raced with another request to insert tenant {}",
1601 : attach_req.tenant_shard_id
1602 : )
1603 : }
1604 0 : _ => return Err(e.into()),
1605 : },
1606 : Ok(()) => {
1607 0 : tracing::info!("Inserted shard {} in database", attach_req.tenant_shard_id);
1608 :
1609 0 : let mut locked = self.inner.write().unwrap();
1610 0 : locked.tenants.insert(
1611 0 : attach_req.tenant_shard_id,
1612 0 : TenantShard::new(
1613 0 : attach_req.tenant_shard_id,
1614 0 : ShardIdentity::unsharded(),
1615 0 : PlacementPolicy::Attached(0),
1616 0 : None,
1617 0 : ),
1618 0 : );
1619 0 : tracing::info!("Inserted shard {} in memory", attach_req.tenant_shard_id);
1620 : }
1621 : }
1622 0 : }
1623 :
1624 0 : let new_generation = if let Some(req_node_id) = attach_req.node_id {
1625 0 : let maybe_tenant_conf = {
1626 0 : let locked = self.inner.write().unwrap();
1627 0 : locked
1628 0 : .tenants
1629 0 : .get(&attach_req.tenant_shard_id)
1630 0 : .map(|t| t.config.clone())
1631 0 : };
1632 0 :
1633 0 : match maybe_tenant_conf {
1634 0 : Some(conf) => {
1635 0 : let new_generation = self
1636 0 : .persistence
1637 0 : .increment_generation(attach_req.tenant_shard_id, req_node_id)
1638 0 : .await?;
1639 :
1640 : // Persist the placement policy update. This is required
1641 : // when we reattaching a detached tenant.
1642 0 : self.persistence
1643 0 : .update_tenant_shard(
1644 0 : TenantFilter::Shard(attach_req.tenant_shard_id),
1645 0 : Some(PlacementPolicy::Attached(0)),
1646 0 : Some(conf),
1647 0 : None,
1648 0 : None,
1649 0 : )
1650 0 : .await?;
1651 0 : Some(new_generation)
1652 : }
1653 : None => {
1654 0 : anyhow::bail!("Attach hook handling raced with tenant removal")
1655 : }
1656 : }
1657 : } else {
1658 0 : self.persistence.detach(attach_req.tenant_shard_id).await?;
1659 0 : None
1660 : };
1661 :
1662 0 : let mut locked = self.inner.write().unwrap();
1663 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
1664 0 :
1665 0 : let tenant_shard = tenants
1666 0 : .get_mut(&attach_req.tenant_shard_id)
1667 0 : .expect("Checked for existence above");
1668 :
1669 0 : if let Some(new_generation) = new_generation {
1670 0 : tenant_shard.generation = Some(new_generation);
1671 0 : tenant_shard.policy = PlacementPolicy::Attached(0);
1672 0 : } else {
1673 : // This is a detach notification. We must update placement policy to avoid re-attaching
1674 : // during background scheduling/reconciliation, or during storage controller restart.
1675 0 : assert!(attach_req.node_id.is_none());
1676 0 : tenant_shard.policy = PlacementPolicy::Detached;
1677 : }
1678 :
1679 0 : if let Some(attaching_pageserver) = attach_req.node_id.as_ref() {
1680 0 : tracing::info!(
1681 : tenant_id = %attach_req.tenant_shard_id,
1682 : ps_id = %attaching_pageserver,
1683 : generation = ?tenant_shard.generation,
1684 0 : "issuing",
1685 : );
1686 0 : } else if let Some(ps_id) = tenant_shard.intent.get_attached() {
1687 0 : tracing::info!(
1688 : tenant_id = %attach_req.tenant_shard_id,
1689 : %ps_id,
1690 : generation = ?tenant_shard.generation,
1691 0 : "dropping",
1692 : );
1693 : } else {
1694 0 : tracing::info!(
1695 : tenant_id = %attach_req.tenant_shard_id,
1696 0 : "no-op: tenant already has no pageserver");
1697 : }
1698 0 : tenant_shard
1699 0 : .intent
1700 0 : .set_attached(scheduler, attach_req.node_id);
1701 0 :
1702 0 : tracing::info!(
1703 0 : "attach_hook: tenant {} set generation {:?}, pageserver {}",
1704 0 : attach_req.tenant_shard_id,
1705 0 : tenant_shard.generation,
1706 0 : // TODO: this is an odd number of 0xf's
1707 0 : attach_req.node_id.unwrap_or(utils::id::NodeId(0xfffffff))
1708 : );
1709 :
1710 : // Trick the reconciler into not doing anything for this tenant: this helps
1711 : // tests that manually configure a tenant on the pagesrever, and then call this
1712 : // attach hook: they don't want background reconciliation to modify what they
1713 : // did to the pageserver.
1714 : #[cfg(feature = "testing")]
1715 : {
1716 0 : if let Some(node_id) = attach_req.node_id {
1717 0 : tenant_shard.observed.locations = HashMap::from([(
1718 0 : node_id,
1719 0 : ObservedStateLocation {
1720 0 : conf: Some(attached_location_conf(
1721 0 : tenant_shard.generation.unwrap(),
1722 0 : &tenant_shard.shard,
1723 0 : &tenant_shard.config,
1724 0 : &PlacementPolicy::Attached(0),
1725 0 : )),
1726 0 : },
1727 0 : )]);
1728 0 : } else {
1729 0 : tenant_shard.observed.locations.clear();
1730 0 : }
1731 : }
1732 :
1733 0 : Ok(AttachHookResponse {
1734 0 : gen: attach_req
1735 0 : .node_id
1736 0 : .map(|_| tenant_shard.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap()),
1737 0 : })
1738 0 : }
1739 :
1740 0 : pub(crate) fn inspect(&self, inspect_req: InspectRequest) -> InspectResponse {
1741 0 : let locked = self.inner.read().unwrap();
1742 0 :
1743 0 : let tenant_shard = locked.tenants.get(&inspect_req.tenant_shard_id);
1744 0 :
1745 0 : InspectResponse {
1746 0 : attachment: tenant_shard.and_then(|s| {
1747 0 : s.intent
1748 0 : .get_attached()
1749 0 : .map(|ps| (s.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap(), ps))
1750 0 : }),
1751 0 : }
1752 0 : }
1753 :
1754 : // When the availability state of a node transitions to active, we must do a full reconciliation
1755 : // of LocationConfigs on that node. This is because while a node was offline:
1756 : // - we might have proceeded through startup_reconcile without checking for extraneous LocationConfigs on this node
1757 : // - aborting a tenant shard split might have left rogue child shards behind on this node.
1758 : //
1759 : // This function must complete _before_ setting a `Node` to Active: once it is set to Active, other
1760 : // Reconcilers might communicate with the node, and these must not overlap with the work we do in
1761 : // this function.
1762 : //
1763 : // The reconciliation logic in here is very similar to what [`Self::startup_reconcile`] does, but
1764 : // for written for a single node rather than as a batch job for all nodes.
1765 : #[tracing::instrument(skip_all, fields(node_id=%node.get_id()))]
1766 : async fn node_activate_reconcile(
1767 : &self,
1768 : mut node: Node,
1769 : _lock: &TracingExclusiveGuard<NodeOperations>,
1770 : ) -> Result<(), ApiError> {
1771 : // This Node is a mutable local copy: we will set it active so that we can use its
1772 : // API client to reconcile with the node. The Node in [`Self::nodes`] will get updated
1773 : // later.
1774 : node.set_availability(NodeAvailability::Active(PageserverUtilization::full()));
1775 :
1776 : let configs = match node
1777 : .with_client_retries(
1778 0 : |client| async move { client.list_location_config().await },
1779 : &self.config.jwt_token,
1780 : 1,
1781 : 5,
1782 : SHORT_RECONCILE_TIMEOUT,
1783 : &self.cancel,
1784 : )
1785 : .await
1786 : {
1787 : None => {
1788 : // We're shutting down (the Node's cancellation token can't have fired, because
1789 : // we're the only scope that has a reference to it, and we didn't fire it).
1790 : return Err(ApiError::ShuttingDown);
1791 : }
1792 : Some(Err(e)) => {
1793 : // This node didn't succeed listing its locations: it may not proceed to active state
1794 : // as it is apparently unavailable.
1795 : return Err(ApiError::PreconditionFailed(
1796 : format!("Failed to query node location configs, cannot activate ({e})").into(),
1797 : ));
1798 : }
1799 : Some(Ok(configs)) => configs,
1800 : };
1801 : tracing::info!("Loaded {} LocationConfigs", configs.tenant_shards.len());
1802 :
1803 : let mut cleanup = Vec::new();
1804 : {
1805 : let mut locked = self.inner.write().unwrap();
1806 :
1807 : for (tenant_shard_id, observed_loc) in configs.tenant_shards {
1808 : let Some(tenant_shard) = locked.tenants.get_mut(&tenant_shard_id) else {
1809 : cleanup.push(tenant_shard_id);
1810 : continue;
1811 : };
1812 : tenant_shard
1813 : .observed
1814 : .locations
1815 : .insert(node.get_id(), ObservedStateLocation { conf: observed_loc });
1816 : }
1817 : }
1818 :
1819 : for tenant_shard_id in cleanup {
1820 : tracing::info!("Detaching {tenant_shard_id}");
1821 : match node
1822 : .with_client_retries(
1823 0 : |client| async move {
1824 0 : let config = LocationConfig {
1825 0 : mode: LocationConfigMode::Detached,
1826 0 : generation: None,
1827 0 : secondary_conf: None,
1828 0 : shard_number: tenant_shard_id.shard_number.0,
1829 0 : shard_count: tenant_shard_id.shard_count.literal(),
1830 0 : shard_stripe_size: 0,
1831 0 : tenant_conf: models::TenantConfig::default(),
1832 0 : };
1833 0 : client
1834 0 : .location_config(tenant_shard_id, config, None, false)
1835 0 : .await
1836 0 : },
1837 : &self.config.jwt_token,
1838 : 1,
1839 : 5,
1840 : SHORT_RECONCILE_TIMEOUT,
1841 : &self.cancel,
1842 : )
1843 : .await
1844 : {
1845 : None => {
1846 : // We're shutting down (the Node's cancellation token can't have fired, because
1847 : // we're the only scope that has a reference to it, and we didn't fire it).
1848 : return Err(ApiError::ShuttingDown);
1849 : }
1850 : Some(Err(e)) => {
1851 : // Do not let the node proceed to Active state if it is not responsive to requests
1852 : // to detach. This could happen if e.g. a shutdown bug in the pageserver is preventing
1853 : // detach completing: we should not let this node back into the set of nodes considered
1854 : // okay for scheduling.
1855 : return Err(ApiError::Conflict(format!(
1856 : "Node {node} failed to detach {tenant_shard_id}: {e}"
1857 : )));
1858 : }
1859 : Some(Ok(_)) => {}
1860 : };
1861 : }
1862 :
1863 : Ok(())
1864 : }
1865 :
1866 0 : pub(crate) async fn re_attach(
1867 0 : &self,
1868 0 : reattach_req: ReAttachRequest,
1869 0 : ) -> Result<ReAttachResponse, ApiError> {
1870 0 : if let Some(register_req) = reattach_req.register {
1871 0 : self.node_register(register_req).await?;
1872 0 : }
1873 :
1874 : // Ordering: we must persist generation number updates before making them visible in the in-memory state
1875 0 : let incremented_generations = self.persistence.re_attach(reattach_req.node_id).await?;
1876 :
1877 0 : tracing::info!(
1878 : node_id=%reattach_req.node_id,
1879 0 : "Incremented {} tenant shards' generations",
1880 0 : incremented_generations.len()
1881 : );
1882 :
1883 : // Apply the updated generation to our in-memory state, and
1884 : // gather discover secondary locations.
1885 0 : let mut locked = self.inner.write().unwrap();
1886 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
1887 0 :
1888 0 : let mut response = ReAttachResponse {
1889 0 : tenants: Vec::new(),
1890 0 : };
1891 :
1892 : // TODO: cancel/restart any running reconciliation for this tenant, it might be trying
1893 : // to call location_conf API with an old generation. Wait for cancellation to complete
1894 : // before responding to this request. Requires well implemented CancellationToken logic
1895 : // all the way to where we call location_conf. Even then, there can still be a location_conf
1896 : // request in flight over the network: TODO handle that by making location_conf API refuse
1897 : // to go backward in generations.
1898 :
1899 : // Scan through all shards, applying updates for ones where we updated generation
1900 : // and identifying shards that intend to have a secondary location on this node.
1901 0 : for (tenant_shard_id, shard) in tenants {
1902 0 : if let Some(new_gen) = incremented_generations.get(tenant_shard_id) {
1903 0 : let new_gen = *new_gen;
1904 0 : response.tenants.push(ReAttachResponseTenant {
1905 0 : id: *tenant_shard_id,
1906 0 : gen: Some(new_gen.into().unwrap()),
1907 0 : // A tenant is only put into multi or stale modes in the middle of a [`Reconciler::live_migrate`]
1908 0 : // execution. If a pageserver is restarted during that process, then the reconcile pass will
1909 0 : // fail, and start from scratch, so it doesn't make sense for us to try and preserve
1910 0 : // the stale/multi states at this point.
1911 0 : mode: LocationConfigMode::AttachedSingle,
1912 0 : });
1913 0 :
1914 0 : shard.generation = std::cmp::max(shard.generation, Some(new_gen));
1915 0 : if let Some(observed) = shard.observed.locations.get_mut(&reattach_req.node_id) {
1916 : // Why can we update `observed` even though we're not sure our response will be received
1917 : // by the pageserver? Because the pageserver will not proceed with startup until
1918 : // it has processed response: if it loses it, we'll see another request and increment
1919 : // generation again, avoiding any uncertainty about dirtiness of tenant's state.
1920 0 : if let Some(conf) = observed.conf.as_mut() {
1921 0 : conf.generation = new_gen.into();
1922 0 : }
1923 0 : } else {
1924 0 : // This node has no observed state for the shard: perhaps it was offline
1925 0 : // when the pageserver restarted. Insert a None, so that the Reconciler
1926 0 : // will be prompted to learn the location's state before it makes changes.
1927 0 : shard
1928 0 : .observed
1929 0 : .locations
1930 0 : .insert(reattach_req.node_id, ObservedStateLocation { conf: None });
1931 0 : }
1932 0 : } else if shard.intent.get_secondary().contains(&reattach_req.node_id) {
1933 0 : // Ordering: pageserver will not accept /location_config requests until it has
1934 0 : // finished processing the response from re-attach. So we can update our in-memory state
1935 0 : // now, and be confident that we are not stamping on the result of some later location config.
1936 0 : // TODO: however, we are not strictly ordered wrt ReconcileResults queue,
1937 0 : // so we might update observed state here, and then get over-written by some racing
1938 0 : // ReconcileResult. The impact is low however, since we have set state on pageserver something
1939 0 : // that matches intent, so worst case if we race then we end up doing a spurious reconcile.
1940 0 :
1941 0 : response.tenants.push(ReAttachResponseTenant {
1942 0 : id: *tenant_shard_id,
1943 0 : gen: None,
1944 0 : mode: LocationConfigMode::Secondary,
1945 0 : });
1946 0 :
1947 0 : // We must not update observed, because we have no guarantee that our
1948 0 : // response will be received by the pageserver. This could leave it
1949 0 : // falsely dirty, but the resulting reconcile should be idempotent.
1950 0 : }
1951 : }
1952 :
1953 : // We consider a node Active once we have composed a re-attach response, but we
1954 : // do not call [`Self::node_activate_reconcile`]: the handling of the re-attach response
1955 : // implicitly synchronizes the LocationConfigs on the node.
1956 : //
1957 : // Setting a node active unblocks any Reconcilers that might write to the location config API,
1958 : // but those requests will not be accepted by the node until it has finished processing
1959 : // the re-attach response.
1960 : //
1961 : // Additionally, reset the nodes scheduling policy to match the conditional update done
1962 : // in [`Persistence::re_attach`].
1963 0 : if let Some(node) = nodes.get(&reattach_req.node_id) {
1964 0 : let reset_scheduling = matches!(
1965 0 : node.get_scheduling(),
1966 : NodeSchedulingPolicy::PauseForRestart
1967 : | NodeSchedulingPolicy::Draining
1968 : | NodeSchedulingPolicy::Filling
1969 : );
1970 :
1971 0 : let mut new_nodes = (**nodes).clone();
1972 0 : if let Some(node) = new_nodes.get_mut(&reattach_req.node_id) {
1973 0 : if reset_scheduling {
1974 0 : node.set_scheduling(NodeSchedulingPolicy::Active);
1975 0 : }
1976 :
1977 0 : tracing::info!("Marking {} warming-up on reattach", reattach_req.node_id);
1978 0 : node.set_availability(NodeAvailability::WarmingUp(std::time::Instant::now()));
1979 0 :
1980 0 : scheduler.node_upsert(node);
1981 0 : let new_nodes = Arc::new(new_nodes);
1982 0 : *nodes = new_nodes;
1983 : } else {
1984 0 : tracing::error!(
1985 0 : "Reattaching node {} was removed while processing the request",
1986 : reattach_req.node_id
1987 : );
1988 : }
1989 0 : }
1990 :
1991 0 : Ok(response)
1992 0 : }
1993 :
1994 0 : pub(crate) async fn validate(
1995 0 : &self,
1996 0 : validate_req: ValidateRequest,
1997 0 : ) -> Result<ValidateResponse, DatabaseError> {
1998 : // Fast in-memory check: we may reject validation on anything that doesn't match our
1999 : // in-memory generation for a shard
2000 0 : let in_memory_result = {
2001 0 : let mut in_memory_result = Vec::new();
2002 0 : let locked = self.inner.read().unwrap();
2003 0 : for req_tenant in validate_req.tenants {
2004 0 : if let Some(tenant_shard) = locked.tenants.get(&req_tenant.id) {
2005 0 : let valid = tenant_shard.generation == Some(Generation::new(req_tenant.gen));
2006 0 : tracing::info!(
2007 0 : "handle_validate: {}(gen {}): valid={valid} (latest {:?})",
2008 : req_tenant.id,
2009 : req_tenant.gen,
2010 : tenant_shard.generation
2011 : );
2012 :
2013 0 : in_memory_result.push((req_tenant.id, Generation::new(req_tenant.gen), valid));
2014 : } else {
2015 : // This is legal: for example during a shard split the pageserver may still
2016 : // have deletions in its queue from the old pre-split shard, or after deletion
2017 : // of a tenant that was busy with compaction/gc while being deleted.
2018 0 : tracing::info!(
2019 0 : "Refusing deletion validation for missing shard {}",
2020 : req_tenant.id
2021 : );
2022 : }
2023 : }
2024 :
2025 0 : in_memory_result
2026 : };
2027 :
2028 : // Database calls to confirm validity for anything that passed the in-memory check. We must do this
2029 : // in case of controller split-brain, where some other controller process might have incremented the generation.
2030 0 : let db_generations = self
2031 0 : .persistence
2032 0 : .shard_generations(in_memory_result.iter().filter_map(|i| {
2033 0 : if i.2 {
2034 0 : Some(&i.0)
2035 : } else {
2036 0 : None
2037 : }
2038 0 : }))
2039 0 : .await?;
2040 0 : let db_generations = db_generations.into_iter().collect::<HashMap<_, _>>();
2041 0 :
2042 0 : let mut response = ValidateResponse {
2043 0 : tenants: Vec::new(),
2044 0 : };
2045 0 : for (tenant_shard_id, validate_generation, valid) in in_memory_result.into_iter() {
2046 0 : let valid = if valid {
2047 0 : let db_generation = db_generations.get(&tenant_shard_id);
2048 0 : db_generation == Some(&Some(validate_generation))
2049 : } else {
2050 : // If in-memory state says it's invalid, trust that. It's always safe to fail a validation, at worst
2051 : // this prevents a pageserver from cleaning up an object in S3.
2052 0 : false
2053 : };
2054 :
2055 0 : response.tenants.push(ValidateResponseTenant {
2056 0 : id: tenant_shard_id,
2057 0 : valid,
2058 0 : })
2059 : }
2060 :
2061 0 : Ok(response)
2062 0 : }
2063 :
2064 0 : pub(crate) async fn tenant_create(
2065 0 : &self,
2066 0 : create_req: TenantCreateRequest,
2067 0 : ) -> Result<TenantCreateResponse, ApiError> {
2068 0 : let tenant_id = create_req.new_tenant_id.tenant_id;
2069 :
2070 : // Exclude any concurrent attempts to create/access the same tenant ID
2071 0 : let _tenant_lock = trace_exclusive_lock(
2072 0 : &self.tenant_op_locks,
2073 0 : create_req.new_tenant_id.tenant_id,
2074 0 : TenantOperations::Create,
2075 0 : )
2076 0 : .await;
2077 0 : let (response, waiters) = self.do_tenant_create(create_req).await?;
2078 :
2079 0 : if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
2080 : // Avoid deadlock: reconcile may fail while notifying compute, if the cloud control plane refuses to
2081 : // accept compute notifications while it is in the process of creating. Reconciliation will
2082 : // be retried in the background.
2083 0 : tracing::warn!(%tenant_id, "Reconcile not done yet while creating tenant ({e})");
2084 0 : }
2085 0 : Ok(response)
2086 0 : }
2087 :
2088 0 : pub(crate) async fn do_tenant_create(
2089 0 : &self,
2090 0 : create_req: TenantCreateRequest,
2091 0 : ) -> Result<(TenantCreateResponse, Vec<ReconcilerWaiter>), ApiError> {
2092 0 : let placement_policy = create_req
2093 0 : .placement_policy
2094 0 : .clone()
2095 0 : // As a default, zero secondaries is convenient for tests that don't choose a policy.
2096 0 : .unwrap_or(PlacementPolicy::Attached(0));
2097 :
2098 : // This service expects to handle sharding itself: it is an error to try and directly create
2099 : // a particular shard here.
2100 0 : let tenant_id = if !create_req.new_tenant_id.is_unsharded() {
2101 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
2102 0 : "Attempted to create a specific shard, this API is for creating the whole tenant"
2103 0 : )));
2104 : } else {
2105 0 : create_req.new_tenant_id.tenant_id
2106 0 : };
2107 0 :
2108 0 : tracing::info!(
2109 0 : "Creating tenant {}, shard_count={:?}",
2110 : create_req.new_tenant_id,
2111 : create_req.shard_parameters.count,
2112 : );
2113 :
2114 0 : let create_ids = (0..create_req.shard_parameters.count.count())
2115 0 : .map(|i| TenantShardId {
2116 0 : tenant_id,
2117 0 : shard_number: ShardNumber(i),
2118 0 : shard_count: create_req.shard_parameters.count,
2119 0 : })
2120 0 : .collect::<Vec<_>>();
2121 :
2122 : // If the caller specifies a None generation, it means "start from default". This is different
2123 : // to [`Self::tenant_location_config`], where a None generation is used to represent
2124 : // an incompletely-onboarded tenant.
2125 0 : let initial_generation = if matches!(placement_policy, PlacementPolicy::Secondary) {
2126 0 : tracing::info!(
2127 0 : "tenant_create: secondary mode, generation is_some={}",
2128 0 : create_req.generation.is_some()
2129 : );
2130 0 : create_req.generation.map(Generation::new)
2131 : } else {
2132 0 : tracing::info!(
2133 0 : "tenant_create: not secondary mode, generation is_some={}",
2134 0 : create_req.generation.is_some()
2135 : );
2136 0 : Some(
2137 0 : create_req
2138 0 : .generation
2139 0 : .map(Generation::new)
2140 0 : .unwrap_or(INITIAL_GENERATION),
2141 0 : )
2142 : };
2143 :
2144 0 : let preferred_az_id = {
2145 0 : let locked = self.inner.read().unwrap();
2146 : // Idempotency: take the existing value if the tenant already exists
2147 0 : if let Some(shard) = locked.tenants.get(create_ids.first().unwrap()) {
2148 0 : shard.preferred_az().cloned()
2149 : } else {
2150 0 : locked.scheduler.get_az_for_new_tenant()
2151 : }
2152 : };
2153 :
2154 : // Ordering: we persist tenant shards before creating them on the pageserver. This enables a caller
2155 : // to clean up after themselves by issuing a tenant deletion if something goes wrong and we restart
2156 : // during the creation, rather than risking leaving orphan objects in S3.
2157 0 : let persist_tenant_shards = create_ids
2158 0 : .iter()
2159 0 : .map(|tenant_shard_id| TenantShardPersistence {
2160 0 : tenant_id: tenant_shard_id.tenant_id.to_string(),
2161 0 : shard_number: tenant_shard_id.shard_number.0 as i32,
2162 0 : shard_count: tenant_shard_id.shard_count.literal() as i32,
2163 0 : shard_stripe_size: create_req.shard_parameters.stripe_size.0 as i32,
2164 0 : generation: initial_generation.map(|g| g.into().unwrap() as i32),
2165 0 : // The pageserver is not known until scheduling happens: we will set this column when
2166 0 : // incrementing the generation the first time we attach to a pageserver.
2167 0 : generation_pageserver: None,
2168 0 : placement_policy: serde_json::to_string(&placement_policy).unwrap(),
2169 0 : config: serde_json::to_string(&create_req.config).unwrap(),
2170 0 : splitting: SplitState::default(),
2171 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
2172 0 : .unwrap(),
2173 0 : preferred_az_id: preferred_az_id.as_ref().map(|az| az.to_string()),
2174 0 : })
2175 0 : .collect();
2176 0 :
2177 0 : match self
2178 0 : .persistence
2179 0 : .insert_tenant_shards(persist_tenant_shards)
2180 0 : .await
2181 : {
2182 0 : Ok(_) => {}
2183 : Err(DatabaseError::Query(diesel::result::Error::DatabaseError(
2184 : DatabaseErrorKind::UniqueViolation,
2185 : _,
2186 : ))) => {
2187 : // Unique key violation: this is probably a retry. Because the shard count is part of the unique key,
2188 : // if we see a unique key violation it means that the creation request's shard count matches the previous
2189 : // creation's shard count.
2190 0 : tracing::info!("Tenant shards already present in database, proceeding with idempotent creation...");
2191 : }
2192 : // Any other database error is unexpected and a bug.
2193 0 : Err(e) => return Err(ApiError::InternalServerError(anyhow::anyhow!(e))),
2194 : };
2195 :
2196 0 : let mut schedule_context = ScheduleContext::default();
2197 0 : let mut schedule_error = None;
2198 0 : let mut response_shards = Vec::new();
2199 0 : for tenant_shard_id in create_ids {
2200 0 : tracing::info!("Creating shard {tenant_shard_id}...");
2201 :
2202 0 : let outcome = self
2203 0 : .do_initial_shard_scheduling(
2204 0 : tenant_shard_id,
2205 0 : initial_generation,
2206 0 : &create_req.shard_parameters,
2207 0 : create_req.config.clone(),
2208 0 : placement_policy.clone(),
2209 0 : preferred_az_id.as_ref(),
2210 0 : &mut schedule_context,
2211 0 : )
2212 0 : .await;
2213 :
2214 0 : match outcome {
2215 0 : InitialShardScheduleOutcome::Scheduled(resp) => response_shards.push(resp),
2216 0 : InitialShardScheduleOutcome::NotScheduled => {}
2217 0 : InitialShardScheduleOutcome::ShardScheduleError(err) => {
2218 0 : schedule_error = Some(err);
2219 0 : }
2220 : }
2221 : }
2222 :
2223 : // If we failed to schedule shards, then they are still created in the controller,
2224 : // but we return an error to the requester to avoid a silent failure when someone
2225 : // tries to e.g. create a tenant whose placement policy requires more nodes than
2226 : // are present in the system. We do this here rather than in the above loop, to
2227 : // avoid situations where we only create a subset of shards in the tenant.
2228 0 : if let Some(e) = schedule_error {
2229 0 : return Err(ApiError::Conflict(format!(
2230 0 : "Failed to schedule shard(s): {e}"
2231 0 : )));
2232 0 : }
2233 0 :
2234 0 : let waiters = {
2235 0 : let mut locked = self.inner.write().unwrap();
2236 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2237 0 : tenants
2238 0 : .range_mut(TenantShardId::tenant_range(tenant_id))
2239 0 : .filter_map(|(_shard_id, shard)| self.maybe_reconcile_shard(shard, nodes))
2240 0 : .collect::<Vec<_>>()
2241 0 : };
2242 0 :
2243 0 : Ok((
2244 0 : TenantCreateResponse {
2245 0 : shards: response_shards,
2246 0 : },
2247 0 : waiters,
2248 0 : ))
2249 0 : }
2250 :
2251 : /// Helper for tenant creation that does the scheduling for an individual shard. Covers both the
2252 : /// case of a new tenant and a pre-existing one.
2253 : #[allow(clippy::too_many_arguments)]
2254 0 : async fn do_initial_shard_scheduling(
2255 0 : &self,
2256 0 : tenant_shard_id: TenantShardId,
2257 0 : initial_generation: Option<Generation>,
2258 0 : shard_params: &ShardParameters,
2259 0 : config: TenantConfig,
2260 0 : placement_policy: PlacementPolicy,
2261 0 : preferred_az_id: Option<&AvailabilityZone>,
2262 0 : schedule_context: &mut ScheduleContext,
2263 0 : ) -> InitialShardScheduleOutcome {
2264 0 : let mut locked = self.inner.write().unwrap();
2265 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
2266 :
2267 : use std::collections::btree_map::Entry;
2268 0 : match tenants.entry(tenant_shard_id) {
2269 0 : Entry::Occupied(mut entry) => {
2270 0 : tracing::info!("Tenant shard {tenant_shard_id} already exists while creating");
2271 :
2272 0 : if let Err(err) = entry.get_mut().schedule(scheduler, schedule_context) {
2273 0 : return InitialShardScheduleOutcome::ShardScheduleError(err);
2274 0 : }
2275 :
2276 0 : if let Some(node_id) = entry.get().intent.get_attached() {
2277 0 : let generation = entry
2278 0 : .get()
2279 0 : .generation
2280 0 : .expect("Generation is set when in attached mode");
2281 0 : InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
2282 0 : shard_id: tenant_shard_id,
2283 0 : node_id: *node_id,
2284 0 : generation: generation.into().unwrap(),
2285 0 : })
2286 : } else {
2287 0 : InitialShardScheduleOutcome::NotScheduled
2288 : }
2289 : }
2290 0 : Entry::Vacant(entry) => {
2291 0 : let state = entry.insert(TenantShard::new(
2292 0 : tenant_shard_id,
2293 0 : ShardIdentity::from_params(tenant_shard_id.shard_number, shard_params),
2294 0 : placement_policy,
2295 0 : preferred_az_id.cloned(),
2296 0 : ));
2297 0 :
2298 0 : state.generation = initial_generation;
2299 0 : state.config = config;
2300 0 : if let Err(e) = state.schedule(scheduler, schedule_context) {
2301 0 : return InitialShardScheduleOutcome::ShardScheduleError(e);
2302 0 : }
2303 :
2304 : // Only include shards in result if we are attaching: the purpose
2305 : // of the response is to tell the caller where the shards are attached.
2306 0 : if let Some(node_id) = state.intent.get_attached() {
2307 0 : let generation = state
2308 0 : .generation
2309 0 : .expect("Generation is set when in attached mode");
2310 0 : InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
2311 0 : shard_id: tenant_shard_id,
2312 0 : node_id: *node_id,
2313 0 : generation: generation.into().unwrap(),
2314 0 : })
2315 : } else {
2316 0 : InitialShardScheduleOutcome::NotScheduled
2317 : }
2318 : }
2319 : }
2320 0 : }
2321 :
2322 : /// Helper for functions that reconcile a number of shards, and would like to do a timeout-bounded
2323 : /// wait for reconciliation to complete before responding.
2324 0 : async fn await_waiters(
2325 0 : &self,
2326 0 : waiters: Vec<ReconcilerWaiter>,
2327 0 : timeout: Duration,
2328 0 : ) -> Result<(), ReconcileWaitError> {
2329 0 : let deadline = Instant::now().checked_add(timeout).unwrap();
2330 0 : for waiter in waiters {
2331 0 : let timeout = deadline.duration_since(Instant::now());
2332 0 : waiter.wait_timeout(timeout).await?;
2333 : }
2334 :
2335 0 : Ok(())
2336 0 : }
2337 :
2338 : /// Same as [`Service::await_waiters`], but returns the waiters which are still
2339 : /// in progress
2340 0 : async fn await_waiters_remainder(
2341 0 : &self,
2342 0 : waiters: Vec<ReconcilerWaiter>,
2343 0 : timeout: Duration,
2344 0 : ) -> Vec<ReconcilerWaiter> {
2345 0 : let deadline = Instant::now().checked_add(timeout).unwrap();
2346 0 : for waiter in waiters.iter() {
2347 0 : let timeout = deadline.duration_since(Instant::now());
2348 0 : let _ = waiter.wait_timeout(timeout).await;
2349 : }
2350 :
2351 0 : waiters
2352 0 : .into_iter()
2353 0 : .filter(|waiter| matches!(waiter.get_status(), ReconcilerStatus::InProgress))
2354 0 : .collect::<Vec<_>>()
2355 0 : }
2356 :
2357 : /// Part of [`Self::tenant_location_config`]: dissect an incoming location config request,
2358 : /// and transform it into either a tenant creation of a series of shard updates.
2359 : ///
2360 : /// If the incoming request makes no changes, a [`TenantCreateOrUpdate::Update`] result will
2361 : /// still be returned.
2362 0 : fn tenant_location_config_prepare(
2363 0 : &self,
2364 0 : tenant_id: TenantId,
2365 0 : req: TenantLocationConfigRequest,
2366 0 : ) -> TenantCreateOrUpdate {
2367 0 : let mut updates = Vec::new();
2368 0 : let mut locked = self.inner.write().unwrap();
2369 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2370 0 : let tenant_shard_id = TenantShardId::unsharded(tenant_id);
2371 :
2372 : // Use location config mode as an indicator of policy.
2373 0 : let placement_policy = match req.config.mode {
2374 0 : LocationConfigMode::Detached => PlacementPolicy::Detached,
2375 0 : LocationConfigMode::Secondary => PlacementPolicy::Secondary,
2376 : LocationConfigMode::AttachedMulti
2377 : | LocationConfigMode::AttachedSingle
2378 : | LocationConfigMode::AttachedStale => {
2379 0 : if nodes.len() > 1 {
2380 0 : PlacementPolicy::Attached(1)
2381 : } else {
2382 : // Convenience for dev/test: if we just have one pageserver, import
2383 : // tenants into non-HA mode so that scheduling will succeed.
2384 0 : PlacementPolicy::Attached(0)
2385 : }
2386 : }
2387 : };
2388 :
2389 : // Ordinarily we do not update scheduling policy, but when making major changes
2390 : // like detaching or demoting to secondary-only, we need to force the scheduling
2391 : // mode to Active, or the caller's expected outcome (detach it) will not happen.
2392 0 : let scheduling_policy = match req.config.mode {
2393 : LocationConfigMode::Detached | LocationConfigMode::Secondary => {
2394 : // Special case: when making major changes like detaching or demoting to secondary-only,
2395 : // we need to force the scheduling mode to Active, or nothing will happen.
2396 0 : Some(ShardSchedulingPolicy::Active)
2397 : }
2398 : LocationConfigMode::AttachedMulti
2399 : | LocationConfigMode::AttachedSingle
2400 : | LocationConfigMode::AttachedStale => {
2401 : // While attached, continue to respect whatever the existing scheduling mode is.
2402 0 : None
2403 : }
2404 : };
2405 :
2406 0 : let mut create = true;
2407 0 : for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
2408 : // Saw an existing shard: this is not a creation
2409 0 : create = false;
2410 :
2411 : // Shards may have initially been created by a Secondary request, where we
2412 : // would have left generation as None.
2413 : //
2414 : // We only update generation the first time we see an attached-mode request,
2415 : // and if there is no existing generation set. The caller is responsible for
2416 : // ensuring that no non-storage-controller pageserver ever uses a higher
2417 : // generation than they passed in here.
2418 : use LocationConfigMode::*;
2419 0 : let set_generation = match req.config.mode {
2420 0 : AttachedMulti | AttachedSingle | AttachedStale if shard.generation.is_none() => {
2421 0 : req.config.generation.map(Generation::new)
2422 : }
2423 0 : _ => None,
2424 : };
2425 :
2426 0 : updates.push(ShardUpdate {
2427 0 : tenant_shard_id: *shard_id,
2428 0 : placement_policy: placement_policy.clone(),
2429 0 : tenant_config: req.config.tenant_conf.clone(),
2430 0 : generation: set_generation,
2431 0 : scheduling_policy,
2432 0 : });
2433 : }
2434 :
2435 0 : if create {
2436 : use LocationConfigMode::*;
2437 0 : let generation = match req.config.mode {
2438 0 : AttachedMulti | AttachedSingle | AttachedStale => req.config.generation,
2439 : // If a caller provided a generation in a non-attached request, ignore it
2440 : // and leave our generation as None: this enables a subsequent update to set
2441 : // the generation when setting an attached mode for the first time.
2442 0 : _ => None,
2443 : };
2444 :
2445 0 : TenantCreateOrUpdate::Create(
2446 0 : // Synthesize a creation request
2447 0 : TenantCreateRequest {
2448 0 : new_tenant_id: tenant_shard_id,
2449 0 : generation,
2450 0 : shard_parameters: ShardParameters {
2451 0 : count: tenant_shard_id.shard_count,
2452 0 : // We only import un-sharded or single-sharded tenants, so stripe
2453 0 : // size can be made up arbitrarily here.
2454 0 : stripe_size: ShardParameters::DEFAULT_STRIPE_SIZE,
2455 0 : },
2456 0 : placement_policy: Some(placement_policy),
2457 0 : config: req.config.tenant_conf,
2458 0 : },
2459 0 : )
2460 : } else {
2461 0 : assert!(!updates.is_empty());
2462 0 : TenantCreateOrUpdate::Update(updates)
2463 : }
2464 0 : }
2465 :
2466 : /// For APIs that might act on tenants with [`PlacementPolicy::Detached`], first check if
2467 : /// the tenant is present in memory. If not, load it from the database. If it is found
2468 : /// in neither location, return a NotFound error.
2469 : ///
2470 : /// Caller must demonstrate they hold a lock guard, as otherwise two callers might try and load
2471 : /// it at the same time, or we might race with [`Self::maybe_drop_tenant`]
2472 0 : async fn maybe_load_tenant(
2473 0 : &self,
2474 0 : tenant_id: TenantId,
2475 0 : _guard: &TracingExclusiveGuard<TenantOperations>,
2476 0 : ) -> Result<(), ApiError> {
2477 0 : let present_in_memory = {
2478 0 : let locked = self.inner.read().unwrap();
2479 0 : locked
2480 0 : .tenants
2481 0 : .range(TenantShardId::tenant_range(tenant_id))
2482 0 : .next()
2483 0 : .is_some()
2484 0 : };
2485 0 :
2486 0 : if present_in_memory {
2487 0 : return Ok(());
2488 0 : }
2489 :
2490 0 : let tenant_shards = self.persistence.load_tenant(tenant_id).await?;
2491 0 : if tenant_shards.is_empty() {
2492 0 : return Err(ApiError::NotFound(
2493 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
2494 0 : ));
2495 0 : }
2496 0 :
2497 0 : // TODO: choose a fresh AZ to use for this tenant when un-detaching: there definitely isn't a running
2498 0 : // compute, so no benefit to making AZ sticky across detaches.
2499 0 :
2500 0 : let mut locked = self.inner.write().unwrap();
2501 0 : tracing::info!(
2502 0 : "Loaded {} shards for tenant {}",
2503 0 : tenant_shards.len(),
2504 : tenant_id
2505 : );
2506 :
2507 0 : locked.tenants.extend(tenant_shards.into_iter().map(|p| {
2508 0 : let intent = IntentState::new();
2509 0 : let shard =
2510 0 : TenantShard::from_persistent(p, intent).expect("Corrupt shard row in database");
2511 0 :
2512 0 : // Sanity check: when loading on-demand, we should always be loaded something Detached
2513 0 : debug_assert!(shard.policy == PlacementPolicy::Detached);
2514 0 : if shard.policy != PlacementPolicy::Detached {
2515 0 : tracing::error!(
2516 0 : "Tenant shard {} loaded on-demand, but has non-Detached policy {:?}",
2517 : shard.tenant_shard_id,
2518 : shard.policy
2519 : );
2520 0 : }
2521 :
2522 0 : (shard.tenant_shard_id, shard)
2523 0 : }));
2524 0 :
2525 0 : Ok(())
2526 0 : }
2527 :
2528 : /// If all shards for a tenant are detached, and in a fully quiescent state (no observed locations on pageservers),
2529 : /// and have no reconciler running, then we can drop the tenant from memory. It will be reloaded on-demand
2530 : /// if we are asked to attach it again (see [`Self::maybe_load_tenant`]).
2531 : ///
2532 : /// Caller must demonstrate they hold a lock guard, as otherwise it is unsafe to drop a tenant from
2533 : /// memory while some other function might assume it continues to exist while not holding the lock on Self::inner.
2534 0 : fn maybe_drop_tenant(
2535 0 : &self,
2536 0 : tenant_id: TenantId,
2537 0 : locked: &mut std::sync::RwLockWriteGuard<ServiceState>,
2538 0 : _guard: &TracingExclusiveGuard<TenantOperations>,
2539 0 : ) {
2540 0 : let mut tenant_shards = locked.tenants.range(TenantShardId::tenant_range(tenant_id));
2541 0 : if tenant_shards.all(|(_id, shard)| {
2542 0 : shard.policy == PlacementPolicy::Detached
2543 0 : && shard.reconciler.is_none()
2544 0 : && shard.observed.is_empty()
2545 0 : }) {
2546 0 : let keys = locked
2547 0 : .tenants
2548 0 : .range(TenantShardId::tenant_range(tenant_id))
2549 0 : .map(|(id, _)| id)
2550 0 : .copied()
2551 0 : .collect::<Vec<_>>();
2552 0 : for key in keys {
2553 0 : tracing::info!("Dropping detached tenant shard {} from memory", key);
2554 0 : locked.tenants.remove(&key);
2555 : }
2556 0 : }
2557 0 : }
2558 :
2559 : /// This API is used by the cloud control plane to migrate unsharded tenants that it created
2560 : /// directly with pageservers into this service.
2561 : ///
2562 : /// Cloud control plane MUST NOT continue issuing GENERATION NUMBERS for this tenant once it
2563 : /// has attempted to call this API. Failure to oblige to this rule may lead to S3 corruption.
2564 : /// Think of the first attempt to call this API as a transfer of absolute authority over the
2565 : /// tenant's source of generation numbers.
2566 : ///
2567 : /// The mode in this request coarse-grained control of tenants:
2568 : /// - Call with mode Attached* to upsert the tenant.
2569 : /// - Call with mode Secondary to either onboard a tenant without attaching it, or
2570 : /// to set an existing tenant to PolicyMode::Secondary
2571 : /// - Call with mode Detached to switch to PolicyMode::Detached
2572 0 : pub(crate) async fn tenant_location_config(
2573 0 : &self,
2574 0 : tenant_shard_id: TenantShardId,
2575 0 : req: TenantLocationConfigRequest,
2576 0 : ) -> Result<TenantLocationConfigResponse, ApiError> {
2577 : // We require an exclusive lock, because we are updating both persistent and in-memory state
2578 0 : let _tenant_lock = trace_exclusive_lock(
2579 0 : &self.tenant_op_locks,
2580 0 : tenant_shard_id.tenant_id,
2581 0 : TenantOperations::LocationConfig,
2582 0 : )
2583 0 : .await;
2584 :
2585 0 : let tenant_id = if !tenant_shard_id.is_unsharded() {
2586 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
2587 0 : "This API is for importing single-sharded or unsharded tenants"
2588 0 : )));
2589 : } else {
2590 0 : tenant_shard_id.tenant_id
2591 0 : };
2592 0 :
2593 0 : // In case we are waking up a Detached tenant
2594 0 : match self.maybe_load_tenant(tenant_id, &_tenant_lock).await {
2595 0 : Ok(()) | Err(ApiError::NotFound(_)) => {
2596 0 : // This is a creation or an update
2597 0 : }
2598 0 : Err(e) => {
2599 0 : return Err(e);
2600 : }
2601 : };
2602 :
2603 : // First check if this is a creation or an update
2604 0 : let create_or_update = self.tenant_location_config_prepare(tenant_id, req);
2605 0 :
2606 0 : let mut result = TenantLocationConfigResponse {
2607 0 : shards: Vec::new(),
2608 0 : stripe_size: None,
2609 0 : };
2610 0 : let waiters = match create_or_update {
2611 0 : TenantCreateOrUpdate::Create(create_req) => {
2612 0 : let (create_resp, waiters) = self.do_tenant_create(create_req).await?;
2613 0 : result.shards = create_resp
2614 0 : .shards
2615 0 : .into_iter()
2616 0 : .map(|s| TenantShardLocation {
2617 0 : node_id: s.node_id,
2618 0 : shard_id: s.shard_id,
2619 0 : })
2620 0 : .collect();
2621 0 : waiters
2622 : }
2623 0 : TenantCreateOrUpdate::Update(updates) => {
2624 0 : // Persist updates
2625 0 : // Ordering: write to the database before applying changes in-memory, so that
2626 0 : // we will not appear time-travel backwards on a restart.
2627 0 :
2628 0 : let mut schedule_context = ScheduleContext::default();
2629 : for ShardUpdate {
2630 0 : tenant_shard_id,
2631 0 : placement_policy,
2632 0 : tenant_config,
2633 0 : generation,
2634 0 : scheduling_policy,
2635 0 : } in &updates
2636 : {
2637 0 : self.persistence
2638 0 : .update_tenant_shard(
2639 0 : TenantFilter::Shard(*tenant_shard_id),
2640 0 : Some(placement_policy.clone()),
2641 0 : Some(tenant_config.clone()),
2642 0 : *generation,
2643 0 : *scheduling_policy,
2644 0 : )
2645 0 : .await?;
2646 : }
2647 :
2648 : // Apply updates in-memory
2649 0 : let mut waiters = Vec::new();
2650 0 : {
2651 0 : let mut locked = self.inner.write().unwrap();
2652 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
2653 :
2654 : for ShardUpdate {
2655 0 : tenant_shard_id,
2656 0 : placement_policy,
2657 0 : tenant_config,
2658 0 : generation: update_generation,
2659 0 : scheduling_policy,
2660 0 : } in updates
2661 : {
2662 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
2663 0 : tracing::warn!("Shard {tenant_shard_id} removed while updating");
2664 0 : continue;
2665 : };
2666 :
2667 : // Update stripe size
2668 0 : if result.stripe_size.is_none() && shard.shard.count.count() > 1 {
2669 0 : result.stripe_size = Some(shard.shard.stripe_size);
2670 0 : }
2671 :
2672 0 : shard.policy = placement_policy;
2673 0 : shard.config = tenant_config;
2674 0 : if let Some(generation) = update_generation {
2675 0 : shard.generation = Some(generation);
2676 0 : }
2677 :
2678 0 : if let Some(scheduling_policy) = scheduling_policy {
2679 0 : shard.set_scheduling_policy(scheduling_policy);
2680 0 : }
2681 :
2682 0 : shard.schedule(scheduler, &mut schedule_context)?;
2683 :
2684 0 : let maybe_waiter = self.maybe_reconcile_shard(shard, nodes);
2685 0 : if let Some(waiter) = maybe_waiter {
2686 0 : waiters.push(waiter);
2687 0 : }
2688 :
2689 0 : if let Some(node_id) = shard.intent.get_attached() {
2690 0 : result.shards.push(TenantShardLocation {
2691 0 : shard_id: tenant_shard_id,
2692 0 : node_id: *node_id,
2693 0 : })
2694 0 : }
2695 : }
2696 : }
2697 0 : waiters
2698 : }
2699 : };
2700 :
2701 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
2702 : // Do not treat a reconcile error as fatal: we have already applied any requested
2703 : // Intent changes, and the reconcile can fail for external reasons like unavailable
2704 : // compute notification API. In these cases, it is important that we do not
2705 : // cause the cloud control plane to retry forever on this API.
2706 0 : tracing::warn!(
2707 0 : "Failed to reconcile after /location_config: {e}, returning success anyway"
2708 : );
2709 0 : }
2710 :
2711 : // Logging the full result is useful because it lets us cross-check what the cloud control
2712 : // plane's tenant_shards table should contain.
2713 0 : tracing::info!("Complete, returning {result:?}");
2714 :
2715 0 : Ok(result)
2716 0 : }
2717 :
2718 0 : pub(crate) async fn tenant_config_patch(
2719 0 : &self,
2720 0 : req: TenantConfigPatchRequest,
2721 0 : ) -> Result<(), ApiError> {
2722 0 : let _tenant_lock = trace_exclusive_lock(
2723 0 : &self.tenant_op_locks,
2724 0 : req.tenant_id,
2725 0 : TenantOperations::ConfigPatch,
2726 0 : )
2727 0 : .await;
2728 :
2729 0 : let tenant_id = req.tenant_id;
2730 0 : let patch = req.config;
2731 0 :
2732 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
2733 :
2734 0 : let base = {
2735 0 : let locked = self.inner.read().unwrap();
2736 0 : let shards = locked
2737 0 : .tenants
2738 0 : .range(TenantShardId::tenant_range(req.tenant_id));
2739 0 :
2740 0 : let mut configs = shards.map(|(_sid, shard)| &shard.config).peekable();
2741 :
2742 0 : let first = match configs.peek() {
2743 0 : Some(first) => (*first).clone(),
2744 : None => {
2745 0 : return Err(ApiError::NotFound(
2746 0 : anyhow::anyhow!("Tenant {} not found", req.tenant_id).into(),
2747 0 : ));
2748 : }
2749 : };
2750 :
2751 0 : if !configs.all_equal() {
2752 0 : tracing::error!("Tenant configs for {} are mismatched. ", req.tenant_id);
2753 : // This can't happen because we atomically update the database records
2754 : // of all shards to the new value in [`Self::set_tenant_config_and_reconcile`].
2755 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
2756 0 : "Tenant configs for {} are mismatched",
2757 0 : req.tenant_id
2758 0 : )));
2759 0 : }
2760 0 :
2761 0 : first
2762 0 : };
2763 0 :
2764 0 : let updated_config = base.apply_patch(patch);
2765 0 : self.set_tenant_config_and_reconcile(tenant_id, updated_config)
2766 0 : .await
2767 0 : }
2768 :
2769 0 : pub(crate) async fn tenant_config_set(&self, req: TenantConfigRequest) -> Result<(), ApiError> {
2770 : // We require an exclusive lock, because we are updating persistent and in-memory state
2771 0 : let _tenant_lock = trace_exclusive_lock(
2772 0 : &self.tenant_op_locks,
2773 0 : req.tenant_id,
2774 0 : TenantOperations::ConfigSet,
2775 0 : )
2776 0 : .await;
2777 :
2778 0 : self.maybe_load_tenant(req.tenant_id, &_tenant_lock).await?;
2779 :
2780 0 : self.set_tenant_config_and_reconcile(req.tenant_id, req.config)
2781 0 : .await
2782 0 : }
2783 :
2784 0 : async fn set_tenant_config_and_reconcile(
2785 0 : &self,
2786 0 : tenant_id: TenantId,
2787 0 : config: TenantConfig,
2788 0 : ) -> Result<(), ApiError> {
2789 0 : self.persistence
2790 0 : .update_tenant_shard(
2791 0 : TenantFilter::Tenant(tenant_id),
2792 0 : None,
2793 0 : Some(config.clone()),
2794 0 : None,
2795 0 : None,
2796 0 : )
2797 0 : .await?;
2798 :
2799 0 : let waiters = {
2800 0 : let mut waiters = Vec::new();
2801 0 : let mut locked = self.inner.write().unwrap();
2802 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2803 0 : for (_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
2804 0 : shard.config = config.clone();
2805 0 : if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
2806 0 : waiters.push(waiter);
2807 0 : }
2808 : }
2809 0 : waiters
2810 : };
2811 :
2812 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
2813 : // Treat this as success because we have stored the configuration. If e.g.
2814 : // a node was unavailable at this time, it should not stop us accepting a
2815 : // configuration change.
2816 0 : tracing::warn!(%tenant_id, "Accepted configuration update but reconciliation failed: {e}");
2817 0 : }
2818 :
2819 0 : Ok(())
2820 0 : }
2821 :
2822 0 : pub(crate) fn tenant_config_get(
2823 0 : &self,
2824 0 : tenant_id: TenantId,
2825 0 : ) -> Result<HashMap<&str, serde_json::Value>, ApiError> {
2826 0 : let config = {
2827 0 : let locked = self.inner.read().unwrap();
2828 0 :
2829 0 : match locked
2830 0 : .tenants
2831 0 : .range(TenantShardId::tenant_range(tenant_id))
2832 0 : .next()
2833 : {
2834 0 : Some((_tenant_shard_id, shard)) => shard.config.clone(),
2835 : None => {
2836 0 : return Err(ApiError::NotFound(
2837 0 : anyhow::anyhow!("Tenant not found").into(),
2838 0 : ))
2839 : }
2840 : }
2841 : };
2842 :
2843 : // Unlike the pageserver, we do not have a set of global defaults: the config is
2844 : // entirely per-tenant. Therefore the distinction between `tenant_specific_overrides`
2845 : // and `effective_config` in the response is meaningless, but we retain that syntax
2846 : // in order to remain compatible with the pageserver API.
2847 :
2848 0 : let response = HashMap::from([
2849 : (
2850 : "tenant_specific_overrides",
2851 0 : serde_json::to_value(&config)
2852 0 : .context("serializing tenant specific overrides")
2853 0 : .map_err(ApiError::InternalServerError)?,
2854 : ),
2855 : (
2856 0 : "effective_config",
2857 0 : serde_json::to_value(&config)
2858 0 : .context("serializing effective config")
2859 0 : .map_err(ApiError::InternalServerError)?,
2860 : ),
2861 : ]);
2862 :
2863 0 : Ok(response)
2864 0 : }
2865 :
2866 0 : pub(crate) async fn tenant_time_travel_remote_storage(
2867 0 : &self,
2868 0 : time_travel_req: &TenantTimeTravelRequest,
2869 0 : tenant_id: TenantId,
2870 0 : timestamp: Cow<'_, str>,
2871 0 : done_if_after: Cow<'_, str>,
2872 0 : ) -> Result<(), ApiError> {
2873 0 : let _tenant_lock = trace_exclusive_lock(
2874 0 : &self.tenant_op_locks,
2875 0 : tenant_id,
2876 0 : TenantOperations::TimeTravelRemoteStorage,
2877 0 : )
2878 0 : .await;
2879 :
2880 0 : let node = {
2881 0 : let mut locked = self.inner.write().unwrap();
2882 : // Just a sanity check to prevent misuse: the API expects that the tenant is fully
2883 : // detached everywhere, and nothing writes to S3 storage. Here, we verify that,
2884 : // but only at the start of the process, so it's really just to prevent operator
2885 : // mistakes.
2886 0 : for (shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
2887 0 : if shard.intent.get_attached().is_some() || !shard.intent.get_secondary().is_empty()
2888 : {
2889 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
2890 0 : "We want tenant to be attached in shard with tenant_shard_id={shard_id}"
2891 0 : )));
2892 0 : }
2893 0 : let maybe_attached = shard
2894 0 : .observed
2895 0 : .locations
2896 0 : .iter()
2897 0 : .filter_map(|(node_id, observed_location)| {
2898 0 : observed_location
2899 0 : .conf
2900 0 : .as_ref()
2901 0 : .map(|loc| (node_id, observed_location, loc.mode))
2902 0 : })
2903 0 : .find(|(_, _, mode)| *mode != LocationConfigMode::Detached);
2904 0 : if let Some((node_id, _observed_location, mode)) = maybe_attached {
2905 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!("We observed attached={mode:?} tenant in node_id={node_id} shard with tenant_shard_id={shard_id}")));
2906 0 : }
2907 : }
2908 0 : let scheduler = &mut locked.scheduler;
2909 : // Right now we only perform the operation on a single node without parallelization
2910 : // TODO fan out the operation to multiple nodes for better performance
2911 0 : let node_id = scheduler.any_available_node()?;
2912 0 : let node = locked
2913 0 : .nodes
2914 0 : .get(&node_id)
2915 0 : .expect("Pageservers may not be deleted while lock is active");
2916 0 : node.clone()
2917 0 : };
2918 0 :
2919 0 : // The shard count is encoded in the remote storage's URL, so we need to handle all historically used shard counts
2920 0 : let mut counts = time_travel_req
2921 0 : .shard_counts
2922 0 : .iter()
2923 0 : .copied()
2924 0 : .collect::<HashSet<_>>()
2925 0 : .into_iter()
2926 0 : .collect::<Vec<_>>();
2927 0 : counts.sort_unstable();
2928 :
2929 0 : for count in counts {
2930 0 : let shard_ids = (0..count.count())
2931 0 : .map(|i| TenantShardId {
2932 0 : tenant_id,
2933 0 : shard_number: ShardNumber(i),
2934 0 : shard_count: count,
2935 0 : })
2936 0 : .collect::<Vec<_>>();
2937 0 : for tenant_shard_id in shard_ids {
2938 0 : let client = PageserverClient::new(
2939 0 : node.get_id(),
2940 0 : node.base_url(),
2941 0 : self.config.jwt_token.as_deref(),
2942 0 : );
2943 0 :
2944 0 : tracing::info!("Doing time travel recovery for shard {tenant_shard_id}",);
2945 :
2946 0 : client
2947 0 : .tenant_time_travel_remote_storage(
2948 0 : tenant_shard_id,
2949 0 : ×tamp,
2950 0 : &done_if_after,
2951 0 : )
2952 0 : .await
2953 0 : .map_err(|e| {
2954 0 : ApiError::InternalServerError(anyhow::anyhow!(
2955 0 : "Error doing time travel recovery for shard {tenant_shard_id} on node {}: {e}",
2956 0 : node
2957 0 : ))
2958 0 : })?;
2959 : }
2960 : }
2961 0 : Ok(())
2962 0 : }
2963 :
2964 0 : pub(crate) async fn tenant_secondary_download(
2965 0 : &self,
2966 0 : tenant_id: TenantId,
2967 0 : wait: Option<Duration>,
2968 0 : ) -> Result<(StatusCode, SecondaryProgress), ApiError> {
2969 0 : let _tenant_lock = trace_shared_lock(
2970 0 : &self.tenant_op_locks,
2971 0 : tenant_id,
2972 0 : TenantOperations::SecondaryDownload,
2973 0 : )
2974 0 : .await;
2975 :
2976 : // Acquire lock and yield the collection of shard-node tuples which we will send requests onward to
2977 0 : let targets = {
2978 0 : let locked = self.inner.read().unwrap();
2979 0 : let mut targets = Vec::new();
2980 :
2981 0 : for (tenant_shard_id, shard) in
2982 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
2983 : {
2984 0 : for node_id in shard.intent.get_secondary() {
2985 0 : let node = locked
2986 0 : .nodes
2987 0 : .get(node_id)
2988 0 : .expect("Pageservers may not be deleted while referenced");
2989 0 :
2990 0 : targets.push((*tenant_shard_id, node.clone()));
2991 0 : }
2992 : }
2993 0 : targets
2994 0 : };
2995 0 :
2996 0 : // Issue concurrent requests to all shards' locations
2997 0 : let mut futs = FuturesUnordered::new();
2998 0 : for (tenant_shard_id, node) in targets {
2999 0 : let client = PageserverClient::new(
3000 0 : node.get_id(),
3001 0 : node.base_url(),
3002 0 : self.config.jwt_token.as_deref(),
3003 0 : );
3004 0 : futs.push(async move {
3005 0 : let result = client
3006 0 : .tenant_secondary_download(tenant_shard_id, wait)
3007 0 : .await;
3008 0 : (result, node, tenant_shard_id)
3009 0 : })
3010 : }
3011 :
3012 : // Handle any errors returned by pageservers. This includes cases like this request racing with
3013 : // a scheduling operation, such that the tenant shard we're calling doesn't exist on that pageserver any more, as
3014 : // well as more general cases like 503s, 500s, or timeouts.
3015 0 : let mut aggregate_progress = SecondaryProgress::default();
3016 0 : let mut aggregate_status: Option<StatusCode> = None;
3017 0 : let mut error: Option<mgmt_api::Error> = None;
3018 0 : while let Some((result, node, tenant_shard_id)) = futs.next().await {
3019 0 : match result {
3020 0 : Err(e) => {
3021 0 : // Secondary downloads are always advisory: if something fails, we nevertheless report success, so that whoever
3022 0 : // is calling us will proceed with whatever migration they're doing, albeit with a slightly less warm cache
3023 0 : // than they had hoped for.
3024 0 : tracing::warn!("Secondary download error from pageserver {node}: {e}",);
3025 0 : error = Some(e)
3026 : }
3027 0 : Ok((status_code, progress)) => {
3028 0 : tracing::info!(%tenant_shard_id, "Shard status={status_code} progress: {progress:?}");
3029 0 : aggregate_progress.layers_downloaded += progress.layers_downloaded;
3030 0 : aggregate_progress.layers_total += progress.layers_total;
3031 0 : aggregate_progress.bytes_downloaded += progress.bytes_downloaded;
3032 0 : aggregate_progress.bytes_total += progress.bytes_total;
3033 0 : aggregate_progress.heatmap_mtime =
3034 0 : std::cmp::max(aggregate_progress.heatmap_mtime, progress.heatmap_mtime);
3035 0 : aggregate_status = match aggregate_status {
3036 0 : None => Some(status_code),
3037 0 : Some(StatusCode::OK) => Some(status_code),
3038 0 : Some(cur) => {
3039 0 : // Other status codes (e.g. 202) -- do not overwrite.
3040 0 : Some(cur)
3041 : }
3042 : };
3043 : }
3044 : }
3045 : }
3046 :
3047 : // If any of the shards return 202, indicate our result as 202.
3048 0 : match aggregate_status {
3049 : None => {
3050 0 : match error {
3051 0 : Some(e) => {
3052 0 : // No successes, and an error: surface it
3053 0 : Err(ApiError::Conflict(format!("Error from pageserver: {e}")))
3054 : }
3055 : None => {
3056 : // No shards found
3057 0 : Err(ApiError::NotFound(
3058 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
3059 0 : ))
3060 : }
3061 : }
3062 : }
3063 0 : Some(aggregate_status) => Ok((aggregate_status, aggregate_progress)),
3064 : }
3065 0 : }
3066 :
3067 0 : pub(crate) async fn tenant_delete(&self, tenant_id: TenantId) -> Result<StatusCode, ApiError> {
3068 0 : let _tenant_lock =
3069 0 : trace_exclusive_lock(&self.tenant_op_locks, tenant_id, TenantOperations::Delete).await;
3070 :
3071 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3072 :
3073 : // Detach all shards. This also deletes local pageserver shard data.
3074 0 : let (detach_waiters, node) = {
3075 0 : let mut detach_waiters = Vec::new();
3076 0 : let mut locked = self.inner.write().unwrap();
3077 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3078 0 : for (_, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3079 : // Update the tenant's intent to remove all attachments
3080 0 : shard.policy = PlacementPolicy::Detached;
3081 0 : shard
3082 0 : .schedule(scheduler, &mut ScheduleContext::default())
3083 0 : .expect("De-scheduling is infallible");
3084 0 : debug_assert!(shard.intent.get_attached().is_none());
3085 0 : debug_assert!(shard.intent.get_secondary().is_empty());
3086 :
3087 0 : if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
3088 0 : detach_waiters.push(waiter);
3089 0 : }
3090 : }
3091 :
3092 : // Pick an arbitrary node to use for remote deletions (does not have to be where the tenant
3093 : // was attached, just has to be able to see the S3 content)
3094 0 : let node_id = scheduler.any_available_node()?;
3095 0 : let node = nodes
3096 0 : .get(&node_id)
3097 0 : .expect("Pageservers may not be deleted while lock is active");
3098 0 : (detach_waiters, node.clone())
3099 0 : };
3100 0 :
3101 0 : // This reconcile wait can fail in a few ways:
3102 0 : // A there is a very long queue for the reconciler semaphore
3103 0 : // B some pageserver is failing to handle a detach promptly
3104 0 : // C some pageserver goes offline right at the moment we send it a request.
3105 0 : //
3106 0 : // A and C are transient: the semaphore will eventually become available, and once a node is marked offline
3107 0 : // the next attempt to reconcile will silently skip detaches for an offline node and succeed. If B happens,
3108 0 : // it's a bug, and needs resolving at the pageserver level (we shouldn't just leave attachments behind while
3109 0 : // deleting the underlying data).
3110 0 : self.await_waiters(detach_waiters, RECONCILE_TIMEOUT)
3111 0 : .await?;
3112 :
3113 : // Delete the entire tenant (all shards) from remote storage via a random pageserver.
3114 : // Passing an unsharded tenant ID will cause the pageserver to remove all remote paths with
3115 : // the tenant ID prefix, including all shards (even possibly stale ones).
3116 0 : match node
3117 0 : .with_client_retries(
3118 0 : |client| async move {
3119 0 : client
3120 0 : .tenant_delete(TenantShardId::unsharded(tenant_id))
3121 0 : .await
3122 0 : },
3123 0 : &self.config.jwt_token,
3124 0 : 1,
3125 0 : 3,
3126 0 : RECONCILE_TIMEOUT,
3127 0 : &self.cancel,
3128 0 : )
3129 0 : .await
3130 0 : .unwrap_or(Err(mgmt_api::Error::Cancelled))
3131 : {
3132 0 : Ok(_) => {}
3133 : Err(mgmt_api::Error::Cancelled) => {
3134 0 : return Err(ApiError::ShuttingDown);
3135 : }
3136 0 : Err(e) => {
3137 0 : // This is unexpected: remote deletion should be infallible, unless the object store
3138 0 : // at large is unavailable.
3139 0 : tracing::error!("Error deleting via node {node}: {e}");
3140 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
3141 : }
3142 : }
3143 :
3144 : // Fall through: deletion of the tenant on pageservers is complete, we may proceed to drop
3145 : // our in-memory state and database state.
3146 :
3147 : // Ordering: we delete persistent state first: if we then
3148 : // crash, we will drop the in-memory state.
3149 :
3150 : // Drop persistent state.
3151 0 : self.persistence.delete_tenant(tenant_id).await?;
3152 :
3153 : // Drop in-memory state
3154 : {
3155 0 : let mut locked = self.inner.write().unwrap();
3156 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
3157 :
3158 : // Dereference Scheduler from shards before dropping them
3159 0 : for (_tenant_shard_id, shard) in
3160 0 : tenants.range_mut(TenantShardId::tenant_range(tenant_id))
3161 0 : {
3162 0 : shard.intent.clear(scheduler);
3163 0 : }
3164 :
3165 0 : tenants.retain(|tenant_shard_id, _shard| tenant_shard_id.tenant_id != tenant_id);
3166 0 : tracing::info!(
3167 0 : "Deleted tenant {tenant_id}, now have {} tenants",
3168 0 : locked.tenants.len()
3169 : );
3170 : };
3171 :
3172 : // Success is represented as 404, to imitate the existing pageserver deletion API
3173 0 : Ok(StatusCode::NOT_FOUND)
3174 0 : }
3175 :
3176 : /// Naming: this configures the storage controller's policies for a tenant, whereas [`Self::tenant_config_set`] is "set the TenantConfig"
3177 : /// for a tenant. The TenantConfig is passed through to pageservers, whereas this function modifies
3178 : /// the tenant's policies (configuration) within the storage controller
3179 0 : pub(crate) async fn tenant_update_policy(
3180 0 : &self,
3181 0 : tenant_id: TenantId,
3182 0 : req: TenantPolicyRequest,
3183 0 : ) -> Result<(), ApiError> {
3184 : // We require an exclusive lock, because we are updating persistent and in-memory state
3185 0 : let _tenant_lock = trace_exclusive_lock(
3186 0 : &self.tenant_op_locks,
3187 0 : tenant_id,
3188 0 : TenantOperations::UpdatePolicy,
3189 0 : )
3190 0 : .await;
3191 :
3192 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3193 :
3194 0 : failpoint_support::sleep_millis_async!("tenant-update-policy-exclusive-lock");
3195 :
3196 : let TenantPolicyRequest {
3197 0 : placement,
3198 0 : mut scheduling,
3199 0 : } = req;
3200 :
3201 0 : if let Some(PlacementPolicy::Detached | PlacementPolicy::Secondary) = placement {
3202 : // When someone configures a tenant to detach, we force the scheduling policy to enable
3203 : // this to take effect.
3204 0 : if scheduling.is_none() {
3205 0 : scheduling = Some(ShardSchedulingPolicy::Active);
3206 0 : }
3207 0 : }
3208 :
3209 0 : self.persistence
3210 0 : .update_tenant_shard(
3211 0 : TenantFilter::Tenant(tenant_id),
3212 0 : placement.clone(),
3213 0 : None,
3214 0 : None,
3215 0 : scheduling,
3216 0 : )
3217 0 : .await?;
3218 :
3219 0 : let mut schedule_context = ScheduleContext::default();
3220 0 : let mut locked = self.inner.write().unwrap();
3221 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3222 0 : for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3223 0 : if let Some(placement) = &placement {
3224 0 : shard.policy = placement.clone();
3225 0 :
3226 0 : tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
3227 0 : "Updated placement policy to {placement:?}");
3228 0 : }
3229 :
3230 0 : if let Some(scheduling) = &scheduling {
3231 0 : shard.set_scheduling_policy(*scheduling);
3232 0 :
3233 0 : tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
3234 0 : "Updated scheduling policy to {scheduling:?}");
3235 0 : }
3236 :
3237 : // In case scheduling is being switched back on, try it now.
3238 0 : shard.schedule(scheduler, &mut schedule_context).ok();
3239 0 : self.maybe_reconcile_shard(shard, nodes);
3240 : }
3241 :
3242 0 : Ok(())
3243 0 : }
3244 :
3245 0 : pub(crate) async fn tenant_timeline_create(
3246 0 : &self,
3247 0 : tenant_id: TenantId,
3248 0 : mut create_req: TimelineCreateRequest,
3249 0 : ) -> Result<TimelineInfo, ApiError> {
3250 0 : tracing::info!(
3251 0 : "Creating timeline {}/{}",
3252 : tenant_id,
3253 : create_req.new_timeline_id,
3254 : );
3255 :
3256 0 : let _tenant_lock = trace_shared_lock(
3257 0 : &self.tenant_op_locks,
3258 0 : tenant_id,
3259 0 : TenantOperations::TimelineCreate,
3260 0 : )
3261 0 : .await;
3262 0 : failpoint_support::sleep_millis_async!("tenant-create-timeline-shared-lock");
3263 :
3264 0 : self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
3265 0 : if targets.0.is_empty() {
3266 0 : return Err(ApiError::NotFound(
3267 0 : anyhow::anyhow!("Tenant not found").into(),
3268 0 : ));
3269 0 : };
3270 0 :
3271 0 : let (shard_zero_tid, shard_zero_locations) =
3272 0 : targets.0.pop_first().expect("Must have at least one shard");
3273 0 : assert!(shard_zero_tid.is_shard_zero());
3274 :
3275 0 : async fn create_one(
3276 0 : tenant_shard_id: TenantShardId,
3277 0 : locations: ShardMutationLocations,
3278 0 : jwt: Option<String>,
3279 0 : create_req: TimelineCreateRequest,
3280 0 : ) -> Result<TimelineInfo, ApiError> {
3281 0 : let latest = locations.latest.node;
3282 0 :
3283 0 : tracing::info!(
3284 0 : "Creating timeline on shard {}/{}, attached to node {latest} in generation {:?}",
3285 : tenant_shard_id,
3286 : create_req.new_timeline_id,
3287 : locations.latest.generation
3288 : );
3289 :
3290 0 : let client =
3291 0 : PageserverClient::new(latest.get_id(), latest.base_url(), jwt.as_deref());
3292 :
3293 0 : let timeline_info = client
3294 0 : .timeline_create(tenant_shard_id, &create_req)
3295 0 : .await
3296 0 : .map_err(|e| passthrough_api_error(&latest, e))?;
3297 :
3298 : // We propagate timeline creations to all attached locations such that a compute
3299 : // for the new timeline is able to start regardless of the current state of the
3300 : // tenant shard reconciliation.
3301 0 : for location in locations.other {
3302 0 : tracing::info!(
3303 0 : "Creating timeline on shard {}/{}, stale attached to node {} in generation {:?}",
3304 : tenant_shard_id,
3305 : create_req.new_timeline_id,
3306 : location.node,
3307 : location.generation
3308 : );
3309 :
3310 0 : let client = PageserverClient::new(
3311 0 : location.node.get_id(),
3312 0 : location.node.base_url(),
3313 0 : jwt.as_deref(),
3314 0 : );
3315 :
3316 0 : let res = client
3317 0 : .timeline_create(tenant_shard_id, &create_req)
3318 0 : .await;
3319 :
3320 0 : if let Err(e) = res {
3321 0 : match e {
3322 0 : mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _) => {
3323 0 : // Tenant might have been detached from the stale location,
3324 0 : // so ignore 404s.
3325 0 : },
3326 : _ => {
3327 0 : return Err(passthrough_api_error(&location.node, e));
3328 : }
3329 : }
3330 0 : }
3331 : }
3332 :
3333 0 : Ok(timeline_info)
3334 0 : }
3335 :
3336 : // Because the caller might not provide an explicit LSN, we must do the creation first on a single shard, and then
3337 : // use whatever LSN that shard picked when creating on subsequent shards. We arbitrarily use shard zero as the shard
3338 : // that will get the first creation request, and propagate the LSN to all the >0 shards.
3339 0 : let timeline_info = create_one(
3340 0 : shard_zero_tid,
3341 0 : shard_zero_locations,
3342 0 : self.config.jwt_token.clone(),
3343 0 : create_req.clone(),
3344 0 : )
3345 0 : .await?;
3346 :
3347 : // Propagate the LSN that shard zero picked, if caller didn't provide one
3348 0 : match &mut create_req.mode {
3349 0 : models::TimelineCreateRequestMode::Branch { ancestor_start_lsn, .. } if ancestor_start_lsn.is_none() => {
3350 0 : *ancestor_start_lsn = timeline_info.ancestor_lsn;
3351 0 : },
3352 0 : _ => {}
3353 : }
3354 :
3355 : // Create timeline on remaining shards with number >0
3356 0 : if !targets.0.is_empty() {
3357 : // If we had multiple shards, issue requests for the remainder now.
3358 0 : let jwt = &self.config.jwt_token;
3359 0 : self.tenant_for_shards(
3360 0 : targets
3361 0 : .0
3362 0 : .iter()
3363 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
3364 0 : .collect(),
3365 0 : |tenant_shard_id: TenantShardId, _node: Node| {
3366 0 : let create_req = create_req.clone();
3367 0 : let mutation_locations = targets.0.remove(&tenant_shard_id).unwrap();
3368 0 : Box::pin(create_one(
3369 0 : tenant_shard_id,
3370 0 : mutation_locations,
3371 0 : jwt.clone(),
3372 0 : create_req,
3373 0 : ))
3374 0 : },
3375 0 : )
3376 0 : .await?;
3377 0 : }
3378 :
3379 0 : Ok(timeline_info)
3380 0 : })
3381 0 : .await?
3382 0 : }
3383 :
3384 0 : pub(crate) async fn tenant_timeline_archival_config(
3385 0 : &self,
3386 0 : tenant_id: TenantId,
3387 0 : timeline_id: TimelineId,
3388 0 : req: TimelineArchivalConfigRequest,
3389 0 : ) -> Result<(), ApiError> {
3390 0 : tracing::info!(
3391 0 : "Setting archival config of timeline {tenant_id}/{timeline_id} to '{:?}'",
3392 : req.state
3393 : );
3394 :
3395 0 : let _tenant_lock = trace_shared_lock(
3396 0 : &self.tenant_op_locks,
3397 0 : tenant_id,
3398 0 : TenantOperations::TimelineArchivalConfig,
3399 0 : )
3400 0 : .await;
3401 :
3402 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
3403 0 : if targets.0.is_empty() {
3404 0 : return Err(ApiError::NotFound(
3405 0 : anyhow::anyhow!("Tenant not found").into(),
3406 0 : ));
3407 0 : }
3408 0 : async fn config_one(
3409 0 : tenant_shard_id: TenantShardId,
3410 0 : timeline_id: TimelineId,
3411 0 : node: Node,
3412 0 : jwt: Option<String>,
3413 0 : req: TimelineArchivalConfigRequest,
3414 0 : ) -> Result<(), ApiError> {
3415 0 : tracing::info!(
3416 0 : "Setting archival config of timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
3417 : );
3418 :
3419 0 : let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
3420 0 :
3421 0 : client
3422 0 : .timeline_archival_config(tenant_shard_id, timeline_id, &req)
3423 0 : .await
3424 0 : .map_err(|e| match e {
3425 0 : mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg) => {
3426 0 : ApiError::PreconditionFailed(msg.into_boxed_str())
3427 : }
3428 0 : _ => passthrough_api_error(&node, e),
3429 0 : })
3430 0 : }
3431 :
3432 : // no shard needs to go first/last; the operation should be idempotent
3433 : // TODO: it would be great to ensure that all shards return the same error
3434 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
3435 0 : let results = self
3436 0 : .tenant_for_shards(locations, |tenant_shard_id, node| {
3437 0 : futures::FutureExt::boxed(config_one(
3438 0 : tenant_shard_id,
3439 0 : timeline_id,
3440 0 : node,
3441 0 : self.config.jwt_token.clone(),
3442 0 : req.clone(),
3443 0 : ))
3444 0 : })
3445 0 : .await?;
3446 0 : assert!(!results.is_empty(), "must have at least one result");
3447 :
3448 0 : Ok(())
3449 0 : }).await?
3450 0 : }
3451 :
3452 0 : pub(crate) async fn tenant_timeline_detach_ancestor(
3453 0 : &self,
3454 0 : tenant_id: TenantId,
3455 0 : timeline_id: TimelineId,
3456 0 : ) -> Result<models::detach_ancestor::AncestorDetached, ApiError> {
3457 0 : tracing::info!("Detaching timeline {tenant_id}/{timeline_id}",);
3458 :
3459 0 : let _tenant_lock = trace_shared_lock(
3460 0 : &self.tenant_op_locks,
3461 0 : tenant_id,
3462 0 : TenantOperations::TimelineDetachAncestor,
3463 0 : )
3464 0 : .await;
3465 :
3466 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
3467 0 : if targets.0.is_empty() {
3468 0 : return Err(ApiError::NotFound(
3469 0 : anyhow::anyhow!("Tenant not found").into(),
3470 0 : ));
3471 0 : }
3472 :
3473 0 : async fn detach_one(
3474 0 : tenant_shard_id: TenantShardId,
3475 0 : timeline_id: TimelineId,
3476 0 : node: Node,
3477 0 : jwt: Option<String>,
3478 0 : ) -> Result<(ShardNumber, models::detach_ancestor::AncestorDetached), ApiError> {
3479 0 : tracing::info!(
3480 0 : "Detaching timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
3481 : );
3482 :
3483 0 : let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
3484 0 :
3485 0 : client
3486 0 : .timeline_detach_ancestor(tenant_shard_id, timeline_id)
3487 0 : .await
3488 0 : .map_err(|e| {
3489 : use mgmt_api::Error;
3490 :
3491 0 : match e {
3492 : // no ancestor (ever)
3493 0 : Error::ApiError(StatusCode::CONFLICT, msg) => ApiError::Conflict(format!(
3494 0 : "{node}: {}",
3495 0 : msg.strip_prefix("Conflict: ").unwrap_or(&msg)
3496 0 : )),
3497 : // too many ancestors
3498 0 : Error::ApiError(StatusCode::BAD_REQUEST, msg) => {
3499 0 : ApiError::BadRequest(anyhow::anyhow!("{node}: {msg}"))
3500 : }
3501 0 : Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, msg) => {
3502 0 : // avoid turning these into conflicts to remain compatible with
3503 0 : // pageservers, 500 errors are sadly retryable with timeline ancestor
3504 0 : // detach
3505 0 : ApiError::InternalServerError(anyhow::anyhow!("{node}: {msg}"))
3506 : }
3507 : // rest can be mapped as usual
3508 0 : other => passthrough_api_error(&node, other),
3509 : }
3510 0 : })
3511 0 : .map(|res| (tenant_shard_id.shard_number, res))
3512 0 : }
3513 :
3514 : // no shard needs to go first/last; the operation should be idempotent
3515 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
3516 0 : let mut results = self
3517 0 : .tenant_for_shards(locations, |tenant_shard_id, node| {
3518 0 : futures::FutureExt::boxed(detach_one(
3519 0 : tenant_shard_id,
3520 0 : timeline_id,
3521 0 : node,
3522 0 : self.config.jwt_token.clone(),
3523 0 : ))
3524 0 : })
3525 0 : .await?;
3526 :
3527 0 : let any = results.pop().expect("we must have at least one response");
3528 0 :
3529 0 : let mismatching = results
3530 0 : .iter()
3531 0 : .filter(|(_, res)| res != &any.1)
3532 0 : .collect::<Vec<_>>();
3533 0 : if !mismatching.is_empty() {
3534 : // this can be hit by races which should not happen because operation lock on cplane
3535 0 : let matching = results.len() - mismatching.len();
3536 0 : tracing::error!(
3537 : matching,
3538 : compared_against=?any,
3539 : ?mismatching,
3540 0 : "shards returned different results"
3541 : );
3542 :
3543 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!("pageservers returned mixed results for ancestor detach; manual intervention is required.")));
3544 0 : }
3545 0 :
3546 0 : Ok(any.1)
3547 0 : }).await?
3548 0 : }
3549 :
3550 0 : pub(crate) async fn tenant_timeline_block_unblock_gc(
3551 0 : &self,
3552 0 : tenant_id: TenantId,
3553 0 : timeline_id: TimelineId,
3554 0 : dir: BlockUnblock,
3555 0 : ) -> Result<(), ApiError> {
3556 0 : let _tenant_lock = trace_shared_lock(
3557 0 : &self.tenant_op_locks,
3558 0 : tenant_id,
3559 0 : TenantOperations::TimelineGcBlockUnblock,
3560 0 : )
3561 0 : .await;
3562 :
3563 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
3564 0 : if targets.0.is_empty() {
3565 0 : return Err(ApiError::NotFound(
3566 0 : anyhow::anyhow!("Tenant not found").into(),
3567 0 : ));
3568 0 : }
3569 :
3570 0 : async fn do_one(
3571 0 : tenant_shard_id: TenantShardId,
3572 0 : timeline_id: TimelineId,
3573 0 : node: Node,
3574 0 : jwt: Option<String>,
3575 0 : dir: BlockUnblock,
3576 0 : ) -> Result<(), ApiError> {
3577 0 : let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
3578 0 :
3579 0 : client
3580 0 : .timeline_block_unblock_gc(tenant_shard_id, timeline_id, dir)
3581 0 : .await
3582 0 : .map_err(|e| passthrough_api_error(&node, e))
3583 0 : }
3584 :
3585 : // no shard needs to go first/last; the operation should be idempotent
3586 0 : let locations = targets
3587 0 : .0
3588 0 : .iter()
3589 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
3590 0 : .collect();
3591 0 : self.tenant_for_shards(locations, |tenant_shard_id, node| {
3592 0 : futures::FutureExt::boxed(do_one(
3593 0 : tenant_shard_id,
3594 0 : timeline_id,
3595 0 : node,
3596 0 : self.config.jwt_token.clone(),
3597 0 : dir,
3598 0 : ))
3599 0 : })
3600 0 : .await
3601 0 : })
3602 0 : .await??;
3603 0 : Ok(())
3604 0 : }
3605 :
3606 : /// Helper for concurrently calling a pageserver API on a number of shards, such as timeline creation.
3607 : ///
3608 : /// On success, the returned vector contains exactly the same number of elements as the input `locations`.
3609 0 : async fn tenant_for_shards<F, R>(
3610 0 : &self,
3611 0 : locations: Vec<(TenantShardId, Node)>,
3612 0 : mut req_fn: F,
3613 0 : ) -> Result<Vec<R>, ApiError>
3614 0 : where
3615 0 : F: FnMut(
3616 0 : TenantShardId,
3617 0 : Node,
3618 0 : )
3619 0 : -> std::pin::Pin<Box<dyn futures::Future<Output = Result<R, ApiError>> + Send>>,
3620 0 : {
3621 0 : let mut futs = FuturesUnordered::new();
3622 0 : let mut results = Vec::with_capacity(locations.len());
3623 :
3624 0 : for (tenant_shard_id, node) in locations {
3625 0 : futs.push(req_fn(tenant_shard_id, node));
3626 0 : }
3627 :
3628 0 : while let Some(r) = futs.next().await {
3629 0 : results.push(r?);
3630 : }
3631 :
3632 0 : Ok(results)
3633 0 : }
3634 :
3635 : /// Concurrently invoke a pageserver API call on many shards at once
3636 0 : pub(crate) async fn tenant_for_shards_api<T, O, F>(
3637 0 : &self,
3638 0 : locations: Vec<(TenantShardId, Node)>,
3639 0 : op: O,
3640 0 : warn_threshold: u32,
3641 0 : max_retries: u32,
3642 0 : timeout: Duration,
3643 0 : cancel: &CancellationToken,
3644 0 : ) -> Vec<mgmt_api::Result<T>>
3645 0 : where
3646 0 : O: Fn(TenantShardId, PageserverClient) -> F + Copy,
3647 0 : F: std::future::Future<Output = mgmt_api::Result<T>>,
3648 0 : {
3649 0 : let mut futs = FuturesUnordered::new();
3650 0 : let mut results = Vec::with_capacity(locations.len());
3651 :
3652 0 : for (tenant_shard_id, node) in locations {
3653 0 : futs.push(async move {
3654 0 : node.with_client_retries(
3655 0 : |client| op(tenant_shard_id, client),
3656 0 : &self.config.jwt_token,
3657 0 : warn_threshold,
3658 0 : max_retries,
3659 0 : timeout,
3660 0 : cancel,
3661 0 : )
3662 0 : .await
3663 0 : });
3664 0 : }
3665 :
3666 0 : while let Some(r) = futs.next().await {
3667 0 : let r = r.unwrap_or(Err(mgmt_api::Error::Cancelled));
3668 0 : results.push(r);
3669 0 : }
3670 :
3671 0 : results
3672 0 : }
3673 :
3674 : /// Helper for safely working with the shards in a tenant remotely on pageservers, for example
3675 : /// when creating and deleting timelines:
3676 : /// - Makes sure shards are attached somewhere if they weren't already
3677 : /// - Looks up the shards and the nodes where they were most recently attached
3678 : /// - Guarantees that after the inner function returns, the shards' generations haven't moved on: this
3679 : /// ensures that the remote operation acted on the most recent generation, and is therefore durable.
3680 0 : async fn tenant_remote_mutation<R, O, F>(
3681 0 : &self,
3682 0 : tenant_id: TenantId,
3683 0 : op: O,
3684 0 : ) -> Result<R, ApiError>
3685 0 : where
3686 0 : O: FnOnce(TenantMutationLocations) -> F,
3687 0 : F: std::future::Future<Output = R>,
3688 0 : {
3689 0 : let mutation_locations = {
3690 0 : let mut locations = TenantMutationLocations::default();
3691 :
3692 : // Load the currently attached pageservers for the latest generation of each shard. This can
3693 : // run concurrently with reconciliations, and it is not guaranteed that the node we find here
3694 : // will still be the latest when we're done: we will check generations again at the end of
3695 : // this function to handle that.
3696 0 : let generations = self.persistence.tenant_generations(tenant_id).await?;
3697 :
3698 0 : if generations
3699 0 : .iter()
3700 0 : .any(|i| i.generation.is_none() || i.generation_pageserver.is_none())
3701 : {
3702 0 : let shard_generations = generations
3703 0 : .into_iter()
3704 0 : .map(|i| (i.tenant_shard_id, (i.generation, i.generation_pageserver)))
3705 0 : .collect::<HashMap<_, _>>();
3706 0 :
3707 0 : // One or more shards has not been attached to a pageserver. Check if this is because it's configured
3708 0 : // to be detached (409: caller should give up), or because it's meant to be attached but isn't yet (503: caller should retry)
3709 0 : let locked = self.inner.read().unwrap();
3710 0 : for (shard_id, shard) in
3711 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
3712 : {
3713 0 : match shard.policy {
3714 : PlacementPolicy::Attached(_) => {
3715 : // This shard is meant to be attached: the caller is not wrong to try and
3716 : // use this function, but we can't service the request right now.
3717 0 : let Some(generation) = shard_generations.get(shard_id) else {
3718 : // This can only happen if there is a split brain controller modifying the database. This should
3719 : // never happen when testing, and if it happens in production we can only log the issue.
3720 0 : debug_assert!(false);
3721 0 : tracing::error!("Shard {shard_id} not found in generation state! Is another rogue controller running?");
3722 0 : continue;
3723 : };
3724 0 : let (generation, generation_pageserver) = generation;
3725 0 : if let Some(generation) = generation {
3726 0 : if generation_pageserver.is_none() {
3727 : // This is legitimate only in a very narrow window where the shard was only just configured into
3728 : // Attached mode after being created in Secondary or Detached mode, and it has had its generation
3729 : // set but not yet had a Reconciler run (reconciler is the only thing that sets generation_pageserver).
3730 0 : tracing::warn!("Shard {shard_id} generation is set ({generation:?}) but generation_pageserver is None, reconciler not run yet?");
3731 0 : }
3732 : } else {
3733 : // This should never happen: a shard with no generation is only permitted when it was created in some state
3734 : // other than PlacementPolicy::Attached (and generation is always written to DB before setting Attached in memory)
3735 0 : debug_assert!(false);
3736 0 : tracing::error!("Shard {shard_id} generation is None, but it is in PlacementPolicy::Attached mode!");
3737 0 : continue;
3738 : }
3739 : }
3740 : PlacementPolicy::Secondary | PlacementPolicy::Detached => {
3741 0 : return Err(ApiError::Conflict(format!(
3742 0 : "Shard {shard_id} tenant has policy {:?}",
3743 0 : shard.policy
3744 0 : )));
3745 : }
3746 : }
3747 : }
3748 :
3749 0 : return Err(ApiError::ResourceUnavailable(
3750 0 : "One or more shards in tenant is not yet attached".into(),
3751 0 : ));
3752 0 : }
3753 0 :
3754 0 : let locked = self.inner.read().unwrap();
3755 : for ShardGenerationState {
3756 0 : tenant_shard_id,
3757 0 : generation,
3758 0 : generation_pageserver,
3759 0 : } in generations
3760 : {
3761 0 : let node_id = generation_pageserver.expect("We checked for None above");
3762 0 : let node = locked
3763 0 : .nodes
3764 0 : .get(&node_id)
3765 0 : .ok_or(ApiError::Conflict(format!(
3766 0 : "Raced with removal of node {node_id}"
3767 0 : )))?;
3768 0 : let generation = generation.expect("Checked above");
3769 0 :
3770 0 : let tenant = locked.tenants.get(&tenant_shard_id);
3771 :
3772 : // TODO(vlad): Abstract the logic that finds stale attached locations
3773 : // from observed state into a [`Service`] method.
3774 0 : let other_locations = match tenant {
3775 0 : Some(tenant) => {
3776 0 : let mut other = tenant.attached_locations();
3777 0 : let latest_location_index =
3778 0 : other.iter().position(|&l| l == (node.get_id(), generation));
3779 0 : if let Some(idx) = latest_location_index {
3780 0 : other.remove(idx);
3781 0 : }
3782 :
3783 0 : other
3784 : }
3785 0 : None => Vec::default(),
3786 : };
3787 :
3788 0 : let location = ShardMutationLocations {
3789 0 : latest: MutationLocation {
3790 0 : node: node.clone(),
3791 0 : generation,
3792 0 : },
3793 0 : other: other_locations
3794 0 : .into_iter()
3795 0 : .filter_map(|(node_id, generation)| {
3796 0 : let node = locked.nodes.get(&node_id)?;
3797 :
3798 0 : Some(MutationLocation {
3799 0 : node: node.clone(),
3800 0 : generation,
3801 0 : })
3802 0 : })
3803 0 : .collect(),
3804 0 : };
3805 0 : locations.0.insert(tenant_shard_id, location);
3806 0 : }
3807 :
3808 0 : locations
3809 : };
3810 :
3811 0 : let result = op(mutation_locations.clone()).await;
3812 :
3813 : // Post-check: are all the generations of all the shards the same as they were initially? This proves that
3814 : // our remote operation executed on the latest generation and is therefore persistent.
3815 : {
3816 0 : let latest_generations = self.persistence.tenant_generations(tenant_id).await?;
3817 0 : if latest_generations
3818 0 : .into_iter()
3819 0 : .map(
3820 0 : |ShardGenerationState {
3821 : tenant_shard_id,
3822 : generation,
3823 : generation_pageserver: _,
3824 0 : }| (tenant_shard_id, generation),
3825 0 : )
3826 0 : .collect::<Vec<_>>()
3827 0 : != mutation_locations
3828 0 : .0
3829 0 : .into_iter()
3830 0 : .map(|i| (i.0, Some(i.1.latest.generation)))
3831 0 : .collect::<Vec<_>>()
3832 : {
3833 : // We raced with something that incremented the generation, and therefore cannot be
3834 : // confident that our actions are persistent (they might have hit an old generation).
3835 : //
3836 : // This is safe but requires a retry: ask the client to do that by giving them a 503 response.
3837 0 : return Err(ApiError::ResourceUnavailable(
3838 0 : "Tenant attachment changed, please retry".into(),
3839 0 : ));
3840 0 : }
3841 0 : }
3842 0 :
3843 0 : Ok(result)
3844 0 : }
3845 :
3846 0 : pub(crate) async fn tenant_timeline_delete(
3847 0 : &self,
3848 0 : tenant_id: TenantId,
3849 0 : timeline_id: TimelineId,
3850 0 : ) -> Result<StatusCode, ApiError> {
3851 0 : tracing::info!("Deleting timeline {}/{}", tenant_id, timeline_id,);
3852 0 : let _tenant_lock = trace_shared_lock(
3853 0 : &self.tenant_op_locks,
3854 0 : tenant_id,
3855 0 : TenantOperations::TimelineDelete,
3856 0 : )
3857 0 : .await;
3858 :
3859 0 : self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
3860 0 : if targets.0.is_empty() {
3861 0 : return Err(ApiError::NotFound(
3862 0 : anyhow::anyhow!("Tenant not found").into(),
3863 0 : ));
3864 0 : }
3865 0 :
3866 0 : let (shard_zero_tid, shard_zero_locations) = targets.0.pop_first().expect("Must have at least one shard");
3867 0 : assert!(shard_zero_tid.is_shard_zero());
3868 :
3869 0 : async fn delete_one(
3870 0 : tenant_shard_id: TenantShardId,
3871 0 : timeline_id: TimelineId,
3872 0 : node: Node,
3873 0 : jwt: Option<String>,
3874 0 : ) -> Result<StatusCode, ApiError> {
3875 0 : tracing::info!(
3876 0 : "Deleting timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
3877 : );
3878 :
3879 0 : let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
3880 0 : let res = client
3881 0 : .timeline_delete(tenant_shard_id, timeline_id)
3882 0 : .await;
3883 :
3884 0 : match res {
3885 0 : Ok(ok) => Ok(ok),
3886 0 : Err(mgmt_api::Error::ApiError(StatusCode::CONFLICT, _)) => Ok(StatusCode::CONFLICT),
3887 0 : Err(mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg)) => Err(ApiError::ResourceUnavailable(msg.into())),
3888 0 : Err(e) => {
3889 0 : Err(
3890 0 : ApiError::InternalServerError(anyhow::anyhow!(
3891 0 : "Error deleting timeline {timeline_id} on {tenant_shard_id} on node {node}: {e}",
3892 0 : ))
3893 0 : )
3894 : }
3895 : }
3896 0 : }
3897 :
3898 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
3899 0 : let statuses = self
3900 0 : .tenant_for_shards(locations, |tenant_shard_id: TenantShardId, node: Node| {
3901 0 : Box::pin(delete_one(
3902 0 : tenant_shard_id,
3903 0 : timeline_id,
3904 0 : node,
3905 0 : self.config.jwt_token.clone(),
3906 0 : ))
3907 0 : })
3908 0 : .await?;
3909 :
3910 : // If any shards >0 haven't finished deletion yet, don't start deletion on shard zero.
3911 : // We return 409 (Conflict) if deletion was already in progress on any of the shards
3912 : // and 202 (Accepted) if deletion was not already in progress on any of the shards.
3913 0 : if statuses.iter().any(|s| s == &StatusCode::CONFLICT) {
3914 0 : return Ok(StatusCode::CONFLICT);
3915 0 : }
3916 0 :
3917 0 : if statuses.iter().any(|s| s != &StatusCode::NOT_FOUND) {
3918 0 : return Ok(StatusCode::ACCEPTED);
3919 0 : }
3920 :
3921 : // Delete shard zero last: this is not strictly necessary, but since a caller's GET on a timeline will be routed
3922 : // to shard zero, it gives a more obvious behavior that a GET returns 404 once the deletion is done.
3923 0 : let shard_zero_status = delete_one(
3924 0 : shard_zero_tid,
3925 0 : timeline_id,
3926 0 : shard_zero_locations.latest.node,
3927 0 : self.config.jwt_token.clone(),
3928 0 : )
3929 0 : .await?;
3930 0 : Ok(shard_zero_status)
3931 0 : }).await?
3932 0 : }
3933 :
3934 : /// When you need to send an HTTP request to the pageserver that holds shard0 of a tenant, this
3935 : /// function looks up and returns node. If the tenant isn't found, returns Err(ApiError::NotFound)
3936 0 : pub(crate) async fn tenant_shard0_node(
3937 0 : &self,
3938 0 : tenant_id: TenantId,
3939 0 : ) -> Result<(Node, TenantShardId), ApiError> {
3940 0 : // Look up in-memory state and maybe use the node from there.
3941 0 : {
3942 0 : let locked = self.inner.read().unwrap();
3943 0 : let Some((tenant_shard_id, shard)) = locked
3944 0 : .tenants
3945 0 : .range(TenantShardId::tenant_range(tenant_id))
3946 0 : .next()
3947 : else {
3948 0 : return Err(ApiError::NotFound(
3949 0 : anyhow::anyhow!("Tenant {tenant_id} not found").into(),
3950 0 : ));
3951 : };
3952 :
3953 0 : let Some(intent_node_id) = shard.intent.get_attached() else {
3954 0 : tracing::warn!(
3955 0 : tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
3956 0 : "Shard not scheduled (policy {:?}), cannot generate pass-through URL",
3957 : shard.policy
3958 : );
3959 0 : return Err(ApiError::Conflict(
3960 0 : "Cannot call timeline API on non-attached tenant".to_string(),
3961 0 : ));
3962 : };
3963 :
3964 0 : if shard.reconciler.is_none() {
3965 : // Optimization: while no reconcile is in flight, we may trust our in-memory state
3966 : // to tell us which pageserver to use. Otherwise we will fall through and hit the database
3967 0 : let Some(node) = locked.nodes.get(intent_node_id) else {
3968 : // This should never happen
3969 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3970 0 : "Shard refers to nonexistent node"
3971 0 : )));
3972 : };
3973 0 : return Ok((node.clone(), *tenant_shard_id));
3974 0 : }
3975 : };
3976 :
3977 : // Look up the latest attached pageserver location from the database
3978 : // generation state: this will reflect the progress of any ongoing migration.
3979 : // Note that it is not guaranteed to _stay_ here, our caller must still handle
3980 : // the case where they call through to the pageserver and get a 404.
3981 0 : let db_result = self.persistence.tenant_generations(tenant_id).await?;
3982 : let Some(ShardGenerationState {
3983 0 : tenant_shard_id,
3984 0 : generation: _,
3985 0 : generation_pageserver: Some(node_id),
3986 0 : }) = db_result.first()
3987 : else {
3988 : // This can happen if we raced with a tenant deletion or a shard split. On a retry
3989 : // the caller will either succeed (shard split case), get a proper 404 (deletion case),
3990 : // or a conflict response (case where tenant was detached in background)
3991 0 : return Err(ApiError::ResourceUnavailable(
3992 0 : "Shard {} not found in database, or is not attached".into(),
3993 0 : ));
3994 : };
3995 0 : let locked = self.inner.read().unwrap();
3996 0 : let Some(node) = locked.nodes.get(node_id) else {
3997 : // This should never happen
3998 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3999 0 : "Shard refers to nonexistent node"
4000 0 : )));
4001 : };
4002 :
4003 0 : Ok((node.clone(), *tenant_shard_id))
4004 0 : }
4005 :
4006 0 : pub(crate) fn tenant_locate(
4007 0 : &self,
4008 0 : tenant_id: TenantId,
4009 0 : ) -> Result<TenantLocateResponse, ApiError> {
4010 0 : let locked = self.inner.read().unwrap();
4011 0 : tracing::info!("Locating shards for tenant {tenant_id}");
4012 :
4013 0 : let mut result = Vec::new();
4014 0 : let mut shard_params: Option<ShardParameters> = None;
4015 :
4016 0 : for (tenant_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id))
4017 : {
4018 0 : let node_id =
4019 0 : shard
4020 0 : .intent
4021 0 : .get_attached()
4022 0 : .ok_or(ApiError::BadRequest(anyhow::anyhow!(
4023 0 : "Cannot locate a tenant that is not attached"
4024 0 : )))?;
4025 :
4026 0 : let node = locked
4027 0 : .nodes
4028 0 : .get(&node_id)
4029 0 : .expect("Pageservers may not be deleted while referenced");
4030 0 :
4031 0 : result.push(node.shard_location(*tenant_shard_id));
4032 0 :
4033 0 : match &shard_params {
4034 0 : None => {
4035 0 : shard_params = Some(ShardParameters {
4036 0 : stripe_size: shard.shard.stripe_size,
4037 0 : count: shard.shard.count,
4038 0 : });
4039 0 : }
4040 0 : Some(params) => {
4041 0 : if params.stripe_size != shard.shard.stripe_size {
4042 : // This should never happen. We enforce at runtime because it's simpler than
4043 : // adding an extra per-tenant data structure to store the things that should be the same
4044 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
4045 0 : "Inconsistent shard stripe size parameters!"
4046 0 : )));
4047 0 : }
4048 : }
4049 : }
4050 : }
4051 :
4052 0 : if result.is_empty() {
4053 0 : return Err(ApiError::NotFound(
4054 0 : anyhow::anyhow!("No shards for this tenant ID found").into(),
4055 0 : ));
4056 0 : }
4057 0 : let shard_params = shard_params.expect("result is non-empty, therefore this is set");
4058 0 : tracing::info!(
4059 0 : "Located tenant {} with params {:?} on shards {}",
4060 0 : tenant_id,
4061 0 : shard_params,
4062 0 : result
4063 0 : .iter()
4064 0 : .map(|s| format!("{:?}", s))
4065 0 : .collect::<Vec<_>>()
4066 0 : .join(",")
4067 : );
4068 :
4069 0 : Ok(TenantLocateResponse {
4070 0 : shards: result,
4071 0 : shard_params,
4072 0 : })
4073 0 : }
4074 :
4075 : /// Returns None if the input iterator of shards does not include a shard with number=0
4076 0 : fn tenant_describe_impl<'a>(
4077 0 : &self,
4078 0 : shards: impl Iterator<Item = &'a TenantShard>,
4079 0 : ) -> Option<TenantDescribeResponse> {
4080 0 : let mut shard_zero = None;
4081 0 : let mut describe_shards = Vec::new();
4082 :
4083 0 : for shard in shards {
4084 0 : if shard.tenant_shard_id.is_shard_zero() {
4085 0 : shard_zero = Some(shard);
4086 0 : }
4087 :
4088 0 : describe_shards.push(TenantDescribeResponseShard {
4089 0 : tenant_shard_id: shard.tenant_shard_id,
4090 0 : node_attached: *shard.intent.get_attached(),
4091 0 : node_secondary: shard.intent.get_secondary().to_vec(),
4092 0 : last_error: shard
4093 0 : .last_error
4094 0 : .lock()
4095 0 : .unwrap()
4096 0 : .as_ref()
4097 0 : .map(|e| format!("{e}"))
4098 0 : .unwrap_or("".to_string())
4099 0 : .clone(),
4100 0 : is_reconciling: shard.reconciler.is_some(),
4101 0 : is_pending_compute_notification: shard.pending_compute_notification,
4102 0 : is_splitting: matches!(shard.splitting, SplitState::Splitting),
4103 0 : scheduling_policy: *shard.get_scheduling_policy(),
4104 0 : preferred_az_id: shard.preferred_az().map(ToString::to_string),
4105 : })
4106 : }
4107 :
4108 0 : let shard_zero = shard_zero?;
4109 :
4110 0 : Some(TenantDescribeResponse {
4111 0 : tenant_id: shard_zero.tenant_shard_id.tenant_id,
4112 0 : shards: describe_shards,
4113 0 : stripe_size: shard_zero.shard.stripe_size,
4114 0 : policy: shard_zero.policy.clone(),
4115 0 : config: shard_zero.config.clone(),
4116 0 : })
4117 0 : }
4118 :
4119 0 : pub(crate) fn tenant_describe(
4120 0 : &self,
4121 0 : tenant_id: TenantId,
4122 0 : ) -> Result<TenantDescribeResponse, ApiError> {
4123 0 : let locked = self.inner.read().unwrap();
4124 0 :
4125 0 : self.tenant_describe_impl(
4126 0 : locked
4127 0 : .tenants
4128 0 : .range(TenantShardId::tenant_range(tenant_id))
4129 0 : .map(|(_k, v)| v),
4130 0 : )
4131 0 : .ok_or_else(|| ApiError::NotFound(anyhow::anyhow!("Tenant {tenant_id} not found").into()))
4132 0 : }
4133 :
4134 0 : pub(crate) fn tenant_list(&self) -> Vec<TenantDescribeResponse> {
4135 0 : let locked = self.inner.read().unwrap();
4136 0 :
4137 0 : let mut result = Vec::new();
4138 0 : for (_tenant_id, tenant_shards) in
4139 0 : &locked.tenants.iter().group_by(|(id, _shard)| id.tenant_id)
4140 0 : {
4141 0 : result.push(
4142 0 : self.tenant_describe_impl(tenant_shards.map(|(_k, v)| v))
4143 0 : .expect("Groups are always non-empty"),
4144 0 : );
4145 0 : }
4146 :
4147 0 : result
4148 0 : }
4149 :
4150 : #[instrument(skip_all, fields(tenant_id=%op.tenant_id))]
4151 : async fn abort_tenant_shard_split(
4152 : &self,
4153 : op: &TenantShardSplitAbort,
4154 : ) -> Result<(), TenantShardSplitAbortError> {
4155 : // Cleaning up a split:
4156 : // - Parent shards are not destroyed during a split, just detached.
4157 : // - Failed pageserver split API calls can leave the remote node with just the parent attached,
4158 : // just the children attached, or both.
4159 : //
4160 : // Therefore our work to do is to:
4161 : // 1. Clean up storage controller's internal state to just refer to parents, no children
4162 : // 2. Call out to pageservers to ensure that children are detached
4163 : // 3. Call out to pageservers to ensure that parents are attached.
4164 : //
4165 : // Crash safety:
4166 : // - If the storage controller stops running during this cleanup *after* clearing the splitting state
4167 : // from our database, then [`Self::startup_reconcile`] will regard child attachments as garbage
4168 : // and detach them.
4169 : // - TODO: If the storage controller stops running during this cleanup *before* clearing the splitting state
4170 : // from our database, then we will re-enter this cleanup routine on startup.
4171 :
4172 : let TenantShardSplitAbort {
4173 : tenant_id,
4174 : new_shard_count,
4175 : new_stripe_size,
4176 : ..
4177 : } = op;
4178 :
4179 : // First abort persistent state, if any exists.
4180 : match self
4181 : .persistence
4182 : .abort_shard_split(*tenant_id, *new_shard_count)
4183 : .await?
4184 : {
4185 : AbortShardSplitStatus::Aborted => {
4186 : // Proceed to roll back any child shards created on pageservers
4187 : }
4188 : AbortShardSplitStatus::Complete => {
4189 : // The split completed (we might hit that path if e.g. our database transaction
4190 : // to write the completion landed in the database, but we dropped connection
4191 : // before seeing the result).
4192 : //
4193 : // We must update in-memory state to reflect the successful split.
4194 : self.tenant_shard_split_commit_inmem(
4195 : *tenant_id,
4196 : *new_shard_count,
4197 : *new_stripe_size,
4198 : );
4199 : return Ok(());
4200 : }
4201 : }
4202 :
4203 : // Clean up in-memory state, and accumulate the list of child locations that need detaching
4204 : let detach_locations: Vec<(Node, TenantShardId)> = {
4205 : let mut detach_locations = Vec::new();
4206 : let mut locked = self.inner.write().unwrap();
4207 : let (nodes, tenants, scheduler) = locked.parts_mut();
4208 :
4209 : for (tenant_shard_id, shard) in
4210 : tenants.range_mut(TenantShardId::tenant_range(op.tenant_id))
4211 : {
4212 : if shard.shard.count == op.new_shard_count {
4213 : // Surprising: the phase of [`Self::do_tenant_shard_split`] which inserts child shards in-memory
4214 : // is infallible, so if we got an error we shouldn't have got that far.
4215 : tracing::warn!(
4216 : "During split abort, child shard {tenant_shard_id} found in-memory"
4217 : );
4218 : continue;
4219 : }
4220 :
4221 : // Add the children of this shard to this list of things to detach
4222 : if let Some(node_id) = shard.intent.get_attached() {
4223 : for child_id in tenant_shard_id.split(*new_shard_count) {
4224 : detach_locations.push((
4225 : nodes
4226 : .get(node_id)
4227 : .expect("Intent references nonexistent node")
4228 : .clone(),
4229 : child_id,
4230 : ));
4231 : }
4232 : } else {
4233 : tracing::warn!(
4234 : "During split abort, shard {tenant_shard_id} has no attached location"
4235 : );
4236 : }
4237 :
4238 : tracing::info!("Restoring parent shard {tenant_shard_id}");
4239 : shard.splitting = SplitState::Idle;
4240 : if let Err(e) = shard.schedule(scheduler, &mut ScheduleContext::default()) {
4241 : // If this shard can't be scheduled now (perhaps due to offline nodes or
4242 : // capacity issues), that must not prevent us rolling back a split. In this
4243 : // case it should be eventually scheduled in the background.
4244 : tracing::warn!("Failed to schedule {tenant_shard_id} during shard abort: {e}")
4245 : }
4246 :
4247 : self.maybe_reconcile_shard(shard, nodes);
4248 : }
4249 :
4250 : // We don't expect any new_shard_count shards to exist here, but drop them just in case
4251 0 : tenants.retain(|_id, s| s.shard.count != *new_shard_count);
4252 :
4253 : detach_locations
4254 : };
4255 :
4256 : for (node, child_id) in detach_locations {
4257 : if !node.is_available() {
4258 : // An unavailable node cannot be cleaned up now: to avoid blocking forever, we will permit this, and
4259 : // rely on the reconciliation that happens when a node transitions to Active to clean up. Since we have
4260 : // removed child shards from our in-memory state and database, the reconciliation will implicitly remove
4261 : // them from the node.
4262 : tracing::warn!("Node {node} unavailable, can't clean up during split abort. It will be cleaned up when it is reactivated.");
4263 : continue;
4264 : }
4265 :
4266 : // Detach the remote child. If the pageserver split API call is still in progress, this call will get
4267 : // a 503 and retry, up to our limit.
4268 : tracing::info!("Detaching {child_id} on {node}...");
4269 : match node
4270 : .with_client_retries(
4271 0 : |client| async move {
4272 0 : let config = LocationConfig {
4273 0 : mode: LocationConfigMode::Detached,
4274 0 : generation: None,
4275 0 : secondary_conf: None,
4276 0 : shard_number: child_id.shard_number.0,
4277 0 : shard_count: child_id.shard_count.literal(),
4278 0 : // Stripe size and tenant config don't matter when detaching
4279 0 : shard_stripe_size: 0,
4280 0 : tenant_conf: TenantConfig::default(),
4281 0 : };
4282 0 :
4283 0 : client.location_config(child_id, config, None, false).await
4284 0 : },
4285 : &self.config.jwt_token,
4286 : 1,
4287 : 10,
4288 : Duration::from_secs(5),
4289 : &self.cancel,
4290 : )
4291 : .await
4292 : {
4293 : Some(Ok(_)) => {}
4294 : Some(Err(e)) => {
4295 : // We failed to communicate with the remote node. This is problematic: we may be
4296 : // leaving it with a rogue child shard.
4297 : tracing::warn!(
4298 : "Failed to detach child {child_id} from node {node} during abort"
4299 : );
4300 : return Err(e.into());
4301 : }
4302 : None => {
4303 : // Cancellation: we were shutdown or the node went offline. Shutdown is fine, we'll
4304 : // clean up on restart. The node going offline requires a retry.
4305 : return Err(TenantShardSplitAbortError::Unavailable);
4306 : }
4307 : };
4308 : }
4309 :
4310 : tracing::info!("Successfully aborted split");
4311 : Ok(())
4312 : }
4313 :
4314 : /// Infallible final stage of [`Self::tenant_shard_split`]: update the contents
4315 : /// of the tenant map to reflect the child shards that exist after the split.
4316 0 : fn tenant_shard_split_commit_inmem(
4317 0 : &self,
4318 0 : tenant_id: TenantId,
4319 0 : new_shard_count: ShardCount,
4320 0 : new_stripe_size: Option<ShardStripeSize>,
4321 0 : ) -> (
4322 0 : TenantShardSplitResponse,
4323 0 : Vec<(TenantShardId, NodeId, ShardStripeSize)>,
4324 0 : Vec<ReconcilerWaiter>,
4325 0 : ) {
4326 0 : let mut response = TenantShardSplitResponse {
4327 0 : new_shards: Vec::new(),
4328 0 : };
4329 0 : let mut child_locations = Vec::new();
4330 0 : let mut waiters = Vec::new();
4331 0 :
4332 0 : {
4333 0 : let mut locked = self.inner.write().unwrap();
4334 0 :
4335 0 : let parent_ids = locked
4336 0 : .tenants
4337 0 : .range(TenantShardId::tenant_range(tenant_id))
4338 0 : .map(|(shard_id, _)| *shard_id)
4339 0 : .collect::<Vec<_>>();
4340 0 :
4341 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
4342 0 : for parent_id in parent_ids {
4343 0 : let child_ids = parent_id.split(new_shard_count);
4344 :
4345 0 : let (pageserver, generation, policy, parent_ident, config, preferred_az) = {
4346 0 : let mut old_state = tenants
4347 0 : .remove(&parent_id)
4348 0 : .expect("It was present, we just split it");
4349 0 :
4350 0 : // A non-splitting state is impossible, because [`Self::tenant_shard_split`] holds
4351 0 : // a TenantId lock and passes it through to [`TenantShardSplitAbort`] in case of cleanup:
4352 0 : // nothing else can clear this.
4353 0 : assert!(matches!(old_state.splitting, SplitState::Splitting));
4354 :
4355 0 : let old_attached = old_state.intent.get_attached().unwrap();
4356 0 : old_state.intent.clear(scheduler);
4357 0 : let generation = old_state.generation.expect("Shard must have been attached");
4358 0 : (
4359 0 : old_attached,
4360 0 : generation,
4361 0 : old_state.policy.clone(),
4362 0 : old_state.shard,
4363 0 : old_state.config.clone(),
4364 0 : old_state.preferred_az().cloned(),
4365 0 : )
4366 0 : };
4367 0 :
4368 0 : let mut schedule_context = ScheduleContext::default();
4369 0 : for child in child_ids {
4370 0 : let mut child_shard = parent_ident;
4371 0 : child_shard.number = child.shard_number;
4372 0 : child_shard.count = child.shard_count;
4373 0 : if let Some(stripe_size) = new_stripe_size {
4374 0 : child_shard.stripe_size = stripe_size;
4375 0 : }
4376 :
4377 0 : let mut child_observed: HashMap<NodeId, ObservedStateLocation> = HashMap::new();
4378 0 : child_observed.insert(
4379 0 : pageserver,
4380 0 : ObservedStateLocation {
4381 0 : conf: Some(attached_location_conf(
4382 0 : generation,
4383 0 : &child_shard,
4384 0 : &config,
4385 0 : &policy,
4386 0 : )),
4387 0 : },
4388 0 : );
4389 0 :
4390 0 : let mut child_state =
4391 0 : TenantShard::new(child, child_shard, policy.clone(), preferred_az.clone());
4392 0 : child_state.intent = IntentState::single(scheduler, Some(pageserver));
4393 0 : child_state.observed = ObservedState {
4394 0 : locations: child_observed,
4395 0 : };
4396 0 : child_state.generation = Some(generation);
4397 0 : child_state.config = config.clone();
4398 0 : if let Some(preferred_az) = &preferred_az {
4399 0 : child_state.set_preferred_az(preferred_az.clone());
4400 0 : }
4401 :
4402 : // The child's TenantShard::splitting is intentionally left at the default value of Idle,
4403 : // as at this point in the split process we have succeeded and this part is infallible:
4404 : // we will never need to do any special recovery from this state.
4405 :
4406 0 : child_locations.push((child, pageserver, child_shard.stripe_size));
4407 :
4408 0 : if let Err(e) = child_state.schedule(scheduler, &mut schedule_context) {
4409 : // This is not fatal, because we've implicitly already got an attached
4410 : // location for the child shard. Failure here just means we couldn't
4411 : // find a secondary (e.g. because cluster is overloaded).
4412 0 : tracing::warn!("Failed to schedule child shard {child}: {e}");
4413 0 : }
4414 : // In the background, attach secondary locations for the new shards
4415 0 : if let Some(waiter) = self.maybe_reconcile_shard(&mut child_state, nodes) {
4416 0 : waiters.push(waiter);
4417 0 : }
4418 :
4419 0 : tenants.insert(child, child_state);
4420 0 : response.new_shards.push(child);
4421 : }
4422 : }
4423 0 : (response, child_locations, waiters)
4424 0 : }
4425 0 : }
4426 :
4427 0 : async fn tenant_shard_split_start_secondaries(
4428 0 : &self,
4429 0 : tenant_id: TenantId,
4430 0 : waiters: Vec<ReconcilerWaiter>,
4431 0 : ) {
4432 : // Wait for initial reconcile of child shards, this creates the secondary locations
4433 0 : if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
4434 : // This is not a failure to split: it's some issue reconciling the new child shards, perhaps
4435 : // their secondaries couldn't be attached.
4436 0 : tracing::warn!("Failed to reconcile after split: {e}");
4437 0 : return;
4438 0 : }
4439 :
4440 : // Take the state lock to discover the attached & secondary intents for all shards
4441 0 : let (attached, secondary) = {
4442 0 : let locked = self.inner.read().unwrap();
4443 0 : let mut attached = Vec::new();
4444 0 : let mut secondary = Vec::new();
4445 :
4446 0 : for (tenant_shard_id, shard) in
4447 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
4448 : {
4449 0 : let Some(node_id) = shard.intent.get_attached() else {
4450 : // Unexpected. Race with a PlacementPolicy change?
4451 0 : tracing::warn!(
4452 0 : "No attached node on {tenant_shard_id} immediately after shard split!"
4453 : );
4454 0 : continue;
4455 : };
4456 :
4457 0 : let Some(secondary_node_id) = shard.intent.get_secondary().first() else {
4458 : // No secondary location. Nothing for us to do.
4459 0 : continue;
4460 : };
4461 :
4462 0 : let attached_node = locked
4463 0 : .nodes
4464 0 : .get(node_id)
4465 0 : .expect("Pageservers may not be deleted while referenced");
4466 0 :
4467 0 : let secondary_node = locked
4468 0 : .nodes
4469 0 : .get(secondary_node_id)
4470 0 : .expect("Pageservers may not be deleted while referenced");
4471 0 :
4472 0 : attached.push((*tenant_shard_id, attached_node.clone()));
4473 0 : secondary.push((*tenant_shard_id, secondary_node.clone()));
4474 : }
4475 0 : (attached, secondary)
4476 0 : };
4477 0 :
4478 0 : if secondary.is_empty() {
4479 : // No secondary locations; nothing for us to do
4480 0 : return;
4481 0 : }
4482 :
4483 0 : for result in self
4484 0 : .tenant_for_shards_api(
4485 0 : attached,
4486 0 : |tenant_shard_id, client| async move {
4487 0 : client.tenant_heatmap_upload(tenant_shard_id).await
4488 0 : },
4489 0 : 1,
4490 0 : 1,
4491 0 : SHORT_RECONCILE_TIMEOUT,
4492 0 : &self.cancel,
4493 0 : )
4494 0 : .await
4495 : {
4496 0 : if let Err(e) = result {
4497 0 : tracing::warn!("Error calling heatmap upload after shard split: {e}");
4498 0 : return;
4499 0 : }
4500 : }
4501 :
4502 0 : for result in self
4503 0 : .tenant_for_shards_api(
4504 0 : secondary,
4505 0 : |tenant_shard_id, client| async move {
4506 0 : client
4507 0 : .tenant_secondary_download(tenant_shard_id, Some(Duration::ZERO))
4508 0 : .await
4509 0 : },
4510 0 : 1,
4511 0 : 1,
4512 0 : SHORT_RECONCILE_TIMEOUT,
4513 0 : &self.cancel,
4514 0 : )
4515 0 : .await
4516 : {
4517 0 : if let Err(e) = result {
4518 0 : tracing::warn!("Error calling secondary download after shard split: {e}");
4519 0 : return;
4520 0 : }
4521 : }
4522 0 : }
4523 :
4524 0 : pub(crate) async fn tenant_shard_split(
4525 0 : &self,
4526 0 : tenant_id: TenantId,
4527 0 : split_req: TenantShardSplitRequest,
4528 0 : ) -> Result<TenantShardSplitResponse, ApiError> {
4529 : // TODO: return 503 if we get stuck waiting for this lock
4530 : // (issue https://github.com/neondatabase/neon/issues/7108)
4531 0 : let _tenant_lock = trace_exclusive_lock(
4532 0 : &self.tenant_op_locks,
4533 0 : tenant_id,
4534 0 : TenantOperations::ShardSplit,
4535 0 : )
4536 0 : .await;
4537 :
4538 0 : let new_shard_count = ShardCount::new(split_req.new_shard_count);
4539 0 : let new_stripe_size = split_req.new_stripe_size;
4540 :
4541 : // Validate the request and construct parameters. This phase is fallible, but does not require
4542 : // rollback on errors, as it does no I/O and mutates no state.
4543 0 : let shard_split_params = match self.prepare_tenant_shard_split(tenant_id, split_req)? {
4544 0 : ShardSplitAction::NoOp(resp) => return Ok(resp),
4545 0 : ShardSplitAction::Split(params) => params,
4546 : };
4547 :
4548 : // Execute this split: this phase mutates state and does remote I/O on pageservers. If it fails,
4549 : // we must roll back.
4550 0 : let r = self
4551 0 : .do_tenant_shard_split(tenant_id, shard_split_params)
4552 0 : .await;
4553 :
4554 0 : let (response, waiters) = match r {
4555 0 : Ok(r) => r,
4556 0 : Err(e) => {
4557 0 : // Split might be part-done, we must do work to abort it.
4558 0 : tracing::warn!("Enqueuing background abort of split on {tenant_id}");
4559 0 : self.abort_tx
4560 0 : .send(TenantShardSplitAbort {
4561 0 : tenant_id,
4562 0 : new_shard_count,
4563 0 : new_stripe_size,
4564 0 : _tenant_lock,
4565 0 : })
4566 0 : // Ignore error sending: that just means we're shutting down: aborts are ephemeral so it's fine to drop it.
4567 0 : .ok();
4568 0 : return Err(e);
4569 : }
4570 : };
4571 :
4572 : // The split is now complete. As an optimization, we will trigger all the child shards to upload
4573 : // a heatmap immediately, and all their secondary locations to start downloading: this avoids waiting
4574 : // for the background heatmap/download interval before secondaries get warm enough to migrate shards
4575 : // in [`Self::optimize_all`]
4576 0 : self.tenant_shard_split_start_secondaries(tenant_id, waiters)
4577 0 : .await;
4578 0 : Ok(response)
4579 0 : }
4580 :
4581 0 : fn prepare_tenant_shard_split(
4582 0 : &self,
4583 0 : tenant_id: TenantId,
4584 0 : split_req: TenantShardSplitRequest,
4585 0 : ) -> Result<ShardSplitAction, ApiError> {
4586 0 : fail::fail_point!("shard-split-validation", |_| Err(ApiError::BadRequest(
4587 0 : anyhow::anyhow!("failpoint")
4588 0 : )));
4589 :
4590 0 : let mut policy = None;
4591 0 : let mut config = None;
4592 0 : let mut shard_ident = None;
4593 0 : let mut preferred_az_id = None;
4594 : // Validate input, and calculate which shards we will create
4595 0 : let (old_shard_count, targets) =
4596 : {
4597 0 : let locked = self.inner.read().unwrap();
4598 0 :
4599 0 : let pageservers = locked.nodes.clone();
4600 0 :
4601 0 : let mut targets = Vec::new();
4602 0 :
4603 0 : // In case this is a retry, count how many already-split shards we found
4604 0 : let mut children_found = Vec::new();
4605 0 : let mut old_shard_count = None;
4606 :
4607 0 : for (tenant_shard_id, shard) in
4608 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
4609 : {
4610 0 : match shard.shard.count.count().cmp(&split_req.new_shard_count) {
4611 : Ordering::Equal => {
4612 : // Already split this
4613 0 : children_found.push(*tenant_shard_id);
4614 0 : continue;
4615 : }
4616 : Ordering::Greater => {
4617 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
4618 0 : "Requested count {} but already have shards at count {}",
4619 0 : split_req.new_shard_count,
4620 0 : shard.shard.count.count()
4621 0 : )));
4622 : }
4623 0 : Ordering::Less => {
4624 0 : // Fall through: this shard has lower count than requested,
4625 0 : // is a candidate for splitting.
4626 0 : }
4627 0 : }
4628 0 :
4629 0 : match old_shard_count {
4630 0 : None => old_shard_count = Some(shard.shard.count),
4631 0 : Some(old_shard_count) => {
4632 0 : if old_shard_count != shard.shard.count {
4633 : // We may hit this case if a caller asked for two splits to
4634 : // different sizes, before the first one is complete.
4635 : // e.g. 1->2, 2->4, where the 4 call comes while we have a mixture
4636 : // of shard_count=1 and shard_count=2 shards in the map.
4637 0 : return Err(ApiError::Conflict(
4638 0 : "Cannot split, currently mid-split".to_string(),
4639 0 : ));
4640 0 : }
4641 : }
4642 : }
4643 0 : if policy.is_none() {
4644 0 : policy = Some(shard.policy.clone());
4645 0 : }
4646 0 : if shard_ident.is_none() {
4647 0 : shard_ident = Some(shard.shard);
4648 0 : }
4649 0 : if config.is_none() {
4650 0 : config = Some(shard.config.clone());
4651 0 : }
4652 0 : if preferred_az_id.is_none() {
4653 0 : preferred_az_id = shard.preferred_az().cloned();
4654 0 : }
4655 :
4656 0 : if tenant_shard_id.shard_count.count() == split_req.new_shard_count {
4657 0 : tracing::info!(
4658 0 : "Tenant shard {} already has shard count {}",
4659 : tenant_shard_id,
4660 : split_req.new_shard_count
4661 : );
4662 0 : continue;
4663 0 : }
4664 :
4665 0 : let node_id = shard.intent.get_attached().ok_or(ApiError::BadRequest(
4666 0 : anyhow::anyhow!("Cannot split a tenant that is not attached"),
4667 0 : ))?;
4668 :
4669 0 : let node = pageservers
4670 0 : .get(&node_id)
4671 0 : .expect("Pageservers may not be deleted while referenced");
4672 0 :
4673 0 : targets.push(ShardSplitTarget {
4674 0 : parent_id: *tenant_shard_id,
4675 0 : node: node.clone(),
4676 0 : child_ids: tenant_shard_id
4677 0 : .split(ShardCount::new(split_req.new_shard_count)),
4678 0 : });
4679 : }
4680 :
4681 0 : if targets.is_empty() {
4682 0 : if children_found.len() == split_req.new_shard_count as usize {
4683 0 : return Ok(ShardSplitAction::NoOp(TenantShardSplitResponse {
4684 0 : new_shards: children_found,
4685 0 : }));
4686 : } else {
4687 : // No shards found to split, and no existing children found: the
4688 : // tenant doesn't exist at all.
4689 0 : return Err(ApiError::NotFound(
4690 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
4691 0 : ));
4692 : }
4693 0 : }
4694 0 :
4695 0 : (old_shard_count, targets)
4696 0 : };
4697 0 :
4698 0 : // unwrap safety: we would have returned above if we didn't find at least one shard to split
4699 0 : let old_shard_count = old_shard_count.unwrap();
4700 0 : let shard_ident = if let Some(new_stripe_size) = split_req.new_stripe_size {
4701 : // This ShardIdentity will be used as the template for all children, so this implicitly
4702 : // applies the new stripe size to the children.
4703 0 : let mut shard_ident = shard_ident.unwrap();
4704 0 : if shard_ident.count.count() > 1 && shard_ident.stripe_size != new_stripe_size {
4705 0 : return Err(ApiError::BadRequest(anyhow::anyhow!("Attempted to change stripe size ({:?}->{new_stripe_size:?}) on a tenant with multiple shards", shard_ident.stripe_size)));
4706 0 : }
4707 0 :
4708 0 : shard_ident.stripe_size = new_stripe_size;
4709 0 : tracing::info!("applied stripe size {}", shard_ident.stripe_size.0);
4710 0 : shard_ident
4711 : } else {
4712 0 : shard_ident.unwrap()
4713 : };
4714 0 : let policy = policy.unwrap();
4715 0 : let config = config.unwrap();
4716 0 :
4717 0 : Ok(ShardSplitAction::Split(Box::new(ShardSplitParams {
4718 0 : old_shard_count,
4719 0 : new_shard_count: ShardCount::new(split_req.new_shard_count),
4720 0 : new_stripe_size: split_req.new_stripe_size,
4721 0 : targets,
4722 0 : policy,
4723 0 : config,
4724 0 : shard_ident,
4725 0 : preferred_az_id,
4726 0 : })))
4727 0 : }
4728 :
4729 0 : async fn do_tenant_shard_split(
4730 0 : &self,
4731 0 : tenant_id: TenantId,
4732 0 : params: Box<ShardSplitParams>,
4733 0 : ) -> Result<(TenantShardSplitResponse, Vec<ReconcilerWaiter>), ApiError> {
4734 0 : // FIXME: we have dropped self.inner lock, and not yet written anything to the database: another
4735 0 : // request could occur here, deleting or mutating the tenant. begin_shard_split checks that the
4736 0 : // parent shards exist as expected, but it would be neater to do the above pre-checks within the
4737 0 : // same database transaction rather than pre-check in-memory and then maybe-fail the database write.
4738 0 : // (https://github.com/neondatabase/neon/issues/6676)
4739 0 :
4740 0 : let ShardSplitParams {
4741 0 : old_shard_count,
4742 0 : new_shard_count,
4743 0 : new_stripe_size,
4744 0 : mut targets,
4745 0 : policy,
4746 0 : config,
4747 0 : shard_ident,
4748 0 : preferred_az_id,
4749 0 : } = *params;
4750 :
4751 : // Drop any secondary locations: pageservers do not support splitting these, and in any case the
4752 : // end-state for a split tenant will usually be to have secondary locations on different nodes.
4753 : // The reconciliation calls in this block also implicitly cancel+barrier wrt any ongoing reconciliation
4754 : // at the time of split.
4755 0 : let waiters = {
4756 0 : let mut locked = self.inner.write().unwrap();
4757 0 : let mut waiters = Vec::new();
4758 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
4759 0 : for target in &mut targets {
4760 0 : let Some(shard) = tenants.get_mut(&target.parent_id) else {
4761 : // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
4762 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
4763 0 : "Shard {} not found",
4764 0 : target.parent_id
4765 0 : )));
4766 : };
4767 :
4768 0 : if shard.intent.get_attached() != &Some(target.node.get_id()) {
4769 : // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
4770 0 : return Err(ApiError::Conflict(format!(
4771 0 : "Shard {} unexpectedly rescheduled during split",
4772 0 : target.parent_id
4773 0 : )));
4774 0 : }
4775 0 :
4776 0 : // Irrespective of PlacementPolicy, clear secondary locations from intent
4777 0 : shard.intent.clear_secondary(scheduler);
4778 :
4779 : // Run Reconciler to execute detach fo secondary locations.
4780 0 : if let Some(waiter) = self.maybe_reconcile_shard(shard, nodes) {
4781 0 : waiters.push(waiter);
4782 0 : }
4783 : }
4784 0 : waiters
4785 0 : };
4786 0 : self.await_waiters(waiters, RECONCILE_TIMEOUT).await?;
4787 :
4788 : // Before creating any new child shards in memory or on the pageservers, persist them: this
4789 : // enables us to ensure that we will always be able to clean up if something goes wrong. This also
4790 : // acts as the protection against two concurrent attempts to split: one of them will get a database
4791 : // error trying to insert the child shards.
4792 0 : let mut child_tsps = Vec::new();
4793 0 : for target in &targets {
4794 0 : let mut this_child_tsps = Vec::new();
4795 0 : for child in &target.child_ids {
4796 0 : let mut child_shard = shard_ident;
4797 0 : child_shard.number = child.shard_number;
4798 0 : child_shard.count = child.shard_count;
4799 0 :
4800 0 : tracing::info!(
4801 0 : "Create child shard persistence with stripe size {}",
4802 : shard_ident.stripe_size.0
4803 : );
4804 :
4805 0 : this_child_tsps.push(TenantShardPersistence {
4806 0 : tenant_id: child.tenant_id.to_string(),
4807 0 : shard_number: child.shard_number.0 as i32,
4808 0 : shard_count: child.shard_count.literal() as i32,
4809 0 : shard_stripe_size: shard_ident.stripe_size.0 as i32,
4810 0 : // Note: this generation is a placeholder, [`Persistence::begin_shard_split`] will
4811 0 : // populate the correct generation as part of its transaction, to protect us
4812 0 : // against racing with changes in the state of the parent.
4813 0 : generation: None,
4814 0 : generation_pageserver: Some(target.node.get_id().0 as i64),
4815 0 : placement_policy: serde_json::to_string(&policy).unwrap(),
4816 0 : config: serde_json::to_string(&config).unwrap(),
4817 0 : splitting: SplitState::Splitting,
4818 0 :
4819 0 : // Scheduling policies and preferred AZ do not carry through to children
4820 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
4821 0 : .unwrap(),
4822 0 : preferred_az_id: preferred_az_id.as_ref().map(|az| az.0.clone()),
4823 0 : });
4824 0 : }
4825 :
4826 0 : child_tsps.push((target.parent_id, this_child_tsps));
4827 : }
4828 :
4829 0 : if let Err(e) = self
4830 0 : .persistence
4831 0 : .begin_shard_split(old_shard_count, tenant_id, child_tsps)
4832 0 : .await
4833 : {
4834 0 : match e {
4835 : DatabaseError::Query(diesel::result::Error::DatabaseError(
4836 : DatabaseErrorKind::UniqueViolation,
4837 : _,
4838 : )) => {
4839 : // Inserting a child shard violated a unique constraint: we raced with another call to
4840 : // this function
4841 0 : tracing::warn!("Conflicting attempt to split {tenant_id}: {e}");
4842 0 : return Err(ApiError::Conflict("Tenant is already splitting".into()));
4843 : }
4844 0 : _ => return Err(ApiError::InternalServerError(e.into())),
4845 : }
4846 0 : }
4847 0 : fail::fail_point!("shard-split-post-begin", |_| Err(
4848 0 : ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
4849 0 : ));
4850 :
4851 : // Now that I have persisted the splitting state, apply it in-memory. This is infallible, so
4852 : // callers may assume that if splitting is set in memory, then it was persisted, and if splitting
4853 : // is not set in memory, then it was not persisted.
4854 : {
4855 0 : let mut locked = self.inner.write().unwrap();
4856 0 : for target in &targets {
4857 0 : if let Some(parent_shard) = locked.tenants.get_mut(&target.parent_id) {
4858 0 : parent_shard.splitting = SplitState::Splitting;
4859 0 : // Put the observed state to None, to reflect that it is indeterminate once we start the
4860 0 : // split operation.
4861 0 : parent_shard
4862 0 : .observed
4863 0 : .locations
4864 0 : .insert(target.node.get_id(), ObservedStateLocation { conf: None });
4865 0 : }
4866 : }
4867 : }
4868 :
4869 : // TODO: issue split calls concurrently (this only matters once we're splitting
4870 : // N>1 shards into M shards -- initially we're usually splitting 1 shard into N).
4871 :
4872 0 : for target in &targets {
4873 : let ShardSplitTarget {
4874 0 : parent_id,
4875 0 : node,
4876 0 : child_ids,
4877 0 : } = target;
4878 0 : let client = PageserverClient::new(
4879 0 : node.get_id(),
4880 0 : node.base_url(),
4881 0 : self.config.jwt_token.as_deref(),
4882 0 : );
4883 0 : let response = client
4884 0 : .tenant_shard_split(
4885 0 : *parent_id,
4886 0 : TenantShardSplitRequest {
4887 0 : new_shard_count: new_shard_count.literal(),
4888 0 : new_stripe_size,
4889 0 : },
4890 0 : )
4891 0 : .await
4892 0 : .map_err(|e| ApiError::Conflict(format!("Failed to split {}: {}", parent_id, e)))?;
4893 :
4894 0 : fail::fail_point!("shard-split-post-remote", |_| Err(ApiError::Conflict(
4895 0 : "failpoint".to_string()
4896 0 : )));
4897 :
4898 0 : failpoint_support::sleep_millis_async!("shard-split-post-remote-sleep", &self.cancel);
4899 :
4900 0 : tracing::info!(
4901 0 : "Split {} into {}",
4902 0 : parent_id,
4903 0 : response
4904 0 : .new_shards
4905 0 : .iter()
4906 0 : .map(|s| format!("{:?}", s))
4907 0 : .collect::<Vec<_>>()
4908 0 : .join(",")
4909 : );
4910 :
4911 0 : if &response.new_shards != child_ids {
4912 : // This should never happen: the pageserver should agree with us on how shard splits work.
4913 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
4914 0 : "Splitting shard {} resulted in unexpected IDs: {:?} (expected {:?})",
4915 0 : parent_id,
4916 0 : response.new_shards,
4917 0 : child_ids
4918 0 : )));
4919 0 : }
4920 : }
4921 :
4922 : // TODO: if the pageserver restarted concurrently with our split API call,
4923 : // the actual generation of the child shard might differ from the generation
4924 : // we expect it to have. In order for our in-database generation to end up
4925 : // correct, we should carry the child generation back in the response and apply it here
4926 : // in complete_shard_split (and apply the correct generation in memory)
4927 : // (or, we can carry generation in the request and reject the request if
4928 : // it doesn't match, but that requires more retry logic on this side)
4929 :
4930 0 : self.persistence
4931 0 : .complete_shard_split(tenant_id, old_shard_count)
4932 0 : .await?;
4933 :
4934 0 : fail::fail_point!("shard-split-post-complete", |_| Err(
4935 0 : ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
4936 0 : ));
4937 :
4938 : // Replace all the shards we just split with their children: this phase is infallible.
4939 0 : let (response, child_locations, waiters) =
4940 0 : self.tenant_shard_split_commit_inmem(tenant_id, new_shard_count, new_stripe_size);
4941 0 :
4942 0 : // Send compute notifications for all the new shards
4943 0 : let mut failed_notifications = Vec::new();
4944 0 : for (child_id, child_ps, stripe_size) in child_locations {
4945 0 : if let Err(e) = self
4946 0 : .compute_hook
4947 0 : .notify(
4948 0 : compute_hook::ShardUpdate {
4949 0 : tenant_shard_id: child_id,
4950 0 : node_id: child_ps,
4951 0 : stripe_size,
4952 0 : preferred_az: preferred_az_id.as_ref().map(Cow::Borrowed),
4953 0 : },
4954 0 : &self.cancel,
4955 0 : )
4956 0 : .await
4957 : {
4958 0 : tracing::warn!("Failed to update compute of {}->{} during split, proceeding anyway to complete split ({e})",
4959 : child_id, child_ps);
4960 0 : failed_notifications.push(child_id);
4961 0 : }
4962 : }
4963 :
4964 : // If we failed any compute notifications, make a note to retry later.
4965 0 : if !failed_notifications.is_empty() {
4966 0 : let mut locked = self.inner.write().unwrap();
4967 0 : for failed in failed_notifications {
4968 0 : if let Some(shard) = locked.tenants.get_mut(&failed) {
4969 0 : shard.pending_compute_notification = true;
4970 0 : }
4971 : }
4972 0 : }
4973 :
4974 0 : Ok((response, waiters))
4975 0 : }
4976 :
4977 0 : pub(crate) async fn tenant_shard_migrate(
4978 0 : &self,
4979 0 : tenant_shard_id: TenantShardId,
4980 0 : migrate_req: TenantShardMigrateRequest,
4981 0 : ) -> Result<TenantShardMigrateResponse, ApiError> {
4982 0 : let waiter = {
4983 0 : let mut locked = self.inner.write().unwrap();
4984 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
4985 :
4986 0 : let Some(node) = nodes.get(&migrate_req.node_id) else {
4987 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
4988 0 : "Node {} not found",
4989 0 : migrate_req.node_id
4990 0 : )));
4991 : };
4992 :
4993 0 : if !node.is_available() {
4994 : // Warn but proceed: the caller may intend to manually adjust the placement of
4995 : // a shard even if the node is down, e.g. if intervening during an incident.
4996 0 : tracing::warn!("Migrating to unavailable node {node}");
4997 0 : }
4998 :
4999 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
5000 0 : return Err(ApiError::NotFound(
5001 0 : anyhow::anyhow!("Tenant shard not found").into(),
5002 0 : ));
5003 : };
5004 :
5005 0 : if shard.intent.get_attached() == &Some(migrate_req.node_id) {
5006 : // No-op case: we will still proceed to wait for reconciliation in case it is
5007 : // incomplete from an earlier update to the intent.
5008 0 : tracing::info!("Migrating: intent is unchanged {:?}", shard.intent);
5009 : } else {
5010 0 : let old_attached = *shard.intent.get_attached();
5011 0 :
5012 0 : match shard.policy {
5013 0 : PlacementPolicy::Attached(n) => {
5014 0 : // If our new attached node was a secondary, it no longer should be.
5015 0 : shard.intent.remove_secondary(scheduler, migrate_req.node_id);
5016 :
5017 : // If we were already attached to something, demote that to a secondary
5018 0 : if let Some(old_attached) = old_attached {
5019 0 : if n > 0 {
5020 : // Remove other secondaries to make room for the location we'll demote
5021 0 : while shard.intent.get_secondary().len() >= n {
5022 0 : shard.intent.pop_secondary(scheduler);
5023 0 : }
5024 :
5025 0 : shard.intent.push_secondary(scheduler, old_attached);
5026 0 : }
5027 0 : }
5028 :
5029 0 : shard.intent.set_attached(scheduler, Some(migrate_req.node_id));
5030 : }
5031 0 : PlacementPolicy::Secondary => {
5032 0 : shard.intent.clear(scheduler);
5033 0 : shard.intent.push_secondary(scheduler, migrate_req.node_id);
5034 0 : }
5035 : PlacementPolicy::Detached => {
5036 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
5037 0 : "Cannot migrate a tenant that is PlacementPolicy::Detached: configure it to an attached policy first"
5038 0 : )))
5039 : }
5040 : }
5041 :
5042 0 : tracing::info!("Migrating: new intent {:?}", shard.intent);
5043 0 : shard.sequence = shard.sequence.next();
5044 : }
5045 :
5046 0 : self.maybe_reconcile_shard(shard, nodes)
5047 : };
5048 :
5049 0 : if let Some(waiter) = waiter {
5050 0 : waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
5051 : } else {
5052 0 : tracing::info!("Migration is a no-op");
5053 : }
5054 :
5055 0 : Ok(TenantShardMigrateResponse {})
5056 0 : }
5057 :
5058 : /// 'cancel' in this context means cancel any ongoing reconcile
5059 0 : pub(crate) async fn tenant_shard_cancel_reconcile(
5060 0 : &self,
5061 0 : tenant_shard_id: TenantShardId,
5062 0 : ) -> Result<(), ApiError> {
5063 : // Take state lock and fire the cancellation token, after which we drop lock and wait for any ongoing reconcile to complete
5064 0 : let waiter = {
5065 0 : let locked = self.inner.write().unwrap();
5066 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
5067 0 : return Err(ApiError::NotFound(
5068 0 : anyhow::anyhow!("Tenant shard not found").into(),
5069 0 : ));
5070 : };
5071 :
5072 0 : let waiter = shard.get_waiter();
5073 0 : match waiter {
5074 : None => {
5075 0 : tracing::info!("Shard does not have an ongoing Reconciler");
5076 0 : return Ok(());
5077 : }
5078 0 : Some(waiter) => {
5079 0 : tracing::info!("Cancelling Reconciler");
5080 0 : shard.cancel_reconciler();
5081 0 : waiter
5082 0 : }
5083 0 : }
5084 0 : };
5085 0 :
5086 0 : // Cancellation should be prompt. If this fails we have still done our job of firing the
5087 0 : // cancellation token, but by returning an ApiError we will indicate to the caller that
5088 0 : // the Reconciler is misbehaving and not respecting the cancellation token
5089 0 : self.await_waiters(vec![waiter], SHORT_RECONCILE_TIMEOUT)
5090 0 : .await?;
5091 :
5092 0 : Ok(())
5093 0 : }
5094 :
5095 : /// This is for debug/support only: we simply drop all state for a tenant, without
5096 : /// detaching or deleting it on pageservers.
5097 0 : pub(crate) async fn tenant_drop(&self, tenant_id: TenantId) -> Result<(), ApiError> {
5098 0 : self.persistence.delete_tenant(tenant_id).await?;
5099 :
5100 0 : let mut locked = self.inner.write().unwrap();
5101 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
5102 0 : let mut shards = Vec::new();
5103 0 : for (tenant_shard_id, _) in tenants.range(TenantShardId::tenant_range(tenant_id)) {
5104 0 : shards.push(*tenant_shard_id);
5105 0 : }
5106 :
5107 0 : for shard_id in shards {
5108 0 : if let Some(mut shard) = tenants.remove(&shard_id) {
5109 0 : shard.intent.clear(scheduler);
5110 0 : }
5111 : }
5112 :
5113 0 : Ok(())
5114 0 : }
5115 :
5116 : /// This is for debug/support only: assuming tenant data is already present in S3, we "create" a
5117 : /// tenant with a very high generation number so that it will see the existing data.
5118 0 : pub(crate) async fn tenant_import(
5119 0 : &self,
5120 0 : tenant_id: TenantId,
5121 0 : ) -> Result<TenantCreateResponse, ApiError> {
5122 0 : // Pick an arbitrary available pageserver to use for scanning the tenant in remote storage
5123 0 : let maybe_node = {
5124 0 : self.inner
5125 0 : .read()
5126 0 : .unwrap()
5127 0 : .nodes
5128 0 : .values()
5129 0 : .find(|n| n.is_available())
5130 0 : .cloned()
5131 : };
5132 0 : let Some(node) = maybe_node else {
5133 0 : return Err(ApiError::BadRequest(anyhow::anyhow!("No nodes available")));
5134 : };
5135 :
5136 0 : let client = PageserverClient::new(
5137 0 : node.get_id(),
5138 0 : node.base_url(),
5139 0 : self.config.jwt_token.as_deref(),
5140 0 : );
5141 :
5142 0 : let scan_result = client
5143 0 : .tenant_scan_remote_storage(tenant_id)
5144 0 : .await
5145 0 : .map_err(|e| passthrough_api_error(&node, e))?;
5146 :
5147 : // A post-split tenant may contain a mixture of shard counts in remote storage: pick the highest count.
5148 0 : let Some(shard_count) = scan_result
5149 0 : .shards
5150 0 : .iter()
5151 0 : .map(|s| s.tenant_shard_id.shard_count)
5152 0 : .max()
5153 : else {
5154 0 : return Err(ApiError::NotFound(
5155 0 : anyhow::anyhow!("No shards found").into(),
5156 0 : ));
5157 : };
5158 :
5159 : // Ideally we would set each newly imported shard's generation independently, but for correctness it is sufficient
5160 : // to
5161 0 : let generation = scan_result
5162 0 : .shards
5163 0 : .iter()
5164 0 : .map(|s| s.generation)
5165 0 : .max()
5166 0 : .expect("We already validated >0 shards");
5167 0 :
5168 0 : // FIXME: we have no way to recover the shard stripe size from contents of remote storage: this will
5169 0 : // only work if they were using the default stripe size.
5170 0 : let stripe_size = ShardParameters::DEFAULT_STRIPE_SIZE;
5171 :
5172 0 : let (response, waiters) = self
5173 0 : .do_tenant_create(TenantCreateRequest {
5174 0 : new_tenant_id: TenantShardId::unsharded(tenant_id),
5175 0 : generation,
5176 0 :
5177 0 : shard_parameters: ShardParameters {
5178 0 : count: shard_count,
5179 0 : stripe_size,
5180 0 : },
5181 0 : placement_policy: Some(PlacementPolicy::Attached(0)), // No secondaries, for convenient debug/hacking
5182 0 : config: TenantConfig::default(),
5183 0 : })
5184 0 : .await?;
5185 :
5186 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
5187 : // Since this is a debug/support operation, all kinds of weird issues are possible (e.g. this
5188 : // tenant doesn't exist in the control plane), so don't fail the request if it can't fully
5189 : // reconcile, as reconciliation includes notifying compute.
5190 0 : tracing::warn!(%tenant_id, "Reconcile not done yet while importing tenant ({e})");
5191 0 : }
5192 :
5193 0 : Ok(response)
5194 0 : }
5195 :
5196 : /// For debug/support: a full JSON dump of TenantShards. Returns a response so that
5197 : /// we don't have to make TenantShard clonable in the return path.
5198 0 : pub(crate) fn tenants_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
5199 0 : let serialized = {
5200 0 : let locked = self.inner.read().unwrap();
5201 0 : let result = locked.tenants.values().collect::<Vec<_>>();
5202 0 : serde_json::to_string(&result).map_err(|e| ApiError::InternalServerError(e.into()))?
5203 : };
5204 :
5205 0 : hyper::Response::builder()
5206 0 : .status(hyper::StatusCode::OK)
5207 0 : .header(hyper::header::CONTENT_TYPE, "application/json")
5208 0 : .body(hyper::Body::from(serialized))
5209 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
5210 0 : }
5211 :
5212 : /// Check the consistency of in-memory state vs. persistent state, and check that the
5213 : /// scheduler's statistics are up to date.
5214 : ///
5215 : /// These consistency checks expect an **idle** system. If changes are going on while
5216 : /// we run, then we can falsely indicate a consistency issue. This is sufficient for end-of-test
5217 : /// checks, but not suitable for running continuously in the background in the field.
5218 0 : pub(crate) async fn consistency_check(&self) -> Result<(), ApiError> {
5219 0 : let (mut expect_nodes, mut expect_shards) = {
5220 0 : let locked = self.inner.read().unwrap();
5221 0 :
5222 0 : locked
5223 0 : .scheduler
5224 0 : .consistency_check(locked.nodes.values(), locked.tenants.values())
5225 0 : .context("Scheduler checks")
5226 0 : .map_err(ApiError::InternalServerError)?;
5227 :
5228 0 : let expect_nodes = locked
5229 0 : .nodes
5230 0 : .values()
5231 0 : .map(|n| n.to_persistent())
5232 0 : .collect::<Vec<_>>();
5233 0 :
5234 0 : let expect_shards = locked
5235 0 : .tenants
5236 0 : .values()
5237 0 : .map(|t| t.to_persistent())
5238 0 : .collect::<Vec<_>>();
5239 :
5240 : // This method can only validate the state of an idle system: if a reconcile is in
5241 : // progress, fail out early to avoid giving false errors on state that won't match
5242 : // between database and memory under a ReconcileResult is processed.
5243 0 : for t in locked.tenants.values() {
5244 0 : if t.reconciler.is_some() {
5245 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5246 0 : "Shard {} reconciliation in progress",
5247 0 : t.tenant_shard_id
5248 0 : )));
5249 0 : }
5250 : }
5251 :
5252 0 : (expect_nodes, expect_shards)
5253 : };
5254 :
5255 0 : let mut nodes = self.persistence.list_nodes().await?;
5256 0 : expect_nodes.sort_by_key(|n| n.node_id);
5257 0 : nodes.sort_by_key(|n| n.node_id);
5258 0 :
5259 0 : if nodes != expect_nodes {
5260 0 : tracing::error!("Consistency check failed on nodes.");
5261 0 : tracing::error!(
5262 0 : "Nodes in memory: {}",
5263 0 : serde_json::to_string(&expect_nodes)
5264 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5265 : );
5266 0 : tracing::error!(
5267 0 : "Nodes in database: {}",
5268 0 : serde_json::to_string(&nodes)
5269 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5270 : );
5271 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5272 0 : "Node consistency failure"
5273 0 : )));
5274 0 : }
5275 :
5276 0 : let mut persistent_shards = self.persistence.load_active_tenant_shards().await?;
5277 0 : persistent_shards
5278 0 : .sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
5279 0 :
5280 0 : expect_shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
5281 0 :
5282 0 : if persistent_shards != expect_shards {
5283 0 : tracing::error!("Consistency check failed on shards.");
5284 0 : tracing::error!(
5285 0 : "Shards in memory: {}",
5286 0 : serde_json::to_string(&expect_shards)
5287 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5288 : );
5289 0 : tracing::error!(
5290 0 : "Shards in database: {}",
5291 0 : serde_json::to_string(&persistent_shards)
5292 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5293 : );
5294 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5295 0 : "Shard consistency failure"
5296 0 : )));
5297 0 : }
5298 0 :
5299 0 : Ok(())
5300 0 : }
5301 :
5302 : /// For debug/support: a JSON dump of the [`Scheduler`]. Returns a response so that
5303 : /// we don't have to make TenantShard clonable in the return path.
5304 0 : pub(crate) fn scheduler_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
5305 0 : let serialized = {
5306 0 : let locked = self.inner.read().unwrap();
5307 0 : serde_json::to_string(&locked.scheduler)
5308 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5309 : };
5310 :
5311 0 : hyper::Response::builder()
5312 0 : .status(hyper::StatusCode::OK)
5313 0 : .header(hyper::header::CONTENT_TYPE, "application/json")
5314 0 : .body(hyper::Body::from(serialized))
5315 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
5316 0 : }
5317 :
5318 : /// This is for debug/support only: we simply drop all state for a tenant, without
5319 : /// detaching or deleting it on pageservers. We do not try and re-schedule any
5320 : /// tenants that were on this node.
5321 0 : pub(crate) async fn node_drop(&self, node_id: NodeId) -> Result<(), ApiError> {
5322 0 : self.persistence.delete_node(node_id).await?;
5323 :
5324 0 : let mut locked = self.inner.write().unwrap();
5325 :
5326 0 : for shard in locked.tenants.values_mut() {
5327 0 : shard.deref_node(node_id);
5328 0 : shard.observed.locations.remove(&node_id);
5329 0 : }
5330 :
5331 0 : let mut nodes = (*locked.nodes).clone();
5332 0 : nodes.remove(&node_id);
5333 0 : locked.nodes = Arc::new(nodes);
5334 0 : metrics::METRICS_REGISTRY
5335 0 : .metrics_group
5336 0 : .storage_controller_pageserver_nodes
5337 0 : .set(locked.nodes.len() as i64);
5338 0 :
5339 0 : locked.scheduler.node_remove(node_id);
5340 0 :
5341 0 : Ok(())
5342 0 : }
5343 :
5344 : /// If a node has any work on it, it will be rescheduled: this is "clean" in the sense
5345 : /// that we don't leave any bad state behind in the storage controller, but unclean
5346 : /// in the sense that we are not carefully draining the node.
5347 0 : pub(crate) async fn node_delete(&self, node_id: NodeId) -> Result<(), ApiError> {
5348 0 : let _node_lock =
5349 0 : trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Delete).await;
5350 :
5351 : // 1. Atomically update in-memory state:
5352 : // - set the scheduling state to Pause to make subsequent scheduling ops skip it
5353 : // - update shards' intents to exclude the node, and reschedule any shards whose intents we modified.
5354 : // - drop the node from the main nodes map, so that when running reconciles complete they do not
5355 : // re-insert references to this node into the ObservedState of shards
5356 : // - drop the node from the scheduler
5357 : {
5358 0 : let mut locked = self.inner.write().unwrap();
5359 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
5360 0 :
5361 0 : {
5362 0 : let mut nodes_mut = (*nodes).deref().clone();
5363 0 : match nodes_mut.get_mut(&node_id) {
5364 0 : Some(node) => {
5365 0 : // We do not bother setting this in the database, because we're about to delete the row anyway, and
5366 0 : // if we crash it would not be desirable to leave the node paused after a restart.
5367 0 : node.set_scheduling(NodeSchedulingPolicy::Pause);
5368 0 : }
5369 : None => {
5370 0 : tracing::info!(
5371 0 : "Node not found: presuming this is a retry and returning success"
5372 : );
5373 0 : return Ok(());
5374 : }
5375 : }
5376 :
5377 0 : *nodes = Arc::new(nodes_mut);
5378 : }
5379 :
5380 0 : for (_tenant_id, mut schedule_context, shards) in
5381 0 : TenantShardContextIterator::new(tenants, ScheduleMode::Normal)
5382 : {
5383 0 : for shard in shards {
5384 0 : if shard.deref_node(node_id) {
5385 0 : if let Err(e) = shard.schedule(scheduler, &mut schedule_context) {
5386 : // TODO: implement force flag to remove a node even if we can't reschedule
5387 : // a tenant
5388 0 : tracing::error!(
5389 0 : "Refusing to delete node, shard {} can't be rescheduled: {e}",
5390 : shard.tenant_shard_id
5391 : );
5392 0 : return Err(e.into());
5393 : } else {
5394 0 : tracing::info!(
5395 0 : "Rescheduled shard {} away from node during deletion",
5396 : shard.tenant_shard_id
5397 : )
5398 : }
5399 :
5400 0 : self.maybe_reconcile_shard(shard, nodes);
5401 0 : }
5402 :
5403 : // Here we remove an existing observed location for the node we're removing, and it will
5404 : // not be re-added by a reconciler's completion because we filter out removed nodes in
5405 : // process_result.
5406 : //
5407 : // Note that we update the shard's observed state _after_ calling maybe_reconcile_shard: that
5408 : // means any reconciles we spawned will know about the node we're deleting, enabling them
5409 : // to do live migrations if it's still online.
5410 0 : shard.observed.locations.remove(&node_id);
5411 : }
5412 : }
5413 :
5414 0 : scheduler.node_remove(node_id);
5415 0 :
5416 0 : {
5417 0 : let mut nodes_mut = (**nodes).clone();
5418 0 : if let Some(mut removed_node) = nodes_mut.remove(&node_id) {
5419 0 : // Ensure that any reconciler holding an Arc<> to this node will
5420 0 : // drop out when trying to RPC to it (setting Offline state sets the
5421 0 : // cancellation token on the Node object).
5422 0 : removed_node.set_availability(NodeAvailability::Offline);
5423 0 : }
5424 0 : *nodes = Arc::new(nodes_mut);
5425 0 : metrics::METRICS_REGISTRY
5426 0 : .metrics_group
5427 0 : .storage_controller_pageserver_nodes
5428 0 : .set(nodes.len() as i64);
5429 0 : }
5430 0 : }
5431 0 :
5432 0 : // Note: some `generation_pageserver` columns on tenant shards in the database may still refer to
5433 0 : // the removed node, as this column means "The pageserver to which this generation was issued", and
5434 0 : // their generations won't get updated until the reconcilers moving them away from this node complete.
5435 0 : // That is safe because in Service::spawn we only use generation_pageserver if it refers to a node
5436 0 : // that exists.
5437 0 :
5438 0 : // 2. Actually delete the node from the database and from in-memory state
5439 0 : tracing::info!("Deleting node from database");
5440 0 : self.persistence.delete_node(node_id).await?;
5441 :
5442 0 : Ok(())
5443 0 : }
5444 :
5445 0 : pub(crate) async fn node_list(&self) -> Result<Vec<Node>, ApiError> {
5446 0 : let nodes = {
5447 0 : self.inner
5448 0 : .read()
5449 0 : .unwrap()
5450 0 : .nodes
5451 0 : .values()
5452 0 : .cloned()
5453 0 : .collect::<Vec<_>>()
5454 0 : };
5455 0 :
5456 0 : Ok(nodes)
5457 0 : }
5458 :
5459 0 : pub(crate) async fn get_node(&self, node_id: NodeId) -> Result<Node, ApiError> {
5460 0 : self.inner
5461 0 : .read()
5462 0 : .unwrap()
5463 0 : .nodes
5464 0 : .get(&node_id)
5465 0 : .cloned()
5466 0 : .ok_or(ApiError::NotFound(
5467 0 : format!("Node {node_id} not registered").into(),
5468 0 : ))
5469 0 : }
5470 :
5471 0 : pub(crate) async fn get_node_shards(
5472 0 : &self,
5473 0 : node_id: NodeId,
5474 0 : ) -> Result<NodeShardResponse, ApiError> {
5475 0 : let locked = self.inner.read().unwrap();
5476 0 : let mut shards = Vec::new();
5477 0 : for (tid, tenant) in locked.tenants.iter() {
5478 0 : let is_intended_secondary = match (
5479 0 : tenant.intent.get_attached() == &Some(node_id),
5480 0 : tenant.intent.get_secondary().contains(&node_id),
5481 0 : ) {
5482 : (true, true) => {
5483 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5484 0 : "{} attached as primary+secondary on the same node",
5485 0 : tid
5486 0 : )))
5487 : }
5488 0 : (true, false) => Some(false),
5489 0 : (false, true) => Some(true),
5490 0 : (false, false) => None,
5491 : };
5492 0 : let is_observed_secondary = if let Some(ObservedStateLocation { conf: Some(conf) }) =
5493 0 : tenant.observed.locations.get(&node_id)
5494 : {
5495 0 : Some(conf.secondary_conf.is_some())
5496 : } else {
5497 0 : None
5498 : };
5499 0 : if is_intended_secondary.is_some() || is_observed_secondary.is_some() {
5500 0 : shards.push(NodeShard {
5501 0 : tenant_shard_id: *tid,
5502 0 : is_intended_secondary,
5503 0 : is_observed_secondary,
5504 0 : });
5505 0 : }
5506 : }
5507 0 : Ok(NodeShardResponse { node_id, shards })
5508 0 : }
5509 :
5510 0 : pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
5511 0 : self.persistence.get_leader().await
5512 0 : }
5513 :
5514 0 : pub(crate) async fn node_register(
5515 0 : &self,
5516 0 : register_req: NodeRegisterRequest,
5517 0 : ) -> Result<(), ApiError> {
5518 0 : let _node_lock = trace_exclusive_lock(
5519 0 : &self.node_op_locks,
5520 0 : register_req.node_id,
5521 0 : NodeOperations::Register,
5522 0 : )
5523 0 : .await;
5524 :
5525 : enum RegistrationStatus {
5526 : Matched,
5527 : Mismatched,
5528 : New,
5529 : }
5530 :
5531 0 : let registration_status = {
5532 0 : let locked = self.inner.read().unwrap();
5533 0 : if let Some(node) = locked.nodes.get(®ister_req.node_id) {
5534 0 : if node.registration_match(®ister_req) {
5535 0 : RegistrationStatus::Matched
5536 : } else {
5537 0 : RegistrationStatus::Mismatched
5538 : }
5539 : } else {
5540 0 : RegistrationStatus::New
5541 : }
5542 : };
5543 :
5544 0 : match registration_status {
5545 : RegistrationStatus::Matched => {
5546 0 : tracing::info!(
5547 0 : "Node {} re-registered with matching address",
5548 : register_req.node_id
5549 : );
5550 :
5551 0 : return Ok(());
5552 : }
5553 : RegistrationStatus::Mismatched => {
5554 : // TODO: decide if we want to allow modifying node addresses without removing and re-adding
5555 : // the node. Safest/simplest thing is to refuse it, and usually we deploy with
5556 : // a fixed address through the lifetime of a node.
5557 0 : tracing::warn!(
5558 0 : "Node {} tried to register with different address",
5559 : register_req.node_id
5560 : );
5561 0 : return Err(ApiError::Conflict(
5562 0 : "Node is already registered with different address".to_string(),
5563 0 : ));
5564 : }
5565 0 : RegistrationStatus::New => {
5566 0 : // fallthrough
5567 0 : }
5568 0 : }
5569 0 :
5570 0 : // We do not require that a node is actually online when registered (it will start life
5571 0 : // with it's availability set to Offline), but we _do_ require that its DNS record exists. We're
5572 0 : // therefore not immune to asymmetric L3 connectivity issues, but we are protected against nodes
5573 0 : // that register themselves with a broken DNS config. We check only the HTTP hostname, because
5574 0 : // the postgres hostname might only be resolvable to clients (e.g. if we're on a different VPC than clients).
5575 0 : if tokio::net::lookup_host(format!(
5576 0 : "{}:{}",
5577 0 : register_req.listen_http_addr, register_req.listen_http_port
5578 0 : ))
5579 0 : .await
5580 0 : .is_err()
5581 : {
5582 : // If we have a transient DNS issue, it's up to the caller to retry their registration. Because
5583 : // we can't robustly distinguish between an intermittent issue and a totally bogus DNS situation,
5584 : // we return a soft 503 error, to encourage callers to retry past transient issues.
5585 0 : return Err(ApiError::ResourceUnavailable(
5586 0 : format!(
5587 0 : "Node {} tried to register with unknown DNS name '{}'",
5588 0 : register_req.node_id, register_req.listen_http_addr
5589 0 : )
5590 0 : .into(),
5591 0 : ));
5592 0 : }
5593 0 :
5594 0 : // Ordering: we must persist the new node _before_ adding it to in-memory state.
5595 0 : // This ensures that before we use it for anything or expose it via any external
5596 0 : // API, it is guaranteed to be available after a restart.
5597 0 : let new_node = Node::new(
5598 0 : register_req.node_id,
5599 0 : register_req.listen_http_addr,
5600 0 : register_req.listen_http_port,
5601 0 : register_req.listen_pg_addr,
5602 0 : register_req.listen_pg_port,
5603 0 : register_req.availability_zone_id,
5604 0 : );
5605 0 :
5606 0 : // TODO: idempotency if the node already exists in the database
5607 0 : self.persistence.insert_node(&new_node).await?;
5608 :
5609 0 : let mut locked = self.inner.write().unwrap();
5610 0 : let mut new_nodes = (*locked.nodes).clone();
5611 0 :
5612 0 : locked.scheduler.node_upsert(&new_node);
5613 0 : new_nodes.insert(register_req.node_id, new_node);
5614 0 :
5615 0 : locked.nodes = Arc::new(new_nodes);
5616 0 :
5617 0 : metrics::METRICS_REGISTRY
5618 0 : .metrics_group
5619 0 : .storage_controller_pageserver_nodes
5620 0 : .set(locked.nodes.len() as i64);
5621 0 :
5622 0 : tracing::info!(
5623 0 : "Registered pageserver {}, now have {} pageservers",
5624 0 : register_req.node_id,
5625 0 : locked.nodes.len()
5626 : );
5627 0 : Ok(())
5628 0 : }
5629 :
5630 : /// Configure in-memory and persistent state of a node as requested
5631 : ///
5632 : /// Note that this function does not trigger any immediate side effects in response
5633 : /// to the changes. That part is handled by [`Self::handle_node_availability_transition`].
5634 0 : async fn node_state_configure(
5635 0 : &self,
5636 0 : node_id: NodeId,
5637 0 : availability: Option<NodeAvailability>,
5638 0 : scheduling: Option<NodeSchedulingPolicy>,
5639 0 : node_lock: &TracingExclusiveGuard<NodeOperations>,
5640 0 : ) -> Result<AvailabilityTransition, ApiError> {
5641 0 : if let Some(scheduling) = scheduling {
5642 : // Scheduling is a persistent part of Node: we must write updates to the database before
5643 : // applying them in memory
5644 0 : self.persistence.update_node(node_id, scheduling).await?;
5645 0 : }
5646 :
5647 : // If we're activating a node, then before setting it active we must reconcile any shard locations
5648 : // on that node, in case it is out of sync, e.g. due to being unavailable during controller startup,
5649 : // by calling [`Self::node_activate_reconcile`]
5650 : //
5651 : // The transition we calculate here remains valid later in the function because we hold the op lock on the node:
5652 : // nothing else can mutate its availability while we run.
5653 0 : let availability_transition = if let Some(input_availability) = availability.as_ref() {
5654 0 : let (activate_node, availability_transition) = {
5655 0 : let locked = self.inner.read().unwrap();
5656 0 : let Some(node) = locked.nodes.get(&node_id) else {
5657 0 : return Err(ApiError::NotFound(
5658 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
5659 0 : ));
5660 : };
5661 :
5662 0 : (
5663 0 : node.clone(),
5664 0 : node.get_availability_transition(input_availability),
5665 0 : )
5666 : };
5667 :
5668 0 : if matches!(availability_transition, AvailabilityTransition::ToActive) {
5669 0 : self.node_activate_reconcile(activate_node, node_lock)
5670 0 : .await?;
5671 0 : }
5672 0 : availability_transition
5673 : } else {
5674 0 : AvailabilityTransition::Unchanged
5675 : };
5676 :
5677 : // Apply changes from the request to our in-memory state for the Node
5678 0 : let mut locked = self.inner.write().unwrap();
5679 0 : let (nodes, _tenants, scheduler) = locked.parts_mut();
5680 0 :
5681 0 : let mut new_nodes = (**nodes).clone();
5682 :
5683 0 : let Some(node) = new_nodes.get_mut(&node_id) else {
5684 0 : return Err(ApiError::NotFound(
5685 0 : anyhow::anyhow!("Node not registered").into(),
5686 0 : ));
5687 : };
5688 :
5689 0 : if let Some(availability) = availability {
5690 0 : node.set_availability(availability);
5691 0 : }
5692 :
5693 0 : if let Some(scheduling) = scheduling {
5694 0 : node.set_scheduling(scheduling);
5695 0 : }
5696 :
5697 : // Update the scheduler, in case the elegibility of the node for new shards has changed
5698 0 : scheduler.node_upsert(node);
5699 0 :
5700 0 : let new_nodes = Arc::new(new_nodes);
5701 0 : locked.nodes = new_nodes;
5702 0 :
5703 0 : Ok(availability_transition)
5704 0 : }
5705 :
5706 : /// Handle availability transition of one node
5707 : ///
5708 : /// Note that you should first call [`Self::node_state_configure`] to update
5709 : /// the in-memory state referencing that node. If you need to handle more than one transition
5710 : /// consider using [`Self::handle_node_availability_transitions`].
5711 0 : async fn handle_node_availability_transition(
5712 0 : &self,
5713 0 : node_id: NodeId,
5714 0 : transition: AvailabilityTransition,
5715 0 : _node_lock: &TracingExclusiveGuard<NodeOperations>,
5716 0 : ) -> Result<(), ApiError> {
5717 0 : // Modify scheduling state for any Tenants that are affected by a change in the node's availability state.
5718 0 : match transition {
5719 : AvailabilityTransition::ToOffline => {
5720 0 : tracing::info!("Node {} transition to offline", node_id);
5721 :
5722 0 : let mut locked = self.inner.write().unwrap();
5723 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
5724 0 :
5725 0 : let mut tenants_affected: usize = 0;
5726 :
5727 0 : for (_tenant_id, mut schedule_context, shards) in
5728 0 : TenantShardContextIterator::new(tenants, ScheduleMode::Normal)
5729 : {
5730 0 : for tenant_shard in shards {
5731 0 : let tenant_shard_id = tenant_shard.tenant_shard_id;
5732 0 : if let Some(observed_loc) =
5733 0 : tenant_shard.observed.locations.get_mut(&node_id)
5734 0 : {
5735 0 : // When a node goes offline, we set its observed configuration to None, indicating unknown: we will
5736 0 : // not assume our knowledge of the node's configuration is accurate until it comes back online
5737 0 : observed_loc.conf = None;
5738 0 : }
5739 :
5740 0 : if nodes.len() == 1 {
5741 : // Special case for single-node cluster: there is no point trying to reschedule
5742 : // any tenant shards: avoid doing so, in order to avoid spewing warnings about
5743 : // failures to schedule them.
5744 0 : continue;
5745 0 : }
5746 0 :
5747 0 : if !nodes
5748 0 : .values()
5749 0 : .any(|n| matches!(n.may_schedule(), MaySchedule::Yes(_)))
5750 : {
5751 : // Special case for when all nodes are unavailable and/or unschedulable: there is no point
5752 : // trying to reschedule since there's nowhere else to go. Without this
5753 : // branch we incorrectly detach tenants in response to node unavailability.
5754 0 : continue;
5755 0 : }
5756 0 :
5757 0 : if tenant_shard.intent.demote_attached(scheduler, node_id) {
5758 0 : tenant_shard.sequence = tenant_shard.sequence.next();
5759 0 :
5760 0 : match tenant_shard.schedule(scheduler, &mut schedule_context) {
5761 0 : Err(e) => {
5762 0 : // It is possible that some tenants will become unschedulable when too many pageservers
5763 0 : // go offline: in this case there isn't much we can do other than make the issue observable.
5764 0 : // TODO: give TenantShard a scheduling error attribute to be queried later.
5765 0 : tracing::warn!(%tenant_shard_id, "Scheduling error when marking pageserver {} offline: {e}", node_id);
5766 : }
5767 : Ok(()) => {
5768 0 : if self.maybe_reconcile_shard(tenant_shard, nodes).is_some() {
5769 0 : tenants_affected += 1;
5770 0 : };
5771 : }
5772 : }
5773 0 : }
5774 : }
5775 : }
5776 0 : tracing::info!(
5777 0 : "Launched {} reconciler tasks for tenants affected by node {} going offline",
5778 : tenants_affected,
5779 : node_id
5780 : )
5781 : }
5782 : AvailabilityTransition::ToActive => {
5783 0 : tracing::info!("Node {} transition to active", node_id);
5784 :
5785 0 : let mut locked = self.inner.write().unwrap();
5786 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
5787 :
5788 : // When a node comes back online, we must reconcile any tenant that has a None observed
5789 : // location on the node.
5790 0 : for tenant_shard in tenants.values_mut() {
5791 : // If a reconciliation is already in progress, rely on the previous scheduling
5792 : // decision and skip triggering a new reconciliation.
5793 0 : if tenant_shard.reconciler.is_some() {
5794 0 : continue;
5795 0 : }
5796 :
5797 0 : if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
5798 0 : if observed_loc.conf.is_none() {
5799 0 : self.maybe_reconcile_shard(tenant_shard, nodes);
5800 0 : }
5801 0 : }
5802 : }
5803 :
5804 : // TODO: in the background, we should balance work back onto this pageserver
5805 : }
5806 : // No action required for the intermediate unavailable state.
5807 : // When we transition into active or offline from the unavailable state,
5808 : // the correct handling above will kick in.
5809 : AvailabilityTransition::ToWarmingUpFromActive => {
5810 0 : tracing::info!("Node {} transition to unavailable from active", node_id);
5811 : }
5812 : AvailabilityTransition::ToWarmingUpFromOffline => {
5813 0 : tracing::info!("Node {} transition to unavailable from offline", node_id);
5814 : }
5815 : AvailabilityTransition::Unchanged => {
5816 0 : tracing::debug!("Node {} no availability change during config", node_id);
5817 : }
5818 : }
5819 :
5820 0 : Ok(())
5821 0 : }
5822 :
5823 : /// Handle availability transition for multiple nodes
5824 : ///
5825 : /// Note that you should first call [`Self::node_state_configure`] for
5826 : /// all nodes being handled here for the handling to use fresh in-memory state.
5827 0 : async fn handle_node_availability_transitions(
5828 0 : &self,
5829 0 : transitions: Vec<(
5830 0 : NodeId,
5831 0 : TracingExclusiveGuard<NodeOperations>,
5832 0 : AvailabilityTransition,
5833 0 : )>,
5834 0 : ) -> Result<(), Vec<(NodeId, ApiError)>> {
5835 0 : let mut errors = Vec::default();
5836 0 : for (node_id, node_lock, transition) in transitions {
5837 0 : let res = self
5838 0 : .handle_node_availability_transition(node_id, transition, &node_lock)
5839 0 : .await;
5840 0 : if let Err(err) = res {
5841 0 : errors.push((node_id, err));
5842 0 : }
5843 : }
5844 :
5845 0 : if errors.is_empty() {
5846 0 : Ok(())
5847 : } else {
5848 0 : Err(errors)
5849 : }
5850 0 : }
5851 :
5852 0 : pub(crate) async fn node_configure(
5853 0 : &self,
5854 0 : node_id: NodeId,
5855 0 : availability: Option<NodeAvailability>,
5856 0 : scheduling: Option<NodeSchedulingPolicy>,
5857 0 : ) -> Result<(), ApiError> {
5858 0 : let node_lock =
5859 0 : trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Configure).await;
5860 :
5861 0 : let transition = self
5862 0 : .node_state_configure(node_id, availability, scheduling, &node_lock)
5863 0 : .await?;
5864 0 : self.handle_node_availability_transition(node_id, transition, &node_lock)
5865 0 : .await
5866 0 : }
5867 :
5868 : /// Wrapper around [`Self::node_configure`] which only allows changes while there is no ongoing
5869 : /// operation for HTTP api.
5870 0 : pub(crate) async fn external_node_configure(
5871 0 : &self,
5872 0 : node_id: NodeId,
5873 0 : availability: Option<NodeAvailability>,
5874 0 : scheduling: Option<NodeSchedulingPolicy>,
5875 0 : ) -> Result<(), ApiError> {
5876 0 : {
5877 0 : let locked = self.inner.read().unwrap();
5878 0 : if let Some(op) = locked.ongoing_operation.as_ref().map(|op| op.operation) {
5879 0 : return Err(ApiError::PreconditionFailed(
5880 0 : format!("Ongoing background operation forbids configuring: {op}").into(),
5881 0 : ));
5882 0 : }
5883 0 : }
5884 0 :
5885 0 : self.node_configure(node_id, availability, scheduling).await
5886 0 : }
5887 :
5888 0 : pub(crate) async fn start_node_drain(
5889 0 : self: &Arc<Self>,
5890 0 : node_id: NodeId,
5891 0 : ) -> Result<(), ApiError> {
5892 0 : let (ongoing_op, node_available, node_policy, schedulable_nodes_count) = {
5893 0 : let locked = self.inner.read().unwrap();
5894 0 : let nodes = &locked.nodes;
5895 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
5896 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
5897 0 : ))?;
5898 0 : let schedulable_nodes_count = nodes
5899 0 : .iter()
5900 0 : .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
5901 0 : .count();
5902 0 :
5903 0 : (
5904 0 : locked
5905 0 : .ongoing_operation
5906 0 : .as_ref()
5907 0 : .map(|ongoing| ongoing.operation),
5908 0 : node.is_available(),
5909 0 : node.get_scheduling(),
5910 0 : schedulable_nodes_count,
5911 0 : )
5912 0 : };
5913 :
5914 0 : if let Some(ongoing) = ongoing_op {
5915 0 : return Err(ApiError::PreconditionFailed(
5916 0 : format!("Background operation already ongoing for node: {}", ongoing).into(),
5917 0 : ));
5918 0 : }
5919 0 :
5920 0 : if !node_available {
5921 0 : return Err(ApiError::ResourceUnavailable(
5922 0 : format!("Node {node_id} is currently unavailable").into(),
5923 0 : ));
5924 0 : }
5925 0 :
5926 0 : if schedulable_nodes_count == 0 {
5927 0 : return Err(ApiError::PreconditionFailed(
5928 0 : "No other schedulable nodes to drain to".into(),
5929 0 : ));
5930 0 : }
5931 0 :
5932 0 : match node_policy {
5933 : NodeSchedulingPolicy::Active => {
5934 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Draining))
5935 0 : .await?;
5936 :
5937 0 : let cancel = self.cancel.child_token();
5938 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
5939 :
5940 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
5941 0 : operation: Operation::Drain(Drain { node_id }),
5942 0 : cancel: cancel.clone(),
5943 0 : });
5944 :
5945 0 : let span = tracing::info_span!(parent: None, "drain_node", %node_id);
5946 :
5947 0 : tokio::task::spawn({
5948 0 : let service = self.clone();
5949 0 : let cancel = cancel.clone();
5950 0 : async move {
5951 0 : let _gate_guard = gate_guard;
5952 0 :
5953 0 : scopeguard::defer! {
5954 0 : let prev = service.inner.write().unwrap().ongoing_operation.take();
5955 0 :
5956 0 : if let Some(Operation::Drain(removed_drain)) = prev.map(|h| h.operation) {
5957 0 : assert_eq!(removed_drain.node_id, node_id, "We always take the same operation");
5958 0 : } else {
5959 0 : panic!("We always remove the same operation")
5960 0 : }
5961 0 : }
5962 0 :
5963 0 : tracing::info!("Drain background operation starting");
5964 0 : let res = service.drain_node(node_id, cancel).await;
5965 0 : match res {
5966 : Ok(()) => {
5967 0 : tracing::info!("Drain background operation completed successfully");
5968 : }
5969 : Err(OperationError::Cancelled) => {
5970 0 : tracing::info!("Drain background operation was cancelled");
5971 : }
5972 0 : Err(err) => {
5973 0 : tracing::error!("Drain background operation encountered: {err}")
5974 : }
5975 : }
5976 0 : }
5977 0 : }.instrument(span));
5978 0 : }
5979 : NodeSchedulingPolicy::Draining => {
5980 0 : return Err(ApiError::Conflict(format!(
5981 0 : "Node {node_id} has drain in progress"
5982 0 : )));
5983 : }
5984 0 : policy => {
5985 0 : return Err(ApiError::PreconditionFailed(
5986 0 : format!("Node {node_id} cannot be drained due to {policy:?} policy").into(),
5987 0 : ));
5988 : }
5989 : }
5990 :
5991 0 : Ok(())
5992 0 : }
5993 :
5994 0 : pub(crate) async fn cancel_node_drain(&self, node_id: NodeId) -> Result<(), ApiError> {
5995 0 : let node_available = {
5996 0 : let locked = self.inner.read().unwrap();
5997 0 : let nodes = &locked.nodes;
5998 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
5999 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
6000 0 : ))?;
6001 :
6002 0 : node.is_available()
6003 0 : };
6004 0 :
6005 0 : if !node_available {
6006 0 : return Err(ApiError::ResourceUnavailable(
6007 0 : format!("Node {node_id} is currently unavailable").into(),
6008 0 : ));
6009 0 : }
6010 :
6011 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
6012 0 : if let Operation::Drain(drain) = op_handler.operation {
6013 0 : if drain.node_id == node_id {
6014 0 : tracing::info!("Cancelling background drain operation for node {node_id}");
6015 0 : op_handler.cancel.cancel();
6016 0 : return Ok(());
6017 0 : }
6018 0 : }
6019 0 : }
6020 :
6021 0 : Err(ApiError::PreconditionFailed(
6022 0 : format!("Node {node_id} has no drain in progress").into(),
6023 0 : ))
6024 0 : }
6025 :
6026 0 : pub(crate) async fn start_node_fill(self: &Arc<Self>, node_id: NodeId) -> Result<(), ApiError> {
6027 0 : let (ongoing_op, node_available, node_policy, total_nodes_count) = {
6028 0 : let locked = self.inner.read().unwrap();
6029 0 : let nodes = &locked.nodes;
6030 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
6031 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
6032 0 : ))?;
6033 :
6034 0 : (
6035 0 : locked
6036 0 : .ongoing_operation
6037 0 : .as_ref()
6038 0 : .map(|ongoing| ongoing.operation),
6039 0 : node.is_available(),
6040 0 : node.get_scheduling(),
6041 0 : nodes.len(),
6042 0 : )
6043 0 : };
6044 :
6045 0 : if let Some(ongoing) = ongoing_op {
6046 0 : return Err(ApiError::PreconditionFailed(
6047 0 : format!("Background operation already ongoing for node: {}", ongoing).into(),
6048 0 : ));
6049 0 : }
6050 0 :
6051 0 : if !node_available {
6052 0 : return Err(ApiError::ResourceUnavailable(
6053 0 : format!("Node {node_id} is currently unavailable").into(),
6054 0 : ));
6055 0 : }
6056 0 :
6057 0 : if total_nodes_count <= 1 {
6058 0 : return Err(ApiError::PreconditionFailed(
6059 0 : "No other nodes to fill from".into(),
6060 0 : ));
6061 0 : }
6062 0 :
6063 0 : match node_policy {
6064 : NodeSchedulingPolicy::Active => {
6065 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Filling))
6066 0 : .await?;
6067 :
6068 0 : let cancel = self.cancel.child_token();
6069 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
6070 :
6071 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
6072 0 : operation: Operation::Fill(Fill { node_id }),
6073 0 : cancel: cancel.clone(),
6074 0 : });
6075 :
6076 0 : let span = tracing::info_span!(parent: None, "fill_node", %node_id);
6077 :
6078 0 : tokio::task::spawn({
6079 0 : let service = self.clone();
6080 0 : let cancel = cancel.clone();
6081 0 : async move {
6082 0 : let _gate_guard = gate_guard;
6083 0 :
6084 0 : scopeguard::defer! {
6085 0 : let prev = service.inner.write().unwrap().ongoing_operation.take();
6086 0 :
6087 0 : if let Some(Operation::Fill(removed_fill)) = prev.map(|h| h.operation) {
6088 0 : assert_eq!(removed_fill.node_id, node_id, "We always take the same operation");
6089 0 : } else {
6090 0 : panic!("We always remove the same operation")
6091 0 : }
6092 0 : }
6093 0 :
6094 0 : tracing::info!("Fill background operation starting");
6095 0 : let res = service.fill_node(node_id, cancel).await;
6096 0 : match res {
6097 : Ok(()) => {
6098 0 : tracing::info!("Fill background operation completed successfully");
6099 : }
6100 : Err(OperationError::Cancelled) => {
6101 0 : tracing::info!("Fill background operation was cancelled");
6102 : }
6103 0 : Err(err) => {
6104 0 : tracing::error!("Fill background operation encountered: {err}")
6105 : }
6106 : }
6107 0 : }
6108 0 : }.instrument(span));
6109 0 : }
6110 : NodeSchedulingPolicy::Filling => {
6111 0 : return Err(ApiError::Conflict(format!(
6112 0 : "Node {node_id} has fill in progress"
6113 0 : )));
6114 : }
6115 0 : policy => {
6116 0 : return Err(ApiError::PreconditionFailed(
6117 0 : format!("Node {node_id} cannot be filled due to {policy:?} policy").into(),
6118 0 : ));
6119 : }
6120 : }
6121 :
6122 0 : Ok(())
6123 0 : }
6124 :
6125 0 : pub(crate) async fn cancel_node_fill(&self, node_id: NodeId) -> Result<(), ApiError> {
6126 0 : let node_available = {
6127 0 : let locked = self.inner.read().unwrap();
6128 0 : let nodes = &locked.nodes;
6129 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
6130 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
6131 0 : ))?;
6132 :
6133 0 : node.is_available()
6134 0 : };
6135 0 :
6136 0 : if !node_available {
6137 0 : return Err(ApiError::ResourceUnavailable(
6138 0 : format!("Node {node_id} is currently unavailable").into(),
6139 0 : ));
6140 0 : }
6141 :
6142 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
6143 0 : if let Operation::Fill(fill) = op_handler.operation {
6144 0 : if fill.node_id == node_id {
6145 0 : tracing::info!("Cancelling background drain operation for node {node_id}");
6146 0 : op_handler.cancel.cancel();
6147 0 : return Ok(());
6148 0 : }
6149 0 : }
6150 0 : }
6151 :
6152 0 : Err(ApiError::PreconditionFailed(
6153 0 : format!("Node {node_id} has no fill in progress").into(),
6154 0 : ))
6155 0 : }
6156 :
6157 : /// Like [`Self::maybe_configured_reconcile_shard`], but uses the default reconciler
6158 : /// configuration
6159 0 : fn maybe_reconcile_shard(
6160 0 : &self,
6161 0 : shard: &mut TenantShard,
6162 0 : nodes: &Arc<HashMap<NodeId, Node>>,
6163 0 : ) -> Option<ReconcilerWaiter> {
6164 0 : self.maybe_configured_reconcile_shard(shard, nodes, ReconcilerConfig::default())
6165 0 : }
6166 :
6167 : /// Wrap [`TenantShard`] reconciliation methods with acquisition of [`Gate`] and [`ReconcileUnits`],
6168 0 : fn maybe_configured_reconcile_shard(
6169 0 : &self,
6170 0 : shard: &mut TenantShard,
6171 0 : nodes: &Arc<HashMap<NodeId, Node>>,
6172 0 : reconciler_config: ReconcilerConfig,
6173 0 : ) -> Option<ReconcilerWaiter> {
6174 0 : let reconcile_needed = shard.get_reconcile_needed(nodes);
6175 0 :
6176 0 : match reconcile_needed {
6177 0 : ReconcileNeeded::No => return None,
6178 0 : ReconcileNeeded::WaitExisting(waiter) => return Some(waiter),
6179 0 : ReconcileNeeded::Yes => {
6180 0 : // Fall through to try and acquire units for spawning reconciler
6181 0 : }
6182 : };
6183 :
6184 0 : let units = match self.reconciler_concurrency.clone().try_acquire_owned() {
6185 0 : Ok(u) => ReconcileUnits::new(u),
6186 : Err(_) => {
6187 0 : tracing::info!(tenant_id=%shard.tenant_shard_id.tenant_id, shard_id=%shard.tenant_shard_id.shard_slug(),
6188 0 : "Concurrency limited: enqueued for reconcile later");
6189 0 : if !shard.delayed_reconcile {
6190 0 : match self.delayed_reconcile_tx.try_send(shard.tenant_shard_id) {
6191 0 : Err(TrySendError::Closed(_)) => {
6192 0 : // Weird mid-shutdown case?
6193 0 : }
6194 : Err(TrySendError::Full(_)) => {
6195 : // It is safe to skip sending our ID in the channel: we will eventually get retried by the background reconcile task.
6196 0 : tracing::warn!(
6197 0 : "Many shards are waiting to reconcile: delayed_reconcile queue is full"
6198 : );
6199 : }
6200 0 : Ok(()) => {
6201 0 : shard.delayed_reconcile = true;
6202 0 : }
6203 : }
6204 0 : }
6205 :
6206 : // We won't spawn a reconciler, but we will construct a waiter that waits for the shard's sequence
6207 : // number to advance. When this function is eventually called again and succeeds in getting units,
6208 : // it will spawn a reconciler that makes this waiter complete.
6209 0 : return Some(shard.future_reconcile_waiter());
6210 : }
6211 : };
6212 :
6213 0 : let Ok(gate_guard) = self.reconcilers_gate.enter() else {
6214 : // Gate closed: we're shutting down, drop out.
6215 0 : return None;
6216 : };
6217 :
6218 0 : shard.spawn_reconciler(
6219 0 : &self.result_tx,
6220 0 : nodes,
6221 0 : &self.compute_hook,
6222 0 : reconciler_config,
6223 0 : &self.config,
6224 0 : &self.persistence,
6225 0 : units,
6226 0 : gate_guard,
6227 0 : &self.reconcilers_cancel,
6228 0 : )
6229 0 : }
6230 :
6231 : /// Check all tenants for pending reconciliation work, and reconcile those in need.
6232 : /// Additionally, reschedule tenants that require it.
6233 : ///
6234 : /// Returns how many reconciliation tasks were started, or `1` if no reconciles were
6235 : /// spawned but some _would_ have been spawned if `reconciler_concurrency` units where
6236 : /// available. A return value of 0 indicates that everything is fully reconciled already.
6237 0 : fn reconcile_all(&self) -> usize {
6238 0 : let mut locked = self.inner.write().unwrap();
6239 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
6240 0 : let pageservers = nodes.clone();
6241 0 :
6242 0 : // This function is an efficient place to update lazy statistics, since we are walking
6243 0 : // all tenants.
6244 0 : let mut pending_reconciles = 0;
6245 0 : let mut az_violations = 0;
6246 0 :
6247 0 : // If we find any tenants to drop from memory, stash them to offload after
6248 0 : // we're done traversing the map of tenants.
6249 0 : let mut drop_detached_tenants = Vec::new();
6250 0 :
6251 0 : let mut reconciles_spawned = 0;
6252 0 : for shard in tenants.values_mut() {
6253 : // Accumulate scheduling statistics
6254 0 : if let (Some(attached), Some(preferred)) =
6255 0 : (shard.intent.get_attached(), shard.preferred_az())
6256 : {
6257 0 : let node_az = nodes
6258 0 : .get(attached)
6259 0 : .expect("Nodes exist if referenced")
6260 0 : .get_availability_zone_id();
6261 0 : if node_az != preferred {
6262 0 : az_violations += 1;
6263 0 : }
6264 0 : }
6265 :
6266 : // Skip checking if this shard is already enqueued for reconciliation
6267 0 : if shard.delayed_reconcile && self.reconciler_concurrency.available_permits() == 0 {
6268 : // If there is something delayed, then return a nonzero count so that
6269 : // callers like reconcile_all_now do not incorrectly get the impression
6270 : // that the system is in a quiescent state.
6271 0 : reconciles_spawned = std::cmp::max(1, reconciles_spawned);
6272 0 : pending_reconciles += 1;
6273 0 : continue;
6274 0 : }
6275 0 :
6276 0 : // Eventual consistency: if an earlier reconcile job failed, and the shard is still
6277 0 : // dirty, spawn another rone
6278 0 : if self.maybe_reconcile_shard(shard, &pageservers).is_some() {
6279 0 : reconciles_spawned += 1;
6280 0 : } else if shard.delayed_reconcile {
6281 0 : // Shard wanted to reconcile but for some reason couldn't.
6282 0 : pending_reconciles += 1;
6283 0 : }
6284 :
6285 : // If this tenant is detached, try dropping it from memory. This is usually done
6286 : // proactively in [`Self::process_results`], but we do it here to handle the edge
6287 : // case where a reconcile completes while someone else is holding an op lock for the tenant.
6288 0 : if shard.tenant_shard_id.shard_number == ShardNumber(0)
6289 0 : && shard.policy == PlacementPolicy::Detached
6290 : {
6291 0 : if let Some(guard) = self.tenant_op_locks.try_exclusive(
6292 0 : shard.tenant_shard_id.tenant_id,
6293 0 : TenantOperations::DropDetached,
6294 0 : ) {
6295 0 : drop_detached_tenants.push((shard.tenant_shard_id.tenant_id, guard));
6296 0 : }
6297 0 : }
6298 : }
6299 :
6300 : // Process any deferred tenant drops
6301 0 : for (tenant_id, guard) in drop_detached_tenants {
6302 0 : self.maybe_drop_tenant(tenant_id, &mut locked, &guard);
6303 0 : }
6304 :
6305 0 : metrics::METRICS_REGISTRY
6306 0 : .metrics_group
6307 0 : .storage_controller_schedule_az_violation
6308 0 : .set(az_violations as i64);
6309 0 :
6310 0 : metrics::METRICS_REGISTRY
6311 0 : .metrics_group
6312 0 : .storage_controller_pending_reconciles
6313 0 : .set(pending_reconciles as i64);
6314 0 :
6315 0 : reconciles_spawned
6316 0 : }
6317 :
6318 : /// `optimize` in this context means identifying shards which have valid scheduled locations, but
6319 : /// could be scheduled somewhere better:
6320 : /// - Cutting over to a secondary if the node with the secondary is more lightly loaded
6321 : /// * e.g. after a node fails then recovers, to move some work back to it
6322 : /// - Cutting over to a secondary if it improves the spread of shard attachments within a tenant
6323 : /// * e.g. after a shard split, the initial attached locations will all be on the node where
6324 : /// we did the split, but are probably better placed elsewhere.
6325 : /// - Creating new secondary locations if it improves the spreading of a sharded tenant
6326 : /// * e.g. after a shard split, some locations will be on the same node (where the split
6327 : /// happened), and will probably be better placed elsewhere.
6328 : ///
6329 : /// To put it more briefly: whereas the scheduler respects soft constraints in a ScheduleContext at
6330 : /// the time of scheduling, this function looks for cases where a better-scoring location is available
6331 : /// according to those same soft constraints.
6332 0 : async fn optimize_all(&self) -> usize {
6333 : // Limit on how many shards' optmizations each call to this function will execute. Combined
6334 : // with the frequency of background calls, this acts as an implicit rate limit that runs a small
6335 : // trickle of optimizations in the background, rather than executing a large number in parallel
6336 : // when a change occurs.
6337 : const MAX_OPTIMIZATIONS_EXEC_PER_PASS: usize = 2;
6338 :
6339 : // Synchronous prepare: scan shards for possible scheduling optimizations
6340 0 : let candidate_work = self.optimize_all_plan();
6341 0 : let candidate_work_len = candidate_work.len();
6342 :
6343 : // Asynchronous validate: I/O to pageservers to make sure shards are in a good state to apply validation
6344 0 : let validated_work = self.optimize_all_validate(candidate_work).await;
6345 :
6346 0 : let was_work_filtered = validated_work.len() != candidate_work_len;
6347 0 :
6348 0 : // Synchronous apply: update the shards' intent states according to validated optimisations
6349 0 : let mut reconciles_spawned = 0;
6350 0 : let mut optimizations_applied = 0;
6351 0 : let mut locked = self.inner.write().unwrap();
6352 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6353 0 : for (tenant_shard_id, optimization) in validated_work {
6354 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
6355 : // Shard was dropped between planning and execution;
6356 0 : continue;
6357 : };
6358 0 : if shard.apply_optimization(scheduler, optimization) {
6359 0 : optimizations_applied += 1;
6360 0 : if self.maybe_reconcile_shard(shard, nodes).is_some() {
6361 0 : reconciles_spawned += 1;
6362 0 : }
6363 0 : }
6364 :
6365 0 : if optimizations_applied >= MAX_OPTIMIZATIONS_EXEC_PER_PASS {
6366 0 : break;
6367 0 : }
6368 : }
6369 :
6370 0 : if was_work_filtered {
6371 0 : // If we filtered any work out during validation, ensure we return a nonzero value to indicate
6372 0 : // to callers that the system is not in a truly quiet state, it's going to do some work as soon
6373 0 : // as these validations start passing.
6374 0 : reconciles_spawned = std::cmp::max(reconciles_spawned, 1);
6375 0 : }
6376 :
6377 0 : reconciles_spawned
6378 0 : }
6379 :
6380 0 : fn optimize_all_plan(&self) -> Vec<(TenantShardId, ScheduleOptimization)> {
6381 : // How many candidate optimizations we will generate, before evaluating them for readniess: setting
6382 : // this higher than the execution limit gives us a chance to execute some work even if the first
6383 : // few optimizations we find are not ready.
6384 : const MAX_OPTIMIZATIONS_PLAN_PER_PASS: usize = 8;
6385 :
6386 0 : let mut work = Vec::new();
6387 0 : let mut locked = self.inner.write().unwrap();
6388 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6389 :
6390 0 : for (_tenant_id, schedule_context, shards) in
6391 0 : TenantShardContextIterator::new(tenants, ScheduleMode::Speculative)
6392 : {
6393 0 : for shard in shards {
6394 0 : if work.len() >= MAX_OPTIMIZATIONS_PLAN_PER_PASS {
6395 0 : break;
6396 0 : }
6397 0 : match shard.get_scheduling_policy() {
6398 0 : ShardSchedulingPolicy::Active => {
6399 0 : // Ok to do optimization
6400 0 : }
6401 : ShardSchedulingPolicy::Essential
6402 : | ShardSchedulingPolicy::Pause
6403 : | ShardSchedulingPolicy::Stop => {
6404 : // Policy prevents optimizing this shard.
6405 0 : continue;
6406 : }
6407 : }
6408 :
6409 0 : if !matches!(shard.splitting, SplitState::Idle)
6410 0 : || matches!(shard.policy, PlacementPolicy::Detached)
6411 0 : || shard.reconciler.is_some()
6412 : {
6413 : // Do not start any optimizations while another change to the tenant is ongoing: this
6414 : // is not necessary for correctness, but simplifies operations and implicitly throttles
6415 : // optimization changes to happen in a "trickle" over time.
6416 0 : continue;
6417 0 : }
6418 :
6419 : // TODO: optimization calculations are relatively expensive: create some fast-path for
6420 : // the common idle case (avoiding the search on tenants that we have recently checked)
6421 0 : if let Some(optimization) =
6422 : // If idle, maybe ptimize attachments: if a shard has a secondary location that is preferable to
6423 : // its primary location based on soft constraints, cut it over.
6424 0 : shard.optimize_attachment(nodes, &schedule_context)
6425 : {
6426 0 : work.push((shard.tenant_shard_id, optimization));
6427 0 : break;
6428 0 : } else if let Some(optimization) =
6429 : // If idle, maybe optimize secondary locations: if a shard has a secondary location that would be
6430 : // better placed on another node, based on ScheduleContext, then adjust it. This
6431 : // covers cases like after a shard split, where we might have too many shards
6432 : // in the same tenant with secondary locations on the node where they originally split.
6433 0 : shard.optimize_secondary(scheduler, &schedule_context)
6434 : {
6435 0 : work.push((shard.tenant_shard_id, optimization));
6436 0 : break;
6437 0 : }
6438 : }
6439 : }
6440 :
6441 0 : work
6442 0 : }
6443 :
6444 0 : async fn optimize_all_validate(
6445 0 : &self,
6446 0 : candidate_work: Vec<(TenantShardId, ScheduleOptimization)>,
6447 0 : ) -> Vec<(TenantShardId, ScheduleOptimization)> {
6448 0 : // Take a clone of the node map to use outside the lock in async validation phase
6449 0 : let validation_nodes = { self.inner.read().unwrap().nodes.clone() };
6450 0 :
6451 0 : let mut want_secondary_status = Vec::new();
6452 0 :
6453 0 : // Validate our plans: this is an async phase where we may do I/O to pageservers to
6454 0 : // check that the state of locations is acceptable to run the optimization, such as
6455 0 : // checking that a secondary location is sufficiently warmed-up to cleanly cut over
6456 0 : // in a live migration.
6457 0 : let mut validated_work = Vec::new();
6458 0 : for (tenant_shard_id, optimization) in candidate_work {
6459 0 : match optimization.action {
6460 : ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
6461 : old_attached_node_id: _,
6462 0 : new_attached_node_id,
6463 0 : }) => {
6464 0 : match validation_nodes.get(&new_attached_node_id) {
6465 0 : None => {
6466 0 : // Node was dropped between planning and validation
6467 0 : }
6468 0 : Some(node) => {
6469 0 : if !node.is_available() {
6470 0 : tracing::info!("Skipping optimization migration of {tenant_shard_id} to {new_attached_node_id} because node unavailable");
6471 0 : } else {
6472 0 : // Accumulate optimizations that require fetching secondary status, so that we can execute these
6473 0 : // remote API requests concurrently.
6474 0 : want_secondary_status.push((
6475 0 : tenant_shard_id,
6476 0 : node.clone(),
6477 0 : optimization,
6478 0 : ));
6479 0 : }
6480 : }
6481 : }
6482 : }
6483 : ScheduleOptimizationAction::ReplaceSecondary(_) => {
6484 : // No extra checks needed to replace a secondary: this does not interrupt client access
6485 0 : validated_work.push((tenant_shard_id, optimization))
6486 : }
6487 : };
6488 : }
6489 :
6490 : // Call into pageserver API to find out if the destination secondary location is warm enough for a reasonably smooth migration: we
6491 : // do this so that we avoid spawning a Reconciler that would have to wait minutes/hours for a destination to warm up: that reconciler
6492 : // would hold a precious reconcile semaphore unit the whole time it was waiting for the destination to warm up.
6493 0 : let results = self
6494 0 : .tenant_for_shards_api(
6495 0 : want_secondary_status
6496 0 : .iter()
6497 0 : .map(|i| (i.0, i.1.clone()))
6498 0 : .collect(),
6499 0 : |tenant_shard_id, client| async move {
6500 0 : client.tenant_secondary_status(tenant_shard_id).await
6501 0 : },
6502 0 : 1,
6503 0 : 1,
6504 0 : SHORT_RECONCILE_TIMEOUT,
6505 0 : &self.cancel,
6506 0 : )
6507 0 : .await;
6508 :
6509 0 : for ((tenant_shard_id, node, optimization), secondary_status) in
6510 0 : want_secondary_status.into_iter().zip(results.into_iter())
6511 : {
6512 0 : match secondary_status {
6513 0 : Err(e) => {
6514 0 : tracing::info!("Skipping migration of {tenant_shard_id} to {node}, error querying secondary: {e}");
6515 : }
6516 0 : Ok(progress) => {
6517 : // We require secondary locations to have less than 10GiB of downloads pending before we will use
6518 : // them in an optimization
6519 : const DOWNLOAD_FRESHNESS_THRESHOLD: u64 = 10 * 1024 * 1024 * 1024;
6520 :
6521 0 : if progress.heatmap_mtime.is_none()
6522 0 : || progress.bytes_total < DOWNLOAD_FRESHNESS_THRESHOLD
6523 0 : && progress.bytes_downloaded != progress.bytes_total
6524 0 : || progress.bytes_total - progress.bytes_downloaded
6525 0 : > DOWNLOAD_FRESHNESS_THRESHOLD
6526 : {
6527 0 : tracing::info!("Skipping migration of {tenant_shard_id} to {node} because secondary isn't ready: {progress:?}");
6528 :
6529 : #[cfg(feature = "testing")]
6530 0 : if progress.heatmap_mtime.is_none() {
6531 : // No heatmap might mean the attached location has never uploaded one, or that
6532 : // the secondary download hasn't happened yet. This is relatively unusual in the field,
6533 : // but fairly common in tests.
6534 0 : self.kick_secondary_download(tenant_shard_id).await;
6535 0 : }
6536 : } else {
6537 : // Location looks ready: proceed
6538 0 : tracing::info!(
6539 0 : "{tenant_shard_id} secondary on {node} is warm enough for migration: {progress:?}"
6540 : );
6541 0 : validated_work.push((tenant_shard_id, optimization))
6542 : }
6543 : }
6544 : }
6545 : }
6546 :
6547 0 : validated_work
6548 0 : }
6549 :
6550 : /// Some aspects of scheduling optimisation wait for secondary locations to be warm. This
6551 : /// happens on multi-minute timescales in the field, which is fine because optimisation is meant
6552 : /// to be a lazy background thing. However, when testing, it is not practical to wait around, so
6553 : /// we have this helper to move things along faster.
6554 : #[cfg(feature = "testing")]
6555 0 : async fn kick_secondary_download(&self, tenant_shard_id: TenantShardId) {
6556 0 : let (attached_node, secondary_node) = {
6557 0 : let locked = self.inner.read().unwrap();
6558 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
6559 0 : return;
6560 : };
6561 0 : let (Some(attached), Some(secondary)) = (
6562 0 : shard.intent.get_attached(),
6563 0 : shard.intent.get_secondary().first(),
6564 : ) else {
6565 0 : return;
6566 : };
6567 0 : (
6568 0 : locked.nodes.get(attached).unwrap().clone(),
6569 0 : locked.nodes.get(secondary).unwrap().clone(),
6570 0 : )
6571 0 : };
6572 0 :
6573 0 : // Make remote API calls to upload + download heatmaps: we ignore errors because this is just
6574 0 : // a 'kick' to let scheduling optimisation run more promptly.
6575 0 : attached_node
6576 0 : .with_client_retries(
6577 0 : |client| async move { client.tenant_heatmap_upload(tenant_shard_id).await },
6578 0 : &self.config.jwt_token,
6579 0 : 3,
6580 0 : 10,
6581 0 : SHORT_RECONCILE_TIMEOUT,
6582 0 : &self.cancel,
6583 0 : )
6584 0 : .await;
6585 :
6586 0 : secondary_node
6587 0 : .with_client_retries(
6588 0 : |client| async move {
6589 0 : client
6590 0 : .tenant_secondary_download(tenant_shard_id, Some(Duration::from_secs(1)))
6591 0 : .await
6592 0 : },
6593 0 : &self.config.jwt_token,
6594 0 : 3,
6595 0 : 10,
6596 0 : SHORT_RECONCILE_TIMEOUT,
6597 0 : &self.cancel,
6598 0 : )
6599 0 : .await;
6600 0 : }
6601 :
6602 : /// Look for shards which are oversized and in need of splitting
6603 0 : async fn autosplit_tenants(self: &Arc<Self>) {
6604 0 : let Some(split_threshold) = self.config.split_threshold else {
6605 : // Auto-splitting is disabled
6606 0 : return;
6607 : };
6608 :
6609 0 : let nodes = self.inner.read().unwrap().nodes.clone();
6610 :
6611 : const SPLIT_TO_MAX: ShardCount = ShardCount::new(8);
6612 :
6613 0 : let mut top_n = Vec::new();
6614 0 :
6615 0 : // Call into each node to look for big tenants
6616 0 : let top_n_request = TopTenantShardsRequest {
6617 0 : // We currently split based on logical size, for simplicity: logical size is a signal of
6618 0 : // the user's intent to run a large database, whereas physical/resident size can be symptoms
6619 0 : // of compaction issues. Eventually we should switch to using resident size to bound the
6620 0 : // disk space impact of one shard.
6621 0 : order_by: models::TenantSorting::MaxLogicalSize,
6622 0 : limit: 10,
6623 0 : where_shards_lt: Some(SPLIT_TO_MAX),
6624 0 : where_gt: Some(split_threshold),
6625 0 : };
6626 0 : for node in nodes.values() {
6627 0 : let request_ref = &top_n_request;
6628 0 : match node
6629 0 : .with_client_retries(
6630 0 : |client| async move {
6631 0 : let request = request_ref.clone();
6632 0 : client.top_tenant_shards(request.clone()).await
6633 0 : },
6634 0 : &self.config.jwt_token,
6635 0 : 3,
6636 0 : 3,
6637 0 : Duration::from_secs(5),
6638 0 : &self.cancel,
6639 0 : )
6640 0 : .await
6641 : {
6642 0 : Some(Ok(node_top_n)) => {
6643 0 : top_n.extend(node_top_n.shards.into_iter());
6644 0 : }
6645 : Some(Err(mgmt_api::Error::Cancelled)) => {
6646 0 : continue;
6647 : }
6648 0 : Some(Err(e)) => {
6649 0 : tracing::warn!("Failed to fetch top N tenants from {node}: {e}");
6650 0 : continue;
6651 : }
6652 : None => {
6653 : // Node is shutting down
6654 0 : continue;
6655 : }
6656 : };
6657 : }
6658 :
6659 : // Pick the biggest tenant to split first
6660 0 : top_n.sort_by_key(|i| i.resident_size);
6661 0 :
6662 0 : // Filter out tenants in a prohibiting scheduling mode
6663 0 : {
6664 0 : let locked = self.inner.read().unwrap();
6665 0 : top_n.retain(|i| {
6666 0 : if let Some(shard) = locked.tenants.get(&i.id) {
6667 0 : matches!(shard.get_scheduling_policy(), ShardSchedulingPolicy::Active)
6668 : } else {
6669 0 : false
6670 : }
6671 0 : });
6672 0 : }
6673 :
6674 0 : let Some(split_candidate) = top_n.into_iter().next() else {
6675 0 : tracing::debug!("No split-elegible shards found");
6676 0 : return;
6677 : };
6678 :
6679 : // We spawn a task to run this, so it's exactly like some external API client requesting it. We don't
6680 : // want to block the background reconcile loop on this.
6681 0 : tracing::info!("Auto-splitting tenant for size threshold {split_threshold}: current size {split_candidate:?}");
6682 :
6683 0 : let this = self.clone();
6684 0 : tokio::spawn(
6685 0 : async move {
6686 0 : match this
6687 0 : .tenant_shard_split(
6688 0 : split_candidate.id.tenant_id,
6689 0 : TenantShardSplitRequest {
6690 0 : // Always split to the max number of shards: this avoids stepping through
6691 0 : // intervening shard counts and encountering the overrhead of a split+cleanup
6692 0 : // each time as a tenant grows, and is not too expensive because our max shard
6693 0 : // count is relatively low anyway.
6694 0 : // This policy will be adjusted in future once we support higher shard count.
6695 0 : new_shard_count: SPLIT_TO_MAX.literal(),
6696 0 : new_stripe_size: Some(ShardParameters::DEFAULT_STRIPE_SIZE),
6697 0 : },
6698 0 : )
6699 0 : .await
6700 : {
6701 : Ok(_) => {
6702 0 : tracing::info!("Successful auto-split");
6703 : }
6704 0 : Err(e) => {
6705 0 : tracing::error!("Auto-split failed: {e}");
6706 : }
6707 : }
6708 0 : }
6709 0 : .instrument(tracing::info_span!("auto_split", tenant_id=%split_candidate.id.tenant_id)),
6710 : );
6711 0 : }
6712 :
6713 : /// Useful for tests: run whatever work a background [`Self::reconcile_all`] would have done, but
6714 : /// also wait for any generated Reconcilers to complete. Calling this until it returns zero should
6715 : /// put the system into a quiescent state where future background reconciliations won't do anything.
6716 0 : pub(crate) async fn reconcile_all_now(&self) -> Result<usize, ReconcileWaitError> {
6717 0 : let reconciles_spawned = self.reconcile_all();
6718 0 : let reconciles_spawned = if reconciles_spawned == 0 {
6719 : // Only optimize when we are otherwise idle
6720 0 : self.optimize_all().await
6721 : } else {
6722 0 : reconciles_spawned
6723 : };
6724 :
6725 0 : let waiters = {
6726 0 : let mut waiters = Vec::new();
6727 0 : let locked = self.inner.read().unwrap();
6728 0 : for (_tenant_shard_id, shard) in locked.tenants.iter() {
6729 0 : if let Some(waiter) = shard.get_waiter() {
6730 0 : waiters.push(waiter);
6731 0 : }
6732 : }
6733 0 : waiters
6734 0 : };
6735 0 :
6736 0 : let waiter_count = waiters.len();
6737 0 : match self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
6738 0 : Ok(()) => {}
6739 0 : Err(ReconcileWaitError::Failed(_, reconcile_error))
6740 0 : if matches!(*reconcile_error, ReconcileError::Cancel) =>
6741 0 : {
6742 0 : // Ignore reconciler cancel errors: this reconciler might have shut down
6743 0 : // because some other change superceded it. We will return a nonzero number,
6744 0 : // so the caller knows they might have to call again to quiesce the system.
6745 0 : }
6746 0 : Err(e) => {
6747 0 : return Err(e);
6748 : }
6749 : };
6750 :
6751 0 : tracing::info!(
6752 0 : "{} reconciles in reconcile_all, {} waiters",
6753 : reconciles_spawned,
6754 : waiter_count
6755 : );
6756 :
6757 0 : Ok(std::cmp::max(waiter_count, reconciles_spawned))
6758 0 : }
6759 :
6760 0 : async fn stop_reconciliations(&self, reason: StopReconciliationsReason) {
6761 0 : // Cancel all on-going reconciles and wait for them to exit the gate.
6762 0 : tracing::info!("{reason}: cancelling and waiting for in-flight reconciles");
6763 0 : self.reconcilers_cancel.cancel();
6764 0 : self.reconcilers_gate.close().await;
6765 :
6766 : // Signal the background loop in [`Service::process_results`] to exit once
6767 : // it has proccessed the results from all the reconciles we cancelled earlier.
6768 0 : tracing::info!("{reason}: processing results from previously in-flight reconciles");
6769 0 : self.result_tx.send(ReconcileResultRequest::Stop).ok();
6770 0 : self.result_tx.closed().await;
6771 0 : }
6772 :
6773 0 : pub async fn shutdown(&self) {
6774 0 : self.stop_reconciliations(StopReconciliationsReason::ShuttingDown)
6775 0 : .await;
6776 :
6777 : // Background tasks hold gate guards: this notifies them of the cancellation and
6778 : // waits for them all to complete.
6779 0 : tracing::info!("Shutting down: cancelling and waiting for background tasks to exit");
6780 0 : self.cancel.cancel();
6781 0 : self.gate.close().await;
6782 0 : }
6783 :
6784 : /// Spot check the download lag for a secondary location of a shard.
6785 : /// Should be used as a heuristic, since it's not always precise: the
6786 : /// secondary might have not downloaded the new heat map yet and, hence,
6787 : /// is not aware of the lag.
6788 : ///
6789 : /// Returns:
6790 : /// * Ok(None) if the lag could not be determined from the status,
6791 : /// * Ok(Some(_)) if the lag could be determind
6792 : /// * Err on failures to query the pageserver.
6793 0 : async fn secondary_lag(
6794 0 : &self,
6795 0 : secondary: &NodeId,
6796 0 : tenant_shard_id: TenantShardId,
6797 0 : ) -> Result<Option<u64>, mgmt_api::Error> {
6798 0 : let nodes = self.inner.read().unwrap().nodes.clone();
6799 0 : let node = nodes.get(secondary).ok_or(mgmt_api::Error::ApiError(
6800 0 : StatusCode::NOT_FOUND,
6801 0 : format!("Node with id {} not found", secondary),
6802 0 : ))?;
6803 :
6804 0 : match node
6805 0 : .with_client_retries(
6806 0 : |client| async move { client.tenant_secondary_status(tenant_shard_id).await },
6807 0 : &self.config.jwt_token,
6808 0 : 1,
6809 0 : 3,
6810 0 : Duration::from_millis(250),
6811 0 : &self.cancel,
6812 0 : )
6813 0 : .await
6814 : {
6815 0 : Some(Ok(status)) => match status.heatmap_mtime {
6816 0 : Some(_) => Ok(Some(status.bytes_total - status.bytes_downloaded)),
6817 0 : None => Ok(None),
6818 : },
6819 0 : Some(Err(e)) => Err(e),
6820 0 : None => Err(mgmt_api::Error::Cancelled),
6821 : }
6822 0 : }
6823 :
6824 : /// Drain a node by moving the shards attached to it as primaries.
6825 : /// This is a long running operation and it should run as a separate Tokio task.
6826 0 : pub(crate) async fn drain_node(
6827 0 : self: &Arc<Self>,
6828 0 : node_id: NodeId,
6829 0 : cancel: CancellationToken,
6830 0 : ) -> Result<(), OperationError> {
6831 : const MAX_SECONDARY_LAG_BYTES_DEFAULT: u64 = 256 * 1024 * 1024;
6832 0 : let max_secondary_lag_bytes = self
6833 0 : .config
6834 0 : .max_secondary_lag_bytes
6835 0 : .unwrap_or(MAX_SECONDARY_LAG_BYTES_DEFAULT);
6836 :
6837 : // By default, live migrations are generous about the wait time for getting
6838 : // the secondary location up to speed. When draining, give up earlier in order
6839 : // to not stall the operation when a cold secondary is encountered.
6840 : const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(20);
6841 : const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
6842 0 : let reconciler_config = ReconcilerConfigBuilder::new()
6843 0 : .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
6844 0 : .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
6845 0 : .build();
6846 0 :
6847 0 : let mut waiters = Vec::new();
6848 0 :
6849 0 : let mut tid_iter = TenantShardIterator::new({
6850 0 : let service = self.clone();
6851 0 : move |last_inspected_shard: Option<TenantShardId>| {
6852 0 : let locked = &service.inner.read().unwrap();
6853 0 : let tenants = &locked.tenants;
6854 0 : let entry = match last_inspected_shard {
6855 0 : Some(skip_past) => {
6856 0 : // Skip to the last seen tenant shard id
6857 0 : let mut cursor = tenants.iter().skip_while(|(tid, _)| **tid != skip_past);
6858 0 :
6859 0 : // Skip past the last seen
6860 0 : cursor.nth(1)
6861 : }
6862 0 : None => tenants.first_key_value(),
6863 : };
6864 :
6865 0 : entry.map(|(tid, _)| tid).copied()
6866 0 : }
6867 0 : });
6868 :
6869 0 : while !tid_iter.finished() {
6870 0 : if cancel.is_cancelled() {
6871 0 : match self
6872 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
6873 0 : .await
6874 : {
6875 0 : Ok(()) => return Err(OperationError::Cancelled),
6876 0 : Err(err) => {
6877 0 : return Err(OperationError::FinalizeError(
6878 0 : format!(
6879 0 : "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
6880 0 : node_id, err
6881 0 : )
6882 0 : .into(),
6883 0 : ));
6884 : }
6885 : }
6886 0 : }
6887 0 :
6888 0 : drain_utils::validate_node_state(&node_id, self.inner.read().unwrap().nodes.clone())?;
6889 :
6890 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
6891 0 : let tid = match tid_iter.next() {
6892 0 : Some(tid) => tid,
6893 : None => {
6894 0 : break;
6895 : }
6896 : };
6897 :
6898 0 : let tid_drain = TenantShardDrain {
6899 0 : drained_node: node_id,
6900 0 : tenant_shard_id: tid,
6901 0 : };
6902 :
6903 0 : let dest_node_id = {
6904 0 : let locked = self.inner.read().unwrap();
6905 0 :
6906 0 : match tid_drain
6907 0 : .tenant_shard_eligible_for_drain(&locked.tenants, &locked.scheduler)
6908 : {
6909 0 : Some(node_id) => node_id,
6910 : None => {
6911 0 : continue;
6912 : }
6913 : }
6914 : };
6915 :
6916 0 : match self.secondary_lag(&dest_node_id, tid).await {
6917 0 : Ok(Some(lag)) if lag <= max_secondary_lag_bytes => {
6918 0 : // The secondary is reasonably up to date.
6919 0 : // Migrate to it
6920 0 : }
6921 0 : Ok(Some(lag)) => {
6922 0 : tracing::info!(
6923 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
6924 0 : "Secondary on node {dest_node_id} is lagging by {lag}. Skipping reconcile."
6925 : );
6926 0 : continue;
6927 : }
6928 : Ok(None) => {
6929 0 : tracing::info!(
6930 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
6931 0 : "Could not determine lag for secondary on node {dest_node_id}. Skipping reconcile."
6932 : );
6933 0 : continue;
6934 : }
6935 0 : Err(err) => {
6936 0 : tracing::warn!(
6937 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
6938 0 : "Failed to get secondary lag from node {dest_node_id}. Skipping reconcile: {err}"
6939 : );
6940 0 : continue;
6941 : }
6942 : }
6943 :
6944 : {
6945 0 : let mut locked = self.inner.write().unwrap();
6946 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6947 0 : let rescheduled = tid_drain.reschedule_to_secondary(
6948 0 : dest_node_id,
6949 0 : tenants,
6950 0 : scheduler,
6951 0 : nodes,
6952 0 : )?;
6953 :
6954 0 : if let Some(tenant_shard) = rescheduled {
6955 0 : let waiter = self.maybe_configured_reconcile_shard(
6956 0 : tenant_shard,
6957 0 : nodes,
6958 0 : reconciler_config,
6959 0 : );
6960 0 : if let Some(some) = waiter {
6961 0 : waiters.push(some);
6962 0 : }
6963 0 : }
6964 : }
6965 : }
6966 :
6967 0 : waiters = self
6968 0 : .await_waiters_remainder(waiters, WAITER_FILL_DRAIN_POLL_TIMEOUT)
6969 0 : .await;
6970 :
6971 0 : failpoint_support::sleep_millis_async!("sleepy-drain-loop", &cancel);
6972 : }
6973 :
6974 0 : while !waiters.is_empty() {
6975 0 : if cancel.is_cancelled() {
6976 0 : match self
6977 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
6978 0 : .await
6979 : {
6980 0 : Ok(()) => return Err(OperationError::Cancelled),
6981 0 : Err(err) => {
6982 0 : return Err(OperationError::FinalizeError(
6983 0 : format!(
6984 0 : "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
6985 0 : node_id, err
6986 0 : )
6987 0 : .into(),
6988 0 : ));
6989 : }
6990 : }
6991 0 : }
6992 0 :
6993 0 : tracing::info!("Awaiting {} pending drain reconciliations", waiters.len());
6994 :
6995 0 : waiters = self
6996 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
6997 0 : .await;
6998 : }
6999 :
7000 : // At this point we have done the best we could to drain shards from this node.
7001 : // Set the node scheduling policy to `[NodeSchedulingPolicy::PauseForRestart]`
7002 : // to complete the drain.
7003 0 : if let Err(err) = self
7004 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::PauseForRestart))
7005 0 : .await
7006 : {
7007 : // This is not fatal. Anything that is polling the node scheduling policy to detect
7008 : // the end of the drain operations will hang, but all such places should enforce an
7009 : // overall timeout. The scheduling policy will be updated upon node re-attach and/or
7010 : // by the counterpart fill operation.
7011 0 : return Err(OperationError::FinalizeError(
7012 0 : format!(
7013 0 : "Failed to finalise drain of {node_id} by setting scheduling policy to PauseForRestart: {err}"
7014 0 : )
7015 0 : .into(),
7016 0 : ));
7017 0 : }
7018 0 :
7019 0 : Ok(())
7020 0 : }
7021 :
7022 : /// Create a node fill plan (pick secondaries to promote) that meets the following requirements:
7023 : /// 1. The node should be filled until it reaches the expected cluster average of
7024 : /// attached shards. If there are not enough secondaries on the node, the plan stops early.
7025 : /// 2. Select tenant shards to promote such that the number of attached shards is balanced
7026 : /// throughout the cluster. We achieve this by picking tenant shards from each node,
7027 : /// starting from the ones with the largest number of attached shards, until the node
7028 : /// reaches the expected cluster average.
7029 : /// 3. Avoid promoting more shards of the same tenant than required. The upper bound
7030 : /// for the number of tenants from the same shard promoted to the node being filled is:
7031 : /// shard count for the tenant divided by the number of nodes in the cluster.
7032 0 : fn fill_node_plan(&self, node_id: NodeId) -> Vec<TenantShardId> {
7033 0 : let mut locked = self.inner.write().unwrap();
7034 0 : let fill_requirement = locked.scheduler.compute_fill_requirement(node_id);
7035 0 :
7036 0 : let mut tids_by_node = locked
7037 0 : .tenants
7038 0 : .iter_mut()
7039 0 : .filter_map(|(tid, tenant_shard)| {
7040 0 : if !matches!(
7041 0 : tenant_shard.get_scheduling_policy(),
7042 : ShardSchedulingPolicy::Active
7043 : ) {
7044 : // Only include tenants in fills if they have a normal (Active) scheduling policy. We
7045 : // even exclude Essential, because moving to fill a node is not essential to keeping this
7046 : // tenant available.
7047 0 : return None;
7048 0 : }
7049 0 :
7050 0 : if tenant_shard.intent.get_secondary().contains(&node_id) {
7051 0 : if let Some(primary) = tenant_shard.intent.get_attached() {
7052 0 : return Some((*primary, *tid));
7053 0 : }
7054 0 : }
7055 :
7056 0 : None
7057 0 : })
7058 0 : .into_group_map();
7059 0 :
7060 0 : let expected_attached = locked.scheduler.expected_attached_shard_count();
7061 0 : let nodes_by_load = locked.scheduler.nodes_by_attached_shard_count();
7062 0 :
7063 0 : let mut promoted_per_tenant: HashMap<TenantId, usize> = HashMap::new();
7064 0 : let mut plan = Vec::new();
7065 :
7066 0 : for (node_id, attached) in nodes_by_load {
7067 0 : let available = locked.nodes.get(&node_id).is_some_and(|n| n.is_available());
7068 0 : if !available {
7069 0 : continue;
7070 0 : }
7071 0 :
7072 0 : if plan.len() >= fill_requirement
7073 0 : || tids_by_node.is_empty()
7074 0 : || attached <= expected_attached
7075 : {
7076 0 : break;
7077 0 : }
7078 0 :
7079 0 : let can_take = attached - expected_attached;
7080 0 : let needed = fill_requirement - plan.len();
7081 0 : let mut take = std::cmp::min(can_take, needed);
7082 0 :
7083 0 : let mut remove_node = false;
7084 0 : while take > 0 {
7085 0 : match tids_by_node.get_mut(&node_id) {
7086 0 : Some(tids) => match tids.pop() {
7087 0 : Some(tid) => {
7088 0 : let max_promote_for_tenant = std::cmp::max(
7089 0 : tid.shard_count.count() as usize / locked.nodes.len(),
7090 0 : 1,
7091 0 : );
7092 0 : let promoted = promoted_per_tenant.entry(tid.tenant_id).or_default();
7093 0 : if *promoted < max_promote_for_tenant {
7094 0 : plan.push(tid);
7095 0 : *promoted += 1;
7096 0 : take -= 1;
7097 0 : }
7098 : }
7099 : None => {
7100 0 : remove_node = true;
7101 0 : break;
7102 : }
7103 : },
7104 : None => {
7105 0 : break;
7106 : }
7107 : }
7108 : }
7109 :
7110 0 : if remove_node {
7111 0 : tids_by_node.remove(&node_id);
7112 0 : }
7113 : }
7114 :
7115 0 : plan
7116 0 : }
7117 :
7118 : /// Fill a node by promoting its secondaries until the cluster is balanced
7119 : /// with regards to attached shard counts. Note that this operation only
7120 : /// makes sense as a counterpart to the drain implemented in [`Service::drain_node`].
7121 : /// This is a long running operation and it should run as a separate Tokio task.
7122 0 : pub(crate) async fn fill_node(
7123 0 : &self,
7124 0 : node_id: NodeId,
7125 0 : cancel: CancellationToken,
7126 0 : ) -> Result<(), OperationError> {
7127 : const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(20);
7128 : const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
7129 0 : let reconciler_config = ReconcilerConfigBuilder::new()
7130 0 : .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
7131 0 : .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
7132 0 : .build();
7133 0 :
7134 0 : let mut tids_to_promote = self.fill_node_plan(node_id);
7135 0 : let mut waiters = Vec::new();
7136 :
7137 : // Execute the plan we've composed above. Before aplying each move from the plan,
7138 : // we validate to ensure that it has not gone stale in the meantime.
7139 0 : while !tids_to_promote.is_empty() {
7140 0 : if cancel.is_cancelled() {
7141 0 : match self
7142 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
7143 0 : .await
7144 : {
7145 0 : Ok(()) => return Err(OperationError::Cancelled),
7146 0 : Err(err) => {
7147 0 : return Err(OperationError::FinalizeError(
7148 0 : format!(
7149 0 : "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
7150 0 : node_id, err
7151 0 : )
7152 0 : .into(),
7153 0 : ));
7154 : }
7155 : }
7156 0 : }
7157 0 :
7158 0 : {
7159 0 : let mut locked = self.inner.write().unwrap();
7160 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
7161 :
7162 0 : let node = nodes.get(&node_id).ok_or(OperationError::NodeStateChanged(
7163 0 : format!("node {node_id} was removed").into(),
7164 0 : ))?;
7165 :
7166 0 : let current_policy = node.get_scheduling();
7167 0 : if !matches!(current_policy, NodeSchedulingPolicy::Filling) {
7168 : // TODO(vlad): maybe cancel pending reconciles before erroring out. need to think
7169 : // about it
7170 0 : return Err(OperationError::NodeStateChanged(
7171 0 : format!("node {node_id} changed state to {current_policy:?}").into(),
7172 0 : ));
7173 0 : }
7174 :
7175 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
7176 0 : if let Some(tid) = tids_to_promote.pop() {
7177 0 : if let Some(tenant_shard) = tenants.get_mut(&tid) {
7178 : // If the node being filled is not a secondary anymore,
7179 : // skip the promotion.
7180 0 : if !tenant_shard.intent.get_secondary().contains(&node_id) {
7181 0 : continue;
7182 0 : }
7183 0 :
7184 0 : let previously_attached_to = *tenant_shard.intent.get_attached();
7185 0 : match tenant_shard.reschedule_to_secondary(Some(node_id), scheduler) {
7186 0 : Err(e) => {
7187 0 : tracing::warn!(
7188 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
7189 0 : "Scheduling error when filling pageserver {} : {e}", node_id
7190 : );
7191 : }
7192 : Ok(()) => {
7193 0 : tracing::info!(
7194 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
7195 0 : "Rescheduled shard while filling node {}: {:?} -> {}",
7196 : node_id,
7197 : previously_attached_to,
7198 : node_id
7199 : );
7200 :
7201 0 : if let Some(waiter) = self.maybe_configured_reconcile_shard(
7202 0 : tenant_shard,
7203 0 : nodes,
7204 0 : reconciler_config,
7205 0 : ) {
7206 0 : waiters.push(waiter);
7207 0 : }
7208 : }
7209 : }
7210 0 : }
7211 : } else {
7212 0 : break;
7213 : }
7214 : }
7215 : }
7216 :
7217 0 : waiters = self
7218 0 : .await_waiters_remainder(waiters, WAITER_FILL_DRAIN_POLL_TIMEOUT)
7219 0 : .await;
7220 : }
7221 :
7222 0 : while !waiters.is_empty() {
7223 0 : if cancel.is_cancelled() {
7224 0 : match self
7225 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
7226 0 : .await
7227 : {
7228 0 : Ok(()) => return Err(OperationError::Cancelled),
7229 0 : Err(err) => {
7230 0 : return Err(OperationError::FinalizeError(
7231 0 : format!(
7232 0 : "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
7233 0 : node_id, err
7234 0 : )
7235 0 : .into(),
7236 0 : ));
7237 : }
7238 : }
7239 0 : }
7240 0 :
7241 0 : tracing::info!("Awaiting {} pending fill reconciliations", waiters.len());
7242 :
7243 0 : waiters = self
7244 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
7245 0 : .await;
7246 : }
7247 :
7248 0 : if let Err(err) = self
7249 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
7250 0 : .await
7251 : {
7252 : // This isn't a huge issue since the filling process starts upon request. However, it
7253 : // will prevent the next drain from starting. The only case in which this can fail
7254 : // is database unavailability. Such a case will require manual intervention.
7255 0 : return Err(OperationError::FinalizeError(
7256 0 : format!("Failed to finalise fill of {node_id} by setting scheduling policy to Active: {err}")
7257 0 : .into(),
7258 0 : ));
7259 0 : }
7260 0 :
7261 0 : Ok(())
7262 0 : }
7263 :
7264 : /// Updates scrubber metadata health check results.
7265 0 : pub(crate) async fn metadata_health_update(
7266 0 : &self,
7267 0 : update_req: MetadataHealthUpdateRequest,
7268 0 : ) -> Result<(), ApiError> {
7269 0 : let now = chrono::offset::Utc::now();
7270 0 : let (healthy_records, unhealthy_records) = {
7271 0 : let locked = self.inner.read().unwrap();
7272 0 : let healthy_records = update_req
7273 0 : .healthy_tenant_shards
7274 0 : .into_iter()
7275 0 : // Retain only health records associated with tenant shards managed by storage controller.
7276 0 : .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
7277 0 : .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, true, now))
7278 0 : .collect();
7279 0 : let unhealthy_records = update_req
7280 0 : .unhealthy_tenant_shards
7281 0 : .into_iter()
7282 0 : .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
7283 0 : .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, false, now))
7284 0 : .collect();
7285 0 :
7286 0 : (healthy_records, unhealthy_records)
7287 0 : };
7288 0 :
7289 0 : self.persistence
7290 0 : .update_metadata_health_records(healthy_records, unhealthy_records, now)
7291 0 : .await?;
7292 0 : Ok(())
7293 0 : }
7294 :
7295 : /// Lists the tenant shards that has unhealthy metadata status.
7296 0 : pub(crate) async fn metadata_health_list_unhealthy(
7297 0 : &self,
7298 0 : ) -> Result<Vec<TenantShardId>, ApiError> {
7299 0 : let result = self
7300 0 : .persistence
7301 0 : .list_unhealthy_metadata_health_records()
7302 0 : .await?
7303 0 : .iter()
7304 0 : .map(|p| p.get_tenant_shard_id().unwrap())
7305 0 : .collect();
7306 0 :
7307 0 : Ok(result)
7308 0 : }
7309 :
7310 : /// Lists the tenant shards that have not been scrubbed for some duration.
7311 0 : pub(crate) async fn metadata_health_list_outdated(
7312 0 : &self,
7313 0 : not_scrubbed_for: Duration,
7314 0 : ) -> Result<Vec<MetadataHealthRecord>, ApiError> {
7315 0 : let earlier = chrono::offset::Utc::now() - not_scrubbed_for;
7316 0 : let result = self
7317 0 : .persistence
7318 0 : .list_outdated_metadata_health_records(earlier)
7319 0 : .await?
7320 0 : .into_iter()
7321 0 : .map(|record| record.into())
7322 0 : .collect();
7323 0 : Ok(result)
7324 0 : }
7325 :
7326 0 : pub(crate) fn get_leadership_status(&self) -> LeadershipStatus {
7327 0 : self.inner.read().unwrap().get_leadership_status()
7328 0 : }
7329 :
7330 0 : pub(crate) async fn step_down(&self) -> GlobalObservedState {
7331 0 : tracing::info!("Received step down request from peer");
7332 0 : failpoint_support::sleep_millis_async!("sleep-on-step-down-handling");
7333 :
7334 0 : self.inner.write().unwrap().step_down();
7335 0 : // TODO: would it make sense to have a time-out for this?
7336 0 : self.stop_reconciliations(StopReconciliationsReason::SteppingDown)
7337 0 : .await;
7338 :
7339 0 : let mut global_observed = GlobalObservedState::default();
7340 0 : let locked = self.inner.read().unwrap();
7341 0 : for (tid, tenant_shard) in locked.tenants.iter() {
7342 0 : global_observed
7343 0 : .0
7344 0 : .insert(*tid, tenant_shard.observed.clone());
7345 0 : }
7346 :
7347 0 : global_observed
7348 0 : }
7349 :
7350 0 : pub(crate) async fn safekeepers_list(
7351 0 : &self,
7352 0 : ) -> Result<Vec<SafekeeperDescribeResponse>, DatabaseError> {
7353 0 : self.persistence
7354 0 : .list_safekeepers()
7355 0 : .await?
7356 0 : .into_iter()
7357 0 : .map(|v| v.as_describe_response())
7358 0 : .collect::<Result<Vec<_>, _>>()
7359 0 : }
7360 :
7361 0 : pub(crate) async fn get_safekeeper(
7362 0 : &self,
7363 0 : id: i64,
7364 0 : ) -> Result<SafekeeperDescribeResponse, DatabaseError> {
7365 0 : self.persistence
7366 0 : .safekeeper_get(id)
7367 0 : .await
7368 0 : .and_then(|v| v.as_describe_response())
7369 0 : }
7370 :
7371 0 : pub(crate) async fn upsert_safekeeper(
7372 0 : &self,
7373 0 : record: crate::persistence::SafekeeperUpsert,
7374 0 : ) -> Result<(), DatabaseError> {
7375 0 : self.persistence.safekeeper_upsert(record).await
7376 0 : }
7377 :
7378 0 : pub(crate) async fn update_shards_preferred_azs(
7379 0 : &self,
7380 0 : req: ShardsPreferredAzsRequest,
7381 0 : ) -> Result<ShardsPreferredAzsResponse, ApiError> {
7382 0 : let preferred_azs = req.preferred_az_ids.into_iter().collect::<Vec<_>>();
7383 0 : let updated = self
7384 0 : .persistence
7385 0 : .set_tenant_shard_preferred_azs(preferred_azs)
7386 0 : .await
7387 0 : .map_err(|err| {
7388 0 : ApiError::InternalServerError(anyhow::anyhow!(
7389 0 : "Failed to persist preferred AZs: {err}"
7390 0 : ))
7391 0 : })?;
7392 :
7393 0 : let mut updated_in_mem_and_db = Vec::default();
7394 0 :
7395 0 : let mut locked = self.inner.write().unwrap();
7396 0 : for (tid, az_id) in updated {
7397 0 : let shard = locked.tenants.get_mut(&tid);
7398 0 : if let Some(shard) = shard {
7399 0 : shard.set_preferred_az(az_id);
7400 0 : updated_in_mem_and_db.push(tid);
7401 0 : }
7402 : }
7403 :
7404 0 : Ok(ShardsPreferredAzsResponse {
7405 0 : updated: updated_in_mem_and_db,
7406 0 : })
7407 0 : }
7408 : }
|