Line data Source code
1 : pub mod chaos_injector;
2 : pub mod feature_flag;
3 : pub(crate) mod safekeeper_reconciler;
4 : mod safekeeper_service;
5 : mod tenant_shard_iterator;
6 :
7 : use std::borrow::Cow;
8 : use std::cmp::Ordering;
9 : use std::collections::{BTreeMap, HashMap, HashSet};
10 : use std::error::Error;
11 : use std::num::NonZeroU32;
12 : use std::ops::{Deref, DerefMut};
13 : use std::path::PathBuf;
14 : use std::str::FromStr;
15 : use std::sync::{Arc, OnceLock};
16 : use std::time::{Duration, Instant, SystemTime};
17 :
18 : use anyhow::Context;
19 : use control_plane::storage_controller::{
20 : AttachHookRequest, AttachHookResponse, InspectRequest, InspectResponse,
21 : };
22 : use diesel::result::DatabaseErrorKind;
23 : use futures::StreamExt;
24 : use futures::stream::FuturesUnordered;
25 : use http_utils::error::ApiError;
26 : use hyper::Uri;
27 : use itertools::Itertools;
28 : use pageserver_api::config::PostHogConfig;
29 : use pageserver_api::controller_api::{
30 : AvailabilityZone, MetadataHealthRecord, MetadataHealthUpdateRequest, NodeAvailability,
31 : NodeRegisterRequest, NodeSchedulingPolicy, NodeShard, NodeShardResponse, PlacementPolicy,
32 : ShardSchedulingPolicy, ShardsPreferredAzsRequest, ShardsPreferredAzsResponse,
33 : SkSchedulingPolicy, TenantCreateRequest, TenantCreateResponse, TenantCreateResponseShard,
34 : TenantDescribeResponse, TenantDescribeResponseShard, TenantLocateResponse, TenantPolicyRequest,
35 : TenantShardMigrateRequest, TenantShardMigrateResponse, TenantTimelineDescribeResponse,
36 : };
37 : use pageserver_api::models::{
38 : self, DetachBehavior, LocationConfig, LocationConfigListResponse, LocationConfigMode, LsnLease,
39 : PageserverUtilization, SecondaryProgress, ShardImportStatus, ShardParameters, TenantConfig,
40 : TenantConfigPatchRequest, TenantConfigRequest, TenantLocationConfigRequest,
41 : TenantLocationConfigResponse, TenantShardLocation, TenantShardSplitRequest,
42 : TenantShardSplitResponse, TenantSorting, TenantTimeTravelRequest,
43 : TimelineArchivalConfigRequest, TimelineCreateRequest, TimelineCreateResponseStorcon,
44 : TimelineInfo, TopTenantShardItem, TopTenantShardsRequest,
45 : };
46 : use pageserver_api::shard::{
47 : DEFAULT_STRIPE_SIZE, ShardCount, ShardIdentity, ShardNumber, ShardStripeSize, TenantShardId,
48 : };
49 : use pageserver_api::upcall_api::{
50 : PutTimelineImportStatusRequest, ReAttachRequest, ReAttachResponse, ReAttachResponseTenant,
51 : TimelineImportStatusRequest, ValidateRequest, ValidateResponse, ValidateResponseTenant,
52 : };
53 : use pageserver_client::{BlockUnblock, mgmt_api};
54 : use reqwest::{Certificate, StatusCode};
55 : use safekeeper_api::models::SafekeeperUtilization;
56 : use safekeeper_reconciler::SafekeeperReconcilers;
57 : use tenant_shard_iterator::{TenantShardExclusiveIterator, create_shared_shard_iterator};
58 : use tokio::sync::TryAcquireError;
59 : use tokio::sync::mpsc::error::TrySendError;
60 : use tokio_util::sync::CancellationToken;
61 : use tracing::{Instrument, debug, error, info, info_span, instrument, warn};
62 : use utils::completion::Barrier;
63 : use utils::env;
64 : use utils::generation::Generation;
65 : use utils::id::{NodeId, TenantId, TimelineId};
66 : use utils::lsn::Lsn;
67 : use utils::shard::ShardIndex;
68 : use utils::sync::gate::{Gate, GateGuard};
69 : use utils::{failpoint_support, pausable_failpoint};
70 :
71 : use crate::background_node_operations::{
72 : Delete, Drain, Fill, MAX_RECONCILES_PER_OPERATION, Operation, OperationError, OperationHandler,
73 : };
74 : use crate::compute_hook::{self, ComputeHook, NotifyError};
75 : use crate::heartbeater::{Heartbeater, PageserverState, SafekeeperState};
76 : use crate::id_lock_map::{
77 : IdLockMap, TracingExclusiveGuard, trace_exclusive_lock, trace_shared_lock,
78 : };
79 : use crate::leadership::Leadership;
80 : use crate::metrics;
81 : use crate::node::{AvailabilityTransition, Node};
82 : use crate::operation_utils::{self, TenantShardDrain, TenantShardDrainAction};
83 : use crate::pageserver_client::PageserverClient;
84 : use crate::peer_client::GlobalObservedState;
85 : use crate::persistence::split_state::SplitState;
86 : use crate::persistence::{
87 : AbortShardSplitStatus, ControllerPersistence, DatabaseError, DatabaseResult,
88 : MetadataHealthPersistence, Persistence, PersistenceConfig, ShardGenerationState, TenantFilter,
89 : TenantShardPersistence,
90 : };
91 : use crate::reconciler::{
92 : ReconcileError, ReconcileUnits, ReconcilerConfig, ReconcilerConfigBuilder, ReconcilerPriority,
93 : attached_location_conf,
94 : };
95 : use crate::safekeeper::Safekeeper;
96 : use crate::scheduler::{
97 : AttachedShardTag, MaySchedule, ScheduleContext, ScheduleError, ScheduleMode, Scheduler,
98 : };
99 : use crate::tenant_shard::{
100 : IntentState, MigrateAttachment, ObservedState, ObservedStateDelta, ObservedStateLocation,
101 : ReconcileNeeded, ReconcileResult, ReconcileWaitError, ReconcilerStatus, ReconcilerWaiter,
102 : ScheduleOptimization, ScheduleOptimizationAction, TenantShard,
103 : };
104 : use crate::timeline_import::{
105 : FinalizingImport, ImportResult, ShardImportStatuses, TimelineImport,
106 : TimelineImportFinalizeError, TimelineImportState, UpcallClient,
107 : };
108 :
109 : const WAITER_OPERATION_POLL_TIMEOUT: Duration = Duration::from_millis(500);
110 :
111 : // For operations that should be quick, like attaching a new tenant
112 : const SHORT_RECONCILE_TIMEOUT: Duration = Duration::from_secs(5);
113 :
114 : // For operations that might be slow, like migrating a tenant with
115 : // some data in it.
116 : pub const RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
117 :
118 : // If we receive a call using Secondary mode initially, it will omit generation. We will initialize
119 : // tenant shards into this generation, and as long as it remains in this generation, we will accept
120 : // input generation from future requests as authoritative.
121 : const INITIAL_GENERATION: Generation = Generation::new(0);
122 :
123 : /// How long [`Service::startup_reconcile`] is allowed to take before it should give
124 : /// up on unresponsive pageservers and proceed.
125 : pub(crate) const STARTUP_RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
126 :
127 : /// How long a node may be unresponsive to heartbeats before we declare it offline.
128 : /// This must be long enough to cover node restarts as well as normal operations: in future
129 : pub const MAX_OFFLINE_INTERVAL_DEFAULT: Duration = Duration::from_secs(30);
130 :
131 : /// How long a node may be unresponsive to heartbeats during start up before we declare it
132 : /// offline.
133 : ///
134 : /// This is much more lenient than [`MAX_OFFLINE_INTERVAL_DEFAULT`] since the pageserver's
135 : /// handling of the re-attach response may take a long time and blocks heartbeats from
136 : /// being handled on the pageserver side.
137 : pub const MAX_WARMING_UP_INTERVAL_DEFAULT: Duration = Duration::from_secs(300);
138 :
139 : /// How often to send heartbeats to registered nodes?
140 : pub const HEARTBEAT_INTERVAL_DEFAULT: Duration = Duration::from_secs(5);
141 :
142 : /// How long is too long for a reconciliation?
143 : pub const LONG_RECONCILE_THRESHOLD_DEFAULT: Duration = Duration::from_secs(120);
144 :
145 : #[derive(Clone, strum_macros::Display)]
146 : enum TenantOperations {
147 : Create,
148 : LocationConfig,
149 : ConfigSet,
150 : ConfigPatch,
151 : TimeTravelRemoteStorage,
152 : Delete,
153 : UpdatePolicy,
154 : ShardSplit,
155 : SecondaryDownload,
156 : TimelineCreate,
157 : TimelineDelete,
158 : AttachHook,
159 : TimelineArchivalConfig,
160 : TimelineDetachAncestor,
161 : TimelineGcBlockUnblock,
162 : DropDetached,
163 : DownloadHeatmapLayers,
164 : TimelineLsnLease,
165 : TimelineSafekeeperMigrate,
166 : }
167 :
168 : #[derive(Clone, strum_macros::Display)]
169 : enum NodeOperations {
170 : Register,
171 : Configure,
172 : Delete,
173 : DeleteTombstone,
174 : }
175 :
176 : /// The leadership status for the storage controller process.
177 : /// Allowed transitions are:
178 : /// 1. Leader -> SteppedDown
179 : /// 2. Candidate -> Leader
180 : #[derive(
181 : Eq,
182 : PartialEq,
183 : Copy,
184 : Clone,
185 : strum_macros::Display,
186 : strum_macros::EnumIter,
187 : measured::FixedCardinalityLabel,
188 : )]
189 : #[strum(serialize_all = "snake_case")]
190 : pub(crate) enum LeadershipStatus {
191 : /// This is the steady state where the storage controller can produce
192 : /// side effects in the cluster.
193 : Leader,
194 : /// We've been notified to step down by another candidate. No reconciliations
195 : /// take place in this state.
196 : SteppedDown,
197 : /// Initial state for a new storage controller instance. Will attempt to assume leadership.
198 : #[allow(unused)]
199 : Candidate,
200 : }
201 :
202 : enum ShardGenerationValidity {
203 : Valid,
204 : Mismatched {
205 : claimed: Generation,
206 : actual: Option<Generation>,
207 : },
208 : }
209 :
210 : pub const RECONCILER_CONCURRENCY_DEFAULT: usize = 128;
211 : pub const PRIORITY_RECONCILER_CONCURRENCY_DEFAULT: usize = 256;
212 : pub const SAFEKEEPER_RECONCILER_CONCURRENCY_DEFAULT: usize = 32;
213 :
214 : // Number of consecutive reconciliations that have occurred for one shard,
215 : // after which the shard is ignored when considering to run optimizations.
216 : const MAX_CONSECUTIVE_RECONCILES: usize = 10;
217 :
218 : // Depth of the channel used to enqueue shards for reconciliation when they can't do it immediately.
219 : // This channel is finite-size to avoid using excessive memory if we get into a state where reconciles are finishing more slowly
220 : // than they're being pushed onto the queue.
221 : const MAX_DELAYED_RECONCILES: usize = 10000;
222 :
223 : // Top level state available to all HTTP handlers
224 : struct ServiceState {
225 : leadership_status: LeadershipStatus,
226 :
227 : tenants: BTreeMap<TenantShardId, TenantShard>,
228 :
229 : nodes: Arc<HashMap<NodeId, Node>>,
230 :
231 : safekeepers: Arc<HashMap<NodeId, Safekeeper>>,
232 :
233 : safekeeper_reconcilers: SafekeeperReconcilers,
234 :
235 : scheduler: Scheduler,
236 :
237 : /// Ongoing background operation on the cluster if any is running.
238 : /// Note that only one such operation may run at any given time,
239 : /// hence the type choice.
240 : ongoing_operation: Option<OperationHandler>,
241 :
242 : /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
243 : delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
244 :
245 : /// Tracks ongoing timeline import finalization tasks
246 : imports_finalizing: BTreeMap<(TenantId, TimelineId), FinalizingImport>,
247 : }
248 :
249 : /// Transform an error from a pageserver into an error to return to callers of a storage
250 : /// controller API.
251 0 : fn passthrough_api_error(node: &Node, e: mgmt_api::Error) -> ApiError {
252 0 : match e {
253 0 : mgmt_api::Error::SendRequest(e) => {
254 : // Presume errors sending requests are connectivity/availability issues
255 0 : ApiError::ResourceUnavailable(format!("{node} error sending request: {e}").into())
256 : }
257 0 : mgmt_api::Error::ReceiveErrorBody(str) => {
258 : // Presume errors receiving body are connectivity/availability issues
259 0 : ApiError::ResourceUnavailable(
260 0 : format!("{node} error receiving error body: {str}").into(),
261 0 : )
262 : }
263 0 : mgmt_api::Error::ReceiveBody(err) if err.is_decode() => {
264 : // Return 500 for decoding errors.
265 0 : ApiError::InternalServerError(anyhow::Error::from(err).context("error decoding body"))
266 : }
267 0 : mgmt_api::Error::ReceiveBody(err) => {
268 : // Presume errors receiving body are connectivity/availability issues except for decoding errors
269 0 : let src_str = err.source().map(|e| e.to_string()).unwrap_or_default();
270 0 : ApiError::ResourceUnavailable(
271 0 : format!("{node} error receiving error body: {err} {src_str}").into(),
272 0 : )
273 : }
274 0 : mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, msg) => {
275 0 : ApiError::NotFound(anyhow::anyhow!(format!("{node}: {msg}")).into())
276 : }
277 0 : mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg) => {
278 0 : ApiError::ResourceUnavailable(format!("{node}: {msg}").into())
279 : }
280 0 : mgmt_api::Error::ApiError(status @ StatusCode::UNAUTHORIZED, msg)
281 0 : | mgmt_api::Error::ApiError(status @ StatusCode::FORBIDDEN, msg) => {
282 : // Auth errors talking to a pageserver are not auth errors for the caller: they are
283 : // internal server errors, showing that something is wrong with the pageserver or
284 : // storage controller's auth configuration.
285 0 : ApiError::InternalServerError(anyhow::anyhow!("{node} {status}: {msg}"))
286 : }
287 0 : mgmt_api::Error::ApiError(status @ StatusCode::TOO_MANY_REQUESTS, msg) => {
288 : // Pass through 429 errors: if pageserver is asking us to wait + retry, we in
289 : // turn ask our clients to wait + retry
290 0 : ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
291 : }
292 0 : mgmt_api::Error::ApiError(status, msg) => {
293 : // Presume general case of pageserver API errors is that we tried to do something
294 : // that can't be done right now.
295 0 : ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
296 : }
297 0 : mgmt_api::Error::Cancelled => ApiError::ShuttingDown,
298 0 : mgmt_api::Error::Timeout(e) => ApiError::Timeout(e.into()),
299 : }
300 0 : }
301 :
302 : impl ServiceState {
303 0 : fn new(
304 0 : nodes: HashMap<NodeId, Node>,
305 0 : safekeepers: HashMap<NodeId, Safekeeper>,
306 0 : tenants: BTreeMap<TenantShardId, TenantShard>,
307 0 : scheduler: Scheduler,
308 0 : delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
309 0 : initial_leadership_status: LeadershipStatus,
310 0 : reconcilers_cancel: CancellationToken,
311 0 : ) -> Self {
312 0 : metrics::update_leadership_status(initial_leadership_status);
313 :
314 0 : Self {
315 0 : leadership_status: initial_leadership_status,
316 0 : tenants,
317 0 : nodes: Arc::new(nodes),
318 0 : safekeepers: Arc::new(safekeepers),
319 0 : safekeeper_reconcilers: SafekeeperReconcilers::new(reconcilers_cancel),
320 0 : scheduler,
321 0 : ongoing_operation: None,
322 0 : delayed_reconcile_rx,
323 0 : imports_finalizing: Default::default(),
324 0 : }
325 0 : }
326 :
327 0 : fn parts_mut(
328 0 : &mut self,
329 0 : ) -> (
330 0 : &mut Arc<HashMap<NodeId, Node>>,
331 0 : &mut BTreeMap<TenantShardId, TenantShard>,
332 0 : &mut Scheduler,
333 0 : ) {
334 0 : (&mut self.nodes, &mut self.tenants, &mut self.scheduler)
335 0 : }
336 :
337 : #[allow(clippy::type_complexity)]
338 0 : fn parts_mut_sk(
339 0 : &mut self,
340 0 : ) -> (
341 0 : &mut Arc<HashMap<NodeId, Node>>,
342 0 : &mut Arc<HashMap<NodeId, Safekeeper>>,
343 0 : &mut BTreeMap<TenantShardId, TenantShard>,
344 0 : &mut Scheduler,
345 0 : ) {
346 0 : (
347 0 : &mut self.nodes,
348 0 : &mut self.safekeepers,
349 0 : &mut self.tenants,
350 0 : &mut self.scheduler,
351 0 : )
352 0 : }
353 :
354 0 : fn get_leadership_status(&self) -> LeadershipStatus {
355 0 : self.leadership_status
356 0 : }
357 :
358 0 : fn step_down(&mut self) {
359 0 : self.leadership_status = LeadershipStatus::SteppedDown;
360 0 : metrics::update_leadership_status(self.leadership_status);
361 0 : }
362 :
363 0 : fn become_leader(&mut self) {
364 0 : self.leadership_status = LeadershipStatus::Leader;
365 0 : metrics::update_leadership_status(self.leadership_status);
366 0 : }
367 : }
368 :
369 : #[derive(Clone)]
370 : pub struct Config {
371 : // All pageservers managed by one instance of this service must have
372 : // the same public key. This JWT token will be used to authenticate
373 : // this service to the pageservers it manages.
374 : pub pageserver_jwt_token: Option<String>,
375 :
376 : // All safekeepers managed by one instance of this service must have
377 : // the same public key. This JWT token will be used to authenticate
378 : // this service to the safekeepers it manages.
379 : pub safekeeper_jwt_token: Option<String>,
380 :
381 : // This JWT token will be used to authenticate this service to the control plane.
382 : pub control_plane_jwt_token: Option<String>,
383 :
384 : // This JWT token will be used to authenticate with other storage controller instances
385 : pub peer_jwt_token: Option<String>,
386 :
387 : /// Prefix for storage API endpoints of the control plane. We use this prefix to compute
388 : /// URLs that we use to send pageserver and safekeeper attachment locations.
389 : /// If this is None, the compute hook will assume it is running in a test environment
390 : /// and try to invoke neon_local instead.
391 : pub control_plane_url: Option<String>,
392 :
393 : /// Grace period within which a pageserver does not respond to heartbeats, but is still
394 : /// considered active. Once the grace period elapses, the next heartbeat failure will
395 : /// mark the pagseserver offline.
396 : pub max_offline_interval: Duration,
397 :
398 : /// Extended grace period within which pageserver may not respond to heartbeats.
399 : /// This extended grace period kicks in after the node has been drained for restart
400 : /// and/or upon handling the re-attach request from a node.
401 : pub max_warming_up_interval: Duration,
402 :
403 : /// How many normal-priority Reconcilers may be spawned concurrently
404 : pub reconciler_concurrency: usize,
405 :
406 : /// How many high-priority Reconcilers may be spawned concurrently
407 : pub priority_reconciler_concurrency: usize,
408 :
409 : /// How many safekeeper reconciles may happen concurrently (per safekeeper)
410 : pub safekeeper_reconciler_concurrency: usize,
411 :
412 : /// How many API requests per second to allow per tenant, across all
413 : /// tenant-scoped API endpoints. Further API requests queue until ready.
414 : pub tenant_rate_limit: NonZeroU32,
415 :
416 : /// If a tenant shard's largest timeline (max_logical_size) exceeds this value, all tenant
417 : /// shards will be split in 2 until they fall below split_threshold (up to max_split_shards).
418 : ///
419 : /// This will greedily split into as many shards as necessary to fall below split_threshold, as
420 : /// powers of 2: if a tenant shard is 7 times larger than split_threshold, it will split into 8
421 : /// immediately, rather than first 2 then 4 then 8.
422 : ///
423 : /// None or 0 disables auto-splitting.
424 : ///
425 : /// TODO: consider using total logical size of all timelines instead.
426 : pub split_threshold: Option<u64>,
427 :
428 : /// The maximum number of shards a tenant can be split into during autosplits. Does not affect
429 : /// manual split requests. 0 or 1 disables autosplits, as we already have 1 shard.
430 : pub max_split_shards: u8,
431 :
432 : /// The size at which an unsharded tenant should initially split. Ingestion is significantly
433 : /// faster with multiple shards, so eagerly splitting below split_threshold will typically speed
434 : /// up initial ingestion of large tenants.
435 : ///
436 : /// This should be below split_threshold, but it is not required. If both split_threshold and
437 : /// initial_split_threshold qualify, the largest number of target shards will be used.
438 : ///
439 : /// Does not apply to already sharded tenants: changing initial_split_threshold or
440 : /// initial_split_shards is not retroactive for already-sharded tenants.
441 : ///
442 : /// None or 0 disables initial splits.
443 : pub initial_split_threshold: Option<u64>,
444 :
445 : /// The number of shards to split into when reaching initial_split_threshold. Will
446 : /// be clamped to max_split_shards.
447 : ///
448 : /// 0 or 1 disables initial splits. Has no effect if initial_split_threshold is disabled.
449 : pub initial_split_shards: u8,
450 :
451 : // TODO: make this cfg(feature = "testing")
452 : pub neon_local_repo_dir: Option<PathBuf>,
453 :
454 : // Maximum acceptable download lag for the secondary location
455 : // while draining a node. If the secondary location is lagging
456 : // by more than the configured amount, then the secondary is not
457 : // upgraded to primary.
458 : pub max_secondary_lag_bytes: Option<u64>,
459 :
460 : pub heartbeat_interval: Duration,
461 :
462 : pub address_for_peers: Option<Uri>,
463 :
464 : pub start_as_candidate: bool,
465 :
466 : pub long_reconcile_threshold: Duration,
467 :
468 : pub use_https_pageserver_api: bool,
469 :
470 : pub use_https_safekeeper_api: bool,
471 :
472 : pub ssl_ca_certs: Vec<Certificate>,
473 :
474 : pub timelines_onto_safekeepers: bool,
475 :
476 : pub use_local_compute_notifications: bool,
477 :
478 : /// Number of safekeepers to choose for a timeline when creating it.
479 : /// Safekeepers will be choosen from different availability zones.
480 : pub timeline_safekeeper_count: usize,
481 :
482 : /// PostHog integration config
483 : pub posthog_config: Option<PostHogConfig>,
484 :
485 : /// When set, actively checks and initiates heatmap downloads/uploads.
486 : pub kick_secondary_downloads: bool,
487 :
488 : /// Timeout used for HTTP client of split requests. [`Duration::MAX`] if None.
489 : pub shard_split_request_timeout: Duration,
490 :
491 : // Feature flag: Whether the storage controller should act to rectify pageserver-reported local disk loss.
492 : pub handle_ps_local_disk_loss: bool,
493 :
494 : pub persistence_config: PersistenceConfig,
495 : }
496 :
497 : impl From<DatabaseError> for ApiError {
498 0 : fn from(err: DatabaseError) -> ApiError {
499 0 : match err {
500 0 : DatabaseError::Query(e) => ApiError::InternalServerError(e.into()),
501 : // FIXME: ApiError doesn't have an Unavailable variant, but ShuttingDown maps to 503.
502 : DatabaseError::Connection(_) | DatabaseError::ConnectionPool(_) => {
503 0 : ApiError::ShuttingDown
504 : }
505 0 : DatabaseError::Logical(reason) | DatabaseError::Migration(reason) => {
506 0 : ApiError::InternalServerError(anyhow::anyhow!(reason))
507 : }
508 0 : DatabaseError::Cas(reason) => ApiError::Conflict(reason),
509 : }
510 0 : }
511 : }
512 :
513 : enum InitialShardScheduleOutcome {
514 : Scheduled(TenantCreateResponseShard),
515 : NotScheduled,
516 : ShardScheduleError(ScheduleError),
517 : }
518 :
519 : pub struct Service {
520 : inner: Arc<std::sync::RwLock<ServiceState>>,
521 : config: Config,
522 : persistence: Arc<Persistence>,
523 : compute_hook: Arc<ComputeHook>,
524 : result_tx: tokio::sync::mpsc::UnboundedSender<ReconcileResultRequest>,
525 :
526 : heartbeater_ps: Heartbeater<Node, PageserverState>,
527 : heartbeater_sk: Heartbeater<Safekeeper, SafekeeperState>,
528 :
529 : // Channel for background cleanup from failed operations that require cleanup, such as shard split
530 : abort_tx: tokio::sync::mpsc::UnboundedSender<TenantShardSplitAbort>,
531 :
532 : // Locking on a tenant granularity (covers all shards in the tenant):
533 : // - Take exclusively for rare operations that mutate the tenant's persistent state (e.g. create/delete/split)
534 : // - Take in shared mode for operations that need the set of shards to stay the same to complete reliably (e.g. timeline CRUD)
535 : tenant_op_locks: IdLockMap<TenantId, TenantOperations>,
536 :
537 : // Locking for node-mutating operations: take exclusively for operations that modify the node's persistent state, or
538 : // that transition it to/from Active.
539 : node_op_locks: IdLockMap<NodeId, NodeOperations>,
540 :
541 : // Limit how many Reconcilers we will spawn concurrently for normal-priority tasks such as background reconciliations
542 : // and reconciliation on startup.
543 : reconciler_concurrency: Arc<tokio::sync::Semaphore>,
544 :
545 : // Limit how many Reconcilers we will spawn concurrently for high-priority tasks such as tenant/timeline CRUD, which
546 : // a human user might be waiting for.
547 : priority_reconciler_concurrency: Arc<tokio::sync::Semaphore>,
548 :
549 : /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
550 : /// Send into this queue to promptly attempt to reconcile this shard next time units are available.
551 : ///
552 : /// Note that this state logically lives inside ServiceState, but carrying Sender here makes the code simpler
553 : /// by avoiding needing a &mut ref to something inside the ServiceState. This could be optimized to
554 : /// use a VecDeque instead of a channel to reduce synchronization overhead, at the cost of some code complexity.
555 : delayed_reconcile_tx: tokio::sync::mpsc::Sender<TenantShardId>,
556 :
557 : // Process shutdown will fire this token
558 : cancel: CancellationToken,
559 :
560 : // Child token of [`Service::cancel`] used by reconcilers
561 : reconcilers_cancel: CancellationToken,
562 :
563 : // Background tasks will hold this gate
564 : gate: Gate,
565 :
566 : // Reconcilers background tasks will hold this gate
567 : reconcilers_gate: Gate,
568 :
569 : /// This waits for initial reconciliation with pageservers to complete. Until this barrier
570 : /// passes, it isn't safe to do any actions that mutate tenants.
571 : pub(crate) startup_complete: Barrier,
572 :
573 : /// HTTP client with proper CA certs.
574 : http_client: reqwest::Client,
575 :
576 : /// Handle for the step down background task if one was ever requested
577 : step_down_barrier: OnceLock<tokio::sync::watch::Receiver<Option<GlobalObservedState>>>,
578 : }
579 :
580 : impl From<ReconcileWaitError> for ApiError {
581 0 : fn from(value: ReconcileWaitError) -> Self {
582 0 : match value {
583 0 : ReconcileWaitError::Shutdown => ApiError::ShuttingDown,
584 0 : e @ ReconcileWaitError::Timeout(_) => ApiError::Timeout(format!("{e}").into()),
585 0 : e @ ReconcileWaitError::Failed(..) => ApiError::InternalServerError(anyhow::anyhow!(e)),
586 : }
587 0 : }
588 : }
589 :
590 : impl From<OperationError> for ApiError {
591 0 : fn from(value: OperationError) -> Self {
592 0 : match value {
593 0 : OperationError::NodeStateChanged(err)
594 0 : | OperationError::FinalizeError(err)
595 0 : | OperationError::ImpossibleConstraint(err) => {
596 0 : ApiError::InternalServerError(anyhow::anyhow!(err))
597 : }
598 0 : OperationError::Cancelled => ApiError::Conflict("Operation was cancelled".into()),
599 : }
600 0 : }
601 : }
602 :
603 : #[allow(clippy::large_enum_variant)]
604 : enum TenantCreateOrUpdate {
605 : Create(TenantCreateRequest),
606 : Update(Vec<ShardUpdate>),
607 : }
608 :
609 : struct ShardSplitParams {
610 : old_shard_count: ShardCount,
611 : new_shard_count: ShardCount,
612 : new_stripe_size: Option<ShardStripeSize>,
613 : targets: Vec<ShardSplitTarget>,
614 : policy: PlacementPolicy,
615 : config: TenantConfig,
616 : shard_ident: ShardIdentity,
617 : preferred_az_id: Option<AvailabilityZone>,
618 : }
619 :
620 : // When preparing for a shard split, we may either choose to proceed with the split,
621 : // or find that the work is already done and return NoOp.
622 : enum ShardSplitAction {
623 : Split(Box<ShardSplitParams>),
624 : NoOp(TenantShardSplitResponse),
625 : }
626 :
627 : // A parent shard which will be split
628 : struct ShardSplitTarget {
629 : parent_id: TenantShardId,
630 : node: Node,
631 : child_ids: Vec<TenantShardId>,
632 : }
633 :
634 : /// When we tenant shard split operation fails, we may not be able to clean up immediately, because nodes
635 : /// might not be available. We therefore use a queue of abort operations processed in the background.
636 : struct TenantShardSplitAbort {
637 : tenant_id: TenantId,
638 : /// The target values from the request that failed
639 : new_shard_count: ShardCount,
640 : new_stripe_size: Option<ShardStripeSize>,
641 : /// Until this abort op is complete, no other operations may be done on the tenant
642 : _tenant_lock: TracingExclusiveGuard<TenantOperations>,
643 : /// The reconciler gate for the duration of the split operation, and any included abort.
644 : _gate: GateGuard,
645 : }
646 :
647 : #[derive(thiserror::Error, Debug)]
648 : enum TenantShardSplitAbortError {
649 : #[error(transparent)]
650 : Database(#[from] DatabaseError),
651 : #[error(transparent)]
652 : Remote(#[from] mgmt_api::Error),
653 : #[error("Unavailable")]
654 : Unavailable,
655 : }
656 :
657 : /// Inputs for computing a target shard count for a tenant.
658 : struct ShardSplitInputs {
659 : /// Current shard count.
660 : shard_count: ShardCount,
661 : /// Total size of largest timeline summed across all shards.
662 : max_logical_size: u64,
663 : /// Size-based split threshold. Zero if size-based splits are disabled.
664 : split_threshold: u64,
665 : /// Upper bound on target shards. 0 or 1 disables splits.
666 : max_split_shards: u8,
667 : /// Initial split threshold. Zero if initial splits are disabled.
668 : initial_split_threshold: u64,
669 : /// Number of shards for initial splits. 0 or 1 disables initial splits.
670 : initial_split_shards: u8,
671 : }
672 :
673 : struct ShardUpdate {
674 : tenant_shard_id: TenantShardId,
675 : placement_policy: PlacementPolicy,
676 : tenant_config: TenantConfig,
677 :
678 : /// If this is None, generation is not updated.
679 : generation: Option<Generation>,
680 :
681 : /// If this is None, scheduling policy is not updated.
682 : scheduling_policy: Option<ShardSchedulingPolicy>,
683 : }
684 :
685 : enum StopReconciliationsReason {
686 : ShuttingDown,
687 : SteppingDown,
688 : }
689 :
690 : impl std::fmt::Display for StopReconciliationsReason {
691 0 : fn fmt(&self, writer: &mut std::fmt::Formatter) -> std::fmt::Result {
692 0 : let s = match self {
693 0 : Self::ShuttingDown => "Shutting down",
694 0 : Self::SteppingDown => "Stepping down",
695 : };
696 0 : write!(writer, "{s}")
697 0 : }
698 : }
699 :
700 : pub(crate) enum ReconcileResultRequest {
701 : ReconcileResult(ReconcileResult),
702 : Stop,
703 : }
704 :
705 : #[derive(Clone)]
706 : pub(crate) struct MutationLocation {
707 : pub(crate) node: Node,
708 : pub(crate) generation: Generation,
709 : }
710 :
711 : #[derive(Clone)]
712 : pub(crate) struct ShardMutationLocations {
713 : pub(crate) latest: MutationLocation,
714 : pub(crate) other: Vec<MutationLocation>,
715 : }
716 :
717 : #[derive(Default, Clone)]
718 : pub(crate) struct TenantMutationLocations(pub BTreeMap<TenantShardId, ShardMutationLocations>);
719 :
720 : struct ReconcileAllResult {
721 : spawned_reconciles: usize,
722 : stuck_reconciles: usize,
723 : has_delayed_reconciles: bool,
724 : }
725 :
726 : impl ReconcileAllResult {
727 0 : fn new(
728 0 : spawned_reconciles: usize,
729 0 : stuck_reconciles: usize,
730 0 : has_delayed_reconciles: bool,
731 0 : ) -> Self {
732 0 : assert!(
733 0 : spawned_reconciles >= stuck_reconciles,
734 0 : "It is impossible to have less spawned reconciles than stuck reconciles"
735 : );
736 0 : Self {
737 0 : spawned_reconciles,
738 0 : stuck_reconciles,
739 0 : has_delayed_reconciles,
740 0 : }
741 0 : }
742 :
743 : /// We can run optimizations only if we don't have any delayed reconciles and
744 : /// all spawned reconciles are also stuck reconciles.
745 0 : fn can_run_optimizations(&self) -> bool {
746 0 : !self.has_delayed_reconciles && self.spawned_reconciles == self.stuck_reconciles
747 0 : }
748 : }
749 :
750 : enum TenantIdOrShardId {
751 : TenantId(TenantId),
752 : TenantShardId(TenantShardId),
753 : }
754 :
755 : impl TenantIdOrShardId {
756 0 : fn tenant_id(&self) -> TenantId {
757 0 : match self {
758 0 : TenantIdOrShardId::TenantId(tenant_id) => *tenant_id,
759 0 : TenantIdOrShardId::TenantShardId(tenant_shard_id) => tenant_shard_id.tenant_id,
760 : }
761 0 : }
762 :
763 0 : fn matches(&self, tenant_shard_id: &TenantShardId) -> bool {
764 0 : match self {
765 0 : TenantIdOrShardId::TenantId(tenant_id) => tenant_shard_id.tenant_id == *tenant_id,
766 0 : TenantIdOrShardId::TenantShardId(this_tenant_shard_id) => {
767 0 : this_tenant_shard_id == tenant_shard_id
768 : }
769 : }
770 0 : }
771 : }
772 :
773 : impl Service {
774 0 : pub fn get_config(&self) -> &Config {
775 0 : &self.config
776 0 : }
777 :
778 0 : pub fn get_http_client(&self) -> &reqwest::Client {
779 0 : &self.http_client
780 0 : }
781 :
782 : /// Called once on startup, this function attempts to contact all pageservers to build an up-to-date
783 : /// view of the world, and determine which pageservers are responsive.
784 : #[instrument(skip_all)]
785 : async fn startup_reconcile(
786 : self: &Arc<Service>,
787 : current_leader: Option<ControllerPersistence>,
788 : leader_step_down_state: Option<GlobalObservedState>,
789 : bg_compute_notify_result_tx: tokio::sync::mpsc::Sender<
790 : Result<(), (TenantShardId, NotifyError)>,
791 : >,
792 : ) {
793 : // Startup reconciliation does I/O to other services: whether they
794 : // are responsive or not, we should aim to finish within our deadline, because:
795 : // - If we don't, a k8s readiness hook watching /ready will kill us.
796 : // - While we're waiting for startup reconciliation, we are not fully
797 : // available for end user operations like creating/deleting tenants and timelines.
798 : //
799 : // We set multiple deadlines to break up the time available between the phases of work: this is
800 : // arbitrary, but avoids a situation where the first phase could burn our entire timeout period.
801 : let start_at = Instant::now();
802 : let node_scan_deadline = start_at
803 : .checked_add(STARTUP_RECONCILE_TIMEOUT / 2)
804 : .expect("Reconcile timeout is a modest constant");
805 :
806 : let observed = if let Some(state) = leader_step_down_state {
807 : tracing::info!(
808 : "Using observed state received from leader at {}",
809 : current_leader.as_ref().unwrap().address
810 : );
811 :
812 : state
813 : } else {
814 : self.build_global_observed_state(node_scan_deadline).await
815 : };
816 :
817 : // Accumulate a list of any tenant locations that ought to be detached
818 : let mut cleanup = Vec::new();
819 :
820 : // Send initial heartbeat requests to all nodes loaded from the database
821 : let all_nodes = {
822 : let locked = self.inner.read().unwrap();
823 : locked.nodes.clone()
824 : };
825 : let (mut nodes_online, mut sks_online) =
826 : self.initial_heartbeat_round(all_nodes.keys()).await;
827 :
828 : // List of tenants for which we will attempt to notify compute of their location at startup
829 : let mut compute_notifications = Vec::new();
830 :
831 : // Populate intent and observed states for all tenants, based on reported state on pageservers
832 : tracing::info!("Populating tenant shards' states from initial pageserver scan...");
833 : let shard_count = {
834 : let mut locked = self.inner.write().unwrap();
835 : let (nodes, safekeepers, tenants, scheduler) = locked.parts_mut_sk();
836 :
837 : // Mark nodes online if they responded to us: nodes are offline by default after a restart.
838 : let mut new_nodes = (**nodes).clone();
839 : for (node_id, node) in new_nodes.iter_mut() {
840 : if let Some(utilization) = nodes_online.remove(node_id) {
841 : node.set_availability(NodeAvailability::Active(utilization));
842 : scheduler.node_upsert(node);
843 : }
844 : }
845 : *nodes = Arc::new(new_nodes);
846 :
847 : let mut new_sks = (**safekeepers).clone();
848 : for (node_id, node) in new_sks.iter_mut() {
849 : if let Some((utilization, last_seen_at)) = sks_online.remove(node_id) {
850 : node.set_availability(SafekeeperState::Available {
851 : utilization,
852 : last_seen_at,
853 : });
854 : }
855 : }
856 : *safekeepers = Arc::new(new_sks);
857 :
858 : for (tenant_shard_id, observed_state) in observed.0 {
859 : let Some(tenant_shard) = tenants.get_mut(&tenant_shard_id) else {
860 : for node_id in observed_state.locations.keys() {
861 : cleanup.push((tenant_shard_id, *node_id));
862 : }
863 :
864 : continue;
865 : };
866 :
867 : tenant_shard.observed = observed_state;
868 : }
869 :
870 : // Populate each tenant's intent state
871 : let mut schedule_context = ScheduleContext::default();
872 : for (tenant_shard_id, tenant_shard) in tenants.iter_mut() {
873 : if tenant_shard_id.shard_number == ShardNumber(0) {
874 : // Reset scheduling context each time we advance to the next Tenant
875 : schedule_context = ScheduleContext::default();
876 : }
877 :
878 : tenant_shard.intent_from_observed(scheduler);
879 : if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
880 : // Non-fatal error: we are unable to properly schedule the tenant, perhaps because
881 : // not enough pageservers are available. The tenant may well still be available
882 : // to clients.
883 : tracing::error!("Failed to schedule tenant {tenant_shard_id} at startup: {e}");
884 : } else {
885 : // If we're both intending and observed to be attached at a particular node, we will
886 : // emit a compute notification for this. In the case where our observed state does not
887 : // yet match our intent, we will eventually reconcile, and that will emit a compute notification.
888 : if let Some(attached_at) = tenant_shard.stably_attached() {
889 : compute_notifications.push(compute_hook::ShardUpdate {
890 : tenant_shard_id: *tenant_shard_id,
891 : node_id: attached_at,
892 : stripe_size: tenant_shard.shard.stripe_size,
893 : preferred_az: tenant_shard
894 : .preferred_az()
895 0 : .map(|az| Cow::Owned(az.clone())),
896 : });
897 : }
898 : }
899 : }
900 :
901 : tenants.len()
902 : };
903 :
904 : // Before making any obeservable changes to the cluster, persist self
905 : // as leader in database and memory.
906 : let leadership = Leadership::new(
907 : self.persistence.clone(),
908 : self.config.clone(),
909 : self.cancel.child_token(),
910 : );
911 :
912 : if let Err(e) = leadership.become_leader(current_leader).await {
913 : tracing::error!("Failed to persist self as leader: {e}. Aborting start-up ...");
914 : std::process::exit(1);
915 : }
916 :
917 : let safekeepers = self.inner.read().unwrap().safekeepers.clone();
918 : let sk_schedule_requests =
919 : match safekeeper_reconciler::load_schedule_requests(self, &safekeepers).await {
920 : Ok(v) => v,
921 : Err(e) => {
922 : tracing::warn!(
923 : "Failed to load safekeeper pending ops at startup: {e}." // Don't abort for now: " Aborting start-up..."
924 : );
925 : // std::process::exit(1);
926 : Vec::new()
927 : }
928 : };
929 :
930 : {
931 : let mut locked = self.inner.write().unwrap();
932 : locked.become_leader();
933 :
934 : for (sk_id, _sk) in locked.safekeepers.clone().iter() {
935 : locked.safekeeper_reconcilers.start_reconciler(*sk_id, self);
936 : }
937 :
938 : locked
939 : .safekeeper_reconcilers
940 : .schedule_request_vec(sk_schedule_requests);
941 : }
942 :
943 : // TODO: if any tenant's intent now differs from its loaded generation_pageserver, we should clear that
944 : // generation_pageserver in the database.
945 :
946 : // Emit compute hook notifications for all tenants which are already stably attached. Other tenants
947 : // will emit compute hook notifications when they reconcile.
948 : //
949 : // Ordering: our calls to notify_attach_background synchronously establish a relative order for these notifications vs. any later
950 : // calls into the ComputeHook for the same tenant: we can leave these to run to completion in the background and any later
951 : // calls will be correctly ordered wrt these.
952 : //
953 : // Concurrency: we call notify_attach_background for all tenants, which will create O(N) tokio tasks, but almost all of them
954 : // will just wait on the ComputeHook::API_CONCURRENCY semaphore immediately, so very cheap until they get that semaphore
955 : // unit and start doing I/O.
956 : tracing::info!(
957 : "Sending {} compute notifications",
958 : compute_notifications.len()
959 : );
960 : self.compute_hook.notify_attach_background(
961 : compute_notifications,
962 : bg_compute_notify_result_tx.clone(),
963 : &self.cancel,
964 : );
965 :
966 : // Finally, now that the service is up and running, launch reconcile operations for any tenants
967 : // which require it: under normal circumstances this should only include tenants that were in some
968 : // transient state before we restarted, or any tenants whose compute hooks failed above.
969 : tracing::info!("Checking for shards in need of reconciliation...");
970 : let reconcile_all_result = self.reconcile_all();
971 : // We will not wait for these reconciliation tasks to run here: we're now done with startup and
972 : // normal operations may proceed.
973 :
974 : // Clean up any tenants that were found on pageservers but are not known to us. Do this in the
975 : // background because it does not need to complete in order to proceed with other work.
976 : if !cleanup.is_empty() {
977 : tracing::info!("Cleaning up {} locations in the background", cleanup.len());
978 : tokio::task::spawn({
979 : let cleanup_self = self.clone();
980 0 : async move { cleanup_self.cleanup_locations(cleanup).await }
981 : });
982 : }
983 :
984 : // Reconcile the timeline imports:
985 : // 1. Mark each tenant shard of tenants with an importing timeline as importing.
986 : // 2. Finalize the completed imports in the background. This handles the case where
987 : // the previous storage controller instance shut down whilst finalizing imports.
988 : let imports = self.persistence.list_timeline_imports().await;
989 : match imports {
990 : Ok(mut imports) => {
991 : {
992 : let mut locked = self.inner.write().unwrap();
993 : for import in &imports {
994 : locked
995 : .tenants
996 : .range_mut(TenantShardId::tenant_range(import.tenant_id))
997 0 : .for_each(|(_id, shard)| {
998 0 : shard.importing = TimelineImportState::Importing
999 0 : });
1000 : }
1001 : }
1002 :
1003 0 : imports.retain(|import| import.is_complete());
1004 : tokio::task::spawn({
1005 : let finalize_imports_self = self.clone();
1006 0 : async move {
1007 0 : finalize_imports_self
1008 0 : .finalize_timeline_imports(imports)
1009 0 : .await
1010 0 : }
1011 : });
1012 : }
1013 : Err(err) => {
1014 : tracing::error!("Could not retrieve completed imports from database: {err}");
1015 : }
1016 : }
1017 :
1018 : let spawned_reconciles = reconcile_all_result.spawned_reconciles;
1019 : tracing::info!(
1020 : "Startup complete, spawned {spawned_reconciles} reconciliation tasks ({shard_count} shards total)"
1021 : );
1022 : }
1023 :
1024 0 : async fn initial_heartbeat_round<'a>(
1025 0 : &self,
1026 0 : node_ids: impl Iterator<Item = &'a NodeId>,
1027 0 : ) -> (
1028 0 : HashMap<NodeId, PageserverUtilization>,
1029 0 : HashMap<NodeId, (SafekeeperUtilization, Instant)>,
1030 0 : ) {
1031 0 : assert!(!self.startup_complete.is_ready());
1032 :
1033 0 : let all_nodes = {
1034 0 : let locked = self.inner.read().unwrap();
1035 0 : locked.nodes.clone()
1036 : };
1037 :
1038 0 : let mut nodes_to_heartbeat = HashMap::new();
1039 0 : for node_id in node_ids {
1040 0 : match all_nodes.get(node_id) {
1041 0 : Some(node) => {
1042 0 : nodes_to_heartbeat.insert(*node_id, node.clone());
1043 0 : }
1044 : None => {
1045 0 : tracing::warn!("Node {node_id} was removed during start-up");
1046 : }
1047 : }
1048 : }
1049 :
1050 0 : let all_sks = {
1051 0 : let locked = self.inner.read().unwrap();
1052 0 : locked.safekeepers.clone()
1053 : };
1054 :
1055 0 : tracing::info!("Sending initial heartbeats...");
1056 0 : let (res_ps, res_sk) = tokio::join!(
1057 0 : self.heartbeater_ps.heartbeat(Arc::new(nodes_to_heartbeat)),
1058 0 : self.heartbeater_sk.heartbeat(all_sks)
1059 : );
1060 :
1061 0 : let mut online_nodes = HashMap::new();
1062 0 : if let Ok(deltas) = res_ps {
1063 0 : for (node_id, status) in deltas.0 {
1064 0 : match status {
1065 0 : PageserverState::Available { utilization, .. } => {
1066 0 : online_nodes.insert(node_id, utilization);
1067 0 : }
1068 0 : PageserverState::Offline => {}
1069 : PageserverState::WarmingUp { .. } => {
1070 0 : unreachable!("Nodes are never marked warming-up during startup reconcile")
1071 : }
1072 : }
1073 : }
1074 0 : }
1075 :
1076 0 : let mut online_sks = HashMap::new();
1077 0 : if let Ok(deltas) = res_sk {
1078 0 : for (node_id, status) in deltas.0 {
1079 0 : match status {
1080 : SafekeeperState::Available {
1081 0 : utilization,
1082 0 : last_seen_at,
1083 0 : } => {
1084 0 : online_sks.insert(node_id, (utilization, last_seen_at));
1085 0 : }
1086 0 : SafekeeperState::Offline => {}
1087 : }
1088 : }
1089 0 : }
1090 :
1091 0 : (online_nodes, online_sks)
1092 0 : }
1093 :
1094 : /// Used during [`Self::startup_reconcile`]: issue GETs to all nodes concurrently, with a deadline.
1095 : ///
1096 : /// The result includes only nodes which responded within the deadline
1097 0 : async fn scan_node_locations(
1098 0 : &self,
1099 0 : deadline: Instant,
1100 0 : ) -> HashMap<NodeId, LocationConfigListResponse> {
1101 0 : let nodes = {
1102 0 : let locked = self.inner.read().unwrap();
1103 0 : locked.nodes.clone()
1104 : };
1105 :
1106 0 : let mut node_results = HashMap::new();
1107 :
1108 0 : let mut node_list_futs = FuturesUnordered::new();
1109 :
1110 0 : tracing::info!("Scanning shards on {} nodes...", nodes.len());
1111 0 : for node in nodes.values() {
1112 0 : node_list_futs.push({
1113 0 : async move {
1114 0 : tracing::info!("Scanning shards on node {node}...");
1115 0 : let timeout = Duration::from_secs(5);
1116 0 : let response = node
1117 0 : .with_client_retries(
1118 0 : |client| async move { client.list_location_config().await },
1119 0 : &self.http_client,
1120 0 : &self.config.pageserver_jwt_token,
1121 : 1,
1122 : 5,
1123 0 : timeout,
1124 0 : &self.cancel,
1125 : )
1126 0 : .await;
1127 0 : (node.get_id(), response)
1128 0 : }
1129 : });
1130 : }
1131 :
1132 : loop {
1133 0 : let (node_id, result) = tokio::select! {
1134 0 : next = node_list_futs.next() => {
1135 0 : match next {
1136 0 : Some(result) => result,
1137 : None =>{
1138 : // We got results for all our nodes
1139 0 : break;
1140 : }
1141 :
1142 : }
1143 : },
1144 0 : _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
1145 : // Give up waiting for anyone who hasn't responded: we will yield the results that we have
1146 0 : tracing::info!("Reached deadline while waiting for nodes to respond to location listing requests");
1147 0 : break;
1148 : }
1149 : };
1150 :
1151 0 : let Some(list_response) = result else {
1152 0 : tracing::info!("Shutdown during startup_reconcile");
1153 0 : break;
1154 : };
1155 :
1156 0 : match list_response {
1157 0 : Err(e) => {
1158 0 : tracing::warn!("Could not scan node {} ({e})", node_id);
1159 : }
1160 0 : Ok(listing) => {
1161 0 : node_results.insert(node_id, listing);
1162 0 : }
1163 : }
1164 : }
1165 :
1166 0 : node_results
1167 0 : }
1168 :
1169 0 : async fn build_global_observed_state(&self, deadline: Instant) -> GlobalObservedState {
1170 0 : let node_listings = self.scan_node_locations(deadline).await;
1171 0 : let mut observed = GlobalObservedState::default();
1172 :
1173 0 : for (node_id, location_confs) in node_listings {
1174 0 : tracing::info!(
1175 0 : "Received {} shard statuses from pageserver {}",
1176 0 : location_confs.tenant_shards.len(),
1177 : node_id
1178 : );
1179 :
1180 0 : for (tid, location_conf) in location_confs.tenant_shards {
1181 0 : let entry = observed.0.entry(tid).or_default();
1182 0 : entry.locations.insert(
1183 0 : node_id,
1184 0 : ObservedStateLocation {
1185 0 : conf: location_conf,
1186 0 : },
1187 0 : );
1188 0 : }
1189 : }
1190 :
1191 0 : observed
1192 0 : }
1193 :
1194 : /// Used during [`Self::startup_reconcile`] and shard splits: detach a list of unknown-to-us
1195 : /// tenants from pageservers.
1196 : ///
1197 : /// This is safe to run in the background, because if we don't have this TenantShardId in our map of
1198 : /// tenants, then it is probably something incompletely deleted before: we will not fight with any
1199 : /// other task trying to attach it.
1200 : #[instrument(skip_all)]
1201 : async fn cleanup_locations(&self, cleanup: Vec<(TenantShardId, NodeId)>) {
1202 : let nodes = self.inner.read().unwrap().nodes.clone();
1203 :
1204 : for (tenant_shard_id, node_id) in cleanup {
1205 : // A node reported a tenant_shard_id which is unknown to us: detach it.
1206 : let Some(node) = nodes.get(&node_id) else {
1207 : // This is legitimate; we run in the background and [`Self::startup_reconcile`] might have identified
1208 : // a location to clean up on a node that has since been removed.
1209 : tracing::info!(
1210 : "Not cleaning up location {node_id}/{tenant_shard_id}: node not found"
1211 : );
1212 : continue;
1213 : };
1214 :
1215 : if self.cancel.is_cancelled() {
1216 : break;
1217 : }
1218 :
1219 : let client = PageserverClient::new(
1220 : node.get_id(),
1221 : self.http_client.clone(),
1222 : node.base_url(),
1223 : self.config.pageserver_jwt_token.as_deref(),
1224 : );
1225 : match client
1226 : .location_config(
1227 : tenant_shard_id,
1228 : LocationConfig {
1229 : mode: LocationConfigMode::Detached,
1230 : generation: None,
1231 : secondary_conf: None,
1232 : shard_number: tenant_shard_id.shard_number.0,
1233 : shard_count: tenant_shard_id.shard_count.literal(),
1234 : shard_stripe_size: 0,
1235 : tenant_conf: models::TenantConfig::default(),
1236 : },
1237 : None,
1238 : false,
1239 : )
1240 : .await
1241 : {
1242 : Ok(()) => {
1243 : tracing::info!(
1244 : "Detached unknown shard {tenant_shard_id} on pageserver {node_id}"
1245 : );
1246 : }
1247 : Err(e) => {
1248 : // Non-fatal error: leaving a tenant shard behind that we are not managing shouldn't
1249 : // break anything.
1250 : tracing::error!(
1251 : "Failed to detach unknown shard {tenant_shard_id} on pageserver {node_id}: {e}"
1252 : );
1253 : }
1254 : }
1255 : }
1256 : }
1257 :
1258 : /// Long running background task that periodically wakes up and looks for shards that need
1259 : /// reconciliation. Reconciliation is fallible, so any reconciliation tasks that fail during
1260 : /// e.g. a tenant create/attach/migrate must eventually be retried: this task is responsible
1261 : /// for those retries.
1262 : #[instrument(skip_all)]
1263 : async fn background_reconcile(self: &Arc<Self>) {
1264 : self.startup_complete.clone().wait().await;
1265 :
1266 : const BACKGROUND_RECONCILE_PERIOD: Duration = Duration::from_secs(20);
1267 : let mut interval = tokio::time::interval(BACKGROUND_RECONCILE_PERIOD);
1268 : while !self.reconcilers_cancel.is_cancelled() {
1269 : tokio::select! {
1270 : _ = interval.tick() => {
1271 : let reconcile_all_result = self.reconcile_all();
1272 : if reconcile_all_result.can_run_optimizations() {
1273 : // Run optimizer only when we didn't find any other work to do
1274 : self.optimize_all().await;
1275 : }
1276 : // Always attempt autosplits. Sharding is crucial for bulk ingest performance, so we
1277 : // must be responsive when new projects begin ingesting and reach the threshold.
1278 : self.autosplit_tenants().await;
1279 : },
1280 : _ = self.reconcilers_cancel.cancelled() => return
1281 : }
1282 : }
1283 : }
1284 : /// Heartbeat all storage nodes once in a while.
1285 : #[instrument(skip_all)]
1286 : async fn spawn_heartbeat_driver(self: &Arc<Self>) {
1287 : self.startup_complete.clone().wait().await;
1288 :
1289 : let mut interval = tokio::time::interval(self.config.heartbeat_interval);
1290 : while !self.cancel.is_cancelled() {
1291 : tokio::select! {
1292 : _ = interval.tick() => { }
1293 : _ = self.cancel.cancelled() => return
1294 : };
1295 :
1296 : let nodes = {
1297 : let locked = self.inner.read().unwrap();
1298 : locked.nodes.clone()
1299 : };
1300 :
1301 : let safekeepers = {
1302 : let locked = self.inner.read().unwrap();
1303 : locked.safekeepers.clone()
1304 : };
1305 :
1306 : let (res_ps, res_sk) = tokio::join!(
1307 : self.heartbeater_ps.heartbeat(nodes),
1308 : self.heartbeater_sk.heartbeat(safekeepers)
1309 : );
1310 :
1311 : if let Ok(deltas) = res_ps {
1312 : let mut to_handle = Vec::default();
1313 :
1314 : for (node_id, state) in deltas.0 {
1315 : let new_availability = match state {
1316 : PageserverState::Available { utilization, .. } => {
1317 : NodeAvailability::Active(utilization)
1318 : }
1319 : PageserverState::WarmingUp { started_at } => {
1320 : NodeAvailability::WarmingUp(started_at)
1321 : }
1322 : PageserverState::Offline => {
1323 : // The node might have been placed in the WarmingUp state
1324 : // while the heartbeat round was on-going. Hence, filter out
1325 : // offline transitions for WarmingUp nodes that are still within
1326 : // their grace period.
1327 : if let Ok(NodeAvailability::WarmingUp(started_at)) = self
1328 : .get_node(node_id)
1329 : .await
1330 : .as_ref()
1331 0 : .map(|n| n.get_availability())
1332 : {
1333 : let now = Instant::now();
1334 : if now - *started_at >= self.config.max_warming_up_interval {
1335 : NodeAvailability::Offline
1336 : } else {
1337 : NodeAvailability::WarmingUp(*started_at)
1338 : }
1339 : } else {
1340 : NodeAvailability::Offline
1341 : }
1342 : }
1343 : };
1344 :
1345 : let node_lock = trace_exclusive_lock(
1346 : &self.node_op_locks,
1347 : node_id,
1348 : NodeOperations::Configure,
1349 : )
1350 : .await;
1351 :
1352 : pausable_failpoint!("heartbeat-pre-node-state-configure");
1353 :
1354 : // This is the code path for geniune availability transitions (i.e node
1355 : // goes unavailable and/or comes back online).
1356 : let res = self
1357 : .node_state_configure(node_id, Some(new_availability), None, &node_lock)
1358 : .await;
1359 :
1360 : match res {
1361 : Ok(transition) => {
1362 : // Keep hold of the lock until the availability transitions
1363 : // have been handled in
1364 : // [`Service::handle_node_availability_transitions`] in order avoid
1365 : // racing with [`Service::external_node_configure`].
1366 : to_handle.push((node_id, node_lock, transition));
1367 : }
1368 : Err(ApiError::NotFound(_)) => {
1369 : // This should be rare, but legitimate since the heartbeats are done
1370 : // on a snapshot of the nodes.
1371 : tracing::info!("Node {} was not found after heartbeat round", node_id);
1372 : }
1373 : Err(ApiError::ShuttingDown) => {
1374 : // No-op: we're shutting down, no need to try and update any nodes' statuses
1375 : }
1376 : Err(err) => {
1377 : // Transition to active involves reconciling: if a node responds to a heartbeat then
1378 : // becomes unavailable again, we may get an error here.
1379 : tracing::error!(
1380 : "Failed to update node state {} after heartbeat round: {}",
1381 : node_id,
1382 : err
1383 : );
1384 : }
1385 : }
1386 : }
1387 :
1388 : // We collected all the transitions above and now we handle them.
1389 : let res = self.handle_node_availability_transitions(to_handle).await;
1390 : if let Err(errs) = res {
1391 : for (node_id, err) in errs {
1392 : match err {
1393 : ApiError::NotFound(_) => {
1394 : // This should be rare, but legitimate since the heartbeats are done
1395 : // on a snapshot of the nodes.
1396 : tracing::info!(
1397 : "Node {} was not found after heartbeat round",
1398 : node_id
1399 : );
1400 : }
1401 : err => {
1402 : tracing::error!(
1403 : "Failed to handle availability transition for {} after heartbeat round: {}",
1404 : node_id,
1405 : err
1406 : );
1407 : }
1408 : }
1409 : }
1410 : }
1411 : }
1412 : if let Ok(deltas) = res_sk {
1413 : let mut to_activate = Vec::new();
1414 : {
1415 : let mut locked = self.inner.write().unwrap();
1416 : let mut safekeepers = (*locked.safekeepers).clone();
1417 :
1418 : for (id, state) in deltas.0 {
1419 : let Some(sk) = safekeepers.get_mut(&id) else {
1420 : tracing::info!(
1421 : "Couldn't update safekeeper safekeeper state for id {id} from heartbeat={state:?}"
1422 : );
1423 : continue;
1424 : };
1425 : if sk.scheduling_policy() == SkSchedulingPolicy::Activating
1426 : && let SafekeeperState::Available { .. } = state
1427 : {
1428 : to_activate.push(id);
1429 : }
1430 : sk.set_availability(state);
1431 : }
1432 : locked.safekeepers = Arc::new(safekeepers);
1433 : }
1434 : for sk_id in to_activate {
1435 : // TODO this can race with set_scheduling_policy (can create disjoint DB <-> in-memory state)
1436 : tracing::info!("Activating safekeeper {sk_id}");
1437 : match self.persistence.activate_safekeeper(sk_id.0 as i64).await {
1438 : Ok(Some(())) => {}
1439 : Ok(None) => {
1440 : tracing::info!(
1441 : "safekeeper {sk_id} has been removed from db or has different scheduling policy than active or activating"
1442 : );
1443 : }
1444 : Err(e) => {
1445 : tracing::warn!("couldn't apply activation of {sk_id} to db: {e}");
1446 : continue;
1447 : }
1448 : }
1449 : if let Err(e) = self
1450 : .set_safekeeper_scheduling_policy_in_mem(sk_id, SkSchedulingPolicy::Active)
1451 : .await
1452 : {
1453 : tracing::info!("couldn't activate safekeeper {sk_id} in memory: {e}");
1454 : continue;
1455 : }
1456 : tracing::info!("Activation of safekeeper {sk_id} done");
1457 : }
1458 : }
1459 : }
1460 : }
1461 :
1462 : /// Apply the contents of a [`ReconcileResult`] to our in-memory state: if the reconciliation
1463 : /// was successful and intent hasn't changed since the Reconciler was spawned, this will update
1464 : /// the observed state of the tenant such that subsequent calls to [`TenantShard::get_reconcile_needed`]
1465 : /// will indicate that reconciliation is not needed.
1466 : #[instrument(skip_all, fields(
1467 : seq=%result.sequence,
1468 : tenant_id=%result.tenant_shard_id.tenant_id,
1469 : shard_id=%result.tenant_shard_id.shard_slug(),
1470 : ))]
1471 : fn process_result(&self, result: ReconcileResult) {
1472 : let mut locked = self.inner.write().unwrap();
1473 : let (nodes, tenants, _scheduler) = locked.parts_mut();
1474 : let Some(tenant) = tenants.get_mut(&result.tenant_shard_id) else {
1475 : // A reconciliation result might race with removing a tenant: drop results for
1476 : // tenants that aren't in our map.
1477 : return;
1478 : };
1479 :
1480 : // Usually generation should only be updated via this path, so the max() isn't
1481 : // needed, but it is used to handle out-of-band updates via. e.g. test hook.
1482 : tenant.generation = std::cmp::max(tenant.generation, result.generation);
1483 :
1484 : // If the reconciler signals that it failed to notify compute, set this state on
1485 : // the shard so that a future [`TenantShard::maybe_reconcile`] will try again.
1486 : tenant.pending_compute_notification = result.pending_compute_notification;
1487 :
1488 : // Let the TenantShard know it is idle.
1489 : tenant.reconcile_complete(result.sequence);
1490 :
1491 : // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
1492 : // make to the tenant
1493 0 : let deltas = result.observed_deltas.into_iter().flat_map(|delta| {
1494 : // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
1495 : // make to the tenant
1496 0 : let node = nodes.get(delta.node_id())?;
1497 :
1498 0 : if node.is_available() {
1499 0 : return Some(delta);
1500 0 : }
1501 :
1502 : // In case a node became unavailable concurrently with the reconcile, observed
1503 : // locations on it are now uncertain. By convention, set them to None in order
1504 : // for them to get refreshed when the node comes back online.
1505 0 : Some(ObservedStateDelta::Upsert(Box::new((
1506 0 : node.get_id(),
1507 0 : ObservedStateLocation { conf: None },
1508 0 : ))))
1509 0 : });
1510 :
1511 : match result.result {
1512 : Ok(()) => {
1513 : tenant.apply_observed_deltas(deltas);
1514 : tenant.waiter.advance(result.sequence);
1515 : }
1516 : Err(e) => {
1517 : match e {
1518 : ReconcileError::Cancel => {
1519 : tracing::info!("Reconciler was cancelled");
1520 : }
1521 : ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
1522 : // This might be due to the reconciler getting cancelled, or it might
1523 : // be due to the `Node` being marked offline.
1524 : tracing::info!("Reconciler cancelled during pageserver API call");
1525 : }
1526 : _ => {
1527 : tracing::warn!("Reconcile error: {}", e);
1528 : }
1529 : }
1530 :
1531 : // Ordering: populate last_error before advancing error_seq,
1532 : // so that waiters will see the correct error after waiting.
1533 : tenant.set_last_error(result.sequence, e);
1534 :
1535 : // If the reconciliation failed, don't clear the observed state for places where we
1536 : // detached. Instead, mark the observed state as uncertain.
1537 0 : let failed_reconcile_deltas = deltas.map(|delta| {
1538 0 : if let ObservedStateDelta::Delete(node_id) = delta {
1539 0 : ObservedStateDelta::Upsert(Box::new((
1540 0 : node_id,
1541 0 : ObservedStateLocation { conf: None },
1542 0 : )))
1543 : } else {
1544 0 : delta
1545 : }
1546 0 : });
1547 : tenant.apply_observed_deltas(failed_reconcile_deltas);
1548 : }
1549 : }
1550 :
1551 : tenant.consecutive_reconciles_count = tenant.consecutive_reconciles_count.saturating_add(1);
1552 :
1553 : // If we just finished detaching all shards for a tenant, it might be time to drop it from memory.
1554 : if tenant.policy == PlacementPolicy::Detached {
1555 : // We may only drop a tenant from memory while holding the exclusive lock on the tenant ID: this protects us
1556 : // from concurrent execution wrt a request handler that might expect the tenant to remain in memory for the
1557 : // duration of the request.
1558 : let guard = self.tenant_op_locks.try_exclusive(
1559 : tenant.tenant_shard_id.tenant_id,
1560 : TenantOperations::DropDetached,
1561 : );
1562 : if let Some(guard) = guard {
1563 : self.maybe_drop_tenant(tenant.tenant_shard_id.tenant_id, &mut locked, &guard);
1564 : }
1565 : }
1566 :
1567 : // Maybe some other work can proceed now that this job finished.
1568 : //
1569 : // Only bother with this if we have some semaphore units available in the normal-priority semaphore (these
1570 : // reconciles are scheduled at `[ReconcilerPriority::Normal]`).
1571 : if self.reconciler_concurrency.available_permits() > 0 {
1572 : while let Ok(tenant_shard_id) = locked.delayed_reconcile_rx.try_recv() {
1573 : let (nodes, tenants, _scheduler) = locked.parts_mut();
1574 : if let Some(shard) = tenants.get_mut(&tenant_shard_id) {
1575 : shard.delayed_reconcile = false;
1576 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
1577 : }
1578 :
1579 : if self.reconciler_concurrency.available_permits() == 0 {
1580 : break;
1581 : }
1582 : }
1583 : }
1584 : }
1585 :
1586 0 : async fn process_results(
1587 0 : &self,
1588 0 : mut result_rx: tokio::sync::mpsc::UnboundedReceiver<ReconcileResultRequest>,
1589 0 : mut bg_compute_hook_result_rx: tokio::sync::mpsc::Receiver<
1590 0 : Result<(), (TenantShardId, NotifyError)>,
1591 0 : >,
1592 0 : ) {
1593 : loop {
1594 : // Wait for the next result, or for cancellation
1595 0 : tokio::select! {
1596 0 : r = result_rx.recv() => {
1597 0 : match r {
1598 0 : Some(ReconcileResultRequest::ReconcileResult(result)) => {self.process_result(result);},
1599 0 : None | Some(ReconcileResultRequest::Stop) => {break;}
1600 : }
1601 : }
1602 0 : _ = async{
1603 0 : match bg_compute_hook_result_rx.recv().await {
1604 0 : Some(result) => {
1605 0 : if let Err((tenant_shard_id, notify_error)) = result {
1606 0 : tracing::warn!("Marking shard {tenant_shard_id} for notification retry, due to error {notify_error}");
1607 0 : let mut locked = self.inner.write().unwrap();
1608 0 : if let Some(shard) = locked.tenants.get_mut(&tenant_shard_id) {
1609 0 : shard.pending_compute_notification = true;
1610 0 : }
1611 :
1612 0 : }
1613 : },
1614 : None => {
1615 : // This channel is dead, but we don't want to terminate the outer loop{}: just wait for shutdown
1616 0 : self.cancel.cancelled().await;
1617 : }
1618 : }
1619 0 : } => {},
1620 0 : _ = self.cancel.cancelled() => {
1621 0 : break;
1622 : }
1623 : };
1624 : }
1625 0 : }
1626 :
1627 0 : async fn process_aborts(
1628 0 : &self,
1629 0 : mut abort_rx: tokio::sync::mpsc::UnboundedReceiver<TenantShardSplitAbort>,
1630 0 : ) {
1631 : loop {
1632 : // Wait for the next result, or for cancellation
1633 0 : let op = tokio::select! {
1634 0 : r = abort_rx.recv() => {
1635 0 : match r {
1636 0 : Some(op) => {op},
1637 0 : None => {break;}
1638 : }
1639 : }
1640 0 : _ = self.cancel.cancelled() => {
1641 0 : break;
1642 : }
1643 : };
1644 :
1645 : // Retry until shutdown: we must keep this request object alive until it is properly
1646 : // processed, as it holds a lock guard that prevents other operations trying to do things
1647 : // to the tenant while it is in a weird part-split state.
1648 0 : while !self.reconcilers_cancel.is_cancelled() {
1649 0 : match self.abort_tenant_shard_split(&op).await {
1650 0 : Ok(_) => break,
1651 0 : Err(e) => {
1652 0 : tracing::warn!(
1653 0 : "Failed to abort shard split on {}, will retry: {e}",
1654 : op.tenant_id
1655 : );
1656 :
1657 : // If a node is unavailable, we hope that it has been properly marked Offline
1658 : // when we retry, so that the abort op will succeed. If the abort op is failing
1659 : // for some other reason, we will keep retrying forever, or until a human notices
1660 : // and does something about it (either fixing a pageserver or restarting the controller).
1661 0 : tokio::time::timeout(
1662 0 : Duration::from_secs(5),
1663 0 : self.reconcilers_cancel.cancelled(),
1664 0 : )
1665 0 : .await
1666 0 : .ok();
1667 : }
1668 : }
1669 : }
1670 : }
1671 0 : }
1672 :
1673 0 : pub async fn spawn(config: Config, persistence: Arc<Persistence>) -> anyhow::Result<Arc<Self>> {
1674 0 : let (result_tx, result_rx) = tokio::sync::mpsc::unbounded_channel();
1675 0 : let (abort_tx, abort_rx) = tokio::sync::mpsc::unbounded_channel();
1676 :
1677 0 : let leadership_cancel = CancellationToken::new();
1678 0 : let leadership = Leadership::new(persistence.clone(), config.clone(), leadership_cancel);
1679 0 : let (leader, leader_step_down_state) = leadership.step_down_current_leader().await?;
1680 :
1681 : // Apply the migrations **after** the current leader has stepped down
1682 : // (or we've given up waiting for it), but **before** reading from the
1683 : // database. The only exception is reading the current leader before
1684 : // migrating.
1685 0 : persistence.migration_run().await?;
1686 :
1687 0 : tracing::info!("Loading nodes from database...");
1688 0 : let nodes = persistence
1689 0 : .list_nodes()
1690 0 : .await?
1691 0 : .into_iter()
1692 0 : .map(|x| Node::from_persistent(x, config.use_https_pageserver_api))
1693 0 : .collect::<anyhow::Result<Vec<Node>>>()?;
1694 0 : let nodes: HashMap<NodeId, Node> = nodes.into_iter().map(|n| (n.get_id(), n)).collect();
1695 0 : tracing::info!("Loaded {} nodes from database.", nodes.len());
1696 0 : metrics::METRICS_REGISTRY
1697 0 : .metrics_group
1698 0 : .storage_controller_pageserver_nodes
1699 0 : .set(nodes.len() as i64);
1700 0 : metrics::METRICS_REGISTRY
1701 0 : .metrics_group
1702 0 : .storage_controller_https_pageserver_nodes
1703 0 : .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
1704 :
1705 0 : tracing::info!("Loading safekeepers from database...");
1706 0 : let safekeepers = persistence
1707 0 : .list_safekeepers()
1708 0 : .await?
1709 0 : .into_iter()
1710 0 : .map(|skp| {
1711 0 : Safekeeper::from_persistence(
1712 0 : skp,
1713 0 : CancellationToken::new(),
1714 0 : config.use_https_safekeeper_api,
1715 : )
1716 0 : })
1717 0 : .collect::<anyhow::Result<Vec<_>>>()?;
1718 0 : let safekeepers: HashMap<NodeId, Safekeeper> =
1719 0 : safekeepers.into_iter().map(|n| (n.get_id(), n)).collect();
1720 0 : let count_policy = |policy| {
1721 0 : safekeepers
1722 0 : .iter()
1723 0 : .filter(|sk| sk.1.scheduling_policy() == policy)
1724 0 : .count()
1725 0 : };
1726 0 : let active_sk_count = count_policy(SkSchedulingPolicy::Active);
1727 0 : let activating_sk_count = count_policy(SkSchedulingPolicy::Activating);
1728 0 : let pause_sk_count = count_policy(SkSchedulingPolicy::Pause);
1729 0 : let decom_sk_count = count_policy(SkSchedulingPolicy::Decomissioned);
1730 0 : tracing::info!(
1731 0 : "Loaded {} safekeepers from database. Active {active_sk_count}, activating {activating_sk_count}, \
1732 0 : paused {pause_sk_count}, decomissioned {decom_sk_count}.",
1733 0 : safekeepers.len()
1734 : );
1735 0 : metrics::METRICS_REGISTRY
1736 0 : .metrics_group
1737 0 : .storage_controller_safekeeper_nodes
1738 0 : .set(safekeepers.len() as i64);
1739 0 : metrics::METRICS_REGISTRY
1740 0 : .metrics_group
1741 0 : .storage_controller_https_safekeeper_nodes
1742 0 : .set(safekeepers.values().filter(|s| s.has_https_port()).count() as i64);
1743 :
1744 0 : tracing::info!("Loading shards from database...");
1745 0 : let mut tenant_shard_persistence = persistence.load_active_tenant_shards().await?;
1746 0 : tracing::info!(
1747 0 : "Loaded {} shards from database.",
1748 0 : tenant_shard_persistence.len()
1749 : );
1750 :
1751 : // If any shard splits were in progress, reset the database state to abort them
1752 0 : let mut tenant_shard_count_min_max: HashMap<TenantId, (ShardCount, ShardCount)> =
1753 0 : HashMap::new();
1754 0 : for tsp in &mut tenant_shard_persistence {
1755 0 : let shard = tsp.get_shard_identity()?;
1756 0 : let tenant_shard_id = tsp.get_tenant_shard_id()?;
1757 0 : let entry = tenant_shard_count_min_max
1758 0 : .entry(tenant_shard_id.tenant_id)
1759 0 : .or_insert_with(|| (shard.count, shard.count));
1760 0 : entry.0 = std::cmp::min(entry.0, shard.count);
1761 0 : entry.1 = std::cmp::max(entry.1, shard.count);
1762 : }
1763 :
1764 0 : for (tenant_id, (count_min, count_max)) in tenant_shard_count_min_max {
1765 0 : if count_min != count_max {
1766 : // Aborting the split in the database and dropping the child shards is sufficient: the reconciliation in
1767 : // [`Self::startup_reconcile`] will implicitly drop the child shards on remote pageservers, or they'll
1768 : // be dropped later in [`Self::node_activate_reconcile`] if it isn't available right now.
1769 0 : tracing::info!("Aborting shard split {tenant_id} {count_min:?} -> {count_max:?}");
1770 0 : let abort_status = persistence.abort_shard_split(tenant_id, count_max).await?;
1771 :
1772 : // We may never see the Complete status here: if the split was complete, we wouldn't have
1773 : // identified this tenant has having mismatching min/max counts.
1774 0 : assert!(matches!(abort_status, AbortShardSplitStatus::Aborted));
1775 :
1776 : // Clear the splitting status in-memory, to reflect that we just aborted in the database
1777 0 : tenant_shard_persistence.iter_mut().for_each(|tsp| {
1778 : // Set idle split state on those shards that we will retain.
1779 0 : let tsp_tenant_id = TenantId::from_str(tsp.tenant_id.as_str()).unwrap();
1780 0 : if tsp_tenant_id == tenant_id
1781 0 : && tsp.get_shard_identity().unwrap().count == count_min
1782 0 : {
1783 0 : tsp.splitting = SplitState::Idle;
1784 0 : } else if tsp_tenant_id == tenant_id {
1785 : // Leave the splitting state on the child shards: this will be used next to
1786 : // drop them.
1787 0 : tracing::info!(
1788 0 : "Shard {tsp_tenant_id} will be dropped after shard split abort",
1789 : );
1790 0 : }
1791 0 : });
1792 :
1793 : // Drop shards for this tenant which we didn't just mark idle (i.e. child shards of the aborted split)
1794 0 : tenant_shard_persistence.retain(|tsp| {
1795 0 : TenantId::from_str(tsp.tenant_id.as_str()).unwrap() != tenant_id
1796 0 : || tsp.splitting == SplitState::Idle
1797 0 : });
1798 0 : }
1799 : }
1800 :
1801 0 : let mut tenants = BTreeMap::new();
1802 :
1803 0 : let mut scheduler = Scheduler::new(nodes.values());
1804 :
1805 : #[cfg(feature = "testing")]
1806 : {
1807 : use pageserver_api::controller_api::AvailabilityZone;
1808 :
1809 : // Hack: insert scheduler state for all nodes referenced by shards, as compatibility
1810 : // tests only store the shards, not the nodes. The nodes will be loaded shortly
1811 : // after when pageservers start up and register.
1812 0 : let mut node_ids = HashSet::new();
1813 0 : for tsp in &tenant_shard_persistence {
1814 0 : if let Some(node_id) = tsp.generation_pageserver {
1815 0 : node_ids.insert(node_id);
1816 0 : }
1817 : }
1818 0 : for node_id in node_ids {
1819 0 : tracing::info!("Creating node {} in scheduler for tests", node_id);
1820 0 : let node = Node::new(
1821 0 : NodeId(node_id as u64),
1822 0 : "".to_string(),
1823 : 123,
1824 0 : None,
1825 0 : "".to_string(),
1826 : 123,
1827 0 : None,
1828 0 : None,
1829 0 : AvailabilityZone("test_az".to_string()),
1830 : false,
1831 : )
1832 0 : .unwrap();
1833 :
1834 0 : scheduler.node_upsert(&node);
1835 : }
1836 : }
1837 0 : for tsp in tenant_shard_persistence {
1838 0 : let tenant_shard_id = tsp.get_tenant_shard_id()?;
1839 :
1840 : // We will populate intent properly later in [`Self::startup_reconcile`], initially populate
1841 : // it with what we can infer: the node for which a generation was most recently issued.
1842 0 : let mut intent = IntentState::new(
1843 0 : tsp.preferred_az_id
1844 0 : .as_ref()
1845 0 : .map(|az| AvailabilityZone(az.clone())),
1846 : );
1847 0 : if let Some(generation_pageserver) = tsp.generation_pageserver.map(|n| NodeId(n as u64))
1848 : {
1849 0 : if nodes.contains_key(&generation_pageserver) {
1850 0 : intent.set_attached(&mut scheduler, Some(generation_pageserver));
1851 0 : } else {
1852 : // If a node was removed before being completely drained, it is legal for it to leave behind a `generation_pageserver` referring
1853 : // to a non-existent node, because node deletion doesn't block on completing the reconciliations that will issue new generations
1854 : // on different pageservers.
1855 0 : tracing::warn!(
1856 0 : "Tenant shard {tenant_shard_id} references non-existent node {generation_pageserver} in database, will be rescheduled"
1857 : );
1858 : }
1859 0 : }
1860 0 : let new_tenant = TenantShard::from_persistent(tsp, intent)?;
1861 :
1862 0 : tenants.insert(tenant_shard_id, new_tenant);
1863 : }
1864 :
1865 0 : let (startup_completion, startup_complete) = utils::completion::channel();
1866 :
1867 : // This channel is continuously consumed by process_results, so doesn't need to be very large.
1868 0 : let (bg_compute_notify_result_tx, bg_compute_notify_result_rx) =
1869 0 : tokio::sync::mpsc::channel(512);
1870 :
1871 0 : let (delayed_reconcile_tx, delayed_reconcile_rx) =
1872 0 : tokio::sync::mpsc::channel(MAX_DELAYED_RECONCILES);
1873 :
1874 0 : let cancel = CancellationToken::new();
1875 0 : let reconcilers_cancel = cancel.child_token();
1876 :
1877 0 : let mut http_client = reqwest::Client::builder();
1878 : // We intentionally disable the connection pool, so every request will create its own TCP connection.
1879 : // It's especially important for heartbeaters to notice more network problems.
1880 : //
1881 : // TODO: It makes sense to use this client only in heartbeaters and create a second one with
1882 : // connection pooling for everything else. But reqwest::Client may create a connection without
1883 : // ever using it (it uses hyper's Client under the hood):
1884 : // https://github.com/hyperium/hyper-util/blob/d51318df3461d40e5f5e5ca163cb3905ac960209/src/client/legacy/client.rs#L415
1885 : //
1886 : // Because of a bug in hyper0::Connection::graceful_shutdown such connections hang during
1887 : // graceful server shutdown: https://github.com/hyperium/hyper/issues/2730
1888 : //
1889 : // The bug has been fixed in hyper v1, so keep alive may be enabled only after we migrate to hyper1.
1890 0 : http_client = http_client.pool_max_idle_per_host(0);
1891 0 : for ssl_ca_cert in &config.ssl_ca_certs {
1892 0 : http_client = http_client.add_root_certificate(ssl_ca_cert.clone());
1893 0 : }
1894 0 : let http_client = http_client.build()?;
1895 :
1896 0 : let heartbeater_ps = Heartbeater::new(
1897 0 : http_client.clone(),
1898 0 : config.pageserver_jwt_token.clone(),
1899 0 : config.max_offline_interval,
1900 0 : config.max_warming_up_interval,
1901 0 : cancel.clone(),
1902 : );
1903 :
1904 0 : let heartbeater_sk = Heartbeater::new(
1905 0 : http_client.clone(),
1906 0 : config.safekeeper_jwt_token.clone(),
1907 0 : config.max_offline_interval,
1908 0 : config.max_warming_up_interval,
1909 0 : cancel.clone(),
1910 : );
1911 :
1912 0 : let initial_leadership_status = if config.start_as_candidate {
1913 0 : LeadershipStatus::Candidate
1914 : } else {
1915 0 : LeadershipStatus::Leader
1916 : };
1917 :
1918 0 : let this = Arc::new(Self {
1919 0 : inner: Arc::new(std::sync::RwLock::new(ServiceState::new(
1920 0 : nodes,
1921 0 : safekeepers,
1922 0 : tenants,
1923 0 : scheduler,
1924 0 : delayed_reconcile_rx,
1925 0 : initial_leadership_status,
1926 0 : reconcilers_cancel.clone(),
1927 : ))),
1928 0 : config: config.clone(),
1929 0 : persistence,
1930 0 : compute_hook: Arc::new(ComputeHook::new(config.clone())?),
1931 0 : result_tx,
1932 0 : heartbeater_ps,
1933 0 : heartbeater_sk,
1934 0 : reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
1935 0 : config.reconciler_concurrency,
1936 : )),
1937 0 : priority_reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
1938 0 : config.priority_reconciler_concurrency,
1939 : )),
1940 0 : delayed_reconcile_tx,
1941 0 : abort_tx,
1942 0 : startup_complete: startup_complete.clone(),
1943 0 : cancel,
1944 0 : reconcilers_cancel,
1945 0 : gate: Gate::default(),
1946 0 : reconcilers_gate: Gate::default(),
1947 0 : tenant_op_locks: Default::default(),
1948 0 : node_op_locks: Default::default(),
1949 0 : http_client,
1950 0 : step_down_barrier: Default::default(),
1951 : });
1952 :
1953 0 : let result_task_this = this.clone();
1954 0 : tokio::task::spawn(async move {
1955 : // Block shutdown until we're done (we must respect self.cancel)
1956 0 : if let Ok(_gate) = result_task_this.gate.enter() {
1957 0 : result_task_this
1958 0 : .process_results(result_rx, bg_compute_notify_result_rx)
1959 0 : .await
1960 0 : }
1961 0 : });
1962 :
1963 0 : tokio::task::spawn({
1964 0 : let this = this.clone();
1965 0 : async move {
1966 : // Block shutdown until we're done (we must respect self.cancel)
1967 0 : if let Ok(_gate) = this.gate.enter() {
1968 0 : this.process_aborts(abort_rx).await
1969 0 : }
1970 0 : }
1971 : });
1972 :
1973 0 : tokio::task::spawn({
1974 0 : let this = this.clone();
1975 0 : async move {
1976 0 : if let Ok(_gate) = this.gate.enter() {
1977 : loop {
1978 0 : tokio::select! {
1979 0 : _ = this.cancel.cancelled() => {
1980 0 : break;
1981 : },
1982 0 : _ = tokio::time::sleep(Duration::from_secs(60)) => {}
1983 : };
1984 0 : this.tenant_op_locks.housekeeping();
1985 : }
1986 0 : }
1987 0 : }
1988 : });
1989 :
1990 0 : tokio::task::spawn({
1991 0 : let this = this.clone();
1992 : // We will block the [`Service::startup_complete`] barrier until [`Self::startup_reconcile`]
1993 : // is done.
1994 0 : let startup_completion = startup_completion.clone();
1995 0 : async move {
1996 : // Block shutdown until we're done (we must respect self.cancel)
1997 0 : let Ok(_gate) = this.gate.enter() else {
1998 0 : return;
1999 : };
2000 :
2001 0 : this.startup_reconcile(leader, leader_step_down_state, bg_compute_notify_result_tx)
2002 0 : .await;
2003 :
2004 0 : drop(startup_completion);
2005 0 : }
2006 : });
2007 :
2008 0 : tokio::task::spawn({
2009 0 : let this = this.clone();
2010 0 : let startup_complete = startup_complete.clone();
2011 0 : async move {
2012 0 : startup_complete.wait().await;
2013 0 : this.background_reconcile().await;
2014 0 : }
2015 : });
2016 :
2017 0 : tokio::task::spawn({
2018 0 : let this = this.clone();
2019 0 : let startup_complete = startup_complete.clone();
2020 0 : async move {
2021 0 : startup_complete.wait().await;
2022 0 : this.spawn_heartbeat_driver().await;
2023 0 : }
2024 : });
2025 :
2026 : // Check that there is enough safekeepers configured that we can create new timelines
2027 0 : let test_sk_res_str = match this.safekeepers_for_new_timeline().await {
2028 0 : Ok(v) => format!("Ok({v:?})"),
2029 0 : Err(v) => format!("Err({v:})"),
2030 : };
2031 0 : tracing::info!(
2032 : timeline_safekeeper_count = config.timeline_safekeeper_count,
2033 : timelines_onto_safekeepers = config.timelines_onto_safekeepers,
2034 0 : "viability test result (test timeline creation on safekeepers): {test_sk_res_str}",
2035 : );
2036 :
2037 0 : Ok(this)
2038 0 : }
2039 :
2040 0 : pub(crate) async fn attach_hook(
2041 0 : &self,
2042 0 : attach_req: AttachHookRequest,
2043 0 : ) -> anyhow::Result<AttachHookResponse> {
2044 0 : let _tenant_lock = trace_exclusive_lock(
2045 0 : &self.tenant_op_locks,
2046 0 : attach_req.tenant_shard_id.tenant_id,
2047 0 : TenantOperations::AttachHook,
2048 0 : )
2049 0 : .await;
2050 :
2051 : // This is a test hook. To enable using it on tenants that were created directly with
2052 : // the pageserver API (not via this service), we will auto-create any missing tenant
2053 : // shards with default state.
2054 0 : let insert = {
2055 0 : match self
2056 0 : .maybe_load_tenant(attach_req.tenant_shard_id.tenant_id, &_tenant_lock)
2057 0 : .await
2058 : {
2059 0 : Ok(_) => false,
2060 0 : Err(ApiError::NotFound(_)) => true,
2061 0 : Err(e) => return Err(e.into()),
2062 : }
2063 : };
2064 :
2065 0 : if insert {
2066 0 : let config = attach_req.config.clone().unwrap_or_default();
2067 0 : let tsp = TenantShardPersistence {
2068 0 : tenant_id: attach_req.tenant_shard_id.tenant_id.to_string(),
2069 0 : shard_number: attach_req.tenant_shard_id.shard_number.0 as i32,
2070 0 : shard_count: attach_req.tenant_shard_id.shard_count.literal() as i32,
2071 0 : shard_stripe_size: 0,
2072 0 : generation: attach_req.generation_override.or(Some(0)),
2073 0 : generation_pageserver: None,
2074 0 : placement_policy: serde_json::to_string(&PlacementPolicy::Attached(0)).unwrap(),
2075 0 : config: serde_json::to_string(&config).unwrap(),
2076 0 : splitting: SplitState::default(),
2077 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
2078 0 : .unwrap(),
2079 0 : preferred_az_id: None,
2080 0 : };
2081 :
2082 0 : match self.persistence.insert_tenant_shards(vec![tsp]).await {
2083 0 : Err(e) => match e {
2084 : DatabaseError::Query(diesel::result::Error::DatabaseError(
2085 : DatabaseErrorKind::UniqueViolation,
2086 : _,
2087 : )) => {
2088 0 : tracing::info!(
2089 0 : "Raced with another request to insert tenant {}",
2090 : attach_req.tenant_shard_id
2091 : )
2092 : }
2093 0 : _ => return Err(e.into()),
2094 : },
2095 : Ok(()) => {
2096 0 : tracing::info!("Inserted shard {} in database", attach_req.tenant_shard_id);
2097 :
2098 0 : let mut shard = TenantShard::new(
2099 0 : attach_req.tenant_shard_id,
2100 0 : ShardIdentity::unsharded(),
2101 0 : PlacementPolicy::Attached(0),
2102 0 : None,
2103 : );
2104 0 : shard.config = config;
2105 :
2106 0 : let mut locked = self.inner.write().unwrap();
2107 0 : locked.tenants.insert(attach_req.tenant_shard_id, shard);
2108 0 : tracing::info!("Inserted shard {} in memory", attach_req.tenant_shard_id);
2109 : }
2110 : }
2111 0 : }
2112 :
2113 0 : let new_generation = if let Some(req_node_id) = attach_req.node_id {
2114 0 : let maybe_tenant_conf = {
2115 0 : let locked = self.inner.write().unwrap();
2116 0 : locked
2117 0 : .tenants
2118 0 : .get(&attach_req.tenant_shard_id)
2119 0 : .map(|t| t.config.clone())
2120 : };
2121 :
2122 0 : match maybe_tenant_conf {
2123 0 : Some(conf) => {
2124 0 : let new_generation = self
2125 0 : .persistence
2126 0 : .increment_generation(attach_req.tenant_shard_id, req_node_id)
2127 0 : .await?;
2128 :
2129 : // Persist the placement policy update. This is required
2130 : // when we reattaching a detached tenant.
2131 0 : self.persistence
2132 0 : .update_tenant_shard(
2133 0 : TenantFilter::Shard(attach_req.tenant_shard_id),
2134 0 : Some(PlacementPolicy::Attached(0)),
2135 0 : Some(conf),
2136 0 : None,
2137 0 : None,
2138 0 : )
2139 0 : .await?;
2140 0 : Some(new_generation)
2141 : }
2142 : None => {
2143 0 : anyhow::bail!("Attach hook handling raced with tenant removal")
2144 : }
2145 : }
2146 : } else {
2147 0 : self.persistence.detach(attach_req.tenant_shard_id).await?;
2148 0 : None
2149 : };
2150 :
2151 0 : let mut locked = self.inner.write().unwrap();
2152 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
2153 :
2154 0 : let tenant_shard = tenants
2155 0 : .get_mut(&attach_req.tenant_shard_id)
2156 0 : .expect("Checked for existence above");
2157 :
2158 0 : if let Some(new_generation) = new_generation {
2159 0 : tenant_shard.generation = Some(new_generation);
2160 0 : tenant_shard.policy = PlacementPolicy::Attached(0);
2161 0 : } else {
2162 : // This is a detach notification. We must update placement policy to avoid re-attaching
2163 : // during background scheduling/reconciliation, or during storage controller restart.
2164 0 : assert!(attach_req.node_id.is_none());
2165 0 : tenant_shard.policy = PlacementPolicy::Detached;
2166 : }
2167 :
2168 0 : if let Some(attaching_pageserver) = attach_req.node_id.as_ref() {
2169 0 : tracing::info!(
2170 : tenant_id = %attach_req.tenant_shard_id,
2171 : ps_id = %attaching_pageserver,
2172 : generation = ?tenant_shard.generation,
2173 0 : "issuing",
2174 : );
2175 0 : } else if let Some(ps_id) = tenant_shard.intent.get_attached() {
2176 0 : tracing::info!(
2177 : tenant_id = %attach_req.tenant_shard_id,
2178 : %ps_id,
2179 : generation = ?tenant_shard.generation,
2180 0 : "dropping",
2181 : );
2182 : } else {
2183 0 : tracing::info!(
2184 : tenant_id = %attach_req.tenant_shard_id,
2185 0 : "no-op: tenant already has no pageserver");
2186 : }
2187 0 : tenant_shard
2188 0 : .intent
2189 0 : .set_attached(scheduler, attach_req.node_id);
2190 :
2191 0 : tracing::info!(
2192 0 : "attach_hook: tenant {} set generation {:?}, pageserver {}, config {:?}",
2193 : attach_req.tenant_shard_id,
2194 : tenant_shard.generation,
2195 : // TODO: this is an odd number of 0xf's
2196 0 : attach_req.node_id.unwrap_or(utils::id::NodeId(0xfffffff)),
2197 : attach_req.config,
2198 : );
2199 :
2200 : // Trick the reconciler into not doing anything for this tenant: this helps
2201 : // tests that manually configure a tenant on the pagesrever, and then call this
2202 : // attach hook: they don't want background reconciliation to modify what they
2203 : // did to the pageserver.
2204 : #[cfg(feature = "testing")]
2205 : {
2206 0 : if let Some(node_id) = attach_req.node_id {
2207 0 : tenant_shard.observed.locations = HashMap::from([(
2208 0 : node_id,
2209 0 : ObservedStateLocation {
2210 0 : conf: Some(attached_location_conf(
2211 0 : tenant_shard.generation.unwrap(),
2212 0 : &tenant_shard.shard,
2213 0 : &tenant_shard.config,
2214 0 : &PlacementPolicy::Attached(0),
2215 0 : tenant_shard.intent.get_secondary().len(),
2216 0 : )),
2217 0 : },
2218 0 : )]);
2219 0 : } else {
2220 0 : tenant_shard.observed.locations.clear();
2221 0 : }
2222 : }
2223 :
2224 : Ok(AttachHookResponse {
2225 0 : generation: attach_req
2226 0 : .node_id
2227 0 : .map(|_| tenant_shard.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap()),
2228 : })
2229 0 : }
2230 :
2231 0 : pub(crate) fn inspect(&self, inspect_req: InspectRequest) -> InspectResponse {
2232 0 : let locked = self.inner.read().unwrap();
2233 :
2234 0 : let tenant_shard = locked.tenants.get(&inspect_req.tenant_shard_id);
2235 :
2236 : InspectResponse {
2237 0 : attachment: tenant_shard.and_then(|s| {
2238 0 : s.intent
2239 0 : .get_attached()
2240 0 : .map(|ps| (s.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap(), ps))
2241 0 : }),
2242 : }
2243 0 : }
2244 :
2245 : // When the availability state of a node transitions to active, we must do a full reconciliation
2246 : // of LocationConfigs on that node. This is because while a node was offline:
2247 : // - we might have proceeded through startup_reconcile without checking for extraneous LocationConfigs on this node
2248 : // - aborting a tenant shard split might have left rogue child shards behind on this node.
2249 : //
2250 : // This function must complete _before_ setting a `Node` to Active: once it is set to Active, other
2251 : // Reconcilers might communicate with the node, and these must not overlap with the work we do in
2252 : // this function.
2253 : //
2254 : // The reconciliation logic in here is very similar to what [`Self::startup_reconcile`] does, but
2255 : // for written for a single node rather than as a batch job for all nodes.
2256 : #[tracing::instrument(skip_all, fields(node_id=%node.get_id()))]
2257 : async fn node_activate_reconcile(
2258 : &self,
2259 : mut node: Node,
2260 : _lock: &TracingExclusiveGuard<NodeOperations>,
2261 : ) -> Result<(), ApiError> {
2262 : // This Node is a mutable local copy: we will set it active so that we can use its
2263 : // API client to reconcile with the node. The Node in [`Self::nodes`] will get updated
2264 : // later.
2265 : node.set_availability(NodeAvailability::Active(PageserverUtilization::full()));
2266 :
2267 : let configs = match node
2268 : .with_client_retries(
2269 0 : |client| async move { client.list_location_config().await },
2270 : &self.http_client,
2271 : &self.config.pageserver_jwt_token,
2272 : 1,
2273 : 5,
2274 : SHORT_RECONCILE_TIMEOUT,
2275 : &self.cancel,
2276 : )
2277 : .await
2278 : {
2279 : None => {
2280 : // We're shutting down (the Node's cancellation token can't have fired, because
2281 : // we're the only scope that has a reference to it, and we didn't fire it).
2282 : return Err(ApiError::ShuttingDown);
2283 : }
2284 : Some(Err(e)) => {
2285 : // This node didn't succeed listing its locations: it may not proceed to active state
2286 : // as it is apparently unavailable.
2287 : return Err(ApiError::PreconditionFailed(
2288 : format!("Failed to query node location configs, cannot activate ({e})").into(),
2289 : ));
2290 : }
2291 : Some(Ok(configs)) => configs,
2292 : };
2293 : tracing::info!("Loaded {} LocationConfigs", configs.tenant_shards.len());
2294 :
2295 : let mut cleanup = Vec::new();
2296 : let mut mismatched_locations = 0;
2297 : {
2298 : let mut locked = self.inner.write().unwrap();
2299 :
2300 : for (tenant_shard_id, reported) in configs.tenant_shards {
2301 : let Some(tenant_shard) = locked.tenants.get_mut(&tenant_shard_id) else {
2302 : cleanup.push(tenant_shard_id);
2303 : continue;
2304 : };
2305 :
2306 : let on_record = &mut tenant_shard
2307 : .observed
2308 : .locations
2309 : .entry(node.get_id())
2310 0 : .or_insert_with(|| ObservedStateLocation { conf: None })
2311 : .conf;
2312 :
2313 : // If the location reported by the node does not match our observed state,
2314 : // then we mark it as uncertain and let the background reconciliation loop
2315 : // deal with it.
2316 : //
2317 : // Note that this also covers net new locations reported by the node.
2318 : if *on_record != reported {
2319 : mismatched_locations += 1;
2320 : *on_record = None;
2321 : }
2322 : }
2323 : }
2324 :
2325 : if mismatched_locations > 0 {
2326 : tracing::info!(
2327 : "Set observed state to None for {mismatched_locations} mismatched locations"
2328 : );
2329 : }
2330 :
2331 : for tenant_shard_id in cleanup {
2332 : tracing::info!("Detaching {tenant_shard_id}");
2333 : match node
2334 : .with_client_retries(
2335 0 : |client| async move {
2336 0 : let config = LocationConfig {
2337 0 : mode: LocationConfigMode::Detached,
2338 0 : generation: None,
2339 0 : secondary_conf: None,
2340 0 : shard_number: tenant_shard_id.shard_number.0,
2341 0 : shard_count: tenant_shard_id.shard_count.literal(),
2342 0 : shard_stripe_size: 0,
2343 0 : tenant_conf: models::TenantConfig::default(),
2344 0 : };
2345 0 : client
2346 0 : .location_config(tenant_shard_id, config, None, false)
2347 0 : .await
2348 0 : },
2349 : &self.http_client,
2350 : &self.config.pageserver_jwt_token,
2351 : 1,
2352 : 5,
2353 : SHORT_RECONCILE_TIMEOUT,
2354 : &self.cancel,
2355 : )
2356 : .await
2357 : {
2358 : None => {
2359 : // We're shutting down (the Node's cancellation token can't have fired, because
2360 : // we're the only scope that has a reference to it, and we didn't fire it).
2361 : return Err(ApiError::ShuttingDown);
2362 : }
2363 : Some(Err(e)) => {
2364 : // Do not let the node proceed to Active state if it is not responsive to requests
2365 : // to detach. This could happen if e.g. a shutdown bug in the pageserver is preventing
2366 : // detach completing: we should not let this node back into the set of nodes considered
2367 : // okay for scheduling.
2368 : return Err(ApiError::Conflict(format!(
2369 : "Node {node} failed to detach {tenant_shard_id}: {e}"
2370 : )));
2371 : }
2372 : Some(Ok(_)) => {}
2373 : };
2374 : }
2375 :
2376 : Ok(())
2377 : }
2378 :
2379 0 : pub(crate) async fn re_attach(
2380 0 : &self,
2381 0 : reattach_req: ReAttachRequest,
2382 0 : ) -> Result<ReAttachResponse, ApiError> {
2383 0 : if let Some(register_req) = reattach_req.register {
2384 0 : self.node_register(register_req).await?;
2385 0 : }
2386 :
2387 : // Ordering: we must persist generation number updates before making them visible in the in-memory state
2388 0 : let incremented_generations = self.persistence.re_attach(reattach_req.node_id).await?;
2389 :
2390 0 : tracing::info!(
2391 : node_id=%reattach_req.node_id,
2392 0 : "Incremented {} tenant shards' generations",
2393 0 : incremented_generations.len()
2394 : );
2395 :
2396 : // Apply the updated generation to our in-memory state, and
2397 : // gather discover secondary locations.
2398 0 : let mut locked = self.inner.write().unwrap();
2399 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
2400 :
2401 0 : let mut response = ReAttachResponse {
2402 0 : tenants: Vec::new(),
2403 0 : };
2404 :
2405 : // [Hadron] If the pageserver reports in the reattach message that it has an empty disk, it's possible that it just
2406 : // recovered from a local disk failure. The response of the reattach request will contain a list of tenants but it
2407 : // will not be honored by the pageserver in this case (disk failure). We should make sure we clear any observed
2408 : // locations of tenants attached to the node so that the reconciler will discover the discrpancy and reconfigure the
2409 : // missing tenants on the node properly.
2410 0 : if self.config.handle_ps_local_disk_loss && reattach_req.empty_local_disk.unwrap_or(false) {
2411 0 : tracing::info!(
2412 0 : "Pageserver {node_id} reports empty local disk, clearing observed locations referencing the pageserver for all tenants",
2413 : node_id = reattach_req.node_id
2414 : );
2415 0 : let mut num_tenant_shards_affected = 0;
2416 0 : for (tenant_shard_id, shard) in tenants.iter_mut() {
2417 0 : if shard
2418 0 : .observed
2419 0 : .locations
2420 0 : .remove(&reattach_req.node_id)
2421 0 : .is_some()
2422 : {
2423 0 : tracing::info!("Cleared observed location for tenant shard {tenant_shard_id}");
2424 0 : num_tenant_shards_affected += 1;
2425 0 : }
2426 : }
2427 0 : tracing::info!(
2428 0 : "Cleared observed locations for {num_tenant_shards_affected} tenant shards"
2429 : );
2430 0 : }
2431 :
2432 : // TODO: cancel/restart any running reconciliation for this tenant, it might be trying
2433 : // to call location_conf API with an old generation. Wait for cancellation to complete
2434 : // before responding to this request. Requires well implemented CancellationToken logic
2435 : // all the way to where we call location_conf. Even then, there can still be a location_conf
2436 : // request in flight over the network: TODO handle that by making location_conf API refuse
2437 : // to go backward in generations.
2438 :
2439 : // Scan through all shards, applying updates for ones where we updated generation
2440 : // and identifying shards that intend to have a secondary location on this node.
2441 0 : for (tenant_shard_id, shard) in tenants {
2442 0 : if let Some(new_gen) = incremented_generations.get(tenant_shard_id) {
2443 0 : let new_gen = *new_gen;
2444 0 : response.tenants.push(ReAttachResponseTenant {
2445 0 : id: *tenant_shard_id,
2446 0 : r#gen: Some(new_gen.into().unwrap()),
2447 0 : // A tenant is only put into multi or stale modes in the middle of a [`Reconciler::live_migrate`]
2448 0 : // execution. If a pageserver is restarted during that process, then the reconcile pass will
2449 0 : // fail, and start from scratch, so it doesn't make sense for us to try and preserve
2450 0 : // the stale/multi states at this point.
2451 0 : mode: LocationConfigMode::AttachedSingle,
2452 0 : stripe_size: shard.shard.stripe_size,
2453 0 : });
2454 :
2455 0 : shard.generation = std::cmp::max(shard.generation, Some(new_gen));
2456 0 : if let Some(observed) = shard.observed.locations.get_mut(&reattach_req.node_id) {
2457 : // Why can we update `observed` even though we're not sure our response will be received
2458 : // by the pageserver? Because the pageserver will not proceed with startup until
2459 : // it has processed response: if it loses it, we'll see another request and increment
2460 : // generation again, avoiding any uncertainty about dirtiness of tenant's state.
2461 0 : if let Some(conf) = observed.conf.as_mut() {
2462 0 : conf.generation = new_gen.into();
2463 0 : }
2464 0 : } else {
2465 0 : // This node has no observed state for the shard: perhaps it was offline
2466 0 : // when the pageserver restarted. Insert a None, so that the Reconciler
2467 0 : // will be prompted to learn the location's state before it makes changes.
2468 0 : shard
2469 0 : .observed
2470 0 : .locations
2471 0 : .insert(reattach_req.node_id, ObservedStateLocation { conf: None });
2472 0 : }
2473 0 : } else if shard.intent.get_secondary().contains(&reattach_req.node_id) {
2474 0 : // Ordering: pageserver will not accept /location_config requests until it has
2475 0 : // finished processing the response from re-attach. So we can update our in-memory state
2476 0 : // now, and be confident that we are not stamping on the result of some later location config.
2477 0 : // TODO: however, we are not strictly ordered wrt ReconcileResults queue,
2478 0 : // so we might update observed state here, and then get over-written by some racing
2479 0 : // ReconcileResult. The impact is low however, since we have set state on pageserver something
2480 0 : // that matches intent, so worst case if we race then we end up doing a spurious reconcile.
2481 0 :
2482 0 : response.tenants.push(ReAttachResponseTenant {
2483 0 : id: *tenant_shard_id,
2484 0 : r#gen: None,
2485 0 : mode: LocationConfigMode::Secondary,
2486 0 : stripe_size: shard.shard.stripe_size,
2487 0 : });
2488 0 :
2489 0 : // We must not update observed, because we have no guarantee that our
2490 0 : // response will be received by the pageserver. This could leave it
2491 0 : // falsely dirty, but the resulting reconcile should be idempotent.
2492 0 : }
2493 : }
2494 :
2495 : // We consider a node Active once we have composed a re-attach response, but we
2496 : // do not call [`Self::node_activate_reconcile`]: the handling of the re-attach response
2497 : // implicitly synchronizes the LocationConfigs on the node.
2498 : //
2499 : // Setting a node active unblocks any Reconcilers that might write to the location config API,
2500 : // but those requests will not be accepted by the node until it has finished processing
2501 : // the re-attach response.
2502 : //
2503 : // Additionally, reset the nodes scheduling policy to match the conditional update done
2504 : // in [`Persistence::re_attach`].
2505 0 : if let Some(node) = nodes.get(&reattach_req.node_id) {
2506 0 : let reset_scheduling = matches!(
2507 0 : node.get_scheduling(),
2508 : NodeSchedulingPolicy::PauseForRestart
2509 : | NodeSchedulingPolicy::Draining
2510 : | NodeSchedulingPolicy::Filling
2511 : | NodeSchedulingPolicy::Deleting
2512 : );
2513 :
2514 0 : let mut new_nodes = (**nodes).clone();
2515 0 : if let Some(node) = new_nodes.get_mut(&reattach_req.node_id) {
2516 0 : if reset_scheduling {
2517 0 : node.set_scheduling(NodeSchedulingPolicy::Active);
2518 0 : }
2519 :
2520 0 : tracing::info!("Marking {} warming-up on reattach", reattach_req.node_id);
2521 0 : node.set_availability(NodeAvailability::WarmingUp(std::time::Instant::now()));
2522 :
2523 0 : scheduler.node_upsert(node);
2524 0 : let new_nodes = Arc::new(new_nodes);
2525 0 : *nodes = new_nodes;
2526 : } else {
2527 0 : tracing::error!(
2528 0 : "Reattaching node {} was removed while processing the request",
2529 : reattach_req.node_id
2530 : );
2531 : }
2532 0 : }
2533 :
2534 0 : Ok(response)
2535 0 : }
2536 :
2537 0 : pub(crate) async fn validate(
2538 0 : &self,
2539 0 : validate_req: ValidateRequest,
2540 0 : ) -> Result<ValidateResponse, DatabaseError> {
2541 : // Fast in-memory check: we may reject validation on anything that doesn't match our
2542 : // in-memory generation for a shard
2543 0 : let in_memory_result = {
2544 0 : let mut in_memory_result = Vec::new();
2545 0 : let locked = self.inner.read().unwrap();
2546 0 : for req_tenant in validate_req.tenants {
2547 0 : if let Some(tenant_shard) = locked.tenants.get(&req_tenant.id) {
2548 0 : let valid = tenant_shard.generation == Some(Generation::new(req_tenant.r#gen));
2549 0 : tracing::info!(
2550 0 : "handle_validate: {}(gen {}): valid={valid} (latest {:?})",
2551 : req_tenant.id,
2552 : req_tenant.r#gen,
2553 : tenant_shard.generation
2554 : );
2555 :
2556 0 : in_memory_result.push((
2557 0 : req_tenant.id,
2558 0 : Generation::new(req_tenant.r#gen),
2559 0 : valid,
2560 0 : ));
2561 : } else {
2562 : // This is legal: for example during a shard split the pageserver may still
2563 : // have deletions in its queue from the old pre-split shard, or after deletion
2564 : // of a tenant that was busy with compaction/gc while being deleted.
2565 0 : tracing::info!(
2566 0 : "Refusing deletion validation for missing shard {}",
2567 : req_tenant.id
2568 : );
2569 : }
2570 : }
2571 :
2572 0 : in_memory_result
2573 : };
2574 :
2575 : // Database calls to confirm validity for anything that passed the in-memory check. We must do this
2576 : // in case of controller split-brain, where some other controller process might have incremented the generation.
2577 0 : let db_generations = self
2578 0 : .persistence
2579 0 : .shard_generations(
2580 0 : in_memory_result
2581 0 : .iter()
2582 0 : .filter_map(|i| if i.2 { Some(&i.0) } else { None }),
2583 : )
2584 0 : .await?;
2585 0 : let db_generations = db_generations.into_iter().collect::<HashMap<_, _>>();
2586 :
2587 0 : let mut response = ValidateResponse {
2588 0 : tenants: Vec::new(),
2589 0 : };
2590 0 : for (tenant_shard_id, validate_generation, valid) in in_memory_result.into_iter() {
2591 0 : let valid = if valid {
2592 0 : let db_generation = db_generations.get(&tenant_shard_id);
2593 0 : db_generation == Some(&Some(validate_generation))
2594 : } else {
2595 : // If in-memory state says it's invalid, trust that. It's always safe to fail a validation, at worst
2596 : // this prevents a pageserver from cleaning up an object in S3.
2597 0 : false
2598 : };
2599 :
2600 0 : response.tenants.push(ValidateResponseTenant {
2601 0 : id: tenant_shard_id,
2602 0 : valid,
2603 0 : })
2604 : }
2605 :
2606 0 : Ok(response)
2607 0 : }
2608 :
2609 0 : pub(crate) async fn tenant_create(
2610 0 : &self,
2611 0 : create_req: TenantCreateRequest,
2612 0 : ) -> Result<TenantCreateResponse, ApiError> {
2613 0 : let tenant_id = create_req.new_tenant_id.tenant_id;
2614 :
2615 : // Exclude any concurrent attempts to create/access the same tenant ID
2616 0 : let _tenant_lock = trace_exclusive_lock(
2617 0 : &self.tenant_op_locks,
2618 0 : create_req.new_tenant_id.tenant_id,
2619 0 : TenantOperations::Create,
2620 0 : )
2621 0 : .await;
2622 0 : let (response, waiters) = self.do_tenant_create(create_req).await?;
2623 :
2624 0 : if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
2625 : // Avoid deadlock: reconcile may fail while notifying compute, if the cloud control plane refuses to
2626 : // accept compute notifications while it is in the process of creating. Reconciliation will
2627 : // be retried in the background.
2628 0 : tracing::warn!(%tenant_id, "Reconcile not done yet while creating tenant ({e})");
2629 0 : }
2630 0 : Ok(response)
2631 0 : }
2632 :
2633 0 : pub(crate) async fn do_tenant_create(
2634 0 : &self,
2635 0 : create_req: TenantCreateRequest,
2636 0 : ) -> Result<(TenantCreateResponse, Vec<ReconcilerWaiter>), ApiError> {
2637 0 : let placement_policy = create_req
2638 0 : .placement_policy
2639 0 : .clone()
2640 : // As a default, zero secondaries is convenient for tests that don't choose a policy.
2641 0 : .unwrap_or(PlacementPolicy::Attached(0));
2642 :
2643 : // This service expects to handle sharding itself: it is an error to try and directly create
2644 : // a particular shard here.
2645 0 : let tenant_id = if !create_req.new_tenant_id.is_unsharded() {
2646 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
2647 0 : "Attempted to create a specific shard, this API is for creating the whole tenant"
2648 0 : )));
2649 : } else {
2650 0 : create_req.new_tenant_id.tenant_id
2651 : };
2652 :
2653 0 : tracing::info!(
2654 0 : "Creating tenant {}, shard_count={:?}",
2655 : create_req.new_tenant_id,
2656 : create_req.shard_parameters.count,
2657 : );
2658 :
2659 0 : let create_ids = (0..create_req.shard_parameters.count.count())
2660 0 : .map(|i| TenantShardId {
2661 0 : tenant_id,
2662 0 : shard_number: ShardNumber(i),
2663 0 : shard_count: create_req.shard_parameters.count,
2664 0 : })
2665 0 : .collect::<Vec<_>>();
2666 :
2667 : // If the caller specifies a None generation, it means "start from default". This is different
2668 : // to [`Self::tenant_location_config`], where a None generation is used to represent
2669 : // an incompletely-onboarded tenant.
2670 0 : let initial_generation = if matches!(placement_policy, PlacementPolicy::Secondary) {
2671 0 : tracing::info!(
2672 0 : "tenant_create: secondary mode, generation is_some={}",
2673 0 : create_req.generation.is_some()
2674 : );
2675 0 : create_req.generation.map(Generation::new)
2676 : } else {
2677 0 : tracing::info!(
2678 0 : "tenant_create: not secondary mode, generation is_some={}",
2679 0 : create_req.generation.is_some()
2680 : );
2681 0 : Some(
2682 0 : create_req
2683 0 : .generation
2684 0 : .map(Generation::new)
2685 0 : .unwrap_or(INITIAL_GENERATION),
2686 0 : )
2687 : };
2688 :
2689 0 : let preferred_az_id = {
2690 0 : let locked = self.inner.read().unwrap();
2691 : // Idempotency: take the existing value if the tenant already exists
2692 0 : if let Some(shard) = locked.tenants.get(create_ids.first().unwrap()) {
2693 0 : shard.preferred_az().cloned()
2694 : } else {
2695 0 : locked.scheduler.get_az_for_new_tenant()
2696 : }
2697 : };
2698 :
2699 : // Ordering: we persist tenant shards before creating them on the pageserver. This enables a caller
2700 : // to clean up after themselves by issuing a tenant deletion if something goes wrong and we restart
2701 : // during the creation, rather than risking leaving orphan objects in S3.
2702 0 : let persist_tenant_shards = create_ids
2703 0 : .iter()
2704 0 : .map(|tenant_shard_id| TenantShardPersistence {
2705 0 : tenant_id: tenant_shard_id.tenant_id.to_string(),
2706 0 : shard_number: tenant_shard_id.shard_number.0 as i32,
2707 0 : shard_count: tenant_shard_id.shard_count.literal() as i32,
2708 0 : shard_stripe_size: create_req.shard_parameters.stripe_size.0 as i32,
2709 0 : generation: initial_generation.map(|g| g.into().unwrap() as i32),
2710 : // The pageserver is not known until scheduling happens: we will set this column when
2711 : // incrementing the generation the first time we attach to a pageserver.
2712 0 : generation_pageserver: None,
2713 0 : placement_policy: serde_json::to_string(&placement_policy).unwrap(),
2714 0 : config: serde_json::to_string(&create_req.config).unwrap(),
2715 0 : splitting: SplitState::default(),
2716 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
2717 0 : .unwrap(),
2718 0 : preferred_az_id: preferred_az_id.as_ref().map(|az| az.to_string()),
2719 0 : })
2720 0 : .collect();
2721 :
2722 0 : match self
2723 0 : .persistence
2724 0 : .insert_tenant_shards(persist_tenant_shards)
2725 0 : .await
2726 : {
2727 0 : Ok(_) => {}
2728 : Err(DatabaseError::Query(diesel::result::Error::DatabaseError(
2729 : DatabaseErrorKind::UniqueViolation,
2730 : _,
2731 : ))) => {
2732 : // Unique key violation: this is probably a retry. Because the shard count is part of the unique key,
2733 : // if we see a unique key violation it means that the creation request's shard count matches the previous
2734 : // creation's shard count.
2735 0 : tracing::info!(
2736 0 : "Tenant shards already present in database, proceeding with idempotent creation..."
2737 : );
2738 : }
2739 : // Any other database error is unexpected and a bug.
2740 0 : Err(e) => return Err(ApiError::InternalServerError(anyhow::anyhow!(e))),
2741 : };
2742 :
2743 0 : let mut schedule_context = ScheduleContext::default();
2744 0 : let mut schedule_error = None;
2745 0 : let mut response_shards = Vec::new();
2746 0 : for tenant_shard_id in create_ids {
2747 0 : tracing::info!("Creating shard {tenant_shard_id}...");
2748 :
2749 0 : let outcome = self
2750 0 : .do_initial_shard_scheduling(
2751 0 : tenant_shard_id,
2752 0 : initial_generation,
2753 0 : create_req.shard_parameters,
2754 0 : create_req.config.clone(),
2755 0 : placement_policy.clone(),
2756 0 : preferred_az_id.as_ref(),
2757 0 : &mut schedule_context,
2758 0 : )
2759 0 : .await;
2760 :
2761 0 : match outcome {
2762 0 : InitialShardScheduleOutcome::Scheduled(resp) => response_shards.push(resp),
2763 0 : InitialShardScheduleOutcome::NotScheduled => {}
2764 0 : InitialShardScheduleOutcome::ShardScheduleError(err) => {
2765 0 : schedule_error = Some(err);
2766 0 : }
2767 : }
2768 : }
2769 :
2770 : // If we failed to schedule shards, then they are still created in the controller,
2771 : // but we return an error to the requester to avoid a silent failure when someone
2772 : // tries to e.g. create a tenant whose placement policy requires more nodes than
2773 : // are present in the system. We do this here rather than in the above loop, to
2774 : // avoid situations where we only create a subset of shards in the tenant.
2775 0 : if let Some(e) = schedule_error {
2776 0 : return Err(ApiError::Conflict(format!(
2777 0 : "Failed to schedule shard(s): {e}"
2778 0 : )));
2779 0 : }
2780 :
2781 0 : let waiters = {
2782 0 : let mut locked = self.inner.write().unwrap();
2783 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2784 0 : let config = ReconcilerConfigBuilder::new(ReconcilerPriority::High)
2785 0 : .tenant_creation_hint(true)
2786 0 : .build();
2787 0 : tenants
2788 0 : .range_mut(TenantShardId::tenant_range(tenant_id))
2789 0 : .filter_map(|(_shard_id, shard)| {
2790 0 : self.maybe_configured_reconcile_shard(shard, nodes, config)
2791 0 : })
2792 0 : .collect::<Vec<_>>()
2793 : };
2794 :
2795 0 : Ok((
2796 0 : TenantCreateResponse {
2797 0 : shards: response_shards,
2798 0 : },
2799 0 : waiters,
2800 0 : ))
2801 0 : }
2802 :
2803 : /// Helper for tenant creation that does the scheduling for an individual shard. Covers both the
2804 : /// case of a new tenant and a pre-existing one.
2805 : #[allow(clippy::too_many_arguments)]
2806 0 : async fn do_initial_shard_scheduling(
2807 0 : &self,
2808 0 : tenant_shard_id: TenantShardId,
2809 0 : initial_generation: Option<Generation>,
2810 0 : shard_params: ShardParameters,
2811 0 : config: TenantConfig,
2812 0 : placement_policy: PlacementPolicy,
2813 0 : preferred_az_id: Option<&AvailabilityZone>,
2814 0 : schedule_context: &mut ScheduleContext,
2815 0 : ) -> InitialShardScheduleOutcome {
2816 0 : let mut locked = self.inner.write().unwrap();
2817 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
2818 :
2819 : use std::collections::btree_map::Entry;
2820 0 : match tenants.entry(tenant_shard_id) {
2821 0 : Entry::Occupied(mut entry) => {
2822 0 : tracing::info!("Tenant shard {tenant_shard_id} already exists while creating");
2823 :
2824 0 : if let Err(err) = entry.get_mut().schedule(scheduler, schedule_context) {
2825 0 : return InitialShardScheduleOutcome::ShardScheduleError(err);
2826 0 : }
2827 :
2828 0 : if let Some(node_id) = entry.get().intent.get_attached() {
2829 0 : let generation = entry
2830 0 : .get()
2831 0 : .generation
2832 0 : .expect("Generation is set when in attached mode");
2833 0 : InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
2834 0 : shard_id: tenant_shard_id,
2835 0 : node_id: *node_id,
2836 0 : generation: generation.into().unwrap(),
2837 0 : })
2838 : } else {
2839 0 : InitialShardScheduleOutcome::NotScheduled
2840 : }
2841 : }
2842 0 : Entry::Vacant(entry) => {
2843 0 : let state = entry.insert(TenantShard::new(
2844 0 : tenant_shard_id,
2845 0 : ShardIdentity::from_params(tenant_shard_id.shard_number, shard_params),
2846 0 : placement_policy,
2847 0 : preferred_az_id.cloned(),
2848 : ));
2849 :
2850 0 : state.generation = initial_generation;
2851 0 : state.config = config;
2852 0 : if let Err(e) = state.schedule(scheduler, schedule_context) {
2853 0 : return InitialShardScheduleOutcome::ShardScheduleError(e);
2854 0 : }
2855 :
2856 : // Only include shards in result if we are attaching: the purpose
2857 : // of the response is to tell the caller where the shards are attached.
2858 0 : if let Some(node_id) = state.intent.get_attached() {
2859 0 : let generation = state
2860 0 : .generation
2861 0 : .expect("Generation is set when in attached mode");
2862 0 : InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
2863 0 : shard_id: tenant_shard_id,
2864 0 : node_id: *node_id,
2865 0 : generation: generation.into().unwrap(),
2866 0 : })
2867 : } else {
2868 0 : InitialShardScheduleOutcome::NotScheduled
2869 : }
2870 : }
2871 : }
2872 0 : }
2873 :
2874 : /// Helper for functions that reconcile a number of shards, and would like to do a timeout-bounded
2875 : /// wait for reconciliation to complete before responding.
2876 0 : async fn await_waiters(
2877 0 : &self,
2878 0 : waiters: Vec<ReconcilerWaiter>,
2879 0 : timeout: Duration,
2880 0 : ) -> Result<(), ReconcileWaitError> {
2881 0 : let deadline = Instant::now().checked_add(timeout).unwrap();
2882 0 : for waiter in waiters {
2883 0 : let timeout = deadline.duration_since(Instant::now());
2884 0 : waiter.wait_timeout(timeout).await?;
2885 : }
2886 :
2887 0 : Ok(())
2888 0 : }
2889 :
2890 : /// Same as [`Service::await_waiters`], but returns the waiters which are still
2891 : /// in progress
2892 0 : async fn await_waiters_remainder(
2893 0 : &self,
2894 0 : waiters: Vec<ReconcilerWaiter>,
2895 0 : timeout: Duration,
2896 0 : ) -> Vec<ReconcilerWaiter> {
2897 0 : let deadline = Instant::now().checked_add(timeout).unwrap();
2898 0 : for waiter in waiters.iter() {
2899 0 : let timeout = deadline.duration_since(Instant::now());
2900 0 : let _ = waiter.wait_timeout(timeout).await;
2901 : }
2902 :
2903 0 : waiters
2904 0 : .into_iter()
2905 0 : .filter(|waiter| matches!(waiter.get_status(), ReconcilerStatus::InProgress))
2906 0 : .collect::<Vec<_>>()
2907 0 : }
2908 :
2909 : /// Part of [`Self::tenant_location_config`]: dissect an incoming location config request,
2910 : /// and transform it into either a tenant creation of a series of shard updates.
2911 : ///
2912 : /// If the incoming request makes no changes, a [`TenantCreateOrUpdate::Update`] result will
2913 : /// still be returned.
2914 0 : fn tenant_location_config_prepare(
2915 0 : &self,
2916 0 : tenant_id: TenantId,
2917 0 : req: TenantLocationConfigRequest,
2918 0 : ) -> TenantCreateOrUpdate {
2919 0 : let mut updates = Vec::new();
2920 0 : let mut locked = self.inner.write().unwrap();
2921 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2922 0 : let tenant_shard_id = TenantShardId::unsharded(tenant_id);
2923 :
2924 : // Use location config mode as an indicator of policy.
2925 0 : let placement_policy = match req.config.mode {
2926 0 : LocationConfigMode::Detached => PlacementPolicy::Detached,
2927 0 : LocationConfigMode::Secondary => PlacementPolicy::Secondary,
2928 : LocationConfigMode::AttachedMulti
2929 : | LocationConfigMode::AttachedSingle
2930 : | LocationConfigMode::AttachedStale => {
2931 0 : if nodes.len() > 1 {
2932 0 : PlacementPolicy::Attached(1)
2933 : } else {
2934 : // Convenience for dev/test: if we just have one pageserver, import
2935 : // tenants into non-HA mode so that scheduling will succeed.
2936 0 : PlacementPolicy::Attached(0)
2937 : }
2938 : }
2939 : };
2940 :
2941 : // Ordinarily we do not update scheduling policy, but when making major changes
2942 : // like detaching or demoting to secondary-only, we need to force the scheduling
2943 : // mode to Active, or the caller's expected outcome (detach it) will not happen.
2944 0 : let scheduling_policy = match req.config.mode {
2945 : LocationConfigMode::Detached | LocationConfigMode::Secondary => {
2946 : // Special case: when making major changes like detaching or demoting to secondary-only,
2947 : // we need to force the scheduling mode to Active, or nothing will happen.
2948 0 : Some(ShardSchedulingPolicy::Active)
2949 : }
2950 : LocationConfigMode::AttachedMulti
2951 : | LocationConfigMode::AttachedSingle
2952 : | LocationConfigMode::AttachedStale => {
2953 : // While attached, continue to respect whatever the existing scheduling mode is.
2954 0 : None
2955 : }
2956 : };
2957 :
2958 0 : let mut create = true;
2959 0 : for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
2960 : // Saw an existing shard: this is not a creation
2961 0 : create = false;
2962 :
2963 : // Shards may have initially been created by a Secondary request, where we
2964 : // would have left generation as None.
2965 : //
2966 : // We only update generation the first time we see an attached-mode request,
2967 : // and if there is no existing generation set. The caller is responsible for
2968 : // ensuring that no non-storage-controller pageserver ever uses a higher
2969 : // generation than they passed in here.
2970 : use LocationConfigMode::*;
2971 0 : let set_generation = match req.config.mode {
2972 0 : AttachedMulti | AttachedSingle | AttachedStale if shard.generation.is_none() => {
2973 0 : req.config.generation.map(Generation::new)
2974 : }
2975 0 : _ => None,
2976 : };
2977 :
2978 0 : updates.push(ShardUpdate {
2979 0 : tenant_shard_id: *shard_id,
2980 0 : placement_policy: placement_policy.clone(),
2981 0 : tenant_config: req.config.tenant_conf.clone(),
2982 0 : generation: set_generation,
2983 0 : scheduling_policy,
2984 0 : });
2985 : }
2986 :
2987 0 : if create {
2988 : use LocationConfigMode::*;
2989 0 : let generation = match req.config.mode {
2990 0 : AttachedMulti | AttachedSingle | AttachedStale => req.config.generation,
2991 : // If a caller provided a generation in a non-attached request, ignore it
2992 : // and leave our generation as None: this enables a subsequent update to set
2993 : // the generation when setting an attached mode for the first time.
2994 0 : _ => None,
2995 : };
2996 :
2997 0 : TenantCreateOrUpdate::Create(
2998 0 : // Synthesize a creation request
2999 0 : TenantCreateRequest {
3000 0 : new_tenant_id: tenant_shard_id,
3001 0 : generation,
3002 0 : shard_parameters: ShardParameters {
3003 0 : count: tenant_shard_id.shard_count,
3004 0 : // We only import un-sharded or single-sharded tenants, so stripe
3005 0 : // size can be made up arbitrarily here.
3006 0 : stripe_size: DEFAULT_STRIPE_SIZE,
3007 0 : },
3008 0 : placement_policy: Some(placement_policy),
3009 0 : config: req.config.tenant_conf,
3010 0 : },
3011 0 : )
3012 : } else {
3013 0 : assert!(!updates.is_empty());
3014 0 : TenantCreateOrUpdate::Update(updates)
3015 : }
3016 0 : }
3017 :
3018 : /// For APIs that might act on tenants with [`PlacementPolicy::Detached`], first check if
3019 : /// the tenant is present in memory. If not, load it from the database. If it is found
3020 : /// in neither location, return a NotFound error.
3021 : ///
3022 : /// Caller must demonstrate they hold a lock guard, as otherwise two callers might try and load
3023 : /// it at the same time, or we might race with [`Self::maybe_drop_tenant`]
3024 0 : async fn maybe_load_tenant(
3025 0 : &self,
3026 0 : tenant_id: TenantId,
3027 0 : _guard: &TracingExclusiveGuard<TenantOperations>,
3028 0 : ) -> Result<(), ApiError> {
3029 : // Check if the tenant is present in memory, and select an AZ to use when loading
3030 : // if we will load it.
3031 0 : let load_in_az = {
3032 0 : let locked = self.inner.read().unwrap();
3033 0 : let existing = locked
3034 0 : .tenants
3035 0 : .range(TenantShardId::tenant_range(tenant_id))
3036 0 : .next();
3037 :
3038 : // If the tenant is not present in memory, we expect to load it from database,
3039 : // so let's figure out what AZ to load it into while we have self.inner locked.
3040 0 : if existing.is_none() {
3041 0 : locked
3042 0 : .scheduler
3043 0 : .get_az_for_new_tenant()
3044 0 : .ok_or(ApiError::BadRequest(anyhow::anyhow!(
3045 0 : "No AZ with nodes found to load tenant"
3046 0 : )))?
3047 : } else {
3048 : // We already have this tenant in memory
3049 0 : return Ok(());
3050 : }
3051 : };
3052 :
3053 0 : let tenant_shards = self.persistence.load_tenant(tenant_id).await?;
3054 0 : if tenant_shards.is_empty() {
3055 0 : return Err(ApiError::NotFound(
3056 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
3057 0 : ));
3058 0 : }
3059 :
3060 : // Update the persistent shards with the AZ that we are about to apply to in-memory state
3061 0 : self.persistence
3062 0 : .set_tenant_shard_preferred_azs(
3063 0 : tenant_shards
3064 0 : .iter()
3065 0 : .map(|t| {
3066 0 : (
3067 0 : t.get_tenant_shard_id().expect("Corrupt shard in database"),
3068 0 : Some(load_in_az.clone()),
3069 0 : )
3070 0 : })
3071 0 : .collect(),
3072 : )
3073 0 : .await?;
3074 :
3075 0 : let mut locked = self.inner.write().unwrap();
3076 0 : tracing::info!(
3077 0 : "Loaded {} shards for tenant {}",
3078 0 : tenant_shards.len(),
3079 : tenant_id
3080 : );
3081 :
3082 0 : locked.tenants.extend(tenant_shards.into_iter().map(|p| {
3083 0 : let intent = IntentState::new(Some(load_in_az.clone()));
3084 0 : let shard =
3085 0 : TenantShard::from_persistent(p, intent).expect("Corrupt shard row in database");
3086 :
3087 : // Sanity check: when loading on-demand, we should always be loaded something Detached
3088 0 : debug_assert!(shard.policy == PlacementPolicy::Detached);
3089 0 : if shard.policy != PlacementPolicy::Detached {
3090 0 : tracing::error!(
3091 0 : "Tenant shard {} loaded on-demand, but has non-Detached policy {:?}",
3092 : shard.tenant_shard_id,
3093 : shard.policy
3094 : );
3095 0 : }
3096 :
3097 0 : (shard.tenant_shard_id, shard)
3098 0 : }));
3099 :
3100 0 : Ok(())
3101 0 : }
3102 :
3103 : /// If all shards for a tenant are detached, and in a fully quiescent state (no observed locations on pageservers),
3104 : /// and have no reconciler running, then we can drop the tenant from memory. It will be reloaded on-demand
3105 : /// if we are asked to attach it again (see [`Self::maybe_load_tenant`]).
3106 : ///
3107 : /// Caller must demonstrate they hold a lock guard, as otherwise it is unsafe to drop a tenant from
3108 : /// memory while some other function might assume it continues to exist while not holding the lock on Self::inner.
3109 0 : fn maybe_drop_tenant(
3110 0 : &self,
3111 0 : tenant_id: TenantId,
3112 0 : locked: &mut std::sync::RwLockWriteGuard<ServiceState>,
3113 0 : _guard: &TracingExclusiveGuard<TenantOperations>,
3114 0 : ) {
3115 0 : let mut tenant_shards = locked.tenants.range(TenantShardId::tenant_range(tenant_id));
3116 0 : if tenant_shards.all(|(_id, shard)| {
3117 0 : shard.policy == PlacementPolicy::Detached
3118 0 : && shard.reconciler.is_none()
3119 0 : && shard.observed.is_empty()
3120 0 : }) {
3121 0 : let keys = locked
3122 0 : .tenants
3123 0 : .range(TenantShardId::tenant_range(tenant_id))
3124 0 : .map(|(id, _)| id)
3125 0 : .copied()
3126 0 : .collect::<Vec<_>>();
3127 0 : for key in keys {
3128 0 : tracing::info!("Dropping detached tenant shard {} from memory", key);
3129 0 : locked.tenants.remove(&key);
3130 : }
3131 0 : }
3132 0 : }
3133 :
3134 : /// This API is used by the cloud control plane to migrate unsharded tenants that it created
3135 : /// directly with pageservers into this service.
3136 : ///
3137 : /// Cloud control plane MUST NOT continue issuing GENERATION NUMBERS for this tenant once it
3138 : /// has attempted to call this API. Failure to oblige to this rule may lead to S3 corruption.
3139 : /// Think of the first attempt to call this API as a transfer of absolute authority over the
3140 : /// tenant's source of generation numbers.
3141 : ///
3142 : /// The mode in this request coarse-grained control of tenants:
3143 : /// - Call with mode Attached* to upsert the tenant.
3144 : /// - Call with mode Secondary to either onboard a tenant without attaching it, or
3145 : /// to set an existing tenant to PolicyMode::Secondary
3146 : /// - Call with mode Detached to switch to PolicyMode::Detached
3147 0 : pub(crate) async fn tenant_location_config(
3148 0 : &self,
3149 0 : tenant_shard_id: TenantShardId,
3150 0 : req: TenantLocationConfigRequest,
3151 0 : ) -> Result<TenantLocationConfigResponse, ApiError> {
3152 : // We require an exclusive lock, because we are updating both persistent and in-memory state
3153 0 : let _tenant_lock = trace_exclusive_lock(
3154 0 : &self.tenant_op_locks,
3155 0 : tenant_shard_id.tenant_id,
3156 0 : TenantOperations::LocationConfig,
3157 0 : )
3158 0 : .await;
3159 :
3160 0 : let tenant_id = if !tenant_shard_id.is_unsharded() {
3161 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
3162 0 : "This API is for importing single-sharded or unsharded tenants"
3163 0 : )));
3164 : } else {
3165 0 : tenant_shard_id.tenant_id
3166 : };
3167 :
3168 : // In case we are waking up a Detached tenant
3169 0 : match self.maybe_load_tenant(tenant_id, &_tenant_lock).await {
3170 0 : Ok(()) | Err(ApiError::NotFound(_)) => {
3171 0 : // This is a creation or an update
3172 0 : }
3173 0 : Err(e) => {
3174 0 : return Err(e);
3175 : }
3176 : };
3177 :
3178 : // First check if this is a creation or an update
3179 0 : let create_or_update = self.tenant_location_config_prepare(tenant_id, req);
3180 :
3181 0 : let mut result = TenantLocationConfigResponse {
3182 0 : shards: Vec::new(),
3183 0 : stripe_size: None,
3184 0 : };
3185 0 : let waiters = match create_or_update {
3186 0 : TenantCreateOrUpdate::Create(create_req) => {
3187 0 : let (create_resp, waiters) = self.do_tenant_create(create_req).await?;
3188 0 : result.shards = create_resp
3189 0 : .shards
3190 0 : .into_iter()
3191 0 : .map(|s| TenantShardLocation {
3192 0 : node_id: s.node_id,
3193 0 : shard_id: s.shard_id,
3194 0 : })
3195 0 : .collect();
3196 0 : waiters
3197 : }
3198 0 : TenantCreateOrUpdate::Update(updates) => {
3199 : // Persist updates
3200 : // Ordering: write to the database before applying changes in-memory, so that
3201 : // we will not appear time-travel backwards on a restart.
3202 :
3203 0 : let mut schedule_context = ScheduleContext::default();
3204 : for ShardUpdate {
3205 0 : tenant_shard_id,
3206 0 : placement_policy,
3207 0 : tenant_config,
3208 0 : generation,
3209 0 : scheduling_policy,
3210 0 : } in &updates
3211 : {
3212 0 : self.persistence
3213 0 : .update_tenant_shard(
3214 0 : TenantFilter::Shard(*tenant_shard_id),
3215 0 : Some(placement_policy.clone()),
3216 0 : Some(tenant_config.clone()),
3217 0 : *generation,
3218 0 : *scheduling_policy,
3219 0 : )
3220 0 : .await?;
3221 : }
3222 :
3223 : // Apply updates in-memory
3224 0 : let mut waiters = Vec::new();
3225 : {
3226 0 : let mut locked = self.inner.write().unwrap();
3227 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3228 :
3229 : for ShardUpdate {
3230 0 : tenant_shard_id,
3231 0 : placement_policy,
3232 0 : tenant_config,
3233 0 : generation: update_generation,
3234 0 : scheduling_policy,
3235 0 : } in updates
3236 : {
3237 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
3238 0 : tracing::warn!("Shard {tenant_shard_id} removed while updating");
3239 0 : continue;
3240 : };
3241 :
3242 : // Update stripe size
3243 0 : if result.stripe_size.is_none() && shard.shard.count.count() > 1 {
3244 0 : result.stripe_size = Some(shard.shard.stripe_size);
3245 0 : }
3246 :
3247 0 : shard.policy = placement_policy;
3248 0 : shard.config = tenant_config;
3249 0 : if let Some(generation) = update_generation {
3250 0 : shard.generation = Some(generation);
3251 0 : }
3252 :
3253 0 : if let Some(scheduling_policy) = scheduling_policy {
3254 0 : shard.set_scheduling_policy(scheduling_policy);
3255 0 : }
3256 :
3257 0 : shard.schedule(scheduler, &mut schedule_context)?;
3258 :
3259 0 : let maybe_waiter =
3260 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
3261 0 : if let Some(waiter) = maybe_waiter {
3262 0 : waiters.push(waiter);
3263 0 : }
3264 :
3265 0 : if let Some(node_id) = shard.intent.get_attached() {
3266 0 : result.shards.push(TenantShardLocation {
3267 0 : shard_id: tenant_shard_id,
3268 0 : node_id: *node_id,
3269 0 : })
3270 0 : }
3271 : }
3272 : }
3273 0 : waiters
3274 : }
3275 : };
3276 :
3277 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
3278 : // Do not treat a reconcile error as fatal: we have already applied any requested
3279 : // Intent changes, and the reconcile can fail for external reasons like unavailable
3280 : // compute notification API. In these cases, it is important that we do not
3281 : // cause the cloud control plane to retry forever on this API.
3282 0 : tracing::warn!(
3283 0 : "Failed to reconcile after /location_config: {e}, returning success anyway"
3284 : );
3285 0 : }
3286 :
3287 : // Logging the full result is useful because it lets us cross-check what the cloud control
3288 : // plane's tenant_shards table should contain.
3289 0 : tracing::info!("Complete, returning {result:?}");
3290 :
3291 0 : Ok(result)
3292 0 : }
3293 :
3294 0 : pub(crate) async fn tenant_config_patch(
3295 0 : &self,
3296 0 : req: TenantConfigPatchRequest,
3297 0 : ) -> Result<(), ApiError> {
3298 0 : let _tenant_lock = trace_exclusive_lock(
3299 0 : &self.tenant_op_locks,
3300 0 : req.tenant_id,
3301 0 : TenantOperations::ConfigPatch,
3302 0 : )
3303 0 : .await;
3304 :
3305 0 : let tenant_id = req.tenant_id;
3306 0 : let patch = req.config;
3307 :
3308 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3309 :
3310 0 : let base = {
3311 0 : let locked = self.inner.read().unwrap();
3312 0 : let shards = locked
3313 0 : .tenants
3314 0 : .range(TenantShardId::tenant_range(req.tenant_id));
3315 :
3316 0 : let mut configs = shards.map(|(_sid, shard)| &shard.config).peekable();
3317 :
3318 0 : let first = match configs.peek() {
3319 0 : Some(first) => (*first).clone(),
3320 : None => {
3321 0 : return Err(ApiError::NotFound(
3322 0 : anyhow::anyhow!("Tenant {} not found", req.tenant_id).into(),
3323 0 : ));
3324 : }
3325 : };
3326 :
3327 0 : if !configs.all_equal() {
3328 0 : tracing::error!("Tenant configs for {} are mismatched. ", req.tenant_id);
3329 : // This can't happen because we atomically update the database records
3330 : // of all shards to the new value in [`Self::set_tenant_config_and_reconcile`].
3331 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3332 0 : "Tenant configs for {} are mismatched",
3333 0 : req.tenant_id
3334 0 : )));
3335 0 : }
3336 :
3337 0 : first
3338 : };
3339 :
3340 0 : let updated_config = base
3341 0 : .apply_patch(patch)
3342 0 : .map_err(|err| ApiError::BadRequest(anyhow::anyhow!(err)))?;
3343 0 : self.set_tenant_config_and_reconcile(tenant_id, updated_config)
3344 0 : .await
3345 0 : }
3346 :
3347 0 : pub(crate) async fn tenant_config_set(&self, req: TenantConfigRequest) -> Result<(), ApiError> {
3348 : // We require an exclusive lock, because we are updating persistent and in-memory state
3349 0 : let _tenant_lock = trace_exclusive_lock(
3350 0 : &self.tenant_op_locks,
3351 0 : req.tenant_id,
3352 0 : TenantOperations::ConfigSet,
3353 0 : )
3354 0 : .await;
3355 :
3356 0 : self.maybe_load_tenant(req.tenant_id, &_tenant_lock).await?;
3357 :
3358 0 : self.set_tenant_config_and_reconcile(req.tenant_id, req.config)
3359 0 : .await
3360 0 : }
3361 :
3362 0 : async fn set_tenant_config_and_reconcile(
3363 0 : &self,
3364 0 : tenant_id: TenantId,
3365 0 : config: TenantConfig,
3366 0 : ) -> Result<(), ApiError> {
3367 0 : self.persistence
3368 0 : .update_tenant_shard(
3369 0 : TenantFilter::Tenant(tenant_id),
3370 0 : None,
3371 0 : Some(config.clone()),
3372 0 : None,
3373 0 : None,
3374 0 : )
3375 0 : .await?;
3376 :
3377 0 : let waiters = {
3378 0 : let mut waiters = Vec::new();
3379 0 : let mut locked = self.inner.write().unwrap();
3380 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
3381 0 : for (_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3382 0 : shard.config = config.clone();
3383 0 : if let Some(waiter) =
3384 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
3385 0 : {
3386 0 : waiters.push(waiter);
3387 0 : }
3388 : }
3389 0 : waiters
3390 : };
3391 :
3392 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
3393 : // Treat this as success because we have stored the configuration. If e.g.
3394 : // a node was unavailable at this time, it should not stop us accepting a
3395 : // configuration change.
3396 0 : tracing::warn!(%tenant_id, "Accepted configuration update but reconciliation failed: {e}");
3397 0 : }
3398 :
3399 0 : Ok(())
3400 0 : }
3401 :
3402 0 : pub(crate) fn tenant_config_get(
3403 0 : &self,
3404 0 : tenant_id: TenantId,
3405 0 : ) -> Result<HashMap<&str, serde_json::Value>, ApiError> {
3406 0 : let config = {
3407 0 : let locked = self.inner.read().unwrap();
3408 :
3409 0 : match locked
3410 0 : .tenants
3411 0 : .range(TenantShardId::tenant_range(tenant_id))
3412 0 : .next()
3413 : {
3414 0 : Some((_tenant_shard_id, shard)) => shard.config.clone(),
3415 : None => {
3416 0 : return Err(ApiError::NotFound(
3417 0 : anyhow::anyhow!("Tenant not found").into(),
3418 0 : ));
3419 : }
3420 : }
3421 : };
3422 :
3423 : // Unlike the pageserver, we do not have a set of global defaults: the config is
3424 : // entirely per-tenant. Therefore the distinction between `tenant_specific_overrides`
3425 : // and `effective_config` in the response is meaningless, but we retain that syntax
3426 : // in order to remain compatible with the pageserver API.
3427 :
3428 0 : let response = HashMap::from([
3429 : (
3430 : "tenant_specific_overrides",
3431 0 : serde_json::to_value(&config)
3432 0 : .context("serializing tenant specific overrides")
3433 0 : .map_err(ApiError::InternalServerError)?,
3434 : ),
3435 : (
3436 0 : "effective_config",
3437 0 : serde_json::to_value(&config)
3438 0 : .context("serializing effective config")
3439 0 : .map_err(ApiError::InternalServerError)?,
3440 : ),
3441 : ]);
3442 :
3443 0 : Ok(response)
3444 0 : }
3445 :
3446 0 : pub(crate) async fn tenant_time_travel_remote_storage(
3447 0 : &self,
3448 0 : time_travel_req: &TenantTimeTravelRequest,
3449 0 : tenant_id: TenantId,
3450 0 : timestamp: Cow<'_, str>,
3451 0 : done_if_after: Cow<'_, str>,
3452 0 : ) -> Result<(), ApiError> {
3453 0 : let _tenant_lock = trace_exclusive_lock(
3454 0 : &self.tenant_op_locks,
3455 0 : tenant_id,
3456 0 : TenantOperations::TimeTravelRemoteStorage,
3457 0 : )
3458 0 : .await;
3459 :
3460 0 : let node = {
3461 0 : let mut locked = self.inner.write().unwrap();
3462 : // Just a sanity check to prevent misuse: the API expects that the tenant is fully
3463 : // detached everywhere, and nothing writes to S3 storage. Here, we verify that,
3464 : // but only at the start of the process, so it's really just to prevent operator
3465 : // mistakes.
3466 0 : for (shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
3467 0 : if shard.intent.get_attached().is_some() || !shard.intent.get_secondary().is_empty()
3468 : {
3469 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3470 0 : "We want tenant to be attached in shard with tenant_shard_id={shard_id}"
3471 0 : )));
3472 0 : }
3473 0 : let maybe_attached = shard
3474 0 : .observed
3475 0 : .locations
3476 0 : .iter()
3477 0 : .filter_map(|(node_id, observed_location)| {
3478 0 : observed_location
3479 0 : .conf
3480 0 : .as_ref()
3481 0 : .map(|loc| (node_id, observed_location, loc.mode))
3482 0 : })
3483 0 : .find(|(_, _, mode)| *mode != LocationConfigMode::Detached);
3484 0 : if let Some((node_id, _observed_location, mode)) = maybe_attached {
3485 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3486 0 : "We observed attached={mode:?} tenant in node_id={node_id} shard with tenant_shard_id={shard_id}"
3487 0 : )));
3488 0 : }
3489 : }
3490 0 : let scheduler = &mut locked.scheduler;
3491 : // Right now we only perform the operation on a single node without parallelization
3492 : // TODO fan out the operation to multiple nodes for better performance
3493 0 : let node_id = scheduler.any_available_node()?;
3494 0 : let node = locked
3495 0 : .nodes
3496 0 : .get(&node_id)
3497 0 : .expect("Pageservers may not be deleted while lock is active");
3498 0 : node.clone()
3499 : };
3500 :
3501 : // The shard count is encoded in the remote storage's URL, so we need to handle all historically used shard counts
3502 0 : let mut counts = time_travel_req
3503 0 : .shard_counts
3504 0 : .iter()
3505 0 : .copied()
3506 0 : .collect::<HashSet<_>>()
3507 0 : .into_iter()
3508 0 : .collect::<Vec<_>>();
3509 0 : counts.sort_unstable();
3510 :
3511 0 : for count in counts {
3512 0 : let shard_ids = (0..count.count())
3513 0 : .map(|i| TenantShardId {
3514 0 : tenant_id,
3515 0 : shard_number: ShardNumber(i),
3516 0 : shard_count: count,
3517 0 : })
3518 0 : .collect::<Vec<_>>();
3519 0 : for tenant_shard_id in shard_ids {
3520 0 : let client = PageserverClient::new(
3521 0 : node.get_id(),
3522 0 : self.http_client.clone(),
3523 0 : node.base_url(),
3524 0 : self.config.pageserver_jwt_token.as_deref(),
3525 : );
3526 :
3527 0 : tracing::info!("Doing time travel recovery for shard {tenant_shard_id}",);
3528 :
3529 0 : client
3530 0 : .tenant_time_travel_remote_storage(
3531 0 : tenant_shard_id,
3532 0 : ×tamp,
3533 0 : &done_if_after,
3534 0 : )
3535 0 : .await
3536 0 : .map_err(|e| {
3537 0 : ApiError::InternalServerError(anyhow::anyhow!(
3538 0 : "Error doing time travel recovery for shard {tenant_shard_id} on node {}: {e}",
3539 0 : node
3540 0 : ))
3541 0 : })?;
3542 : }
3543 : }
3544 0 : Ok(())
3545 0 : }
3546 :
3547 0 : pub(crate) async fn tenant_secondary_download(
3548 0 : &self,
3549 0 : tenant_id: TenantId,
3550 0 : wait: Option<Duration>,
3551 0 : ) -> Result<(StatusCode, SecondaryProgress), ApiError> {
3552 0 : let _tenant_lock = trace_shared_lock(
3553 0 : &self.tenant_op_locks,
3554 0 : tenant_id,
3555 0 : TenantOperations::SecondaryDownload,
3556 0 : )
3557 0 : .await;
3558 :
3559 : // Acquire lock and yield the collection of shard-node tuples which we will send requests onward to
3560 0 : let targets = {
3561 0 : let locked = self.inner.read().unwrap();
3562 0 : let mut targets = Vec::new();
3563 :
3564 0 : for (tenant_shard_id, shard) in
3565 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
3566 : {
3567 0 : for node_id in shard.intent.get_secondary() {
3568 0 : let node = locked
3569 0 : .nodes
3570 0 : .get(node_id)
3571 0 : .expect("Pageservers may not be deleted while referenced");
3572 0 :
3573 0 : targets.push((*tenant_shard_id, node.clone()));
3574 0 : }
3575 : }
3576 0 : targets
3577 : };
3578 :
3579 : // Issue concurrent requests to all shards' locations
3580 0 : let mut futs = FuturesUnordered::new();
3581 0 : for (tenant_shard_id, node) in targets {
3582 0 : let client = PageserverClient::new(
3583 0 : node.get_id(),
3584 0 : self.http_client.clone(),
3585 0 : node.base_url(),
3586 0 : self.config.pageserver_jwt_token.as_deref(),
3587 : );
3588 0 : futs.push(async move {
3589 0 : let result = client
3590 0 : .tenant_secondary_download(tenant_shard_id, wait)
3591 0 : .await;
3592 0 : (result, node, tenant_shard_id)
3593 0 : })
3594 : }
3595 :
3596 : // Handle any errors returned by pageservers. This includes cases like this request racing with
3597 : // a scheduling operation, such that the tenant shard we're calling doesn't exist on that pageserver any more, as
3598 : // well as more general cases like 503s, 500s, or timeouts.
3599 0 : let mut aggregate_progress = SecondaryProgress::default();
3600 0 : let mut aggregate_status: Option<StatusCode> = None;
3601 0 : let mut error: Option<mgmt_api::Error> = None;
3602 0 : while let Some((result, node, tenant_shard_id)) = futs.next().await {
3603 0 : match result {
3604 0 : Err(e) => {
3605 : // Secondary downloads are always advisory: if something fails, we nevertheless report success, so that whoever
3606 : // is calling us will proceed with whatever migration they're doing, albeit with a slightly less warm cache
3607 : // than they had hoped for.
3608 0 : tracing::warn!("Secondary download error from pageserver {node}: {e}",);
3609 0 : error = Some(e)
3610 : }
3611 0 : Ok((status_code, progress)) => {
3612 0 : tracing::info!(%tenant_shard_id, "Shard status={status_code} progress: {progress:?}");
3613 0 : aggregate_progress.layers_downloaded += progress.layers_downloaded;
3614 0 : aggregate_progress.layers_total += progress.layers_total;
3615 0 : aggregate_progress.bytes_downloaded += progress.bytes_downloaded;
3616 0 : aggregate_progress.bytes_total += progress.bytes_total;
3617 0 : aggregate_progress.heatmap_mtime =
3618 0 : std::cmp::max(aggregate_progress.heatmap_mtime, progress.heatmap_mtime);
3619 0 : aggregate_status = match aggregate_status {
3620 0 : None => Some(status_code),
3621 0 : Some(StatusCode::OK) => Some(status_code),
3622 0 : Some(cur) => {
3623 : // Other status codes (e.g. 202) -- do not overwrite.
3624 0 : Some(cur)
3625 : }
3626 : };
3627 : }
3628 : }
3629 : }
3630 :
3631 : // If any of the shards return 202, indicate our result as 202.
3632 0 : match aggregate_status {
3633 : None => {
3634 0 : match error {
3635 0 : Some(e) => {
3636 : // No successes, and an error: surface it
3637 0 : Err(ApiError::Conflict(format!("Error from pageserver: {e}")))
3638 : }
3639 : None => {
3640 : // No shards found
3641 0 : Err(ApiError::NotFound(
3642 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
3643 0 : ))
3644 : }
3645 : }
3646 : }
3647 0 : Some(aggregate_status) => Ok((aggregate_status, aggregate_progress)),
3648 : }
3649 0 : }
3650 :
3651 0 : pub(crate) async fn tenant_delete(
3652 0 : self: &Arc<Self>,
3653 0 : tenant_id: TenantId,
3654 0 : ) -> Result<StatusCode, ApiError> {
3655 0 : let _tenant_lock =
3656 0 : trace_exclusive_lock(&self.tenant_op_locks, tenant_id, TenantOperations::Delete).await;
3657 :
3658 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3659 :
3660 : // Detach all shards. This also deletes local pageserver shard data.
3661 0 : let (detach_waiters, node) = {
3662 0 : let mut detach_waiters = Vec::new();
3663 0 : let mut locked = self.inner.write().unwrap();
3664 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3665 0 : for (_, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3666 : // Update the tenant's intent to remove all attachments
3667 0 : shard.policy = PlacementPolicy::Detached;
3668 0 : shard
3669 0 : .schedule(scheduler, &mut ScheduleContext::default())
3670 0 : .expect("De-scheduling is infallible");
3671 0 : debug_assert!(shard.intent.get_attached().is_none());
3672 0 : debug_assert!(shard.intent.get_secondary().is_empty());
3673 :
3674 0 : if let Some(waiter) =
3675 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
3676 0 : {
3677 0 : detach_waiters.push(waiter);
3678 0 : }
3679 : }
3680 :
3681 : // Pick an arbitrary node to use for remote deletions (does not have to be where the tenant
3682 : // was attached, just has to be able to see the S3 content)
3683 0 : let node_id = scheduler.any_available_node()?;
3684 0 : let node = nodes
3685 0 : .get(&node_id)
3686 0 : .expect("Pageservers may not be deleted while lock is active");
3687 0 : (detach_waiters, node.clone())
3688 : };
3689 :
3690 : // This reconcile wait can fail in a few ways:
3691 : // A there is a very long queue for the reconciler semaphore
3692 : // B some pageserver is failing to handle a detach promptly
3693 : // C some pageserver goes offline right at the moment we send it a request.
3694 : //
3695 : // A and C are transient: the semaphore will eventually become available, and once a node is marked offline
3696 : // the next attempt to reconcile will silently skip detaches for an offline node and succeed. If B happens,
3697 : // it's a bug, and needs resolving at the pageserver level (we shouldn't just leave attachments behind while
3698 : // deleting the underlying data).
3699 0 : self.await_waiters(detach_waiters, RECONCILE_TIMEOUT)
3700 0 : .await?;
3701 :
3702 : // Delete the entire tenant (all shards) from remote storage via a random pageserver.
3703 : // Passing an unsharded tenant ID will cause the pageserver to remove all remote paths with
3704 : // the tenant ID prefix, including all shards (even possibly stale ones).
3705 0 : match node
3706 0 : .with_client_retries(
3707 0 : |client| async move {
3708 0 : client
3709 0 : .tenant_delete(TenantShardId::unsharded(tenant_id))
3710 0 : .await
3711 0 : },
3712 0 : &self.http_client,
3713 0 : &self.config.pageserver_jwt_token,
3714 : 1,
3715 : 3,
3716 : RECONCILE_TIMEOUT,
3717 0 : &self.cancel,
3718 : )
3719 0 : .await
3720 0 : .unwrap_or(Err(mgmt_api::Error::Cancelled))
3721 : {
3722 0 : Ok(_) => {}
3723 : Err(mgmt_api::Error::Cancelled) => {
3724 0 : return Err(ApiError::ShuttingDown);
3725 : }
3726 0 : Err(e) => {
3727 : // This is unexpected: remote deletion should be infallible, unless the object store
3728 : // at large is unavailable.
3729 0 : tracing::error!("Error deleting via node {node}: {e}");
3730 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
3731 : }
3732 : }
3733 :
3734 : // Fall through: deletion of the tenant on pageservers is complete, we may proceed to drop
3735 : // our in-memory state and database state.
3736 :
3737 : // Ordering: we delete persistent state first: if we then
3738 : // crash, we will drop the in-memory state.
3739 :
3740 : // Drop persistent state.
3741 0 : self.persistence.delete_tenant(tenant_id).await?;
3742 :
3743 : // Drop in-memory state
3744 : {
3745 0 : let mut locked = self.inner.write().unwrap();
3746 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
3747 :
3748 : // Dereference Scheduler from shards before dropping them
3749 0 : for (_tenant_shard_id, shard) in
3750 0 : tenants.range_mut(TenantShardId::tenant_range(tenant_id))
3751 0 : {
3752 0 : shard.intent.clear(scheduler);
3753 0 : }
3754 :
3755 0 : tenants.retain(|tenant_shard_id, _shard| tenant_shard_id.tenant_id != tenant_id);
3756 0 : tracing::info!(
3757 0 : "Deleted tenant {tenant_id}, now have {} tenants",
3758 0 : locked.tenants.len()
3759 : );
3760 : };
3761 :
3762 : // Delete the tenant from safekeepers (if needed)
3763 0 : self.tenant_delete_safekeepers(tenant_id)
3764 0 : .instrument(tracing::info_span!("tenant_delete_safekeepers", %tenant_id))
3765 0 : .await?;
3766 :
3767 : // Success is represented as 404, to imitate the existing pageserver deletion API
3768 0 : Ok(StatusCode::NOT_FOUND)
3769 0 : }
3770 :
3771 : /// Naming: this configures the storage controller's policies for a tenant, whereas [`Self::tenant_config_set`] is "set the TenantConfig"
3772 : /// for a tenant. The TenantConfig is passed through to pageservers, whereas this function modifies
3773 : /// the tenant's policies (configuration) within the storage controller
3774 0 : pub(crate) async fn tenant_update_policy(
3775 0 : &self,
3776 0 : tenant_id: TenantId,
3777 0 : req: TenantPolicyRequest,
3778 0 : ) -> Result<(), ApiError> {
3779 : // We require an exclusive lock, because we are updating persistent and in-memory state
3780 0 : let _tenant_lock = trace_exclusive_lock(
3781 0 : &self.tenant_op_locks,
3782 0 : tenant_id,
3783 0 : TenantOperations::UpdatePolicy,
3784 0 : )
3785 0 : .await;
3786 :
3787 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3788 :
3789 0 : failpoint_support::sleep_millis_async!("tenant-update-policy-exclusive-lock");
3790 :
3791 : let TenantPolicyRequest {
3792 0 : placement,
3793 0 : mut scheduling,
3794 0 : } = req;
3795 :
3796 0 : if let Some(PlacementPolicy::Detached | PlacementPolicy::Secondary) = placement {
3797 : // When someone configures a tenant to detach, we force the scheduling policy to enable
3798 : // this to take effect.
3799 0 : if scheduling.is_none() {
3800 0 : scheduling = Some(ShardSchedulingPolicy::Active);
3801 0 : }
3802 0 : }
3803 :
3804 0 : self.persistence
3805 0 : .update_tenant_shard(
3806 0 : TenantFilter::Tenant(tenant_id),
3807 0 : placement.clone(),
3808 0 : None,
3809 0 : None,
3810 0 : scheduling,
3811 0 : )
3812 0 : .await?;
3813 :
3814 0 : let mut schedule_context = ScheduleContext::default();
3815 0 : let mut locked = self.inner.write().unwrap();
3816 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3817 0 : for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3818 0 : if let Some(placement) = &placement {
3819 0 : shard.policy = placement.clone();
3820 :
3821 0 : tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
3822 0 : "Updated placement policy to {placement:?}");
3823 0 : }
3824 :
3825 0 : if let Some(scheduling) = &scheduling {
3826 0 : shard.set_scheduling_policy(*scheduling);
3827 :
3828 0 : tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
3829 0 : "Updated scheduling policy to {scheduling:?}");
3830 0 : }
3831 :
3832 : // In case scheduling is being switched back on, try it now.
3833 0 : shard.schedule(scheduler, &mut schedule_context).ok();
3834 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
3835 : }
3836 :
3837 0 : Ok(())
3838 0 : }
3839 :
3840 0 : pub(crate) async fn tenant_timeline_create_pageservers(
3841 0 : &self,
3842 0 : tenant_id: TenantId,
3843 0 : mut create_req: TimelineCreateRequest,
3844 0 : ) -> Result<TimelineInfo, ApiError> {
3845 0 : tracing::info!(
3846 0 : "Creating timeline {}/{}",
3847 : tenant_id,
3848 : create_req.new_timeline_id,
3849 : );
3850 :
3851 0 : self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
3852 0 : if targets.0.is_empty() {
3853 0 : return Err(ApiError::NotFound(
3854 0 : anyhow::anyhow!("Tenant not found").into(),
3855 0 : ));
3856 0 : };
3857 :
3858 0 : let (shard_zero_tid, shard_zero_locations) =
3859 0 : targets.0.pop_first().expect("Must have at least one shard");
3860 0 : assert!(shard_zero_tid.is_shard_zero());
3861 :
3862 0 : async fn create_one(
3863 0 : tenant_shard_id: TenantShardId,
3864 0 : locations: ShardMutationLocations,
3865 0 : http_client: reqwest::Client,
3866 0 : jwt: Option<String>,
3867 0 : mut create_req: TimelineCreateRequest,
3868 0 : ) -> Result<TimelineInfo, ApiError> {
3869 0 : let latest = locations.latest.node;
3870 :
3871 0 : tracing::info!(
3872 0 : "Creating timeline on shard {}/{}, attached to node {latest} in generation {:?}",
3873 : tenant_shard_id,
3874 : create_req.new_timeline_id,
3875 : locations.latest.generation
3876 : );
3877 :
3878 0 : let client =
3879 0 : PageserverClient::new(latest.get_id(), http_client.clone(), latest.base_url(), jwt.as_deref());
3880 :
3881 0 : let timeline_info = client
3882 0 : .timeline_create(tenant_shard_id, &create_req)
3883 0 : .await
3884 0 : .map_err(|e| passthrough_api_error(&latest, e))?;
3885 :
3886 : // If we are going to create the timeline on some stale locations for shard 0, then ask them to re-use
3887 : // the initdb generated by the latest location, rather than generating their own. This avoids racing uploads
3888 : // of initdb to S3 which might not be binary-identical if different pageservers have different postgres binaries.
3889 0 : if tenant_shard_id.is_shard_zero() {
3890 0 : if let models::TimelineCreateRequestMode::Bootstrap { existing_initdb_timeline_id, .. } = &mut create_req.mode {
3891 0 : *existing_initdb_timeline_id = Some(create_req.new_timeline_id);
3892 0 : }
3893 0 : }
3894 :
3895 : // We propagate timeline creations to all attached locations such that a compute
3896 : // for the new timeline is able to start regardless of the current state of the
3897 : // tenant shard reconciliation.
3898 0 : for location in locations.other {
3899 0 : tracing::info!(
3900 0 : "Creating timeline on shard {}/{}, stale attached to node {} in generation {:?}",
3901 : tenant_shard_id,
3902 : create_req.new_timeline_id,
3903 : location.node,
3904 : location.generation
3905 : );
3906 :
3907 0 : let client = PageserverClient::new(
3908 0 : location.node.get_id(),
3909 0 : http_client.clone(),
3910 0 : location.node.base_url(),
3911 0 : jwt.as_deref(),
3912 : );
3913 :
3914 0 : let res = client
3915 0 : .timeline_create(tenant_shard_id, &create_req)
3916 0 : .await;
3917 :
3918 0 : if let Err(e) = res {
3919 0 : match e {
3920 0 : mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _) => {
3921 0 : // Tenant might have been detached from the stale location,
3922 0 : // so ignore 404s.
3923 0 : },
3924 : _ => {
3925 0 : return Err(passthrough_api_error(&location.node, e));
3926 : }
3927 : }
3928 0 : }
3929 : }
3930 :
3931 0 : Ok(timeline_info)
3932 0 : }
3933 :
3934 : // Because the caller might not provide an explicit LSN, we must do the creation first on a single shard, and then
3935 : // use whatever LSN that shard picked when creating on subsequent shards. We arbitrarily use shard zero as the shard
3936 : // that will get the first creation request, and propagate the LSN to all the >0 shards.
3937 : //
3938 : // This also enables non-zero shards to use the initdb that shard 0 generated and uploaded to S3, rather than
3939 : // independently generating their own initdb. This guarantees that shards cannot end up with different initial
3940 : // states if e.g. they have different postgres binary versions.
3941 0 : let timeline_info = create_one(
3942 0 : shard_zero_tid,
3943 0 : shard_zero_locations,
3944 0 : self.http_client.clone(),
3945 0 : self.config.pageserver_jwt_token.clone(),
3946 0 : create_req.clone(),
3947 0 : )
3948 0 : .await?;
3949 :
3950 : // Update the create request for shards >= 0
3951 0 : match &mut create_req.mode {
3952 0 : models::TimelineCreateRequestMode::Branch { ancestor_start_lsn, .. } if ancestor_start_lsn.is_none() => {
3953 0 : // Propagate the LSN that shard zero picked, if caller didn't provide one
3954 0 : *ancestor_start_lsn = timeline_info.ancestor_lsn;
3955 0 : },
3956 0 : models::TimelineCreateRequestMode::Bootstrap { existing_initdb_timeline_id, .. } => {
3957 : // For shards >= 0, do not run initdb: use the one that shard 0 uploaded to S3
3958 0 : *existing_initdb_timeline_id = Some(create_req.new_timeline_id)
3959 : }
3960 0 : _ => {}
3961 : }
3962 :
3963 : // Create timeline on remaining shards with number >0
3964 0 : if !targets.0.is_empty() {
3965 : // If we had multiple shards, issue requests for the remainder now.
3966 0 : let jwt = &self.config.pageserver_jwt_token;
3967 0 : self.tenant_for_shards(
3968 0 : targets
3969 0 : .0
3970 0 : .iter()
3971 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
3972 0 : .collect(),
3973 0 : |tenant_shard_id: TenantShardId, _node: Node| {
3974 0 : let create_req = create_req.clone();
3975 0 : let mutation_locations = targets.0.remove(&tenant_shard_id).unwrap();
3976 0 : Box::pin(create_one(
3977 0 : tenant_shard_id,
3978 0 : mutation_locations,
3979 0 : self.http_client.clone(),
3980 0 : jwt.clone(),
3981 0 : create_req,
3982 0 : ))
3983 0 : },
3984 : )
3985 0 : .await?;
3986 0 : }
3987 :
3988 0 : Ok(timeline_info)
3989 0 : })
3990 0 : .await?
3991 0 : }
3992 :
3993 0 : pub(crate) async fn tenant_timeline_create(
3994 0 : self: &Arc<Self>,
3995 0 : tenant_id: TenantId,
3996 0 : create_req: TimelineCreateRequest,
3997 0 : ) -> Result<TimelineCreateResponseStorcon, ApiError> {
3998 0 : let safekeepers = self.config.timelines_onto_safekeepers;
3999 0 : let timeline_id = create_req.new_timeline_id;
4000 :
4001 0 : tracing::info!(
4002 0 : mode=%create_req.mode_tag(),
4003 : %safekeepers,
4004 0 : "Creating timeline {}/{}",
4005 : tenant_id,
4006 : timeline_id,
4007 : );
4008 :
4009 0 : let _tenant_lock = trace_shared_lock(
4010 0 : &self.tenant_op_locks,
4011 0 : tenant_id,
4012 0 : TenantOperations::TimelineCreate,
4013 0 : )
4014 0 : .await;
4015 0 : failpoint_support::sleep_millis_async!("tenant-create-timeline-shared-lock");
4016 0 : let is_import = create_req.is_import();
4017 0 : let read_only = matches!(
4018 0 : create_req.mode,
4019 : models::TimelineCreateRequestMode::Branch {
4020 : read_only: true,
4021 : ..
4022 : }
4023 : );
4024 :
4025 0 : if is_import {
4026 : // Ensure that there is no split on-going.
4027 : // [`Self::tenant_shard_split`] holds the exclusive tenant lock
4028 : // for the duration of the split, but here we handle the case
4029 : // where we restarted and the split is being aborted.
4030 0 : let locked = self.inner.read().unwrap();
4031 0 : let splitting = locked
4032 0 : .tenants
4033 0 : .range(TenantShardId::tenant_range(tenant_id))
4034 0 : .any(|(_id, shard)| shard.splitting != SplitState::Idle);
4035 :
4036 0 : if splitting {
4037 0 : return Err(ApiError::Conflict("Tenant is splitting shard".to_string()));
4038 0 : }
4039 0 : }
4040 :
4041 0 : let timeline_info = self
4042 0 : .tenant_timeline_create_pageservers(tenant_id, create_req)
4043 0 : .await?;
4044 :
4045 0 : let selected_safekeepers = if is_import {
4046 0 : let shards = {
4047 0 : let locked = self.inner.read().unwrap();
4048 0 : locked
4049 0 : .tenants
4050 0 : .range(TenantShardId::tenant_range(tenant_id))
4051 0 : .map(|(ts_id, _)| ts_id.to_index())
4052 0 : .collect::<Vec<_>>()
4053 : };
4054 :
4055 0 : if !shards
4056 0 : .iter()
4057 0 : .map(|shard_index| shard_index.shard_count)
4058 0 : .all_equal()
4059 : {
4060 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
4061 0 : "Inconsistent shard count"
4062 0 : )));
4063 0 : }
4064 :
4065 0 : let import = TimelineImport {
4066 0 : tenant_id,
4067 0 : timeline_id,
4068 0 : shard_statuses: ShardImportStatuses::new(shards),
4069 0 : };
4070 :
4071 0 : let inserted = self
4072 0 : .persistence
4073 0 : .insert_timeline_import(import.to_persistent())
4074 0 : .await
4075 0 : .context("timeline import insert")
4076 0 : .map_err(ApiError::InternalServerError)?;
4077 :
4078 : // Set the importing flag on the tenant shards
4079 0 : self.inner
4080 0 : .write()
4081 0 : .unwrap()
4082 0 : .tenants
4083 0 : .range_mut(TenantShardId::tenant_range(tenant_id))
4084 0 : .for_each(|(_id, shard)| shard.importing = TimelineImportState::Importing);
4085 :
4086 0 : match inserted {
4087 : true => {
4088 0 : tracing::info!(%tenant_id, %timeline_id, "Inserted timeline import");
4089 : }
4090 : false => {
4091 0 : tracing::info!(%tenant_id, %timeline_id, "Timeline import entry already present");
4092 : }
4093 : }
4094 :
4095 0 : None
4096 0 : } else if safekeepers || read_only {
4097 : // Note that for imported timelines, we do not create the timeline on the safekeepers
4098 : // straight away. Instead, we do it once the import finalized such that we know what
4099 : // start LSN to provide for the safekeepers. This is done in
4100 : // [`Self::finalize_timeline_import`].
4101 0 : let res = self
4102 0 : .tenant_timeline_create_safekeepers(tenant_id, &timeline_info, read_only)
4103 0 : .instrument(tracing::info_span!("timeline_create_safekeepers", %tenant_id, timeline_id=%timeline_info.timeline_id))
4104 0 : .await?;
4105 0 : Some(res)
4106 : } else {
4107 0 : None
4108 : };
4109 :
4110 0 : Ok(TimelineCreateResponseStorcon {
4111 0 : timeline_info,
4112 0 : safekeepers: selected_safekeepers,
4113 0 : })
4114 0 : }
4115 :
4116 : #[instrument(skip_all, fields(
4117 : tenant_id=%req.tenant_shard_id.tenant_id,
4118 : shard_id=%req.tenant_shard_id.shard_slug(),
4119 : timeline_id=%req.timeline_id,
4120 : ))]
4121 : pub(crate) async fn handle_timeline_shard_import_progress(
4122 : self: &Arc<Self>,
4123 : req: TimelineImportStatusRequest,
4124 : ) -> Result<ShardImportStatus, ApiError> {
4125 : let validity = self
4126 : .validate_shard_generation(req.tenant_shard_id, req.generation)
4127 : .await?;
4128 : match validity {
4129 : ShardGenerationValidity::Valid => {
4130 : // fallthrough
4131 : }
4132 : ShardGenerationValidity::Mismatched { claimed, actual } => {
4133 : tracing::info!(
4134 : claimed=?claimed.into(),
4135 0 : actual=?actual.and_then(|g| g.into()),
4136 : "Rejecting import progress fetch from stale generation"
4137 : );
4138 :
4139 : return Err(ApiError::BadRequest(anyhow::anyhow!("Invalid generation")));
4140 : }
4141 : }
4142 :
4143 : let maybe_import = self
4144 : .persistence
4145 : .get_timeline_import(req.tenant_shard_id.tenant_id, req.timeline_id)
4146 : .await?;
4147 :
4148 0 : let import = maybe_import.ok_or_else(|| {
4149 0 : ApiError::NotFound(
4150 0 : format!(
4151 0 : "import for {}/{} not found",
4152 0 : req.tenant_shard_id.tenant_id, req.timeline_id
4153 0 : )
4154 0 : .into(),
4155 0 : )
4156 0 : })?;
4157 :
4158 : import
4159 : .shard_statuses
4160 : .0
4161 : .get(&req.tenant_shard_id.to_index())
4162 : .cloned()
4163 0 : .ok_or_else(|| {
4164 0 : ApiError::NotFound(
4165 0 : format!("shard {} not found", req.tenant_shard_id.shard_slug()).into(),
4166 0 : )
4167 0 : })
4168 : }
4169 :
4170 : #[instrument(skip_all, fields(
4171 : tenant_id=%req.tenant_shard_id.tenant_id,
4172 : shard_id=%req.tenant_shard_id.shard_slug(),
4173 : timeline_id=%req.timeline_id,
4174 : ))]
4175 : pub(crate) async fn handle_timeline_shard_import_progress_upcall(
4176 : self: &Arc<Self>,
4177 : req: PutTimelineImportStatusRequest,
4178 : ) -> Result<(), ApiError> {
4179 : let validity = self
4180 : .validate_shard_generation(req.tenant_shard_id, req.generation)
4181 : .await?;
4182 : match validity {
4183 : ShardGenerationValidity::Valid => {
4184 : // fallthrough
4185 : }
4186 : ShardGenerationValidity::Mismatched { claimed, actual } => {
4187 : tracing::info!(
4188 : claimed=?claimed.into(),
4189 0 : actual=?actual.and_then(|g| g.into()),
4190 : "Rejecting import progress update from stale generation"
4191 : );
4192 :
4193 : return Err(ApiError::PreconditionFailed("Invalid generation".into()));
4194 : }
4195 : }
4196 :
4197 : let res = self
4198 : .persistence
4199 : .update_timeline_import(req.tenant_shard_id, req.timeline_id, req.status)
4200 : .await;
4201 : let timeline_import = match res {
4202 : Ok(Ok(Some(timeline_import))) => timeline_import,
4203 : Ok(Ok(None)) => {
4204 : // Idempotency: we've already seen and handled this update.
4205 : return Ok(());
4206 : }
4207 : Ok(Err(logical_err)) => {
4208 : return Err(logical_err.into());
4209 : }
4210 : Err(db_err) => {
4211 : return Err(db_err.into());
4212 : }
4213 : };
4214 :
4215 : tracing::info!(
4216 : tenant_id=%req.tenant_shard_id.tenant_id,
4217 : timeline_id=%req.timeline_id,
4218 : shard_id=%req.tenant_shard_id.shard_slug(),
4219 : "Updated timeline import status to: {timeline_import:?}");
4220 :
4221 : if timeline_import.is_complete() {
4222 : tokio::task::spawn({
4223 : let this = self.clone();
4224 0 : async move { this.finalize_timeline_import(timeline_import).await }
4225 : });
4226 : }
4227 :
4228 : Ok(())
4229 : }
4230 :
4231 : /// Check that a provided generation for some tenant shard is the most recent one.
4232 : ///
4233 : /// Validate with the in-mem state first, and, if that passes, validate with the
4234 : /// database state which is authoritative.
4235 0 : async fn validate_shard_generation(
4236 0 : self: &Arc<Self>,
4237 0 : tenant_shard_id: TenantShardId,
4238 0 : generation: Generation,
4239 0 : ) -> Result<ShardGenerationValidity, ApiError> {
4240 : {
4241 0 : let locked = self.inner.read().unwrap();
4242 0 : let tenant_shard =
4243 0 : locked
4244 0 : .tenants
4245 0 : .get(&tenant_shard_id)
4246 0 : .ok_or(ApiError::InternalServerError(anyhow::anyhow!(
4247 0 : "{} shard not found",
4248 0 : tenant_shard_id
4249 0 : )))?;
4250 :
4251 0 : if tenant_shard.generation != Some(generation) {
4252 0 : return Ok(ShardGenerationValidity::Mismatched {
4253 0 : claimed: generation,
4254 0 : actual: tenant_shard.generation,
4255 0 : });
4256 0 : }
4257 : }
4258 :
4259 0 : let mut db_generations = self
4260 0 : .persistence
4261 0 : .shard_generations(std::iter::once(&tenant_shard_id))
4262 0 : .await?;
4263 0 : let (_tid, db_generation) =
4264 0 : db_generations
4265 0 : .pop()
4266 0 : .ok_or(ApiError::InternalServerError(anyhow::anyhow!(
4267 0 : "{} shard not found",
4268 0 : tenant_shard_id
4269 0 : )))?;
4270 :
4271 0 : if db_generation != Some(generation) {
4272 0 : return Ok(ShardGenerationValidity::Mismatched {
4273 0 : claimed: generation,
4274 0 : actual: db_generation,
4275 0 : });
4276 0 : }
4277 :
4278 0 : Ok(ShardGenerationValidity::Valid)
4279 0 : }
4280 :
4281 : /// Finalize the import of a timeline
4282 : ///
4283 : /// This method should be called once all shards have reported that the import is complete.
4284 : /// Firstly, it polls the post import timeline activation endpoint exposed by the pageserver.
4285 : /// Once the timeline is active on all shards, the timeline also gets created on the
4286 : /// safekeepers. Finally, notify cplane of the import completion (whether failed or
4287 : /// successful), and remove the import from the database and in-memory.
4288 : ///
4289 : /// If this method gets pre-empted by shut down, it will be called again at start-up (on-going
4290 : /// imports are stored in the database).
4291 : ///
4292 : /// # Cancel-Safety
4293 : /// Not cancel safe.
4294 : /// If the caller stops polling, the import will not be removed from
4295 : /// [`ServiceState::imports_finalizing`].
4296 : #[instrument(skip_all, fields(
4297 : tenant_id=%import.tenant_id,
4298 : timeline_id=%import.timeline_id,
4299 : ))]
4300 :
4301 : async fn finalize_timeline_import(
4302 : self: &Arc<Self>,
4303 : import: TimelineImport,
4304 : ) -> Result<(), TimelineImportFinalizeError> {
4305 : let tenant_timeline = (import.tenant_id, import.timeline_id);
4306 :
4307 : let (_finalize_import_guard, cancel) = {
4308 : let mut locked = self.inner.write().unwrap();
4309 : let gate = Gate::default();
4310 : let cancel = CancellationToken::default();
4311 :
4312 : let guard = gate.enter().unwrap();
4313 :
4314 : locked.imports_finalizing.insert(
4315 : tenant_timeline,
4316 : FinalizingImport {
4317 : gate,
4318 : cancel: cancel.clone(),
4319 : },
4320 : );
4321 :
4322 : (guard, cancel)
4323 : };
4324 :
4325 : let res = tokio::select! {
4326 : res = self.finalize_timeline_import_impl(import) => {
4327 : res
4328 : },
4329 : _ = cancel.cancelled() => {
4330 : Err(TimelineImportFinalizeError::Cancelled)
4331 : }
4332 : };
4333 :
4334 : let mut locked = self.inner.write().unwrap();
4335 : locked.imports_finalizing.remove(&tenant_timeline);
4336 :
4337 : res
4338 : }
4339 :
4340 0 : async fn finalize_timeline_import_impl(
4341 0 : self: &Arc<Self>,
4342 0 : import: TimelineImport,
4343 0 : ) -> Result<(), TimelineImportFinalizeError> {
4344 0 : tracing::info!("Finalizing timeline import");
4345 :
4346 0 : pausable_failpoint!("timeline-import-pre-cplane-notification");
4347 :
4348 0 : let tenant_id = import.tenant_id;
4349 0 : let timeline_id = import.timeline_id;
4350 :
4351 0 : let import_error = import.completion_error();
4352 0 : match import_error {
4353 0 : Some(err) => {
4354 0 : self.notify_cplane_and_delete_import(tenant_id, timeline_id, Err(err))
4355 0 : .await?;
4356 0 : tracing::warn!("Timeline import completed with shard errors");
4357 0 : Ok(())
4358 : }
4359 0 : None => match self.activate_timeline_post_import(&import).await {
4360 0 : Ok(timeline_info) => {
4361 0 : tracing::info!("Post import timeline activation complete");
4362 :
4363 0 : if self.config.timelines_onto_safekeepers {
4364 : // Now that we know the start LSN of this timeline, create it on the
4365 : // safekeepers.
4366 0 : self.tenant_timeline_create_safekeepers_until_success(
4367 0 : import.tenant_id,
4368 0 : timeline_info,
4369 0 : )
4370 0 : .await?;
4371 0 : }
4372 :
4373 0 : self.notify_cplane_and_delete_import(tenant_id, timeline_id, Ok(()))
4374 0 : .await?;
4375 :
4376 0 : tracing::info!("Timeline import completed successfully");
4377 0 : Ok(())
4378 : }
4379 : Err(TimelineImportFinalizeError::ShuttingDown) => {
4380 : // We got pre-empted by shut down and will resume after the restart.
4381 0 : Err(TimelineImportFinalizeError::ShuttingDown)
4382 : }
4383 0 : Err(err) => {
4384 : // Any finalize error apart from shut down is permanent and requires us to notify
4385 : // cplane such that it can clean up.
4386 0 : tracing::error!("Import finalize failed with permanent error: {err}");
4387 0 : self.notify_cplane_and_delete_import(
4388 0 : tenant_id,
4389 0 : timeline_id,
4390 0 : Err(err.to_string()),
4391 0 : )
4392 0 : .await?;
4393 0 : Err(err)
4394 : }
4395 : },
4396 : }
4397 0 : }
4398 :
4399 0 : async fn notify_cplane_and_delete_import(
4400 0 : self: &Arc<Self>,
4401 0 : tenant_id: TenantId,
4402 0 : timeline_id: TimelineId,
4403 0 : import_result: ImportResult,
4404 0 : ) -> Result<(), TimelineImportFinalizeError> {
4405 0 : let import_failed = import_result.is_err();
4406 0 : tracing::info!(%import_failed, "Notifying cplane of import completion");
4407 :
4408 0 : let client = UpcallClient::new(self.get_config(), self.cancel.child_token());
4409 0 : client
4410 0 : .notify_import_complete(tenant_id, timeline_id, import_result)
4411 0 : .await
4412 0 : .map_err(|_err| TimelineImportFinalizeError::ShuttingDown)?;
4413 :
4414 0 : if let Err(err) = self
4415 0 : .persistence
4416 0 : .delete_timeline_import(tenant_id, timeline_id)
4417 0 : .await
4418 : {
4419 0 : tracing::warn!("Failed to delete timeline import entry from database: {err}");
4420 0 : }
4421 :
4422 0 : self.inner
4423 0 : .write()
4424 0 : .unwrap()
4425 0 : .tenants
4426 0 : .range_mut(TenantShardId::tenant_range(tenant_id))
4427 0 : .for_each(|(_id, shard)| shard.importing = TimelineImportState::Idle);
4428 :
4429 0 : Ok(())
4430 0 : }
4431 :
4432 : /// Activate an imported timeline on all shards once the import is complete.
4433 : /// Returns the [`TimelineInfo`] reported by shard zero.
4434 0 : async fn activate_timeline_post_import(
4435 0 : self: &Arc<Self>,
4436 0 : import: &TimelineImport,
4437 0 : ) -> Result<TimelineInfo, TimelineImportFinalizeError> {
4438 : const TIMELINE_ACTIVATE_TIMEOUT: Duration = Duration::from_millis(128);
4439 :
4440 0 : let mut shards_to_activate: HashSet<ShardIndex> =
4441 0 : import.shard_statuses.0.keys().cloned().collect();
4442 0 : let mut shard_zero_timeline_info = None;
4443 :
4444 0 : while !shards_to_activate.is_empty() {
4445 0 : if self.cancel.is_cancelled() {
4446 0 : return Err(TimelineImportFinalizeError::ShuttingDown);
4447 0 : }
4448 :
4449 0 : let targets = {
4450 0 : let locked = self.inner.read().unwrap();
4451 0 : let mut targets = Vec::new();
4452 :
4453 0 : for (tenant_shard_id, shard) in locked
4454 0 : .tenants
4455 0 : .range(TenantShardId::tenant_range(import.tenant_id))
4456 : {
4457 0 : if !import
4458 0 : .shard_statuses
4459 0 : .0
4460 0 : .contains_key(&tenant_shard_id.to_index())
4461 : {
4462 0 : return Err(TimelineImportFinalizeError::MismatchedShards(
4463 0 : tenant_shard_id.to_index(),
4464 0 : ));
4465 0 : }
4466 :
4467 0 : if let Some(node_id) = shard.intent.get_attached() {
4468 0 : let node = locked
4469 0 : .nodes
4470 0 : .get(node_id)
4471 0 : .expect("Pageservers may not be deleted while referenced");
4472 0 : targets.push((*tenant_shard_id, node.clone()));
4473 0 : }
4474 : }
4475 :
4476 0 : targets
4477 : };
4478 :
4479 0 : let targeted_tenant_shards: Vec<_> = targets.iter().map(|(tid, _node)| *tid).collect();
4480 :
4481 0 : let results = self
4482 0 : .tenant_for_shards_api(
4483 0 : targets,
4484 0 : |tenant_shard_id, client| async move {
4485 0 : client
4486 0 : .activate_post_import(
4487 0 : tenant_shard_id,
4488 0 : import.timeline_id,
4489 0 : TIMELINE_ACTIVATE_TIMEOUT,
4490 0 : )
4491 0 : .await
4492 0 : },
4493 : 1,
4494 : 1,
4495 : SHORT_RECONCILE_TIMEOUT,
4496 0 : &self.cancel,
4497 : )
4498 0 : .await;
4499 :
4500 0 : let mut failed = 0;
4501 0 : for (tid, (_, result)) in targeted_tenant_shards.iter().zip(results.into_iter()) {
4502 0 : match result {
4503 0 : Ok(ok) => {
4504 0 : if tid.is_shard_zero() {
4505 0 : shard_zero_timeline_info = Some(ok);
4506 0 : }
4507 :
4508 0 : shards_to_activate.remove(&tid.to_index());
4509 : }
4510 0 : Err(_err) => {
4511 0 : failed += 1;
4512 0 : }
4513 : }
4514 : }
4515 :
4516 0 : if failed > 0 {
4517 0 : tracing::info!(
4518 0 : "Failed to activate timeline on {failed} shards post import. Will retry"
4519 : );
4520 0 : }
4521 :
4522 0 : tokio::select! {
4523 0 : _ = tokio::time::sleep(Duration::from_millis(250)) => {},
4524 0 : _ = self.cancel.cancelled() => {
4525 0 : return Err(TimelineImportFinalizeError::ShuttingDown);
4526 : }
4527 : }
4528 : }
4529 :
4530 0 : Ok(shard_zero_timeline_info.expect("All shards replied"))
4531 0 : }
4532 :
4533 0 : async fn finalize_timeline_imports(self: &Arc<Self>, imports: Vec<TimelineImport>) {
4534 0 : futures::future::join_all(
4535 0 : imports
4536 0 : .into_iter()
4537 0 : .map(|import| self.finalize_timeline_import(import)),
4538 : )
4539 0 : .await;
4540 0 : }
4541 :
4542 : /// Delete a timeline import if it exists
4543 : ///
4544 : /// Firstly, delete the entry from the database. Any updates
4545 : /// from pageservers after the update will fail with a 404, so the
4546 : /// import cannot progress into finalizing state if it's not there already.
4547 : /// Secondly, cancel the finalization if one is in progress.
4548 0 : pub(crate) async fn maybe_delete_timeline_import(
4549 0 : self: &Arc<Self>,
4550 0 : tenant_id: TenantId,
4551 0 : timeline_id: TimelineId,
4552 0 : ) -> Result<(), DatabaseError> {
4553 0 : let tenant_has_ongoing_import = {
4554 0 : let locked = self.inner.read().unwrap();
4555 0 : locked
4556 0 : .tenants
4557 0 : .range(TenantShardId::tenant_range(tenant_id))
4558 0 : .any(|(_tid, shard)| shard.importing == TimelineImportState::Importing)
4559 : };
4560 :
4561 0 : if !tenant_has_ongoing_import {
4562 0 : return Ok(());
4563 0 : }
4564 :
4565 0 : self.persistence
4566 0 : .delete_timeline_import(tenant_id, timeline_id)
4567 0 : .await?;
4568 :
4569 0 : let maybe_finalizing = {
4570 0 : let mut locked = self.inner.write().unwrap();
4571 0 : locked.imports_finalizing.remove(&(tenant_id, timeline_id))
4572 : };
4573 :
4574 0 : if let Some(finalizing) = maybe_finalizing {
4575 0 : finalizing.cancel.cancel();
4576 0 : finalizing.gate.close().await;
4577 0 : }
4578 :
4579 0 : Ok(())
4580 0 : }
4581 :
4582 0 : pub(crate) async fn tenant_timeline_archival_config(
4583 0 : &self,
4584 0 : tenant_id: TenantId,
4585 0 : timeline_id: TimelineId,
4586 0 : req: TimelineArchivalConfigRequest,
4587 0 : ) -> Result<(), ApiError> {
4588 0 : tracing::info!(
4589 0 : "Setting archival config of timeline {tenant_id}/{timeline_id} to '{:?}'",
4590 : req.state
4591 : );
4592 :
4593 0 : let _tenant_lock = trace_shared_lock(
4594 0 : &self.tenant_op_locks,
4595 0 : tenant_id,
4596 0 : TenantOperations::TimelineArchivalConfig,
4597 0 : )
4598 0 : .await;
4599 :
4600 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
4601 0 : if targets.0.is_empty() {
4602 0 : return Err(ApiError::NotFound(
4603 0 : anyhow::anyhow!("Tenant not found").into(),
4604 0 : ));
4605 0 : }
4606 0 : async fn config_one(
4607 0 : tenant_shard_id: TenantShardId,
4608 0 : timeline_id: TimelineId,
4609 0 : node: Node,
4610 0 : http_client: reqwest::Client,
4611 0 : jwt: Option<String>,
4612 0 : req: TimelineArchivalConfigRequest,
4613 0 : ) -> Result<(), ApiError> {
4614 0 : tracing::info!(
4615 0 : "Setting archival config of timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
4616 : );
4617 :
4618 0 : let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
4619 :
4620 0 : client
4621 0 : .timeline_archival_config(tenant_shard_id, timeline_id, &req)
4622 0 : .await
4623 0 : .map_err(|e| match e {
4624 0 : mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg) => {
4625 0 : ApiError::PreconditionFailed(msg.into_boxed_str())
4626 : }
4627 0 : _ => passthrough_api_error(&node, e),
4628 0 : })
4629 0 : }
4630 :
4631 : // no shard needs to go first/last; the operation should be idempotent
4632 : // TODO: it would be great to ensure that all shards return the same error
4633 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
4634 0 : let results = self
4635 0 : .tenant_for_shards(locations, |tenant_shard_id, node| {
4636 0 : futures::FutureExt::boxed(config_one(
4637 0 : tenant_shard_id,
4638 0 : timeline_id,
4639 0 : node,
4640 0 : self.http_client.clone(),
4641 0 : self.config.pageserver_jwt_token.clone(),
4642 0 : req.clone(),
4643 0 : ))
4644 0 : })
4645 0 : .await?;
4646 0 : assert!(!results.is_empty(), "must have at least one result");
4647 :
4648 0 : Ok(())
4649 0 : }).await?
4650 0 : }
4651 :
4652 0 : pub(crate) async fn tenant_timeline_detach_ancestor(
4653 0 : &self,
4654 0 : tenant_id: TenantId,
4655 0 : timeline_id: TimelineId,
4656 0 : behavior: Option<DetachBehavior>,
4657 0 : ) -> Result<models::detach_ancestor::AncestorDetached, ApiError> {
4658 0 : tracing::info!("Detaching timeline {tenant_id}/{timeline_id}",);
4659 :
4660 0 : let _tenant_lock = trace_shared_lock(
4661 0 : &self.tenant_op_locks,
4662 0 : tenant_id,
4663 0 : TenantOperations::TimelineDetachAncestor,
4664 0 : )
4665 0 : .await;
4666 :
4667 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
4668 0 : if targets.0.is_empty() {
4669 0 : return Err(ApiError::NotFound(
4670 0 : anyhow::anyhow!("Tenant not found").into(),
4671 0 : ));
4672 0 : }
4673 :
4674 0 : async fn detach_one(
4675 0 : tenant_shard_id: TenantShardId,
4676 0 : timeline_id: TimelineId,
4677 0 : node: Node,
4678 0 : http_client: reqwest::Client,
4679 0 : jwt: Option<String>,
4680 0 : behavior: Option<DetachBehavior>,
4681 0 : ) -> Result<(ShardNumber, models::detach_ancestor::AncestorDetached), ApiError> {
4682 0 : tracing::info!(
4683 0 : "Detaching timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
4684 : );
4685 :
4686 0 : let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
4687 :
4688 0 : client
4689 0 : .timeline_detach_ancestor(tenant_shard_id, timeline_id, behavior)
4690 0 : .await
4691 0 : .map_err(|e| {
4692 : use mgmt_api::Error;
4693 :
4694 0 : match e {
4695 : // no ancestor (ever)
4696 0 : Error::ApiError(StatusCode::CONFLICT, msg) => ApiError::Conflict(format!(
4697 0 : "{node}: {}",
4698 0 : msg.strip_prefix("Conflict: ").unwrap_or(&msg)
4699 0 : )),
4700 : // too many ancestors
4701 0 : Error::ApiError(StatusCode::BAD_REQUEST, msg) => {
4702 0 : ApiError::BadRequest(anyhow::anyhow!("{node}: {msg}"))
4703 : }
4704 0 : Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, msg) => {
4705 : // avoid turning these into conflicts to remain compatible with
4706 : // pageservers, 500 errors are sadly retryable with timeline ancestor
4707 : // detach
4708 0 : ApiError::InternalServerError(anyhow::anyhow!("{node}: {msg}"))
4709 : }
4710 : // rest can be mapped as usual
4711 0 : other => passthrough_api_error(&node, other),
4712 : }
4713 0 : })
4714 0 : .map(|res| (tenant_shard_id.shard_number, res))
4715 0 : }
4716 :
4717 : // no shard needs to go first/last; the operation should be idempotent
4718 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
4719 0 : let mut results = self
4720 0 : .tenant_for_shards(locations, |tenant_shard_id, node| {
4721 0 : futures::FutureExt::boxed(detach_one(
4722 0 : tenant_shard_id,
4723 0 : timeline_id,
4724 0 : node,
4725 0 : self.http_client.clone(),
4726 0 : self.config.pageserver_jwt_token.clone(),
4727 0 : behavior,
4728 0 : ))
4729 0 : })
4730 0 : .await?;
4731 :
4732 0 : let any = results.pop().expect("we must have at least one response");
4733 :
4734 0 : let mismatching = results
4735 0 : .iter()
4736 0 : .filter(|(_, res)| res != &any.1)
4737 0 : .collect::<Vec<_>>();
4738 0 : if !mismatching.is_empty() {
4739 : // this can be hit by races which should not happen because operation lock on cplane
4740 0 : let matching = results.len() - mismatching.len();
4741 0 : tracing::error!(
4742 : matching,
4743 : compared_against=?any,
4744 : ?mismatching,
4745 0 : "shards returned different results"
4746 : );
4747 :
4748 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!("pageservers returned mixed results for ancestor detach; manual intervention is required.")));
4749 0 : }
4750 :
4751 0 : Ok(any.1)
4752 0 : }).await?
4753 0 : }
4754 :
4755 0 : pub(crate) async fn tenant_timeline_block_unblock_gc(
4756 0 : &self,
4757 0 : tenant_id: TenantId,
4758 0 : timeline_id: TimelineId,
4759 0 : dir: BlockUnblock,
4760 0 : ) -> Result<(), ApiError> {
4761 0 : let _tenant_lock = trace_shared_lock(
4762 0 : &self.tenant_op_locks,
4763 0 : tenant_id,
4764 0 : TenantOperations::TimelineGcBlockUnblock,
4765 0 : )
4766 0 : .await;
4767 :
4768 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
4769 0 : if targets.0.is_empty() {
4770 0 : return Err(ApiError::NotFound(
4771 0 : anyhow::anyhow!("Tenant not found").into(),
4772 0 : ));
4773 0 : }
4774 :
4775 0 : async fn do_one(
4776 0 : tenant_shard_id: TenantShardId,
4777 0 : timeline_id: TimelineId,
4778 0 : node: Node,
4779 0 : http_client: reqwest::Client,
4780 0 : jwt: Option<String>,
4781 0 : dir: BlockUnblock,
4782 0 : ) -> Result<(), ApiError> {
4783 0 : let client = PageserverClient::new(
4784 0 : node.get_id(),
4785 0 : http_client,
4786 0 : node.base_url(),
4787 0 : jwt.as_deref(),
4788 : );
4789 :
4790 0 : client
4791 0 : .timeline_block_unblock_gc(tenant_shard_id, timeline_id, dir)
4792 0 : .await
4793 0 : .map_err(|e| passthrough_api_error(&node, e))
4794 0 : }
4795 :
4796 : // no shard needs to go first/last; the operation should be idempotent
4797 0 : let locations = targets
4798 0 : .0
4799 0 : .iter()
4800 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
4801 0 : .collect();
4802 0 : self.tenant_for_shards(locations, |tenant_shard_id, node| {
4803 0 : futures::FutureExt::boxed(do_one(
4804 0 : tenant_shard_id,
4805 0 : timeline_id,
4806 0 : node,
4807 0 : self.http_client.clone(),
4808 0 : self.config.pageserver_jwt_token.clone(),
4809 0 : dir,
4810 0 : ))
4811 0 : })
4812 0 : .await
4813 0 : })
4814 0 : .await??;
4815 0 : Ok(())
4816 0 : }
4817 :
4818 0 : pub(crate) fn is_tenant_not_found_error(body: &str, tenant_id: TenantId) -> bool {
4819 0 : body.contains(&format!("tenant {tenant_id}"))
4820 0 : }
4821 :
4822 0 : fn process_result_and_passthrough_errors<T>(
4823 0 : &self,
4824 0 : tenant_id: TenantId,
4825 0 : results: Vec<(Node, Result<T, mgmt_api::Error>)>,
4826 0 : ) -> Result<Vec<(Node, T)>, ApiError> {
4827 0 : let mut processed_results: Vec<(Node, T)> = Vec::with_capacity(results.len());
4828 0 : for (node, res) in results {
4829 0 : match res {
4830 0 : Ok(res) => processed_results.push((node, res)),
4831 0 : Err(mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, body))
4832 0 : if Self::is_tenant_not_found_error(&body, tenant_id) =>
4833 : {
4834 : // If there's a tenant not found, we are still in the process of attaching the tenant.
4835 : // Return 503 so that the client can retry.
4836 0 : return Err(ApiError::ResourceUnavailable(
4837 0 : format!(
4838 0 : "Timeline is not attached to the pageserver {} yet, please retry",
4839 0 : node.get_id()
4840 0 : )
4841 0 : .into(),
4842 0 : ));
4843 : }
4844 0 : Err(e) => return Err(passthrough_api_error(&node, e)),
4845 : }
4846 : }
4847 0 : Ok(processed_results)
4848 0 : }
4849 :
4850 0 : pub(crate) async fn tenant_timeline_lsn_lease(
4851 0 : &self,
4852 0 : tenant_id: TenantId,
4853 0 : timeline_id: TimelineId,
4854 0 : lsn: Lsn,
4855 0 : ) -> Result<LsnLease, ApiError> {
4856 0 : let _tenant_lock = trace_shared_lock(
4857 0 : &self.tenant_op_locks,
4858 0 : tenant_id,
4859 0 : TenantOperations::TimelineLsnLease,
4860 0 : )
4861 0 : .await;
4862 :
4863 0 : self.tenant_remote_mutation(tenant_id, |locations| async move {
4864 0 : if locations.0.is_empty() {
4865 0 : return Err(ApiError::NotFound(
4866 0 : anyhow::anyhow!("Tenant not found").into(),
4867 0 : ));
4868 0 : }
4869 :
4870 0 : let results = self
4871 0 : .tenant_for_shards_api(
4872 0 : locations
4873 0 : .0
4874 0 : .iter()
4875 0 : .map(|(tenant_shard_id, ShardMutationLocations { latest, .. })| {
4876 0 : (*tenant_shard_id, latest.node.clone())
4877 0 : })
4878 0 : .collect(),
4879 0 : |tenant_shard_id, client| async move {
4880 0 : client
4881 0 : .timeline_lease_lsn(tenant_shard_id, timeline_id, lsn)
4882 0 : .await
4883 0 : },
4884 : 1,
4885 : 1,
4886 : SHORT_RECONCILE_TIMEOUT,
4887 0 : &self.cancel,
4888 : )
4889 0 : .await;
4890 :
4891 0 : let leases = self.process_result_and_passthrough_errors(tenant_id, results)?;
4892 0 : let mut valid_until = None;
4893 0 : for (_, lease) in leases {
4894 0 : if let Some(ref mut valid_until) = valid_until {
4895 0 : *valid_until = std::cmp::min(*valid_until, lease.valid_until);
4896 0 : } else {
4897 0 : valid_until = Some(lease.valid_until);
4898 0 : }
4899 : }
4900 0 : Ok(LsnLease {
4901 0 : valid_until: valid_until.unwrap_or_else(SystemTime::now),
4902 0 : })
4903 0 : })
4904 0 : .await?
4905 0 : }
4906 :
4907 0 : pub(crate) async fn tenant_timeline_download_heatmap_layers(
4908 0 : &self,
4909 0 : tenant_shard_id: TenantShardId,
4910 0 : timeline_id: TimelineId,
4911 0 : concurrency: Option<usize>,
4912 0 : recurse: bool,
4913 0 : ) -> Result<(), ApiError> {
4914 0 : let _tenant_lock = trace_shared_lock(
4915 0 : &self.tenant_op_locks,
4916 0 : tenant_shard_id.tenant_id,
4917 0 : TenantOperations::DownloadHeatmapLayers,
4918 0 : )
4919 0 : .await;
4920 :
4921 0 : let targets = {
4922 0 : let locked = self.inner.read().unwrap();
4923 0 : let mut targets = Vec::new();
4924 :
4925 : // If the request got an unsharded tenant id, then apply
4926 : // the operation to all shards. Otherwise, apply it to a specific shard.
4927 0 : let shards_range = if tenant_shard_id.is_unsharded() {
4928 0 : TenantShardId::tenant_range(tenant_shard_id.tenant_id)
4929 : } else {
4930 0 : tenant_shard_id.range()
4931 : };
4932 :
4933 0 : for (tenant_shard_id, shard) in locked.tenants.range(shards_range) {
4934 0 : if let Some(node_id) = shard.intent.get_attached() {
4935 0 : let node = locked
4936 0 : .nodes
4937 0 : .get(node_id)
4938 0 : .expect("Pageservers may not be deleted while referenced");
4939 0 :
4940 0 : targets.push((*tenant_shard_id, node.clone()));
4941 0 : }
4942 : }
4943 0 : targets
4944 : };
4945 :
4946 0 : self.tenant_for_shards_api(
4947 0 : targets,
4948 0 : |tenant_shard_id, client| async move {
4949 0 : client
4950 0 : .timeline_download_heatmap_layers(
4951 0 : tenant_shard_id,
4952 0 : timeline_id,
4953 0 : concurrency,
4954 0 : recurse,
4955 0 : )
4956 0 : .await
4957 0 : },
4958 : 1,
4959 : 1,
4960 : SHORT_RECONCILE_TIMEOUT,
4961 0 : &self.cancel,
4962 : )
4963 0 : .await;
4964 :
4965 0 : Ok(())
4966 0 : }
4967 :
4968 : /// Helper for concurrently calling a pageserver API on a number of shards, such as timeline creation.
4969 : ///
4970 : /// On success, the returned vector contains exactly the same number of elements as the input `locations`
4971 : /// and returned element at index `i` is the result for `req_fn(op(locations[i])`.
4972 0 : async fn tenant_for_shards<F, R>(
4973 0 : &self,
4974 0 : locations: Vec<(TenantShardId, Node)>,
4975 0 : mut req_fn: F,
4976 0 : ) -> Result<Vec<R>, ApiError>
4977 0 : where
4978 0 : F: FnMut(
4979 0 : TenantShardId,
4980 0 : Node,
4981 0 : )
4982 0 : -> std::pin::Pin<Box<dyn futures::Future<Output = Result<R, ApiError>> + Send>>,
4983 0 : {
4984 0 : let mut futs = FuturesUnordered::new();
4985 0 : let mut results = Vec::with_capacity(locations.len());
4986 :
4987 0 : for (idx, (tenant_shard_id, node)) in locations.into_iter().enumerate() {
4988 0 : let fut = req_fn(tenant_shard_id, node);
4989 0 : futs.push(async move { (idx, fut.await) });
4990 : }
4991 :
4992 0 : while let Some((idx, r)) = futs.next().await {
4993 0 : results.push((idx, r?));
4994 : }
4995 :
4996 0 : results.sort_by_key(|(idx, _)| *idx);
4997 0 : Ok(results.into_iter().map(|(_, r)| r).collect())
4998 0 : }
4999 :
5000 : /// Concurrently invoke a pageserver API call on many shards at once.
5001 : ///
5002 : /// The returned Vec has the same length as the `locations` Vec,
5003 : /// and returned element at index `i` is the result for `op(locations[i])`.
5004 0 : pub(crate) async fn tenant_for_shards_api<T, O, F>(
5005 0 : &self,
5006 0 : locations: Vec<(TenantShardId, Node)>,
5007 0 : op: O,
5008 0 : warn_threshold: u32,
5009 0 : max_retries: u32,
5010 0 : timeout: Duration,
5011 0 : cancel: &CancellationToken,
5012 0 : ) -> Vec<(Node, mgmt_api::Result<T>)>
5013 0 : where
5014 0 : O: Fn(TenantShardId, PageserverClient) -> F + Copy,
5015 0 : F: std::future::Future<Output = mgmt_api::Result<T>>,
5016 0 : {
5017 0 : let mut futs = FuturesUnordered::new();
5018 0 : let mut results = Vec::with_capacity(locations.len());
5019 :
5020 0 : for (idx, (tenant_shard_id, node)) in locations.into_iter().enumerate() {
5021 0 : futs.push(async move {
5022 0 : let r = node
5023 0 : .with_client_retries(
5024 0 : |client| op(tenant_shard_id, client),
5025 0 : &self.http_client,
5026 0 : &self.config.pageserver_jwt_token,
5027 0 : warn_threshold,
5028 0 : max_retries,
5029 0 : timeout,
5030 0 : cancel,
5031 : )
5032 0 : .await;
5033 0 : (idx, node, r)
5034 0 : });
5035 : }
5036 :
5037 0 : while let Some((idx, node, r)) = futs.next().await {
5038 0 : results.push((idx, node, r.unwrap_or(Err(mgmt_api::Error::Cancelled))));
5039 0 : }
5040 :
5041 0 : results.sort_by_key(|(idx, _, _)| *idx);
5042 0 : results.into_iter().map(|(_, node, r)| (node, r)).collect()
5043 0 : }
5044 :
5045 : /// Helper for safely working with the shards in a tenant remotely on pageservers, for example
5046 : /// when creating and deleting timelines:
5047 : /// - Makes sure shards are attached somewhere if they weren't already
5048 : /// - Looks up the shards and the nodes where they were most recently attached
5049 : /// - Guarantees that after the inner function returns, the shards' generations haven't moved on: this
5050 : /// ensures that the remote operation acted on the most recent generation, and is therefore durable.
5051 0 : pub(crate) async fn tenant_remote_mutation<R, O, F>(
5052 0 : &self,
5053 0 : tenant_id: TenantId,
5054 0 : op: O,
5055 0 : ) -> Result<R, ApiError>
5056 0 : where
5057 0 : O: FnOnce(TenantMutationLocations) -> F,
5058 0 : F: std::future::Future<Output = R>,
5059 0 : {
5060 0 : self.tenant_remote_mutation_inner(TenantIdOrShardId::TenantId(tenant_id), op)
5061 0 : .await
5062 0 : }
5063 :
5064 0 : pub(crate) async fn tenant_shard_remote_mutation<R, O, F>(
5065 0 : &self,
5066 0 : tenant_shard_id: TenantShardId,
5067 0 : op: O,
5068 0 : ) -> Result<R, ApiError>
5069 0 : where
5070 0 : O: FnOnce(TenantMutationLocations) -> F,
5071 0 : F: std::future::Future<Output = R>,
5072 0 : {
5073 0 : self.tenant_remote_mutation_inner(TenantIdOrShardId::TenantShardId(tenant_shard_id), op)
5074 0 : .await
5075 0 : }
5076 :
5077 0 : async fn tenant_remote_mutation_inner<R, O, F>(
5078 0 : &self,
5079 0 : tenant_id_or_shard_id: TenantIdOrShardId,
5080 0 : op: O,
5081 0 : ) -> Result<R, ApiError>
5082 0 : where
5083 0 : O: FnOnce(TenantMutationLocations) -> F,
5084 0 : F: std::future::Future<Output = R>,
5085 0 : {
5086 0 : let mutation_locations = {
5087 0 : let mut locations = TenantMutationLocations::default();
5088 :
5089 : // Load the currently attached pageservers for the latest generation of each shard. This can
5090 : // run concurrently with reconciliations, and it is not guaranteed that the node we find here
5091 : // will still be the latest when we're done: we will check generations again at the end of
5092 : // this function to handle that.
5093 0 : let generations = self
5094 0 : .persistence
5095 0 : .tenant_generations(tenant_id_or_shard_id.tenant_id())
5096 0 : .await?
5097 0 : .into_iter()
5098 0 : .filter(|i| tenant_id_or_shard_id.matches(&i.tenant_shard_id))
5099 0 : .collect::<Vec<_>>();
5100 :
5101 0 : if generations
5102 0 : .iter()
5103 0 : .any(|i| i.generation.is_none() || i.generation_pageserver.is_none())
5104 : {
5105 0 : let shard_generations = generations
5106 0 : .into_iter()
5107 0 : .map(|i| (i.tenant_shard_id, (i.generation, i.generation_pageserver)))
5108 0 : .collect::<HashMap<_, _>>();
5109 :
5110 : // One or more shards has not been attached to a pageserver. Check if this is because it's configured
5111 : // to be detached (409: caller should give up), or because it's meant to be attached but isn't yet (503: caller should retry)
5112 0 : let locked = self.inner.read().unwrap();
5113 0 : let tenant_shards = locked
5114 0 : .tenants
5115 0 : .range(TenantShardId::tenant_range(
5116 0 : tenant_id_or_shard_id.tenant_id(),
5117 : ))
5118 0 : .filter(|(shard_id, _)| tenant_id_or_shard_id.matches(shard_id))
5119 0 : .collect::<Vec<_>>();
5120 0 : for (shard_id, shard) in tenant_shards {
5121 0 : match shard.policy {
5122 : PlacementPolicy::Attached(_) => {
5123 : // This shard is meant to be attached: the caller is not wrong to try and
5124 : // use this function, but we can't service the request right now.
5125 0 : let Some(generation) = shard_generations.get(shard_id) else {
5126 : // This can only happen if there is a split brain controller modifying the database. This should
5127 : // never happen when testing, and if it happens in production we can only log the issue.
5128 0 : debug_assert!(false);
5129 0 : tracing::error!(
5130 0 : "Shard {shard_id} not found in generation state! Is another rogue controller running?"
5131 : );
5132 0 : continue;
5133 : };
5134 0 : let (generation, generation_pageserver) = generation;
5135 0 : if let Some(generation) = generation {
5136 0 : if generation_pageserver.is_none() {
5137 : // This is legitimate only in a very narrow window where the shard was only just configured into
5138 : // Attached mode after being created in Secondary or Detached mode, and it has had its generation
5139 : // set but not yet had a Reconciler run (reconciler is the only thing that sets generation_pageserver).
5140 0 : tracing::warn!(
5141 0 : "Shard {shard_id} generation is set ({generation:?}) but generation_pageserver is None, reconciler not run yet?"
5142 : );
5143 0 : }
5144 : } else {
5145 : // This should never happen: a shard with no generation is only permitted when it was created in some state
5146 : // other than PlacementPolicy::Attached (and generation is always written to DB before setting Attached in memory)
5147 0 : debug_assert!(false);
5148 0 : tracing::error!(
5149 0 : "Shard {shard_id} generation is None, but it is in PlacementPolicy::Attached mode!"
5150 : );
5151 0 : continue;
5152 : }
5153 : }
5154 : PlacementPolicy::Secondary | PlacementPolicy::Detached => {
5155 0 : return Err(ApiError::Conflict(format!(
5156 0 : "Shard {shard_id} tenant has policy {:?}",
5157 0 : shard.policy
5158 0 : )));
5159 : }
5160 : }
5161 : }
5162 :
5163 0 : return Err(ApiError::ResourceUnavailable(
5164 0 : "One or more shards in tenant is not yet attached".into(),
5165 0 : ));
5166 0 : }
5167 :
5168 0 : let locked = self.inner.read().unwrap();
5169 : for ShardGenerationState {
5170 0 : tenant_shard_id,
5171 0 : generation,
5172 0 : generation_pageserver,
5173 0 : } in generations
5174 : {
5175 0 : let node_id = generation_pageserver.expect("We checked for None above");
5176 0 : let node = locked
5177 0 : .nodes
5178 0 : .get(&node_id)
5179 0 : .ok_or(ApiError::Conflict(format!(
5180 0 : "Raced with removal of node {node_id}"
5181 0 : )))?;
5182 0 : let generation = generation.expect("Checked above");
5183 :
5184 0 : let tenant = locked.tenants.get(&tenant_shard_id);
5185 :
5186 : // TODO(vlad): Abstract the logic that finds stale attached locations
5187 : // from observed state into a [`Service`] method.
5188 0 : let other_locations = match tenant {
5189 0 : Some(tenant) => {
5190 0 : let mut other = tenant.attached_locations();
5191 0 : let latest_location_index =
5192 0 : other.iter().position(|&l| l == (node.get_id(), generation));
5193 0 : if let Some(idx) = latest_location_index {
5194 0 : other.remove(idx);
5195 0 : }
5196 :
5197 0 : other
5198 : }
5199 0 : None => Vec::default(),
5200 : };
5201 :
5202 0 : let location = ShardMutationLocations {
5203 0 : latest: MutationLocation {
5204 0 : node: node.clone(),
5205 0 : generation,
5206 0 : },
5207 0 : other: other_locations
5208 0 : .into_iter()
5209 0 : .filter_map(|(node_id, generation)| {
5210 0 : let node = locked.nodes.get(&node_id)?;
5211 :
5212 0 : Some(MutationLocation {
5213 0 : node: node.clone(),
5214 0 : generation,
5215 0 : })
5216 0 : })
5217 0 : .collect(),
5218 : };
5219 0 : locations.0.insert(tenant_shard_id, location);
5220 : }
5221 :
5222 0 : locations
5223 : };
5224 :
5225 0 : let result = op(mutation_locations.clone()).await;
5226 :
5227 : // Post-check: are all the generations of all the shards the same as they were initially? This proves that
5228 : // our remote operation executed on the latest generation and is therefore persistent.
5229 : {
5230 0 : let latest_generations = self
5231 0 : .persistence
5232 0 : .tenant_generations(tenant_id_or_shard_id.tenant_id())
5233 0 : .await?
5234 0 : .into_iter()
5235 0 : .filter(|i| tenant_id_or_shard_id.matches(&i.tenant_shard_id))
5236 0 : .collect::<Vec<_>>();
5237 :
5238 0 : if latest_generations
5239 0 : .into_iter()
5240 0 : .map(
5241 : |ShardGenerationState {
5242 : tenant_shard_id,
5243 : generation,
5244 : generation_pageserver: _,
5245 0 : }| (tenant_shard_id, generation),
5246 : )
5247 0 : .collect::<Vec<_>>()
5248 0 : != mutation_locations
5249 0 : .0
5250 0 : .into_iter()
5251 0 : .map(|i| (i.0, Some(i.1.latest.generation)))
5252 0 : .collect::<Vec<_>>()
5253 : {
5254 : // We raced with something that incremented the generation, and therefore cannot be
5255 : // confident that our actions are persistent (they might have hit an old generation).
5256 : //
5257 : // This is safe but requires a retry: ask the client to do that by giving them a 503 response.
5258 0 : return Err(ApiError::ResourceUnavailable(
5259 0 : "Tenant attachment changed, please retry".into(),
5260 0 : ));
5261 0 : }
5262 : }
5263 :
5264 0 : Ok(result)
5265 0 : }
5266 :
5267 0 : pub(crate) async fn tenant_timeline_delete(
5268 0 : self: &Arc<Self>,
5269 0 : tenant_id: TenantId,
5270 0 : timeline_id: TimelineId,
5271 0 : ) -> Result<StatusCode, ApiError> {
5272 0 : tracing::info!("Deleting timeline {}/{}", tenant_id, timeline_id,);
5273 0 : let _tenant_lock = trace_shared_lock(
5274 0 : &self.tenant_op_locks,
5275 0 : tenant_id,
5276 0 : TenantOperations::TimelineDelete,
5277 0 : )
5278 0 : .await;
5279 :
5280 0 : let status_code = self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
5281 0 : if targets.0.is_empty() {
5282 0 : return Err(ApiError::NotFound(
5283 0 : anyhow::anyhow!("Tenant not found").into(),
5284 0 : ));
5285 0 : }
5286 :
5287 0 : let (shard_zero_tid, shard_zero_locations) = targets.0.pop_first().expect("Must have at least one shard");
5288 0 : assert!(shard_zero_tid.is_shard_zero());
5289 :
5290 0 : async fn delete_one(
5291 0 : tenant_shard_id: TenantShardId,
5292 0 : timeline_id: TimelineId,
5293 0 : node: Node,
5294 0 : http_client: reqwest::Client,
5295 0 : jwt: Option<String>,
5296 0 : ) -> Result<StatusCode, ApiError> {
5297 0 : tracing::info!(
5298 0 : "Deleting timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
5299 : );
5300 :
5301 0 : let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
5302 0 : let res = client
5303 0 : .timeline_delete(tenant_shard_id, timeline_id)
5304 0 : .await;
5305 :
5306 0 : match res {
5307 0 : Ok(ok) => Ok(ok),
5308 0 : Err(mgmt_api::Error::ApiError(StatusCode::CONFLICT, _)) => Ok(StatusCode::CONFLICT),
5309 0 : Err(mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg)) if msg.contains("Requested tenant is missing") => {
5310 0 : Err(ApiError::ResourceUnavailable("Tenant migration in progress".into()))
5311 : },
5312 0 : Err(mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg)) => Err(ApiError::ResourceUnavailable(msg.into())),
5313 0 : Err(e) => {
5314 0 : Err(
5315 0 : ApiError::InternalServerError(anyhow::anyhow!(
5316 0 : "Error deleting timeline {timeline_id} on {tenant_shard_id} on node {node}: {e}",
5317 0 : ))
5318 0 : )
5319 : }
5320 : }
5321 0 : }
5322 :
5323 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
5324 0 : let statuses = self
5325 0 : .tenant_for_shards(locations, |tenant_shard_id: TenantShardId, node: Node| {
5326 0 : Box::pin(delete_one(
5327 0 : tenant_shard_id,
5328 0 : timeline_id,
5329 0 : node,
5330 0 : self.http_client.clone(),
5331 0 : self.config.pageserver_jwt_token.clone(),
5332 0 : ))
5333 0 : })
5334 0 : .await?;
5335 :
5336 : // If any shards >0 haven't finished deletion yet, don't start deletion on shard zero.
5337 : // We return 409 (Conflict) if deletion was already in progress on any of the shards
5338 : // and 202 (Accepted) if deletion was not already in progress on any of the shards.
5339 0 : if statuses.iter().any(|s| s == &StatusCode::CONFLICT) {
5340 0 : return Ok(StatusCode::CONFLICT);
5341 0 : }
5342 :
5343 0 : if statuses.iter().any(|s| s != &StatusCode::NOT_FOUND) {
5344 0 : return Ok(StatusCode::ACCEPTED);
5345 0 : }
5346 :
5347 : // Delete shard zero last: this is not strictly necessary, but since a caller's GET on a timeline will be routed
5348 : // to shard zero, it gives a more obvious behavior that a GET returns 404 once the deletion is done.
5349 0 : let shard_zero_status = delete_one(
5350 0 : shard_zero_tid,
5351 0 : timeline_id,
5352 0 : shard_zero_locations.latest.node,
5353 0 : self.http_client.clone(),
5354 0 : self.config.pageserver_jwt_token.clone(),
5355 0 : )
5356 0 : .await?;
5357 0 : Ok(shard_zero_status)
5358 0 : }).await?;
5359 :
5360 0 : self.tenant_timeline_delete_safekeepers(tenant_id, timeline_id)
5361 0 : .await?;
5362 :
5363 0 : status_code
5364 0 : }
5365 : /// When you know the TenantId but not a specific shard, and would like to get the node holding shard 0.
5366 : ///
5367 : /// Returns the node, tenant shard id, and whether it is consistent with the observed state.
5368 0 : pub(crate) async fn tenant_shard0_node(
5369 0 : &self,
5370 0 : tenant_id: TenantId,
5371 0 : ) -> Result<(Node, TenantShardId), ApiError> {
5372 0 : let tenant_shard_id = {
5373 0 : let locked = self.inner.read().unwrap();
5374 0 : let Some((tenant_shard_id, _shard)) = locked
5375 0 : .tenants
5376 0 : .range(TenantShardId::tenant_range(tenant_id))
5377 0 : .next()
5378 : else {
5379 0 : return Err(ApiError::NotFound(
5380 0 : anyhow::anyhow!("Tenant {tenant_id} not found").into(),
5381 0 : ));
5382 : };
5383 :
5384 0 : *tenant_shard_id
5385 : };
5386 :
5387 0 : self.tenant_shard_node(tenant_shard_id)
5388 0 : .await
5389 0 : .map(|node| (node, tenant_shard_id))
5390 0 : }
5391 :
5392 : /// When you need to send an HTTP request to the pageserver that holds a shard of a tenant, this
5393 : /// function looks up and returns node. If the shard isn't found, returns Err(ApiError::NotFound)
5394 : ///
5395 : /// Returns the intent node and whether it is consistent with the observed state.
5396 0 : pub(crate) async fn tenant_shard_node(
5397 0 : &self,
5398 0 : tenant_shard_id: TenantShardId,
5399 0 : ) -> Result<Node, ApiError> {
5400 : // Look up in-memory state and maybe use the node from there.
5401 : {
5402 0 : let locked = self.inner.read().unwrap();
5403 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
5404 0 : return Err(ApiError::NotFound(
5405 0 : anyhow::anyhow!("Tenant shard {tenant_shard_id} not found").into(),
5406 0 : ));
5407 : };
5408 :
5409 0 : let Some(intent_node_id) = shard.intent.get_attached() else {
5410 0 : tracing::warn!(
5411 0 : tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
5412 0 : "Shard not scheduled (policy {:?}), cannot generate pass-through URL",
5413 : shard.policy
5414 : );
5415 0 : return Err(ApiError::Conflict(
5416 0 : "Cannot call timeline API on non-attached tenant".to_string(),
5417 0 : ));
5418 : };
5419 :
5420 0 : if shard.reconciler.is_none() {
5421 : // Optimization: while no reconcile is in flight, we may trust our in-memory state
5422 : // to tell us which pageserver to use. Otherwise we will fall through and hit the database
5423 0 : let Some(node) = locked.nodes.get(intent_node_id) else {
5424 : // This should never happen
5425 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5426 0 : "Shard refers to nonexistent node"
5427 0 : )));
5428 : };
5429 0 : return Ok(node.clone());
5430 0 : }
5431 : };
5432 :
5433 : // Look up the latest attached pageserver location from the database
5434 : // generation state: this will reflect the progress of any ongoing migration.
5435 : // Note that it is not guaranteed to _stay_ here, our caller must still handle
5436 : // the case where they call through to the pageserver and get a 404.
5437 0 : let db_result = self
5438 0 : .persistence
5439 0 : .tenant_generations(tenant_shard_id.tenant_id)
5440 0 : .await?;
5441 : let Some(ShardGenerationState {
5442 : tenant_shard_id: _,
5443 : generation: _,
5444 0 : generation_pageserver: Some(node_id),
5445 0 : }) = db_result
5446 0 : .into_iter()
5447 0 : .find(|s| s.tenant_shard_id == tenant_shard_id)
5448 : else {
5449 : // This can happen if we raced with a tenant deletion or a shard split. On a retry
5450 : // the caller will either succeed (shard split case), get a proper 404 (deletion case),
5451 : // or a conflict response (case where tenant was detached in background)
5452 0 : return Err(ApiError::ResourceUnavailable(
5453 0 : format!("Shard {tenant_shard_id} not found in database, or is not attached").into(),
5454 0 : ));
5455 : };
5456 0 : let locked = self.inner.read().unwrap();
5457 0 : let Some(node) = locked.nodes.get(&node_id) else {
5458 : // This should never happen
5459 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5460 0 : "Shard refers to nonexistent node"
5461 0 : )));
5462 : };
5463 : // As a reconciliation is in flight, we do not have the observed state yet, and therefore we assume it is always inconsistent.
5464 0 : Ok(node.clone())
5465 0 : }
5466 :
5467 0 : pub(crate) fn tenant_locate(
5468 0 : &self,
5469 0 : tenant_id: TenantId,
5470 0 : ) -> Result<TenantLocateResponse, ApiError> {
5471 0 : let locked = self.inner.read().unwrap();
5472 0 : tracing::info!("Locating shards for tenant {tenant_id}");
5473 :
5474 0 : let mut result = Vec::new();
5475 0 : let mut shard_params: Option<ShardParameters> = None;
5476 :
5477 0 : for (tenant_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id))
5478 : {
5479 0 : let node_id =
5480 0 : shard
5481 0 : .intent
5482 0 : .get_attached()
5483 0 : .ok_or(ApiError::BadRequest(anyhow::anyhow!(
5484 0 : "Cannot locate a tenant that is not attached"
5485 0 : )))?;
5486 :
5487 0 : let node = locked
5488 0 : .nodes
5489 0 : .get(&node_id)
5490 0 : .expect("Pageservers may not be deleted while referenced");
5491 :
5492 0 : result.push(node.shard_location(*tenant_shard_id));
5493 :
5494 0 : match &shard_params {
5495 0 : None => {
5496 0 : shard_params = Some(ShardParameters {
5497 0 : stripe_size: shard.shard.stripe_size,
5498 0 : count: shard.shard.count,
5499 0 : });
5500 0 : }
5501 0 : Some(params) => {
5502 0 : if params.stripe_size != shard.shard.stripe_size {
5503 : // This should never happen. We enforce at runtime because it's simpler than
5504 : // adding an extra per-tenant data structure to store the things that should be the same
5505 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5506 0 : "Inconsistent shard stripe size parameters!"
5507 0 : )));
5508 0 : }
5509 : }
5510 : }
5511 : }
5512 :
5513 0 : if result.is_empty() {
5514 0 : return Err(ApiError::NotFound(
5515 0 : anyhow::anyhow!("No shards for this tenant ID found").into(),
5516 0 : ));
5517 0 : }
5518 0 : let shard_params = shard_params.expect("result is non-empty, therefore this is set");
5519 0 : tracing::info!(
5520 0 : "Located tenant {} with params {:?} on shards {}",
5521 : tenant_id,
5522 : shard_params,
5523 0 : result
5524 0 : .iter()
5525 0 : .map(|s| format!("{s:?}"))
5526 0 : .collect::<Vec<_>>()
5527 0 : .join(",")
5528 : );
5529 :
5530 0 : Ok(TenantLocateResponse {
5531 0 : shards: result,
5532 0 : shard_params,
5533 0 : })
5534 0 : }
5535 :
5536 : /// Returns None if the input iterator of shards does not include a shard with number=0
5537 0 : fn tenant_describe_impl<'a>(
5538 0 : &self,
5539 0 : shards: impl Iterator<Item = &'a TenantShard>,
5540 0 : ) -> Option<TenantDescribeResponse> {
5541 0 : let mut shard_zero = None;
5542 0 : let mut describe_shards = Vec::new();
5543 :
5544 0 : for shard in shards {
5545 0 : if shard.tenant_shard_id.is_shard_zero() {
5546 0 : shard_zero = Some(shard);
5547 0 : }
5548 :
5549 0 : describe_shards.push(TenantDescribeResponseShard {
5550 0 : tenant_shard_id: shard.tenant_shard_id,
5551 0 : node_attached: *shard.intent.get_attached(),
5552 0 : node_secondary: shard.intent.get_secondary().to_vec(),
5553 0 : last_error: shard
5554 0 : .last_error
5555 0 : .lock()
5556 0 : .unwrap()
5557 0 : .as_ref()
5558 0 : .map(|e| format!("{e}"))
5559 0 : .unwrap_or("".to_string())
5560 0 : .clone(),
5561 0 : is_reconciling: shard.reconciler.is_some(),
5562 0 : is_pending_compute_notification: shard.pending_compute_notification,
5563 0 : is_splitting: matches!(shard.splitting, SplitState::Splitting),
5564 0 : is_importing: shard.importing == TimelineImportState::Importing,
5565 0 : scheduling_policy: shard.get_scheduling_policy(),
5566 0 : preferred_az_id: shard.preferred_az().map(ToString::to_string),
5567 : })
5568 : }
5569 :
5570 0 : let shard_zero = shard_zero?;
5571 :
5572 0 : Some(TenantDescribeResponse {
5573 0 : tenant_id: shard_zero.tenant_shard_id.tenant_id,
5574 0 : shards: describe_shards,
5575 0 : stripe_size: shard_zero.shard.stripe_size,
5576 0 : policy: shard_zero.policy.clone(),
5577 0 : config: shard_zero.config.clone(),
5578 0 : })
5579 0 : }
5580 :
5581 0 : pub(crate) fn tenant_describe(
5582 0 : &self,
5583 0 : tenant_id: TenantId,
5584 0 : ) -> Result<TenantDescribeResponse, ApiError> {
5585 0 : let locked = self.inner.read().unwrap();
5586 :
5587 0 : self.tenant_describe_impl(
5588 0 : locked
5589 0 : .tenants
5590 0 : .range(TenantShardId::tenant_range(tenant_id))
5591 0 : .map(|(_k, v)| v),
5592 : )
5593 0 : .ok_or_else(|| ApiError::NotFound(anyhow::anyhow!("Tenant {tenant_id} not found").into()))
5594 0 : }
5595 :
5596 : /* BEGIN_HADRON */
5597 0 : pub(crate) async fn tenant_timeline_describe(
5598 0 : &self,
5599 0 : tenant_id: TenantId,
5600 0 : timeline_id: TimelineId,
5601 0 : ) -> Result<TenantTimelineDescribeResponse, ApiError> {
5602 0 : self.tenant_remote_mutation(tenant_id, |locations| async move {
5603 0 : if locations.0.is_empty() {
5604 0 : return Err(ApiError::NotFound(
5605 0 : anyhow::anyhow!("Tenant not found").into(),
5606 0 : ));
5607 0 : };
5608 :
5609 0 : let locations: Vec<(TenantShardId, Node)> = locations
5610 0 : .0
5611 0 : .iter()
5612 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
5613 0 : .collect();
5614 0 : let mut futs = FuturesUnordered::new();
5615 :
5616 0 : for (shard_id, node) in locations {
5617 0 : futs.push({
5618 0 : async move {
5619 0 : let result = node
5620 0 : .with_client_retries(
5621 0 : |client| async move {
5622 0 : client
5623 0 : .tenant_timeline_describe(&shard_id, &timeline_id)
5624 0 : .await
5625 0 : },
5626 0 : &self.http_client,
5627 0 : &self.config.pageserver_jwt_token,
5628 : 3,
5629 : 3,
5630 0 : Duration::from_secs(30),
5631 0 : &self.cancel,
5632 : )
5633 0 : .await;
5634 0 : (result, shard_id, node.get_id())
5635 0 : }
5636 : });
5637 : }
5638 :
5639 0 : let mut results: Vec<TimelineInfo> = Vec::new();
5640 0 : while let Some((result, tenant_shard_id, node_id)) = futs.next().await {
5641 0 : match result {
5642 0 : Some(Ok(timeline_info)) => results.push(timeline_info),
5643 0 : Some(Err(e)) => {
5644 0 : tracing::warn!(
5645 0 : "Failed to describe tenant {} timeline {} for pageserver {}: {e}",
5646 : tenant_shard_id,
5647 : timeline_id,
5648 : node_id,
5649 : );
5650 0 : return Err(ApiError::ResourceUnavailable(format!("{e}").into()));
5651 : }
5652 0 : None => return Err(ApiError::Cancelled),
5653 : }
5654 : }
5655 0 : let mut image_consistent_lsn: Option<Lsn> = Some(Lsn::MAX);
5656 0 : for timeline_info in &results {
5657 0 : if let Some(tline_image_consistent_lsn) = timeline_info.image_consistent_lsn {
5658 0 : image_consistent_lsn = Some(std::cmp::min(
5659 0 : image_consistent_lsn.unwrap(),
5660 0 : tline_image_consistent_lsn,
5661 0 : ));
5662 0 : } else {
5663 0 : tracing::warn!(
5664 0 : "Timeline {} on shard {} does not have image consistent lsn",
5665 : timeline_info.timeline_id,
5666 : timeline_info.tenant_id
5667 : );
5668 0 : image_consistent_lsn = None;
5669 0 : break;
5670 : }
5671 : }
5672 :
5673 0 : Ok(TenantTimelineDescribeResponse {
5674 0 : shards: results,
5675 0 : image_consistent_lsn,
5676 0 : })
5677 0 : })
5678 0 : .await?
5679 0 : }
5680 : /* END_HADRON */
5681 :
5682 : /// limit & offset are pagination parameters. Since we are walking an in-memory HashMap, `offset` does not
5683 : /// avoid traversing data, it just avoid returning it. This is suitable for our purposes, since our in memory
5684 : /// maps are small enough to traverse fast, our pagination is just to avoid serializing huge JSON responses
5685 : /// in our external API.
5686 0 : pub(crate) fn tenant_list(
5687 0 : &self,
5688 0 : limit: Option<usize>,
5689 0 : start_after: Option<TenantId>,
5690 0 : ) -> Vec<TenantDescribeResponse> {
5691 0 : let locked = self.inner.read().unwrap();
5692 :
5693 : // Apply start_from parameter
5694 0 : let shard_range = match start_after {
5695 0 : None => locked.tenants.range(..),
5696 0 : Some(tenant_id) => locked.tenants.range(
5697 0 : TenantShardId {
5698 0 : tenant_id,
5699 0 : shard_number: ShardNumber(u8::MAX),
5700 0 : shard_count: ShardCount(u8::MAX),
5701 0 : }..,
5702 : ),
5703 : };
5704 :
5705 0 : let mut result = Vec::new();
5706 0 : for (_tenant_id, tenant_shards) in &shard_range.group_by(|(id, _shard)| id.tenant_id) {
5707 0 : result.push(
5708 0 : self.tenant_describe_impl(tenant_shards.map(|(_k, v)| v))
5709 0 : .expect("Groups are always non-empty"),
5710 : );
5711 :
5712 : // Enforce `limit` parameter
5713 0 : if let Some(limit) = limit {
5714 0 : if result.len() >= limit {
5715 0 : break;
5716 0 : }
5717 0 : }
5718 : }
5719 :
5720 0 : result
5721 0 : }
5722 :
5723 : #[instrument(skip_all, fields(tenant_id=%op.tenant_id))]
5724 : async fn abort_tenant_shard_split(
5725 : &self,
5726 : op: &TenantShardSplitAbort,
5727 : ) -> Result<(), TenantShardSplitAbortError> {
5728 : // Cleaning up a split:
5729 : // - Parent shards are not destroyed during a split, just detached.
5730 : // - Failed pageserver split API calls can leave the remote node with just the parent attached,
5731 : // just the children attached, or both.
5732 : //
5733 : // Therefore our work to do is to:
5734 : // 1. Clean up storage controller's internal state to just refer to parents, no children
5735 : // 2. Call out to pageservers to ensure that children are detached
5736 : // 3. Call out to pageservers to ensure that parents are attached.
5737 : //
5738 : // Crash safety:
5739 : // - If the storage controller stops running during this cleanup *after* clearing the splitting state
5740 : // from our database, then [`Self::startup_reconcile`] will regard child attachments as garbage
5741 : // and detach them.
5742 : // - TODO: If the storage controller stops running during this cleanup *before* clearing the splitting state
5743 : // from our database, then we will re-enter this cleanup routine on startup.
5744 :
5745 : let TenantShardSplitAbort {
5746 : tenant_id,
5747 : new_shard_count,
5748 : new_stripe_size,
5749 : ..
5750 : } = op;
5751 :
5752 : // First abort persistent state, if any exists.
5753 : match self
5754 : .persistence
5755 : .abort_shard_split(*tenant_id, *new_shard_count)
5756 : .await?
5757 : {
5758 : AbortShardSplitStatus::Aborted => {
5759 : // Proceed to roll back any child shards created on pageservers
5760 : }
5761 : AbortShardSplitStatus::Complete => {
5762 : // The split completed (we might hit that path if e.g. our database transaction
5763 : // to write the completion landed in the database, but we dropped connection
5764 : // before seeing the result).
5765 : //
5766 : // We must update in-memory state to reflect the successful split.
5767 : self.tenant_shard_split_commit_inmem(
5768 : *tenant_id,
5769 : *new_shard_count,
5770 : *new_stripe_size,
5771 : );
5772 : return Ok(());
5773 : }
5774 : }
5775 :
5776 : // Clean up in-memory state, and accumulate the list of child locations that need detaching
5777 : let detach_locations: Vec<(Node, TenantShardId)> = {
5778 : let mut detach_locations = Vec::new();
5779 : let mut locked = self.inner.write().unwrap();
5780 : let (nodes, tenants, scheduler) = locked.parts_mut();
5781 :
5782 : for (tenant_shard_id, shard) in
5783 : tenants.range_mut(TenantShardId::tenant_range(op.tenant_id))
5784 : {
5785 : if shard.shard.count == op.new_shard_count {
5786 : // Surprising: the phase of [`Self::do_tenant_shard_split`] which inserts child shards in-memory
5787 : // is infallible, so if we got an error we shouldn't have got that far.
5788 : tracing::warn!(
5789 : "During split abort, child shard {tenant_shard_id} found in-memory"
5790 : );
5791 : continue;
5792 : }
5793 :
5794 : // Add the children of this shard to this list of things to detach
5795 : if let Some(node_id) = shard.intent.get_attached() {
5796 : for child_id in tenant_shard_id.split(*new_shard_count) {
5797 : detach_locations.push((
5798 : nodes
5799 : .get(node_id)
5800 : .expect("Intent references nonexistent node")
5801 : .clone(),
5802 : child_id,
5803 : ));
5804 : }
5805 : } else {
5806 : tracing::warn!(
5807 : "During split abort, shard {tenant_shard_id} has no attached location"
5808 : );
5809 : }
5810 :
5811 : tracing::info!("Restoring parent shard {tenant_shard_id}");
5812 :
5813 : // Drop any intents that refer to unavailable nodes, to enable this abort to proceed even
5814 : // if the original attachment location is offline.
5815 : if let Some(node_id) = shard.intent.get_attached() {
5816 : if !nodes.get(node_id).unwrap().is_available() {
5817 : tracing::info!(
5818 : "Demoting attached intent for {tenant_shard_id} on unavailable node {node_id}"
5819 : );
5820 : shard.intent.demote_attached(scheduler, *node_id);
5821 : }
5822 : }
5823 : for node_id in shard.intent.get_secondary().clone() {
5824 : if !nodes.get(&node_id).unwrap().is_available() {
5825 : tracing::info!(
5826 : "Dropping secondary intent for {tenant_shard_id} on unavailable node {node_id}"
5827 : );
5828 : shard.intent.remove_secondary(scheduler, node_id);
5829 : }
5830 : }
5831 :
5832 : shard.splitting = SplitState::Idle;
5833 : if let Err(e) = shard.schedule(scheduler, &mut ScheduleContext::default()) {
5834 : // If this shard can't be scheduled now (perhaps due to offline nodes or
5835 : // capacity issues), that must not prevent us rolling back a split. In this
5836 : // case it should be eventually scheduled in the background.
5837 : tracing::warn!("Failed to schedule {tenant_shard_id} during shard abort: {e}")
5838 : }
5839 :
5840 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
5841 : }
5842 :
5843 : // We don't expect any new_shard_count shards to exist here, but drop them just in case
5844 : tenants
5845 0 : .retain(|id, s| !(id.tenant_id == *tenant_id && s.shard.count == *new_shard_count));
5846 :
5847 : detach_locations
5848 : };
5849 :
5850 : for (node, child_id) in detach_locations {
5851 : if !node.is_available() {
5852 : // An unavailable node cannot be cleaned up now: to avoid blocking forever, we will permit this, and
5853 : // rely on the reconciliation that happens when a node transitions to Active to clean up. Since we have
5854 : // removed child shards from our in-memory state and database, the reconciliation will implicitly remove
5855 : // them from the node.
5856 : tracing::warn!(
5857 : "Node {node} unavailable, can't clean up during split abort. It will be cleaned up when it is reactivated."
5858 : );
5859 : continue;
5860 : }
5861 :
5862 : // Detach the remote child. If the pageserver split API call is still in progress, this call will get
5863 : // a 503 and retry, up to our limit.
5864 : tracing::info!("Detaching {child_id} on {node}...");
5865 : match node
5866 : .with_client_retries(
5867 0 : |client| async move {
5868 0 : let config = LocationConfig {
5869 0 : mode: LocationConfigMode::Detached,
5870 0 : generation: None,
5871 0 : secondary_conf: None,
5872 0 : shard_number: child_id.shard_number.0,
5873 0 : shard_count: child_id.shard_count.literal(),
5874 0 : // Stripe size and tenant config don't matter when detaching
5875 0 : shard_stripe_size: 0,
5876 0 : tenant_conf: TenantConfig::default(),
5877 0 : };
5878 :
5879 0 : client.location_config(child_id, config, None, false).await
5880 0 : },
5881 : &self.http_client,
5882 : &self.config.pageserver_jwt_token,
5883 : 1,
5884 : 10,
5885 : Duration::from_secs(5),
5886 : &self.reconcilers_cancel,
5887 : )
5888 : .await
5889 : {
5890 : Some(Ok(_)) => {}
5891 : Some(Err(e)) => {
5892 : // We failed to communicate with the remote node. This is problematic: we may be
5893 : // leaving it with a rogue child shard.
5894 : tracing::warn!(
5895 : "Failed to detach child {child_id} from node {node} during abort"
5896 : );
5897 : return Err(e.into());
5898 : }
5899 : None => {
5900 : // Cancellation: we were shutdown or the node went offline. Shutdown is fine, we'll
5901 : // clean up on restart. The node going offline requires a retry.
5902 : return Err(TenantShardSplitAbortError::Unavailable);
5903 : }
5904 : };
5905 : }
5906 :
5907 : tracing::info!("Successfully aborted split");
5908 : Ok(())
5909 : }
5910 :
5911 : /// Infallible final stage of [`Self::tenant_shard_split`]: update the contents
5912 : /// of the tenant map to reflect the child shards that exist after the split.
5913 0 : fn tenant_shard_split_commit_inmem(
5914 0 : &self,
5915 0 : tenant_id: TenantId,
5916 0 : new_shard_count: ShardCount,
5917 0 : new_stripe_size: Option<ShardStripeSize>,
5918 0 : ) -> (
5919 0 : TenantShardSplitResponse,
5920 0 : Vec<(TenantShardId, NodeId, ShardStripeSize)>,
5921 0 : Vec<ReconcilerWaiter>,
5922 0 : ) {
5923 0 : let mut response = TenantShardSplitResponse {
5924 0 : new_shards: Vec::new(),
5925 0 : };
5926 0 : let mut child_locations = Vec::new();
5927 0 : let mut waiters = Vec::new();
5928 :
5929 : {
5930 0 : let mut locked = self.inner.write().unwrap();
5931 :
5932 0 : let parent_ids = locked
5933 0 : .tenants
5934 0 : .range(TenantShardId::tenant_range(tenant_id))
5935 0 : .map(|(shard_id, _)| *shard_id)
5936 0 : .collect::<Vec<_>>();
5937 :
5938 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
5939 0 : for parent_id in parent_ids {
5940 0 : let child_ids = parent_id.split(new_shard_count);
5941 :
5942 : let (
5943 0 : pageserver,
5944 0 : generation,
5945 0 : policy,
5946 0 : parent_ident,
5947 0 : config,
5948 0 : preferred_az,
5949 0 : secondary_count,
5950 : ) = {
5951 0 : let mut old_state = tenants
5952 0 : .remove(&parent_id)
5953 0 : .expect("It was present, we just split it");
5954 :
5955 : // A non-splitting state is impossible, because [`Self::tenant_shard_split`] holds
5956 : // a TenantId lock and passes it through to [`TenantShardSplitAbort`] in case of cleanup:
5957 : // nothing else can clear this.
5958 0 : assert!(matches!(old_state.splitting, SplitState::Splitting));
5959 :
5960 0 : let old_attached = old_state.intent.get_attached().unwrap();
5961 0 : old_state.intent.clear(scheduler);
5962 0 : let generation = old_state.generation.expect("Shard must have been attached");
5963 0 : (
5964 0 : old_attached,
5965 0 : generation,
5966 0 : old_state.policy.clone(),
5967 0 : old_state.shard,
5968 0 : old_state.config.clone(),
5969 0 : old_state.preferred_az().cloned(),
5970 0 : old_state.intent.get_secondary().len(),
5971 0 : )
5972 : };
5973 :
5974 0 : let mut schedule_context = ScheduleContext::default();
5975 0 : for child in child_ids {
5976 0 : let mut child_shard = parent_ident;
5977 0 : child_shard.number = child.shard_number;
5978 0 : child_shard.count = child.shard_count;
5979 0 : if let Some(stripe_size) = new_stripe_size {
5980 0 : child_shard.stripe_size = stripe_size;
5981 0 : }
5982 :
5983 0 : let mut child_observed: HashMap<NodeId, ObservedStateLocation> = HashMap::new();
5984 0 : child_observed.insert(
5985 0 : pageserver,
5986 0 : ObservedStateLocation {
5987 0 : conf: Some(attached_location_conf(
5988 0 : generation,
5989 0 : &child_shard,
5990 0 : &config,
5991 0 : &policy,
5992 0 : secondary_count,
5993 0 : )),
5994 0 : },
5995 : );
5996 :
5997 0 : let mut child_state =
5998 0 : TenantShard::new(child, child_shard, policy.clone(), preferred_az.clone());
5999 0 : child_state.intent =
6000 0 : IntentState::single(scheduler, Some(pageserver), preferred_az.clone());
6001 0 : child_state.observed = ObservedState {
6002 0 : locations: child_observed,
6003 0 : };
6004 0 : child_state.generation = Some(generation);
6005 0 : child_state.config = config.clone();
6006 :
6007 : // The child's TenantShard::splitting is intentionally left at the default value of Idle,
6008 : // as at this point in the split process we have succeeded and this part is infallible:
6009 : // we will never need to do any special recovery from this state.
6010 :
6011 0 : child_locations.push((child, pageserver, child_shard.stripe_size));
6012 :
6013 0 : if let Err(e) = child_state.schedule(scheduler, &mut schedule_context) {
6014 : // This is not fatal, because we've implicitly already got an attached
6015 : // location for the child shard. Failure here just means we couldn't
6016 : // find a secondary (e.g. because cluster is overloaded).
6017 0 : tracing::warn!("Failed to schedule child shard {child}: {e}");
6018 0 : }
6019 : // In the background, attach secondary locations for the new shards
6020 0 : if let Some(waiter) = self.maybe_reconcile_shard(
6021 0 : &mut child_state,
6022 0 : nodes,
6023 0 : ReconcilerPriority::High,
6024 0 : ) {
6025 0 : waiters.push(waiter);
6026 0 : }
6027 :
6028 0 : tenants.insert(child, child_state);
6029 0 : response.new_shards.push(child);
6030 : }
6031 : }
6032 0 : (response, child_locations, waiters)
6033 : }
6034 0 : }
6035 :
6036 0 : async fn tenant_shard_split_start_secondaries(
6037 0 : &self,
6038 0 : tenant_id: TenantId,
6039 0 : waiters: Vec<ReconcilerWaiter>,
6040 0 : ) {
6041 : // Wait for initial reconcile of child shards, this creates the secondary locations
6042 0 : if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
6043 : // This is not a failure to split: it's some issue reconciling the new child shards, perhaps
6044 : // their secondaries couldn't be attached.
6045 0 : tracing::warn!("Failed to reconcile after split: {e}");
6046 0 : return;
6047 0 : }
6048 :
6049 : // Take the state lock to discover the attached & secondary intents for all shards
6050 0 : let (attached, secondary) = {
6051 0 : let locked = self.inner.read().unwrap();
6052 0 : let mut attached = Vec::new();
6053 0 : let mut secondary = Vec::new();
6054 :
6055 0 : for (tenant_shard_id, shard) in
6056 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
6057 : {
6058 0 : let Some(node_id) = shard.intent.get_attached() else {
6059 : // Unexpected. Race with a PlacementPolicy change?
6060 0 : tracing::warn!(
6061 0 : "No attached node on {tenant_shard_id} immediately after shard split!"
6062 : );
6063 0 : continue;
6064 : };
6065 :
6066 0 : let Some(secondary_node_id) = shard.intent.get_secondary().first() else {
6067 : // No secondary location. Nothing for us to do.
6068 0 : continue;
6069 : };
6070 :
6071 0 : let attached_node = locked
6072 0 : .nodes
6073 0 : .get(node_id)
6074 0 : .expect("Pageservers may not be deleted while referenced");
6075 :
6076 0 : let secondary_node = locked
6077 0 : .nodes
6078 0 : .get(secondary_node_id)
6079 0 : .expect("Pageservers may not be deleted while referenced");
6080 :
6081 0 : attached.push((*tenant_shard_id, attached_node.clone()));
6082 0 : secondary.push((*tenant_shard_id, secondary_node.clone()));
6083 : }
6084 0 : (attached, secondary)
6085 : };
6086 :
6087 0 : if secondary.is_empty() {
6088 : // No secondary locations; nothing for us to do
6089 0 : return;
6090 0 : }
6091 :
6092 0 : for (_, result) in self
6093 0 : .tenant_for_shards_api(
6094 0 : attached,
6095 0 : |tenant_shard_id, client| async move {
6096 0 : client.tenant_heatmap_upload(tenant_shard_id).await
6097 0 : },
6098 : 1,
6099 : 1,
6100 : SHORT_RECONCILE_TIMEOUT,
6101 0 : &self.cancel,
6102 : )
6103 0 : .await
6104 : {
6105 0 : if let Err(e) = result {
6106 0 : tracing::warn!("Error calling heatmap upload after shard split: {e}");
6107 0 : return;
6108 0 : }
6109 : }
6110 :
6111 0 : for (_, result) in self
6112 0 : .tenant_for_shards_api(
6113 0 : secondary,
6114 0 : |tenant_shard_id, client| async move {
6115 0 : client
6116 0 : .tenant_secondary_download(tenant_shard_id, Some(Duration::ZERO))
6117 0 : .await
6118 0 : },
6119 : 1,
6120 : 1,
6121 : SHORT_RECONCILE_TIMEOUT,
6122 0 : &self.cancel,
6123 : )
6124 0 : .await
6125 : {
6126 0 : if let Err(e) = result {
6127 0 : tracing::warn!("Error calling secondary download after shard split: {e}");
6128 0 : return;
6129 0 : }
6130 : }
6131 0 : }
6132 :
6133 0 : pub(crate) async fn tenant_shard_split(
6134 0 : &self,
6135 0 : tenant_id: TenantId,
6136 0 : split_req: TenantShardSplitRequest,
6137 0 : ) -> Result<TenantShardSplitResponse, ApiError> {
6138 : // TODO: return 503 if we get stuck waiting for this lock
6139 : // (issue https://github.com/neondatabase/neon/issues/7108)
6140 0 : let _tenant_lock = trace_exclusive_lock(
6141 0 : &self.tenant_op_locks,
6142 0 : tenant_id,
6143 0 : TenantOperations::ShardSplit,
6144 0 : )
6145 0 : .await;
6146 :
6147 0 : let _gate = self
6148 0 : .reconcilers_gate
6149 0 : .enter()
6150 0 : .map_err(|_| ApiError::ShuttingDown)?;
6151 :
6152 : // Timeline imports on the pageserver side can't handle shard-splits.
6153 : // If the tenant is importing a timeline, dont't shard split it.
6154 0 : match self
6155 0 : .persistence
6156 0 : .is_tenant_importing_timeline(tenant_id)
6157 0 : .await
6158 : {
6159 0 : Ok(importing) => {
6160 0 : if importing {
6161 0 : return Err(ApiError::Conflict(
6162 0 : "Cannot shard split during timeline import".to_string(),
6163 0 : ));
6164 0 : }
6165 : }
6166 0 : Err(err) => {
6167 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
6168 0 : "Failed to check for running imports: {err}"
6169 0 : )));
6170 : }
6171 : }
6172 :
6173 0 : let new_shard_count = ShardCount::new(split_req.new_shard_count);
6174 0 : let new_stripe_size = split_req.new_stripe_size;
6175 :
6176 : // Validate the request and construct parameters. This phase is fallible, but does not require
6177 : // rollback on errors, as it does no I/O and mutates no state.
6178 0 : let shard_split_params = match self.prepare_tenant_shard_split(tenant_id, split_req)? {
6179 0 : ShardSplitAction::NoOp(resp) => return Ok(resp),
6180 0 : ShardSplitAction::Split(params) => params,
6181 : };
6182 :
6183 : // Execute this split: this phase mutates state and does remote I/O on pageservers. If it fails,
6184 : // we must roll back.
6185 0 : let r = self
6186 0 : .do_tenant_shard_split(tenant_id, shard_split_params)
6187 0 : .await;
6188 :
6189 0 : let (response, waiters) = match r {
6190 0 : Ok(r) => r,
6191 0 : Err(e) => {
6192 : // Split might be part-done, we must do work to abort it.
6193 0 : tracing::warn!("Enqueuing background abort of split on {tenant_id}");
6194 0 : self.abort_tx
6195 0 : .send(TenantShardSplitAbort {
6196 0 : tenant_id,
6197 0 : new_shard_count,
6198 0 : new_stripe_size,
6199 0 : _tenant_lock,
6200 0 : _gate,
6201 0 : })
6202 : // Ignore error sending: that just means we're shutting down: aborts are ephemeral so it's fine to drop it.
6203 0 : .ok();
6204 0 : return Err(e);
6205 : }
6206 : };
6207 :
6208 : // The split is now complete. As an optimization, we will trigger all the child shards to upload
6209 : // a heatmap immediately, and all their secondary locations to start downloading: this avoids waiting
6210 : // for the background heatmap/download interval before secondaries get warm enough to migrate shards
6211 : // in [`Self::optimize_all`]
6212 0 : self.tenant_shard_split_start_secondaries(tenant_id, waiters)
6213 0 : .await;
6214 0 : Ok(response)
6215 0 : }
6216 :
6217 0 : fn prepare_tenant_shard_split(
6218 0 : &self,
6219 0 : tenant_id: TenantId,
6220 0 : split_req: TenantShardSplitRequest,
6221 0 : ) -> Result<ShardSplitAction, ApiError> {
6222 0 : fail::fail_point!("shard-split-validation", |_| Err(ApiError::BadRequest(
6223 0 : anyhow::anyhow!("failpoint")
6224 0 : )));
6225 :
6226 0 : let mut policy = None;
6227 0 : let mut config = None;
6228 0 : let mut shard_ident = None;
6229 0 : let mut preferred_az_id = None;
6230 : // Validate input, and calculate which shards we will create
6231 0 : let (old_shard_count, targets) =
6232 : {
6233 0 : let locked = self.inner.read().unwrap();
6234 :
6235 0 : let pageservers = locked.nodes.clone();
6236 :
6237 0 : let mut targets = Vec::new();
6238 :
6239 : // In case this is a retry, count how many already-split shards we found
6240 0 : let mut children_found = Vec::new();
6241 0 : let mut old_shard_count = None;
6242 :
6243 0 : for (tenant_shard_id, shard) in
6244 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
6245 : {
6246 0 : match shard.shard.count.count().cmp(&split_req.new_shard_count) {
6247 : Ordering::Equal => {
6248 : // Already split this
6249 0 : children_found.push(*tenant_shard_id);
6250 0 : continue;
6251 : }
6252 : Ordering::Greater => {
6253 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6254 0 : "Requested count {} but already have shards at count {}",
6255 0 : split_req.new_shard_count,
6256 0 : shard.shard.count.count()
6257 0 : )));
6258 : }
6259 0 : Ordering::Less => {
6260 0 : // Fall through: this shard has lower count than requested,
6261 0 : // is a candidate for splitting.
6262 0 : }
6263 : }
6264 :
6265 0 : match old_shard_count {
6266 0 : None => old_shard_count = Some(shard.shard.count),
6267 0 : Some(old_shard_count) => {
6268 0 : if old_shard_count != shard.shard.count {
6269 : // We may hit this case if a caller asked for two splits to
6270 : // different sizes, before the first one is complete.
6271 : // e.g. 1->2, 2->4, where the 4 call comes while we have a mixture
6272 : // of shard_count=1 and shard_count=2 shards in the map.
6273 0 : return Err(ApiError::Conflict(
6274 0 : "Cannot split, currently mid-split".to_string(),
6275 0 : ));
6276 0 : }
6277 : }
6278 : }
6279 0 : if policy.is_none() {
6280 0 : policy = Some(shard.policy.clone());
6281 0 : }
6282 0 : if shard_ident.is_none() {
6283 0 : shard_ident = Some(shard.shard);
6284 0 : }
6285 0 : if config.is_none() {
6286 0 : config = Some(shard.config.clone());
6287 0 : }
6288 0 : if preferred_az_id.is_none() {
6289 0 : preferred_az_id = shard.preferred_az().cloned();
6290 0 : }
6291 :
6292 0 : if tenant_shard_id.shard_count.count() == split_req.new_shard_count {
6293 0 : tracing::info!(
6294 0 : "Tenant shard {} already has shard count {}",
6295 : tenant_shard_id,
6296 : split_req.new_shard_count
6297 : );
6298 0 : continue;
6299 0 : }
6300 :
6301 0 : let node_id = shard.intent.get_attached().ok_or(ApiError::BadRequest(
6302 0 : anyhow::anyhow!("Cannot split a tenant that is not attached"),
6303 0 : ))?;
6304 :
6305 0 : let node = pageservers
6306 0 : .get(&node_id)
6307 0 : .expect("Pageservers may not be deleted while referenced");
6308 :
6309 0 : targets.push(ShardSplitTarget {
6310 0 : parent_id: *tenant_shard_id,
6311 0 : node: node.clone(),
6312 0 : child_ids: tenant_shard_id
6313 0 : .split(ShardCount::new(split_req.new_shard_count)),
6314 0 : });
6315 : }
6316 :
6317 0 : if targets.is_empty() {
6318 0 : if children_found.len() == split_req.new_shard_count as usize {
6319 0 : return Ok(ShardSplitAction::NoOp(TenantShardSplitResponse {
6320 0 : new_shards: children_found,
6321 0 : }));
6322 : } else {
6323 : // No shards found to split, and no existing children found: the
6324 : // tenant doesn't exist at all.
6325 0 : return Err(ApiError::NotFound(
6326 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
6327 0 : ));
6328 : }
6329 0 : }
6330 :
6331 0 : (old_shard_count, targets)
6332 : };
6333 :
6334 : // unwrap safety: we would have returned above if we didn't find at least one shard to split
6335 0 : let old_shard_count = old_shard_count.unwrap();
6336 0 : let shard_ident = if let Some(new_stripe_size) = split_req.new_stripe_size {
6337 : // This ShardIdentity will be used as the template for all children, so this implicitly
6338 : // applies the new stripe size to the children.
6339 0 : let mut shard_ident = shard_ident.unwrap();
6340 0 : if shard_ident.count.count() > 1 && shard_ident.stripe_size != new_stripe_size {
6341 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6342 0 : "Attempted to change stripe size ({:?}->{new_stripe_size:?}) on a tenant with multiple shards",
6343 0 : shard_ident.stripe_size
6344 0 : )));
6345 0 : }
6346 :
6347 0 : shard_ident.stripe_size = new_stripe_size;
6348 0 : tracing::info!("applied stripe size {}", shard_ident.stripe_size.0);
6349 0 : shard_ident
6350 : } else {
6351 0 : shard_ident.unwrap()
6352 : };
6353 0 : let policy = policy.unwrap();
6354 0 : let config = config.unwrap();
6355 :
6356 0 : Ok(ShardSplitAction::Split(Box::new(ShardSplitParams {
6357 0 : old_shard_count,
6358 0 : new_shard_count: ShardCount::new(split_req.new_shard_count),
6359 0 : new_stripe_size: split_req.new_stripe_size,
6360 0 : targets,
6361 0 : policy,
6362 0 : config,
6363 0 : shard_ident,
6364 0 : preferred_az_id,
6365 0 : })))
6366 0 : }
6367 :
6368 0 : async fn do_tenant_shard_split(
6369 0 : &self,
6370 0 : tenant_id: TenantId,
6371 0 : params: Box<ShardSplitParams>,
6372 0 : ) -> Result<(TenantShardSplitResponse, Vec<ReconcilerWaiter>), ApiError> {
6373 : // FIXME: we have dropped self.inner lock, and not yet written anything to the database: another
6374 : // request could occur here, deleting or mutating the tenant. begin_shard_split checks that the
6375 : // parent shards exist as expected, but it would be neater to do the above pre-checks within the
6376 : // same database transaction rather than pre-check in-memory and then maybe-fail the database write.
6377 : // (https://github.com/neondatabase/neon/issues/6676)
6378 :
6379 : let ShardSplitParams {
6380 0 : old_shard_count,
6381 0 : new_shard_count,
6382 0 : new_stripe_size,
6383 0 : mut targets,
6384 0 : policy,
6385 0 : config,
6386 0 : shard_ident,
6387 0 : preferred_az_id,
6388 0 : } = *params;
6389 :
6390 : // Drop any secondary locations: pageservers do not support splitting these, and in any case the
6391 : // end-state for a split tenant will usually be to have secondary locations on different nodes.
6392 : // The reconciliation calls in this block also implicitly cancel+barrier wrt any ongoing reconciliation
6393 : // at the time of split.
6394 0 : let waiters = {
6395 0 : let mut locked = self.inner.write().unwrap();
6396 0 : let mut waiters = Vec::new();
6397 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6398 0 : for target in &mut targets {
6399 0 : let Some(shard) = tenants.get_mut(&target.parent_id) else {
6400 : // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
6401 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
6402 0 : "Shard {} not found",
6403 0 : target.parent_id
6404 0 : )));
6405 : };
6406 :
6407 0 : if shard.intent.get_attached() != &Some(target.node.get_id()) {
6408 : // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
6409 0 : return Err(ApiError::Conflict(format!(
6410 0 : "Shard {} unexpectedly rescheduled during split",
6411 0 : target.parent_id
6412 0 : )));
6413 0 : }
6414 :
6415 : // Irrespective of PlacementPolicy, clear secondary locations from intent
6416 0 : shard.intent.clear_secondary(scheduler);
6417 :
6418 : // Run Reconciler to execute detach fo secondary locations.
6419 0 : if let Some(waiter) =
6420 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
6421 0 : {
6422 0 : waiters.push(waiter);
6423 0 : }
6424 : }
6425 0 : waiters
6426 : };
6427 0 : self.await_waiters(waiters, RECONCILE_TIMEOUT).await?;
6428 :
6429 : // Before creating any new child shards in memory or on the pageservers, persist them: this
6430 : // enables us to ensure that we will always be able to clean up if something goes wrong. This also
6431 : // acts as the protection against two concurrent attempts to split: one of them will get a database
6432 : // error trying to insert the child shards.
6433 0 : let mut child_tsps = Vec::new();
6434 0 : for target in &targets {
6435 0 : let mut this_child_tsps = Vec::new();
6436 0 : for child in &target.child_ids {
6437 0 : let mut child_shard = shard_ident;
6438 0 : child_shard.number = child.shard_number;
6439 0 : child_shard.count = child.shard_count;
6440 :
6441 0 : tracing::info!(
6442 0 : "Create child shard persistence with stripe size {}",
6443 : shard_ident.stripe_size.0
6444 : );
6445 :
6446 0 : this_child_tsps.push(TenantShardPersistence {
6447 0 : tenant_id: child.tenant_id.to_string(),
6448 0 : shard_number: child.shard_number.0 as i32,
6449 0 : shard_count: child.shard_count.literal() as i32,
6450 0 : shard_stripe_size: shard_ident.stripe_size.0 as i32,
6451 : // Note: this generation is a placeholder, [`Persistence::begin_shard_split`] will
6452 : // populate the correct generation as part of its transaction, to protect us
6453 : // against racing with changes in the state of the parent.
6454 0 : generation: None,
6455 0 : generation_pageserver: Some(target.node.get_id().0 as i64),
6456 0 : placement_policy: serde_json::to_string(&policy).unwrap(),
6457 0 : config: serde_json::to_string(&config).unwrap(),
6458 0 : splitting: SplitState::Splitting,
6459 :
6460 : // Scheduling policies and preferred AZ do not carry through to children
6461 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
6462 0 : .unwrap(),
6463 0 : preferred_az_id: preferred_az_id.as_ref().map(|az| az.0.clone()),
6464 : });
6465 : }
6466 :
6467 0 : child_tsps.push((target.parent_id, this_child_tsps));
6468 : }
6469 :
6470 0 : if let Err(e) = self
6471 0 : .persistence
6472 0 : .begin_shard_split(old_shard_count, tenant_id, child_tsps)
6473 0 : .await
6474 : {
6475 0 : match e {
6476 : DatabaseError::Query(diesel::result::Error::DatabaseError(
6477 : DatabaseErrorKind::UniqueViolation,
6478 : _,
6479 : )) => {
6480 : // Inserting a child shard violated a unique constraint: we raced with another call to
6481 : // this function
6482 0 : tracing::warn!("Conflicting attempt to split {tenant_id}: {e}");
6483 0 : return Err(ApiError::Conflict("Tenant is already splitting".into()));
6484 : }
6485 0 : _ => return Err(ApiError::InternalServerError(e.into())),
6486 : }
6487 0 : }
6488 0 : fail::fail_point!("shard-split-post-begin", |_| Err(
6489 0 : ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
6490 : ));
6491 :
6492 : // Now that I have persisted the splitting state, apply it in-memory. This is infallible, so
6493 : // callers may assume that if splitting is set in memory, then it was persisted, and if splitting
6494 : // is not set in memory, then it was not persisted.
6495 : {
6496 0 : let mut locked = self.inner.write().unwrap();
6497 0 : for target in &targets {
6498 0 : if let Some(parent_shard) = locked.tenants.get_mut(&target.parent_id) {
6499 0 : parent_shard.splitting = SplitState::Splitting;
6500 0 : // Put the observed state to None, to reflect that it is indeterminate once we start the
6501 0 : // split operation.
6502 0 : parent_shard
6503 0 : .observed
6504 0 : .locations
6505 0 : .insert(target.node.get_id(), ObservedStateLocation { conf: None });
6506 0 : }
6507 : }
6508 : }
6509 :
6510 : // TODO: issue split calls concurrently (this only matters once we're splitting
6511 : // N>1 shards into M shards -- initially we're usually splitting 1 shard into N).
6512 :
6513 : // HADRON: set a timeout for splitting individual shards on page servers.
6514 : // Currently we do not perform any retry because it's not clear if page server can handle
6515 : // partially split shards correctly.
6516 0 : let shard_split_timeout =
6517 0 : if let Some(env::DeploymentMode::Local) = env::get_deployment_mode() {
6518 0 : Duration::from_secs(30)
6519 : } else {
6520 0 : self.config.shard_split_request_timeout
6521 : };
6522 0 : let mut http_client_builder = reqwest::ClientBuilder::new()
6523 0 : .pool_max_idle_per_host(0)
6524 0 : .timeout(shard_split_timeout);
6525 :
6526 0 : for ssl_ca_cert in &self.config.ssl_ca_certs {
6527 0 : http_client_builder = http_client_builder.add_root_certificate(ssl_ca_cert.clone());
6528 0 : }
6529 0 : let http_client = http_client_builder
6530 0 : .build()
6531 0 : .expect("Failed to construct HTTP client");
6532 0 : for target in &targets {
6533 : let ShardSplitTarget {
6534 0 : parent_id,
6535 0 : node,
6536 0 : child_ids,
6537 0 : } = target;
6538 :
6539 0 : let client = PageserverClient::new(
6540 0 : node.get_id(),
6541 0 : http_client.clone(),
6542 0 : node.base_url(),
6543 0 : self.config.pageserver_jwt_token.as_deref(),
6544 : );
6545 :
6546 0 : let response = client
6547 0 : .tenant_shard_split(
6548 0 : *parent_id,
6549 0 : TenantShardSplitRequest {
6550 0 : new_shard_count: new_shard_count.literal(),
6551 0 : new_stripe_size,
6552 0 : },
6553 0 : )
6554 0 : .await
6555 0 : .map_err(|e| ApiError::Conflict(format!("Failed to split {parent_id}: {e}")))?;
6556 :
6557 0 : fail::fail_point!("shard-split-post-remote", |_| Err(ApiError::Conflict(
6558 0 : "failpoint".to_string()
6559 0 : )));
6560 :
6561 0 : failpoint_support::sleep_millis_async!(
6562 : "shard-split-post-remote-sleep",
6563 0 : &self.reconcilers_cancel
6564 : );
6565 :
6566 0 : tracing::info!(
6567 0 : "Split {} into {}",
6568 : parent_id,
6569 0 : response
6570 0 : .new_shards
6571 0 : .iter()
6572 0 : .map(|s| format!("{s:?}"))
6573 0 : .collect::<Vec<_>>()
6574 0 : .join(",")
6575 : );
6576 :
6577 0 : if &response.new_shards != child_ids {
6578 : // This should never happen: the pageserver should agree with us on how shard splits work.
6579 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
6580 0 : "Splitting shard {} resulted in unexpected IDs: {:?} (expected {:?})",
6581 0 : parent_id,
6582 0 : response.new_shards,
6583 0 : child_ids
6584 0 : )));
6585 0 : }
6586 : }
6587 :
6588 0 : fail::fail_point!("shard-split-pre-complete", |_| Err(ApiError::Conflict(
6589 0 : "failpoint".to_string()
6590 0 : )));
6591 :
6592 0 : pausable_failpoint!("shard-split-pre-complete-pause");
6593 :
6594 : // TODO: if the pageserver restarted concurrently with our split API call,
6595 : // the actual generation of the child shard might differ from the generation
6596 : // we expect it to have. In order for our in-database generation to end up
6597 : // correct, we should carry the child generation back in the response and apply it here
6598 : // in complete_shard_split (and apply the correct generation in memory)
6599 : // (or, we can carry generation in the request and reject the request if
6600 : // it doesn't match, but that requires more retry logic on this side)
6601 :
6602 0 : self.persistence
6603 0 : .complete_shard_split(tenant_id, old_shard_count, new_shard_count)
6604 0 : .await?;
6605 :
6606 0 : fail::fail_point!("shard-split-post-complete", |_| Err(
6607 0 : ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
6608 : ));
6609 :
6610 : // Replace all the shards we just split with their children: this phase is infallible.
6611 0 : let (response, child_locations, waiters) =
6612 0 : self.tenant_shard_split_commit_inmem(tenant_id, new_shard_count, new_stripe_size);
6613 :
6614 : // Notify all page servers to detach and clean up the old shards because they will no longer
6615 : // be needed. This is best-effort: if it fails, it will be cleaned up on a subsequent
6616 : // Pageserver re-attach/startup.
6617 0 : let shards_to_cleanup = targets
6618 0 : .iter()
6619 0 : .map(|target| (target.parent_id, target.node.get_id()))
6620 0 : .collect();
6621 0 : self.cleanup_locations(shards_to_cleanup).await;
6622 :
6623 : // Send compute notifications for all the new shards
6624 0 : let mut failed_notifications = Vec::new();
6625 0 : for (child_id, child_ps, stripe_size) in child_locations {
6626 0 : if let Err(e) = self
6627 0 : .compute_hook
6628 0 : .notify_attach(
6629 0 : compute_hook::ShardUpdate {
6630 0 : tenant_shard_id: child_id,
6631 0 : node_id: child_ps,
6632 0 : stripe_size,
6633 0 : preferred_az: preferred_az_id.as_ref().map(Cow::Borrowed),
6634 0 : },
6635 0 : &self.reconcilers_cancel,
6636 0 : )
6637 0 : .await
6638 : {
6639 0 : tracing::warn!(
6640 0 : "Failed to update compute of {}->{} during split, proceeding anyway to complete split ({e})",
6641 : child_id,
6642 : child_ps
6643 : );
6644 0 : failed_notifications.push(child_id);
6645 0 : }
6646 : }
6647 :
6648 : // If we failed any compute notifications, make a note to retry later.
6649 0 : if !failed_notifications.is_empty() {
6650 0 : let mut locked = self.inner.write().unwrap();
6651 0 : for failed in failed_notifications {
6652 0 : if let Some(shard) = locked.tenants.get_mut(&failed) {
6653 0 : shard.pending_compute_notification = true;
6654 0 : }
6655 : }
6656 0 : }
6657 :
6658 0 : Ok((response, waiters))
6659 0 : }
6660 :
6661 : /// A graceful migration: update the preferred node and let optimisation handle the migration
6662 : /// in the background (may take a long time as it will fully warm up a location before cutting over)
6663 : ///
6664 : /// Our external API calls this a 'prewarm=true' migration, but internally it isn't a special prewarm step: it's
6665 : /// just a migration that uses the same graceful procedure as our background scheduling optimisations would use.
6666 0 : fn tenant_shard_migrate_with_prewarm(
6667 0 : &self,
6668 0 : migrate_req: &TenantShardMigrateRequest,
6669 0 : shard: &mut TenantShard,
6670 0 : scheduler: &mut Scheduler,
6671 0 : schedule_context: ScheduleContext,
6672 0 : ) -> Result<Option<ScheduleOptimization>, ApiError> {
6673 0 : shard.set_preferred_node(Some(migrate_req.node_id));
6674 :
6675 : // Generate whatever the initial change to the intent is: this could be creation of a secondary, or
6676 : // cutting over to an existing secondary. Caller is responsible for validating this before applying it,
6677 : // e.g. by checking secondary is warm enough.
6678 0 : Ok(shard.optimize_attachment(scheduler, &schedule_context))
6679 0 : }
6680 :
6681 : /// Immediate migration: directly update the intent state and kick off a reconciler
6682 0 : fn tenant_shard_migrate_immediate(
6683 0 : &self,
6684 0 : migrate_req: &TenantShardMigrateRequest,
6685 0 : nodes: &Arc<HashMap<NodeId, Node>>,
6686 0 : shard: &mut TenantShard,
6687 0 : scheduler: &mut Scheduler,
6688 0 : ) -> Result<Option<ReconcilerWaiter>, ApiError> {
6689 : // Non-graceful migration: update the intent state immediately
6690 0 : let old_attached = *shard.intent.get_attached();
6691 0 : match shard.policy {
6692 0 : PlacementPolicy::Attached(n) => {
6693 : // If our new attached node was a secondary, it no longer should be.
6694 0 : shard
6695 0 : .intent
6696 0 : .remove_secondary(scheduler, migrate_req.node_id);
6697 :
6698 0 : shard
6699 0 : .intent
6700 0 : .set_attached(scheduler, Some(migrate_req.node_id));
6701 :
6702 : // If we were already attached to something, demote that to a secondary
6703 0 : if let Some(old_attached) = old_attached {
6704 0 : if n > 0 {
6705 : // Remove other secondaries to make room for the location we'll demote
6706 0 : while shard.intent.get_secondary().len() >= n {
6707 0 : shard.intent.pop_secondary(scheduler);
6708 0 : }
6709 :
6710 0 : shard.intent.push_secondary(scheduler, old_attached);
6711 0 : }
6712 0 : }
6713 : }
6714 0 : PlacementPolicy::Secondary => {
6715 0 : shard.intent.clear(scheduler);
6716 0 : shard.intent.push_secondary(scheduler, migrate_req.node_id);
6717 0 : }
6718 : PlacementPolicy::Detached => {
6719 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6720 0 : "Cannot migrate a tenant that is PlacementPolicy::Detached: configure it to an attached policy first"
6721 0 : )));
6722 : }
6723 : }
6724 :
6725 0 : tracing::info!("Migrating: new intent {:?}", shard.intent);
6726 0 : shard.sequence = shard.sequence.next();
6727 0 : shard.set_preferred_node(None); // Abort any in-flight graceful migration
6728 0 : Ok(self.maybe_configured_reconcile_shard(
6729 0 : shard,
6730 0 : nodes,
6731 0 : (&migrate_req.migration_config).into(),
6732 0 : ))
6733 0 : }
6734 :
6735 0 : pub(crate) async fn tenant_shard_migrate(
6736 0 : &self,
6737 0 : tenant_shard_id: TenantShardId,
6738 0 : migrate_req: TenantShardMigrateRequest,
6739 0 : ) -> Result<TenantShardMigrateResponse, ApiError> {
6740 : // Depending on whether the migration is a change and whether it's graceful or immediate, we might
6741 : // get a different outcome to handle
6742 : enum MigrationOutcome {
6743 : Optimization(Option<ScheduleOptimization>),
6744 : Reconcile(Option<ReconcilerWaiter>),
6745 : }
6746 :
6747 0 : let outcome = {
6748 0 : let mut locked = self.inner.write().unwrap();
6749 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6750 :
6751 0 : let Some(node) = nodes.get(&migrate_req.node_id) else {
6752 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6753 0 : "Node {} not found",
6754 0 : migrate_req.node_id
6755 0 : )));
6756 : };
6757 :
6758 : // Migration to unavavailable node requires force flag
6759 0 : if !node.is_available() {
6760 0 : if migrate_req.migration_config.override_scheduler {
6761 : // Warn but proceed: the caller may intend to manually adjust the placement of
6762 : // a shard even if the node is down, e.g. if intervening during an incident.
6763 0 : tracing::warn!("Forcibly migrating to unavailable node {node}");
6764 : } else {
6765 0 : tracing::warn!("Node {node} is unavailable, refusing migration");
6766 0 : return Err(ApiError::PreconditionFailed(
6767 0 : format!("Node {node} is unavailable").into_boxed_str(),
6768 0 : ));
6769 : }
6770 0 : }
6771 :
6772 : // Calculate the ScheduleContext for this tenant
6773 0 : let mut schedule_context = ScheduleContext::default();
6774 0 : for (_shard_id, shard) in
6775 0 : tenants.range(TenantShardId::tenant_range(tenant_shard_id.tenant_id))
6776 0 : {
6777 0 : schedule_context.avoid(&shard.intent.all_pageservers());
6778 0 : }
6779 :
6780 : // Look up the specific shard we will migrate
6781 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
6782 0 : return Err(ApiError::NotFound(
6783 0 : anyhow::anyhow!("Tenant shard not found").into(),
6784 0 : ));
6785 : };
6786 :
6787 : // Migration to a node with unfavorable scheduling score requires a force flag, because it might just
6788 : // be migrated back by the optimiser.
6789 0 : if let Some(better_node) = shard.find_better_location::<AttachedShardTag>(
6790 0 : scheduler,
6791 0 : &schedule_context,
6792 0 : migrate_req.node_id,
6793 0 : &[],
6794 0 : ) {
6795 0 : if !migrate_req.migration_config.override_scheduler {
6796 0 : return Err(ApiError::PreconditionFailed(
6797 0 : "Migration to a worse-scoring node".into(),
6798 0 : ));
6799 : } else {
6800 0 : tracing::info!(
6801 0 : "Migrating to a worse-scoring node {} (optimiser would prefer {better_node})",
6802 : migrate_req.node_id
6803 : );
6804 : }
6805 0 : }
6806 :
6807 0 : if let Some(origin_node_id) = migrate_req.origin_node_id {
6808 0 : if shard.intent.get_attached() != &Some(origin_node_id) {
6809 0 : return Err(ApiError::PreconditionFailed(
6810 0 : format!(
6811 0 : "Migration expected to originate from {} but shard is on {:?}",
6812 0 : origin_node_id,
6813 0 : shard.intent.get_attached()
6814 0 : )
6815 0 : .into(),
6816 0 : ));
6817 0 : }
6818 0 : }
6819 :
6820 0 : if shard.intent.get_attached() == &Some(migrate_req.node_id) {
6821 : // No-op case: we will still proceed to wait for reconciliation in case it is
6822 : // incomplete from an earlier update to the intent.
6823 0 : tracing::info!("Migrating: intent is unchanged {:?}", shard.intent);
6824 :
6825 : // An instruction to migrate to the currently attached node should
6826 : // cancel any pending graceful migration
6827 0 : shard.set_preferred_node(None);
6828 :
6829 0 : MigrationOutcome::Reconcile(self.maybe_configured_reconcile_shard(
6830 0 : shard,
6831 0 : nodes,
6832 0 : (&migrate_req.migration_config).into(),
6833 0 : ))
6834 0 : } else if migrate_req.migration_config.prewarm {
6835 0 : MigrationOutcome::Optimization(self.tenant_shard_migrate_with_prewarm(
6836 0 : &migrate_req,
6837 0 : shard,
6838 0 : scheduler,
6839 0 : schedule_context,
6840 0 : )?)
6841 : } else {
6842 0 : MigrationOutcome::Reconcile(self.tenant_shard_migrate_immediate(
6843 0 : &migrate_req,
6844 0 : nodes,
6845 0 : shard,
6846 0 : scheduler,
6847 0 : )?)
6848 : }
6849 : };
6850 :
6851 : // We may need to validate + apply an optimisation, or we may need to just retrive a reconcile waiter
6852 0 : let waiter = match outcome {
6853 0 : MigrationOutcome::Optimization(Some(optimization)) => {
6854 : // Validate and apply the optimization -- this would happen anyway in background reconcile loop, but
6855 : // we might as well do it more promptly as this is a direct external request.
6856 0 : let mut validated = self
6857 0 : .optimize_all_validate(vec![(tenant_shard_id, optimization)])
6858 0 : .await;
6859 0 : if let Some((_shard_id, optimization)) = validated.pop() {
6860 0 : let mut locked = self.inner.write().unwrap();
6861 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6862 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
6863 : // Rare but possible: tenant is removed between generating optimisation and validating it.
6864 0 : return Err(ApiError::NotFound(
6865 0 : anyhow::anyhow!("Tenant shard not found").into(),
6866 0 : ));
6867 : };
6868 :
6869 0 : if !shard.apply_optimization(scheduler, optimization) {
6870 : // This can happen but is unusual enough to warn on: something else changed in the shard that made the optimisation stale
6871 : // and therefore not applied.
6872 0 : tracing::warn!(
6873 0 : "Schedule optimisation generated during graceful migration was not applied, shard changed?"
6874 : );
6875 0 : }
6876 0 : self.maybe_configured_reconcile_shard(
6877 0 : shard,
6878 0 : nodes,
6879 0 : (&migrate_req.migration_config).into(),
6880 : )
6881 : } else {
6882 0 : None
6883 : }
6884 : }
6885 0 : MigrationOutcome::Optimization(None) => None,
6886 0 : MigrationOutcome::Reconcile(waiter) => waiter,
6887 : };
6888 :
6889 : // Finally, wait for any reconcile we started to complete. In the case of immediate-mode migrations to cold
6890 : // locations, this has a good chance of timing out.
6891 0 : if let Some(waiter) = waiter {
6892 0 : waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
6893 : } else {
6894 0 : tracing::info!("Migration is a no-op");
6895 : }
6896 :
6897 0 : Ok(TenantShardMigrateResponse {})
6898 0 : }
6899 :
6900 0 : pub(crate) async fn tenant_shard_migrate_secondary(
6901 0 : &self,
6902 0 : tenant_shard_id: TenantShardId,
6903 0 : migrate_req: TenantShardMigrateRequest,
6904 0 : ) -> Result<TenantShardMigrateResponse, ApiError> {
6905 0 : let waiter = {
6906 0 : let mut locked = self.inner.write().unwrap();
6907 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6908 :
6909 0 : let Some(node) = nodes.get(&migrate_req.node_id) else {
6910 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6911 0 : "Node {} not found",
6912 0 : migrate_req.node_id
6913 0 : )));
6914 : };
6915 :
6916 0 : if !node.is_available() {
6917 : // Warn but proceed: the caller may intend to manually adjust the placement of
6918 : // a shard even if the node is down, e.g. if intervening during an incident.
6919 0 : tracing::warn!("Migrating to unavailable node {node}");
6920 0 : }
6921 :
6922 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
6923 0 : return Err(ApiError::NotFound(
6924 0 : anyhow::anyhow!("Tenant shard not found").into(),
6925 0 : ));
6926 : };
6927 :
6928 0 : if shard.intent.get_secondary().len() == 1
6929 0 : && shard.intent.get_secondary()[0] == migrate_req.node_id
6930 : {
6931 0 : tracing::info!(
6932 0 : "Migrating secondary to {node}: intent is unchanged {:?}",
6933 : shard.intent
6934 : );
6935 0 : } else if shard.intent.get_attached() == &Some(migrate_req.node_id) {
6936 0 : tracing::info!(
6937 0 : "Migrating secondary to {node}: already attached where we were asked to create a secondary"
6938 : );
6939 : } else {
6940 0 : let old_secondaries = shard.intent.get_secondary().clone();
6941 0 : for secondary in old_secondaries {
6942 0 : shard.intent.remove_secondary(scheduler, secondary);
6943 0 : }
6944 :
6945 0 : shard.intent.push_secondary(scheduler, migrate_req.node_id);
6946 0 : shard.sequence = shard.sequence.next();
6947 0 : tracing::info!(
6948 0 : "Migrating secondary to {node}: new intent {:?}",
6949 : shard.intent
6950 : );
6951 : }
6952 :
6953 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
6954 : };
6955 :
6956 0 : if let Some(waiter) = waiter {
6957 0 : waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
6958 : } else {
6959 0 : tracing::info!("Migration is a no-op");
6960 : }
6961 :
6962 0 : Ok(TenantShardMigrateResponse {})
6963 0 : }
6964 :
6965 : /// 'cancel' in this context means cancel any ongoing reconcile
6966 0 : pub(crate) async fn tenant_shard_cancel_reconcile(
6967 0 : &self,
6968 0 : tenant_shard_id: TenantShardId,
6969 0 : ) -> Result<(), ApiError> {
6970 : // Take state lock and fire the cancellation token, after which we drop lock and wait for any ongoing reconcile to complete
6971 0 : let waiter = {
6972 0 : let locked = self.inner.write().unwrap();
6973 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
6974 0 : return Err(ApiError::NotFound(
6975 0 : anyhow::anyhow!("Tenant shard not found").into(),
6976 0 : ));
6977 : };
6978 :
6979 0 : let waiter = shard.get_waiter();
6980 0 : match waiter {
6981 : None => {
6982 0 : tracing::info!("Shard does not have an ongoing Reconciler");
6983 0 : return Ok(());
6984 : }
6985 0 : Some(waiter) => {
6986 0 : tracing::info!("Cancelling Reconciler");
6987 0 : shard.cancel_reconciler();
6988 0 : waiter
6989 : }
6990 : }
6991 : };
6992 :
6993 : // Cancellation should be prompt. If this fails we have still done our job of firing the
6994 : // cancellation token, but by returning an ApiError we will indicate to the caller that
6995 : // the Reconciler is misbehaving and not respecting the cancellation token
6996 0 : self.await_waiters(vec![waiter], SHORT_RECONCILE_TIMEOUT)
6997 0 : .await?;
6998 :
6999 0 : Ok(())
7000 0 : }
7001 :
7002 : /// This is for debug/support only: we simply drop all state for a tenant, without
7003 : /// detaching or deleting it on pageservers.
7004 0 : pub(crate) async fn tenant_drop(&self, tenant_id: TenantId) -> Result<(), ApiError> {
7005 0 : self.persistence.delete_tenant(tenant_id).await?;
7006 :
7007 0 : let mut locked = self.inner.write().unwrap();
7008 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
7009 0 : let mut shards = Vec::new();
7010 0 : for (tenant_shard_id, _) in tenants.range(TenantShardId::tenant_range(tenant_id)) {
7011 0 : shards.push(*tenant_shard_id);
7012 0 : }
7013 :
7014 0 : for shard_id in shards {
7015 0 : if let Some(mut shard) = tenants.remove(&shard_id) {
7016 0 : shard.intent.clear(scheduler);
7017 0 : }
7018 : }
7019 :
7020 0 : Ok(())
7021 0 : }
7022 :
7023 : /// This is for debug/support only: assuming tenant data is already present in S3, we "create" a
7024 : /// tenant with a very high generation number so that it will see the existing data.
7025 : /// It does not create timelines on safekeepers, because they might already exist on some
7026 : /// safekeeper set. So, the timelines are not storcon-managed after the import.
7027 0 : pub(crate) async fn tenant_import(
7028 0 : &self,
7029 0 : tenant_id: TenantId,
7030 0 : ) -> Result<TenantCreateResponse, ApiError> {
7031 : // Pick an arbitrary available pageserver to use for scanning the tenant in remote storage
7032 0 : let maybe_node = {
7033 0 : self.inner
7034 0 : .read()
7035 0 : .unwrap()
7036 0 : .nodes
7037 0 : .values()
7038 0 : .find(|n| n.is_available())
7039 0 : .cloned()
7040 : };
7041 0 : let Some(node) = maybe_node else {
7042 0 : return Err(ApiError::BadRequest(anyhow::anyhow!("No nodes available")));
7043 : };
7044 :
7045 0 : let client = PageserverClient::new(
7046 0 : node.get_id(),
7047 0 : self.http_client.clone(),
7048 0 : node.base_url(),
7049 0 : self.config.pageserver_jwt_token.as_deref(),
7050 : );
7051 :
7052 0 : let scan_result = client
7053 0 : .tenant_scan_remote_storage(tenant_id)
7054 0 : .await
7055 0 : .map_err(|e| passthrough_api_error(&node, e))?;
7056 :
7057 : // A post-split tenant may contain a mixture of shard counts in remote storage: pick the highest count.
7058 0 : let Some(shard_count) = scan_result
7059 0 : .shards
7060 0 : .iter()
7061 0 : .map(|s| s.tenant_shard_id.shard_count)
7062 0 : .max()
7063 : else {
7064 0 : return Err(ApiError::NotFound(
7065 0 : anyhow::anyhow!("No shards found").into(),
7066 0 : ));
7067 : };
7068 :
7069 : // Ideally we would set each newly imported shard's generation independently, but for correctness it is sufficient
7070 : // to
7071 0 : let generation = scan_result
7072 0 : .shards
7073 0 : .iter()
7074 0 : .map(|s| s.generation)
7075 0 : .max()
7076 0 : .expect("We already validated >0 shards");
7077 :
7078 : // Find the tenant's stripe size. This wasn't always persisted in the tenant manifest, so
7079 : // fall back to the original default stripe size of 32768 (256 MB) if it's not specified.
7080 : const ORIGINAL_STRIPE_SIZE: ShardStripeSize = ShardStripeSize(32768);
7081 0 : let stripe_size = scan_result
7082 0 : .shards
7083 0 : .iter()
7084 0 : .find(|s| s.tenant_shard_id.shard_count == shard_count && s.generation == generation)
7085 0 : .expect("we validated >0 shards above")
7086 : .stripe_size
7087 0 : .unwrap_or_else(|| {
7088 0 : if shard_count.count() > 1 {
7089 0 : warn!("unknown stripe size, assuming {ORIGINAL_STRIPE_SIZE}");
7090 0 : }
7091 0 : ORIGINAL_STRIPE_SIZE
7092 0 : });
7093 :
7094 0 : let (response, waiters) = self
7095 0 : .do_tenant_create(TenantCreateRequest {
7096 0 : new_tenant_id: TenantShardId::unsharded(tenant_id),
7097 0 : generation,
7098 0 :
7099 0 : shard_parameters: ShardParameters {
7100 0 : count: shard_count,
7101 0 : stripe_size,
7102 0 : },
7103 0 : placement_policy: Some(PlacementPolicy::Attached(0)), // No secondaries, for convenient debug/hacking
7104 0 : config: TenantConfig::default(),
7105 0 : })
7106 0 : .await?;
7107 :
7108 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
7109 : // Since this is a debug/support operation, all kinds of weird issues are possible (e.g. this
7110 : // tenant doesn't exist in the control plane), so don't fail the request if it can't fully
7111 : // reconcile, as reconciliation includes notifying compute.
7112 0 : tracing::warn!(%tenant_id, "Reconcile not done yet while importing tenant ({e})");
7113 0 : }
7114 :
7115 0 : Ok(response)
7116 0 : }
7117 :
7118 : /// For debug/support: a full JSON dump of TenantShards. Returns a response so that
7119 : /// we don't have to make TenantShard clonable in the return path.
7120 0 : pub(crate) fn tenants_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
7121 0 : let serialized = {
7122 0 : let locked = self.inner.read().unwrap();
7123 0 : let result = locked.tenants.values().collect::<Vec<_>>();
7124 0 : serde_json::to_string(&result).map_err(|e| ApiError::InternalServerError(e.into()))?
7125 : };
7126 :
7127 0 : hyper::Response::builder()
7128 0 : .status(hyper::StatusCode::OK)
7129 0 : .header(hyper::header::CONTENT_TYPE, "application/json")
7130 0 : .body(hyper::Body::from(serialized))
7131 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
7132 0 : }
7133 :
7134 : /// Check the consistency of in-memory state vs. persistent state, and check that the
7135 : /// scheduler's statistics are up to date.
7136 : ///
7137 : /// These consistency checks expect an **idle** system. If changes are going on while
7138 : /// we run, then we can falsely indicate a consistency issue. This is sufficient for end-of-test
7139 : /// checks, but not suitable for running continuously in the background in the field.
7140 0 : pub(crate) async fn consistency_check(&self) -> Result<(), ApiError> {
7141 0 : let (mut expect_nodes, mut expect_shards) = {
7142 0 : let locked = self.inner.read().unwrap();
7143 :
7144 0 : locked
7145 0 : .scheduler
7146 0 : .consistency_check(locked.nodes.values(), locked.tenants.values())
7147 0 : .context("Scheduler checks")
7148 0 : .map_err(ApiError::InternalServerError)?;
7149 :
7150 0 : let expect_nodes = locked
7151 0 : .nodes
7152 0 : .values()
7153 0 : .map(|n| n.to_persistent())
7154 0 : .collect::<Vec<_>>();
7155 :
7156 0 : let expect_shards = locked
7157 0 : .tenants
7158 0 : .values()
7159 0 : .map(|t| t.to_persistent())
7160 0 : .collect::<Vec<_>>();
7161 :
7162 : // This method can only validate the state of an idle system: if a reconcile is in
7163 : // progress, fail out early to avoid giving false errors on state that won't match
7164 : // between database and memory under a ReconcileResult is processed.
7165 0 : for t in locked.tenants.values() {
7166 0 : if t.reconciler.is_some() {
7167 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
7168 0 : "Shard {} reconciliation in progress",
7169 0 : t.tenant_shard_id
7170 0 : )));
7171 0 : }
7172 : }
7173 :
7174 0 : (expect_nodes, expect_shards)
7175 : };
7176 :
7177 0 : let mut nodes = self.persistence.list_nodes().await?;
7178 0 : expect_nodes.sort_by_key(|n| n.node_id);
7179 0 : nodes.sort_by_key(|n| n.node_id);
7180 :
7181 : // Errors relating to nodes are deferred so that we don't skip the shard checks below if we have a node error
7182 0 : let node_result = if nodes != expect_nodes {
7183 0 : tracing::error!("Consistency check failed on nodes.");
7184 0 : tracing::error!(
7185 0 : "Nodes in memory: {}",
7186 0 : serde_json::to_string(&expect_nodes)
7187 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7188 : );
7189 0 : tracing::error!(
7190 0 : "Nodes in database: {}",
7191 0 : serde_json::to_string(&nodes)
7192 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7193 : );
7194 0 : Err(ApiError::InternalServerError(anyhow::anyhow!(
7195 0 : "Node consistency failure"
7196 0 : )))
7197 : } else {
7198 0 : Ok(())
7199 : };
7200 :
7201 0 : let mut persistent_shards = self.persistence.load_active_tenant_shards().await?;
7202 0 : persistent_shards
7203 0 : .sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
7204 :
7205 0 : expect_shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
7206 :
7207 : // Because JSON contents of persistent tenants might disagree with the fields in current `TenantConfig`
7208 : // definition, we will do an encode/decode cycle to ensure any legacy fields are dropped and any new
7209 : // fields are added, before doing a comparison.
7210 0 : for tsp in &mut persistent_shards {
7211 0 : let config: TenantConfig = serde_json::from_str(&tsp.config)
7212 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?;
7213 0 : tsp.config = serde_json::to_string(&config).expect("Encoding config is infallible");
7214 : }
7215 :
7216 0 : if persistent_shards != expect_shards {
7217 0 : tracing::error!("Consistency check failed on shards.");
7218 :
7219 0 : tracing::error!(
7220 0 : "Shards in memory: {}",
7221 0 : serde_json::to_string(&expect_shards)
7222 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7223 : );
7224 0 : tracing::error!(
7225 0 : "Shards in database: {}",
7226 0 : serde_json::to_string(&persistent_shards)
7227 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7228 : );
7229 :
7230 : // The total dump log lines above are useful in testing but in the field grafana will
7231 : // usually just drop them because they're so large. So we also do some explicit logging
7232 : // of just the diffs.
7233 0 : let persistent_shards = persistent_shards
7234 0 : .into_iter()
7235 0 : .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
7236 0 : .collect::<HashMap<_, _>>();
7237 0 : let expect_shards = expect_shards
7238 0 : .into_iter()
7239 0 : .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
7240 0 : .collect::<HashMap<_, _>>();
7241 0 : for (tenant_shard_id, persistent_tsp) in &persistent_shards {
7242 0 : match expect_shards.get(tenant_shard_id) {
7243 : None => {
7244 0 : tracing::error!(
7245 0 : "Shard {} found in database but not in memory",
7246 : tenant_shard_id
7247 : );
7248 : }
7249 0 : Some(expect_tsp) => {
7250 0 : if expect_tsp != persistent_tsp {
7251 0 : tracing::error!(
7252 0 : "Shard {} is inconsistent. In memory: {}, database has: {}",
7253 : tenant_shard_id,
7254 0 : serde_json::to_string(expect_tsp).unwrap(),
7255 0 : serde_json::to_string(&persistent_tsp).unwrap()
7256 : );
7257 0 : }
7258 : }
7259 : }
7260 : }
7261 :
7262 : // Having already logged any differences, log any shards that simply aren't present in the database
7263 0 : for (tenant_shard_id, memory_tsp) in &expect_shards {
7264 0 : if !persistent_shards.contains_key(tenant_shard_id) {
7265 0 : tracing::error!(
7266 0 : "Shard {} found in memory but not in database: {}",
7267 : tenant_shard_id,
7268 0 : serde_json::to_string(memory_tsp)
7269 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7270 : );
7271 0 : }
7272 : }
7273 :
7274 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
7275 0 : "Shard consistency failure"
7276 0 : )));
7277 0 : }
7278 :
7279 0 : node_result
7280 0 : }
7281 :
7282 : /// For debug/support: a JSON dump of the [`Scheduler`]. Returns a response so that
7283 : /// we don't have to make TenantShard clonable in the return path.
7284 0 : pub(crate) fn scheduler_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
7285 0 : let serialized = {
7286 0 : let locked = self.inner.read().unwrap();
7287 0 : serde_json::to_string(&locked.scheduler)
7288 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7289 : };
7290 :
7291 0 : hyper::Response::builder()
7292 0 : .status(hyper::StatusCode::OK)
7293 0 : .header(hyper::header::CONTENT_TYPE, "application/json")
7294 0 : .body(hyper::Body::from(serialized))
7295 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
7296 0 : }
7297 :
7298 : /// This is for debug/support only: we simply drop all state for a tenant, without
7299 : /// detaching or deleting it on pageservers. We do not try and re-schedule any
7300 : /// tenants that were on this node.
7301 0 : pub(crate) async fn node_drop(&self, node_id: NodeId) -> Result<(), ApiError> {
7302 0 : self.persistence.set_tombstone(node_id).await?;
7303 :
7304 0 : let mut locked = self.inner.write().unwrap();
7305 :
7306 0 : for shard in locked.tenants.values_mut() {
7307 0 : shard.deref_node(node_id);
7308 0 : shard.observed.locations.remove(&node_id);
7309 0 : }
7310 :
7311 0 : let mut nodes = (*locked.nodes).clone();
7312 0 : nodes.remove(&node_id);
7313 0 : locked.nodes = Arc::new(nodes);
7314 0 : metrics::METRICS_REGISTRY
7315 0 : .metrics_group
7316 0 : .storage_controller_pageserver_nodes
7317 0 : .set(locked.nodes.len() as i64);
7318 0 : metrics::METRICS_REGISTRY
7319 0 : .metrics_group
7320 0 : .storage_controller_https_pageserver_nodes
7321 0 : .set(locked.nodes.values().filter(|n| n.has_https_port()).count() as i64);
7322 :
7323 0 : locked.scheduler.node_remove(node_id);
7324 :
7325 0 : Ok(())
7326 0 : }
7327 :
7328 : /// If a node has any work on it, it will be rescheduled: this is "clean" in the sense
7329 : /// that we don't leave any bad state behind in the storage controller, but unclean
7330 : /// in the sense that we are not carefully draining the node.
7331 0 : pub(crate) async fn node_delete_old(&self, node_id: NodeId) -> Result<(), ApiError> {
7332 0 : let _node_lock =
7333 0 : trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Delete).await;
7334 :
7335 : // 1. Atomically update in-memory state:
7336 : // - set the scheduling state to Pause to make subsequent scheduling ops skip it
7337 : // - update shards' intents to exclude the node, and reschedule any shards whose intents we modified.
7338 : // - drop the node from the main nodes map, so that when running reconciles complete they do not
7339 : // re-insert references to this node into the ObservedState of shards
7340 : // - drop the node from the scheduler
7341 : {
7342 0 : let mut locked = self.inner.write().unwrap();
7343 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
7344 :
7345 : {
7346 0 : let mut nodes_mut = (*nodes).deref().clone();
7347 0 : match nodes_mut.get_mut(&node_id) {
7348 0 : Some(node) => {
7349 0 : // We do not bother setting this in the database, because we're about to delete the row anyway, and
7350 0 : // if we crash it would not be desirable to leave the node paused after a restart.
7351 0 : node.set_scheduling(NodeSchedulingPolicy::Pause);
7352 0 : }
7353 : None => {
7354 0 : tracing::info!(
7355 0 : "Node not found: presuming this is a retry and returning success"
7356 : );
7357 0 : return Ok(());
7358 : }
7359 : }
7360 :
7361 0 : *nodes = Arc::new(nodes_mut);
7362 : }
7363 :
7364 0 : for (_tenant_id, mut schedule_context, shards) in
7365 0 : TenantShardExclusiveIterator::new(tenants, ScheduleMode::Normal)
7366 : {
7367 0 : for shard in shards {
7368 0 : if shard.deref_node(node_id) {
7369 0 : if let Err(e) = shard.schedule(scheduler, &mut schedule_context) {
7370 : // TODO: implement force flag to remove a node even if we can't reschedule
7371 : // a tenant
7372 0 : tracing::error!(
7373 0 : "Refusing to delete node, shard {} can't be rescheduled: {e}",
7374 : shard.tenant_shard_id
7375 : );
7376 0 : return Err(e.into());
7377 : } else {
7378 0 : tracing::info!(
7379 0 : "Rescheduled shard {} away from node during deletion",
7380 : shard.tenant_shard_id
7381 : )
7382 : }
7383 :
7384 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
7385 0 : }
7386 :
7387 : // Here we remove an existing observed location for the node we're removing, and it will
7388 : // not be re-added by a reconciler's completion because we filter out removed nodes in
7389 : // process_result.
7390 : //
7391 : // Note that we update the shard's observed state _after_ calling maybe_reconcile_shard: that
7392 : // means any reconciles we spawned will know about the node we're deleting, enabling them
7393 : // to do live migrations if it's still online.
7394 0 : shard.observed.locations.remove(&node_id);
7395 : }
7396 : }
7397 :
7398 0 : scheduler.node_remove(node_id);
7399 :
7400 : {
7401 0 : let mut nodes_mut = (**nodes).clone();
7402 0 : if let Some(mut removed_node) = nodes_mut.remove(&node_id) {
7403 0 : // Ensure that any reconciler holding an Arc<> to this node will
7404 0 : // drop out when trying to RPC to it (setting Offline state sets the
7405 0 : // cancellation token on the Node object).
7406 0 : removed_node.set_availability(NodeAvailability::Offline);
7407 0 : }
7408 0 : *nodes = Arc::new(nodes_mut);
7409 0 : metrics::METRICS_REGISTRY
7410 0 : .metrics_group
7411 0 : .storage_controller_pageserver_nodes
7412 0 : .set(nodes.len() as i64);
7413 0 : metrics::METRICS_REGISTRY
7414 0 : .metrics_group
7415 0 : .storage_controller_https_pageserver_nodes
7416 0 : .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
7417 : }
7418 : }
7419 :
7420 : // Note: some `generation_pageserver` columns on tenant shards in the database may still refer to
7421 : // the removed node, as this column means "The pageserver to which this generation was issued", and
7422 : // their generations won't get updated until the reconcilers moving them away from this node complete.
7423 : // That is safe because in Service::spawn we only use generation_pageserver if it refers to a node
7424 : // that exists.
7425 :
7426 : // 2. Actually delete the node from in-memory state and set tombstone to the database
7427 : // for preventing the node to register again.
7428 0 : tracing::info!("Deleting node from database");
7429 0 : self.persistence.set_tombstone(node_id).await?;
7430 :
7431 0 : Ok(())
7432 0 : }
7433 :
7434 0 : pub(crate) async fn delete_node(
7435 0 : self: &Arc<Self>,
7436 0 : node_id: NodeId,
7437 0 : policy_on_start: NodeSchedulingPolicy,
7438 0 : force: bool,
7439 0 : cancel: CancellationToken,
7440 0 : ) -> Result<(), OperationError> {
7441 0 : let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal).build();
7442 :
7443 0 : let mut waiters: Vec<ReconcilerWaiter> = Vec::new();
7444 0 : let mut tid_iter = create_shared_shard_iterator(self.clone());
7445 :
7446 0 : let reset_node_policy_on_cancel = || async {
7447 0 : match self
7448 0 : .node_configure(node_id, None, Some(policy_on_start))
7449 0 : .await
7450 : {
7451 0 : Ok(()) => OperationError::Cancelled,
7452 0 : Err(err) => {
7453 0 : OperationError::FinalizeError(
7454 0 : format!(
7455 0 : "Failed to finalise delete cancel of {} by setting scheduling policy to {}: {}",
7456 0 : node_id, String::from(policy_on_start), err
7457 0 : )
7458 0 : .into(),
7459 0 : )
7460 : }
7461 : }
7462 0 : };
7463 :
7464 0 : while !tid_iter.finished() {
7465 0 : if cancel.is_cancelled() {
7466 0 : return Err(reset_node_policy_on_cancel().await);
7467 0 : }
7468 :
7469 0 : operation_utils::validate_node_state(
7470 0 : &node_id,
7471 0 : self.inner.read().unwrap().nodes.clone(),
7472 0 : NodeSchedulingPolicy::Deleting,
7473 0 : )?;
7474 :
7475 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
7476 0 : let tid = match tid_iter.next() {
7477 0 : Some(tid) => tid,
7478 : None => {
7479 0 : break;
7480 : }
7481 : };
7482 :
7483 0 : let mut locked = self.inner.write().unwrap();
7484 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
7485 :
7486 : // Calculate a schedule context here to avoid borrow checker issues.
7487 0 : let mut schedule_context = ScheduleContext::default();
7488 0 : for (_, shard) in tenants.range(TenantShardId::tenant_range(tid.tenant_id)) {
7489 0 : schedule_context.avoid(&shard.intent.all_pageservers());
7490 0 : }
7491 :
7492 0 : let tenant_shard = match tenants.get_mut(&tid) {
7493 0 : Some(tenant_shard) => tenant_shard,
7494 : None => {
7495 : // Tenant shard was deleted by another operation. Skip it.
7496 0 : continue;
7497 : }
7498 : };
7499 :
7500 0 : match tenant_shard.get_scheduling_policy() {
7501 0 : ShardSchedulingPolicy::Active | ShardSchedulingPolicy::Essential => {
7502 0 : // A migration during delete is classed as 'essential' because it is required to
7503 0 : // uphold our availability goals for the tenant: this shard is elegible for migration.
7504 0 : }
7505 : ShardSchedulingPolicy::Pause | ShardSchedulingPolicy::Stop => {
7506 : // If we have been asked to avoid rescheduling this shard, then do not migrate it during a deletion
7507 0 : tracing::warn!(
7508 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
7509 0 : "Skip migration during deletion because shard scheduling policy {:?} disallows it",
7510 0 : tenant_shard.get_scheduling_policy(),
7511 : );
7512 0 : continue;
7513 : }
7514 : }
7515 :
7516 0 : if tenant_shard.deref_node(node_id) {
7517 0 : if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
7518 0 : tracing::error!(
7519 0 : "Refusing to delete node, shard {} can't be rescheduled: {e}",
7520 : tenant_shard.tenant_shard_id
7521 : );
7522 0 : return Err(OperationError::ImpossibleConstraint(e.to_string().into()));
7523 : } else {
7524 0 : tracing::info!(
7525 0 : "Rescheduled shard {} away from node during deletion",
7526 : tenant_shard.tenant_shard_id
7527 : )
7528 : }
7529 :
7530 0 : let waiter = self.maybe_configured_reconcile_shard(
7531 0 : tenant_shard,
7532 0 : nodes,
7533 0 : reconciler_config,
7534 0 : );
7535 :
7536 0 : if force {
7537 0 : // Here we remove an existing observed location for the node we're removing, and it will
7538 0 : // not be re-added by a reconciler's completion because we filter out removed nodes in
7539 0 : // process_result.
7540 0 : //
7541 0 : // Note that we update the shard's observed state _after_ calling maybe_configured_reconcile_shard:
7542 0 : // that means any reconciles we spawned will know about the node we're deleting,
7543 0 : // enabling them to do live migrations if it's still online.
7544 0 : tenant_shard.observed.locations.remove(&node_id);
7545 0 : } else if let Some(waiter) = waiter {
7546 0 : waiters.push(waiter);
7547 0 : }
7548 0 : }
7549 : }
7550 :
7551 0 : waiters = self
7552 0 : .await_waiters_remainder(waiters, WAITER_OPERATION_POLL_TIMEOUT)
7553 0 : .await;
7554 :
7555 0 : failpoint_support::sleep_millis_async!("sleepy-delete-loop", &cancel);
7556 : }
7557 :
7558 0 : while !waiters.is_empty() {
7559 0 : if cancel.is_cancelled() {
7560 0 : return Err(reset_node_policy_on_cancel().await);
7561 0 : }
7562 :
7563 0 : tracing::info!("Awaiting {} pending delete reconciliations", waiters.len());
7564 :
7565 0 : waiters = self
7566 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
7567 0 : .await;
7568 : }
7569 :
7570 0 : let pf = pausable_failpoint!("delete-node-after-reconciles-spawned", &cancel);
7571 0 : if pf.is_err() {
7572 : // An error from pausable_failpoint indicates the cancel token was triggered.
7573 0 : return Err(reset_node_policy_on_cancel().await);
7574 0 : }
7575 :
7576 0 : self.persistence
7577 0 : .set_tombstone(node_id)
7578 0 : .await
7579 0 : .map_err(|e| OperationError::FinalizeError(e.to_string().into()))?;
7580 :
7581 : {
7582 0 : let mut locked = self.inner.write().unwrap();
7583 0 : let (nodes, _, scheduler) = locked.parts_mut();
7584 :
7585 0 : scheduler.node_remove(node_id);
7586 :
7587 0 : let mut nodes_mut = (**nodes).clone();
7588 0 : if let Some(mut removed_node) = nodes_mut.remove(&node_id) {
7589 0 : // Ensure that any reconciler holding an Arc<> to this node will
7590 0 : // drop out when trying to RPC to it (setting Offline state sets the
7591 0 : // cancellation token on the Node object).
7592 0 : removed_node.set_availability(NodeAvailability::Offline);
7593 0 : }
7594 0 : *nodes = Arc::new(nodes_mut);
7595 :
7596 0 : metrics::METRICS_REGISTRY
7597 0 : .metrics_group
7598 0 : .storage_controller_pageserver_nodes
7599 0 : .set(nodes.len() as i64);
7600 0 : metrics::METRICS_REGISTRY
7601 0 : .metrics_group
7602 0 : .storage_controller_https_pageserver_nodes
7603 0 : .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
7604 : }
7605 :
7606 0 : Ok(())
7607 0 : }
7608 :
7609 0 : pub(crate) async fn node_list(&self) -> Result<Vec<Node>, ApiError> {
7610 0 : let nodes = {
7611 0 : self.inner
7612 0 : .read()
7613 0 : .unwrap()
7614 0 : .nodes
7615 0 : .values()
7616 0 : .cloned()
7617 0 : .collect::<Vec<_>>()
7618 : };
7619 :
7620 0 : Ok(nodes)
7621 0 : }
7622 :
7623 0 : pub(crate) async fn tombstone_list(&self) -> Result<Vec<Node>, ApiError> {
7624 0 : self.persistence
7625 0 : .list_tombstones()
7626 0 : .await?
7627 0 : .into_iter()
7628 0 : .map(|np| Node::from_persistent(np, false))
7629 0 : .collect::<Result<Vec<_>, _>>()
7630 0 : .map_err(ApiError::InternalServerError)
7631 0 : }
7632 :
7633 0 : pub(crate) async fn tombstone_delete(&self, node_id: NodeId) -> Result<(), ApiError> {
7634 0 : let _node_lock = trace_exclusive_lock(
7635 0 : &self.node_op_locks,
7636 0 : node_id,
7637 0 : NodeOperations::DeleteTombstone,
7638 0 : )
7639 0 : .await;
7640 :
7641 0 : if matches!(self.get_node(node_id).await, Err(ApiError::NotFound(_))) {
7642 0 : self.persistence.delete_node(node_id).await?;
7643 0 : Ok(())
7644 : } else {
7645 0 : Err(ApiError::Conflict(format!(
7646 0 : "Node {node_id} is in use, consider using tombstone API first"
7647 0 : )))
7648 : }
7649 0 : }
7650 :
7651 0 : pub(crate) async fn get_node(&self, node_id: NodeId) -> Result<Node, ApiError> {
7652 0 : self.inner
7653 0 : .read()
7654 0 : .unwrap()
7655 0 : .nodes
7656 0 : .get(&node_id)
7657 0 : .cloned()
7658 0 : .ok_or(ApiError::NotFound(
7659 0 : format!("Node {node_id} not registered").into(),
7660 0 : ))
7661 0 : }
7662 :
7663 0 : pub(crate) async fn get_node_shards(
7664 0 : &self,
7665 0 : node_id: NodeId,
7666 0 : ) -> Result<NodeShardResponse, ApiError> {
7667 0 : let locked = self.inner.read().unwrap();
7668 0 : let mut shards = Vec::new();
7669 0 : for (tid, tenant) in locked.tenants.iter() {
7670 0 : let is_intended_secondary = match (
7671 0 : tenant.intent.get_attached() == &Some(node_id),
7672 0 : tenant.intent.get_secondary().contains(&node_id),
7673 0 : ) {
7674 : (true, true) => {
7675 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
7676 0 : "{} attached as primary+secondary on the same node",
7677 0 : tid
7678 0 : )));
7679 : }
7680 0 : (true, false) => Some(false),
7681 0 : (false, true) => Some(true),
7682 0 : (false, false) => None,
7683 : };
7684 0 : let is_observed_secondary = if let Some(ObservedStateLocation { conf: Some(conf) }) =
7685 0 : tenant.observed.locations.get(&node_id)
7686 : {
7687 0 : Some(conf.secondary_conf.is_some())
7688 : } else {
7689 0 : None
7690 : };
7691 0 : if is_intended_secondary.is_some() || is_observed_secondary.is_some() {
7692 0 : shards.push(NodeShard {
7693 0 : tenant_shard_id: *tid,
7694 0 : is_intended_secondary,
7695 0 : is_observed_secondary,
7696 0 : });
7697 0 : }
7698 : }
7699 0 : Ok(NodeShardResponse { node_id, shards })
7700 0 : }
7701 :
7702 0 : pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
7703 0 : self.persistence.get_leader().await
7704 0 : }
7705 :
7706 0 : pub(crate) async fn node_register(
7707 0 : &self,
7708 0 : register_req: NodeRegisterRequest,
7709 0 : ) -> Result<(), ApiError> {
7710 0 : let _node_lock = trace_exclusive_lock(
7711 0 : &self.node_op_locks,
7712 0 : register_req.node_id,
7713 0 : NodeOperations::Register,
7714 0 : )
7715 0 : .await;
7716 :
7717 : #[derive(PartialEq)]
7718 : enum RegistrationStatus {
7719 : UpToDate,
7720 : NeedUpdate,
7721 : Mismatched,
7722 : New,
7723 : }
7724 :
7725 0 : let registration_status = {
7726 0 : let locked = self.inner.read().unwrap();
7727 0 : if let Some(node) = locked.nodes.get(®ister_req.node_id) {
7728 0 : if node.registration_match(®ister_req) {
7729 0 : if node.need_update(®ister_req) {
7730 0 : RegistrationStatus::NeedUpdate
7731 : } else {
7732 0 : RegistrationStatus::UpToDate
7733 : }
7734 : } else {
7735 0 : RegistrationStatus::Mismatched
7736 : }
7737 : } else {
7738 0 : RegistrationStatus::New
7739 : }
7740 : };
7741 :
7742 0 : match registration_status {
7743 : RegistrationStatus::UpToDate => {
7744 0 : tracing::info!(
7745 0 : "Node {} re-registered with matching address and is up to date",
7746 : register_req.node_id
7747 : );
7748 :
7749 0 : return Ok(());
7750 : }
7751 : RegistrationStatus::Mismatched => {
7752 : // TODO: decide if we want to allow modifying node addresses without removing and re-adding
7753 : // the node. Safest/simplest thing is to refuse it, and usually we deploy with
7754 : // a fixed address through the lifetime of a node.
7755 0 : tracing::warn!(
7756 0 : "Node {} tried to register with different address",
7757 : register_req.node_id
7758 : );
7759 0 : return Err(ApiError::Conflict(
7760 0 : "Node is already registered with different address".to_string(),
7761 0 : ));
7762 : }
7763 0 : RegistrationStatus::New | RegistrationStatus::NeedUpdate => {
7764 0 : // fallthrough
7765 0 : }
7766 : }
7767 :
7768 : // We do not require that a node is actually online when registered (it will start life
7769 : // with it's availability set to Offline), but we _do_ require that its DNS record exists. We're
7770 : // therefore not immune to asymmetric L3 connectivity issues, but we are protected against nodes
7771 : // that register themselves with a broken DNS config. We check only the HTTP hostname, because
7772 : // the postgres hostname might only be resolvable to clients (e.g. if we're on a different VPC than clients).
7773 0 : if tokio::net::lookup_host(format!(
7774 0 : "{}:{}",
7775 : register_req.listen_http_addr, register_req.listen_http_port
7776 : ))
7777 0 : .await
7778 0 : .is_err()
7779 : {
7780 : // If we have a transient DNS issue, it's up to the caller to retry their registration. Because
7781 : // we can't robustly distinguish between an intermittent issue and a totally bogus DNS situation,
7782 : // we return a soft 503 error, to encourage callers to retry past transient issues.
7783 0 : return Err(ApiError::ResourceUnavailable(
7784 0 : format!(
7785 0 : "Node {} tried to register with unknown DNS name '{}'",
7786 0 : register_req.node_id, register_req.listen_http_addr
7787 0 : )
7788 0 : .into(),
7789 0 : ));
7790 0 : }
7791 :
7792 0 : if self.config.use_https_pageserver_api && register_req.listen_https_port.is_none() {
7793 0 : return Err(ApiError::PreconditionFailed(
7794 0 : format!(
7795 0 : "Node {} has no https port, but use_https is enabled",
7796 0 : register_req.node_id
7797 0 : )
7798 0 : .into(),
7799 0 : ));
7800 0 : }
7801 :
7802 0 : if register_req.listen_grpc_addr.is_some() != register_req.listen_grpc_port.is_some() {
7803 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
7804 0 : "must specify both gRPC address and port"
7805 0 : )));
7806 0 : }
7807 :
7808 : // Ordering: we must persist the new node _before_ adding it to in-memory state.
7809 : // This ensures that before we use it for anything or expose it via any external
7810 : // API, it is guaranteed to be available after a restart.
7811 0 : let new_node = Node::new(
7812 0 : register_req.node_id,
7813 0 : register_req.listen_http_addr,
7814 0 : register_req.listen_http_port,
7815 0 : register_req.listen_https_port,
7816 0 : register_req.listen_pg_addr,
7817 0 : register_req.listen_pg_port,
7818 0 : register_req.listen_grpc_addr,
7819 0 : register_req.listen_grpc_port,
7820 0 : register_req.availability_zone_id.clone(),
7821 0 : self.config.use_https_pageserver_api,
7822 : );
7823 0 : let new_node = match new_node {
7824 0 : Ok(new_node) => new_node,
7825 0 : Err(error) => return Err(ApiError::InternalServerError(error)),
7826 : };
7827 :
7828 0 : match registration_status {
7829 : RegistrationStatus::New => {
7830 0 : self.persistence.insert_node(&new_node).await.map_err(|e| {
7831 0 : if matches!(
7832 0 : e,
7833 : crate::persistence::DatabaseError::Query(
7834 : diesel::result::Error::DatabaseError(
7835 : diesel::result::DatabaseErrorKind::UniqueViolation,
7836 : _,
7837 : )
7838 : )
7839 : ) {
7840 : // The node can be deleted by tombstone API, and not show up in the list of nodes.
7841 : // If you see this error, check tombstones first.
7842 0 : ApiError::Conflict(format!("Node {} is already exists", new_node.get_id()))
7843 : } else {
7844 0 : ApiError::from(e)
7845 : }
7846 0 : })?;
7847 : }
7848 : RegistrationStatus::NeedUpdate => {
7849 0 : self.persistence
7850 0 : .update_node_on_registration(
7851 0 : register_req.node_id,
7852 0 : register_req.listen_https_port,
7853 0 : )
7854 0 : .await?
7855 : }
7856 0 : _ => unreachable!("Other statuses have been processed earlier"),
7857 : }
7858 :
7859 0 : let mut locked = self.inner.write().unwrap();
7860 0 : let mut new_nodes = (*locked.nodes).clone();
7861 :
7862 0 : locked.scheduler.node_upsert(&new_node);
7863 0 : new_nodes.insert(register_req.node_id, new_node);
7864 :
7865 0 : locked.nodes = Arc::new(new_nodes);
7866 :
7867 0 : metrics::METRICS_REGISTRY
7868 0 : .metrics_group
7869 0 : .storage_controller_pageserver_nodes
7870 0 : .set(locked.nodes.len() as i64);
7871 0 : metrics::METRICS_REGISTRY
7872 0 : .metrics_group
7873 0 : .storage_controller_https_pageserver_nodes
7874 0 : .set(locked.nodes.values().filter(|n| n.has_https_port()).count() as i64);
7875 :
7876 0 : match registration_status {
7877 : RegistrationStatus::New => {
7878 0 : tracing::info!(
7879 0 : "Registered pageserver {} ({}), now have {} pageservers",
7880 : register_req.node_id,
7881 : register_req.availability_zone_id,
7882 0 : locked.nodes.len()
7883 : );
7884 : }
7885 : RegistrationStatus::NeedUpdate => {
7886 0 : tracing::info!(
7887 0 : "Re-registered and updated node {} ({})",
7888 : register_req.node_id,
7889 : register_req.availability_zone_id,
7890 : );
7891 : }
7892 0 : _ => unreachable!("Other statuses have been processed earlier"),
7893 : }
7894 0 : Ok(())
7895 0 : }
7896 :
7897 : /// Configure in-memory and persistent state of a node as requested
7898 : ///
7899 : /// Note that this function does not trigger any immediate side effects in response
7900 : /// to the changes. That part is handled by [`Self::handle_node_availability_transition`].
7901 0 : async fn node_state_configure(
7902 0 : &self,
7903 0 : node_id: NodeId,
7904 0 : availability: Option<NodeAvailability>,
7905 0 : scheduling: Option<NodeSchedulingPolicy>,
7906 0 : node_lock: &TracingExclusiveGuard<NodeOperations>,
7907 0 : ) -> Result<AvailabilityTransition, ApiError> {
7908 0 : if let Some(scheduling) = scheduling {
7909 : // Scheduling is a persistent part of Node: we must write updates to the database before
7910 : // applying them in memory
7911 0 : self.persistence
7912 0 : .update_node_scheduling_policy(node_id, scheduling)
7913 0 : .await?;
7914 0 : }
7915 :
7916 : // If we're activating a node, then before setting it active we must reconcile any shard locations
7917 : // on that node, in case it is out of sync, e.g. due to being unavailable during controller startup,
7918 : // by calling [`Self::node_activate_reconcile`]
7919 : //
7920 : // The transition we calculate here remains valid later in the function because we hold the op lock on the node:
7921 : // nothing else can mutate its availability while we run.
7922 0 : let availability_transition = if let Some(input_availability) = availability.as_ref() {
7923 0 : let (activate_node, availability_transition) = {
7924 0 : let locked = self.inner.read().unwrap();
7925 0 : let Some(node) = locked.nodes.get(&node_id) else {
7926 0 : return Err(ApiError::NotFound(
7927 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
7928 0 : ));
7929 : };
7930 :
7931 0 : (
7932 0 : node.clone(),
7933 0 : node.get_availability_transition(input_availability),
7934 0 : )
7935 : };
7936 :
7937 0 : if matches!(availability_transition, AvailabilityTransition::ToActive) {
7938 0 : self.node_activate_reconcile(activate_node, node_lock)
7939 0 : .await?;
7940 0 : }
7941 0 : availability_transition
7942 : } else {
7943 0 : AvailabilityTransition::Unchanged
7944 : };
7945 :
7946 : // Apply changes from the request to our in-memory state for the Node
7947 0 : let mut locked = self.inner.write().unwrap();
7948 0 : let (nodes, _tenants, scheduler) = locked.parts_mut();
7949 :
7950 0 : let mut new_nodes = (**nodes).clone();
7951 :
7952 0 : let Some(node) = new_nodes.get_mut(&node_id) else {
7953 0 : return Err(ApiError::NotFound(
7954 0 : anyhow::anyhow!("Node not registered").into(),
7955 0 : ));
7956 : };
7957 :
7958 0 : if let Some(availability) = availability {
7959 0 : node.set_availability(availability);
7960 0 : }
7961 :
7962 0 : if let Some(scheduling) = scheduling {
7963 0 : node.set_scheduling(scheduling);
7964 0 : }
7965 :
7966 : // Update the scheduler, in case the elegibility of the node for new shards has changed
7967 0 : scheduler.node_upsert(node);
7968 :
7969 0 : let new_nodes = Arc::new(new_nodes);
7970 0 : locked.nodes = new_nodes;
7971 :
7972 0 : Ok(availability_transition)
7973 0 : }
7974 :
7975 : /// Handle availability transition of one node
7976 : ///
7977 : /// Note that you should first call [`Self::node_state_configure`] to update
7978 : /// the in-memory state referencing that node. If you need to handle more than one transition
7979 : /// consider using [`Self::handle_node_availability_transitions`].
7980 0 : async fn handle_node_availability_transition(
7981 0 : &self,
7982 0 : node_id: NodeId,
7983 0 : transition: AvailabilityTransition,
7984 0 : _node_lock: &TracingExclusiveGuard<NodeOperations>,
7985 0 : ) -> Result<(), ApiError> {
7986 : // Modify scheduling state for any Tenants that are affected by a change in the node's availability state.
7987 0 : match transition {
7988 : AvailabilityTransition::ToOffline => {
7989 0 : tracing::info!("Node {} transition to offline", node_id);
7990 :
7991 0 : let mut locked = self.inner.write().unwrap();
7992 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
7993 :
7994 0 : let mut tenants_affected: usize = 0;
7995 :
7996 0 : for (_tenant_id, mut schedule_context, shards) in
7997 0 : TenantShardExclusiveIterator::new(tenants, ScheduleMode::Normal)
7998 : {
7999 0 : for tenant_shard in shards {
8000 0 : let tenant_shard_id = tenant_shard.tenant_shard_id;
8001 0 : if let Some(observed_loc) =
8002 0 : tenant_shard.observed.locations.get_mut(&node_id)
8003 0 : {
8004 0 : // When a node goes offline, we set its observed configuration to None, indicating unknown: we will
8005 0 : // not assume our knowledge of the node's configuration is accurate until it comes back online
8006 0 : observed_loc.conf = None;
8007 0 : }
8008 :
8009 0 : if nodes.len() == 1 {
8010 : // Special case for single-node cluster: there is no point trying to reschedule
8011 : // any tenant shards: avoid doing so, in order to avoid spewing warnings about
8012 : // failures to schedule them.
8013 0 : continue;
8014 0 : }
8015 :
8016 0 : if !nodes
8017 0 : .values()
8018 0 : .any(|n| matches!(n.may_schedule(), MaySchedule::Yes(_)))
8019 : {
8020 : // Special case for when all nodes are unavailable and/or unschedulable: there is no point
8021 : // trying to reschedule since there's nowhere else to go. Without this
8022 : // branch we incorrectly detach tenants in response to node unavailability.
8023 0 : continue;
8024 0 : }
8025 :
8026 0 : if tenant_shard.intent.demote_attached(scheduler, node_id) {
8027 0 : tenant_shard.sequence = tenant_shard.sequence.next();
8028 :
8029 0 : match tenant_shard.schedule(scheduler, &mut schedule_context) {
8030 0 : Err(e) => {
8031 : // It is possible that some tenants will become unschedulable when too many pageservers
8032 : // go offline: in this case there isn't much we can do other than make the issue observable.
8033 : // TODO: give TenantShard a scheduling error attribute to be queried later.
8034 0 : tracing::warn!(%tenant_shard_id, "Scheduling error when marking pageserver {} offline: {e}", node_id);
8035 : }
8036 : Ok(()) => {
8037 0 : if self
8038 0 : .maybe_reconcile_shard(
8039 0 : tenant_shard,
8040 0 : nodes,
8041 0 : ReconcilerPriority::Normal,
8042 0 : )
8043 0 : .is_some()
8044 0 : {
8045 0 : tenants_affected += 1;
8046 0 : };
8047 : }
8048 : }
8049 0 : }
8050 : }
8051 : }
8052 0 : tracing::info!(
8053 0 : "Launched {} reconciler tasks for tenants affected by node {} going offline",
8054 : tenants_affected,
8055 : node_id
8056 : )
8057 : }
8058 : AvailabilityTransition::ToActive => {
8059 0 : tracing::info!("Node {} transition to active", node_id);
8060 :
8061 0 : let mut locked = self.inner.write().unwrap();
8062 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
8063 :
8064 : // When a node comes back online, we must reconcile any tenant that has a None observed
8065 : // location on the node.
8066 0 : for tenant_shard in tenants.values_mut() {
8067 : // If a reconciliation is already in progress, rely on the previous scheduling
8068 : // decision and skip triggering a new reconciliation.
8069 0 : if tenant_shard.reconciler.is_some() {
8070 0 : continue;
8071 0 : }
8072 :
8073 0 : if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
8074 0 : if observed_loc.conf.is_none() {
8075 0 : self.maybe_reconcile_shard(
8076 0 : tenant_shard,
8077 0 : nodes,
8078 0 : ReconcilerPriority::Normal,
8079 0 : );
8080 0 : }
8081 0 : }
8082 : }
8083 :
8084 : // TODO: in the background, we should balance work back onto this pageserver
8085 : }
8086 : // No action required for the intermediate unavailable state.
8087 : // When we transition into active or offline from the unavailable state,
8088 : // the correct handling above will kick in.
8089 : AvailabilityTransition::ToWarmingUpFromActive => {
8090 0 : tracing::info!("Node {} transition to unavailable from active", node_id);
8091 : }
8092 : AvailabilityTransition::ToWarmingUpFromOffline => {
8093 0 : tracing::info!("Node {} transition to unavailable from offline", node_id);
8094 : }
8095 : AvailabilityTransition::Unchanged => {
8096 0 : tracing::debug!("Node {} no availability change during config", node_id);
8097 : }
8098 : }
8099 :
8100 0 : Ok(())
8101 0 : }
8102 :
8103 : /// Handle availability transition for multiple nodes
8104 : ///
8105 : /// Note that you should first call [`Self::node_state_configure`] for
8106 : /// all nodes being handled here for the handling to use fresh in-memory state.
8107 0 : async fn handle_node_availability_transitions(
8108 0 : &self,
8109 0 : transitions: Vec<(
8110 0 : NodeId,
8111 0 : TracingExclusiveGuard<NodeOperations>,
8112 0 : AvailabilityTransition,
8113 0 : )>,
8114 0 : ) -> Result<(), Vec<(NodeId, ApiError)>> {
8115 0 : let mut errors = Vec::default();
8116 0 : for (node_id, node_lock, transition) in transitions {
8117 0 : let res = self
8118 0 : .handle_node_availability_transition(node_id, transition, &node_lock)
8119 0 : .await;
8120 0 : if let Err(err) = res {
8121 0 : errors.push((node_id, err));
8122 0 : }
8123 : }
8124 :
8125 0 : if errors.is_empty() {
8126 0 : Ok(())
8127 : } else {
8128 0 : Err(errors)
8129 : }
8130 0 : }
8131 :
8132 0 : pub(crate) async fn node_configure(
8133 0 : &self,
8134 0 : node_id: NodeId,
8135 0 : availability: Option<NodeAvailability>,
8136 0 : scheduling: Option<NodeSchedulingPolicy>,
8137 0 : ) -> Result<(), ApiError> {
8138 0 : let node_lock =
8139 0 : trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Configure).await;
8140 :
8141 0 : let transition = self
8142 0 : .node_state_configure(node_id, availability, scheduling, &node_lock)
8143 0 : .await?;
8144 0 : self.handle_node_availability_transition(node_id, transition, &node_lock)
8145 0 : .await
8146 0 : }
8147 :
8148 : /// Wrapper around [`Self::node_configure`] which only allows changes while there is no ongoing
8149 : /// operation for HTTP api.
8150 0 : pub(crate) async fn external_node_configure(
8151 0 : &self,
8152 0 : node_id: NodeId,
8153 0 : availability: Option<NodeAvailability>,
8154 0 : scheduling: Option<NodeSchedulingPolicy>,
8155 0 : ) -> Result<(), ApiError> {
8156 : {
8157 0 : let locked = self.inner.read().unwrap();
8158 0 : if let Some(op) = locked.ongoing_operation.as_ref().map(|op| op.operation) {
8159 0 : return Err(ApiError::PreconditionFailed(
8160 0 : format!("Ongoing background operation forbids configuring: {op}").into(),
8161 0 : ));
8162 0 : }
8163 : }
8164 :
8165 0 : self.node_configure(node_id, availability, scheduling).await
8166 0 : }
8167 :
8168 0 : pub(crate) async fn start_node_delete(
8169 0 : self: &Arc<Self>,
8170 0 : node_id: NodeId,
8171 0 : force: bool,
8172 0 : ) -> Result<(), ApiError> {
8173 0 : let (ongoing_op, node_policy, schedulable_nodes_count) = {
8174 0 : let locked = self.inner.read().unwrap();
8175 0 : let nodes = &locked.nodes;
8176 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8177 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8178 0 : ))?;
8179 0 : let schedulable_nodes_count = nodes
8180 0 : .iter()
8181 0 : .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
8182 0 : .count();
8183 :
8184 : (
8185 0 : locked
8186 0 : .ongoing_operation
8187 0 : .as_ref()
8188 0 : .map(|ongoing| ongoing.operation),
8189 0 : node.get_scheduling(),
8190 0 : schedulable_nodes_count,
8191 : )
8192 : };
8193 :
8194 0 : if let Some(ongoing) = ongoing_op {
8195 0 : return Err(ApiError::PreconditionFailed(
8196 0 : format!("Background operation already ongoing for node: {ongoing}").into(),
8197 0 : ));
8198 0 : }
8199 :
8200 0 : if schedulable_nodes_count == 0 {
8201 0 : return Err(ApiError::PreconditionFailed(
8202 0 : "No other schedulable nodes to move shards".into(),
8203 0 : ));
8204 0 : }
8205 :
8206 0 : match node_policy {
8207 : NodeSchedulingPolicy::Active | NodeSchedulingPolicy::Pause => {
8208 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Deleting))
8209 0 : .await?;
8210 :
8211 0 : let cancel = self.cancel.child_token();
8212 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
8213 0 : let policy_on_start = node_policy;
8214 :
8215 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
8216 0 : operation: Operation::Delete(Delete { node_id }),
8217 0 : cancel: cancel.clone(),
8218 0 : });
8219 :
8220 0 : let span = tracing::info_span!(parent: None, "delete_node", %node_id);
8221 :
8222 0 : tokio::task::spawn(
8223 : {
8224 0 : let service = self.clone();
8225 0 : let cancel = cancel.clone();
8226 0 : async move {
8227 0 : let _gate_guard = gate_guard;
8228 :
8229 0 : scopeguard::defer! {
8230 : let prev = service.inner.write().unwrap().ongoing_operation.take();
8231 :
8232 : if let Some(Operation::Delete(removed_delete)) = prev.map(|h| h.operation) {
8233 : assert_eq!(removed_delete.node_id, node_id, "We always take the same operation");
8234 : } else {
8235 : panic!("We always remove the same operation")
8236 : }
8237 : }
8238 :
8239 0 : tracing::info!("Delete background operation starting");
8240 0 : let res = service
8241 0 : .delete_node(node_id, policy_on_start, force, cancel)
8242 0 : .await;
8243 0 : match res {
8244 : Ok(()) => {
8245 0 : tracing::info!(
8246 0 : "Delete background operation completed successfully"
8247 : );
8248 : }
8249 : Err(OperationError::Cancelled) => {
8250 0 : tracing::info!("Delete background operation was cancelled");
8251 : }
8252 0 : Err(err) => {
8253 0 : tracing::error!(
8254 0 : "Delete background operation encountered: {err}"
8255 : )
8256 : }
8257 : }
8258 0 : }
8259 : }
8260 0 : .instrument(span),
8261 : );
8262 : }
8263 : NodeSchedulingPolicy::Deleting => {
8264 0 : return Err(ApiError::Conflict(format!(
8265 0 : "Node {node_id} has delete in progress"
8266 0 : )));
8267 : }
8268 0 : policy => {
8269 0 : return Err(ApiError::PreconditionFailed(
8270 0 : format!("Node {node_id} cannot be deleted due to {policy:?} policy").into(),
8271 0 : ));
8272 : }
8273 : }
8274 :
8275 0 : Ok(())
8276 0 : }
8277 :
8278 0 : pub(crate) async fn cancel_node_delete(
8279 0 : self: &Arc<Self>,
8280 0 : node_id: NodeId,
8281 0 : ) -> Result<(), ApiError> {
8282 : {
8283 0 : let locked = self.inner.read().unwrap();
8284 0 : let nodes = &locked.nodes;
8285 0 : nodes.get(&node_id).ok_or(ApiError::NotFound(
8286 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8287 0 : ))?;
8288 : }
8289 :
8290 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
8291 0 : if let Operation::Delete(delete) = op_handler.operation {
8292 0 : if delete.node_id == node_id {
8293 0 : tracing::info!("Cancelling background delete operation for node {node_id}");
8294 0 : op_handler.cancel.cancel();
8295 0 : return Ok(());
8296 0 : }
8297 0 : }
8298 0 : }
8299 :
8300 0 : Err(ApiError::PreconditionFailed(
8301 0 : format!("Node {node_id} has no delete in progress").into(),
8302 0 : ))
8303 0 : }
8304 :
8305 0 : pub(crate) async fn start_node_drain(
8306 0 : self: &Arc<Self>,
8307 0 : node_id: NodeId,
8308 0 : ) -> Result<(), ApiError> {
8309 0 : let (ongoing_op, node_available, node_policy, schedulable_nodes_count) = {
8310 0 : let locked = self.inner.read().unwrap();
8311 0 : let nodes = &locked.nodes;
8312 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8313 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8314 0 : ))?;
8315 0 : let schedulable_nodes_count = nodes
8316 0 : .iter()
8317 0 : .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
8318 0 : .count();
8319 :
8320 : (
8321 0 : locked
8322 0 : .ongoing_operation
8323 0 : .as_ref()
8324 0 : .map(|ongoing| ongoing.operation),
8325 0 : node.is_available(),
8326 0 : node.get_scheduling(),
8327 0 : schedulable_nodes_count,
8328 : )
8329 : };
8330 :
8331 0 : if let Some(ongoing) = ongoing_op {
8332 0 : return Err(ApiError::PreconditionFailed(
8333 0 : format!("Background operation already ongoing for node: {ongoing}").into(),
8334 0 : ));
8335 0 : }
8336 :
8337 0 : if !node_available {
8338 0 : return Err(ApiError::ResourceUnavailable(
8339 0 : format!("Node {node_id} is currently unavailable").into(),
8340 0 : ));
8341 0 : }
8342 :
8343 0 : if schedulable_nodes_count == 0 {
8344 0 : return Err(ApiError::PreconditionFailed(
8345 0 : "No other schedulable nodes to drain to".into(),
8346 0 : ));
8347 0 : }
8348 :
8349 0 : match node_policy {
8350 : NodeSchedulingPolicy::Active => {
8351 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Draining))
8352 0 : .await?;
8353 :
8354 0 : let cancel = self.cancel.child_token();
8355 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
8356 :
8357 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
8358 0 : operation: Operation::Drain(Drain { node_id }),
8359 0 : cancel: cancel.clone(),
8360 0 : });
8361 :
8362 0 : let span = tracing::info_span!(parent: None, "drain_node", %node_id);
8363 :
8364 0 : tokio::task::spawn({
8365 0 : let service = self.clone();
8366 0 : let cancel = cancel.clone();
8367 0 : async move {
8368 0 : let _gate_guard = gate_guard;
8369 :
8370 0 : scopeguard::defer! {
8371 : let prev = service.inner.write().unwrap().ongoing_operation.take();
8372 :
8373 : if let Some(Operation::Drain(removed_drain)) = prev.map(|h| h.operation) {
8374 : assert_eq!(removed_drain.node_id, node_id, "We always take the same operation");
8375 : } else {
8376 : panic!("We always remove the same operation")
8377 : }
8378 : }
8379 :
8380 0 : tracing::info!("Drain background operation starting");
8381 0 : let res = service.drain_node(node_id, cancel).await;
8382 0 : match res {
8383 : Ok(()) => {
8384 0 : tracing::info!("Drain background operation completed successfully");
8385 : }
8386 : Err(OperationError::Cancelled) => {
8387 0 : tracing::info!("Drain background operation was cancelled");
8388 : }
8389 0 : Err(err) => {
8390 0 : tracing::error!("Drain background operation encountered: {err}")
8391 : }
8392 : }
8393 0 : }
8394 0 : }.instrument(span));
8395 : }
8396 : NodeSchedulingPolicy::Draining => {
8397 0 : return Err(ApiError::Conflict(format!(
8398 0 : "Node {node_id} has drain in progress"
8399 0 : )));
8400 : }
8401 0 : policy => {
8402 0 : return Err(ApiError::PreconditionFailed(
8403 0 : format!("Node {node_id} cannot be drained due to {policy:?} policy").into(),
8404 0 : ));
8405 : }
8406 : }
8407 :
8408 0 : Ok(())
8409 0 : }
8410 :
8411 0 : pub(crate) async fn cancel_node_drain(&self, node_id: NodeId) -> Result<(), ApiError> {
8412 0 : let node_available = {
8413 0 : let locked = self.inner.read().unwrap();
8414 0 : let nodes = &locked.nodes;
8415 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8416 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8417 0 : ))?;
8418 :
8419 0 : node.is_available()
8420 : };
8421 :
8422 0 : if !node_available {
8423 0 : return Err(ApiError::ResourceUnavailable(
8424 0 : format!("Node {node_id} is currently unavailable").into(),
8425 0 : ));
8426 0 : }
8427 :
8428 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
8429 0 : if let Operation::Drain(drain) = op_handler.operation {
8430 0 : if drain.node_id == node_id {
8431 0 : tracing::info!("Cancelling background drain operation for node {node_id}");
8432 0 : op_handler.cancel.cancel();
8433 0 : return Ok(());
8434 0 : }
8435 0 : }
8436 0 : }
8437 :
8438 0 : Err(ApiError::PreconditionFailed(
8439 0 : format!("Node {node_id} has no drain in progress").into(),
8440 0 : ))
8441 0 : }
8442 :
8443 0 : pub(crate) async fn start_node_fill(self: &Arc<Self>, node_id: NodeId) -> Result<(), ApiError> {
8444 0 : let (ongoing_op, node_available, node_policy, total_nodes_count) = {
8445 0 : let locked = self.inner.read().unwrap();
8446 0 : let nodes = &locked.nodes;
8447 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8448 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8449 0 : ))?;
8450 :
8451 : (
8452 0 : locked
8453 0 : .ongoing_operation
8454 0 : .as_ref()
8455 0 : .map(|ongoing| ongoing.operation),
8456 0 : node.is_available(),
8457 0 : node.get_scheduling(),
8458 0 : nodes.len(),
8459 : )
8460 : };
8461 :
8462 0 : if let Some(ongoing) = ongoing_op {
8463 0 : return Err(ApiError::PreconditionFailed(
8464 0 : format!("Background operation already ongoing for node: {ongoing}").into(),
8465 0 : ));
8466 0 : }
8467 :
8468 0 : if !node_available {
8469 0 : return Err(ApiError::ResourceUnavailable(
8470 0 : format!("Node {node_id} is currently unavailable").into(),
8471 0 : ));
8472 0 : }
8473 :
8474 0 : if total_nodes_count <= 1 {
8475 0 : return Err(ApiError::PreconditionFailed(
8476 0 : "No other nodes to fill from".into(),
8477 0 : ));
8478 0 : }
8479 :
8480 0 : match node_policy {
8481 : NodeSchedulingPolicy::Active => {
8482 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Filling))
8483 0 : .await?;
8484 :
8485 0 : let cancel = self.cancel.child_token();
8486 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
8487 :
8488 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
8489 0 : operation: Operation::Fill(Fill { node_id }),
8490 0 : cancel: cancel.clone(),
8491 0 : });
8492 :
8493 0 : let span = tracing::info_span!(parent: None, "fill_node", %node_id);
8494 :
8495 0 : tokio::task::spawn({
8496 0 : let service = self.clone();
8497 0 : let cancel = cancel.clone();
8498 0 : async move {
8499 0 : let _gate_guard = gate_guard;
8500 :
8501 0 : scopeguard::defer! {
8502 : let prev = service.inner.write().unwrap().ongoing_operation.take();
8503 :
8504 : if let Some(Operation::Fill(removed_fill)) = prev.map(|h| h.operation) {
8505 : assert_eq!(removed_fill.node_id, node_id, "We always take the same operation");
8506 : } else {
8507 : panic!("We always remove the same operation")
8508 : }
8509 : }
8510 :
8511 0 : tracing::info!("Fill background operation starting");
8512 0 : let res = service.fill_node(node_id, cancel).await;
8513 0 : match res {
8514 : Ok(()) => {
8515 0 : tracing::info!("Fill background operation completed successfully");
8516 : }
8517 : Err(OperationError::Cancelled) => {
8518 0 : tracing::info!("Fill background operation was cancelled");
8519 : }
8520 0 : Err(err) => {
8521 0 : tracing::error!("Fill background operation encountered: {err}")
8522 : }
8523 : }
8524 0 : }
8525 0 : }.instrument(span));
8526 : }
8527 : NodeSchedulingPolicy::Filling => {
8528 0 : return Err(ApiError::Conflict(format!(
8529 0 : "Node {node_id} has fill in progress"
8530 0 : )));
8531 : }
8532 0 : policy => {
8533 0 : return Err(ApiError::PreconditionFailed(
8534 0 : format!("Node {node_id} cannot be filled due to {policy:?} policy").into(),
8535 0 : ));
8536 : }
8537 : }
8538 :
8539 0 : Ok(())
8540 0 : }
8541 :
8542 0 : pub(crate) async fn cancel_node_fill(&self, node_id: NodeId) -> Result<(), ApiError> {
8543 0 : let node_available = {
8544 0 : let locked = self.inner.read().unwrap();
8545 0 : let nodes = &locked.nodes;
8546 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8547 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8548 0 : ))?;
8549 :
8550 0 : node.is_available()
8551 : };
8552 :
8553 0 : if !node_available {
8554 0 : return Err(ApiError::ResourceUnavailable(
8555 0 : format!("Node {node_id} is currently unavailable").into(),
8556 0 : ));
8557 0 : }
8558 :
8559 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
8560 0 : if let Operation::Fill(fill) = op_handler.operation {
8561 0 : if fill.node_id == node_id {
8562 0 : tracing::info!("Cancelling background drain operation for node {node_id}");
8563 0 : op_handler.cancel.cancel();
8564 0 : return Ok(());
8565 0 : }
8566 0 : }
8567 0 : }
8568 :
8569 0 : Err(ApiError::PreconditionFailed(
8570 0 : format!("Node {node_id} has no fill in progress").into(),
8571 0 : ))
8572 0 : }
8573 :
8574 : /// Like [`Self::maybe_configured_reconcile_shard`], but uses the default reconciler
8575 : /// configuration
8576 0 : fn maybe_reconcile_shard(
8577 0 : &self,
8578 0 : shard: &mut TenantShard,
8579 0 : nodes: &Arc<HashMap<NodeId, Node>>,
8580 0 : priority: ReconcilerPriority,
8581 0 : ) -> Option<ReconcilerWaiter> {
8582 0 : self.maybe_configured_reconcile_shard(shard, nodes, ReconcilerConfig::new(priority))
8583 0 : }
8584 :
8585 : /// Before constructing a Reconciler, acquire semaphore units from the appropriate concurrency limit (depends on priority)
8586 0 : fn get_reconciler_units(
8587 0 : &self,
8588 0 : priority: ReconcilerPriority,
8589 0 : ) -> Result<ReconcileUnits, TryAcquireError> {
8590 0 : let units = match priority {
8591 0 : ReconcilerPriority::Normal => self.reconciler_concurrency.clone().try_acquire_owned(),
8592 : ReconcilerPriority::High => {
8593 0 : match self
8594 0 : .priority_reconciler_concurrency
8595 0 : .clone()
8596 0 : .try_acquire_owned()
8597 : {
8598 0 : Ok(u) => Ok(u),
8599 : Err(TryAcquireError::NoPermits) => {
8600 : // If the high priority semaphore is exhausted, then high priority tasks may steal units from
8601 : // the normal priority semaphore.
8602 0 : self.reconciler_concurrency.clone().try_acquire_owned()
8603 : }
8604 0 : Err(e) => Err(e),
8605 : }
8606 : }
8607 : };
8608 :
8609 0 : units.map(ReconcileUnits::new)
8610 0 : }
8611 :
8612 : /// Wrap [`TenantShard`] reconciliation methods with acquisition of [`Gate`] and [`ReconcileUnits`],
8613 0 : fn maybe_configured_reconcile_shard(
8614 0 : &self,
8615 0 : shard: &mut TenantShard,
8616 0 : nodes: &Arc<HashMap<NodeId, Node>>,
8617 0 : reconciler_config: ReconcilerConfig,
8618 0 : ) -> Option<ReconcilerWaiter> {
8619 0 : let reconcile_needed = shard.get_reconcile_needed(nodes);
8620 :
8621 0 : let reconcile_reason = match reconcile_needed {
8622 0 : ReconcileNeeded::No => return None,
8623 0 : ReconcileNeeded::WaitExisting(waiter) => return Some(waiter),
8624 0 : ReconcileNeeded::Yes(reason) => {
8625 : // Fall through to try and acquire units for spawning reconciler
8626 0 : reason
8627 : }
8628 : };
8629 :
8630 0 : let units = match self.get_reconciler_units(reconciler_config.priority) {
8631 0 : Ok(u) => u,
8632 : Err(_) => {
8633 0 : tracing::info!(tenant_id=%shard.tenant_shard_id.tenant_id, shard_id=%shard.tenant_shard_id.shard_slug(),
8634 0 : "Concurrency limited: enqueued for reconcile later");
8635 0 : if !shard.delayed_reconcile {
8636 0 : match self.delayed_reconcile_tx.try_send(shard.tenant_shard_id) {
8637 0 : Err(TrySendError::Closed(_)) => {
8638 0 : // Weird mid-shutdown case?
8639 0 : }
8640 : Err(TrySendError::Full(_)) => {
8641 : // It is safe to skip sending our ID in the channel: we will eventually get retried by the background reconcile task.
8642 0 : tracing::warn!(
8643 0 : "Many shards are waiting to reconcile: delayed_reconcile queue is full"
8644 : );
8645 : }
8646 0 : Ok(()) => {
8647 0 : shard.delayed_reconcile = true;
8648 0 : }
8649 : }
8650 0 : }
8651 :
8652 : // We won't spawn a reconciler, but we will construct a waiter that waits for the shard's sequence
8653 : // number to advance. When this function is eventually called again and succeeds in getting units,
8654 : // it will spawn a reconciler that makes this waiter complete.
8655 0 : return Some(shard.future_reconcile_waiter());
8656 : }
8657 : };
8658 :
8659 0 : let Ok(gate_guard) = self.reconcilers_gate.enter() else {
8660 : // Gate closed: we're shutting down, drop out.
8661 0 : return None;
8662 : };
8663 :
8664 0 : shard.spawn_reconciler(
8665 0 : reconcile_reason,
8666 0 : &self.result_tx,
8667 0 : nodes,
8668 0 : &self.compute_hook,
8669 0 : reconciler_config,
8670 0 : &self.config,
8671 0 : &self.persistence,
8672 0 : units,
8673 0 : gate_guard,
8674 0 : &self.reconcilers_cancel,
8675 0 : self.http_client.clone(),
8676 : )
8677 0 : }
8678 :
8679 : /// Check all tenants for pending reconciliation work, and reconcile those in need.
8680 : /// Additionally, reschedule tenants that require it.
8681 : ///
8682 : /// Returns how many reconciliation tasks were started, or `1` if no reconciles were
8683 : /// spawned but some _would_ have been spawned if `reconciler_concurrency` units where
8684 : /// available. A return value of 0 indicates that everything is fully reconciled already.
8685 0 : fn reconcile_all(&self) -> ReconcileAllResult {
8686 0 : let mut locked = self.inner.write().unwrap();
8687 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
8688 0 : let pageservers = nodes.clone();
8689 :
8690 : // This function is an efficient place to update lazy statistics, since we are walking
8691 : // all tenants.
8692 0 : let mut pending_reconciles = 0;
8693 0 : let mut stuck_reconciles = 0;
8694 0 : let mut az_violations = 0;
8695 :
8696 : // If we find any tenants to drop from memory, stash them to offload after
8697 : // we're done traversing the map of tenants.
8698 0 : let mut drop_detached_tenants = Vec::new();
8699 :
8700 0 : let mut spawned_reconciles = 0;
8701 0 : let mut has_delayed_reconciles = false;
8702 :
8703 0 : for shard in tenants.values_mut() {
8704 : // Accumulate scheduling statistics
8705 0 : if let (Some(attached), Some(preferred)) =
8706 0 : (shard.intent.get_attached(), shard.preferred_az())
8707 : {
8708 0 : let node_az = nodes
8709 0 : .get(attached)
8710 0 : .expect("Nodes exist if referenced")
8711 0 : .get_availability_zone_id();
8712 0 : if node_az != preferred {
8713 0 : az_violations += 1;
8714 0 : }
8715 0 : }
8716 :
8717 : // Skip checking if this shard is already enqueued for reconciliation
8718 0 : if shard.delayed_reconcile && self.reconciler_concurrency.available_permits() == 0 {
8719 : // If there is something delayed, then return a nonzero count so that
8720 : // callers like reconcile_all_now do not incorrectly get the impression
8721 : // that the system is in a quiescent state.
8722 0 : has_delayed_reconciles = true;
8723 0 : pending_reconciles += 1;
8724 0 : continue;
8725 0 : }
8726 :
8727 : // Eventual consistency: if an earlier reconcile job failed, and the shard is still
8728 : // dirty, spawn another one
8729 0 : if self
8730 0 : .maybe_reconcile_shard(shard, &pageservers, ReconcilerPriority::Normal)
8731 0 : .is_some()
8732 : {
8733 0 : spawned_reconciles += 1;
8734 :
8735 0 : if shard.consecutive_reconciles_count >= MAX_CONSECUTIVE_RECONCILES {
8736 : // Count shards that are stuck, butwe still want to reconcile them.
8737 : // We don't want to consider them when deciding to run optimizations.
8738 0 : tracing::warn!(
8739 : tenant_id=%shard.tenant_shard_id.tenant_id,
8740 0 : shard_id=%shard.tenant_shard_id.shard_slug(),
8741 0 : "Shard reconciliation is stuck: {} consecutive launches",
8742 : shard.consecutive_reconciles_count
8743 : );
8744 0 : stuck_reconciles += 1;
8745 0 : }
8746 : } else {
8747 0 : if shard.delayed_reconcile {
8748 0 : // Shard wanted to reconcile but for some reason couldn't.
8749 0 : pending_reconciles += 1;
8750 0 : }
8751 :
8752 : // Reset the counter when we don't need to launch a reconcile.
8753 0 : shard.consecutive_reconciles_count = 0;
8754 : }
8755 : // If this tenant is detached, try dropping it from memory. This is usually done
8756 : // proactively in [`Self::process_results`], but we do it here to handle the edge
8757 : // case where a reconcile completes while someone else is holding an op lock for the tenant.
8758 0 : if shard.tenant_shard_id.shard_number == ShardNumber(0)
8759 0 : && shard.policy == PlacementPolicy::Detached
8760 : {
8761 0 : if let Some(guard) = self.tenant_op_locks.try_exclusive(
8762 0 : shard.tenant_shard_id.tenant_id,
8763 0 : TenantOperations::DropDetached,
8764 0 : ) {
8765 0 : drop_detached_tenants.push((shard.tenant_shard_id.tenant_id, guard));
8766 0 : }
8767 0 : }
8768 : }
8769 :
8770 : // Some metrics are calculated from SchedulerNode state, update these periodically
8771 0 : scheduler.update_metrics();
8772 :
8773 : // Process any deferred tenant drops
8774 0 : for (tenant_id, guard) in drop_detached_tenants {
8775 0 : self.maybe_drop_tenant(tenant_id, &mut locked, &guard);
8776 0 : }
8777 :
8778 0 : metrics::METRICS_REGISTRY
8779 0 : .metrics_group
8780 0 : .storage_controller_schedule_az_violation
8781 0 : .set(az_violations as i64);
8782 :
8783 0 : metrics::METRICS_REGISTRY
8784 0 : .metrics_group
8785 0 : .storage_controller_pending_reconciles
8786 0 : .set(pending_reconciles as i64);
8787 :
8788 0 : metrics::METRICS_REGISTRY
8789 0 : .metrics_group
8790 0 : .storage_controller_stuck_reconciles
8791 0 : .set(stuck_reconciles as i64);
8792 :
8793 0 : ReconcileAllResult::new(spawned_reconciles, stuck_reconciles, has_delayed_reconciles)
8794 0 : }
8795 :
8796 : /// `optimize` in this context means identifying shards which have valid scheduled locations, but
8797 : /// could be scheduled somewhere better:
8798 : /// - Cutting over to a secondary if the node with the secondary is more lightly loaded
8799 : /// * e.g. after a node fails then recovers, to move some work back to it
8800 : /// - Cutting over to a secondary if it improves the spread of shard attachments within a tenant
8801 : /// * e.g. after a shard split, the initial attached locations will all be on the node where
8802 : /// we did the split, but are probably better placed elsewhere.
8803 : /// - Creating new secondary locations if it improves the spreading of a sharded tenant
8804 : /// * e.g. after a shard split, some locations will be on the same node (where the split
8805 : /// happened), and will probably be better placed elsewhere.
8806 : ///
8807 : /// To put it more briefly: whereas the scheduler respects soft constraints in a ScheduleContext at
8808 : /// the time of scheduling, this function looks for cases where a better-scoring location is available
8809 : /// according to those same soft constraints.
8810 0 : async fn optimize_all(&self) -> usize {
8811 : // Limit on how many shards' optmizations each call to this function will execute. Combined
8812 : // with the frequency of background calls, this acts as an implicit rate limit that runs a small
8813 : // trickle of optimizations in the background, rather than executing a large number in parallel
8814 : // when a change occurs.
8815 : const MAX_OPTIMIZATIONS_EXEC_PER_PASS: usize = 16;
8816 :
8817 : // Synchronous prepare: scan shards for possible scheduling optimizations
8818 0 : let candidate_work = self.optimize_all_plan();
8819 0 : let candidate_work_len = candidate_work.len();
8820 :
8821 : // Asynchronous validate: I/O to pageservers to make sure shards are in a good state to apply validation
8822 0 : let validated_work = self.optimize_all_validate(candidate_work).await;
8823 :
8824 0 : let was_work_filtered = validated_work.len() != candidate_work_len;
8825 :
8826 : // Synchronous apply: update the shards' intent states according to validated optimisations
8827 0 : let mut reconciles_spawned = 0;
8828 0 : let mut optimizations_applied = 0;
8829 0 : let mut locked = self.inner.write().unwrap();
8830 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
8831 0 : for (tenant_shard_id, optimization) in validated_work {
8832 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
8833 : // Shard was dropped between planning and execution;
8834 0 : continue;
8835 : };
8836 0 : tracing::info!(tenant_shard_id=%tenant_shard_id, "Applying optimization: {optimization:?}");
8837 0 : if shard.apply_optimization(scheduler, optimization) {
8838 0 : optimizations_applied += 1;
8839 0 : if self
8840 0 : .maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal)
8841 0 : .is_some()
8842 0 : {
8843 0 : reconciles_spawned += 1;
8844 0 : }
8845 0 : }
8846 :
8847 0 : if optimizations_applied >= MAX_OPTIMIZATIONS_EXEC_PER_PASS {
8848 0 : break;
8849 0 : }
8850 : }
8851 :
8852 0 : if was_work_filtered {
8853 0 : // If we filtered any work out during validation, ensure we return a nonzero value to indicate
8854 0 : // to callers that the system is not in a truly quiet state, it's going to do some work as soon
8855 0 : // as these validations start passing.
8856 0 : reconciles_spawned = std::cmp::max(reconciles_spawned, 1);
8857 0 : }
8858 :
8859 0 : reconciles_spawned
8860 0 : }
8861 :
8862 0 : fn optimize_all_plan(&self) -> Vec<(TenantShardId, ScheduleOptimization)> {
8863 : // How many candidate optimizations we will generate, before evaluating them for readniess: setting
8864 : // this higher than the execution limit gives us a chance to execute some work even if the first
8865 : // few optimizations we find are not ready.
8866 : const MAX_OPTIMIZATIONS_PLAN_PER_PASS: usize = 64;
8867 :
8868 0 : let mut work = Vec::new();
8869 0 : let mut locked = self.inner.write().unwrap();
8870 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
8871 :
8872 : // We are going to plan a bunch of optimisations before applying any of them, so the
8873 : // utilisation stats on nodes will be effectively stale for the >1st optimisation we
8874 : // generate. To avoid this causing unstable migrations/flapping, it's important that the
8875 : // code in TenantShard for finding optimisations uses [`NodeAttachmentSchedulingScore::disregard_utilization`]
8876 : // to ignore the utilisation component of the score.
8877 :
8878 0 : for (_tenant_id, schedule_context, shards) in
8879 0 : TenantShardExclusiveIterator::new(tenants, ScheduleMode::Speculative)
8880 : {
8881 0 : if work.len() >= MAX_OPTIMIZATIONS_PLAN_PER_PASS {
8882 0 : break;
8883 0 : }
8884 0 : for shard in shards {
8885 0 : if work.len() >= MAX_OPTIMIZATIONS_PLAN_PER_PASS {
8886 0 : break;
8887 0 : }
8888 0 : match shard.get_scheduling_policy() {
8889 0 : ShardSchedulingPolicy::Active => {
8890 0 : // Ok to do optimization
8891 0 : }
8892 0 : ShardSchedulingPolicy::Essential if shard.get_preferred_node().is_some() => {
8893 0 : // Ok to do optimization: we are executing a graceful migration that
8894 0 : // has set preferred_node
8895 0 : }
8896 : ShardSchedulingPolicy::Essential
8897 : | ShardSchedulingPolicy::Pause
8898 : | ShardSchedulingPolicy::Stop => {
8899 : // Policy prevents optimizing this shard.
8900 0 : continue;
8901 : }
8902 : }
8903 :
8904 0 : if !matches!(shard.splitting, SplitState::Idle)
8905 0 : || matches!(shard.policy, PlacementPolicy::Detached)
8906 0 : || shard.reconciler.is_some()
8907 : {
8908 : // Do not start any optimizations while another change to the tenant is ongoing: this
8909 : // is not necessary for correctness, but simplifies operations and implicitly throttles
8910 : // optimization changes to happen in a "trickle" over time.
8911 0 : continue;
8912 0 : }
8913 :
8914 : // Fast path: we may quickly identify shards that don't have any possible optimisations
8915 0 : if !shard.maybe_optimizable(scheduler, &schedule_context) {
8916 0 : if cfg!(feature = "testing") {
8917 : // Check that maybe_optimizable doesn't disagree with the actual optimization functions.
8918 : // Only do this in testing builds because it is not a correctness-critical check, so we shouldn't
8919 : // panic in prod if we hit this, or spend cycles on it in prod.
8920 0 : assert!(
8921 0 : shard
8922 0 : .optimize_attachment(scheduler, &schedule_context)
8923 0 : .is_none()
8924 : );
8925 0 : assert!(
8926 0 : shard
8927 0 : .optimize_secondary(scheduler, &schedule_context)
8928 0 : .is_none()
8929 : );
8930 0 : }
8931 0 : continue;
8932 0 : }
8933 :
8934 0 : if let Some(optimization) =
8935 : // If idle, maybe optimize attachments: if a shard has a secondary location that is preferable to
8936 : // its primary location based on soft constraints, cut it over.
8937 0 : shard.optimize_attachment(scheduler, &schedule_context)
8938 : {
8939 0 : tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for attachment: {optimization:?}");
8940 0 : work.push((shard.tenant_shard_id, optimization));
8941 0 : break;
8942 0 : } else if let Some(optimization) =
8943 : // If idle, maybe optimize secondary locations: if a shard has a secondary location that would be
8944 : // better placed on another node, based on ScheduleContext, then adjust it. This
8945 : // covers cases like after a shard split, where we might have too many shards
8946 : // in the same tenant with secondary locations on the node where they originally split.
8947 0 : shard.optimize_secondary(scheduler, &schedule_context)
8948 : {
8949 0 : tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for secondary: {optimization:?}");
8950 0 : work.push((shard.tenant_shard_id, optimization));
8951 0 : break;
8952 0 : }
8953 : }
8954 : }
8955 :
8956 0 : work
8957 0 : }
8958 :
8959 0 : async fn optimize_all_validate(
8960 0 : &self,
8961 0 : candidate_work: Vec<(TenantShardId, ScheduleOptimization)>,
8962 0 : ) -> Vec<(TenantShardId, ScheduleOptimization)> {
8963 : // Take a clone of the node map to use outside the lock in async validation phase
8964 0 : let validation_nodes = { self.inner.read().unwrap().nodes.clone() };
8965 :
8966 0 : let mut want_secondary_status = Vec::new();
8967 :
8968 : // Validate our plans: this is an async phase where we may do I/O to pageservers to
8969 : // check that the state of locations is acceptable to run the optimization, such as
8970 : // checking that a secondary location is sufficiently warmed-up to cleanly cut over
8971 : // in a live migration.
8972 0 : let mut validated_work = Vec::new();
8973 0 : for (tenant_shard_id, optimization) in candidate_work {
8974 0 : match optimization.action {
8975 : ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
8976 : old_attached_node_id: _,
8977 0 : new_attached_node_id,
8978 : }) => {
8979 0 : match validation_nodes.get(&new_attached_node_id) {
8980 0 : None => {
8981 0 : // Node was dropped between planning and validation
8982 0 : }
8983 0 : Some(node) => {
8984 0 : if !node.is_available() {
8985 0 : tracing::info!(
8986 0 : "Skipping optimization migration of {tenant_shard_id} to {new_attached_node_id} because node unavailable"
8987 : );
8988 0 : } else {
8989 0 : // Accumulate optimizations that require fetching secondary status, so that we can execute these
8990 0 : // remote API requests concurrently.
8991 0 : want_secondary_status.push((
8992 0 : tenant_shard_id,
8993 0 : node.clone(),
8994 0 : optimization,
8995 0 : ));
8996 0 : }
8997 : }
8998 : }
8999 : }
9000 : ScheduleOptimizationAction::ReplaceSecondary(_)
9001 : | ScheduleOptimizationAction::CreateSecondary(_)
9002 : | ScheduleOptimizationAction::RemoveSecondary(_) => {
9003 : // No extra checks needed to manage secondaries: this does not interrupt client access
9004 0 : validated_work.push((tenant_shard_id, optimization))
9005 : }
9006 : };
9007 : }
9008 :
9009 : // Call into pageserver API to find out if the destination secondary location is warm enough for a reasonably smooth migration: we
9010 : // do this so that we avoid spawning a Reconciler that would have to wait minutes/hours for a destination to warm up: that reconciler
9011 : // would hold a precious reconcile semaphore unit the whole time it was waiting for the destination to warm up.
9012 0 : let results = self
9013 0 : .tenant_for_shards_api(
9014 0 : want_secondary_status
9015 0 : .iter()
9016 0 : .map(|i| (i.0, i.1.clone()))
9017 0 : .collect(),
9018 0 : |tenant_shard_id, client| async move {
9019 0 : client.tenant_secondary_status(tenant_shard_id).await
9020 0 : },
9021 : 1,
9022 : 1,
9023 : SHORT_RECONCILE_TIMEOUT,
9024 0 : &self.cancel,
9025 : )
9026 0 : .await;
9027 :
9028 0 : for ((tenant_shard_id, node, optimization), (_, secondary_status)) in
9029 0 : want_secondary_status.into_iter().zip(results.into_iter())
9030 : {
9031 0 : match secondary_status {
9032 0 : Err(e) => {
9033 0 : tracing::info!(
9034 0 : "Skipping migration of {tenant_shard_id} to {node}, error querying secondary: {e}"
9035 : );
9036 : }
9037 0 : Ok(progress) => {
9038 : // We require secondary locations to have less than 10GiB of downloads pending before we will use
9039 : // them in an optimization
9040 : const DOWNLOAD_FRESHNESS_THRESHOLD: u64 = 10 * 1024 * 1024 * 1024;
9041 :
9042 0 : if progress.heatmap_mtime.is_none()
9043 0 : || progress.bytes_total < DOWNLOAD_FRESHNESS_THRESHOLD
9044 0 : && progress.bytes_downloaded != progress.bytes_total
9045 0 : || progress.bytes_total - progress.bytes_downloaded
9046 0 : > DOWNLOAD_FRESHNESS_THRESHOLD
9047 : {
9048 0 : tracing::info!(
9049 0 : "Skipping migration of {tenant_shard_id} to {node} because secondary isn't ready: {progress:?}"
9050 : );
9051 :
9052 0 : if progress.heatmap_mtime.is_none() {
9053 : // No heatmap might mean the attached location has never uploaded one, or that
9054 : // the secondary download hasn't happened yet. This is relatively unusual in the field,
9055 : // but fairly common in tests.
9056 0 : self.kick_secondary_download(tenant_shard_id).await;
9057 0 : }
9058 : } else {
9059 : // Location looks ready: proceed
9060 0 : tracing::info!(
9061 0 : "{tenant_shard_id} secondary on {node} is warm enough for migration: {progress:?}"
9062 : );
9063 0 : validated_work.push((tenant_shard_id, optimization))
9064 : }
9065 : }
9066 : }
9067 : }
9068 :
9069 0 : validated_work
9070 0 : }
9071 :
9072 : /// Some aspects of scheduling optimisation wait for secondary locations to be warm. This
9073 : /// happens on multi-minute timescales in the field, which is fine because optimisation is meant
9074 : /// to be a lazy background thing. However, when testing, it is not practical to wait around, so
9075 : /// we have this helper to move things along faster.
9076 0 : async fn kick_secondary_download(&self, tenant_shard_id: TenantShardId) {
9077 0 : if !self.config.kick_secondary_downloads {
9078 : // No-op if kick_secondary_downloads functionaliuty is not configured
9079 0 : return;
9080 0 : }
9081 :
9082 0 : let (attached_node, secondaries) = {
9083 0 : let locked = self.inner.read().unwrap();
9084 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
9085 0 : tracing::warn!(
9086 0 : "Skipping kick of secondary download for {tenant_shard_id}: not found"
9087 : );
9088 0 : return;
9089 : };
9090 :
9091 0 : let Some(attached) = shard.intent.get_attached() else {
9092 0 : tracing::warn!(
9093 0 : "Skipping kick of secondary download for {tenant_shard_id}: no attached"
9094 : );
9095 0 : return;
9096 : };
9097 :
9098 0 : let secondaries = shard
9099 0 : .intent
9100 0 : .get_secondary()
9101 0 : .iter()
9102 0 : .map(|n| locked.nodes.get(n).unwrap().clone())
9103 0 : .collect::<Vec<_>>();
9104 :
9105 0 : (locked.nodes.get(attached).unwrap().clone(), secondaries)
9106 : };
9107 :
9108 : // Make remote API calls to upload + download heatmaps: we ignore errors because this is just
9109 : // a 'kick' to let scheduling optimisation run more promptly.
9110 0 : match attached_node
9111 0 : .with_client_retries(
9112 0 : |client| async move { client.tenant_heatmap_upload(tenant_shard_id).await },
9113 0 : &self.http_client,
9114 0 : &self.config.pageserver_jwt_token,
9115 : 3,
9116 : 10,
9117 : SHORT_RECONCILE_TIMEOUT,
9118 0 : &self.cancel,
9119 : )
9120 0 : .await
9121 : {
9122 0 : Some(Err(e)) => {
9123 0 : tracing::info!(
9124 0 : "Failed to upload heatmap from {attached_node} for {tenant_shard_id}: {e}"
9125 : );
9126 : }
9127 : None => {
9128 0 : tracing::info!(
9129 0 : "Cancelled while uploading heatmap from {attached_node} for {tenant_shard_id}"
9130 : );
9131 : }
9132 : Some(Ok(_)) => {
9133 0 : tracing::info!(
9134 0 : "Successfully uploaded heatmap from {attached_node} for {tenant_shard_id}"
9135 : );
9136 : }
9137 : }
9138 :
9139 0 : for secondary_node in secondaries {
9140 0 : match secondary_node
9141 0 : .with_client_retries(
9142 0 : |client| async move {
9143 0 : client
9144 0 : .tenant_secondary_download(
9145 0 : tenant_shard_id,
9146 0 : Some(Duration::from_secs(1)),
9147 0 : )
9148 0 : .await
9149 0 : },
9150 0 : &self.http_client,
9151 0 : &self.config.pageserver_jwt_token,
9152 : 3,
9153 : 10,
9154 : SHORT_RECONCILE_TIMEOUT,
9155 0 : &self.cancel,
9156 : )
9157 0 : .await
9158 : {
9159 0 : Some(Err(e)) => {
9160 0 : tracing::info!(
9161 0 : "Failed to download heatmap from {secondary_node} for {tenant_shard_id}: {e}"
9162 : );
9163 : }
9164 : None => {
9165 0 : tracing::info!(
9166 0 : "Cancelled while downloading heatmap from {secondary_node} for {tenant_shard_id}"
9167 : );
9168 : }
9169 0 : Some(Ok(progress)) => {
9170 0 : tracing::info!(
9171 0 : "Successfully downloaded heatmap from {secondary_node} for {tenant_shard_id}: {progress:?}"
9172 : );
9173 : }
9174 : }
9175 : }
9176 0 : }
9177 :
9178 : /// Asynchronously split a tenant that's eligible for automatic splits. At most one tenant will
9179 : /// be split per call.
9180 : ///
9181 : /// Two sets of criteria are used: initial splits and size-based splits (in that order).
9182 : /// Initial splits are used to eagerly split unsharded tenants that may be performing initial
9183 : /// ingestion, since sharded tenants have significantly better ingestion throughput. Size-based
9184 : /// splits are used to bound the maximum shard size and balance out load.
9185 : ///
9186 : /// Splits are based on max_logical_size, i.e. the logical size of the largest timeline in a
9187 : /// tenant. We use this instead of the total logical size because branches will duplicate
9188 : /// logical size without actually using more storage. We could also use visible physical size,
9189 : /// but this might overestimate tenants that frequently churn branches.
9190 : ///
9191 : /// Initial splits (initial_split_threshold):
9192 : /// * Applies to tenants with 1 shard.
9193 : /// * The largest timeline (max_logical_size) exceeds initial_split_threshold.
9194 : /// * Splits into initial_split_shards.
9195 : ///
9196 : /// Size-based splits (split_threshold):
9197 : /// * Applies to all tenants.
9198 : /// * The largest timeline (max_logical_size) divided by shard count exceeds split_threshold.
9199 : /// * Splits such that max_logical_size / shard_count <= split_threshold, in powers of 2.
9200 : ///
9201 : /// Tenant shards are ordered by descending max_logical_size, first initial split candidates
9202 : /// then size-based split candidates. The first matching candidate is split.
9203 : ///
9204 : /// The shard count is clamped to max_split_shards. If a candidate is eligible for both initial
9205 : /// and size-based splits, the largest shard count will be used.
9206 : ///
9207 : /// An unsharded tenant will get DEFAULT_STRIPE_SIZE, regardless of what its ShardIdentity says.
9208 : /// A sharded tenant will retain its stripe size, as splits do not allow changing it.
9209 : ///
9210 : /// TODO: consider spawning multiple splits in parallel: this is only called once every 20
9211 : /// seconds, so a large backlog can take a long time, and if a tenant fails to split it will
9212 : /// block all other splits.
9213 0 : async fn autosplit_tenants(self: &Arc<Self>) {
9214 : // If max_split_shards is set to 0 or 1, we can't split.
9215 0 : let max_split_shards = self.config.max_split_shards;
9216 0 : if max_split_shards <= 1 {
9217 0 : return;
9218 0 : }
9219 :
9220 : // If initial_split_shards is set to 0 or 1, disable initial splits.
9221 0 : let mut initial_split_threshold = self.config.initial_split_threshold.unwrap_or(0);
9222 0 : let initial_split_shards = self.config.initial_split_shards;
9223 0 : if initial_split_shards <= 1 {
9224 0 : initial_split_threshold = 0;
9225 0 : }
9226 :
9227 : // If no split_threshold nor initial_split_threshold, disable autosplits.
9228 0 : let split_threshold = self.config.split_threshold.unwrap_or(0);
9229 0 : if split_threshold == 0 && initial_split_threshold == 0 {
9230 0 : return;
9231 0 : }
9232 :
9233 : // Fetch split candidates in prioritized order.
9234 : //
9235 : // If initial splits are enabled, fetch eligible tenants first. We prioritize initial splits
9236 : // over size-based splits, since these are often performing initial ingestion and rely on
9237 : // splits to improve ingest throughput.
9238 0 : let mut candidates = Vec::new();
9239 :
9240 0 : if initial_split_threshold > 0 {
9241 : // Initial splits: fetch tenants with 1 shard where the logical size of the largest
9242 : // timeline exceeds the initial split threshold.
9243 0 : let initial_candidates = self
9244 0 : .get_top_tenant_shards(&TopTenantShardsRequest {
9245 0 : order_by: TenantSorting::MaxLogicalSize,
9246 0 : limit: 10,
9247 0 : where_shards_lt: Some(ShardCount(2)),
9248 0 : where_gt: Some(initial_split_threshold),
9249 0 : })
9250 0 : .await;
9251 0 : candidates.extend(initial_candidates);
9252 0 : }
9253 :
9254 0 : if split_threshold > 0 {
9255 : // Size-based splits: fetch tenants where the logical size of the largest timeline
9256 : // divided by shard count exceeds the split threshold.
9257 : //
9258 : // max_logical_size is only tracked on shard 0, and contains the total logical size
9259 : // across all shards. We have to order and filter by MaxLogicalSizePerShard, i.e.
9260 : // max_logical_size / shard_count, such that we only receive tenants that are actually
9261 : // eligible for splits. But we still use max_logical_size for later split calculations.
9262 0 : let size_candidates = self
9263 0 : .get_top_tenant_shards(&TopTenantShardsRequest {
9264 0 : order_by: TenantSorting::MaxLogicalSizePerShard,
9265 0 : limit: 10,
9266 0 : where_shards_lt: Some(ShardCount(max_split_shards)),
9267 0 : where_gt: Some(split_threshold),
9268 0 : })
9269 0 : .await;
9270 : #[cfg(feature = "testing")]
9271 0 : assert!(
9272 0 : size_candidates.iter().all(|c| c.id.is_shard_zero()),
9273 0 : "MaxLogicalSizePerShard returned non-zero shard: {size_candidates:?}",
9274 : );
9275 0 : candidates.extend(size_candidates);
9276 0 : }
9277 :
9278 : // Filter out tenants in a prohibiting scheduling modes
9279 : // and tenants with an ongoing import.
9280 : //
9281 : // Note that the import check here is oportunistic. An import might start
9282 : // after the check before we actually update [`TenantShard::splitting`].
9283 : // [`Self::tenant_shard_split`] checks the database whilst holding the exclusive
9284 : // tenant lock. Imports might take a long time, so the check here allows us
9285 : // to split something else instead of trying the same shard over and over.
9286 : {
9287 0 : let state = self.inner.read().unwrap();
9288 0 : candidates.retain(|i| {
9289 0 : let shard = state.tenants.get(&i.id);
9290 0 : match shard {
9291 0 : Some(t) => {
9292 0 : t.get_scheduling_policy() == ShardSchedulingPolicy::Active
9293 0 : && t.importing == TimelineImportState::Idle
9294 : }
9295 0 : None => false,
9296 : }
9297 0 : });
9298 : }
9299 :
9300 : // Pick the first candidate to split. This will generally always be the first one in
9301 : // candidates, but we defensively skip candidates that end up not actually splitting.
9302 0 : let Some((candidate, new_shard_count)) = candidates
9303 0 : .into_iter()
9304 0 : .filter_map(|candidate| {
9305 0 : let new_shard_count = Self::compute_split_shards(ShardSplitInputs {
9306 0 : shard_count: candidate.id.shard_count,
9307 0 : max_logical_size: candidate.max_logical_size,
9308 0 : split_threshold,
9309 0 : max_split_shards,
9310 0 : initial_split_threshold,
9311 0 : initial_split_shards,
9312 0 : });
9313 0 : new_shard_count.map(|shards| (candidate, shards.count()))
9314 0 : })
9315 0 : .next()
9316 : else {
9317 0 : debug!("no split-eligible tenants found");
9318 0 : return;
9319 : };
9320 :
9321 : // Retain the stripe size of sharded tenants, as splits don't allow changing it. Otherwise,
9322 : // use DEFAULT_STRIPE_SIZE for unsharded tenants -- their stripe size doesn't really matter,
9323 : // and if we change the default stripe size we want to use the new default rather than an
9324 : // old, persisted stripe size.
9325 0 : let new_stripe_size = match candidate.id.shard_count.count() {
9326 0 : 0 => panic!("invalid shard count 0"),
9327 0 : 1 => Some(DEFAULT_STRIPE_SIZE),
9328 0 : 2.. => None,
9329 : };
9330 :
9331 : // We spawn a task to run this, so it's exactly like some external API client requesting
9332 : // it. We don't want to block the background reconcile loop on this.
9333 0 : let old_shard_count = candidate.id.shard_count.count();
9334 0 : info!(
9335 0 : "auto-splitting tenant {old_shard_count} → {new_shard_count} shards, \
9336 0 : current size {candidate:?} (split_threshold={split_threshold} \
9337 0 : initial_split_threshold={initial_split_threshold})"
9338 : );
9339 :
9340 0 : let this = self.clone();
9341 0 : tokio::spawn(
9342 0 : async move {
9343 0 : match this
9344 0 : .tenant_shard_split(
9345 0 : candidate.id.tenant_id,
9346 0 : TenantShardSplitRequest {
9347 0 : new_shard_count,
9348 0 : new_stripe_size,
9349 0 : },
9350 0 : )
9351 0 : .await
9352 : {
9353 : Ok(_) => {
9354 0 : info!("successful auto-split {old_shard_count} → {new_shard_count} shards")
9355 : }
9356 0 : Err(err) => error!("auto-split failed: {err}"),
9357 : }
9358 0 : }
9359 0 : .instrument(info_span!("auto_split", tenant_id=%candidate.id.tenant_id)),
9360 : );
9361 0 : }
9362 :
9363 : /// Returns the number of shards to split a tenant into, or None if the tenant shouldn't split,
9364 : /// based on the total logical size of the largest timeline summed across all shards. Uses the
9365 : /// larger of size-based and initial splits, clamped to max_split_shards.
9366 : ///
9367 : /// NB: the thresholds are exclusive, since TopTenantShardsRequest uses where_gt.
9368 25 : fn compute_split_shards(inputs: ShardSplitInputs) -> Option<ShardCount> {
9369 : let ShardSplitInputs {
9370 25 : shard_count,
9371 25 : max_logical_size,
9372 25 : split_threshold,
9373 25 : max_split_shards,
9374 25 : initial_split_threshold,
9375 25 : initial_split_shards,
9376 25 : } = inputs;
9377 :
9378 25 : let mut new_shard_count: u8 = shard_count.count();
9379 :
9380 : // Size-based splits. Ensures max_logical_size / new_shard_count <= split_threshold, using
9381 : // power-of-two shard counts.
9382 : //
9383 : // If the current shard count is not a power of two, and does not exceed split_threshold,
9384 : // then we leave it alone rather than forcing a power-of-two split.
9385 25 : if split_threshold > 0
9386 18 : && max_logical_size.div_ceil(split_threshold) > shard_count.count() as u64
9387 12 : {
9388 12 : new_shard_count = max_logical_size
9389 12 : .div_ceil(split_threshold)
9390 12 : .checked_next_power_of_two()
9391 12 : .unwrap_or(u8::MAX as u64)
9392 12 : .try_into()
9393 12 : .unwrap_or(u8::MAX);
9394 13 : }
9395 :
9396 : // Initial splits. Use the larger of size-based and initial split shard counts. This only
9397 : // applies to unsharded tenants, i.e. changes to initial_split_threshold or
9398 : // initial_split_shards are not retroactive for sharded tenants.
9399 25 : if initial_split_threshold > 0
9400 14 : && shard_count.count() <= 1
9401 11 : && max_logical_size > initial_split_threshold
9402 8 : {
9403 8 : new_shard_count = new_shard_count.max(initial_split_shards);
9404 17 : }
9405 :
9406 : // Clamp to max shards.
9407 25 : new_shard_count = new_shard_count.min(max_split_shards);
9408 :
9409 : // Don't split if we're not increasing the shard count.
9410 25 : if new_shard_count <= shard_count.count() {
9411 10 : return None;
9412 15 : }
9413 :
9414 15 : Some(ShardCount(new_shard_count))
9415 25 : }
9416 :
9417 : /// Fetches the top tenant shards from every available node, in descending order of
9418 : /// max logical size. Offline nodes are skipped, and any errors from available nodes
9419 : /// will be logged and ignored.
9420 0 : async fn get_top_tenant_shards(
9421 0 : &self,
9422 0 : request: &TopTenantShardsRequest,
9423 0 : ) -> Vec<TopTenantShardItem> {
9424 0 : let nodes = self
9425 0 : .inner
9426 0 : .read()
9427 0 : .unwrap()
9428 0 : .nodes
9429 0 : .values()
9430 0 : .filter(|node| node.is_available())
9431 0 : .cloned()
9432 0 : .collect_vec();
9433 :
9434 0 : let mut futures = FuturesUnordered::new();
9435 0 : for node in nodes {
9436 0 : futures.push(async move {
9437 0 : node.with_client_retries(
9438 0 : |client| async move { client.top_tenant_shards(request.clone()).await },
9439 0 : &self.http_client,
9440 0 : &self.config.pageserver_jwt_token,
9441 : 3,
9442 : 3,
9443 0 : Duration::from_secs(5),
9444 0 : &self.cancel,
9445 : )
9446 0 : .await
9447 0 : });
9448 : }
9449 :
9450 0 : let mut top = Vec::new();
9451 0 : while let Some(output) = futures.next().await {
9452 0 : match output {
9453 0 : Some(Ok(response)) => top.extend(response.shards),
9454 0 : Some(Err(mgmt_api::Error::Cancelled)) => {}
9455 0 : Some(Err(err)) => warn!("failed to fetch top tenants: {err}"),
9456 0 : None => {} // node is shutting down
9457 : }
9458 : }
9459 :
9460 0 : top.sort_by_key(|i| i.max_logical_size);
9461 0 : top.reverse();
9462 0 : top
9463 0 : }
9464 :
9465 : /// Useful for tests: run whatever work a background [`Self::reconcile_all`] would have done, but
9466 : /// also wait for any generated Reconcilers to complete. Calling this until it returns zero should
9467 : /// put the system into a quiescent state where future background reconciliations won't do anything.
9468 0 : pub(crate) async fn reconcile_all_now(&self) -> Result<usize, ReconcileWaitError> {
9469 0 : let reconcile_all_result = self.reconcile_all();
9470 0 : let mut spawned_reconciles = reconcile_all_result.spawned_reconciles;
9471 0 : if reconcile_all_result.can_run_optimizations() {
9472 : // Only optimize when we are otherwise idle
9473 0 : let optimization_reconciles = self.optimize_all().await;
9474 0 : spawned_reconciles += optimization_reconciles;
9475 0 : }
9476 :
9477 0 : let waiters = {
9478 0 : let mut waiters = Vec::new();
9479 0 : let locked = self.inner.read().unwrap();
9480 0 : for (_tenant_shard_id, shard) in locked.tenants.iter() {
9481 0 : if let Some(waiter) = shard.get_waiter() {
9482 0 : waiters.push(waiter);
9483 0 : }
9484 : }
9485 0 : waiters
9486 : };
9487 :
9488 0 : let waiter_count = waiters.len();
9489 0 : match self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
9490 0 : Ok(()) => {}
9491 0 : Err(e) => {
9492 0 : if let ReconcileWaitError::Failed(_, reconcile_error) = &e {
9493 0 : match **reconcile_error {
9494 : ReconcileError::Cancel
9495 0 : | ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
9496 0 : // Ignore reconciler cancel errors: this reconciler might have shut down
9497 0 : // because some other change superceded it. We will return a nonzero number,
9498 0 : // so the caller knows they might have to call again to quiesce the system.
9499 0 : }
9500 : _ => {
9501 0 : return Err(e);
9502 : }
9503 : }
9504 : } else {
9505 0 : return Err(e);
9506 : }
9507 : }
9508 : };
9509 :
9510 0 : tracing::info!(
9511 0 : "{} reconciles in reconcile_all, {} waiters",
9512 : spawned_reconciles,
9513 : waiter_count
9514 : );
9515 :
9516 0 : Ok(std::cmp::max(waiter_count, spawned_reconciles))
9517 0 : }
9518 :
9519 0 : async fn stop_reconciliations(&self, reason: StopReconciliationsReason) {
9520 : // Cancel all on-going reconciles and wait for them to exit the gate.
9521 0 : tracing::info!("{reason}: cancelling and waiting for in-flight reconciles");
9522 0 : self.reconcilers_cancel.cancel();
9523 0 : self.reconcilers_gate.close().await;
9524 :
9525 : // Signal the background loop in [`Service::process_results`] to exit once
9526 : // it has proccessed the results from all the reconciles we cancelled earlier.
9527 0 : tracing::info!("{reason}: processing results from previously in-flight reconciles");
9528 0 : self.result_tx.send(ReconcileResultRequest::Stop).ok();
9529 0 : self.result_tx.closed().await;
9530 0 : }
9531 :
9532 0 : pub async fn shutdown(&self) {
9533 0 : self.stop_reconciliations(StopReconciliationsReason::ShuttingDown)
9534 0 : .await;
9535 :
9536 : // Background tasks hold gate guards: this notifies them of the cancellation and
9537 : // waits for them all to complete.
9538 0 : tracing::info!("Shutting down: cancelling and waiting for background tasks to exit");
9539 0 : self.cancel.cancel();
9540 0 : self.gate.close().await;
9541 0 : }
9542 :
9543 : /// Spot check the download lag for a secondary location of a shard.
9544 : /// Should be used as a heuristic, since it's not always precise: the
9545 : /// secondary might have not downloaded the new heat map yet and, hence,
9546 : /// is not aware of the lag.
9547 : ///
9548 : /// Returns:
9549 : /// * Ok(None) if the lag could not be determined from the status,
9550 : /// * Ok(Some(_)) if the lag could be determind
9551 : /// * Err on failures to query the pageserver.
9552 0 : async fn secondary_lag(
9553 0 : &self,
9554 0 : secondary: &NodeId,
9555 0 : tenant_shard_id: TenantShardId,
9556 0 : ) -> Result<Option<u64>, mgmt_api::Error> {
9557 0 : let nodes = self.inner.read().unwrap().nodes.clone();
9558 0 : let node = nodes.get(secondary).ok_or(mgmt_api::Error::ApiError(
9559 0 : StatusCode::NOT_FOUND,
9560 0 : format!("Node with id {secondary} not found"),
9561 0 : ))?;
9562 :
9563 0 : match node
9564 0 : .with_client_retries(
9565 0 : |client| async move { client.tenant_secondary_status(tenant_shard_id).await },
9566 0 : &self.http_client,
9567 0 : &self.config.pageserver_jwt_token,
9568 : 1,
9569 : 3,
9570 0 : Duration::from_millis(250),
9571 0 : &self.cancel,
9572 : )
9573 0 : .await
9574 : {
9575 0 : Some(Ok(status)) => match status.heatmap_mtime {
9576 0 : Some(_) => Ok(Some(status.bytes_total - status.bytes_downloaded)),
9577 0 : None => Ok(None),
9578 : },
9579 0 : Some(Err(e)) => Err(e),
9580 0 : None => Err(mgmt_api::Error::Cancelled),
9581 : }
9582 0 : }
9583 :
9584 : /// Drain a node by moving the shards attached to it as primaries.
9585 : /// This is a long running operation and it should run as a separate Tokio task.
9586 0 : pub(crate) async fn drain_node(
9587 0 : self: &Arc<Self>,
9588 0 : node_id: NodeId,
9589 0 : cancel: CancellationToken,
9590 0 : ) -> Result<(), OperationError> {
9591 : const MAX_SECONDARY_LAG_BYTES_DEFAULT: u64 = 256 * 1024 * 1024;
9592 0 : let max_secondary_lag_bytes = self
9593 0 : .config
9594 0 : .max_secondary_lag_bytes
9595 0 : .unwrap_or(MAX_SECONDARY_LAG_BYTES_DEFAULT);
9596 :
9597 : // By default, live migrations are generous about the wait time for getting
9598 : // the secondary location up to speed. When draining, give up earlier in order
9599 : // to not stall the operation when a cold secondary is encountered.
9600 : const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(30);
9601 : const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
9602 0 : let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
9603 0 : .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
9604 0 : .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
9605 0 : .build();
9606 :
9607 0 : let mut waiters = Vec::new();
9608 :
9609 0 : let mut tid_iter = create_shared_shard_iterator(self.clone());
9610 :
9611 0 : while !tid_iter.finished() {
9612 0 : if cancel.is_cancelled() {
9613 0 : match self
9614 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
9615 0 : .await
9616 : {
9617 0 : Ok(()) => return Err(OperationError::Cancelled),
9618 0 : Err(err) => {
9619 0 : return Err(OperationError::FinalizeError(
9620 0 : format!(
9621 0 : "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
9622 0 : )
9623 0 : .into(),
9624 0 : ));
9625 : }
9626 : }
9627 0 : }
9628 :
9629 0 : operation_utils::validate_node_state(
9630 0 : &node_id,
9631 0 : self.inner.read().unwrap().nodes.clone(),
9632 0 : NodeSchedulingPolicy::Draining,
9633 0 : )?;
9634 :
9635 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
9636 0 : let tid = match tid_iter.next() {
9637 0 : Some(tid) => tid,
9638 : None => {
9639 0 : break;
9640 : }
9641 : };
9642 :
9643 0 : let tid_drain = TenantShardDrain {
9644 0 : drained_node: node_id,
9645 0 : tenant_shard_id: tid,
9646 0 : };
9647 :
9648 0 : let drain_action = {
9649 0 : let locked = self.inner.read().unwrap();
9650 0 : tid_drain.tenant_shard_eligible_for_drain(&locked.tenants, &locked.scheduler)
9651 : };
9652 :
9653 0 : let dest_node_id = match drain_action {
9654 0 : TenantShardDrainAction::RescheduleToSecondary(dest_node_id) => dest_node_id,
9655 0 : TenantShardDrainAction::Reconcile(intent_node_id) => intent_node_id,
9656 : TenantShardDrainAction::Skip => {
9657 0 : continue;
9658 : }
9659 : };
9660 :
9661 0 : match self.secondary_lag(&dest_node_id, tid).await {
9662 0 : Ok(Some(lag)) if lag <= max_secondary_lag_bytes => {
9663 0 : // The secondary is reasonably up to date.
9664 0 : // Migrate to it
9665 0 : }
9666 0 : Ok(Some(lag)) => {
9667 0 : tracing::info!(
9668 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9669 0 : "Secondary on node {dest_node_id} is lagging by {lag}. Skipping reconcile."
9670 : );
9671 0 : continue;
9672 : }
9673 : Ok(None) => {
9674 0 : tracing::info!(
9675 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9676 0 : "Could not determine lag for secondary on node {dest_node_id}. Skipping reconcile."
9677 : );
9678 0 : continue;
9679 : }
9680 0 : Err(err) => {
9681 0 : tracing::warn!(
9682 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9683 0 : "Failed to get secondary lag from node {dest_node_id}. Skipping reconcile: {err}"
9684 : );
9685 0 : continue;
9686 : }
9687 : }
9688 :
9689 : {
9690 0 : let mut locked = self.inner.write().unwrap();
9691 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
9692 :
9693 0 : let tenant_shard = match drain_action {
9694 0 : TenantShardDrainAction::RescheduleToSecondary(dest_node_id) => tid_drain
9695 0 : .reschedule_to_secondary(dest_node_id, tenants, scheduler, nodes)?,
9696 0 : TenantShardDrainAction::Reconcile(_) => tenants.get_mut(&tid),
9697 : // Note: Unreachable, handled above.
9698 0 : TenantShardDrainAction::Skip => None,
9699 : };
9700 :
9701 0 : if let Some(tenant_shard) = tenant_shard {
9702 0 : let waiter = self.maybe_configured_reconcile_shard(
9703 0 : tenant_shard,
9704 0 : nodes,
9705 0 : reconciler_config,
9706 0 : );
9707 0 : if let Some(some) = waiter {
9708 0 : waiters.push(some);
9709 0 : }
9710 0 : }
9711 : }
9712 : }
9713 :
9714 0 : waiters = self
9715 0 : .await_waiters_remainder(waiters, WAITER_OPERATION_POLL_TIMEOUT)
9716 0 : .await;
9717 :
9718 0 : failpoint_support::sleep_millis_async!("sleepy-drain-loop", &cancel);
9719 : }
9720 :
9721 0 : while !waiters.is_empty() {
9722 0 : if cancel.is_cancelled() {
9723 0 : match self
9724 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
9725 0 : .await
9726 : {
9727 0 : Ok(()) => return Err(OperationError::Cancelled),
9728 0 : Err(err) => {
9729 0 : return Err(OperationError::FinalizeError(
9730 0 : format!(
9731 0 : "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
9732 0 : )
9733 0 : .into(),
9734 0 : ));
9735 : }
9736 : }
9737 0 : }
9738 :
9739 0 : tracing::info!("Awaiting {} pending drain reconciliations", waiters.len());
9740 :
9741 0 : waiters = self
9742 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
9743 0 : .await;
9744 : }
9745 :
9746 : // At this point we have done the best we could to drain shards from this node.
9747 : // Set the node scheduling policy to `[NodeSchedulingPolicy::PauseForRestart]`
9748 : // to complete the drain.
9749 0 : if let Err(err) = self
9750 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::PauseForRestart))
9751 0 : .await
9752 : {
9753 : // This is not fatal. Anything that is polling the node scheduling policy to detect
9754 : // the end of the drain operations will hang, but all such places should enforce an
9755 : // overall timeout. The scheduling policy will be updated upon node re-attach and/or
9756 : // by the counterpart fill operation.
9757 0 : return Err(OperationError::FinalizeError(
9758 0 : format!(
9759 0 : "Failed to finalise drain of {node_id} by setting scheduling policy to PauseForRestart: {err}"
9760 0 : )
9761 0 : .into(),
9762 0 : ));
9763 0 : }
9764 :
9765 0 : Ok(())
9766 0 : }
9767 :
9768 : /// Create a node fill plan (pick secondaries to promote), based on:
9769 : /// 1. Shards which have a secondary on this node, and this node is in their home AZ, and are currently attached to a node
9770 : /// outside their home AZ, should be migrated back here.
9771 : /// 2. If after step 1 we have not migrated enough shards for this node to have its fair share of
9772 : /// attached shards, we will promote more shards from the nodes with the most attached shards, unless
9773 : /// those shards have a home AZ that doesn't match the node we're filling.
9774 0 : fn fill_node_plan(&self, node_id: NodeId) -> Vec<TenantShardId> {
9775 0 : let mut locked = self.inner.write().unwrap();
9776 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
9777 :
9778 0 : let node_az = nodes
9779 0 : .get(&node_id)
9780 0 : .expect("Node must exist")
9781 0 : .get_availability_zone_id()
9782 0 : .clone();
9783 :
9784 : // The tenant shard IDs that we plan to promote from secondary to attached on this node
9785 0 : let mut plan = Vec::new();
9786 :
9787 : // Collect shards which do not have a preferred AZ & are elegible for moving in stage 2
9788 0 : let mut free_tids_by_node: HashMap<NodeId, Vec<TenantShardId>> = HashMap::new();
9789 :
9790 : // Don't respect AZ preferences if there is only one AZ. This comes up in tests, but it could
9791 : // conceivably come up in real life if deploying a single-AZ region intentionally.
9792 0 : let respect_azs = nodes
9793 0 : .values()
9794 0 : .map(|n| n.get_availability_zone_id())
9795 0 : .unique()
9796 0 : .count()
9797 : > 1;
9798 :
9799 : // Step 1: collect all shards that we are required to migrate back to this node because their AZ preference
9800 : // requires it.
9801 0 : for (tsid, tenant_shard) in tenants {
9802 0 : if !tenant_shard.intent.get_secondary().contains(&node_id) {
9803 : // Shard doesn't have a secondary on this node, ignore it.
9804 0 : continue;
9805 0 : }
9806 :
9807 : // AZ check: when filling nodes after a restart, our intent is to move _back_ the
9808 : // shards which belong on this node, not to promote shards whose scheduling preference
9809 : // would be on their currently attached node. So will avoid promoting shards whose
9810 : // home AZ doesn't match the AZ of the node we're filling.
9811 0 : match tenant_shard.preferred_az() {
9812 0 : _ if !respect_azs => {
9813 0 : if let Some(primary) = tenant_shard.intent.get_attached() {
9814 0 : free_tids_by_node.entry(*primary).or_default().push(*tsid);
9815 0 : }
9816 : }
9817 : None => {
9818 : // Shard doesn't have an AZ preference: it is elegible to be moved, but we
9819 : // will only do so if our target shard count requires it.
9820 0 : if let Some(primary) = tenant_shard.intent.get_attached() {
9821 0 : free_tids_by_node.entry(*primary).or_default().push(*tsid);
9822 0 : }
9823 : }
9824 0 : Some(az) if az == &node_az => {
9825 : // This shard's home AZ is equal to the node we're filling: it should
9826 : // be moved back to this node as part of filling, unless its currently
9827 : // attached location is also in its home AZ.
9828 0 : if let Some(primary) = tenant_shard.intent.get_attached() {
9829 0 : if nodes
9830 0 : .get(primary)
9831 0 : .expect("referenced node must exist")
9832 0 : .get_availability_zone_id()
9833 0 : != tenant_shard
9834 0 : .preferred_az()
9835 0 : .expect("tenant must have an AZ preference")
9836 : {
9837 0 : plan.push(*tsid)
9838 0 : }
9839 : } else {
9840 0 : plan.push(*tsid)
9841 : }
9842 : }
9843 0 : Some(_) => {
9844 0 : // This shard's home AZ is somewhere other than the node we're filling,
9845 0 : // it may not be moved back to this node as part of filling. Ignore it
9846 0 : }
9847 : }
9848 : }
9849 :
9850 : // Step 2: also promote any AZ-agnostic shards as required to achieve the target number of attachments
9851 0 : let fill_requirement = locked.scheduler.compute_fill_requirement(node_id);
9852 :
9853 0 : let expected_attached = locked.scheduler.expected_attached_shard_count();
9854 0 : let nodes_by_load = locked.scheduler.nodes_by_attached_shard_count();
9855 :
9856 0 : let mut promoted_per_tenant: HashMap<TenantId, usize> = HashMap::new();
9857 :
9858 0 : for (node_id, attached) in nodes_by_load {
9859 0 : let available = locked.nodes.get(&node_id).is_some_and(|n| n.is_available());
9860 0 : if !available {
9861 0 : continue;
9862 0 : }
9863 :
9864 0 : if plan.len() >= fill_requirement
9865 0 : || free_tids_by_node.is_empty()
9866 0 : || attached <= expected_attached
9867 : {
9868 0 : break;
9869 0 : }
9870 :
9871 0 : let can_take = attached - expected_attached;
9872 0 : let needed = fill_requirement - plan.len();
9873 0 : let mut take = std::cmp::min(can_take, needed);
9874 :
9875 0 : let mut remove_node = false;
9876 0 : while take > 0 {
9877 0 : match free_tids_by_node.get_mut(&node_id) {
9878 0 : Some(tids) => match tids.pop() {
9879 0 : Some(tid) => {
9880 0 : let max_promote_for_tenant = std::cmp::max(
9881 0 : tid.shard_count.count() as usize / locked.nodes.len(),
9882 : 1,
9883 : );
9884 0 : let promoted = promoted_per_tenant.entry(tid.tenant_id).or_default();
9885 0 : if *promoted < max_promote_for_tenant {
9886 0 : plan.push(tid);
9887 0 : *promoted += 1;
9888 0 : take -= 1;
9889 0 : }
9890 : }
9891 : None => {
9892 0 : remove_node = true;
9893 0 : break;
9894 : }
9895 : },
9896 : None => {
9897 0 : break;
9898 : }
9899 : }
9900 : }
9901 :
9902 0 : if remove_node {
9903 0 : free_tids_by_node.remove(&node_id);
9904 0 : }
9905 : }
9906 :
9907 0 : plan
9908 0 : }
9909 :
9910 : /// Fill a node by promoting its secondaries until the cluster is balanced
9911 : /// with regards to attached shard counts. Note that this operation only
9912 : /// makes sense as a counterpart to the drain implemented in [`Service::drain_node`].
9913 : /// This is a long running operation and it should run as a separate Tokio task.
9914 0 : pub(crate) async fn fill_node(
9915 0 : &self,
9916 0 : node_id: NodeId,
9917 0 : cancel: CancellationToken,
9918 0 : ) -> Result<(), OperationError> {
9919 : const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(30);
9920 : const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
9921 0 : let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
9922 0 : .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
9923 0 : .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
9924 0 : .build();
9925 :
9926 0 : let mut tids_to_promote = self.fill_node_plan(node_id);
9927 0 : let mut waiters = Vec::new();
9928 :
9929 : // Execute the plan we've composed above. Before aplying each move from the plan,
9930 : // we validate to ensure that it has not gone stale in the meantime.
9931 0 : while !tids_to_promote.is_empty() {
9932 0 : if cancel.is_cancelled() {
9933 0 : match self
9934 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
9935 0 : .await
9936 : {
9937 0 : Ok(()) => return Err(OperationError::Cancelled),
9938 0 : Err(err) => {
9939 0 : return Err(OperationError::FinalizeError(
9940 0 : format!(
9941 0 : "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
9942 0 : )
9943 0 : .into(),
9944 0 : ));
9945 : }
9946 : }
9947 0 : }
9948 :
9949 : {
9950 0 : let mut locked = self.inner.write().unwrap();
9951 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
9952 :
9953 0 : let node = nodes.get(&node_id).ok_or(OperationError::NodeStateChanged(
9954 0 : format!("node {node_id} was removed").into(),
9955 0 : ))?;
9956 :
9957 0 : let current_policy = node.get_scheduling();
9958 0 : if !matches!(current_policy, NodeSchedulingPolicy::Filling) {
9959 : // TODO(vlad): maybe cancel pending reconciles before erroring out. need to think
9960 : // about it
9961 0 : return Err(OperationError::NodeStateChanged(
9962 0 : format!("node {node_id} changed state to {current_policy:?}").into(),
9963 0 : ));
9964 0 : }
9965 :
9966 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
9967 0 : if let Some(tid) = tids_to_promote.pop() {
9968 0 : if let Some(tenant_shard) = tenants.get_mut(&tid) {
9969 : // If the node being filled is not a secondary anymore,
9970 : // skip the promotion.
9971 0 : if !tenant_shard.intent.get_secondary().contains(&node_id) {
9972 0 : continue;
9973 0 : }
9974 :
9975 0 : let previously_attached_to = *tenant_shard.intent.get_attached();
9976 0 : match tenant_shard.reschedule_to_secondary(Some(node_id), scheduler) {
9977 0 : Err(e) => {
9978 0 : tracing::warn!(
9979 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9980 0 : "Scheduling error when filling pageserver {} : {e}", node_id
9981 : );
9982 : }
9983 : Ok(()) => {
9984 0 : tracing::info!(
9985 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9986 0 : "Rescheduled shard while filling node {}: {:?} -> {}",
9987 : node_id,
9988 : previously_attached_to,
9989 : node_id
9990 : );
9991 :
9992 0 : if let Some(waiter) = self.maybe_configured_reconcile_shard(
9993 0 : tenant_shard,
9994 0 : nodes,
9995 0 : reconciler_config,
9996 0 : ) {
9997 0 : waiters.push(waiter);
9998 0 : }
9999 : }
10000 : }
10001 0 : }
10002 : } else {
10003 0 : break;
10004 : }
10005 : }
10006 : }
10007 :
10008 0 : waiters = self
10009 0 : .await_waiters_remainder(waiters, WAITER_OPERATION_POLL_TIMEOUT)
10010 0 : .await;
10011 : }
10012 :
10013 0 : while !waiters.is_empty() {
10014 0 : if cancel.is_cancelled() {
10015 0 : match self
10016 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
10017 0 : .await
10018 : {
10019 0 : Ok(()) => return Err(OperationError::Cancelled),
10020 0 : Err(err) => {
10021 0 : return Err(OperationError::FinalizeError(
10022 0 : format!(
10023 0 : "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
10024 0 : )
10025 0 : .into(),
10026 0 : ));
10027 : }
10028 : }
10029 0 : }
10030 :
10031 0 : tracing::info!("Awaiting {} pending fill reconciliations", waiters.len());
10032 :
10033 0 : waiters = self
10034 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
10035 0 : .await;
10036 : }
10037 :
10038 0 : if let Err(err) = self
10039 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
10040 0 : .await
10041 : {
10042 : // This isn't a huge issue since the filling process starts upon request. However, it
10043 : // will prevent the next drain from starting. The only case in which this can fail
10044 : // is database unavailability. Such a case will require manual intervention.
10045 0 : return Err(OperationError::FinalizeError(
10046 0 : format!("Failed to finalise fill of {node_id} by setting scheduling policy to Active: {err}")
10047 0 : .into(),
10048 0 : ));
10049 0 : }
10050 :
10051 0 : Ok(())
10052 0 : }
10053 :
10054 : /// Updates scrubber metadata health check results.
10055 0 : pub(crate) async fn metadata_health_update(
10056 0 : &self,
10057 0 : update_req: MetadataHealthUpdateRequest,
10058 0 : ) -> Result<(), ApiError> {
10059 0 : let now = chrono::offset::Utc::now();
10060 0 : let (healthy_records, unhealthy_records) = {
10061 0 : let locked = self.inner.read().unwrap();
10062 0 : let healthy_records = update_req
10063 0 : .healthy_tenant_shards
10064 0 : .into_iter()
10065 : // Retain only health records associated with tenant shards managed by storage controller.
10066 0 : .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
10067 0 : .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, true, now))
10068 0 : .collect();
10069 0 : let unhealthy_records = update_req
10070 0 : .unhealthy_tenant_shards
10071 0 : .into_iter()
10072 0 : .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
10073 0 : .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, false, now))
10074 0 : .collect();
10075 :
10076 0 : (healthy_records, unhealthy_records)
10077 : };
10078 :
10079 0 : self.persistence
10080 0 : .update_metadata_health_records(healthy_records, unhealthy_records, now)
10081 0 : .await?;
10082 0 : Ok(())
10083 0 : }
10084 :
10085 : /// Lists the tenant shards that has unhealthy metadata status.
10086 0 : pub(crate) async fn metadata_health_list_unhealthy(
10087 0 : &self,
10088 0 : ) -> Result<Vec<TenantShardId>, ApiError> {
10089 0 : let result = self
10090 0 : .persistence
10091 0 : .list_unhealthy_metadata_health_records()
10092 0 : .await?
10093 0 : .iter()
10094 0 : .map(|p| p.get_tenant_shard_id().unwrap())
10095 0 : .collect();
10096 :
10097 0 : Ok(result)
10098 0 : }
10099 :
10100 : /// Lists the tenant shards that have not been scrubbed for some duration.
10101 0 : pub(crate) async fn metadata_health_list_outdated(
10102 0 : &self,
10103 0 : not_scrubbed_for: Duration,
10104 0 : ) -> Result<Vec<MetadataHealthRecord>, ApiError> {
10105 0 : let earlier = chrono::offset::Utc::now() - not_scrubbed_for;
10106 0 : let result = self
10107 0 : .persistence
10108 0 : .list_outdated_metadata_health_records(earlier)
10109 0 : .await?
10110 0 : .into_iter()
10111 0 : .map(|record| record.into())
10112 0 : .collect();
10113 0 : Ok(result)
10114 0 : }
10115 :
10116 0 : pub(crate) fn get_leadership_status(&self) -> LeadershipStatus {
10117 0 : self.inner.read().unwrap().get_leadership_status()
10118 0 : }
10119 :
10120 : /// Handler for step down requests
10121 : ///
10122 : /// Step down runs in separate task since once it's called it should
10123 : /// be driven to completion. Subsequent requests will wait on the same
10124 : /// step down task.
10125 0 : pub(crate) async fn step_down(self: &Arc<Self>) -> GlobalObservedState {
10126 0 : let handle = self.step_down_barrier.get_or_init(|| {
10127 0 : let step_down_self = self.clone();
10128 0 : let (tx, rx) = tokio::sync::watch::channel::<Option<GlobalObservedState>>(None);
10129 0 : tokio::spawn(async move {
10130 0 : let state = step_down_self.step_down_task().await;
10131 0 : tx.send(Some(state))
10132 0 : .expect("Task Arc<Service> keeps receiver alive");
10133 0 : });
10134 :
10135 0 : rx
10136 0 : });
10137 :
10138 0 : handle
10139 0 : .clone()
10140 0 : .wait_for(|observed_state| observed_state.is_some())
10141 0 : .await
10142 0 : .expect("Task Arc<Service> keeps sender alive")
10143 0 : .deref()
10144 0 : .clone()
10145 0 : .expect("Checked above")
10146 0 : }
10147 :
10148 0 : async fn step_down_task(&self) -> GlobalObservedState {
10149 0 : tracing::info!("Received step down request from peer");
10150 0 : failpoint_support::sleep_millis_async!("sleep-on-step-down-handling");
10151 :
10152 0 : self.inner.write().unwrap().step_down();
10153 :
10154 0 : let stop_reconciliations =
10155 0 : self.stop_reconciliations(StopReconciliationsReason::SteppingDown);
10156 0 : let mut stop_reconciliations = std::pin::pin!(stop_reconciliations);
10157 :
10158 0 : let started_at = Instant::now();
10159 :
10160 : // Wait for reconciliations to stop and warn if that's taking a long time
10161 : loop {
10162 0 : tokio::select! {
10163 0 : _ = &mut stop_reconciliations => {
10164 0 : tracing::info!("Reconciliations stopped, proceeding with step down");
10165 0 : break;
10166 : }
10167 0 : _ = tokio::time::sleep(Duration::from_secs(10)) => {
10168 0 : tracing::warn!(
10169 0 : elapsed_sec=%started_at.elapsed().as_secs(),
10170 0 : "Stopping reconciliations during step down is taking too long"
10171 : );
10172 : }
10173 : }
10174 : }
10175 :
10176 0 : let mut global_observed = GlobalObservedState::default();
10177 0 : let locked = self.inner.read().unwrap();
10178 0 : for (tid, tenant_shard) in locked.tenants.iter() {
10179 0 : global_observed
10180 0 : .0
10181 0 : .insert(*tid, tenant_shard.observed.clone());
10182 0 : }
10183 :
10184 0 : global_observed
10185 0 : }
10186 :
10187 0 : pub(crate) async fn update_shards_preferred_azs(
10188 0 : &self,
10189 0 : req: ShardsPreferredAzsRequest,
10190 0 : ) -> Result<ShardsPreferredAzsResponse, ApiError> {
10191 0 : let preferred_azs = req.preferred_az_ids.into_iter().collect::<Vec<_>>();
10192 0 : let updated = self
10193 0 : .persistence
10194 0 : .set_tenant_shard_preferred_azs(preferred_azs)
10195 0 : .await
10196 0 : .map_err(|err| {
10197 0 : ApiError::InternalServerError(anyhow::anyhow!(
10198 0 : "Failed to persist preferred AZs: {err}"
10199 0 : ))
10200 0 : })?;
10201 :
10202 0 : let mut updated_in_mem_and_db = Vec::default();
10203 :
10204 0 : let mut locked = self.inner.write().unwrap();
10205 0 : let state = locked.deref_mut();
10206 0 : for (tid, az_id) in updated {
10207 0 : let shard = state.tenants.get_mut(&tid);
10208 0 : if let Some(shard) = shard {
10209 0 : shard.set_preferred_az(&mut state.scheduler, az_id);
10210 0 : updated_in_mem_and_db.push(tid);
10211 0 : }
10212 : }
10213 :
10214 0 : Ok(ShardsPreferredAzsResponse {
10215 0 : updated: updated_in_mem_and_db,
10216 0 : })
10217 0 : }
10218 : }
10219 :
10220 : #[cfg(test)]
10221 : mod tests {
10222 : use super::*;
10223 :
10224 : /// Tests Service::compute_split_shards. For readability, this specifies sizes in GBs rather
10225 : /// than bytes. Note that max_logical_size is the total logical size of the largest timeline
10226 : /// summed across all shards.
10227 : #[test]
10228 1 : fn compute_split_shards() {
10229 : // Size-based split: two shards have a 500 GB timeline, which need to split into 8 shards
10230 : // that are <= 64 GB,
10231 1 : assert_eq!(
10232 1 : Service::compute_split_shards(ShardSplitInputs {
10233 1 : shard_count: ShardCount(2),
10234 1 : max_logical_size: 500,
10235 1 : split_threshold: 64,
10236 1 : max_split_shards: 16,
10237 1 : initial_split_threshold: 0,
10238 1 : initial_split_shards: 0,
10239 1 : }),
10240 : Some(ShardCount(8))
10241 : );
10242 :
10243 : // Size-based split: noop at or below threshold, fires above.
10244 1 : assert_eq!(
10245 1 : Service::compute_split_shards(ShardSplitInputs {
10246 1 : shard_count: ShardCount(2),
10247 1 : max_logical_size: 127,
10248 1 : split_threshold: 64,
10249 1 : max_split_shards: 16,
10250 1 : initial_split_threshold: 0,
10251 1 : initial_split_shards: 0,
10252 1 : }),
10253 : None,
10254 : );
10255 1 : assert_eq!(
10256 1 : Service::compute_split_shards(ShardSplitInputs {
10257 1 : shard_count: ShardCount(2),
10258 1 : max_logical_size: 128,
10259 1 : split_threshold: 64,
10260 1 : max_split_shards: 16,
10261 1 : initial_split_threshold: 0,
10262 1 : initial_split_shards: 0,
10263 1 : }),
10264 : None,
10265 : );
10266 1 : assert_eq!(
10267 1 : Service::compute_split_shards(ShardSplitInputs {
10268 1 : shard_count: ShardCount(2),
10269 1 : max_logical_size: 129,
10270 1 : split_threshold: 64,
10271 1 : max_split_shards: 16,
10272 1 : initial_split_threshold: 0,
10273 1 : initial_split_shards: 0,
10274 1 : }),
10275 : Some(ShardCount(4)),
10276 : );
10277 :
10278 : // Size-based split: clamped to max_split_shards.
10279 1 : assert_eq!(
10280 1 : Service::compute_split_shards(ShardSplitInputs {
10281 1 : shard_count: ShardCount(2),
10282 1 : max_logical_size: 10000,
10283 1 : split_threshold: 64,
10284 1 : max_split_shards: 16,
10285 1 : initial_split_threshold: 0,
10286 1 : initial_split_shards: 0,
10287 1 : }),
10288 : Some(ShardCount(16))
10289 : );
10290 :
10291 : // Size-based split: tenant already at or beyond max_split_shards is not split.
10292 1 : assert_eq!(
10293 1 : Service::compute_split_shards(ShardSplitInputs {
10294 1 : shard_count: ShardCount(16),
10295 1 : max_logical_size: 10000,
10296 1 : split_threshold: 64,
10297 1 : max_split_shards: 16,
10298 1 : initial_split_threshold: 0,
10299 1 : initial_split_shards: 0,
10300 1 : }),
10301 : None
10302 : );
10303 :
10304 1 : assert_eq!(
10305 1 : Service::compute_split_shards(ShardSplitInputs {
10306 1 : shard_count: ShardCount(32),
10307 1 : max_logical_size: 10000,
10308 1 : split_threshold: 64,
10309 1 : max_split_shards: 16,
10310 1 : initial_split_threshold: 0,
10311 1 : initial_split_shards: 0,
10312 1 : }),
10313 : None
10314 : );
10315 :
10316 : // Size-based split: a non-power-of-2 shard count is normalized to power-of-2 if it
10317 : // exceeds split_threshold (i.e. a 3-shard tenant splits into 8, not 6).
10318 1 : assert_eq!(
10319 1 : Service::compute_split_shards(ShardSplitInputs {
10320 1 : shard_count: ShardCount(3),
10321 1 : max_logical_size: 320,
10322 1 : split_threshold: 64,
10323 1 : max_split_shards: 16,
10324 1 : initial_split_threshold: 0,
10325 1 : initial_split_shards: 0,
10326 1 : }),
10327 : Some(ShardCount(8))
10328 : );
10329 :
10330 : // Size-based split: a non-power-of-2 shard count is not normalized to power-of-2 if the
10331 : // existing shards are below or at split_threshold, but splits into 4 if it exceeds it.
10332 1 : assert_eq!(
10333 1 : Service::compute_split_shards(ShardSplitInputs {
10334 1 : shard_count: ShardCount(3),
10335 1 : max_logical_size: 191,
10336 1 : split_threshold: 64,
10337 1 : max_split_shards: 16,
10338 1 : initial_split_threshold: 0,
10339 1 : initial_split_shards: 0,
10340 1 : }),
10341 : None
10342 : );
10343 1 : assert_eq!(
10344 1 : Service::compute_split_shards(ShardSplitInputs {
10345 1 : shard_count: ShardCount(3),
10346 1 : max_logical_size: 192,
10347 1 : split_threshold: 64,
10348 1 : max_split_shards: 16,
10349 1 : initial_split_threshold: 0,
10350 1 : initial_split_shards: 0,
10351 1 : }),
10352 : None
10353 : );
10354 1 : assert_eq!(
10355 1 : Service::compute_split_shards(ShardSplitInputs {
10356 1 : shard_count: ShardCount(3),
10357 1 : max_logical_size: 193,
10358 1 : split_threshold: 64,
10359 1 : max_split_shards: 16,
10360 1 : initial_split_threshold: 0,
10361 1 : initial_split_shards: 0,
10362 1 : }),
10363 : Some(ShardCount(4))
10364 : );
10365 :
10366 : // Initial split: tenant has a 10 GB timeline, split into 4 shards.
10367 1 : assert_eq!(
10368 1 : Service::compute_split_shards(ShardSplitInputs {
10369 1 : shard_count: ShardCount(1),
10370 1 : max_logical_size: 10,
10371 1 : split_threshold: 0,
10372 1 : max_split_shards: 16,
10373 1 : initial_split_threshold: 8,
10374 1 : initial_split_shards: 4,
10375 1 : }),
10376 : Some(ShardCount(4))
10377 : );
10378 :
10379 : // Initial split: 0 ShardCount is equivalent to 1.
10380 1 : assert_eq!(
10381 1 : Service::compute_split_shards(ShardSplitInputs {
10382 1 : shard_count: ShardCount(0),
10383 1 : max_logical_size: 10,
10384 1 : split_threshold: 0,
10385 1 : max_split_shards: 16,
10386 1 : initial_split_threshold: 8,
10387 1 : initial_split_shards: 4,
10388 1 : }),
10389 : Some(ShardCount(4))
10390 : );
10391 :
10392 : // Initial split: at or below threshold is noop.
10393 1 : assert_eq!(
10394 1 : Service::compute_split_shards(ShardSplitInputs {
10395 1 : shard_count: ShardCount(1),
10396 1 : max_logical_size: 7,
10397 1 : split_threshold: 0,
10398 1 : max_split_shards: 16,
10399 1 : initial_split_threshold: 8,
10400 1 : initial_split_shards: 4,
10401 1 : }),
10402 : None,
10403 : );
10404 1 : assert_eq!(
10405 1 : Service::compute_split_shards(ShardSplitInputs {
10406 1 : shard_count: ShardCount(1),
10407 1 : max_logical_size: 8,
10408 1 : split_threshold: 0,
10409 1 : max_split_shards: 16,
10410 1 : initial_split_threshold: 8,
10411 1 : initial_split_shards: 4,
10412 1 : }),
10413 : None,
10414 : );
10415 1 : assert_eq!(
10416 1 : Service::compute_split_shards(ShardSplitInputs {
10417 1 : shard_count: ShardCount(1),
10418 1 : max_logical_size: 9,
10419 1 : split_threshold: 0,
10420 1 : max_split_shards: 16,
10421 1 : initial_split_threshold: 8,
10422 1 : initial_split_shards: 4,
10423 1 : }),
10424 : Some(ShardCount(4))
10425 : );
10426 :
10427 : // Initial split: already sharded tenant is not affected, even if above threshold and below
10428 : // shard count.
10429 1 : assert_eq!(
10430 1 : Service::compute_split_shards(ShardSplitInputs {
10431 1 : shard_count: ShardCount(2),
10432 1 : max_logical_size: 20,
10433 1 : split_threshold: 0,
10434 1 : max_split_shards: 16,
10435 1 : initial_split_threshold: 8,
10436 1 : initial_split_shards: 4,
10437 1 : }),
10438 : None,
10439 : );
10440 :
10441 : // Initial split: clamped to max_shards.
10442 1 : assert_eq!(
10443 1 : Service::compute_split_shards(ShardSplitInputs {
10444 1 : shard_count: ShardCount(1),
10445 1 : max_logical_size: 10,
10446 1 : split_threshold: 0,
10447 1 : max_split_shards: 3,
10448 1 : initial_split_threshold: 8,
10449 1 : initial_split_shards: 4,
10450 1 : }),
10451 : Some(ShardCount(3)),
10452 : );
10453 :
10454 : // Initial+size split: tenant eligible for both will use the larger shard count.
10455 1 : assert_eq!(
10456 1 : Service::compute_split_shards(ShardSplitInputs {
10457 1 : shard_count: ShardCount(1),
10458 1 : max_logical_size: 10,
10459 1 : split_threshold: 64,
10460 1 : max_split_shards: 16,
10461 1 : initial_split_threshold: 8,
10462 1 : initial_split_shards: 4,
10463 1 : }),
10464 : Some(ShardCount(4)),
10465 : );
10466 1 : assert_eq!(
10467 1 : Service::compute_split_shards(ShardSplitInputs {
10468 1 : shard_count: ShardCount(1),
10469 1 : max_logical_size: 500,
10470 1 : split_threshold: 64,
10471 1 : max_split_shards: 16,
10472 1 : initial_split_threshold: 8,
10473 1 : initial_split_shards: 4,
10474 1 : }),
10475 : Some(ShardCount(8)),
10476 : );
10477 :
10478 : // Initial+size split: sharded tenant is only eligible for size-based split.
10479 1 : assert_eq!(
10480 1 : Service::compute_split_shards(ShardSplitInputs {
10481 1 : shard_count: ShardCount(2),
10482 1 : max_logical_size: 200,
10483 1 : split_threshold: 64,
10484 1 : max_split_shards: 16,
10485 1 : initial_split_threshold: 8,
10486 1 : initial_split_shards: 8,
10487 1 : }),
10488 : Some(ShardCount(4)),
10489 : );
10490 :
10491 : // Initial+size split: uses the larger shard count even with initial_split_threshold above
10492 : // split_threshold.
10493 1 : assert_eq!(
10494 1 : Service::compute_split_shards(ShardSplitInputs {
10495 1 : shard_count: ShardCount(1),
10496 1 : max_logical_size: 10,
10497 1 : split_threshold: 4,
10498 1 : max_split_shards: 16,
10499 1 : initial_split_threshold: 8,
10500 1 : initial_split_shards: 8,
10501 1 : }),
10502 : Some(ShardCount(8)),
10503 : );
10504 :
10505 : // Test backwards compatibility with production settings when initial/size-based splits were
10506 : // rolled out: a single split into 8 shards at 64 GB. Any already sharded tenants with <8
10507 : // shards will split according to split_threshold.
10508 1 : assert_eq!(
10509 1 : Service::compute_split_shards(ShardSplitInputs {
10510 1 : shard_count: ShardCount(1),
10511 1 : max_logical_size: 65,
10512 1 : split_threshold: 64,
10513 1 : max_split_shards: 8,
10514 1 : initial_split_threshold: 64,
10515 1 : initial_split_shards: 8,
10516 1 : }),
10517 : Some(ShardCount(8)),
10518 : );
10519 :
10520 1 : assert_eq!(
10521 1 : Service::compute_split_shards(ShardSplitInputs {
10522 1 : shard_count: ShardCount(1),
10523 1 : max_logical_size: 64,
10524 1 : split_threshold: 64,
10525 1 : max_split_shards: 8,
10526 1 : initial_split_threshold: 64,
10527 1 : initial_split_shards: 8,
10528 1 : }),
10529 : None,
10530 : );
10531 :
10532 1 : assert_eq!(
10533 1 : Service::compute_split_shards(ShardSplitInputs {
10534 1 : shard_count: ShardCount(2),
10535 1 : max_logical_size: 129,
10536 1 : split_threshold: 64,
10537 1 : max_split_shards: 8,
10538 1 : initial_split_threshold: 64,
10539 1 : initial_split_shards: 8,
10540 1 : }),
10541 : Some(ShardCount(4)),
10542 : );
10543 1 : }
10544 : }
|