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