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