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