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