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