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};
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, 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 :
495 : impl From<DatabaseError> for ApiError {
496 0 : fn from(err: DatabaseError) -> ApiError {
497 0 : match err {
498 0 : DatabaseError::Query(e) => ApiError::InternalServerError(e.into()),
499 : // FIXME: ApiError doesn't have an Unavailable variant, but ShuttingDown maps to 503.
500 : DatabaseError::Connection(_) | DatabaseError::ConnectionPool(_) => {
501 0 : ApiError::ShuttingDown
502 : }
503 0 : DatabaseError::Logical(reason) | DatabaseError::Migration(reason) => {
504 0 : ApiError::InternalServerError(anyhow::anyhow!(reason))
505 : }
506 0 : DatabaseError::Cas(reason) => ApiError::Conflict(reason),
507 : }
508 0 : }
509 : }
510 :
511 : enum InitialShardScheduleOutcome {
512 : Scheduled(TenantCreateResponseShard),
513 : NotScheduled,
514 : ShardScheduleError(ScheduleError),
515 : }
516 :
517 : pub struct Service {
518 : inner: Arc<std::sync::RwLock<ServiceState>>,
519 : config: Config,
520 : persistence: Arc<Persistence>,
521 : compute_hook: Arc<ComputeHook>,
522 : result_tx: tokio::sync::mpsc::UnboundedSender<ReconcileResultRequest>,
523 :
524 : heartbeater_ps: Heartbeater<Node, PageserverState>,
525 : heartbeater_sk: Heartbeater<Safekeeper, SafekeeperState>,
526 :
527 : // Channel for background cleanup from failed operations that require cleanup, such as shard split
528 : abort_tx: tokio::sync::mpsc::UnboundedSender<TenantShardSplitAbort>,
529 :
530 : // Locking on a tenant granularity (covers all shards in the tenant):
531 : // - Take exclusively for rare operations that mutate the tenant's persistent state (e.g. create/delete/split)
532 : // - Take in shared mode for operations that need the set of shards to stay the same to complete reliably (e.g. timeline CRUD)
533 : tenant_op_locks: IdLockMap<TenantId, TenantOperations>,
534 :
535 : // Locking for node-mutating operations: take exclusively for operations that modify the node's persistent state, or
536 : // that transition it to/from Active.
537 : node_op_locks: IdLockMap<NodeId, NodeOperations>,
538 :
539 : // Limit how many Reconcilers we will spawn concurrently for normal-priority tasks such as background reconciliations
540 : // and reconciliation on startup.
541 : reconciler_concurrency: Arc<tokio::sync::Semaphore>,
542 :
543 : // Limit how many Reconcilers we will spawn concurrently for high-priority tasks such as tenant/timeline CRUD, which
544 : // a human user might be waiting for.
545 : priority_reconciler_concurrency: Arc<tokio::sync::Semaphore>,
546 :
547 : /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
548 : /// Send into this queue to promptly attempt to reconcile this shard next time units are available.
549 : ///
550 : /// Note that this state logically lives inside ServiceState, but carrying Sender here makes the code simpler
551 : /// by avoiding needing a &mut ref to something inside the ServiceState. This could be optimized to
552 : /// use a VecDeque instead of a channel to reduce synchronization overhead, at the cost of some code complexity.
553 : delayed_reconcile_tx: tokio::sync::mpsc::Sender<TenantShardId>,
554 :
555 : // Process shutdown will fire this token
556 : cancel: CancellationToken,
557 :
558 : // Child token of [`Service::cancel`] used by reconcilers
559 : reconcilers_cancel: CancellationToken,
560 :
561 : // Background tasks will hold this gate
562 : gate: Gate,
563 :
564 : // Reconcilers background tasks will hold this gate
565 : reconcilers_gate: Gate,
566 :
567 : /// This waits for initial reconciliation with pageservers to complete. Until this barrier
568 : /// passes, it isn't safe to do any actions that mutate tenants.
569 : pub(crate) startup_complete: Barrier,
570 :
571 : /// HTTP client with proper CA certs.
572 : http_client: reqwest::Client,
573 :
574 : /// Handle for the step down background task if one was ever requested
575 : step_down_barrier: OnceLock<tokio::sync::watch::Receiver<Option<GlobalObservedState>>>,
576 : }
577 :
578 : impl From<ReconcileWaitError> for ApiError {
579 0 : fn from(value: ReconcileWaitError) -> Self {
580 0 : match value {
581 0 : ReconcileWaitError::Shutdown => ApiError::ShuttingDown,
582 0 : e @ ReconcileWaitError::Timeout(_) => ApiError::Timeout(format!("{e}").into()),
583 0 : e @ ReconcileWaitError::Failed(..) => ApiError::InternalServerError(anyhow::anyhow!(e)),
584 : }
585 0 : }
586 : }
587 :
588 : impl From<OperationError> for ApiError {
589 0 : fn from(value: OperationError) -> Self {
590 0 : match value {
591 0 : OperationError::NodeStateChanged(err)
592 0 : | OperationError::FinalizeError(err)
593 0 : | OperationError::ImpossibleConstraint(err) => {
594 0 : ApiError::InternalServerError(anyhow::anyhow!(err))
595 : }
596 0 : OperationError::Cancelled => ApiError::Conflict("Operation was cancelled".into()),
597 : }
598 0 : }
599 : }
600 :
601 : #[allow(clippy::large_enum_variant)]
602 : enum TenantCreateOrUpdate {
603 : Create(TenantCreateRequest),
604 : Update(Vec<ShardUpdate>),
605 : }
606 :
607 : struct ShardSplitParams {
608 : old_shard_count: ShardCount,
609 : new_shard_count: ShardCount,
610 : new_stripe_size: Option<ShardStripeSize>,
611 : targets: Vec<ShardSplitTarget>,
612 : policy: PlacementPolicy,
613 : config: TenantConfig,
614 : shard_ident: ShardIdentity,
615 : preferred_az_id: Option<AvailabilityZone>,
616 : }
617 :
618 : // When preparing for a shard split, we may either choose to proceed with the split,
619 : // or find that the work is already done and return NoOp.
620 : enum ShardSplitAction {
621 : Split(Box<ShardSplitParams>),
622 : NoOp(TenantShardSplitResponse),
623 : }
624 :
625 : // A parent shard which will be split
626 : struct ShardSplitTarget {
627 : parent_id: TenantShardId,
628 : node: Node,
629 : child_ids: Vec<TenantShardId>,
630 : }
631 :
632 : /// When we tenant shard split operation fails, we may not be able to clean up immediately, because nodes
633 : /// might not be available. We therefore use a queue of abort operations processed in the background.
634 : struct TenantShardSplitAbort {
635 : tenant_id: TenantId,
636 : /// The target values from the request that failed
637 : new_shard_count: ShardCount,
638 : new_stripe_size: Option<ShardStripeSize>,
639 : /// Until this abort op is complete, no other operations may be done on the tenant
640 : _tenant_lock: TracingExclusiveGuard<TenantOperations>,
641 : /// The reconciler gate for the duration of the split operation, and any included abort.
642 : _gate: GateGuard,
643 : }
644 :
645 : #[derive(thiserror::Error, Debug)]
646 : enum TenantShardSplitAbortError {
647 : #[error(transparent)]
648 : Database(#[from] DatabaseError),
649 : #[error(transparent)]
650 : Remote(#[from] mgmt_api::Error),
651 : #[error("Unavailable")]
652 : Unavailable,
653 : }
654 :
655 : /// Inputs for computing a target shard count for a tenant.
656 : struct ShardSplitInputs {
657 : /// Current shard count.
658 : shard_count: ShardCount,
659 : /// Total size of largest timeline summed across all shards.
660 : max_logical_size: u64,
661 : /// Size-based split threshold. Zero if size-based splits are disabled.
662 : split_threshold: u64,
663 : /// Upper bound on target shards. 0 or 1 disables splits.
664 : max_split_shards: u8,
665 : /// Initial split threshold. Zero if initial splits are disabled.
666 : initial_split_threshold: u64,
667 : /// Number of shards for initial splits. 0 or 1 disables initial splits.
668 : initial_split_shards: u8,
669 : }
670 :
671 : struct ShardUpdate {
672 : tenant_shard_id: TenantShardId,
673 : placement_policy: PlacementPolicy,
674 : tenant_config: TenantConfig,
675 :
676 : /// If this is None, generation is not updated.
677 : generation: Option<Generation>,
678 :
679 : /// If this is None, scheduling policy is not updated.
680 : scheduling_policy: Option<ShardSchedulingPolicy>,
681 : }
682 :
683 : enum StopReconciliationsReason {
684 : ShuttingDown,
685 : SteppingDown,
686 : }
687 :
688 : impl std::fmt::Display for StopReconciliationsReason {
689 0 : fn fmt(&self, writer: &mut std::fmt::Formatter) -> std::fmt::Result {
690 0 : let s = match self {
691 0 : Self::ShuttingDown => "Shutting down",
692 0 : Self::SteppingDown => "Stepping down",
693 : };
694 0 : write!(writer, "{s}")
695 0 : }
696 : }
697 :
698 : pub(crate) enum ReconcileResultRequest {
699 : ReconcileResult(ReconcileResult),
700 : Stop,
701 : }
702 :
703 : #[derive(Clone)]
704 : pub(crate) struct MutationLocation {
705 : pub(crate) node: Node,
706 : pub(crate) generation: Generation,
707 : }
708 :
709 : #[derive(Clone)]
710 : pub(crate) struct ShardMutationLocations {
711 : pub(crate) latest: MutationLocation,
712 : pub(crate) other: Vec<MutationLocation>,
713 : }
714 :
715 : #[derive(Default, Clone)]
716 : pub(crate) struct TenantMutationLocations(pub BTreeMap<TenantShardId, ShardMutationLocations>);
717 :
718 : struct ReconcileAllResult {
719 : spawned_reconciles: usize,
720 : stuck_reconciles: usize,
721 : has_delayed_reconciles: bool,
722 : }
723 :
724 : impl ReconcileAllResult {
725 0 : fn new(
726 0 : spawned_reconciles: usize,
727 0 : stuck_reconciles: usize,
728 0 : has_delayed_reconciles: bool,
729 0 : ) -> Self {
730 0 : assert!(
731 0 : spawned_reconciles >= stuck_reconciles,
732 0 : "It is impossible to have less spawned reconciles than stuck reconciles"
733 : );
734 0 : Self {
735 0 : spawned_reconciles,
736 0 : stuck_reconciles,
737 0 : has_delayed_reconciles,
738 0 : }
739 0 : }
740 :
741 : /// We can run optimizations only if we don't have any delayed reconciles and
742 : /// all spawned reconciles are also stuck reconciles.
743 0 : fn can_run_optimizations(&self) -> bool {
744 0 : !self.has_delayed_reconciles && self.spawned_reconciles == self.stuck_reconciles
745 0 : }
746 : }
747 :
748 : enum TenantIdOrShardId {
749 : TenantId(TenantId),
750 : TenantShardId(TenantShardId),
751 : }
752 :
753 : impl TenantIdOrShardId {
754 0 : fn tenant_id(&self) -> TenantId {
755 0 : match self {
756 0 : TenantIdOrShardId::TenantId(tenant_id) => *tenant_id,
757 0 : TenantIdOrShardId::TenantShardId(tenant_shard_id) => tenant_shard_id.tenant_id,
758 : }
759 0 : }
760 :
761 0 : fn matches(&self, tenant_shard_id: &TenantShardId) -> bool {
762 0 : match self {
763 0 : TenantIdOrShardId::TenantId(tenant_id) => tenant_shard_id.tenant_id == *tenant_id,
764 0 : TenantIdOrShardId::TenantShardId(this_tenant_shard_id) => {
765 0 : this_tenant_shard_id == tenant_shard_id
766 : }
767 : }
768 0 : }
769 : }
770 :
771 : impl Service {
772 0 : pub fn get_config(&self) -> &Config {
773 0 : &self.config
774 0 : }
775 :
776 0 : pub fn get_http_client(&self) -> &reqwest::Client {
777 0 : &self.http_client
778 0 : }
779 :
780 : /// Called once on startup, this function attempts to contact all pageservers to build an up-to-date
781 : /// view of the world, and determine which pageservers are responsive.
782 : #[instrument(skip_all)]
783 : async fn startup_reconcile(
784 : self: &Arc<Service>,
785 : current_leader: Option<ControllerPersistence>,
786 : leader_step_down_state: Option<GlobalObservedState>,
787 : bg_compute_notify_result_tx: tokio::sync::mpsc::Sender<
788 : Result<(), (TenantShardId, NotifyError)>,
789 : >,
790 : ) {
791 : // Startup reconciliation does I/O to other services: whether they
792 : // are responsive or not, we should aim to finish within our deadline, because:
793 : // - If we don't, a k8s readiness hook watching /ready will kill us.
794 : // - While we're waiting for startup reconciliation, we are not fully
795 : // available for end user operations like creating/deleting tenants and timelines.
796 : //
797 : // We set multiple deadlines to break up the time available between the phases of work: this is
798 : // arbitrary, but avoids a situation where the first phase could burn our entire timeout period.
799 : let start_at = Instant::now();
800 : let node_scan_deadline = start_at
801 : .checked_add(STARTUP_RECONCILE_TIMEOUT / 2)
802 : .expect("Reconcile timeout is a modest constant");
803 :
804 : let observed = if let Some(state) = leader_step_down_state {
805 : tracing::info!(
806 : "Using observed state received from leader at {}",
807 : current_leader.as_ref().unwrap().address
808 : );
809 :
810 : state
811 : } else {
812 : self.build_global_observed_state(node_scan_deadline).await
813 : };
814 :
815 : // Accumulate a list of any tenant locations that ought to be detached
816 : let mut cleanup = Vec::new();
817 :
818 : // Send initial heartbeat requests to all nodes loaded from the database
819 : let all_nodes = {
820 : let locked = self.inner.read().unwrap();
821 : locked.nodes.clone()
822 : };
823 : let (mut nodes_online, mut sks_online) =
824 : self.initial_heartbeat_round(all_nodes.keys()).await;
825 :
826 : // List of tenants for which we will attempt to notify compute of their location at startup
827 : let mut compute_notifications = Vec::new();
828 :
829 : // Populate intent and observed states for all tenants, based on reported state on pageservers
830 : tracing::info!("Populating tenant shards' states from initial pageserver scan...");
831 : let shard_count = {
832 : let mut locked = self.inner.write().unwrap();
833 : let (nodes, safekeepers, tenants, scheduler) = locked.parts_mut_sk();
834 :
835 : // Mark nodes online if they responded to us: nodes are offline by default after a restart.
836 : let mut new_nodes = (**nodes).clone();
837 : for (node_id, node) in new_nodes.iter_mut() {
838 : if let Some(utilization) = nodes_online.remove(node_id) {
839 : node.set_availability(NodeAvailability::Active(utilization));
840 : scheduler.node_upsert(node);
841 : }
842 : }
843 : *nodes = Arc::new(new_nodes);
844 :
845 : let mut new_sks = (**safekeepers).clone();
846 : for (node_id, node) in new_sks.iter_mut() {
847 : if let Some((utilization, last_seen_at)) = sks_online.remove(node_id) {
848 : node.set_availability(SafekeeperState::Available {
849 : utilization,
850 : last_seen_at,
851 : });
852 : }
853 : }
854 : *safekeepers = Arc::new(new_sks);
855 :
856 : for (tenant_shard_id, observed_state) in observed.0 {
857 : let Some(tenant_shard) = tenants.get_mut(&tenant_shard_id) else {
858 : for node_id in observed_state.locations.keys() {
859 : cleanup.push((tenant_shard_id, *node_id));
860 : }
861 :
862 : continue;
863 : };
864 :
865 : tenant_shard.observed = observed_state;
866 : }
867 :
868 : // Populate each tenant's intent state
869 : let mut schedule_context = ScheduleContext::default();
870 : for (tenant_shard_id, tenant_shard) in tenants.iter_mut() {
871 : if tenant_shard_id.shard_number == ShardNumber(0) {
872 : // Reset scheduling context each time we advance to the next Tenant
873 : schedule_context = ScheduleContext::default();
874 : }
875 :
876 : tenant_shard.intent_from_observed(scheduler);
877 : if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
878 : // Non-fatal error: we are unable to properly schedule the tenant, perhaps because
879 : // not enough pageservers are available. The tenant may well still be available
880 : // to clients.
881 : tracing::error!("Failed to schedule tenant {tenant_shard_id} at startup: {e}");
882 : } else {
883 : // If we're both intending and observed to be attached at a particular node, we will
884 : // emit a compute notification for this. In the case where our observed state does not
885 : // yet match our intent, we will eventually reconcile, and that will emit a compute notification.
886 : if let Some(attached_at) = tenant_shard.stably_attached() {
887 : compute_notifications.push(compute_hook::ShardUpdate {
888 : tenant_shard_id: *tenant_shard_id,
889 : node_id: attached_at,
890 : stripe_size: tenant_shard.shard.stripe_size,
891 : preferred_az: tenant_shard
892 : .preferred_az()
893 0 : .map(|az| Cow::Owned(az.clone())),
894 : });
895 : }
896 : }
897 : }
898 :
899 : tenants.len()
900 : };
901 :
902 : // Before making any obeservable changes to the cluster, persist self
903 : // as leader in database and memory.
904 : let leadership = Leadership::new(
905 : self.persistence.clone(),
906 : self.config.clone(),
907 : self.cancel.child_token(),
908 : );
909 :
910 : if let Err(e) = leadership.become_leader(current_leader).await {
911 : tracing::error!("Failed to persist self as leader: {e}. Aborting start-up ...");
912 : std::process::exit(1);
913 : }
914 :
915 : let safekeepers = self.inner.read().unwrap().safekeepers.clone();
916 : let sk_schedule_requests =
917 : match safekeeper_reconciler::load_schedule_requests(self, &safekeepers).await {
918 : Ok(v) => v,
919 : Err(e) => {
920 : tracing::warn!(
921 : "Failed to load safekeeper pending ops at startup: {e}." // Don't abort for now: " Aborting start-up..."
922 : );
923 : // std::process::exit(1);
924 : Vec::new()
925 : }
926 : };
927 :
928 : {
929 : let mut locked = self.inner.write().unwrap();
930 : locked.become_leader();
931 :
932 : for (sk_id, _sk) in locked.safekeepers.clone().iter() {
933 : locked.safekeeper_reconcilers.start_reconciler(*sk_id, self);
934 : }
935 :
936 : locked
937 : .safekeeper_reconcilers
938 : .schedule_request_vec(sk_schedule_requests);
939 : }
940 :
941 : // TODO: if any tenant's intent now differs from its loaded generation_pageserver, we should clear that
942 : // generation_pageserver in the database.
943 :
944 : // Emit compute hook notifications for all tenants which are already stably attached. Other tenants
945 : // will emit compute hook notifications when they reconcile.
946 : //
947 : // Ordering: our calls to notify_attach_background synchronously establish a relative order for these notifications vs. any later
948 : // calls into the ComputeHook for the same tenant: we can leave these to run to completion in the background and any later
949 : // calls will be correctly ordered wrt these.
950 : //
951 : // Concurrency: we call notify_attach_background for all tenants, which will create O(N) tokio tasks, but almost all of them
952 : // will just wait on the ComputeHook::API_CONCURRENCY semaphore immediately, so very cheap until they get that semaphore
953 : // unit and start doing I/O.
954 : tracing::info!(
955 : "Sending {} compute notifications",
956 : compute_notifications.len()
957 : );
958 : self.compute_hook.notify_attach_background(
959 : compute_notifications,
960 : bg_compute_notify_result_tx.clone(),
961 : &self.cancel,
962 : );
963 :
964 : // Finally, now that the service is up and running, launch reconcile operations for any tenants
965 : // which require it: under normal circumstances this should only include tenants that were in some
966 : // transient state before we restarted, or any tenants whose compute hooks failed above.
967 : tracing::info!("Checking for shards in need of reconciliation...");
968 : let reconcile_all_result = self.reconcile_all();
969 : // We will not wait for these reconciliation tasks to run here: we're now done with startup and
970 : // normal operations may proceed.
971 :
972 : // Clean up any tenants that were found on pageservers but are not known to us. Do this in the
973 : // background because it does not need to complete in order to proceed with other work.
974 : if !cleanup.is_empty() {
975 : tracing::info!("Cleaning up {} locations in the background", cleanup.len());
976 : tokio::task::spawn({
977 : let cleanup_self = self.clone();
978 0 : async move { cleanup_self.cleanup_locations(cleanup).await }
979 : });
980 : }
981 :
982 : // Reconcile the timeline imports:
983 : // 1. Mark each tenant shard of tenants with an importing timeline as importing.
984 : // 2. Finalize the completed imports in the background. This handles the case where
985 : // the previous storage controller instance shut down whilst finalizing imports.
986 : let imports = self.persistence.list_timeline_imports().await;
987 : match imports {
988 : Ok(mut imports) => {
989 : {
990 : let mut locked = self.inner.write().unwrap();
991 : for import in &imports {
992 : locked
993 : .tenants
994 : .range_mut(TenantShardId::tenant_range(import.tenant_id))
995 0 : .for_each(|(_id, shard)| {
996 0 : shard.importing = TimelineImportState::Importing
997 0 : });
998 : }
999 : }
1000 :
1001 0 : imports.retain(|import| import.is_complete());
1002 : tokio::task::spawn({
1003 : let finalize_imports_self = self.clone();
1004 0 : async move {
1005 0 : finalize_imports_self
1006 0 : .finalize_timeline_imports(imports)
1007 0 : .await
1008 0 : }
1009 : });
1010 : }
1011 : Err(err) => {
1012 : tracing::error!("Could not retrieve completed imports from database: {err}");
1013 : }
1014 : }
1015 :
1016 : let spawned_reconciles = reconcile_all_result.spawned_reconciles;
1017 : tracing::info!(
1018 : "Startup complete, spawned {spawned_reconciles} reconciliation tasks ({shard_count} shards total)"
1019 : );
1020 : }
1021 :
1022 0 : async fn initial_heartbeat_round<'a>(
1023 0 : &self,
1024 0 : node_ids: impl Iterator<Item = &'a NodeId>,
1025 0 : ) -> (
1026 0 : HashMap<NodeId, PageserverUtilization>,
1027 0 : HashMap<NodeId, (SafekeeperUtilization, Instant)>,
1028 0 : ) {
1029 0 : assert!(!self.startup_complete.is_ready());
1030 :
1031 0 : let all_nodes = {
1032 0 : let locked = self.inner.read().unwrap();
1033 0 : locked.nodes.clone()
1034 : };
1035 :
1036 0 : let mut nodes_to_heartbeat = HashMap::new();
1037 0 : for node_id in node_ids {
1038 0 : match all_nodes.get(node_id) {
1039 0 : Some(node) => {
1040 0 : nodes_to_heartbeat.insert(*node_id, node.clone());
1041 0 : }
1042 : None => {
1043 0 : tracing::warn!("Node {node_id} was removed during start-up");
1044 : }
1045 : }
1046 : }
1047 :
1048 0 : let all_sks = {
1049 0 : let locked = self.inner.read().unwrap();
1050 0 : locked.safekeepers.clone()
1051 : };
1052 :
1053 0 : tracing::info!("Sending initial heartbeats...");
1054 0 : let (res_ps, res_sk) = tokio::join!(
1055 0 : self.heartbeater_ps.heartbeat(Arc::new(nodes_to_heartbeat)),
1056 0 : self.heartbeater_sk.heartbeat(all_sks)
1057 : );
1058 :
1059 0 : let mut online_nodes = HashMap::new();
1060 0 : if let Ok(deltas) = res_ps {
1061 0 : for (node_id, status) in deltas.0 {
1062 0 : match status {
1063 0 : PageserverState::Available { utilization, .. } => {
1064 0 : online_nodes.insert(node_id, utilization);
1065 0 : }
1066 0 : PageserverState::Offline => {}
1067 : PageserverState::WarmingUp { .. } => {
1068 0 : unreachable!("Nodes are never marked warming-up during startup reconcile")
1069 : }
1070 : }
1071 : }
1072 0 : }
1073 :
1074 0 : let mut online_sks = HashMap::new();
1075 0 : if let Ok(deltas) = res_sk {
1076 0 : for (node_id, status) in deltas.0 {
1077 0 : match status {
1078 : SafekeeperState::Available {
1079 0 : utilization,
1080 0 : last_seen_at,
1081 0 : } => {
1082 0 : online_sks.insert(node_id, (utilization, last_seen_at));
1083 0 : }
1084 0 : SafekeeperState::Offline => {}
1085 : }
1086 : }
1087 0 : }
1088 :
1089 0 : (online_nodes, online_sks)
1090 0 : }
1091 :
1092 : /// Used during [`Self::startup_reconcile`]: issue GETs to all nodes concurrently, with a deadline.
1093 : ///
1094 : /// The result includes only nodes which responded within the deadline
1095 0 : async fn scan_node_locations(
1096 0 : &self,
1097 0 : deadline: Instant,
1098 0 : ) -> HashMap<NodeId, LocationConfigListResponse> {
1099 0 : let nodes = {
1100 0 : let locked = self.inner.read().unwrap();
1101 0 : locked.nodes.clone()
1102 : };
1103 :
1104 0 : let mut node_results = HashMap::new();
1105 :
1106 0 : let mut node_list_futs = FuturesUnordered::new();
1107 :
1108 0 : tracing::info!("Scanning shards on {} nodes...", nodes.len());
1109 0 : for node in nodes.values() {
1110 0 : node_list_futs.push({
1111 0 : async move {
1112 0 : tracing::info!("Scanning shards on node {node}...");
1113 0 : let timeout = Duration::from_secs(5);
1114 0 : let response = node
1115 0 : .with_client_retries(
1116 0 : |client| async move { client.list_location_config().await },
1117 0 : &self.http_client,
1118 0 : &self.config.pageserver_jwt_token,
1119 : 1,
1120 : 5,
1121 0 : timeout,
1122 0 : &self.cancel,
1123 : )
1124 0 : .await;
1125 0 : (node.get_id(), response)
1126 0 : }
1127 : });
1128 : }
1129 :
1130 : loop {
1131 0 : let (node_id, result) = tokio::select! {
1132 0 : next = node_list_futs.next() => {
1133 0 : match next {
1134 0 : Some(result) => result,
1135 : None =>{
1136 : // We got results for all our nodes
1137 0 : break;
1138 : }
1139 :
1140 : }
1141 : },
1142 0 : _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
1143 : // Give up waiting for anyone who hasn't responded: we will yield the results that we have
1144 0 : tracing::info!("Reached deadline while waiting for nodes to respond to location listing requests");
1145 0 : break;
1146 : }
1147 : };
1148 :
1149 0 : let Some(list_response) = result else {
1150 0 : tracing::info!("Shutdown during startup_reconcile");
1151 0 : break;
1152 : };
1153 :
1154 0 : match list_response {
1155 0 : Err(e) => {
1156 0 : tracing::warn!("Could not scan node {} ({e})", node_id);
1157 : }
1158 0 : Ok(listing) => {
1159 0 : node_results.insert(node_id, listing);
1160 0 : }
1161 : }
1162 : }
1163 :
1164 0 : node_results
1165 0 : }
1166 :
1167 0 : async fn build_global_observed_state(&self, deadline: Instant) -> GlobalObservedState {
1168 0 : let node_listings = self.scan_node_locations(deadline).await;
1169 0 : let mut observed = GlobalObservedState::default();
1170 :
1171 0 : for (node_id, location_confs) in node_listings {
1172 0 : tracing::info!(
1173 0 : "Received {} shard statuses from pageserver {}",
1174 0 : location_confs.tenant_shards.len(),
1175 : node_id
1176 : );
1177 :
1178 0 : for (tid, location_conf) in location_confs.tenant_shards {
1179 0 : let entry = observed.0.entry(tid).or_default();
1180 0 : entry.locations.insert(
1181 0 : node_id,
1182 0 : ObservedStateLocation {
1183 0 : conf: location_conf,
1184 0 : },
1185 0 : );
1186 0 : }
1187 : }
1188 :
1189 0 : observed
1190 0 : }
1191 :
1192 : /// Used during [`Self::startup_reconcile`] and shard splits: detach a list of unknown-to-us
1193 : /// tenants from pageservers.
1194 : ///
1195 : /// This is safe to run in the background, because if we don't have this TenantShardId in our map of
1196 : /// tenants, then it is probably something incompletely deleted before: we will not fight with any
1197 : /// other task trying to attach it.
1198 : #[instrument(skip_all)]
1199 : async fn cleanup_locations(&self, cleanup: Vec<(TenantShardId, NodeId)>) {
1200 : let nodes = self.inner.read().unwrap().nodes.clone();
1201 :
1202 : for (tenant_shard_id, node_id) in cleanup {
1203 : // A node reported a tenant_shard_id which is unknown to us: detach it.
1204 : let Some(node) = nodes.get(&node_id) else {
1205 : // This is legitimate; we run in the background and [`Self::startup_reconcile`] might have identified
1206 : // a location to clean up on a node that has since been removed.
1207 : tracing::info!(
1208 : "Not cleaning up location {node_id}/{tenant_shard_id}: node not found"
1209 : );
1210 : continue;
1211 : };
1212 :
1213 : if self.cancel.is_cancelled() {
1214 : break;
1215 : }
1216 :
1217 : let client = PageserverClient::new(
1218 : node.get_id(),
1219 : self.http_client.clone(),
1220 : node.base_url(),
1221 : self.config.pageserver_jwt_token.as_deref(),
1222 : );
1223 : match client
1224 : .location_config(
1225 : tenant_shard_id,
1226 : LocationConfig {
1227 : mode: LocationConfigMode::Detached,
1228 : generation: None,
1229 : secondary_conf: None,
1230 : shard_number: tenant_shard_id.shard_number.0,
1231 : shard_count: tenant_shard_id.shard_count.literal(),
1232 : shard_stripe_size: 0,
1233 : tenant_conf: models::TenantConfig::default(),
1234 : },
1235 : None,
1236 : false,
1237 : )
1238 : .await
1239 : {
1240 : Ok(()) => {
1241 : tracing::info!(
1242 : "Detached unknown shard {tenant_shard_id} on pageserver {node_id}"
1243 : );
1244 : }
1245 : Err(e) => {
1246 : // Non-fatal error: leaving a tenant shard behind that we are not managing shouldn't
1247 : // break anything.
1248 : tracing::error!(
1249 : "Failed to detach unknown shard {tenant_shard_id} on pageserver {node_id}: {e}"
1250 : );
1251 : }
1252 : }
1253 : }
1254 : }
1255 :
1256 : /// Long running background task that periodically wakes up and looks for shards that need
1257 : /// reconciliation. Reconciliation is fallible, so any reconciliation tasks that fail during
1258 : /// e.g. a tenant create/attach/migrate must eventually be retried: this task is responsible
1259 : /// for those retries.
1260 : #[instrument(skip_all)]
1261 : async fn background_reconcile(self: &Arc<Self>) {
1262 : self.startup_complete.clone().wait().await;
1263 :
1264 : const BACKGROUND_RECONCILE_PERIOD: Duration = Duration::from_secs(20);
1265 : let mut interval = tokio::time::interval(BACKGROUND_RECONCILE_PERIOD);
1266 : while !self.reconcilers_cancel.is_cancelled() {
1267 : tokio::select! {
1268 : _ = interval.tick() => {
1269 : let reconcile_all_result = self.reconcile_all();
1270 : if reconcile_all_result.can_run_optimizations() {
1271 : // Run optimizer only when we didn't find any other work to do
1272 : self.optimize_all().await;
1273 : }
1274 : // Always attempt autosplits. Sharding is crucial for bulk ingest performance, so we
1275 : // must be responsive when new projects begin ingesting and reach the threshold.
1276 : self.autosplit_tenants().await;
1277 : }
1278 : _ = self.reconcilers_cancel.cancelled() => return
1279 : }
1280 : }
1281 : }
1282 : /// Heartbeat all storage nodes once in a while.
1283 : #[instrument(skip_all)]
1284 : async fn spawn_heartbeat_driver(self: &Arc<Self>) {
1285 : self.startup_complete.clone().wait().await;
1286 :
1287 : let mut interval = tokio::time::interval(self.config.heartbeat_interval);
1288 : while !self.cancel.is_cancelled() {
1289 : tokio::select! {
1290 : _ = interval.tick() => { }
1291 : _ = self.cancel.cancelled() => return
1292 : };
1293 :
1294 : let nodes = {
1295 : let locked = self.inner.read().unwrap();
1296 : locked.nodes.clone()
1297 : };
1298 :
1299 : let safekeepers = {
1300 : let locked = self.inner.read().unwrap();
1301 : locked.safekeepers.clone()
1302 : };
1303 :
1304 : let (res_ps, res_sk) = tokio::join!(
1305 : self.heartbeater_ps.heartbeat(nodes),
1306 : self.heartbeater_sk.heartbeat(safekeepers)
1307 : );
1308 :
1309 : if let Ok(deltas) = res_ps {
1310 : let mut to_handle = Vec::default();
1311 :
1312 : for (node_id, state) in deltas.0 {
1313 : let new_availability = match state {
1314 : PageserverState::Available { utilization, .. } => {
1315 : NodeAvailability::Active(utilization)
1316 : }
1317 : PageserverState::WarmingUp { started_at } => {
1318 : NodeAvailability::WarmingUp(started_at)
1319 : }
1320 : PageserverState::Offline => {
1321 : // The node might have been placed in the WarmingUp state
1322 : // while the heartbeat round was on-going. Hence, filter out
1323 : // offline transitions for WarmingUp nodes that are still within
1324 : // their grace period.
1325 : if let Ok(NodeAvailability::WarmingUp(started_at)) = self
1326 : .get_node(node_id)
1327 : .await
1328 : .as_ref()
1329 0 : .map(|n| n.get_availability())
1330 : {
1331 : let now = Instant::now();
1332 : if now - *started_at >= self.config.max_warming_up_interval {
1333 : NodeAvailability::Offline
1334 : } else {
1335 : NodeAvailability::WarmingUp(*started_at)
1336 : }
1337 : } else {
1338 : NodeAvailability::Offline
1339 : }
1340 : }
1341 : };
1342 :
1343 : let node_lock = trace_exclusive_lock(
1344 : &self.node_op_locks,
1345 : node_id,
1346 : NodeOperations::Configure,
1347 : )
1348 : .await;
1349 :
1350 : pausable_failpoint!("heartbeat-pre-node-state-configure");
1351 :
1352 : // This is the code path for geniune availability transitions (i.e node
1353 : // goes unavailable and/or comes back online).
1354 : let res = self
1355 : .node_state_configure(node_id, Some(new_availability), None, &node_lock)
1356 : .await;
1357 :
1358 : match res {
1359 : Ok(transition) => {
1360 : // Keep hold of the lock until the availability transitions
1361 : // have been handled in
1362 : // [`Service::handle_node_availability_transitions`] in order avoid
1363 : // racing with [`Service::external_node_configure`].
1364 : to_handle.push((node_id, node_lock, transition));
1365 : }
1366 : Err(ApiError::NotFound(_)) => {
1367 : // This should be rare, but legitimate since the heartbeats are done
1368 : // on a snapshot of the nodes.
1369 : tracing::info!("Node {} was not found after heartbeat round", node_id);
1370 : }
1371 : Err(ApiError::ShuttingDown) => {
1372 : // No-op: we're shutting down, no need to try and update any nodes' statuses
1373 : }
1374 : Err(err) => {
1375 : // Transition to active involves reconciling: if a node responds to a heartbeat then
1376 : // becomes unavailable again, we may get an error here.
1377 : tracing::error!(
1378 : "Failed to update node state {} after heartbeat round: {}",
1379 : node_id,
1380 : err
1381 : );
1382 : }
1383 : }
1384 : }
1385 :
1386 : // We collected all the transitions above and now we handle them.
1387 : let res = self.handle_node_availability_transitions(to_handle).await;
1388 : if let Err(errs) = res {
1389 : for (node_id, err) in errs {
1390 : match err {
1391 : ApiError::NotFound(_) => {
1392 : // This should be rare, but legitimate since the heartbeats are done
1393 : // on a snapshot of the nodes.
1394 : tracing::info!(
1395 : "Node {} was not found after heartbeat round",
1396 : node_id
1397 : );
1398 : }
1399 : err => {
1400 : tracing::error!(
1401 : "Failed to handle availability transition for {} after heartbeat round: {}",
1402 : node_id,
1403 : err
1404 : );
1405 : }
1406 : }
1407 : }
1408 : }
1409 : }
1410 : if let Ok(deltas) = res_sk {
1411 : let mut to_activate = Vec::new();
1412 : {
1413 : let mut locked = self.inner.write().unwrap();
1414 : let mut safekeepers = (*locked.safekeepers).clone();
1415 :
1416 : for (id, state) in deltas.0 {
1417 : let Some(sk) = safekeepers.get_mut(&id) else {
1418 : tracing::info!(
1419 : "Couldn't update safekeeper safekeeper state for id {id} from heartbeat={state:?}"
1420 : );
1421 : continue;
1422 : };
1423 : if sk.scheduling_policy() == SkSchedulingPolicy::Activating
1424 : && let SafekeeperState::Available { .. } = state
1425 : {
1426 : to_activate.push(id);
1427 : }
1428 : sk.set_availability(state);
1429 : }
1430 : locked.safekeepers = Arc::new(safekeepers);
1431 : }
1432 : for sk_id in to_activate {
1433 : // TODO this can race with set_scheduling_policy (can create disjoint DB <-> in-memory state)
1434 : tracing::info!("Activating safekeeper {sk_id}");
1435 : match self.persistence.activate_safekeeper(sk_id.0 as i64).await {
1436 : Ok(Some(())) => {}
1437 : Ok(None) => {
1438 : tracing::info!(
1439 : "safekeeper {sk_id} has been removed from db or has different scheduling policy than active or activating"
1440 : );
1441 : }
1442 : Err(e) => {
1443 : tracing::warn!("couldn't apply activation of {sk_id} to db: {e}");
1444 : continue;
1445 : }
1446 : }
1447 : if let Err(e) = self
1448 : .set_safekeeper_scheduling_policy_in_mem(sk_id, SkSchedulingPolicy::Active)
1449 : .await
1450 : {
1451 : tracing::info!("couldn't activate safekeeper {sk_id} in memory: {e}");
1452 : continue;
1453 : }
1454 : tracing::info!("Activation of safekeeper {sk_id} done");
1455 : }
1456 : }
1457 : }
1458 : }
1459 :
1460 : /// Apply the contents of a [`ReconcileResult`] to our in-memory state: if the reconciliation
1461 : /// was successful and intent hasn't changed since the Reconciler was spawned, this will update
1462 : /// the observed state of the tenant such that subsequent calls to [`TenantShard::get_reconcile_needed`]
1463 : /// will indicate that reconciliation is not needed.
1464 : #[instrument(skip_all, fields(
1465 : seq=%result.sequence,
1466 : tenant_id=%result.tenant_shard_id.tenant_id,
1467 : shard_id=%result.tenant_shard_id.shard_slug(),
1468 : ))]
1469 : fn process_result(&self, result: ReconcileResult) {
1470 : let mut locked = self.inner.write().unwrap();
1471 : let (nodes, tenants, _scheduler) = locked.parts_mut();
1472 : let Some(tenant) = tenants.get_mut(&result.tenant_shard_id) else {
1473 : // A reconciliation result might race with removing a tenant: drop results for
1474 : // tenants that aren't in our map.
1475 : return;
1476 : };
1477 :
1478 : // Usually generation should only be updated via this path, so the max() isn't
1479 : // needed, but it is used to handle out-of-band updates via. e.g. test hook.
1480 : tenant.generation = std::cmp::max(tenant.generation, result.generation);
1481 :
1482 : // If the reconciler signals that it failed to notify compute, set this state on
1483 : // the shard so that a future [`TenantShard::maybe_reconcile`] will try again.
1484 : tenant.pending_compute_notification = result.pending_compute_notification;
1485 :
1486 : // Let the TenantShard know it is idle.
1487 : tenant.reconcile_complete(result.sequence);
1488 :
1489 : // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
1490 : // make to the tenant
1491 0 : let deltas = result.observed_deltas.into_iter().flat_map(|delta| {
1492 : // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
1493 : // make to the tenant
1494 0 : let node = nodes.get(delta.node_id())?;
1495 :
1496 0 : if node.is_available() {
1497 0 : return Some(delta);
1498 0 : }
1499 :
1500 : // In case a node became unavailable concurrently with the reconcile, observed
1501 : // locations on it are now uncertain. By convention, set them to None in order
1502 : // for them to get refreshed when the node comes back online.
1503 0 : Some(ObservedStateDelta::Upsert(Box::new((
1504 0 : node.get_id(),
1505 0 : ObservedStateLocation { conf: None },
1506 0 : ))))
1507 0 : });
1508 :
1509 : match result.result {
1510 : Ok(()) => {
1511 : tenant.apply_observed_deltas(deltas);
1512 : tenant.waiter.advance(result.sequence);
1513 : }
1514 : Err(e) => {
1515 : match e {
1516 : ReconcileError::Cancel => {
1517 : tracing::info!("Reconciler was cancelled");
1518 : }
1519 : ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
1520 : // This might be due to the reconciler getting cancelled, or it might
1521 : // be due to the `Node` being marked offline.
1522 : tracing::info!("Reconciler cancelled during pageserver API call");
1523 : }
1524 : _ => {
1525 : tracing::warn!("Reconcile error: {}", e);
1526 : }
1527 : }
1528 :
1529 : // Ordering: populate last_error before advancing error_seq,
1530 : // so that waiters will see the correct error after waiting.
1531 : tenant.set_last_error(result.sequence, e);
1532 :
1533 : // If the reconciliation failed, don't clear the observed state for places where we
1534 : // detached. Instead, mark the observed state as uncertain.
1535 0 : let failed_reconcile_deltas = deltas.map(|delta| {
1536 0 : if let ObservedStateDelta::Delete(node_id) = delta {
1537 0 : ObservedStateDelta::Upsert(Box::new((
1538 0 : node_id,
1539 0 : ObservedStateLocation { conf: None },
1540 0 : )))
1541 : } else {
1542 0 : delta
1543 : }
1544 0 : });
1545 : tenant.apply_observed_deltas(failed_reconcile_deltas);
1546 : }
1547 : }
1548 :
1549 : tenant.consecutive_reconciles_count = tenant.consecutive_reconciles_count.saturating_add(1);
1550 :
1551 : // If we just finished detaching all shards for a tenant, it might be time to drop it from memory.
1552 : if tenant.policy == PlacementPolicy::Detached {
1553 : // We may only drop a tenant from memory while holding the exclusive lock on the tenant ID: this protects us
1554 : // from concurrent execution wrt a request handler that might expect the tenant to remain in memory for the
1555 : // duration of the request.
1556 : let guard = self.tenant_op_locks.try_exclusive(
1557 : tenant.tenant_shard_id.tenant_id,
1558 : TenantOperations::DropDetached,
1559 : );
1560 : if let Some(guard) = guard {
1561 : self.maybe_drop_tenant(tenant.tenant_shard_id.tenant_id, &mut locked, &guard);
1562 : }
1563 : }
1564 :
1565 : // Maybe some other work can proceed now that this job finished.
1566 : //
1567 : // Only bother with this if we have some semaphore units available in the normal-priority semaphore (these
1568 : // reconciles are scheduled at `[ReconcilerPriority::Normal]`).
1569 : if self.reconciler_concurrency.available_permits() > 0 {
1570 : while let Ok(tenant_shard_id) = locked.delayed_reconcile_rx.try_recv() {
1571 : let (nodes, tenants, _scheduler) = locked.parts_mut();
1572 : if let Some(shard) = tenants.get_mut(&tenant_shard_id) {
1573 : shard.delayed_reconcile = false;
1574 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
1575 : }
1576 :
1577 : if self.reconciler_concurrency.available_permits() == 0 {
1578 : break;
1579 : }
1580 : }
1581 : }
1582 : }
1583 :
1584 0 : async fn process_results(
1585 0 : &self,
1586 0 : mut result_rx: tokio::sync::mpsc::UnboundedReceiver<ReconcileResultRequest>,
1587 0 : mut bg_compute_hook_result_rx: tokio::sync::mpsc::Receiver<
1588 0 : Result<(), (TenantShardId, NotifyError)>,
1589 0 : >,
1590 0 : ) {
1591 : loop {
1592 : // Wait for the next result, or for cancellation
1593 0 : tokio::select! {
1594 0 : r = result_rx.recv() => {
1595 0 : match r {
1596 0 : Some(ReconcileResultRequest::ReconcileResult(result)) => {self.process_result(result);},
1597 0 : None | Some(ReconcileResultRequest::Stop) => {break;}
1598 : }
1599 : }
1600 0 : _ = async{
1601 0 : match bg_compute_hook_result_rx.recv().await {
1602 0 : Some(result) => {
1603 0 : if let Err((tenant_shard_id, notify_error)) = result {
1604 0 : tracing::warn!("Marking shard {tenant_shard_id} for notification retry, due to error {notify_error}");
1605 0 : let mut locked = self.inner.write().unwrap();
1606 0 : if let Some(shard) = locked.tenants.get_mut(&tenant_shard_id) {
1607 0 : shard.pending_compute_notification = true;
1608 0 : }
1609 :
1610 0 : }
1611 : },
1612 : None => {
1613 : // This channel is dead, but we don't want to terminate the outer loop{}: just wait for shutdown
1614 0 : self.cancel.cancelled().await;
1615 : }
1616 : }
1617 0 : } => {},
1618 0 : _ = self.cancel.cancelled() => {
1619 0 : break;
1620 : }
1621 : };
1622 : }
1623 0 : }
1624 :
1625 0 : async fn process_aborts(
1626 0 : &self,
1627 0 : mut abort_rx: tokio::sync::mpsc::UnboundedReceiver<TenantShardSplitAbort>,
1628 0 : ) {
1629 : loop {
1630 : // Wait for the next result, or for cancellation
1631 0 : let op = tokio::select! {
1632 0 : r = abort_rx.recv() => {
1633 0 : match r {
1634 0 : Some(op) => {op},
1635 0 : None => {break;}
1636 : }
1637 : }
1638 0 : _ = self.cancel.cancelled() => {
1639 0 : break;
1640 : }
1641 : };
1642 :
1643 : // Retry until shutdown: we must keep this request object alive until it is properly
1644 : // processed, as it holds a lock guard that prevents other operations trying to do things
1645 : // to the tenant while it is in a weird part-split state.
1646 0 : while !self.reconcilers_cancel.is_cancelled() {
1647 0 : match self.abort_tenant_shard_split(&op).await {
1648 0 : Ok(_) => break,
1649 0 : Err(e) => {
1650 0 : tracing::warn!(
1651 0 : "Failed to abort shard split on {}, will retry: {e}",
1652 : op.tenant_id
1653 : );
1654 :
1655 : // If a node is unavailable, we hope that it has been properly marked Offline
1656 : // when we retry, so that the abort op will succeed. If the abort op is failing
1657 : // for some other reason, we will keep retrying forever, or until a human notices
1658 : // and does something about it (either fixing a pageserver or restarting the controller).
1659 0 : tokio::time::timeout(
1660 0 : Duration::from_secs(5),
1661 0 : self.reconcilers_cancel.cancelled(),
1662 0 : )
1663 0 : .await
1664 0 : .ok();
1665 : }
1666 : }
1667 : }
1668 : }
1669 0 : }
1670 :
1671 0 : pub async fn spawn(config: Config, persistence: Arc<Persistence>) -> anyhow::Result<Arc<Self>> {
1672 0 : let (result_tx, result_rx) = tokio::sync::mpsc::unbounded_channel();
1673 0 : let (abort_tx, abort_rx) = tokio::sync::mpsc::unbounded_channel();
1674 :
1675 0 : let leadership_cancel = CancellationToken::new();
1676 0 : let leadership = Leadership::new(persistence.clone(), config.clone(), leadership_cancel);
1677 0 : let (leader, leader_step_down_state) = leadership.step_down_current_leader().await?;
1678 :
1679 : // Apply the migrations **after** the current leader has stepped down
1680 : // (or we've given up waiting for it), but **before** reading from the
1681 : // database. The only exception is reading the current leader before
1682 : // migrating.
1683 0 : persistence.migration_run().await?;
1684 :
1685 0 : tracing::info!("Loading nodes from database...");
1686 0 : let nodes = persistence
1687 0 : .list_nodes()
1688 0 : .await?
1689 0 : .into_iter()
1690 0 : .map(|x| Node::from_persistent(x, config.use_https_pageserver_api))
1691 0 : .collect::<anyhow::Result<Vec<Node>>>()?;
1692 0 : let nodes: HashMap<NodeId, Node> = nodes.into_iter().map(|n| (n.get_id(), n)).collect();
1693 0 : tracing::info!("Loaded {} nodes from database.", nodes.len());
1694 0 : metrics::METRICS_REGISTRY
1695 0 : .metrics_group
1696 0 : .storage_controller_pageserver_nodes
1697 0 : .set(nodes.len() as i64);
1698 0 : metrics::METRICS_REGISTRY
1699 0 : .metrics_group
1700 0 : .storage_controller_https_pageserver_nodes
1701 0 : .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
1702 :
1703 0 : tracing::info!("Loading safekeepers from database...");
1704 0 : let safekeepers = persistence
1705 0 : .list_safekeepers()
1706 0 : .await?
1707 0 : .into_iter()
1708 0 : .map(|skp| {
1709 0 : Safekeeper::from_persistence(
1710 0 : skp,
1711 0 : CancellationToken::new(),
1712 0 : config.use_https_safekeeper_api,
1713 : )
1714 0 : })
1715 0 : .collect::<anyhow::Result<Vec<_>>>()?;
1716 0 : let safekeepers: HashMap<NodeId, Safekeeper> =
1717 0 : safekeepers.into_iter().map(|n| (n.get_id(), n)).collect();
1718 0 : let count_policy = |policy| {
1719 0 : safekeepers
1720 0 : .iter()
1721 0 : .filter(|sk| sk.1.scheduling_policy() == policy)
1722 0 : .count()
1723 0 : };
1724 0 : let active_sk_count = count_policy(SkSchedulingPolicy::Active);
1725 0 : let activating_sk_count = count_policy(SkSchedulingPolicy::Activating);
1726 0 : let pause_sk_count = count_policy(SkSchedulingPolicy::Pause);
1727 0 : let decom_sk_count = count_policy(SkSchedulingPolicy::Decomissioned);
1728 0 : tracing::info!(
1729 0 : "Loaded {} safekeepers from database. Active {active_sk_count}, activating {activating_sk_count}, \
1730 0 : paused {pause_sk_count}, decomissioned {decom_sk_count}.",
1731 0 : safekeepers.len()
1732 : );
1733 0 : metrics::METRICS_REGISTRY
1734 0 : .metrics_group
1735 0 : .storage_controller_safekeeper_nodes
1736 0 : .set(safekeepers.len() as i64);
1737 0 : metrics::METRICS_REGISTRY
1738 0 : .metrics_group
1739 0 : .storage_controller_https_safekeeper_nodes
1740 0 : .set(safekeepers.values().filter(|s| s.has_https_port()).count() as i64);
1741 :
1742 0 : tracing::info!("Loading shards from database...");
1743 0 : let mut tenant_shard_persistence = persistence.load_active_tenant_shards().await?;
1744 0 : tracing::info!(
1745 0 : "Loaded {} shards from database.",
1746 0 : tenant_shard_persistence.len()
1747 : );
1748 :
1749 : // If any shard splits were in progress, reset the database state to abort them
1750 0 : let mut tenant_shard_count_min_max: HashMap<TenantId, (ShardCount, ShardCount)> =
1751 0 : HashMap::new();
1752 0 : for tsp in &mut tenant_shard_persistence {
1753 0 : let shard = tsp.get_shard_identity()?;
1754 0 : let tenant_shard_id = tsp.get_tenant_shard_id()?;
1755 0 : let entry = tenant_shard_count_min_max
1756 0 : .entry(tenant_shard_id.tenant_id)
1757 0 : .or_insert_with(|| (shard.count, shard.count));
1758 0 : entry.0 = std::cmp::min(entry.0, shard.count);
1759 0 : entry.1 = std::cmp::max(entry.1, shard.count);
1760 : }
1761 :
1762 0 : for (tenant_id, (count_min, count_max)) in tenant_shard_count_min_max {
1763 0 : if count_min != count_max {
1764 : // Aborting the split in the database and dropping the child shards is sufficient: the reconciliation in
1765 : // [`Self::startup_reconcile`] will implicitly drop the child shards on remote pageservers, or they'll
1766 : // be dropped later in [`Self::node_activate_reconcile`] if it isn't available right now.
1767 0 : tracing::info!("Aborting shard split {tenant_id} {count_min:?} -> {count_max:?}");
1768 0 : let abort_status = persistence.abort_shard_split(tenant_id, count_max).await?;
1769 :
1770 : // We may never see the Complete status here: if the split was complete, we wouldn't have
1771 : // identified this tenant has having mismatching min/max counts.
1772 0 : assert!(matches!(abort_status, AbortShardSplitStatus::Aborted));
1773 :
1774 : // Clear the splitting status in-memory, to reflect that we just aborted in the database
1775 0 : tenant_shard_persistence.iter_mut().for_each(|tsp| {
1776 : // Set idle split state on those shards that we will retain.
1777 0 : let tsp_tenant_id = TenantId::from_str(tsp.tenant_id.as_str()).unwrap();
1778 0 : if tsp_tenant_id == tenant_id
1779 0 : && tsp.get_shard_identity().unwrap().count == count_min
1780 0 : {
1781 0 : tsp.splitting = SplitState::Idle;
1782 0 : } else if tsp_tenant_id == tenant_id {
1783 : // Leave the splitting state on the child shards: this will be used next to
1784 : // drop them.
1785 0 : tracing::info!(
1786 0 : "Shard {tsp_tenant_id} will be dropped after shard split abort",
1787 : );
1788 0 : }
1789 0 : });
1790 :
1791 : // Drop shards for this tenant which we didn't just mark idle (i.e. child shards of the aborted split)
1792 0 : tenant_shard_persistence.retain(|tsp| {
1793 0 : TenantId::from_str(tsp.tenant_id.as_str()).unwrap() != tenant_id
1794 0 : || tsp.splitting == SplitState::Idle
1795 0 : });
1796 0 : }
1797 : }
1798 :
1799 0 : let mut tenants = BTreeMap::new();
1800 :
1801 0 : let mut scheduler = Scheduler::new(nodes.values());
1802 :
1803 : #[cfg(feature = "testing")]
1804 : {
1805 : use pageserver_api::controller_api::AvailabilityZone;
1806 :
1807 : // Hack: insert scheduler state for all nodes referenced by shards, as compatibility
1808 : // tests only store the shards, not the nodes. The nodes will be loaded shortly
1809 : // after when pageservers start up and register.
1810 0 : let mut node_ids = HashSet::new();
1811 0 : for tsp in &tenant_shard_persistence {
1812 0 : if let Some(node_id) = tsp.generation_pageserver {
1813 0 : node_ids.insert(node_id);
1814 0 : }
1815 : }
1816 0 : for node_id in node_ids {
1817 0 : tracing::info!("Creating node {} in scheduler for tests", node_id);
1818 0 : let node = Node::new(
1819 0 : NodeId(node_id as u64),
1820 0 : "".to_string(),
1821 : 123,
1822 0 : None,
1823 0 : "".to_string(),
1824 : 123,
1825 0 : None,
1826 0 : None,
1827 0 : AvailabilityZone("test_az".to_string()),
1828 : false,
1829 : )
1830 0 : .unwrap();
1831 :
1832 0 : scheduler.node_upsert(&node);
1833 : }
1834 : }
1835 0 : for tsp in tenant_shard_persistence {
1836 0 : let tenant_shard_id = tsp.get_tenant_shard_id()?;
1837 :
1838 : // We will populate intent properly later in [`Self::startup_reconcile`], initially populate
1839 : // it with what we can infer: the node for which a generation was most recently issued.
1840 0 : let mut intent = IntentState::new(
1841 0 : tsp.preferred_az_id
1842 0 : .as_ref()
1843 0 : .map(|az| AvailabilityZone(az.clone())),
1844 : );
1845 0 : if let Some(generation_pageserver) = tsp.generation_pageserver.map(|n| NodeId(n as u64))
1846 : {
1847 0 : if nodes.contains_key(&generation_pageserver) {
1848 0 : intent.set_attached(&mut scheduler, Some(generation_pageserver));
1849 0 : } else {
1850 : // If a node was removed before being completely drained, it is legal for it to leave behind a `generation_pageserver` referring
1851 : // to a non-existent node, because node deletion doesn't block on completing the reconciliations that will issue new generations
1852 : // on different pageservers.
1853 0 : tracing::warn!(
1854 0 : "Tenant shard {tenant_shard_id} references non-existent node {generation_pageserver} in database, will be rescheduled"
1855 : );
1856 : }
1857 0 : }
1858 0 : let new_tenant = TenantShard::from_persistent(tsp, intent)?;
1859 :
1860 0 : tenants.insert(tenant_shard_id, new_tenant);
1861 : }
1862 :
1863 0 : let (startup_completion, startup_complete) = utils::completion::channel();
1864 :
1865 : // This channel is continuously consumed by process_results, so doesn't need to be very large.
1866 0 : let (bg_compute_notify_result_tx, bg_compute_notify_result_rx) =
1867 0 : tokio::sync::mpsc::channel(512);
1868 :
1869 0 : let (delayed_reconcile_tx, delayed_reconcile_rx) =
1870 0 : tokio::sync::mpsc::channel(MAX_DELAYED_RECONCILES);
1871 :
1872 0 : let cancel = CancellationToken::new();
1873 0 : let reconcilers_cancel = cancel.child_token();
1874 :
1875 0 : let mut http_client = reqwest::Client::builder();
1876 : // We intentionally disable the connection pool, so every request will create its own TCP connection.
1877 : // It's especially important for heartbeaters to notice more network problems.
1878 : //
1879 : // TODO: It makes sense to use this client only in heartbeaters and create a second one with
1880 : // connection pooling for everything else. But reqwest::Client may create a connection without
1881 : // ever using it (it uses hyper's Client under the hood):
1882 : // https://github.com/hyperium/hyper-util/blob/d51318df3461d40e5f5e5ca163cb3905ac960209/src/client/legacy/client.rs#L415
1883 : //
1884 : // Because of a bug in hyper0::Connection::graceful_shutdown such connections hang during
1885 : // graceful server shutdown: https://github.com/hyperium/hyper/issues/2730
1886 : //
1887 : // The bug has been fixed in hyper v1, so keep alive may be enabled only after we migrate to hyper1.
1888 0 : http_client = http_client.pool_max_idle_per_host(0);
1889 0 : for ssl_ca_cert in &config.ssl_ca_certs {
1890 0 : http_client = http_client.add_root_certificate(ssl_ca_cert.clone());
1891 0 : }
1892 0 : let http_client = http_client.build()?;
1893 :
1894 0 : let heartbeater_ps = Heartbeater::new(
1895 0 : http_client.clone(),
1896 0 : config.pageserver_jwt_token.clone(),
1897 0 : config.max_offline_interval,
1898 0 : config.max_warming_up_interval,
1899 0 : cancel.clone(),
1900 : );
1901 :
1902 0 : let heartbeater_sk = Heartbeater::new(
1903 0 : http_client.clone(),
1904 0 : config.safekeeper_jwt_token.clone(),
1905 0 : config.max_offline_interval,
1906 0 : config.max_warming_up_interval,
1907 0 : cancel.clone(),
1908 : );
1909 :
1910 0 : let initial_leadership_status = if config.start_as_candidate {
1911 0 : LeadershipStatus::Candidate
1912 : } else {
1913 0 : LeadershipStatus::Leader
1914 : };
1915 :
1916 0 : let this = Arc::new(Self {
1917 0 : inner: Arc::new(std::sync::RwLock::new(ServiceState::new(
1918 0 : nodes,
1919 0 : safekeepers,
1920 0 : tenants,
1921 0 : scheduler,
1922 0 : delayed_reconcile_rx,
1923 0 : initial_leadership_status,
1924 0 : reconcilers_cancel.clone(),
1925 : ))),
1926 0 : config: config.clone(),
1927 0 : persistence,
1928 0 : compute_hook: Arc::new(ComputeHook::new(config.clone())?),
1929 0 : result_tx,
1930 0 : heartbeater_ps,
1931 0 : heartbeater_sk,
1932 0 : reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
1933 0 : config.reconciler_concurrency,
1934 : )),
1935 0 : priority_reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
1936 0 : config.priority_reconciler_concurrency,
1937 : )),
1938 0 : delayed_reconcile_tx,
1939 0 : abort_tx,
1940 0 : startup_complete: startup_complete.clone(),
1941 0 : cancel,
1942 0 : reconcilers_cancel,
1943 0 : gate: Gate::default(),
1944 0 : reconcilers_gate: Gate::default(),
1945 0 : tenant_op_locks: Default::default(),
1946 0 : node_op_locks: Default::default(),
1947 0 : http_client,
1948 0 : step_down_barrier: Default::default(),
1949 : });
1950 :
1951 0 : let result_task_this = this.clone();
1952 0 : tokio::task::spawn(async move {
1953 : // Block shutdown until we're done (we must respect self.cancel)
1954 0 : if let Ok(_gate) = result_task_this.gate.enter() {
1955 0 : result_task_this
1956 0 : .process_results(result_rx, bg_compute_notify_result_rx)
1957 0 : .await
1958 0 : }
1959 0 : });
1960 :
1961 0 : tokio::task::spawn({
1962 0 : let this = this.clone();
1963 0 : async move {
1964 : // Block shutdown until we're done (we must respect self.cancel)
1965 0 : if let Ok(_gate) = this.gate.enter() {
1966 0 : this.process_aborts(abort_rx).await
1967 0 : }
1968 0 : }
1969 : });
1970 :
1971 0 : tokio::task::spawn({
1972 0 : let this = this.clone();
1973 0 : async move {
1974 0 : if let Ok(_gate) = this.gate.enter() {
1975 : loop {
1976 0 : tokio::select! {
1977 0 : _ = this.cancel.cancelled() => {
1978 0 : break;
1979 : },
1980 0 : _ = tokio::time::sleep(Duration::from_secs(60)) => {}
1981 : };
1982 0 : this.tenant_op_locks.housekeeping();
1983 : }
1984 0 : }
1985 0 : }
1986 : });
1987 :
1988 0 : tokio::task::spawn({
1989 0 : let this = this.clone();
1990 : // We will block the [`Service::startup_complete`] barrier until [`Self::startup_reconcile`]
1991 : // is done.
1992 0 : let startup_completion = startup_completion.clone();
1993 0 : async move {
1994 : // Block shutdown until we're done (we must respect self.cancel)
1995 0 : let Ok(_gate) = this.gate.enter() else {
1996 0 : return;
1997 : };
1998 :
1999 0 : this.startup_reconcile(leader, leader_step_down_state, bg_compute_notify_result_tx)
2000 0 : .await;
2001 :
2002 0 : drop(startup_completion);
2003 0 : }
2004 : });
2005 :
2006 0 : tokio::task::spawn({
2007 0 : let this = this.clone();
2008 0 : let startup_complete = startup_complete.clone();
2009 0 : async move {
2010 0 : startup_complete.wait().await;
2011 0 : this.background_reconcile().await;
2012 0 : }
2013 : });
2014 :
2015 0 : tokio::task::spawn({
2016 0 : let this = this.clone();
2017 0 : let startup_complete = startup_complete.clone();
2018 0 : async move {
2019 0 : startup_complete.wait().await;
2020 0 : this.spawn_heartbeat_driver().await;
2021 0 : }
2022 : });
2023 :
2024 : // Check that there is enough safekeepers configured that we can create new timelines
2025 0 : let test_sk_res_str = match this.safekeepers_for_new_timeline().await {
2026 0 : Ok(v) => format!("Ok({v:?})"),
2027 0 : Err(v) => format!("Err({v:})"),
2028 : };
2029 0 : tracing::info!(
2030 : timeline_safekeeper_count = config.timeline_safekeeper_count,
2031 : timelines_onto_safekeepers = config.timelines_onto_safekeepers,
2032 0 : "viability test result (test timeline creation on safekeepers): {test_sk_res_str}",
2033 : );
2034 :
2035 0 : Ok(this)
2036 0 : }
2037 :
2038 0 : pub(crate) async fn attach_hook(
2039 0 : &self,
2040 0 : attach_req: AttachHookRequest,
2041 0 : ) -> anyhow::Result<AttachHookResponse> {
2042 0 : let _tenant_lock = trace_exclusive_lock(
2043 0 : &self.tenant_op_locks,
2044 0 : attach_req.tenant_shard_id.tenant_id,
2045 0 : TenantOperations::AttachHook,
2046 0 : )
2047 0 : .await;
2048 :
2049 : // This is a test hook. To enable using it on tenants that were created directly with
2050 : // the pageserver API (not via this service), we will auto-create any missing tenant
2051 : // shards with default state.
2052 0 : let insert = {
2053 0 : match self
2054 0 : .maybe_load_tenant(attach_req.tenant_shard_id.tenant_id, &_tenant_lock)
2055 0 : .await
2056 : {
2057 0 : Ok(_) => false,
2058 0 : Err(ApiError::NotFound(_)) => true,
2059 0 : Err(e) => return Err(e.into()),
2060 : }
2061 : };
2062 :
2063 0 : if insert {
2064 0 : let config = attach_req.config.clone().unwrap_or_default();
2065 0 : let tsp = TenantShardPersistence {
2066 0 : tenant_id: attach_req.tenant_shard_id.tenant_id.to_string(),
2067 0 : shard_number: attach_req.tenant_shard_id.shard_number.0 as i32,
2068 0 : shard_count: attach_req.tenant_shard_id.shard_count.literal() as i32,
2069 0 : shard_stripe_size: 0,
2070 0 : generation: attach_req.generation_override.or(Some(0)),
2071 0 : generation_pageserver: None,
2072 0 : placement_policy: serde_json::to_string(&PlacementPolicy::Attached(0)).unwrap(),
2073 0 : config: serde_json::to_string(&config).unwrap(),
2074 0 : splitting: SplitState::default(),
2075 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
2076 0 : .unwrap(),
2077 0 : preferred_az_id: None,
2078 0 : };
2079 :
2080 0 : match self.persistence.insert_tenant_shards(vec![tsp]).await {
2081 0 : Err(e) => match e {
2082 : DatabaseError::Query(diesel::result::Error::DatabaseError(
2083 : DatabaseErrorKind::UniqueViolation,
2084 : _,
2085 : )) => {
2086 0 : tracing::info!(
2087 0 : "Raced with another request to insert tenant {}",
2088 : attach_req.tenant_shard_id
2089 : )
2090 : }
2091 0 : _ => return Err(e.into()),
2092 : },
2093 : Ok(()) => {
2094 0 : tracing::info!("Inserted shard {} in database", attach_req.tenant_shard_id);
2095 :
2096 0 : let mut shard = TenantShard::new(
2097 0 : attach_req.tenant_shard_id,
2098 0 : ShardIdentity::unsharded(),
2099 0 : PlacementPolicy::Attached(0),
2100 0 : None,
2101 : );
2102 0 : shard.config = config;
2103 :
2104 0 : let mut locked = self.inner.write().unwrap();
2105 0 : locked.tenants.insert(attach_req.tenant_shard_id, shard);
2106 0 : tracing::info!("Inserted shard {} in memory", attach_req.tenant_shard_id);
2107 : }
2108 : }
2109 0 : }
2110 :
2111 0 : let new_generation = if let Some(req_node_id) = attach_req.node_id {
2112 0 : let maybe_tenant_conf = {
2113 0 : let locked = self.inner.write().unwrap();
2114 0 : locked
2115 0 : .tenants
2116 0 : .get(&attach_req.tenant_shard_id)
2117 0 : .map(|t| t.config.clone())
2118 : };
2119 :
2120 0 : match maybe_tenant_conf {
2121 0 : Some(conf) => {
2122 0 : let new_generation = self
2123 0 : .persistence
2124 0 : .increment_generation(attach_req.tenant_shard_id, req_node_id)
2125 0 : .await?;
2126 :
2127 : // Persist the placement policy update. This is required
2128 : // when we reattaching a detached tenant.
2129 0 : self.persistence
2130 0 : .update_tenant_shard(
2131 0 : TenantFilter::Shard(attach_req.tenant_shard_id),
2132 0 : Some(PlacementPolicy::Attached(0)),
2133 0 : Some(conf),
2134 0 : None,
2135 0 : None,
2136 0 : )
2137 0 : .await?;
2138 0 : Some(new_generation)
2139 : }
2140 : None => {
2141 0 : anyhow::bail!("Attach hook handling raced with tenant removal")
2142 : }
2143 : }
2144 : } else {
2145 0 : self.persistence.detach(attach_req.tenant_shard_id).await?;
2146 0 : None
2147 : };
2148 :
2149 0 : let mut locked = self.inner.write().unwrap();
2150 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
2151 :
2152 0 : let tenant_shard = tenants
2153 0 : .get_mut(&attach_req.tenant_shard_id)
2154 0 : .expect("Checked for existence above");
2155 :
2156 0 : if let Some(new_generation) = new_generation {
2157 0 : tenant_shard.generation = Some(new_generation);
2158 0 : tenant_shard.policy = PlacementPolicy::Attached(0);
2159 0 : } else {
2160 : // This is a detach notification. We must update placement policy to avoid re-attaching
2161 : // during background scheduling/reconciliation, or during storage controller restart.
2162 0 : assert!(attach_req.node_id.is_none());
2163 0 : tenant_shard.policy = PlacementPolicy::Detached;
2164 : }
2165 :
2166 0 : if let Some(attaching_pageserver) = attach_req.node_id.as_ref() {
2167 0 : tracing::info!(
2168 : tenant_id = %attach_req.tenant_shard_id,
2169 : ps_id = %attaching_pageserver,
2170 : generation = ?tenant_shard.generation,
2171 0 : "issuing",
2172 : );
2173 0 : } else if let Some(ps_id) = tenant_shard.intent.get_attached() {
2174 0 : tracing::info!(
2175 : tenant_id = %attach_req.tenant_shard_id,
2176 : %ps_id,
2177 : generation = ?tenant_shard.generation,
2178 0 : "dropping",
2179 : );
2180 : } else {
2181 0 : tracing::info!(
2182 : tenant_id = %attach_req.tenant_shard_id,
2183 0 : "no-op: tenant already has no pageserver");
2184 : }
2185 0 : tenant_shard
2186 0 : .intent
2187 0 : .set_attached(scheduler, attach_req.node_id);
2188 :
2189 0 : tracing::info!(
2190 0 : "attach_hook: tenant {} set generation {:?}, pageserver {}, config {:?}",
2191 : attach_req.tenant_shard_id,
2192 : tenant_shard.generation,
2193 : // TODO: this is an odd number of 0xf's
2194 0 : attach_req.node_id.unwrap_or(utils::id::NodeId(0xfffffff)),
2195 : attach_req.config,
2196 : );
2197 :
2198 : // Trick the reconciler into not doing anything for this tenant: this helps
2199 : // tests that manually configure a tenant on the pagesrever, and then call this
2200 : // attach hook: they don't want background reconciliation to modify what they
2201 : // did to the pageserver.
2202 : #[cfg(feature = "testing")]
2203 : {
2204 0 : if let Some(node_id) = attach_req.node_id {
2205 0 : tenant_shard.observed.locations = HashMap::from([(
2206 0 : node_id,
2207 0 : ObservedStateLocation {
2208 0 : conf: Some(attached_location_conf(
2209 0 : tenant_shard.generation.unwrap(),
2210 0 : &tenant_shard.shard,
2211 0 : &tenant_shard.config,
2212 0 : &PlacementPolicy::Attached(0),
2213 0 : tenant_shard.intent.get_secondary().len(),
2214 0 : )),
2215 0 : },
2216 0 : )]);
2217 0 : } else {
2218 0 : tenant_shard.observed.locations.clear();
2219 0 : }
2220 : }
2221 :
2222 : Ok(AttachHookResponse {
2223 0 : generation: attach_req
2224 0 : .node_id
2225 0 : .map(|_| tenant_shard.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap()),
2226 : })
2227 0 : }
2228 :
2229 0 : pub(crate) fn inspect(&self, inspect_req: InspectRequest) -> InspectResponse {
2230 0 : let locked = self.inner.read().unwrap();
2231 :
2232 0 : let tenant_shard = locked.tenants.get(&inspect_req.tenant_shard_id);
2233 :
2234 : InspectResponse {
2235 0 : attachment: tenant_shard.and_then(|s| {
2236 0 : s.intent
2237 0 : .get_attached()
2238 0 : .map(|ps| (s.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap(), ps))
2239 0 : }),
2240 : }
2241 0 : }
2242 :
2243 : // When the availability state of a node transitions to active, we must do a full reconciliation
2244 : // of LocationConfigs on that node. This is because while a node was offline:
2245 : // - we might have proceeded through startup_reconcile without checking for extraneous LocationConfigs on this node
2246 : // - aborting a tenant shard split might have left rogue child shards behind on this node.
2247 : //
2248 : // This function must complete _before_ setting a `Node` to Active: once it is set to Active, other
2249 : // Reconcilers might communicate with the node, and these must not overlap with the work we do in
2250 : // this function.
2251 : //
2252 : // The reconciliation logic in here is very similar to what [`Self::startup_reconcile`] does, but
2253 : // for written for a single node rather than as a batch job for all nodes.
2254 : #[tracing::instrument(skip_all, fields(node_id=%node.get_id()))]
2255 : async fn node_activate_reconcile(
2256 : &self,
2257 : mut node: Node,
2258 : _lock: &TracingExclusiveGuard<NodeOperations>,
2259 : ) -> Result<(), ApiError> {
2260 : // This Node is a mutable local copy: we will set it active so that we can use its
2261 : // API client to reconcile with the node. The Node in [`Self::nodes`] will get updated
2262 : // later.
2263 : node.set_availability(NodeAvailability::Active(PageserverUtilization::full()));
2264 :
2265 : let configs = match node
2266 : .with_client_retries(
2267 0 : |client| async move { client.list_location_config().await },
2268 : &self.http_client,
2269 : &self.config.pageserver_jwt_token,
2270 : 1,
2271 : 5,
2272 : SHORT_RECONCILE_TIMEOUT,
2273 : &self.cancel,
2274 : )
2275 : .await
2276 : {
2277 : None => {
2278 : // We're shutting down (the Node's cancellation token can't have fired, because
2279 : // we're the only scope that has a reference to it, and we didn't fire it).
2280 : return Err(ApiError::ShuttingDown);
2281 : }
2282 : Some(Err(e)) => {
2283 : // This node didn't succeed listing its locations: it may not proceed to active state
2284 : // as it is apparently unavailable.
2285 : return Err(ApiError::PreconditionFailed(
2286 : format!("Failed to query node location configs, cannot activate ({e})").into(),
2287 : ));
2288 : }
2289 : Some(Ok(configs)) => configs,
2290 : };
2291 : tracing::info!("Loaded {} LocationConfigs", configs.tenant_shards.len());
2292 :
2293 : let mut cleanup = Vec::new();
2294 : let mut mismatched_locations = 0;
2295 : {
2296 : let mut locked = self.inner.write().unwrap();
2297 :
2298 : for (tenant_shard_id, reported) in configs.tenant_shards {
2299 : let Some(tenant_shard) = locked.tenants.get_mut(&tenant_shard_id) else {
2300 : cleanup.push(tenant_shard_id);
2301 : continue;
2302 : };
2303 :
2304 : let on_record = &mut tenant_shard
2305 : .observed
2306 : .locations
2307 : .entry(node.get_id())
2308 0 : .or_insert_with(|| ObservedStateLocation { conf: None })
2309 : .conf;
2310 :
2311 : // If the location reported by the node does not match our observed state,
2312 : // then we mark it as uncertain and let the background reconciliation loop
2313 : // deal with it.
2314 : //
2315 : // Note that this also covers net new locations reported by the node.
2316 : if *on_record != reported {
2317 : mismatched_locations += 1;
2318 : *on_record = None;
2319 : }
2320 : }
2321 : }
2322 :
2323 : if mismatched_locations > 0 {
2324 : tracing::info!(
2325 : "Set observed state to None for {mismatched_locations} mismatched locations"
2326 : );
2327 : }
2328 :
2329 : for tenant_shard_id in cleanup {
2330 : tracing::info!("Detaching {tenant_shard_id}");
2331 : match node
2332 : .with_client_retries(
2333 0 : |client| async move {
2334 0 : let config = LocationConfig {
2335 0 : mode: LocationConfigMode::Detached,
2336 0 : generation: None,
2337 0 : secondary_conf: None,
2338 0 : shard_number: tenant_shard_id.shard_number.0,
2339 0 : shard_count: tenant_shard_id.shard_count.literal(),
2340 0 : shard_stripe_size: 0,
2341 0 : tenant_conf: models::TenantConfig::default(),
2342 0 : };
2343 0 : client
2344 0 : .location_config(tenant_shard_id, config, None, false)
2345 0 : .await
2346 0 : },
2347 : &self.http_client,
2348 : &self.config.pageserver_jwt_token,
2349 : 1,
2350 : 5,
2351 : SHORT_RECONCILE_TIMEOUT,
2352 : &self.cancel,
2353 : )
2354 : .await
2355 : {
2356 : None => {
2357 : // We're shutting down (the Node's cancellation token can't have fired, because
2358 : // we're the only scope that has a reference to it, and we didn't fire it).
2359 : return Err(ApiError::ShuttingDown);
2360 : }
2361 : Some(Err(e)) => {
2362 : // Do not let the node proceed to Active state if it is not responsive to requests
2363 : // to detach. This could happen if e.g. a shutdown bug in the pageserver is preventing
2364 : // detach completing: we should not let this node back into the set of nodes considered
2365 : // okay for scheduling.
2366 : return Err(ApiError::Conflict(format!(
2367 : "Node {node} failed to detach {tenant_shard_id}: {e}"
2368 : )));
2369 : }
2370 : Some(Ok(_)) => {}
2371 : };
2372 : }
2373 :
2374 : Ok(())
2375 : }
2376 :
2377 0 : pub(crate) async fn re_attach(
2378 0 : &self,
2379 0 : reattach_req: ReAttachRequest,
2380 0 : ) -> Result<ReAttachResponse, ApiError> {
2381 0 : if let Some(register_req) = reattach_req.register {
2382 0 : self.node_register(register_req).await?;
2383 0 : }
2384 :
2385 : // Ordering: we must persist generation number updates before making them visible in the in-memory state
2386 0 : let incremented_generations = self.persistence.re_attach(reattach_req.node_id).await?;
2387 :
2388 0 : tracing::info!(
2389 : node_id=%reattach_req.node_id,
2390 0 : "Incremented {} tenant shards' generations",
2391 0 : incremented_generations.len()
2392 : );
2393 :
2394 : // Apply the updated generation to our in-memory state, and
2395 : // gather discover secondary locations.
2396 0 : let mut locked = self.inner.write().unwrap();
2397 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
2398 :
2399 0 : let mut response = ReAttachResponse {
2400 0 : tenants: Vec::new(),
2401 0 : };
2402 :
2403 : // [Hadron] If the pageserver reports in the reattach message that it has an empty disk, it's possible that it just
2404 : // recovered from a local disk failure. The response of the reattach request will contain a list of tenants but it
2405 : // will not be honored by the pageserver in this case (disk failure). We should make sure we clear any observed
2406 : // locations of tenants attached to the node so that the reconciler will discover the discrpancy and reconfigure the
2407 : // missing tenants on the node properly.
2408 0 : if self.config.handle_ps_local_disk_loss && reattach_req.empty_local_disk.unwrap_or(false) {
2409 0 : tracing::info!(
2410 0 : "Pageserver {node_id} reports empty local disk, clearing observed locations referencing the pageserver for all tenants",
2411 : node_id = reattach_req.node_id
2412 : );
2413 0 : let mut num_tenant_shards_affected = 0;
2414 0 : for (tenant_shard_id, shard) in tenants.iter_mut() {
2415 0 : if shard
2416 0 : .observed
2417 0 : .locations
2418 0 : .remove(&reattach_req.node_id)
2419 0 : .is_some()
2420 : {
2421 0 : tracing::info!("Cleared observed location for tenant shard {tenant_shard_id}");
2422 0 : num_tenant_shards_affected += 1;
2423 0 : }
2424 : }
2425 0 : tracing::info!(
2426 0 : "Cleared observed locations for {num_tenant_shards_affected} tenant shards"
2427 : );
2428 0 : }
2429 :
2430 : // TODO: cancel/restart any running reconciliation for this tenant, it might be trying
2431 : // to call location_conf API with an old generation. Wait for cancellation to complete
2432 : // before responding to this request. Requires well implemented CancellationToken logic
2433 : // all the way to where we call location_conf. Even then, there can still be a location_conf
2434 : // request in flight over the network: TODO handle that by making location_conf API refuse
2435 : // to go backward in generations.
2436 :
2437 : // Scan through all shards, applying updates for ones where we updated generation
2438 : // and identifying shards that intend to have a secondary location on this node.
2439 0 : for (tenant_shard_id, shard) in tenants {
2440 0 : if let Some(new_gen) = incremented_generations.get(tenant_shard_id) {
2441 0 : let new_gen = *new_gen;
2442 0 : response.tenants.push(ReAttachResponseTenant {
2443 0 : id: *tenant_shard_id,
2444 0 : r#gen: Some(new_gen.into().unwrap()),
2445 0 : // A tenant is only put into multi or stale modes in the middle of a [`Reconciler::live_migrate`]
2446 0 : // execution. If a pageserver is restarted during that process, then the reconcile pass will
2447 0 : // fail, and start from scratch, so it doesn't make sense for us to try and preserve
2448 0 : // the stale/multi states at this point.
2449 0 : mode: LocationConfigMode::AttachedSingle,
2450 0 : stripe_size: shard.shard.stripe_size,
2451 0 : });
2452 :
2453 0 : shard.generation = std::cmp::max(shard.generation, Some(new_gen));
2454 0 : if let Some(observed) = shard.observed.locations.get_mut(&reattach_req.node_id) {
2455 : // Why can we update `observed` even though we're not sure our response will be received
2456 : // by the pageserver? Because the pageserver will not proceed with startup until
2457 : // it has processed response: if it loses it, we'll see another request and increment
2458 : // generation again, avoiding any uncertainty about dirtiness of tenant's state.
2459 0 : if let Some(conf) = observed.conf.as_mut() {
2460 0 : conf.generation = new_gen.into();
2461 0 : }
2462 0 : } else {
2463 0 : // This node has no observed state for the shard: perhaps it was offline
2464 0 : // when the pageserver restarted. Insert a None, so that the Reconciler
2465 0 : // will be prompted to learn the location's state before it makes changes.
2466 0 : shard
2467 0 : .observed
2468 0 : .locations
2469 0 : .insert(reattach_req.node_id, ObservedStateLocation { conf: None });
2470 0 : }
2471 0 : } else if shard.intent.get_secondary().contains(&reattach_req.node_id) {
2472 0 : // Ordering: pageserver will not accept /location_config requests until it has
2473 0 : // finished processing the response from re-attach. So we can update our in-memory state
2474 0 : // now, and be confident that we are not stamping on the result of some later location config.
2475 0 : // TODO: however, we are not strictly ordered wrt ReconcileResults queue,
2476 0 : // so we might update observed state here, and then get over-written by some racing
2477 0 : // ReconcileResult. The impact is low however, since we have set state on pageserver something
2478 0 : // that matches intent, so worst case if we race then we end up doing a spurious reconcile.
2479 0 :
2480 0 : response.tenants.push(ReAttachResponseTenant {
2481 0 : id: *tenant_shard_id,
2482 0 : r#gen: None,
2483 0 : mode: LocationConfigMode::Secondary,
2484 0 : stripe_size: shard.shard.stripe_size,
2485 0 : });
2486 0 :
2487 0 : // We must not update observed, because we have no guarantee that our
2488 0 : // response will be received by the pageserver. This could leave it
2489 0 : // falsely dirty, but the resulting reconcile should be idempotent.
2490 0 : }
2491 : }
2492 :
2493 : // We consider a node Active once we have composed a re-attach response, but we
2494 : // do not call [`Self::node_activate_reconcile`]: the handling of the re-attach response
2495 : // implicitly synchronizes the LocationConfigs on the node.
2496 : //
2497 : // Setting a node active unblocks any Reconcilers that might write to the location config API,
2498 : // but those requests will not be accepted by the node until it has finished processing
2499 : // the re-attach response.
2500 : //
2501 : // Additionally, reset the nodes scheduling policy to match the conditional update done
2502 : // in [`Persistence::re_attach`].
2503 0 : if let Some(node) = nodes.get(&reattach_req.node_id) {
2504 0 : let reset_scheduling = matches!(
2505 0 : node.get_scheduling(),
2506 : NodeSchedulingPolicy::PauseForRestart
2507 : | NodeSchedulingPolicy::Draining
2508 : | NodeSchedulingPolicy::Filling
2509 : | NodeSchedulingPolicy::Deleting
2510 : );
2511 :
2512 0 : let mut new_nodes = (**nodes).clone();
2513 0 : if let Some(node) = new_nodes.get_mut(&reattach_req.node_id) {
2514 0 : if reset_scheduling {
2515 0 : node.set_scheduling(NodeSchedulingPolicy::Active);
2516 0 : }
2517 :
2518 0 : tracing::info!("Marking {} warming-up on reattach", reattach_req.node_id);
2519 0 : node.set_availability(NodeAvailability::WarmingUp(std::time::Instant::now()));
2520 :
2521 0 : scheduler.node_upsert(node);
2522 0 : let new_nodes = Arc::new(new_nodes);
2523 0 : *nodes = new_nodes;
2524 : } else {
2525 0 : tracing::error!(
2526 0 : "Reattaching node {} was removed while processing the request",
2527 : reattach_req.node_id
2528 : );
2529 : }
2530 0 : }
2531 :
2532 0 : Ok(response)
2533 0 : }
2534 :
2535 0 : pub(crate) async fn validate(
2536 0 : &self,
2537 0 : validate_req: ValidateRequest,
2538 0 : ) -> Result<ValidateResponse, DatabaseError> {
2539 : // Fast in-memory check: we may reject validation on anything that doesn't match our
2540 : // in-memory generation for a shard
2541 0 : let in_memory_result = {
2542 0 : let mut in_memory_result = Vec::new();
2543 0 : let locked = self.inner.read().unwrap();
2544 0 : for req_tenant in validate_req.tenants {
2545 0 : if let Some(tenant_shard) = locked.tenants.get(&req_tenant.id) {
2546 0 : let valid = tenant_shard.generation == Some(Generation::new(req_tenant.r#gen));
2547 0 : tracing::info!(
2548 0 : "handle_validate: {}(gen {}): valid={valid} (latest {:?})",
2549 : req_tenant.id,
2550 : req_tenant.r#gen,
2551 : tenant_shard.generation
2552 : );
2553 :
2554 0 : in_memory_result.push((
2555 0 : req_tenant.id,
2556 0 : Generation::new(req_tenant.r#gen),
2557 0 : valid,
2558 0 : ));
2559 : } else {
2560 : // This is legal: for example during a shard split the pageserver may still
2561 : // have deletions in its queue from the old pre-split shard, or after deletion
2562 : // of a tenant that was busy with compaction/gc while being deleted.
2563 0 : tracing::info!(
2564 0 : "Refusing deletion validation for missing shard {}",
2565 : req_tenant.id
2566 : );
2567 : }
2568 : }
2569 :
2570 0 : in_memory_result
2571 : };
2572 :
2573 : // Database calls to confirm validity for anything that passed the in-memory check. We must do this
2574 : // in case of controller split-brain, where some other controller process might have incremented the generation.
2575 0 : let db_generations = self
2576 0 : .persistence
2577 0 : .shard_generations(
2578 0 : in_memory_result
2579 0 : .iter()
2580 0 : .filter_map(|i| if i.2 { Some(&i.0) } else { None }),
2581 : )
2582 0 : .await?;
2583 0 : let db_generations = db_generations.into_iter().collect::<HashMap<_, _>>();
2584 :
2585 0 : let mut response = ValidateResponse {
2586 0 : tenants: Vec::new(),
2587 0 : };
2588 0 : for (tenant_shard_id, validate_generation, valid) in in_memory_result.into_iter() {
2589 0 : let valid = if valid {
2590 0 : let db_generation = db_generations.get(&tenant_shard_id);
2591 0 : db_generation == Some(&Some(validate_generation))
2592 : } else {
2593 : // If in-memory state says it's invalid, trust that. It's always safe to fail a validation, at worst
2594 : // this prevents a pageserver from cleaning up an object in S3.
2595 0 : false
2596 : };
2597 :
2598 0 : response.tenants.push(ValidateResponseTenant {
2599 0 : id: tenant_shard_id,
2600 0 : valid,
2601 0 : })
2602 : }
2603 :
2604 0 : Ok(response)
2605 0 : }
2606 :
2607 0 : pub(crate) async fn tenant_create(
2608 0 : &self,
2609 0 : create_req: TenantCreateRequest,
2610 0 : ) -> Result<TenantCreateResponse, ApiError> {
2611 0 : let tenant_id = create_req.new_tenant_id.tenant_id;
2612 :
2613 : // Exclude any concurrent attempts to create/access the same tenant ID
2614 0 : let _tenant_lock = trace_exclusive_lock(
2615 0 : &self.tenant_op_locks,
2616 0 : create_req.new_tenant_id.tenant_id,
2617 0 : TenantOperations::Create,
2618 0 : )
2619 0 : .await;
2620 0 : let (response, waiters) = self.do_tenant_create(create_req).await?;
2621 :
2622 0 : if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
2623 : // Avoid deadlock: reconcile may fail while notifying compute, if the cloud control plane refuses to
2624 : // accept compute notifications while it is in the process of creating. Reconciliation will
2625 : // be retried in the background.
2626 0 : tracing::warn!(%tenant_id, "Reconcile not done yet while creating tenant ({e})");
2627 0 : }
2628 0 : Ok(response)
2629 0 : }
2630 :
2631 0 : pub(crate) async fn do_tenant_create(
2632 0 : &self,
2633 0 : create_req: TenantCreateRequest,
2634 0 : ) -> Result<(TenantCreateResponse, Vec<ReconcilerWaiter>), ApiError> {
2635 0 : let placement_policy = create_req
2636 0 : .placement_policy
2637 0 : .clone()
2638 : // As a default, zero secondaries is convenient for tests that don't choose a policy.
2639 0 : .unwrap_or(PlacementPolicy::Attached(0));
2640 :
2641 : // This service expects to handle sharding itself: it is an error to try and directly create
2642 : // a particular shard here.
2643 0 : let tenant_id = if !create_req.new_tenant_id.is_unsharded() {
2644 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
2645 0 : "Attempted to create a specific shard, this API is for creating the whole tenant"
2646 0 : )));
2647 : } else {
2648 0 : create_req.new_tenant_id.tenant_id
2649 : };
2650 :
2651 0 : tracing::info!(
2652 0 : "Creating tenant {}, shard_count={:?}",
2653 : create_req.new_tenant_id,
2654 : create_req.shard_parameters.count,
2655 : );
2656 :
2657 0 : let create_ids = (0..create_req.shard_parameters.count.count())
2658 0 : .map(|i| TenantShardId {
2659 0 : tenant_id,
2660 0 : shard_number: ShardNumber(i),
2661 0 : shard_count: create_req.shard_parameters.count,
2662 0 : })
2663 0 : .collect::<Vec<_>>();
2664 :
2665 : // If the caller specifies a None generation, it means "start from default". This is different
2666 : // to [`Self::tenant_location_config`], where a None generation is used to represent
2667 : // an incompletely-onboarded tenant.
2668 0 : let initial_generation = if matches!(placement_policy, PlacementPolicy::Secondary) {
2669 0 : tracing::info!(
2670 0 : "tenant_create: secondary mode, generation is_some={}",
2671 0 : create_req.generation.is_some()
2672 : );
2673 0 : create_req.generation.map(Generation::new)
2674 : } else {
2675 0 : tracing::info!(
2676 0 : "tenant_create: not secondary mode, generation is_some={}",
2677 0 : create_req.generation.is_some()
2678 : );
2679 0 : Some(
2680 0 : create_req
2681 0 : .generation
2682 0 : .map(Generation::new)
2683 0 : .unwrap_or(INITIAL_GENERATION),
2684 0 : )
2685 : };
2686 :
2687 0 : let preferred_az_id = {
2688 0 : let locked = self.inner.read().unwrap();
2689 : // Idempotency: take the existing value if the tenant already exists
2690 0 : if let Some(shard) = locked.tenants.get(create_ids.first().unwrap()) {
2691 0 : shard.preferred_az().cloned()
2692 : } else {
2693 0 : locked.scheduler.get_az_for_new_tenant()
2694 : }
2695 : };
2696 :
2697 : // Ordering: we persist tenant shards before creating them on the pageserver. This enables a caller
2698 : // to clean up after themselves by issuing a tenant deletion if something goes wrong and we restart
2699 : // during the creation, rather than risking leaving orphan objects in S3.
2700 0 : let persist_tenant_shards = create_ids
2701 0 : .iter()
2702 0 : .map(|tenant_shard_id| TenantShardPersistence {
2703 0 : tenant_id: tenant_shard_id.tenant_id.to_string(),
2704 0 : shard_number: tenant_shard_id.shard_number.0 as i32,
2705 0 : shard_count: tenant_shard_id.shard_count.literal() as i32,
2706 0 : shard_stripe_size: create_req.shard_parameters.stripe_size.0 as i32,
2707 0 : generation: initial_generation.map(|g| g.into().unwrap() as i32),
2708 : // The pageserver is not known until scheduling happens: we will set this column when
2709 : // incrementing the generation the first time we attach to a pageserver.
2710 0 : generation_pageserver: None,
2711 0 : placement_policy: serde_json::to_string(&placement_policy).unwrap(),
2712 0 : config: serde_json::to_string(&create_req.config).unwrap(),
2713 0 : splitting: SplitState::default(),
2714 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
2715 0 : .unwrap(),
2716 0 : preferred_az_id: preferred_az_id.as_ref().map(|az| az.to_string()),
2717 0 : })
2718 0 : .collect();
2719 :
2720 0 : match self
2721 0 : .persistence
2722 0 : .insert_tenant_shards(persist_tenant_shards)
2723 0 : .await
2724 : {
2725 0 : Ok(_) => {}
2726 : Err(DatabaseError::Query(diesel::result::Error::DatabaseError(
2727 : DatabaseErrorKind::UniqueViolation,
2728 : _,
2729 : ))) => {
2730 : // Unique key violation: this is probably a retry. Because the shard count is part of the unique key,
2731 : // if we see a unique key violation it means that the creation request's shard count matches the previous
2732 : // creation's shard count.
2733 0 : tracing::info!(
2734 0 : "Tenant shards already present in database, proceeding with idempotent creation..."
2735 : );
2736 : }
2737 : // Any other database error is unexpected and a bug.
2738 0 : Err(e) => return Err(ApiError::InternalServerError(anyhow::anyhow!(e))),
2739 : };
2740 :
2741 0 : let mut schedule_context = ScheduleContext::default();
2742 0 : let mut schedule_error = None;
2743 0 : let mut response_shards = Vec::new();
2744 0 : for tenant_shard_id in create_ids {
2745 0 : tracing::info!("Creating shard {tenant_shard_id}...");
2746 :
2747 0 : let outcome = self
2748 0 : .do_initial_shard_scheduling(
2749 0 : tenant_shard_id,
2750 0 : initial_generation,
2751 0 : create_req.shard_parameters,
2752 0 : create_req.config.clone(),
2753 0 : placement_policy.clone(),
2754 0 : preferred_az_id.as_ref(),
2755 0 : &mut schedule_context,
2756 0 : )
2757 0 : .await;
2758 :
2759 0 : match outcome {
2760 0 : InitialShardScheduleOutcome::Scheduled(resp) => response_shards.push(resp),
2761 0 : InitialShardScheduleOutcome::NotScheduled => {}
2762 0 : InitialShardScheduleOutcome::ShardScheduleError(err) => {
2763 0 : schedule_error = Some(err);
2764 0 : }
2765 : }
2766 : }
2767 :
2768 : // If we failed to schedule shards, then they are still created in the controller,
2769 : // but we return an error to the requester to avoid a silent failure when someone
2770 : // tries to e.g. create a tenant whose placement policy requires more nodes than
2771 : // are present in the system. We do this here rather than in the above loop, to
2772 : // avoid situations where we only create a subset of shards in the tenant.
2773 0 : if let Some(e) = schedule_error {
2774 0 : return Err(ApiError::Conflict(format!(
2775 0 : "Failed to schedule shard(s): {e}"
2776 0 : )));
2777 0 : }
2778 :
2779 0 : let waiters = {
2780 0 : let mut locked = self.inner.write().unwrap();
2781 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2782 0 : let config = ReconcilerConfigBuilder::new(ReconcilerPriority::High)
2783 0 : .tenant_creation_hint(true)
2784 0 : .build();
2785 0 : tenants
2786 0 : .range_mut(TenantShardId::tenant_range(tenant_id))
2787 0 : .filter_map(|(_shard_id, shard)| {
2788 0 : self.maybe_configured_reconcile_shard(shard, nodes, config)
2789 0 : })
2790 0 : .collect::<Vec<_>>()
2791 : };
2792 :
2793 0 : Ok((
2794 0 : TenantCreateResponse {
2795 0 : shards: response_shards,
2796 0 : },
2797 0 : waiters,
2798 0 : ))
2799 0 : }
2800 :
2801 : /// Helper for tenant creation that does the scheduling for an individual shard. Covers both the
2802 : /// case of a new tenant and a pre-existing one.
2803 : #[allow(clippy::too_many_arguments)]
2804 0 : async fn do_initial_shard_scheduling(
2805 0 : &self,
2806 0 : tenant_shard_id: TenantShardId,
2807 0 : initial_generation: Option<Generation>,
2808 0 : shard_params: ShardParameters,
2809 0 : config: TenantConfig,
2810 0 : placement_policy: PlacementPolicy,
2811 0 : preferred_az_id: Option<&AvailabilityZone>,
2812 0 : schedule_context: &mut ScheduleContext,
2813 0 : ) -> InitialShardScheduleOutcome {
2814 0 : let mut locked = self.inner.write().unwrap();
2815 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
2816 :
2817 : use std::collections::btree_map::Entry;
2818 0 : match tenants.entry(tenant_shard_id) {
2819 0 : Entry::Occupied(mut entry) => {
2820 0 : tracing::info!("Tenant shard {tenant_shard_id} already exists while creating");
2821 :
2822 0 : if let Err(err) = entry.get_mut().schedule(scheduler, schedule_context) {
2823 0 : return InitialShardScheduleOutcome::ShardScheduleError(err);
2824 0 : }
2825 :
2826 0 : if let Some(node_id) = entry.get().intent.get_attached() {
2827 0 : let generation = entry
2828 0 : .get()
2829 0 : .generation
2830 0 : .expect("Generation is set when in attached mode");
2831 0 : InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
2832 0 : shard_id: tenant_shard_id,
2833 0 : node_id: *node_id,
2834 0 : generation: generation.into().unwrap(),
2835 0 : })
2836 : } else {
2837 0 : InitialShardScheduleOutcome::NotScheduled
2838 : }
2839 : }
2840 0 : Entry::Vacant(entry) => {
2841 0 : let state = entry.insert(TenantShard::new(
2842 0 : tenant_shard_id,
2843 0 : ShardIdentity::from_params(tenant_shard_id.shard_number, shard_params),
2844 0 : placement_policy,
2845 0 : preferred_az_id.cloned(),
2846 : ));
2847 :
2848 0 : state.generation = initial_generation;
2849 0 : state.config = config;
2850 0 : if let Err(e) = state.schedule(scheduler, schedule_context) {
2851 0 : return InitialShardScheduleOutcome::ShardScheduleError(e);
2852 0 : }
2853 :
2854 : // Only include shards in result if we are attaching: the purpose
2855 : // of the response is to tell the caller where the shards are attached.
2856 0 : if let Some(node_id) = state.intent.get_attached() {
2857 0 : let generation = state
2858 0 : .generation
2859 0 : .expect("Generation is set when in attached mode");
2860 0 : InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
2861 0 : shard_id: tenant_shard_id,
2862 0 : node_id: *node_id,
2863 0 : generation: generation.into().unwrap(),
2864 0 : })
2865 : } else {
2866 0 : InitialShardScheduleOutcome::NotScheduled
2867 : }
2868 : }
2869 : }
2870 0 : }
2871 :
2872 : /// Helper for functions that reconcile a number of shards, and would like to do a timeout-bounded
2873 : /// wait for reconciliation to complete before responding.
2874 0 : async fn await_waiters(
2875 0 : &self,
2876 0 : waiters: Vec<ReconcilerWaiter>,
2877 0 : timeout: Duration,
2878 0 : ) -> Result<(), ReconcileWaitError> {
2879 0 : let deadline = Instant::now().checked_add(timeout).unwrap();
2880 0 : for waiter in waiters {
2881 0 : let timeout = deadline.duration_since(Instant::now());
2882 0 : waiter.wait_timeout(timeout).await?;
2883 : }
2884 :
2885 0 : Ok(())
2886 0 : }
2887 :
2888 : /// Same as [`Service::await_waiters`], but returns the waiters which are still
2889 : /// in progress
2890 0 : async fn await_waiters_remainder(
2891 0 : &self,
2892 0 : waiters: Vec<ReconcilerWaiter>,
2893 0 : timeout: Duration,
2894 0 : ) -> Vec<ReconcilerWaiter> {
2895 0 : let deadline = Instant::now().checked_add(timeout).unwrap();
2896 0 : for waiter in waiters.iter() {
2897 0 : let timeout = deadline.duration_since(Instant::now());
2898 0 : let _ = waiter.wait_timeout(timeout).await;
2899 : }
2900 :
2901 0 : waiters
2902 0 : .into_iter()
2903 0 : .filter(|waiter| matches!(waiter.get_status(), ReconcilerStatus::InProgress))
2904 0 : .collect::<Vec<_>>()
2905 0 : }
2906 :
2907 : /// Part of [`Self::tenant_location_config`]: dissect an incoming location config request,
2908 : /// and transform it into either a tenant creation of a series of shard updates.
2909 : ///
2910 : /// If the incoming request makes no changes, a [`TenantCreateOrUpdate::Update`] result will
2911 : /// still be returned.
2912 0 : fn tenant_location_config_prepare(
2913 0 : &self,
2914 0 : tenant_id: TenantId,
2915 0 : req: TenantLocationConfigRequest,
2916 0 : ) -> TenantCreateOrUpdate {
2917 0 : let mut updates = Vec::new();
2918 0 : let mut locked = self.inner.write().unwrap();
2919 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2920 0 : let tenant_shard_id = TenantShardId::unsharded(tenant_id);
2921 :
2922 : // Use location config mode as an indicator of policy.
2923 0 : let placement_policy = match req.config.mode {
2924 0 : LocationConfigMode::Detached => PlacementPolicy::Detached,
2925 0 : LocationConfigMode::Secondary => PlacementPolicy::Secondary,
2926 : LocationConfigMode::AttachedMulti
2927 : | LocationConfigMode::AttachedSingle
2928 : | LocationConfigMode::AttachedStale => {
2929 0 : if nodes.len() > 1 {
2930 0 : PlacementPolicy::Attached(1)
2931 : } else {
2932 : // Convenience for dev/test: if we just have one pageserver, import
2933 : // tenants into non-HA mode so that scheduling will succeed.
2934 0 : PlacementPolicy::Attached(0)
2935 : }
2936 : }
2937 : };
2938 :
2939 : // Ordinarily we do not update scheduling policy, but when making major changes
2940 : // like detaching or demoting to secondary-only, we need to force the scheduling
2941 : // mode to Active, or the caller's expected outcome (detach it) will not happen.
2942 0 : let scheduling_policy = match req.config.mode {
2943 : LocationConfigMode::Detached | LocationConfigMode::Secondary => {
2944 : // Special case: when making major changes like detaching or demoting to secondary-only,
2945 : // we need to force the scheduling mode to Active, or nothing will happen.
2946 0 : Some(ShardSchedulingPolicy::Active)
2947 : }
2948 : LocationConfigMode::AttachedMulti
2949 : | LocationConfigMode::AttachedSingle
2950 : | LocationConfigMode::AttachedStale => {
2951 : // While attached, continue to respect whatever the existing scheduling mode is.
2952 0 : None
2953 : }
2954 : };
2955 :
2956 0 : let mut create = true;
2957 0 : for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
2958 : // Saw an existing shard: this is not a creation
2959 0 : create = false;
2960 :
2961 : // Shards may have initially been created by a Secondary request, where we
2962 : // would have left generation as None.
2963 : //
2964 : // We only update generation the first time we see an attached-mode request,
2965 : // and if there is no existing generation set. The caller is responsible for
2966 : // ensuring that no non-storage-controller pageserver ever uses a higher
2967 : // generation than they passed in here.
2968 : use LocationConfigMode::*;
2969 0 : let set_generation = match req.config.mode {
2970 0 : AttachedMulti | AttachedSingle | AttachedStale if shard.generation.is_none() => {
2971 0 : req.config.generation.map(Generation::new)
2972 : }
2973 0 : _ => None,
2974 : };
2975 :
2976 0 : updates.push(ShardUpdate {
2977 0 : tenant_shard_id: *shard_id,
2978 0 : placement_policy: placement_policy.clone(),
2979 0 : tenant_config: req.config.tenant_conf.clone(),
2980 0 : generation: set_generation,
2981 0 : scheduling_policy,
2982 0 : });
2983 : }
2984 :
2985 0 : if create {
2986 : use LocationConfigMode::*;
2987 0 : let generation = match req.config.mode {
2988 0 : AttachedMulti | AttachedSingle | AttachedStale => req.config.generation,
2989 : // If a caller provided a generation in a non-attached request, ignore it
2990 : // and leave our generation as None: this enables a subsequent update to set
2991 : // the generation when setting an attached mode for the first time.
2992 0 : _ => None,
2993 : };
2994 :
2995 0 : TenantCreateOrUpdate::Create(
2996 0 : // Synthesize a creation request
2997 0 : TenantCreateRequest {
2998 0 : new_tenant_id: tenant_shard_id,
2999 0 : generation,
3000 0 : shard_parameters: ShardParameters {
3001 0 : count: tenant_shard_id.shard_count,
3002 0 : // We only import un-sharded or single-sharded tenants, so stripe
3003 0 : // size can be made up arbitrarily here.
3004 0 : stripe_size: DEFAULT_STRIPE_SIZE,
3005 0 : },
3006 0 : placement_policy: Some(placement_policy),
3007 0 : config: req.config.tenant_conf,
3008 0 : },
3009 0 : )
3010 : } else {
3011 0 : assert!(!updates.is_empty());
3012 0 : TenantCreateOrUpdate::Update(updates)
3013 : }
3014 0 : }
3015 :
3016 : /// For APIs that might act on tenants with [`PlacementPolicy::Detached`], first check if
3017 : /// the tenant is present in memory. If not, load it from the database. If it is found
3018 : /// in neither location, return a NotFound error.
3019 : ///
3020 : /// Caller must demonstrate they hold a lock guard, as otherwise two callers might try and load
3021 : /// it at the same time, or we might race with [`Self::maybe_drop_tenant`]
3022 0 : async fn maybe_load_tenant(
3023 0 : &self,
3024 0 : tenant_id: TenantId,
3025 0 : _guard: &TracingExclusiveGuard<TenantOperations>,
3026 0 : ) -> Result<(), ApiError> {
3027 : // Check if the tenant is present in memory, and select an AZ to use when loading
3028 : // if we will load it.
3029 0 : let load_in_az = {
3030 0 : let locked = self.inner.read().unwrap();
3031 0 : let existing = locked
3032 0 : .tenants
3033 0 : .range(TenantShardId::tenant_range(tenant_id))
3034 0 : .next();
3035 :
3036 : // If the tenant is not present in memory, we expect to load it from database,
3037 : // so let's figure out what AZ to load it into while we have self.inner locked.
3038 0 : if existing.is_none() {
3039 0 : locked
3040 0 : .scheduler
3041 0 : .get_az_for_new_tenant()
3042 0 : .ok_or(ApiError::BadRequest(anyhow::anyhow!(
3043 0 : "No AZ with nodes found to load tenant"
3044 0 : )))?
3045 : } else {
3046 : // We already have this tenant in memory
3047 0 : return Ok(());
3048 : }
3049 : };
3050 :
3051 0 : let tenant_shards = self.persistence.load_tenant(tenant_id).await?;
3052 0 : if tenant_shards.is_empty() {
3053 0 : return Err(ApiError::NotFound(
3054 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
3055 0 : ));
3056 0 : }
3057 :
3058 : // Update the persistent shards with the AZ that we are about to apply to in-memory state
3059 0 : self.persistence
3060 0 : .set_tenant_shard_preferred_azs(
3061 0 : tenant_shards
3062 0 : .iter()
3063 0 : .map(|t| {
3064 0 : (
3065 0 : t.get_tenant_shard_id().expect("Corrupt shard in database"),
3066 0 : Some(load_in_az.clone()),
3067 0 : )
3068 0 : })
3069 0 : .collect(),
3070 : )
3071 0 : .await?;
3072 :
3073 0 : let mut locked = self.inner.write().unwrap();
3074 0 : tracing::info!(
3075 0 : "Loaded {} shards for tenant {}",
3076 0 : tenant_shards.len(),
3077 : tenant_id
3078 : );
3079 :
3080 0 : locked.tenants.extend(tenant_shards.into_iter().map(|p| {
3081 0 : let intent = IntentState::new(Some(load_in_az.clone()));
3082 0 : let shard =
3083 0 : TenantShard::from_persistent(p, intent).expect("Corrupt shard row in database");
3084 :
3085 : // Sanity check: when loading on-demand, we should always be loaded something Detached
3086 0 : debug_assert!(shard.policy == PlacementPolicy::Detached);
3087 0 : if shard.policy != PlacementPolicy::Detached {
3088 0 : tracing::error!(
3089 0 : "Tenant shard {} loaded on-demand, but has non-Detached policy {:?}",
3090 : shard.tenant_shard_id,
3091 : shard.policy
3092 : );
3093 0 : }
3094 :
3095 0 : (shard.tenant_shard_id, shard)
3096 0 : }));
3097 :
3098 0 : Ok(())
3099 0 : }
3100 :
3101 : /// If all shards for a tenant are detached, and in a fully quiescent state (no observed locations on pageservers),
3102 : /// and have no reconciler running, then we can drop the tenant from memory. It will be reloaded on-demand
3103 : /// if we are asked to attach it again (see [`Self::maybe_load_tenant`]).
3104 : ///
3105 : /// Caller must demonstrate they hold a lock guard, as otherwise it is unsafe to drop a tenant from
3106 : /// memory while some other function might assume it continues to exist while not holding the lock on Self::inner.
3107 0 : fn maybe_drop_tenant(
3108 0 : &self,
3109 0 : tenant_id: TenantId,
3110 0 : locked: &mut std::sync::RwLockWriteGuard<ServiceState>,
3111 0 : _guard: &TracingExclusiveGuard<TenantOperations>,
3112 0 : ) {
3113 0 : let mut tenant_shards = locked.tenants.range(TenantShardId::tenant_range(tenant_id));
3114 0 : if tenant_shards.all(|(_id, shard)| {
3115 0 : shard.policy == PlacementPolicy::Detached
3116 0 : && shard.reconciler.is_none()
3117 0 : && shard.observed.is_empty()
3118 0 : }) {
3119 0 : let keys = locked
3120 0 : .tenants
3121 0 : .range(TenantShardId::tenant_range(tenant_id))
3122 0 : .map(|(id, _)| id)
3123 0 : .copied()
3124 0 : .collect::<Vec<_>>();
3125 0 : for key in keys {
3126 0 : tracing::info!("Dropping detached tenant shard {} from memory", key);
3127 0 : locked.tenants.remove(&key);
3128 : }
3129 0 : }
3130 0 : }
3131 :
3132 : /// This API is used by the cloud control plane to migrate unsharded tenants that it created
3133 : /// directly with pageservers into this service.
3134 : ///
3135 : /// Cloud control plane MUST NOT continue issuing GENERATION NUMBERS for this tenant once it
3136 : /// has attempted to call this API. Failure to oblige to this rule may lead to S3 corruption.
3137 : /// Think of the first attempt to call this API as a transfer of absolute authority over the
3138 : /// tenant's source of generation numbers.
3139 : ///
3140 : /// The mode in this request coarse-grained control of tenants:
3141 : /// - Call with mode Attached* to upsert the tenant.
3142 : /// - Call with mode Secondary to either onboard a tenant without attaching it, or
3143 : /// to set an existing tenant to PolicyMode::Secondary
3144 : /// - Call with mode Detached to switch to PolicyMode::Detached
3145 0 : pub(crate) async fn tenant_location_config(
3146 0 : &self,
3147 0 : tenant_shard_id: TenantShardId,
3148 0 : req: TenantLocationConfigRequest,
3149 0 : ) -> Result<TenantLocationConfigResponse, ApiError> {
3150 : // We require an exclusive lock, because we are updating both persistent and in-memory state
3151 0 : let _tenant_lock = trace_exclusive_lock(
3152 0 : &self.tenant_op_locks,
3153 0 : tenant_shard_id.tenant_id,
3154 0 : TenantOperations::LocationConfig,
3155 0 : )
3156 0 : .await;
3157 :
3158 0 : let tenant_id = if !tenant_shard_id.is_unsharded() {
3159 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
3160 0 : "This API is for importing single-sharded or unsharded tenants"
3161 0 : )));
3162 : } else {
3163 0 : tenant_shard_id.tenant_id
3164 : };
3165 :
3166 : // In case we are waking up a Detached tenant
3167 0 : match self.maybe_load_tenant(tenant_id, &_tenant_lock).await {
3168 0 : Ok(()) | Err(ApiError::NotFound(_)) => {
3169 0 : // This is a creation or an update
3170 0 : }
3171 0 : Err(e) => {
3172 0 : return Err(e);
3173 : }
3174 : };
3175 :
3176 : // First check if this is a creation or an update
3177 0 : let create_or_update = self.tenant_location_config_prepare(tenant_id, req);
3178 :
3179 0 : let mut result = TenantLocationConfigResponse {
3180 0 : shards: Vec::new(),
3181 0 : stripe_size: None,
3182 0 : };
3183 0 : let waiters = match create_or_update {
3184 0 : TenantCreateOrUpdate::Create(create_req) => {
3185 0 : let (create_resp, waiters) = self.do_tenant_create(create_req).await?;
3186 0 : result.shards = create_resp
3187 0 : .shards
3188 0 : .into_iter()
3189 0 : .map(|s| TenantShardLocation {
3190 0 : node_id: s.node_id,
3191 0 : shard_id: s.shard_id,
3192 0 : })
3193 0 : .collect();
3194 0 : waiters
3195 : }
3196 0 : TenantCreateOrUpdate::Update(updates) => {
3197 : // Persist updates
3198 : // Ordering: write to the database before applying changes in-memory, so that
3199 : // we will not appear time-travel backwards on a restart.
3200 :
3201 0 : let mut schedule_context = ScheduleContext::default();
3202 : for ShardUpdate {
3203 0 : tenant_shard_id,
3204 0 : placement_policy,
3205 0 : tenant_config,
3206 0 : generation,
3207 0 : scheduling_policy,
3208 0 : } in &updates
3209 : {
3210 0 : self.persistence
3211 0 : .update_tenant_shard(
3212 0 : TenantFilter::Shard(*tenant_shard_id),
3213 0 : Some(placement_policy.clone()),
3214 0 : Some(tenant_config.clone()),
3215 0 : *generation,
3216 0 : *scheduling_policy,
3217 0 : )
3218 0 : .await?;
3219 : }
3220 :
3221 : // Apply updates in-memory
3222 0 : let mut waiters = Vec::new();
3223 : {
3224 0 : let mut locked = self.inner.write().unwrap();
3225 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3226 :
3227 : for ShardUpdate {
3228 0 : tenant_shard_id,
3229 0 : placement_policy,
3230 0 : tenant_config,
3231 0 : generation: update_generation,
3232 0 : scheduling_policy,
3233 0 : } in updates
3234 : {
3235 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
3236 0 : tracing::warn!("Shard {tenant_shard_id} removed while updating");
3237 0 : continue;
3238 : };
3239 :
3240 : // Update stripe size
3241 0 : if result.stripe_size.is_none() && shard.shard.count.count() > 1 {
3242 0 : result.stripe_size = Some(shard.shard.stripe_size);
3243 0 : }
3244 :
3245 0 : shard.policy = placement_policy;
3246 0 : shard.config = tenant_config;
3247 0 : if let Some(generation) = update_generation {
3248 0 : shard.generation = Some(generation);
3249 0 : }
3250 :
3251 0 : if let Some(scheduling_policy) = scheduling_policy {
3252 0 : shard.set_scheduling_policy(scheduling_policy);
3253 0 : }
3254 :
3255 0 : shard.schedule(scheduler, &mut schedule_context)?;
3256 :
3257 0 : let maybe_waiter =
3258 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
3259 0 : if let Some(waiter) = maybe_waiter {
3260 0 : waiters.push(waiter);
3261 0 : }
3262 :
3263 0 : if let Some(node_id) = shard.intent.get_attached() {
3264 0 : result.shards.push(TenantShardLocation {
3265 0 : shard_id: tenant_shard_id,
3266 0 : node_id: *node_id,
3267 0 : })
3268 0 : }
3269 : }
3270 : }
3271 0 : waiters
3272 : }
3273 : };
3274 :
3275 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
3276 : // Do not treat a reconcile error as fatal: we have already applied any requested
3277 : // Intent changes, and the reconcile can fail for external reasons like unavailable
3278 : // compute notification API. In these cases, it is important that we do not
3279 : // cause the cloud control plane to retry forever on this API.
3280 0 : tracing::warn!(
3281 0 : "Failed to reconcile after /location_config: {e}, returning success anyway"
3282 : );
3283 0 : }
3284 :
3285 : // Logging the full result is useful because it lets us cross-check what the cloud control
3286 : // plane's tenant_shards table should contain.
3287 0 : tracing::info!("Complete, returning {result:?}");
3288 :
3289 0 : Ok(result)
3290 0 : }
3291 :
3292 0 : pub(crate) async fn tenant_config_patch(
3293 0 : &self,
3294 0 : req: TenantConfigPatchRequest,
3295 0 : ) -> Result<(), ApiError> {
3296 0 : let _tenant_lock = trace_exclusive_lock(
3297 0 : &self.tenant_op_locks,
3298 0 : req.tenant_id,
3299 0 : TenantOperations::ConfigPatch,
3300 0 : )
3301 0 : .await;
3302 :
3303 0 : let tenant_id = req.tenant_id;
3304 0 : let patch = req.config;
3305 :
3306 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3307 :
3308 0 : let base = {
3309 0 : let locked = self.inner.read().unwrap();
3310 0 : let shards = locked
3311 0 : .tenants
3312 0 : .range(TenantShardId::tenant_range(req.tenant_id));
3313 :
3314 0 : let mut configs = shards.map(|(_sid, shard)| &shard.config).peekable();
3315 :
3316 0 : let first = match configs.peek() {
3317 0 : Some(first) => (*first).clone(),
3318 : None => {
3319 0 : return Err(ApiError::NotFound(
3320 0 : anyhow::anyhow!("Tenant {} not found", req.tenant_id).into(),
3321 0 : ));
3322 : }
3323 : };
3324 :
3325 0 : if !configs.all_equal() {
3326 0 : tracing::error!("Tenant configs for {} are mismatched. ", req.tenant_id);
3327 : // This can't happen because we atomically update the database records
3328 : // of all shards to the new value in [`Self::set_tenant_config_and_reconcile`].
3329 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3330 0 : "Tenant configs for {} are mismatched",
3331 0 : req.tenant_id
3332 0 : )));
3333 0 : }
3334 :
3335 0 : first
3336 : };
3337 :
3338 0 : let updated_config = base
3339 0 : .apply_patch(patch)
3340 0 : .map_err(|err| ApiError::BadRequest(anyhow::anyhow!(err)))?;
3341 0 : self.set_tenant_config_and_reconcile(tenant_id, updated_config)
3342 0 : .await
3343 0 : }
3344 :
3345 0 : pub(crate) async fn tenant_config_set(&self, req: TenantConfigRequest) -> Result<(), ApiError> {
3346 : // We require an exclusive lock, because we are updating persistent and in-memory state
3347 0 : let _tenant_lock = trace_exclusive_lock(
3348 0 : &self.tenant_op_locks,
3349 0 : req.tenant_id,
3350 0 : TenantOperations::ConfigSet,
3351 0 : )
3352 0 : .await;
3353 :
3354 0 : self.maybe_load_tenant(req.tenant_id, &_tenant_lock).await?;
3355 :
3356 0 : self.set_tenant_config_and_reconcile(req.tenant_id, req.config)
3357 0 : .await
3358 0 : }
3359 :
3360 0 : async fn set_tenant_config_and_reconcile(
3361 0 : &self,
3362 0 : tenant_id: TenantId,
3363 0 : config: TenantConfig,
3364 0 : ) -> Result<(), ApiError> {
3365 0 : self.persistence
3366 0 : .update_tenant_shard(
3367 0 : TenantFilter::Tenant(tenant_id),
3368 0 : None,
3369 0 : Some(config.clone()),
3370 0 : None,
3371 0 : None,
3372 0 : )
3373 0 : .await?;
3374 :
3375 0 : let waiters = {
3376 0 : let mut waiters = Vec::new();
3377 0 : let mut locked = self.inner.write().unwrap();
3378 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
3379 0 : for (_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3380 0 : shard.config = config.clone();
3381 0 : if let Some(waiter) =
3382 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
3383 0 : {
3384 0 : waiters.push(waiter);
3385 0 : }
3386 : }
3387 0 : waiters
3388 : };
3389 :
3390 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
3391 : // Treat this as success because we have stored the configuration. If e.g.
3392 : // a node was unavailable at this time, it should not stop us accepting a
3393 : // configuration change.
3394 0 : tracing::warn!(%tenant_id, "Accepted configuration update but reconciliation failed: {e}");
3395 0 : }
3396 :
3397 0 : Ok(())
3398 0 : }
3399 :
3400 0 : pub(crate) fn tenant_config_get(
3401 0 : &self,
3402 0 : tenant_id: TenantId,
3403 0 : ) -> Result<HashMap<&str, serde_json::Value>, ApiError> {
3404 0 : let config = {
3405 0 : let locked = self.inner.read().unwrap();
3406 :
3407 0 : match locked
3408 0 : .tenants
3409 0 : .range(TenantShardId::tenant_range(tenant_id))
3410 0 : .next()
3411 : {
3412 0 : Some((_tenant_shard_id, shard)) => shard.config.clone(),
3413 : None => {
3414 0 : return Err(ApiError::NotFound(
3415 0 : anyhow::anyhow!("Tenant not found").into(),
3416 0 : ));
3417 : }
3418 : }
3419 : };
3420 :
3421 : // Unlike the pageserver, we do not have a set of global defaults: the config is
3422 : // entirely per-tenant. Therefore the distinction between `tenant_specific_overrides`
3423 : // and `effective_config` in the response is meaningless, but we retain that syntax
3424 : // in order to remain compatible with the pageserver API.
3425 :
3426 0 : let response = HashMap::from([
3427 : (
3428 : "tenant_specific_overrides",
3429 0 : serde_json::to_value(&config)
3430 0 : .context("serializing tenant specific overrides")
3431 0 : .map_err(ApiError::InternalServerError)?,
3432 : ),
3433 : (
3434 0 : "effective_config",
3435 0 : serde_json::to_value(&config)
3436 0 : .context("serializing effective config")
3437 0 : .map_err(ApiError::InternalServerError)?,
3438 : ),
3439 : ]);
3440 :
3441 0 : Ok(response)
3442 0 : }
3443 :
3444 0 : pub(crate) async fn tenant_time_travel_remote_storage(
3445 0 : &self,
3446 0 : time_travel_req: &TenantTimeTravelRequest,
3447 0 : tenant_id: TenantId,
3448 0 : timestamp: Cow<'_, str>,
3449 0 : done_if_after: Cow<'_, str>,
3450 0 : ) -> Result<(), ApiError> {
3451 0 : let _tenant_lock = trace_exclusive_lock(
3452 0 : &self.tenant_op_locks,
3453 0 : tenant_id,
3454 0 : TenantOperations::TimeTravelRemoteStorage,
3455 0 : )
3456 0 : .await;
3457 :
3458 0 : let node = {
3459 0 : let mut locked = self.inner.write().unwrap();
3460 : // Just a sanity check to prevent misuse: the API expects that the tenant is fully
3461 : // detached everywhere, and nothing writes to S3 storage. Here, we verify that,
3462 : // but only at the start of the process, so it's really just to prevent operator
3463 : // mistakes.
3464 0 : for (shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
3465 0 : if shard.intent.get_attached().is_some() || !shard.intent.get_secondary().is_empty()
3466 : {
3467 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3468 0 : "We want tenant to be attached in shard with tenant_shard_id={shard_id}"
3469 0 : )));
3470 0 : }
3471 0 : let maybe_attached = shard
3472 0 : .observed
3473 0 : .locations
3474 0 : .iter()
3475 0 : .filter_map(|(node_id, observed_location)| {
3476 0 : observed_location
3477 0 : .conf
3478 0 : .as_ref()
3479 0 : .map(|loc| (node_id, observed_location, loc.mode))
3480 0 : })
3481 0 : .find(|(_, _, mode)| *mode != LocationConfigMode::Detached);
3482 0 : if let Some((node_id, _observed_location, mode)) = maybe_attached {
3483 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3484 0 : "We observed attached={mode:?} tenant in node_id={node_id} shard with tenant_shard_id={shard_id}"
3485 0 : )));
3486 0 : }
3487 : }
3488 0 : let scheduler = &mut locked.scheduler;
3489 : // Right now we only perform the operation on a single node without parallelization
3490 : // TODO fan out the operation to multiple nodes for better performance
3491 0 : let node_id = scheduler.any_available_node()?;
3492 0 : let node = locked
3493 0 : .nodes
3494 0 : .get(&node_id)
3495 0 : .expect("Pageservers may not be deleted while lock is active");
3496 0 : node.clone()
3497 : };
3498 :
3499 : // The shard count is encoded in the remote storage's URL, so we need to handle all historically used shard counts
3500 0 : let mut counts = time_travel_req
3501 0 : .shard_counts
3502 0 : .iter()
3503 0 : .copied()
3504 0 : .collect::<HashSet<_>>()
3505 0 : .into_iter()
3506 0 : .collect::<Vec<_>>();
3507 0 : counts.sort_unstable();
3508 :
3509 0 : for count in counts {
3510 0 : let shard_ids = (0..count.count())
3511 0 : .map(|i| TenantShardId {
3512 0 : tenant_id,
3513 0 : shard_number: ShardNumber(i),
3514 0 : shard_count: count,
3515 0 : })
3516 0 : .collect::<Vec<_>>();
3517 0 : for tenant_shard_id in shard_ids {
3518 0 : let client = PageserverClient::new(
3519 0 : node.get_id(),
3520 0 : self.http_client.clone(),
3521 0 : node.base_url(),
3522 0 : self.config.pageserver_jwt_token.as_deref(),
3523 : );
3524 :
3525 0 : tracing::info!("Doing time travel recovery for shard {tenant_shard_id}",);
3526 :
3527 0 : client
3528 0 : .tenant_time_travel_remote_storage(
3529 0 : tenant_shard_id,
3530 0 : ×tamp,
3531 0 : &done_if_after,
3532 0 : )
3533 0 : .await
3534 0 : .map_err(|e| {
3535 0 : ApiError::InternalServerError(anyhow::anyhow!(
3536 0 : "Error doing time travel recovery for shard {tenant_shard_id} on node {}: {e}",
3537 0 : node
3538 0 : ))
3539 0 : })?;
3540 : }
3541 : }
3542 0 : Ok(())
3543 0 : }
3544 :
3545 0 : pub(crate) async fn tenant_secondary_download(
3546 0 : &self,
3547 0 : tenant_id: TenantId,
3548 0 : wait: Option<Duration>,
3549 0 : ) -> Result<(StatusCode, SecondaryProgress), ApiError> {
3550 0 : let _tenant_lock = trace_shared_lock(
3551 0 : &self.tenant_op_locks,
3552 0 : tenant_id,
3553 0 : TenantOperations::SecondaryDownload,
3554 0 : )
3555 0 : .await;
3556 :
3557 : // Acquire lock and yield the collection of shard-node tuples which we will send requests onward to
3558 0 : let targets = {
3559 0 : let locked = self.inner.read().unwrap();
3560 0 : let mut targets = Vec::new();
3561 :
3562 0 : for (tenant_shard_id, shard) in
3563 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
3564 : {
3565 0 : for node_id in shard.intent.get_secondary() {
3566 0 : let node = locked
3567 0 : .nodes
3568 0 : .get(node_id)
3569 0 : .expect("Pageservers may not be deleted while referenced");
3570 0 :
3571 0 : targets.push((*tenant_shard_id, node.clone()));
3572 0 : }
3573 : }
3574 0 : targets
3575 : };
3576 :
3577 : // Issue concurrent requests to all shards' locations
3578 0 : let mut futs = FuturesUnordered::new();
3579 0 : for (tenant_shard_id, node) in targets {
3580 0 : let client = PageserverClient::new(
3581 0 : node.get_id(),
3582 0 : self.http_client.clone(),
3583 0 : node.base_url(),
3584 0 : self.config.pageserver_jwt_token.as_deref(),
3585 : );
3586 0 : futs.push(async move {
3587 0 : let result = client
3588 0 : .tenant_secondary_download(tenant_shard_id, wait)
3589 0 : .await;
3590 0 : (result, node, tenant_shard_id)
3591 0 : })
3592 : }
3593 :
3594 : // Handle any errors returned by pageservers. This includes cases like this request racing with
3595 : // a scheduling operation, such that the tenant shard we're calling doesn't exist on that pageserver any more, as
3596 : // well as more general cases like 503s, 500s, or timeouts.
3597 0 : let mut aggregate_progress = SecondaryProgress::default();
3598 0 : let mut aggregate_status: Option<StatusCode> = None;
3599 0 : let mut error: Option<mgmt_api::Error> = None;
3600 0 : while let Some((result, node, tenant_shard_id)) = futs.next().await {
3601 0 : match result {
3602 0 : Err(e) => {
3603 : // Secondary downloads are always advisory: if something fails, we nevertheless report success, so that whoever
3604 : // is calling us will proceed with whatever migration they're doing, albeit with a slightly less warm cache
3605 : // than they had hoped for.
3606 0 : tracing::warn!("Secondary download error from pageserver {node}: {e}",);
3607 0 : error = Some(e)
3608 : }
3609 0 : Ok((status_code, progress)) => {
3610 0 : tracing::info!(%tenant_shard_id, "Shard status={status_code} progress: {progress:?}");
3611 0 : aggregate_progress.layers_downloaded += progress.layers_downloaded;
3612 0 : aggregate_progress.layers_total += progress.layers_total;
3613 0 : aggregate_progress.bytes_downloaded += progress.bytes_downloaded;
3614 0 : aggregate_progress.bytes_total += progress.bytes_total;
3615 0 : aggregate_progress.heatmap_mtime =
3616 0 : std::cmp::max(aggregate_progress.heatmap_mtime, progress.heatmap_mtime);
3617 0 : aggregate_status = match aggregate_status {
3618 0 : None => Some(status_code),
3619 0 : Some(StatusCode::OK) => Some(status_code),
3620 0 : Some(cur) => {
3621 : // Other status codes (e.g. 202) -- do not overwrite.
3622 0 : Some(cur)
3623 : }
3624 : };
3625 : }
3626 : }
3627 : }
3628 :
3629 : // If any of the shards return 202, indicate our result as 202.
3630 0 : match aggregate_status {
3631 : None => {
3632 0 : match error {
3633 0 : Some(e) => {
3634 : // No successes, and an error: surface it
3635 0 : Err(ApiError::Conflict(format!("Error from pageserver: {e}")))
3636 : }
3637 : None => {
3638 : // No shards found
3639 0 : Err(ApiError::NotFound(
3640 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
3641 0 : ))
3642 : }
3643 : }
3644 : }
3645 0 : Some(aggregate_status) => Ok((aggregate_status, aggregate_progress)),
3646 : }
3647 0 : }
3648 :
3649 0 : pub(crate) async fn tenant_delete(
3650 0 : self: &Arc<Self>,
3651 0 : tenant_id: TenantId,
3652 0 : ) -> Result<StatusCode, ApiError> {
3653 0 : let _tenant_lock =
3654 0 : trace_exclusive_lock(&self.tenant_op_locks, tenant_id, TenantOperations::Delete).await;
3655 :
3656 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3657 :
3658 : // Detach all shards. This also deletes local pageserver shard data.
3659 0 : let (detach_waiters, node) = {
3660 0 : let mut detach_waiters = Vec::new();
3661 0 : let mut locked = self.inner.write().unwrap();
3662 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3663 0 : for (_, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3664 : // Update the tenant's intent to remove all attachments
3665 0 : shard.policy = PlacementPolicy::Detached;
3666 0 : shard
3667 0 : .schedule(scheduler, &mut ScheduleContext::default())
3668 0 : .expect("De-scheduling is infallible");
3669 0 : debug_assert!(shard.intent.get_attached().is_none());
3670 0 : debug_assert!(shard.intent.get_secondary().is_empty());
3671 :
3672 0 : if let Some(waiter) =
3673 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
3674 0 : {
3675 0 : detach_waiters.push(waiter);
3676 0 : }
3677 : }
3678 :
3679 : // Pick an arbitrary node to use for remote deletions (does not have to be where the tenant
3680 : // was attached, just has to be able to see the S3 content)
3681 0 : let node_id = scheduler.any_available_node()?;
3682 0 : let node = nodes
3683 0 : .get(&node_id)
3684 0 : .expect("Pageservers may not be deleted while lock is active");
3685 0 : (detach_waiters, node.clone())
3686 : };
3687 :
3688 : // This reconcile wait can fail in a few ways:
3689 : // A there is a very long queue for the reconciler semaphore
3690 : // B some pageserver is failing to handle a detach promptly
3691 : // C some pageserver goes offline right at the moment we send it a request.
3692 : //
3693 : // A and C are transient: the semaphore will eventually become available, and once a node is marked offline
3694 : // the next attempt to reconcile will silently skip detaches for an offline node and succeed. If B happens,
3695 : // it's a bug, and needs resolving at the pageserver level (we shouldn't just leave attachments behind while
3696 : // deleting the underlying data).
3697 0 : self.await_waiters(detach_waiters, RECONCILE_TIMEOUT)
3698 0 : .await?;
3699 :
3700 : // Delete the entire tenant (all shards) from remote storage via a random pageserver.
3701 : // Passing an unsharded tenant ID will cause the pageserver to remove all remote paths with
3702 : // the tenant ID prefix, including all shards (even possibly stale ones).
3703 0 : match node
3704 0 : .with_client_retries(
3705 0 : |client| async move {
3706 0 : client
3707 0 : .tenant_delete(TenantShardId::unsharded(tenant_id))
3708 0 : .await
3709 0 : },
3710 0 : &self.http_client,
3711 0 : &self.config.pageserver_jwt_token,
3712 : 1,
3713 : 3,
3714 : RECONCILE_TIMEOUT,
3715 0 : &self.cancel,
3716 : )
3717 0 : .await
3718 0 : .unwrap_or(Err(mgmt_api::Error::Cancelled))
3719 : {
3720 0 : Ok(_) => {}
3721 : Err(mgmt_api::Error::Cancelled) => {
3722 0 : return Err(ApiError::ShuttingDown);
3723 : }
3724 0 : Err(e) => {
3725 : // This is unexpected: remote deletion should be infallible, unless the object store
3726 : // at large is unavailable.
3727 0 : tracing::error!("Error deleting via node {node}: {e}");
3728 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
3729 : }
3730 : }
3731 :
3732 : // Fall through: deletion of the tenant on pageservers is complete, we may proceed to drop
3733 : // our in-memory state and database state.
3734 :
3735 : // Ordering: we delete persistent state first: if we then
3736 : // crash, we will drop the in-memory state.
3737 :
3738 : // Drop persistent state.
3739 0 : self.persistence.delete_tenant(tenant_id).await?;
3740 :
3741 : // Drop in-memory state
3742 : {
3743 0 : let mut locked = self.inner.write().unwrap();
3744 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
3745 :
3746 : // Dereference Scheduler from shards before dropping them
3747 0 : for (_tenant_shard_id, shard) in
3748 0 : tenants.range_mut(TenantShardId::tenant_range(tenant_id))
3749 0 : {
3750 0 : shard.intent.clear(scheduler);
3751 0 : }
3752 :
3753 0 : tenants.retain(|tenant_shard_id, _shard| tenant_shard_id.tenant_id != tenant_id);
3754 0 : tracing::info!(
3755 0 : "Deleted tenant {tenant_id}, now have {} tenants",
3756 0 : locked.tenants.len()
3757 : );
3758 : };
3759 :
3760 : // Delete the tenant from safekeepers (if needed)
3761 0 : self.tenant_delete_safekeepers(tenant_id)
3762 0 : .instrument(tracing::info_span!("tenant_delete_safekeepers", %tenant_id))
3763 0 : .await?;
3764 :
3765 : // Success is represented as 404, to imitate the existing pageserver deletion API
3766 0 : Ok(StatusCode::NOT_FOUND)
3767 0 : }
3768 :
3769 : /// Naming: this configures the storage controller's policies for a tenant, whereas [`Self::tenant_config_set`] is "set the TenantConfig"
3770 : /// for a tenant. The TenantConfig is passed through to pageservers, whereas this function modifies
3771 : /// the tenant's policies (configuration) within the storage controller
3772 0 : pub(crate) async fn tenant_update_policy(
3773 0 : &self,
3774 0 : tenant_id: TenantId,
3775 0 : req: TenantPolicyRequest,
3776 0 : ) -> Result<(), ApiError> {
3777 : // We require an exclusive lock, because we are updating persistent and in-memory state
3778 0 : let _tenant_lock = trace_exclusive_lock(
3779 0 : &self.tenant_op_locks,
3780 0 : tenant_id,
3781 0 : TenantOperations::UpdatePolicy,
3782 0 : )
3783 0 : .await;
3784 :
3785 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3786 :
3787 0 : failpoint_support::sleep_millis_async!("tenant-update-policy-exclusive-lock");
3788 :
3789 : let TenantPolicyRequest {
3790 0 : placement,
3791 0 : mut scheduling,
3792 0 : } = req;
3793 :
3794 0 : if let Some(PlacementPolicy::Detached | PlacementPolicy::Secondary) = placement {
3795 : // When someone configures a tenant to detach, we force the scheduling policy to enable
3796 : // this to take effect.
3797 0 : if scheduling.is_none() {
3798 0 : scheduling = Some(ShardSchedulingPolicy::Active);
3799 0 : }
3800 0 : }
3801 :
3802 0 : self.persistence
3803 0 : .update_tenant_shard(
3804 0 : TenantFilter::Tenant(tenant_id),
3805 0 : placement.clone(),
3806 0 : None,
3807 0 : None,
3808 0 : scheduling,
3809 0 : )
3810 0 : .await?;
3811 :
3812 0 : let mut schedule_context = ScheduleContext::default();
3813 0 : let mut locked = self.inner.write().unwrap();
3814 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3815 0 : for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3816 0 : if let Some(placement) = &placement {
3817 0 : shard.policy = placement.clone();
3818 :
3819 0 : tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
3820 0 : "Updated placement policy to {placement:?}");
3821 0 : }
3822 :
3823 0 : if let Some(scheduling) = &scheduling {
3824 0 : shard.set_scheduling_policy(*scheduling);
3825 :
3826 0 : tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
3827 0 : "Updated scheduling policy to {scheduling:?}");
3828 0 : }
3829 :
3830 : // In case scheduling is being switched back on, try it now.
3831 0 : shard.schedule(scheduler, &mut schedule_context).ok();
3832 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
3833 : }
3834 :
3835 0 : Ok(())
3836 0 : }
3837 :
3838 0 : pub(crate) async fn tenant_timeline_create_pageservers(
3839 0 : &self,
3840 0 : tenant_id: TenantId,
3841 0 : mut create_req: TimelineCreateRequest,
3842 0 : ) -> Result<TimelineInfo, ApiError> {
3843 0 : tracing::info!(
3844 0 : "Creating timeline {}/{}",
3845 : tenant_id,
3846 : create_req.new_timeline_id,
3847 : );
3848 :
3849 0 : self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
3850 0 : if targets.0.is_empty() {
3851 0 : return Err(ApiError::NotFound(
3852 0 : anyhow::anyhow!("Tenant not found").into(),
3853 0 : ));
3854 0 : };
3855 :
3856 0 : let (shard_zero_tid, shard_zero_locations) =
3857 0 : targets.0.pop_first().expect("Must have at least one shard");
3858 0 : assert!(shard_zero_tid.is_shard_zero());
3859 :
3860 0 : async fn create_one(
3861 0 : tenant_shard_id: TenantShardId,
3862 0 : locations: ShardMutationLocations,
3863 0 : http_client: reqwest::Client,
3864 0 : jwt: Option<String>,
3865 0 : mut create_req: TimelineCreateRequest,
3866 0 : ) -> Result<TimelineInfo, ApiError> {
3867 0 : let latest = locations.latest.node;
3868 :
3869 0 : tracing::info!(
3870 0 : "Creating timeline on shard {}/{}, attached to node {latest} in generation {:?}",
3871 : tenant_shard_id,
3872 : create_req.new_timeline_id,
3873 : locations.latest.generation
3874 : );
3875 :
3876 0 : let client =
3877 0 : PageserverClient::new(latest.get_id(), http_client.clone(), latest.base_url(), jwt.as_deref());
3878 :
3879 0 : let timeline_info = client
3880 0 : .timeline_create(tenant_shard_id, &create_req)
3881 0 : .await
3882 0 : .map_err(|e| passthrough_api_error(&latest, e))?;
3883 :
3884 : // If we are going to create the timeline on some stale locations for shard 0, then ask them to re-use
3885 : // the initdb generated by the latest location, rather than generating their own. This avoids racing uploads
3886 : // of initdb to S3 which might not be binary-identical if different pageservers have different postgres binaries.
3887 0 : if tenant_shard_id.is_shard_zero() {
3888 0 : if let models::TimelineCreateRequestMode::Bootstrap { existing_initdb_timeline_id, .. } = &mut create_req.mode {
3889 0 : *existing_initdb_timeline_id = Some(create_req.new_timeline_id);
3890 0 : }
3891 0 : }
3892 :
3893 : // We propagate timeline creations to all attached locations such that a compute
3894 : // for the new timeline is able to start regardless of the current state of the
3895 : // tenant shard reconciliation.
3896 0 : for location in locations.other {
3897 0 : tracing::info!(
3898 0 : "Creating timeline on shard {}/{}, stale attached to node {} in generation {:?}",
3899 : tenant_shard_id,
3900 : create_req.new_timeline_id,
3901 : location.node,
3902 : location.generation
3903 : );
3904 :
3905 0 : let client = PageserverClient::new(
3906 0 : location.node.get_id(),
3907 0 : http_client.clone(),
3908 0 : location.node.base_url(),
3909 0 : jwt.as_deref(),
3910 : );
3911 :
3912 0 : let res = client
3913 0 : .timeline_create(tenant_shard_id, &create_req)
3914 0 : .await;
3915 :
3916 0 : if let Err(e) = res {
3917 0 : match e {
3918 0 : mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _) => {
3919 0 : // Tenant might have been detached from the stale location,
3920 0 : // so ignore 404s.
3921 0 : },
3922 : _ => {
3923 0 : return Err(passthrough_api_error(&location.node, e));
3924 : }
3925 : }
3926 0 : }
3927 : }
3928 :
3929 0 : Ok(timeline_info)
3930 0 : }
3931 :
3932 : // Because the caller might not provide an explicit LSN, we must do the creation first on a single shard, and then
3933 : // use whatever LSN that shard picked when creating on subsequent shards. We arbitrarily use shard zero as the shard
3934 : // that will get the first creation request, and propagate the LSN to all the >0 shards.
3935 : //
3936 : // This also enables non-zero shards to use the initdb that shard 0 generated and uploaded to S3, rather than
3937 : // independently generating their own initdb. This guarantees that shards cannot end up with different initial
3938 : // states if e.g. they have different postgres binary versions.
3939 0 : let timeline_info = create_one(
3940 0 : shard_zero_tid,
3941 0 : shard_zero_locations,
3942 0 : self.http_client.clone(),
3943 0 : self.config.pageserver_jwt_token.clone(),
3944 0 : create_req.clone(),
3945 0 : )
3946 0 : .await?;
3947 :
3948 : // Update the create request for shards >= 0
3949 0 : match &mut create_req.mode {
3950 0 : models::TimelineCreateRequestMode::Branch { ancestor_start_lsn, .. } if ancestor_start_lsn.is_none() => {
3951 0 : // Propagate the LSN that shard zero picked, if caller didn't provide one
3952 0 : *ancestor_start_lsn = timeline_info.ancestor_lsn;
3953 0 : },
3954 0 : models::TimelineCreateRequestMode::Bootstrap { existing_initdb_timeline_id, .. } => {
3955 : // For shards >= 0, do not run initdb: use the one that shard 0 uploaded to S3
3956 0 : *existing_initdb_timeline_id = Some(create_req.new_timeline_id)
3957 : }
3958 0 : _ => {}
3959 : }
3960 :
3961 : // Create timeline on remaining shards with number >0
3962 0 : if !targets.0.is_empty() {
3963 : // If we had multiple shards, issue requests for the remainder now.
3964 0 : let jwt = &self.config.pageserver_jwt_token;
3965 0 : self.tenant_for_shards(
3966 0 : targets
3967 0 : .0
3968 0 : .iter()
3969 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
3970 0 : .collect(),
3971 0 : |tenant_shard_id: TenantShardId, _node: Node| {
3972 0 : let create_req = create_req.clone();
3973 0 : let mutation_locations = targets.0.remove(&tenant_shard_id).unwrap();
3974 0 : Box::pin(create_one(
3975 0 : tenant_shard_id,
3976 0 : mutation_locations,
3977 0 : self.http_client.clone(),
3978 0 : jwt.clone(),
3979 0 : create_req,
3980 0 : ))
3981 0 : },
3982 : )
3983 0 : .await?;
3984 0 : }
3985 :
3986 0 : Ok(timeline_info)
3987 0 : })
3988 0 : .await?
3989 0 : }
3990 :
3991 0 : pub(crate) async fn tenant_timeline_create(
3992 0 : self: &Arc<Self>,
3993 0 : tenant_id: TenantId,
3994 0 : create_req: TimelineCreateRequest,
3995 0 : ) -> Result<TimelineCreateResponseStorcon, ApiError> {
3996 0 : let safekeepers = self.config.timelines_onto_safekeepers;
3997 0 : let timeline_id = create_req.new_timeline_id;
3998 :
3999 0 : tracing::info!(
4000 0 : mode=%create_req.mode_tag(),
4001 : %safekeepers,
4002 0 : "Creating timeline {}/{}",
4003 : tenant_id,
4004 : timeline_id,
4005 : );
4006 :
4007 0 : let _tenant_lock = trace_shared_lock(
4008 0 : &self.tenant_op_locks,
4009 0 : tenant_id,
4010 0 : TenantOperations::TimelineCreate,
4011 0 : )
4012 0 : .await;
4013 0 : failpoint_support::sleep_millis_async!("tenant-create-timeline-shared-lock");
4014 0 : let is_import = create_req.is_import();
4015 0 : let read_only = matches!(
4016 0 : create_req.mode,
4017 : models::TimelineCreateRequestMode::Branch {
4018 : read_only: true,
4019 : ..
4020 : }
4021 : );
4022 :
4023 0 : if is_import {
4024 : // Ensure that there is no split on-going.
4025 : // [`Self::tenant_shard_split`] holds the exclusive tenant lock
4026 : // for the duration of the split, but here we handle the case
4027 : // where we restarted and the split is being aborted.
4028 0 : let locked = self.inner.read().unwrap();
4029 0 : let splitting = locked
4030 0 : .tenants
4031 0 : .range(TenantShardId::tenant_range(tenant_id))
4032 0 : .any(|(_id, shard)| shard.splitting != SplitState::Idle);
4033 :
4034 0 : if splitting {
4035 0 : return Err(ApiError::Conflict("Tenant is splitting shard".to_string()));
4036 0 : }
4037 0 : }
4038 :
4039 0 : let timeline_info = self
4040 0 : .tenant_timeline_create_pageservers(tenant_id, create_req)
4041 0 : .await?;
4042 :
4043 0 : let selected_safekeepers = if is_import {
4044 0 : let shards = {
4045 0 : let locked = self.inner.read().unwrap();
4046 0 : locked
4047 0 : .tenants
4048 0 : .range(TenantShardId::tenant_range(tenant_id))
4049 0 : .map(|(ts_id, _)| ts_id.to_index())
4050 0 : .collect::<Vec<_>>()
4051 : };
4052 :
4053 0 : if !shards
4054 0 : .iter()
4055 0 : .map(|shard_index| shard_index.shard_count)
4056 0 : .all_equal()
4057 : {
4058 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
4059 0 : "Inconsistent shard count"
4060 0 : )));
4061 0 : }
4062 :
4063 0 : let import = TimelineImport {
4064 0 : tenant_id,
4065 0 : timeline_id,
4066 0 : shard_statuses: ShardImportStatuses::new(shards),
4067 0 : };
4068 :
4069 0 : let inserted = self
4070 0 : .persistence
4071 0 : .insert_timeline_import(import.to_persistent())
4072 0 : .await
4073 0 : .context("timeline import insert")
4074 0 : .map_err(ApiError::InternalServerError)?;
4075 :
4076 : // Set the importing flag on the tenant shards
4077 0 : self.inner
4078 0 : .write()
4079 0 : .unwrap()
4080 0 : .tenants
4081 0 : .range_mut(TenantShardId::tenant_range(tenant_id))
4082 0 : .for_each(|(_id, shard)| shard.importing = TimelineImportState::Importing);
4083 :
4084 0 : match inserted {
4085 : true => {
4086 0 : tracing::info!(%tenant_id, %timeline_id, "Inserted timeline import");
4087 : }
4088 : false => {
4089 0 : tracing::info!(%tenant_id, %timeline_id, "Timeline import entry already present");
4090 : }
4091 : }
4092 :
4093 0 : None
4094 0 : } else if safekeepers || read_only {
4095 : // Note that for imported timelines, we do not create the timeline on the safekeepers
4096 : // straight away. Instead, we do it once the import finalized such that we know what
4097 : // start LSN to provide for the safekeepers. This is done in
4098 : // [`Self::finalize_timeline_import`].
4099 0 : let res = self
4100 0 : .tenant_timeline_create_safekeepers(tenant_id, &timeline_info, read_only)
4101 0 : .instrument(tracing::info_span!("timeline_create_safekeepers", %tenant_id, timeline_id=%timeline_info.timeline_id))
4102 0 : .await?;
4103 0 : Some(res)
4104 : } else {
4105 0 : None
4106 : };
4107 :
4108 0 : Ok(TimelineCreateResponseStorcon {
4109 0 : timeline_info,
4110 0 : safekeepers: selected_safekeepers,
4111 0 : })
4112 0 : }
4113 :
4114 : #[instrument(skip_all, fields(
4115 : tenant_id=%req.tenant_shard_id.tenant_id,
4116 : shard_id=%req.tenant_shard_id.shard_slug(),
4117 : timeline_id=%req.timeline_id,
4118 : ))]
4119 : pub(crate) async fn handle_timeline_shard_import_progress(
4120 : self: &Arc<Self>,
4121 : req: TimelineImportStatusRequest,
4122 : ) -> Result<ShardImportStatus, ApiError> {
4123 : let validity = self
4124 : .validate_shard_generation(req.tenant_shard_id, req.generation)
4125 : .await?;
4126 : match validity {
4127 : ShardGenerationValidity::Valid => {
4128 : // fallthrough
4129 : }
4130 : ShardGenerationValidity::Mismatched { claimed, actual } => {
4131 : tracing::info!(
4132 : claimed=?claimed.into(),
4133 0 : actual=?actual.and_then(|g| g.into()),
4134 : "Rejecting import progress fetch from stale generation"
4135 : );
4136 :
4137 : return Err(ApiError::BadRequest(anyhow::anyhow!("Invalid generation")));
4138 : }
4139 : }
4140 :
4141 : let maybe_import = self
4142 : .persistence
4143 : .get_timeline_import(req.tenant_shard_id.tenant_id, req.timeline_id)
4144 : .await?;
4145 :
4146 0 : let import = maybe_import.ok_or_else(|| {
4147 0 : ApiError::NotFound(
4148 0 : format!(
4149 0 : "import for {}/{} not found",
4150 0 : req.tenant_shard_id.tenant_id, req.timeline_id
4151 0 : )
4152 0 : .into(),
4153 0 : )
4154 0 : })?;
4155 :
4156 : import
4157 : .shard_statuses
4158 : .0
4159 : .get(&req.tenant_shard_id.to_index())
4160 : .cloned()
4161 0 : .ok_or_else(|| {
4162 0 : ApiError::NotFound(
4163 0 : format!("shard {} not found", req.tenant_shard_id.shard_slug()).into(),
4164 0 : )
4165 0 : })
4166 : }
4167 :
4168 : #[instrument(skip_all, fields(
4169 : tenant_id=%req.tenant_shard_id.tenant_id,
4170 : shard_id=%req.tenant_shard_id.shard_slug(),
4171 : timeline_id=%req.timeline_id,
4172 : ))]
4173 : pub(crate) async fn handle_timeline_shard_import_progress_upcall(
4174 : self: &Arc<Self>,
4175 : req: PutTimelineImportStatusRequest,
4176 : ) -> Result<(), ApiError> {
4177 : let validity = self
4178 : .validate_shard_generation(req.tenant_shard_id, req.generation)
4179 : .await?;
4180 : match validity {
4181 : ShardGenerationValidity::Valid => {
4182 : // fallthrough
4183 : }
4184 : ShardGenerationValidity::Mismatched { claimed, actual } => {
4185 : tracing::info!(
4186 : claimed=?claimed.into(),
4187 0 : actual=?actual.and_then(|g| g.into()),
4188 : "Rejecting import progress update from stale generation"
4189 : );
4190 :
4191 : return Err(ApiError::PreconditionFailed("Invalid generation".into()));
4192 : }
4193 : }
4194 :
4195 : let res = self
4196 : .persistence
4197 : .update_timeline_import(req.tenant_shard_id, req.timeline_id, req.status)
4198 : .await;
4199 : let timeline_import = match res {
4200 : Ok(Ok(Some(timeline_import))) => timeline_import,
4201 : Ok(Ok(None)) => {
4202 : // Idempotency: we've already seen and handled this update.
4203 : return Ok(());
4204 : }
4205 : Ok(Err(logical_err)) => {
4206 : return Err(logical_err.into());
4207 : }
4208 : Err(db_err) => {
4209 : return Err(db_err.into());
4210 : }
4211 : };
4212 :
4213 : tracing::info!(
4214 : tenant_id=%req.tenant_shard_id.tenant_id,
4215 : timeline_id=%req.timeline_id,
4216 : shard_id=%req.tenant_shard_id.shard_slug(),
4217 : "Updated timeline import status to: {timeline_import:?}");
4218 :
4219 : if timeline_import.is_complete() {
4220 : tokio::task::spawn({
4221 : let this = self.clone();
4222 0 : async move { this.finalize_timeline_import(timeline_import).await }
4223 : });
4224 : }
4225 :
4226 : Ok(())
4227 : }
4228 :
4229 : /// Check that a provided generation for some tenant shard is the most recent one.
4230 : ///
4231 : /// Validate with the in-mem state first, and, if that passes, validate with the
4232 : /// database state which is authoritative.
4233 0 : async fn validate_shard_generation(
4234 0 : self: &Arc<Self>,
4235 0 : tenant_shard_id: TenantShardId,
4236 0 : generation: Generation,
4237 0 : ) -> Result<ShardGenerationValidity, ApiError> {
4238 : {
4239 0 : let locked = self.inner.read().unwrap();
4240 0 : let tenant_shard =
4241 0 : locked
4242 0 : .tenants
4243 0 : .get(&tenant_shard_id)
4244 0 : .ok_or(ApiError::InternalServerError(anyhow::anyhow!(
4245 0 : "{} shard not found",
4246 0 : tenant_shard_id
4247 0 : )))?;
4248 :
4249 0 : if tenant_shard.generation != Some(generation) {
4250 0 : return Ok(ShardGenerationValidity::Mismatched {
4251 0 : claimed: generation,
4252 0 : actual: tenant_shard.generation,
4253 0 : });
4254 0 : }
4255 : }
4256 :
4257 0 : let mut db_generations = self
4258 0 : .persistence
4259 0 : .shard_generations(std::iter::once(&tenant_shard_id))
4260 0 : .await?;
4261 0 : let (_tid, db_generation) =
4262 0 : db_generations
4263 0 : .pop()
4264 0 : .ok_or(ApiError::InternalServerError(anyhow::anyhow!(
4265 0 : "{} shard not found",
4266 0 : tenant_shard_id
4267 0 : )))?;
4268 :
4269 0 : if db_generation != Some(generation) {
4270 0 : return Ok(ShardGenerationValidity::Mismatched {
4271 0 : claimed: generation,
4272 0 : actual: db_generation,
4273 0 : });
4274 0 : }
4275 :
4276 0 : Ok(ShardGenerationValidity::Valid)
4277 0 : }
4278 :
4279 : /// Finalize the import of a timeline
4280 : ///
4281 : /// This method should be called once all shards have reported that the import is complete.
4282 : /// Firstly, it polls the post import timeline activation endpoint exposed by the pageserver.
4283 : /// Once the timeline is active on all shards, the timeline also gets created on the
4284 : /// safekeepers. Finally, notify cplane of the import completion (whether failed or
4285 : /// successful), and remove the import from the database and in-memory.
4286 : ///
4287 : /// If this method gets pre-empted by shut down, it will be called again at start-up (on-going
4288 : /// imports are stored in the database).
4289 : ///
4290 : /// # Cancel-Safety
4291 : /// Not cancel safe.
4292 : /// If the caller stops polling, the import will not be removed from
4293 : /// [`ServiceState::imports_finalizing`].
4294 : #[instrument(skip_all, fields(
4295 : tenant_id=%import.tenant_id,
4296 : timeline_id=%import.timeline_id,
4297 : ))]
4298 :
4299 : async fn finalize_timeline_import(
4300 : self: &Arc<Self>,
4301 : import: TimelineImport,
4302 : ) -> Result<(), TimelineImportFinalizeError> {
4303 : let tenant_timeline = (import.tenant_id, import.timeline_id);
4304 :
4305 : let (_finalize_import_guard, cancel) = {
4306 : let mut locked = self.inner.write().unwrap();
4307 : let gate = Gate::default();
4308 : let cancel = CancellationToken::default();
4309 :
4310 : let guard = gate.enter().unwrap();
4311 :
4312 : locked.imports_finalizing.insert(
4313 : tenant_timeline,
4314 : FinalizingImport {
4315 : gate,
4316 : cancel: cancel.clone(),
4317 : },
4318 : );
4319 :
4320 : (guard, cancel)
4321 : };
4322 :
4323 : let res = tokio::select! {
4324 : res = self.finalize_timeline_import_impl(import) => {
4325 : res
4326 : },
4327 : _ = cancel.cancelled() => {
4328 : Err(TimelineImportFinalizeError::Cancelled)
4329 : }
4330 : };
4331 :
4332 : let mut locked = self.inner.write().unwrap();
4333 : locked.imports_finalizing.remove(&tenant_timeline);
4334 :
4335 : res
4336 : }
4337 :
4338 0 : async fn finalize_timeline_import_impl(
4339 0 : self: &Arc<Self>,
4340 0 : import: TimelineImport,
4341 0 : ) -> Result<(), TimelineImportFinalizeError> {
4342 0 : tracing::info!("Finalizing timeline import");
4343 :
4344 0 : pausable_failpoint!("timeline-import-pre-cplane-notification");
4345 :
4346 0 : let tenant_id = import.tenant_id;
4347 0 : let timeline_id = import.timeline_id;
4348 :
4349 0 : let import_error = import.completion_error();
4350 0 : match import_error {
4351 0 : Some(err) => {
4352 0 : self.notify_cplane_and_delete_import(tenant_id, timeline_id, Err(err))
4353 0 : .await?;
4354 0 : tracing::warn!("Timeline import completed with shard errors");
4355 0 : Ok(())
4356 : }
4357 0 : None => match self.activate_timeline_post_import(&import).await {
4358 0 : Ok(timeline_info) => {
4359 0 : tracing::info!("Post import timeline activation complete");
4360 :
4361 0 : if self.config.timelines_onto_safekeepers {
4362 : // Now that we know the start LSN of this timeline, create it on the
4363 : // safekeepers.
4364 0 : self.tenant_timeline_create_safekeepers_until_success(
4365 0 : import.tenant_id,
4366 0 : timeline_info,
4367 0 : )
4368 0 : .await?;
4369 0 : }
4370 :
4371 0 : self.notify_cplane_and_delete_import(tenant_id, timeline_id, Ok(()))
4372 0 : .await?;
4373 :
4374 0 : tracing::info!("Timeline import completed successfully");
4375 0 : Ok(())
4376 : }
4377 : Err(TimelineImportFinalizeError::ShuttingDown) => {
4378 : // We got pre-empted by shut down and will resume after the restart.
4379 0 : Err(TimelineImportFinalizeError::ShuttingDown)
4380 : }
4381 0 : Err(err) => {
4382 : // Any finalize error apart from shut down is permanent and requires us to notify
4383 : // cplane such that it can clean up.
4384 0 : tracing::error!("Import finalize failed with permanent error: {err}");
4385 0 : self.notify_cplane_and_delete_import(
4386 0 : tenant_id,
4387 0 : timeline_id,
4388 0 : Err(err.to_string()),
4389 0 : )
4390 0 : .await?;
4391 0 : Err(err)
4392 : }
4393 : },
4394 : }
4395 0 : }
4396 :
4397 0 : async fn notify_cplane_and_delete_import(
4398 0 : self: &Arc<Self>,
4399 0 : tenant_id: TenantId,
4400 0 : timeline_id: TimelineId,
4401 0 : import_result: ImportResult,
4402 0 : ) -> Result<(), TimelineImportFinalizeError> {
4403 0 : let import_failed = import_result.is_err();
4404 0 : tracing::info!(%import_failed, "Notifying cplane of import completion");
4405 :
4406 0 : let client = UpcallClient::new(self.get_config(), self.cancel.child_token());
4407 0 : client
4408 0 : .notify_import_complete(tenant_id, timeline_id, import_result)
4409 0 : .await
4410 0 : .map_err(|_err| TimelineImportFinalizeError::ShuttingDown)?;
4411 :
4412 0 : if let Err(err) = self
4413 0 : .persistence
4414 0 : .delete_timeline_import(tenant_id, timeline_id)
4415 0 : .await
4416 : {
4417 0 : tracing::warn!("Failed to delete timeline import entry from database: {err}");
4418 0 : }
4419 :
4420 0 : self.inner
4421 0 : .write()
4422 0 : .unwrap()
4423 0 : .tenants
4424 0 : .range_mut(TenantShardId::tenant_range(tenant_id))
4425 0 : .for_each(|(_id, shard)| shard.importing = TimelineImportState::Idle);
4426 :
4427 0 : Ok(())
4428 0 : }
4429 :
4430 : /// Activate an imported timeline on all shards once the import is complete.
4431 : /// Returns the [`TimelineInfo`] reported by shard zero.
4432 0 : async fn activate_timeline_post_import(
4433 0 : self: &Arc<Self>,
4434 0 : import: &TimelineImport,
4435 0 : ) -> Result<TimelineInfo, TimelineImportFinalizeError> {
4436 : const TIMELINE_ACTIVATE_TIMEOUT: Duration = Duration::from_millis(128);
4437 :
4438 0 : let mut shards_to_activate: HashSet<ShardIndex> =
4439 0 : import.shard_statuses.0.keys().cloned().collect();
4440 0 : let mut shard_zero_timeline_info = None;
4441 :
4442 0 : while !shards_to_activate.is_empty() {
4443 0 : if self.cancel.is_cancelled() {
4444 0 : return Err(TimelineImportFinalizeError::ShuttingDown);
4445 0 : }
4446 :
4447 0 : let targets = {
4448 0 : let locked = self.inner.read().unwrap();
4449 0 : let mut targets = Vec::new();
4450 :
4451 0 : for (tenant_shard_id, shard) in locked
4452 0 : .tenants
4453 0 : .range(TenantShardId::tenant_range(import.tenant_id))
4454 : {
4455 0 : if !import
4456 0 : .shard_statuses
4457 0 : .0
4458 0 : .contains_key(&tenant_shard_id.to_index())
4459 : {
4460 0 : return Err(TimelineImportFinalizeError::MismatchedShards(
4461 0 : tenant_shard_id.to_index(),
4462 0 : ));
4463 0 : }
4464 :
4465 0 : if let Some(node_id) = shard.intent.get_attached() {
4466 0 : let node = locked
4467 0 : .nodes
4468 0 : .get(node_id)
4469 0 : .expect("Pageservers may not be deleted while referenced");
4470 0 : targets.push((*tenant_shard_id, node.clone()));
4471 0 : }
4472 : }
4473 :
4474 0 : targets
4475 : };
4476 :
4477 0 : let targeted_tenant_shards: Vec<_> = targets.iter().map(|(tid, _node)| *tid).collect();
4478 :
4479 0 : let results = self
4480 0 : .tenant_for_shards_api(
4481 0 : targets,
4482 0 : |tenant_shard_id, client| async move {
4483 0 : client
4484 0 : .activate_post_import(
4485 0 : tenant_shard_id,
4486 0 : import.timeline_id,
4487 0 : TIMELINE_ACTIVATE_TIMEOUT,
4488 0 : )
4489 0 : .await
4490 0 : },
4491 : 1,
4492 : 1,
4493 : SHORT_RECONCILE_TIMEOUT,
4494 0 : &self.cancel,
4495 : )
4496 0 : .await;
4497 :
4498 0 : let mut failed = 0;
4499 0 : for (tid, (_, result)) in targeted_tenant_shards.iter().zip(results.into_iter()) {
4500 0 : match result {
4501 0 : Ok(ok) => {
4502 0 : if tid.is_shard_zero() {
4503 0 : shard_zero_timeline_info = Some(ok);
4504 0 : }
4505 :
4506 0 : shards_to_activate.remove(&tid.to_index());
4507 : }
4508 0 : Err(_err) => {
4509 0 : failed += 1;
4510 0 : }
4511 : }
4512 : }
4513 :
4514 0 : if failed > 0 {
4515 0 : tracing::info!(
4516 0 : "Failed to activate timeline on {failed} shards post import. Will retry"
4517 : );
4518 0 : }
4519 :
4520 0 : tokio::select! {
4521 0 : _ = tokio::time::sleep(Duration::from_millis(250)) => {},
4522 0 : _ = self.cancel.cancelled() => {
4523 0 : return Err(TimelineImportFinalizeError::ShuttingDown);
4524 : }
4525 : }
4526 : }
4527 :
4528 0 : Ok(shard_zero_timeline_info.expect("All shards replied"))
4529 0 : }
4530 :
4531 0 : async fn finalize_timeline_imports(self: &Arc<Self>, imports: Vec<TimelineImport>) {
4532 0 : futures::future::join_all(
4533 0 : imports
4534 0 : .into_iter()
4535 0 : .map(|import| self.finalize_timeline_import(import)),
4536 : )
4537 0 : .await;
4538 0 : }
4539 :
4540 : /// Delete a timeline import if it exists
4541 : ///
4542 : /// Firstly, delete the entry from the database. Any updates
4543 : /// from pageservers after the update will fail with a 404, so the
4544 : /// import cannot progress into finalizing state if it's not there already.
4545 : /// Secondly, cancel the finalization if one is in progress.
4546 0 : pub(crate) async fn maybe_delete_timeline_import(
4547 0 : self: &Arc<Self>,
4548 0 : tenant_id: TenantId,
4549 0 : timeline_id: TimelineId,
4550 0 : ) -> Result<(), DatabaseError> {
4551 0 : let tenant_has_ongoing_import = {
4552 0 : let locked = self.inner.read().unwrap();
4553 0 : locked
4554 0 : .tenants
4555 0 : .range(TenantShardId::tenant_range(tenant_id))
4556 0 : .any(|(_tid, shard)| shard.importing == TimelineImportState::Importing)
4557 : };
4558 :
4559 0 : if !tenant_has_ongoing_import {
4560 0 : return Ok(());
4561 0 : }
4562 :
4563 0 : self.persistence
4564 0 : .delete_timeline_import(tenant_id, timeline_id)
4565 0 : .await?;
4566 :
4567 0 : let maybe_finalizing = {
4568 0 : let mut locked = self.inner.write().unwrap();
4569 0 : locked.imports_finalizing.remove(&(tenant_id, timeline_id))
4570 : };
4571 :
4572 0 : if let Some(finalizing) = maybe_finalizing {
4573 0 : finalizing.cancel.cancel();
4574 0 : finalizing.gate.close().await;
4575 0 : }
4576 :
4577 0 : Ok(())
4578 0 : }
4579 :
4580 0 : pub(crate) async fn tenant_timeline_archival_config(
4581 0 : &self,
4582 0 : tenant_id: TenantId,
4583 0 : timeline_id: TimelineId,
4584 0 : req: TimelineArchivalConfigRequest,
4585 0 : ) -> Result<(), ApiError> {
4586 0 : tracing::info!(
4587 0 : "Setting archival config of timeline {tenant_id}/{timeline_id} to '{:?}'",
4588 : req.state
4589 : );
4590 :
4591 0 : let _tenant_lock = trace_shared_lock(
4592 0 : &self.tenant_op_locks,
4593 0 : tenant_id,
4594 0 : TenantOperations::TimelineArchivalConfig,
4595 0 : )
4596 0 : .await;
4597 :
4598 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
4599 0 : if targets.0.is_empty() {
4600 0 : return Err(ApiError::NotFound(
4601 0 : anyhow::anyhow!("Tenant not found").into(),
4602 0 : ));
4603 0 : }
4604 0 : async fn config_one(
4605 0 : tenant_shard_id: TenantShardId,
4606 0 : timeline_id: TimelineId,
4607 0 : node: Node,
4608 0 : http_client: reqwest::Client,
4609 0 : jwt: Option<String>,
4610 0 : req: TimelineArchivalConfigRequest,
4611 0 : ) -> Result<(), ApiError> {
4612 0 : tracing::info!(
4613 0 : "Setting archival config of timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
4614 : );
4615 :
4616 0 : let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
4617 :
4618 0 : client
4619 0 : .timeline_archival_config(tenant_shard_id, timeline_id, &req)
4620 0 : .await
4621 0 : .map_err(|e| match e {
4622 0 : mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg) => {
4623 0 : ApiError::PreconditionFailed(msg.into_boxed_str())
4624 : }
4625 0 : _ => passthrough_api_error(&node, e),
4626 0 : })
4627 0 : }
4628 :
4629 : // no shard needs to go first/last; the operation should be idempotent
4630 : // TODO: it would be great to ensure that all shards return the same error
4631 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
4632 0 : let results = self
4633 0 : .tenant_for_shards(locations, |tenant_shard_id, node| {
4634 0 : futures::FutureExt::boxed(config_one(
4635 0 : tenant_shard_id,
4636 0 : timeline_id,
4637 0 : node,
4638 0 : self.http_client.clone(),
4639 0 : self.config.pageserver_jwt_token.clone(),
4640 0 : req.clone(),
4641 0 : ))
4642 0 : })
4643 0 : .await?;
4644 0 : assert!(!results.is_empty(), "must have at least one result");
4645 :
4646 0 : Ok(())
4647 0 : }).await?
4648 0 : }
4649 :
4650 0 : pub(crate) async fn tenant_timeline_detach_ancestor(
4651 0 : &self,
4652 0 : tenant_id: TenantId,
4653 0 : timeline_id: TimelineId,
4654 0 : behavior: Option<DetachBehavior>,
4655 0 : ) -> Result<models::detach_ancestor::AncestorDetached, ApiError> {
4656 0 : tracing::info!("Detaching timeline {tenant_id}/{timeline_id}",);
4657 :
4658 0 : let _tenant_lock = trace_shared_lock(
4659 0 : &self.tenant_op_locks,
4660 0 : tenant_id,
4661 0 : TenantOperations::TimelineDetachAncestor,
4662 0 : )
4663 0 : .await;
4664 :
4665 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
4666 0 : if targets.0.is_empty() {
4667 0 : return Err(ApiError::NotFound(
4668 0 : anyhow::anyhow!("Tenant not found").into(),
4669 0 : ));
4670 0 : }
4671 :
4672 0 : async fn detach_one(
4673 0 : tenant_shard_id: TenantShardId,
4674 0 : timeline_id: TimelineId,
4675 0 : node: Node,
4676 0 : http_client: reqwest::Client,
4677 0 : jwt: Option<String>,
4678 0 : behavior: Option<DetachBehavior>,
4679 0 : ) -> Result<(ShardNumber, models::detach_ancestor::AncestorDetached), ApiError> {
4680 0 : tracing::info!(
4681 0 : "Detaching timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
4682 : );
4683 :
4684 0 : let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
4685 :
4686 0 : client
4687 0 : .timeline_detach_ancestor(tenant_shard_id, timeline_id, behavior)
4688 0 : .await
4689 0 : .map_err(|e| {
4690 : use mgmt_api::Error;
4691 :
4692 0 : match e {
4693 : // no ancestor (ever)
4694 0 : Error::ApiError(StatusCode::CONFLICT, msg) => ApiError::Conflict(format!(
4695 0 : "{node}: {}",
4696 0 : msg.strip_prefix("Conflict: ").unwrap_or(&msg)
4697 0 : )),
4698 : // too many ancestors
4699 0 : Error::ApiError(StatusCode::BAD_REQUEST, msg) => {
4700 0 : ApiError::BadRequest(anyhow::anyhow!("{node}: {msg}"))
4701 : }
4702 0 : Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, msg) => {
4703 : // avoid turning these into conflicts to remain compatible with
4704 : // pageservers, 500 errors are sadly retryable with timeline ancestor
4705 : // detach
4706 0 : ApiError::InternalServerError(anyhow::anyhow!("{node}: {msg}"))
4707 : }
4708 : // rest can be mapped as usual
4709 0 : other => passthrough_api_error(&node, other),
4710 : }
4711 0 : })
4712 0 : .map(|res| (tenant_shard_id.shard_number, res))
4713 0 : }
4714 :
4715 : // no shard needs to go first/last; the operation should be idempotent
4716 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
4717 0 : let mut results = self
4718 0 : .tenant_for_shards(locations, |tenant_shard_id, node| {
4719 0 : futures::FutureExt::boxed(detach_one(
4720 0 : tenant_shard_id,
4721 0 : timeline_id,
4722 0 : node,
4723 0 : self.http_client.clone(),
4724 0 : self.config.pageserver_jwt_token.clone(),
4725 0 : behavior,
4726 0 : ))
4727 0 : })
4728 0 : .await?;
4729 :
4730 0 : let any = results.pop().expect("we must have at least one response");
4731 :
4732 0 : let mismatching = results
4733 0 : .iter()
4734 0 : .filter(|(_, res)| res != &any.1)
4735 0 : .collect::<Vec<_>>();
4736 0 : if !mismatching.is_empty() {
4737 : // this can be hit by races which should not happen because operation lock on cplane
4738 0 : let matching = results.len() - mismatching.len();
4739 0 : tracing::error!(
4740 : matching,
4741 : compared_against=?any,
4742 : ?mismatching,
4743 0 : "shards returned different results"
4744 : );
4745 :
4746 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!("pageservers returned mixed results for ancestor detach; manual intervention is required.")));
4747 0 : }
4748 :
4749 0 : Ok(any.1)
4750 0 : }).await?
4751 0 : }
4752 :
4753 0 : pub(crate) async fn tenant_timeline_block_unblock_gc(
4754 0 : &self,
4755 0 : tenant_id: TenantId,
4756 0 : timeline_id: TimelineId,
4757 0 : dir: BlockUnblock,
4758 0 : ) -> Result<(), ApiError> {
4759 0 : let _tenant_lock = trace_shared_lock(
4760 0 : &self.tenant_op_locks,
4761 0 : tenant_id,
4762 0 : TenantOperations::TimelineGcBlockUnblock,
4763 0 : )
4764 0 : .await;
4765 :
4766 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
4767 0 : if targets.0.is_empty() {
4768 0 : return Err(ApiError::NotFound(
4769 0 : anyhow::anyhow!("Tenant not found").into(),
4770 0 : ));
4771 0 : }
4772 :
4773 0 : async fn do_one(
4774 0 : tenant_shard_id: TenantShardId,
4775 0 : timeline_id: TimelineId,
4776 0 : node: Node,
4777 0 : http_client: reqwest::Client,
4778 0 : jwt: Option<String>,
4779 0 : dir: BlockUnblock,
4780 0 : ) -> Result<(), ApiError> {
4781 0 : let client = PageserverClient::new(
4782 0 : node.get_id(),
4783 0 : http_client,
4784 0 : node.base_url(),
4785 0 : jwt.as_deref(),
4786 : );
4787 :
4788 0 : client
4789 0 : .timeline_block_unblock_gc(tenant_shard_id, timeline_id, dir)
4790 0 : .await
4791 0 : .map_err(|e| passthrough_api_error(&node, e))
4792 0 : }
4793 :
4794 : // no shard needs to go first/last; the operation should be idempotent
4795 0 : let locations = targets
4796 0 : .0
4797 0 : .iter()
4798 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
4799 0 : .collect();
4800 0 : self.tenant_for_shards(locations, |tenant_shard_id, node| {
4801 0 : futures::FutureExt::boxed(do_one(
4802 0 : tenant_shard_id,
4803 0 : timeline_id,
4804 0 : node,
4805 0 : self.http_client.clone(),
4806 0 : self.config.pageserver_jwt_token.clone(),
4807 0 : dir,
4808 0 : ))
4809 0 : })
4810 0 : .await
4811 0 : })
4812 0 : .await??;
4813 0 : Ok(())
4814 0 : }
4815 :
4816 0 : pub(crate) fn is_tenant_not_found_error(body: &str, tenant_id: TenantId) -> bool {
4817 0 : body.contains(&format!("tenant {tenant_id}"))
4818 0 : }
4819 :
4820 0 : fn process_result_and_passthrough_errors<T>(
4821 0 : &self,
4822 0 : tenant_id: TenantId,
4823 0 : results: Vec<(Node, Result<T, mgmt_api::Error>)>,
4824 0 : ) -> Result<Vec<(Node, T)>, ApiError> {
4825 0 : let mut processed_results: Vec<(Node, T)> = Vec::with_capacity(results.len());
4826 0 : for (node, res) in results {
4827 0 : match res {
4828 0 : Ok(res) => processed_results.push((node, res)),
4829 0 : Err(mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, body))
4830 0 : if Self::is_tenant_not_found_error(&body, tenant_id) =>
4831 : {
4832 : // If there's a tenant not found, we are still in the process of attaching the tenant.
4833 : // Return 503 so that the client can retry.
4834 0 : return Err(ApiError::ResourceUnavailable(
4835 0 : format!(
4836 0 : "Timeline is not attached to the pageserver {} yet, please retry",
4837 0 : node.get_id()
4838 0 : )
4839 0 : .into(),
4840 0 : ));
4841 : }
4842 0 : Err(e) => return Err(passthrough_api_error(&node, e)),
4843 : }
4844 : }
4845 0 : Ok(processed_results)
4846 0 : }
4847 :
4848 0 : pub(crate) async fn tenant_timeline_lsn_lease(
4849 0 : &self,
4850 0 : tenant_id: TenantId,
4851 0 : timeline_id: TimelineId,
4852 0 : lsn: Lsn,
4853 0 : ) -> Result<LsnLease, ApiError> {
4854 0 : let _tenant_lock = trace_shared_lock(
4855 0 : &self.tenant_op_locks,
4856 0 : tenant_id,
4857 0 : TenantOperations::TimelineLsnLease,
4858 0 : )
4859 0 : .await;
4860 :
4861 0 : self.tenant_remote_mutation(tenant_id, |locations| async move {
4862 0 : if locations.0.is_empty() {
4863 0 : return Err(ApiError::NotFound(
4864 0 : anyhow::anyhow!("Tenant not found").into(),
4865 0 : ));
4866 0 : }
4867 :
4868 0 : let results = self
4869 0 : .tenant_for_shards_api(
4870 0 : locations
4871 0 : .0
4872 0 : .iter()
4873 0 : .map(|(tenant_shard_id, ShardMutationLocations { latest, .. })| {
4874 0 : (*tenant_shard_id, latest.node.clone())
4875 0 : })
4876 0 : .collect(),
4877 0 : |tenant_shard_id, client| async move {
4878 0 : client
4879 0 : .timeline_lease_lsn(tenant_shard_id, timeline_id, lsn)
4880 0 : .await
4881 0 : },
4882 : 1,
4883 : 1,
4884 : SHORT_RECONCILE_TIMEOUT,
4885 0 : &self.cancel,
4886 : )
4887 0 : .await;
4888 :
4889 0 : let leases = self.process_result_and_passthrough_errors(tenant_id, results)?;
4890 0 : let mut valid_until = None;
4891 0 : for (_, lease) in leases {
4892 0 : if let Some(ref mut valid_until) = valid_until {
4893 0 : *valid_until = std::cmp::min(*valid_until, lease.valid_until);
4894 0 : } else {
4895 0 : valid_until = Some(lease.valid_until);
4896 0 : }
4897 : }
4898 0 : Ok(LsnLease {
4899 0 : valid_until: valid_until.unwrap_or_else(SystemTime::now),
4900 0 : })
4901 0 : })
4902 0 : .await?
4903 0 : }
4904 :
4905 0 : pub(crate) async fn tenant_timeline_download_heatmap_layers(
4906 0 : &self,
4907 0 : tenant_shard_id: TenantShardId,
4908 0 : timeline_id: TimelineId,
4909 0 : concurrency: Option<usize>,
4910 0 : recurse: bool,
4911 0 : ) -> Result<(), ApiError> {
4912 0 : let _tenant_lock = trace_shared_lock(
4913 0 : &self.tenant_op_locks,
4914 0 : tenant_shard_id.tenant_id,
4915 0 : TenantOperations::DownloadHeatmapLayers,
4916 0 : )
4917 0 : .await;
4918 :
4919 0 : let targets = {
4920 0 : let locked = self.inner.read().unwrap();
4921 0 : let mut targets = Vec::new();
4922 :
4923 : // If the request got an unsharded tenant id, then apply
4924 : // the operation to all shards. Otherwise, apply it to a specific shard.
4925 0 : let shards_range = if tenant_shard_id.is_unsharded() {
4926 0 : TenantShardId::tenant_range(tenant_shard_id.tenant_id)
4927 : } else {
4928 0 : tenant_shard_id.range()
4929 : };
4930 :
4931 0 : for (tenant_shard_id, shard) in locked.tenants.range(shards_range) {
4932 0 : if let Some(node_id) = shard.intent.get_attached() {
4933 0 : let node = locked
4934 0 : .nodes
4935 0 : .get(node_id)
4936 0 : .expect("Pageservers may not be deleted while referenced");
4937 0 :
4938 0 : targets.push((*tenant_shard_id, node.clone()));
4939 0 : }
4940 : }
4941 0 : targets
4942 : };
4943 :
4944 0 : self.tenant_for_shards_api(
4945 0 : targets,
4946 0 : |tenant_shard_id, client| async move {
4947 0 : client
4948 0 : .timeline_download_heatmap_layers(
4949 0 : tenant_shard_id,
4950 0 : timeline_id,
4951 0 : concurrency,
4952 0 : recurse,
4953 0 : )
4954 0 : .await
4955 0 : },
4956 : 1,
4957 : 1,
4958 : SHORT_RECONCILE_TIMEOUT,
4959 0 : &self.cancel,
4960 : )
4961 0 : .await;
4962 :
4963 0 : Ok(())
4964 0 : }
4965 :
4966 : /// Helper for concurrently calling a pageserver API on a number of shards, such as timeline creation.
4967 : ///
4968 : /// On success, the returned vector contains exactly the same number of elements as the input `locations`
4969 : /// and returned element at index `i` is the result for `req_fn(op(locations[i])`.
4970 0 : async fn tenant_for_shards<F, R>(
4971 0 : &self,
4972 0 : locations: Vec<(TenantShardId, Node)>,
4973 0 : mut req_fn: F,
4974 0 : ) -> Result<Vec<R>, ApiError>
4975 0 : where
4976 0 : F: FnMut(
4977 0 : TenantShardId,
4978 0 : Node,
4979 0 : )
4980 0 : -> std::pin::Pin<Box<dyn futures::Future<Output = Result<R, ApiError>> + Send>>,
4981 0 : {
4982 0 : let mut futs = FuturesUnordered::new();
4983 0 : let mut results = Vec::with_capacity(locations.len());
4984 :
4985 0 : for (idx, (tenant_shard_id, node)) in locations.into_iter().enumerate() {
4986 0 : let fut = req_fn(tenant_shard_id, node);
4987 0 : futs.push(async move { (idx, fut.await) });
4988 : }
4989 :
4990 0 : while let Some((idx, r)) = futs.next().await {
4991 0 : results.push((idx, r?));
4992 : }
4993 :
4994 0 : results.sort_by_key(|(idx, _)| *idx);
4995 0 : Ok(results.into_iter().map(|(_, r)| r).collect())
4996 0 : }
4997 :
4998 : /// Concurrently invoke a pageserver API call on many shards at once.
4999 : ///
5000 : /// The returned Vec has the same length as the `locations` Vec,
5001 : /// and returned element at index `i` is the result for `op(locations[i])`.
5002 0 : pub(crate) async fn tenant_for_shards_api<T, O, F>(
5003 0 : &self,
5004 0 : locations: Vec<(TenantShardId, Node)>,
5005 0 : op: O,
5006 0 : warn_threshold: u32,
5007 0 : max_retries: u32,
5008 0 : timeout: Duration,
5009 0 : cancel: &CancellationToken,
5010 0 : ) -> Vec<(Node, mgmt_api::Result<T>)>
5011 0 : where
5012 0 : O: Fn(TenantShardId, PageserverClient) -> F + Copy,
5013 0 : F: std::future::Future<Output = mgmt_api::Result<T>>,
5014 0 : {
5015 0 : let mut futs = FuturesUnordered::new();
5016 0 : let mut results = Vec::with_capacity(locations.len());
5017 :
5018 0 : for (idx, (tenant_shard_id, node)) in locations.into_iter().enumerate() {
5019 0 : futs.push(async move {
5020 0 : let r = node
5021 0 : .with_client_retries(
5022 0 : |client| op(tenant_shard_id, client),
5023 0 : &self.http_client,
5024 0 : &self.config.pageserver_jwt_token,
5025 0 : warn_threshold,
5026 0 : max_retries,
5027 0 : timeout,
5028 0 : cancel,
5029 : )
5030 0 : .await;
5031 0 : (idx, node, r)
5032 0 : });
5033 : }
5034 :
5035 0 : while let Some((idx, node, r)) = futs.next().await {
5036 0 : results.push((idx, node, r.unwrap_or(Err(mgmt_api::Error::Cancelled))));
5037 0 : }
5038 :
5039 0 : results.sort_by_key(|(idx, _, _)| *idx);
5040 0 : results.into_iter().map(|(_, node, r)| (node, r)).collect()
5041 0 : }
5042 :
5043 : /// Helper for safely working with the shards in a tenant remotely on pageservers, for example
5044 : /// when creating and deleting timelines:
5045 : /// - Makes sure shards are attached somewhere if they weren't already
5046 : /// - Looks up the shards and the nodes where they were most recently attached
5047 : /// - Guarantees that after the inner function returns, the shards' generations haven't moved on: this
5048 : /// ensures that the remote operation acted on the most recent generation, and is therefore durable.
5049 0 : pub(crate) async fn tenant_remote_mutation<R, O, F>(
5050 0 : &self,
5051 0 : tenant_id: TenantId,
5052 0 : op: O,
5053 0 : ) -> Result<R, ApiError>
5054 0 : where
5055 0 : O: FnOnce(TenantMutationLocations) -> F,
5056 0 : F: std::future::Future<Output = R>,
5057 0 : {
5058 0 : self.tenant_remote_mutation_inner(TenantIdOrShardId::TenantId(tenant_id), op)
5059 0 : .await
5060 0 : }
5061 :
5062 0 : pub(crate) async fn tenant_shard_remote_mutation<R, O, F>(
5063 0 : &self,
5064 0 : tenant_shard_id: TenantShardId,
5065 0 : op: O,
5066 0 : ) -> Result<R, ApiError>
5067 0 : where
5068 0 : O: FnOnce(TenantMutationLocations) -> F,
5069 0 : F: std::future::Future<Output = R>,
5070 0 : {
5071 0 : self.tenant_remote_mutation_inner(TenantIdOrShardId::TenantShardId(tenant_shard_id), op)
5072 0 : .await
5073 0 : }
5074 :
5075 0 : async fn tenant_remote_mutation_inner<R, O, F>(
5076 0 : &self,
5077 0 : tenant_id_or_shard_id: TenantIdOrShardId,
5078 0 : op: O,
5079 0 : ) -> Result<R, ApiError>
5080 0 : where
5081 0 : O: FnOnce(TenantMutationLocations) -> F,
5082 0 : F: std::future::Future<Output = R>,
5083 0 : {
5084 0 : let mutation_locations = {
5085 0 : let mut locations = TenantMutationLocations::default();
5086 :
5087 : // Load the currently attached pageservers for the latest generation of each shard. This can
5088 : // run concurrently with reconciliations, and it is not guaranteed that the node we find here
5089 : // will still be the latest when we're done: we will check generations again at the end of
5090 : // this function to handle that.
5091 0 : let generations = self
5092 0 : .persistence
5093 0 : .tenant_generations(tenant_id_or_shard_id.tenant_id())
5094 0 : .await?
5095 0 : .into_iter()
5096 0 : .filter(|i| tenant_id_or_shard_id.matches(&i.tenant_shard_id))
5097 0 : .collect::<Vec<_>>();
5098 :
5099 0 : if generations
5100 0 : .iter()
5101 0 : .any(|i| i.generation.is_none() || i.generation_pageserver.is_none())
5102 : {
5103 0 : let shard_generations = generations
5104 0 : .into_iter()
5105 0 : .map(|i| (i.tenant_shard_id, (i.generation, i.generation_pageserver)))
5106 0 : .collect::<HashMap<_, _>>();
5107 :
5108 : // One or more shards has not been attached to a pageserver. Check if this is because it's configured
5109 : // to be detached (409: caller should give up), or because it's meant to be attached but isn't yet (503: caller should retry)
5110 0 : let locked = self.inner.read().unwrap();
5111 0 : let tenant_shards = locked
5112 0 : .tenants
5113 0 : .range(TenantShardId::tenant_range(
5114 0 : tenant_id_or_shard_id.tenant_id(),
5115 : ))
5116 0 : .filter(|(shard_id, _)| tenant_id_or_shard_id.matches(shard_id))
5117 0 : .collect::<Vec<_>>();
5118 0 : for (shard_id, shard) in tenant_shards {
5119 0 : match shard.policy {
5120 : PlacementPolicy::Attached(_) => {
5121 : // This shard is meant to be attached: the caller is not wrong to try and
5122 : // use this function, but we can't service the request right now.
5123 0 : let Some(generation) = shard_generations.get(shard_id) else {
5124 : // This can only happen if there is a split brain controller modifying the database. This should
5125 : // never happen when testing, and if it happens in production we can only log the issue.
5126 0 : debug_assert!(false);
5127 0 : tracing::error!(
5128 0 : "Shard {shard_id} not found in generation state! Is another rogue controller running?"
5129 : );
5130 0 : continue;
5131 : };
5132 0 : let (generation, generation_pageserver) = generation;
5133 0 : if let Some(generation) = generation {
5134 0 : if generation_pageserver.is_none() {
5135 : // This is legitimate only in a very narrow window where the shard was only just configured into
5136 : // Attached mode after being created in Secondary or Detached mode, and it has had its generation
5137 : // set but not yet had a Reconciler run (reconciler is the only thing that sets generation_pageserver).
5138 0 : tracing::warn!(
5139 0 : "Shard {shard_id} generation is set ({generation:?}) but generation_pageserver is None, reconciler not run yet?"
5140 : );
5141 0 : }
5142 : } else {
5143 : // This should never happen: a shard with no generation is only permitted when it was created in some state
5144 : // other than PlacementPolicy::Attached (and generation is always written to DB before setting Attached in memory)
5145 0 : debug_assert!(false);
5146 0 : tracing::error!(
5147 0 : "Shard {shard_id} generation is None, but it is in PlacementPolicy::Attached mode!"
5148 : );
5149 0 : continue;
5150 : }
5151 : }
5152 : PlacementPolicy::Secondary | PlacementPolicy::Detached => {
5153 0 : return Err(ApiError::Conflict(format!(
5154 0 : "Shard {shard_id} tenant has policy {:?}",
5155 0 : shard.policy
5156 0 : )));
5157 : }
5158 : }
5159 : }
5160 :
5161 0 : return Err(ApiError::ResourceUnavailable(
5162 0 : "One or more shards in tenant is not yet attached".into(),
5163 0 : ));
5164 0 : }
5165 :
5166 0 : let locked = self.inner.read().unwrap();
5167 : for ShardGenerationState {
5168 0 : tenant_shard_id,
5169 0 : generation,
5170 0 : generation_pageserver,
5171 0 : } in generations
5172 : {
5173 0 : let node_id = generation_pageserver.expect("We checked for None above");
5174 0 : let node = locked
5175 0 : .nodes
5176 0 : .get(&node_id)
5177 0 : .ok_or(ApiError::Conflict(format!(
5178 0 : "Raced with removal of node {node_id}"
5179 0 : )))?;
5180 0 : let generation = generation.expect("Checked above");
5181 :
5182 0 : let tenant = locked.tenants.get(&tenant_shard_id);
5183 :
5184 : // TODO(vlad): Abstract the logic that finds stale attached locations
5185 : // from observed state into a [`Service`] method.
5186 0 : let other_locations = match tenant {
5187 0 : Some(tenant) => {
5188 0 : let mut other = tenant.attached_locations();
5189 0 : let latest_location_index =
5190 0 : other.iter().position(|&l| l == (node.get_id(), generation));
5191 0 : if let Some(idx) = latest_location_index {
5192 0 : other.remove(idx);
5193 0 : }
5194 :
5195 0 : other
5196 : }
5197 0 : None => Vec::default(),
5198 : };
5199 :
5200 0 : let location = ShardMutationLocations {
5201 0 : latest: MutationLocation {
5202 0 : node: node.clone(),
5203 0 : generation,
5204 0 : },
5205 0 : other: other_locations
5206 0 : .into_iter()
5207 0 : .filter_map(|(node_id, generation)| {
5208 0 : let node = locked.nodes.get(&node_id)?;
5209 :
5210 0 : Some(MutationLocation {
5211 0 : node: node.clone(),
5212 0 : generation,
5213 0 : })
5214 0 : })
5215 0 : .collect(),
5216 : };
5217 0 : locations.0.insert(tenant_shard_id, location);
5218 : }
5219 :
5220 0 : locations
5221 : };
5222 :
5223 0 : let result = op(mutation_locations.clone()).await;
5224 :
5225 : // Post-check: are all the generations of all the shards the same as they were initially? This proves that
5226 : // our remote operation executed on the latest generation and is therefore persistent.
5227 : {
5228 0 : let latest_generations = self
5229 0 : .persistence
5230 0 : .tenant_generations(tenant_id_or_shard_id.tenant_id())
5231 0 : .await?
5232 0 : .into_iter()
5233 0 : .filter(|i| tenant_id_or_shard_id.matches(&i.tenant_shard_id))
5234 0 : .collect::<Vec<_>>();
5235 :
5236 0 : if latest_generations
5237 0 : .into_iter()
5238 0 : .map(
5239 : |ShardGenerationState {
5240 : tenant_shard_id,
5241 : generation,
5242 : generation_pageserver: _,
5243 0 : }| (tenant_shard_id, generation),
5244 : )
5245 0 : .collect::<Vec<_>>()
5246 0 : != mutation_locations
5247 0 : .0
5248 0 : .into_iter()
5249 0 : .map(|i| (i.0, Some(i.1.latest.generation)))
5250 0 : .collect::<Vec<_>>()
5251 : {
5252 : // We raced with something that incremented the generation, and therefore cannot be
5253 : // confident that our actions are persistent (they might have hit an old generation).
5254 : //
5255 : // This is safe but requires a retry: ask the client to do that by giving them a 503 response.
5256 0 : return Err(ApiError::ResourceUnavailable(
5257 0 : "Tenant attachment changed, please retry".into(),
5258 0 : ));
5259 0 : }
5260 : }
5261 :
5262 0 : Ok(result)
5263 0 : }
5264 :
5265 0 : pub(crate) async fn tenant_timeline_delete(
5266 0 : self: &Arc<Self>,
5267 0 : tenant_id: TenantId,
5268 0 : timeline_id: TimelineId,
5269 0 : ) -> Result<StatusCode, ApiError> {
5270 0 : tracing::info!("Deleting timeline {}/{}", tenant_id, timeline_id,);
5271 0 : let _tenant_lock = trace_shared_lock(
5272 0 : &self.tenant_op_locks,
5273 0 : tenant_id,
5274 0 : TenantOperations::TimelineDelete,
5275 0 : )
5276 0 : .await;
5277 :
5278 0 : let status_code = self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
5279 0 : if targets.0.is_empty() {
5280 0 : return Err(ApiError::NotFound(
5281 0 : anyhow::anyhow!("Tenant not found").into(),
5282 0 : ));
5283 0 : }
5284 :
5285 0 : let (shard_zero_tid, shard_zero_locations) = targets.0.pop_first().expect("Must have at least one shard");
5286 0 : assert!(shard_zero_tid.is_shard_zero());
5287 :
5288 0 : async fn delete_one(
5289 0 : tenant_shard_id: TenantShardId,
5290 0 : timeline_id: TimelineId,
5291 0 : node: Node,
5292 0 : http_client: reqwest::Client,
5293 0 : jwt: Option<String>,
5294 0 : ) -> Result<StatusCode, ApiError> {
5295 0 : tracing::info!(
5296 0 : "Deleting timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
5297 : );
5298 :
5299 0 : let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
5300 0 : let res = client
5301 0 : .timeline_delete(tenant_shard_id, timeline_id)
5302 0 : .await;
5303 :
5304 0 : match res {
5305 0 : Ok(ok) => Ok(ok),
5306 0 : Err(mgmt_api::Error::ApiError(StatusCode::CONFLICT, _)) => Ok(StatusCode::CONFLICT),
5307 0 : Err(mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg)) if msg.contains("Requested tenant is missing") => {
5308 0 : Err(ApiError::ResourceUnavailable("Tenant migration in progress".into()))
5309 : },
5310 0 : Err(mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg)) => Err(ApiError::ResourceUnavailable(msg.into())),
5311 0 : Err(e) => {
5312 0 : Err(
5313 0 : ApiError::InternalServerError(anyhow::anyhow!(
5314 0 : "Error deleting timeline {timeline_id} on {tenant_shard_id} on node {node}: {e}",
5315 0 : ))
5316 0 : )
5317 : }
5318 : }
5319 0 : }
5320 :
5321 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
5322 0 : let statuses = self
5323 0 : .tenant_for_shards(locations, |tenant_shard_id: TenantShardId, node: Node| {
5324 0 : Box::pin(delete_one(
5325 0 : tenant_shard_id,
5326 0 : timeline_id,
5327 0 : node,
5328 0 : self.http_client.clone(),
5329 0 : self.config.pageserver_jwt_token.clone(),
5330 0 : ))
5331 0 : })
5332 0 : .await?;
5333 :
5334 : // If any shards >0 haven't finished deletion yet, don't start deletion on shard zero.
5335 : // We return 409 (Conflict) if deletion was already in progress on any of the shards
5336 : // and 202 (Accepted) if deletion was not already in progress on any of the shards.
5337 0 : if statuses.iter().any(|s| s == &StatusCode::CONFLICT) {
5338 0 : return Ok(StatusCode::CONFLICT);
5339 0 : }
5340 :
5341 0 : if statuses.iter().any(|s| s != &StatusCode::NOT_FOUND) {
5342 0 : return Ok(StatusCode::ACCEPTED);
5343 0 : }
5344 :
5345 : // Delete shard zero last: this is not strictly necessary, but since a caller's GET on a timeline will be routed
5346 : // to shard zero, it gives a more obvious behavior that a GET returns 404 once the deletion is done.
5347 0 : let shard_zero_status = delete_one(
5348 0 : shard_zero_tid,
5349 0 : timeline_id,
5350 0 : shard_zero_locations.latest.node,
5351 0 : self.http_client.clone(),
5352 0 : self.config.pageserver_jwt_token.clone(),
5353 0 : )
5354 0 : .await?;
5355 0 : Ok(shard_zero_status)
5356 0 : }).await?;
5357 :
5358 0 : self.tenant_timeline_delete_safekeepers(tenant_id, timeline_id)
5359 0 : .await?;
5360 :
5361 0 : status_code
5362 0 : }
5363 : /// When you know the TenantId but not a specific shard, and would like to get the node holding shard 0.
5364 : ///
5365 : /// Returns the node, tenant shard id, and whether it is consistent with the observed state.
5366 0 : pub(crate) async fn tenant_shard0_node(
5367 0 : &self,
5368 0 : tenant_id: TenantId,
5369 0 : ) -> Result<(Node, TenantShardId), ApiError> {
5370 0 : let tenant_shard_id = {
5371 0 : let locked = self.inner.read().unwrap();
5372 0 : let Some((tenant_shard_id, _shard)) = locked
5373 0 : .tenants
5374 0 : .range(TenantShardId::tenant_range(tenant_id))
5375 0 : .next()
5376 : else {
5377 0 : return Err(ApiError::NotFound(
5378 0 : anyhow::anyhow!("Tenant {tenant_id} not found").into(),
5379 0 : ));
5380 : };
5381 :
5382 0 : *tenant_shard_id
5383 : };
5384 :
5385 0 : self.tenant_shard_node(tenant_shard_id)
5386 0 : .await
5387 0 : .map(|node| (node, tenant_shard_id))
5388 0 : }
5389 :
5390 : /// When you need to send an HTTP request to the pageserver that holds a shard of a tenant, this
5391 : /// function looks up and returns node. If the shard isn't found, returns Err(ApiError::NotFound)
5392 : ///
5393 : /// Returns the intent node and whether it is consistent with the observed state.
5394 0 : pub(crate) async fn tenant_shard_node(
5395 0 : &self,
5396 0 : tenant_shard_id: TenantShardId,
5397 0 : ) -> Result<Node, ApiError> {
5398 : // Look up in-memory state and maybe use the node from there.
5399 : {
5400 0 : let locked = self.inner.read().unwrap();
5401 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
5402 0 : return Err(ApiError::NotFound(
5403 0 : anyhow::anyhow!("Tenant shard {tenant_shard_id} not found").into(),
5404 0 : ));
5405 : };
5406 :
5407 0 : let Some(intent_node_id) = shard.intent.get_attached() else {
5408 0 : tracing::warn!(
5409 0 : tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
5410 0 : "Shard not scheduled (policy {:?}), cannot generate pass-through URL",
5411 : shard.policy
5412 : );
5413 0 : return Err(ApiError::Conflict(
5414 0 : "Cannot call timeline API on non-attached tenant".to_string(),
5415 0 : ));
5416 : };
5417 :
5418 0 : if shard.reconciler.is_none() {
5419 : // Optimization: while no reconcile is in flight, we may trust our in-memory state
5420 : // to tell us which pageserver to use. Otherwise we will fall through and hit the database
5421 0 : let Some(node) = locked.nodes.get(intent_node_id) else {
5422 : // This should never happen
5423 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5424 0 : "Shard refers to nonexistent node"
5425 0 : )));
5426 : };
5427 0 : return Ok(node.clone());
5428 0 : }
5429 : };
5430 :
5431 : // Look up the latest attached pageserver location from the database
5432 : // generation state: this will reflect the progress of any ongoing migration.
5433 : // Note that it is not guaranteed to _stay_ here, our caller must still handle
5434 : // the case where they call through to the pageserver and get a 404.
5435 0 : let db_result = self
5436 0 : .persistence
5437 0 : .tenant_generations(tenant_shard_id.tenant_id)
5438 0 : .await?;
5439 : let Some(ShardGenerationState {
5440 : tenant_shard_id: _,
5441 : generation: _,
5442 0 : generation_pageserver: Some(node_id),
5443 0 : }) = db_result
5444 0 : .into_iter()
5445 0 : .find(|s| s.tenant_shard_id == tenant_shard_id)
5446 : else {
5447 : // This can happen if we raced with a tenant deletion or a shard split. On a retry
5448 : // the caller will either succeed (shard split case), get a proper 404 (deletion case),
5449 : // or a conflict response (case where tenant was detached in background)
5450 0 : return Err(ApiError::ResourceUnavailable(
5451 0 : format!("Shard {tenant_shard_id} not found in database, or is not attached").into(),
5452 0 : ));
5453 : };
5454 0 : let locked = self.inner.read().unwrap();
5455 0 : let Some(node) = locked.nodes.get(&node_id) else {
5456 : // This should never happen
5457 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5458 0 : "Shard refers to nonexistent node"
5459 0 : )));
5460 : };
5461 : // As a reconciliation is in flight, we do not have the observed state yet, and therefore we assume it is always inconsistent.
5462 0 : Ok(node.clone())
5463 0 : }
5464 :
5465 0 : pub(crate) fn tenant_locate(
5466 0 : &self,
5467 0 : tenant_id: TenantId,
5468 0 : ) -> Result<TenantLocateResponse, ApiError> {
5469 0 : let locked = self.inner.read().unwrap();
5470 0 : tracing::info!("Locating shards for tenant {tenant_id}");
5471 :
5472 0 : let mut result = Vec::new();
5473 0 : let mut shard_params: Option<ShardParameters> = None;
5474 :
5475 0 : for (tenant_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id))
5476 : {
5477 0 : let node_id =
5478 0 : shard
5479 0 : .intent
5480 0 : .get_attached()
5481 0 : .ok_or(ApiError::BadRequest(anyhow::anyhow!(
5482 0 : "Cannot locate a tenant that is not attached"
5483 0 : )))?;
5484 :
5485 0 : let node = locked
5486 0 : .nodes
5487 0 : .get(&node_id)
5488 0 : .expect("Pageservers may not be deleted while referenced");
5489 :
5490 0 : result.push(node.shard_location(*tenant_shard_id));
5491 :
5492 0 : match &shard_params {
5493 0 : None => {
5494 0 : shard_params = Some(ShardParameters {
5495 0 : stripe_size: shard.shard.stripe_size,
5496 0 : count: shard.shard.count,
5497 0 : });
5498 0 : }
5499 0 : Some(params) => {
5500 0 : if params.stripe_size != shard.shard.stripe_size {
5501 : // This should never happen. We enforce at runtime because it's simpler than
5502 : // adding an extra per-tenant data structure to store the things that should be the same
5503 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5504 0 : "Inconsistent shard stripe size parameters!"
5505 0 : )));
5506 0 : }
5507 : }
5508 : }
5509 : }
5510 :
5511 0 : if result.is_empty() {
5512 0 : return Err(ApiError::NotFound(
5513 0 : anyhow::anyhow!("No shards for this tenant ID found").into(),
5514 0 : ));
5515 0 : }
5516 0 : let shard_params = shard_params.expect("result is non-empty, therefore this is set");
5517 0 : tracing::info!(
5518 0 : "Located tenant {} with params {:?} on shards {}",
5519 : tenant_id,
5520 : shard_params,
5521 0 : result
5522 0 : .iter()
5523 0 : .map(|s| format!("{s:?}"))
5524 0 : .collect::<Vec<_>>()
5525 0 : .join(",")
5526 : );
5527 :
5528 0 : Ok(TenantLocateResponse {
5529 0 : shards: result,
5530 0 : shard_params,
5531 0 : })
5532 0 : }
5533 :
5534 : /// Returns None if the input iterator of shards does not include a shard with number=0
5535 0 : fn tenant_describe_impl<'a>(
5536 0 : &self,
5537 0 : shards: impl Iterator<Item = &'a TenantShard>,
5538 0 : ) -> Option<TenantDescribeResponse> {
5539 0 : let mut shard_zero = None;
5540 0 : let mut describe_shards = Vec::new();
5541 :
5542 0 : for shard in shards {
5543 0 : if shard.tenant_shard_id.is_shard_zero() {
5544 0 : shard_zero = Some(shard);
5545 0 : }
5546 :
5547 0 : describe_shards.push(TenantDescribeResponseShard {
5548 0 : tenant_shard_id: shard.tenant_shard_id,
5549 0 : node_attached: *shard.intent.get_attached(),
5550 0 : node_secondary: shard.intent.get_secondary().to_vec(),
5551 0 : last_error: shard
5552 0 : .last_error
5553 0 : .lock()
5554 0 : .unwrap()
5555 0 : .as_ref()
5556 0 : .map(|e| format!("{e}"))
5557 0 : .unwrap_or("".to_string())
5558 0 : .clone(),
5559 0 : is_reconciling: shard.reconciler.is_some(),
5560 0 : is_pending_compute_notification: shard.pending_compute_notification,
5561 0 : is_splitting: matches!(shard.splitting, SplitState::Splitting),
5562 0 : is_importing: shard.importing == TimelineImportState::Importing,
5563 0 : scheduling_policy: shard.get_scheduling_policy(),
5564 0 : preferred_az_id: shard.preferred_az().map(ToString::to_string),
5565 : })
5566 : }
5567 :
5568 0 : let shard_zero = shard_zero?;
5569 :
5570 0 : Some(TenantDescribeResponse {
5571 0 : tenant_id: shard_zero.tenant_shard_id.tenant_id,
5572 0 : shards: describe_shards,
5573 0 : stripe_size: shard_zero.shard.stripe_size,
5574 0 : policy: shard_zero.policy.clone(),
5575 0 : config: shard_zero.config.clone(),
5576 0 : })
5577 0 : }
5578 :
5579 0 : pub(crate) fn tenant_describe(
5580 0 : &self,
5581 0 : tenant_id: TenantId,
5582 0 : ) -> Result<TenantDescribeResponse, ApiError> {
5583 0 : let locked = self.inner.read().unwrap();
5584 :
5585 0 : self.tenant_describe_impl(
5586 0 : locked
5587 0 : .tenants
5588 0 : .range(TenantShardId::tenant_range(tenant_id))
5589 0 : .map(|(_k, v)| v),
5590 : )
5591 0 : .ok_or_else(|| ApiError::NotFound(anyhow::anyhow!("Tenant {tenant_id} not found").into()))
5592 0 : }
5593 :
5594 : /* BEGIN_HADRON */
5595 0 : pub(crate) async fn tenant_timeline_describe(
5596 0 : &self,
5597 0 : tenant_id: TenantId,
5598 0 : timeline_id: TimelineId,
5599 0 : ) -> Result<TenantTimelineDescribeResponse, ApiError> {
5600 0 : self.tenant_remote_mutation(tenant_id, |locations| async move {
5601 0 : if locations.0.is_empty() {
5602 0 : return Err(ApiError::NotFound(
5603 0 : anyhow::anyhow!("Tenant not found").into(),
5604 0 : ));
5605 0 : };
5606 :
5607 0 : let locations: Vec<(TenantShardId, Node)> = locations
5608 0 : .0
5609 0 : .iter()
5610 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
5611 0 : .collect();
5612 0 : let mut futs = FuturesUnordered::new();
5613 :
5614 0 : for (shard_id, node) in locations {
5615 0 : futs.push({
5616 0 : async move {
5617 0 : let result = node
5618 0 : .with_client_retries(
5619 0 : |client| async move {
5620 0 : client
5621 0 : .tenant_timeline_describe(&shard_id, &timeline_id)
5622 0 : .await
5623 0 : },
5624 0 : &self.http_client,
5625 0 : &self.config.pageserver_jwt_token,
5626 : 3,
5627 : 3,
5628 0 : Duration::from_secs(30),
5629 0 : &self.cancel,
5630 : )
5631 0 : .await;
5632 0 : (result, shard_id, node.get_id())
5633 0 : }
5634 : });
5635 : }
5636 :
5637 0 : let mut results: Vec<TimelineInfo> = Vec::new();
5638 0 : while let Some((result, tenant_shard_id, node_id)) = futs.next().await {
5639 0 : match result {
5640 0 : Some(Ok(timeline_info)) => results.push(timeline_info),
5641 0 : Some(Err(e)) => {
5642 0 : tracing::warn!(
5643 0 : "Failed to describe tenant {} timeline {} for pageserver {}: {e}",
5644 : tenant_shard_id,
5645 : timeline_id,
5646 : node_id,
5647 : );
5648 0 : return Err(ApiError::ResourceUnavailable(format!("{e}").into()));
5649 : }
5650 0 : None => return Err(ApiError::Cancelled),
5651 : }
5652 : }
5653 0 : let mut image_consistent_lsn: Option<Lsn> = Some(Lsn::MAX);
5654 0 : for timeline_info in &results {
5655 0 : if let Some(tline_image_consistent_lsn) = timeline_info.image_consistent_lsn {
5656 0 : image_consistent_lsn = Some(std::cmp::min(
5657 0 : image_consistent_lsn.unwrap(),
5658 0 : tline_image_consistent_lsn,
5659 0 : ));
5660 0 : } else {
5661 0 : tracing::warn!(
5662 0 : "Timeline {} on shard {} does not have image consistent lsn",
5663 : timeline_info.timeline_id,
5664 : timeline_info.tenant_id
5665 : );
5666 0 : image_consistent_lsn = None;
5667 0 : break;
5668 : }
5669 : }
5670 :
5671 0 : Ok(TenantTimelineDescribeResponse {
5672 0 : shards: results,
5673 0 : image_consistent_lsn,
5674 0 : })
5675 0 : })
5676 0 : .await?
5677 0 : }
5678 : /* END_HADRON */
5679 :
5680 : /// limit & offset are pagination parameters. Since we are walking an in-memory HashMap, `offset` does not
5681 : /// avoid traversing data, it just avoid returning it. This is suitable for our purposes, since our in memory
5682 : /// maps are small enough to traverse fast, our pagination is just to avoid serializing huge JSON responses
5683 : /// in our external API.
5684 0 : pub(crate) fn tenant_list(
5685 0 : &self,
5686 0 : limit: Option<usize>,
5687 0 : start_after: Option<TenantId>,
5688 0 : ) -> Vec<TenantDescribeResponse> {
5689 0 : let locked = self.inner.read().unwrap();
5690 :
5691 : // Apply start_from parameter
5692 0 : let shard_range = match start_after {
5693 0 : None => locked.tenants.range(..),
5694 0 : Some(tenant_id) => locked.tenants.range(
5695 0 : TenantShardId {
5696 0 : tenant_id,
5697 0 : shard_number: ShardNumber(u8::MAX),
5698 0 : shard_count: ShardCount(u8::MAX),
5699 0 : }..,
5700 : ),
5701 : };
5702 :
5703 0 : let mut result = Vec::new();
5704 0 : for (_tenant_id, tenant_shards) in &shard_range.group_by(|(id, _shard)| id.tenant_id) {
5705 0 : result.push(
5706 0 : self.tenant_describe_impl(tenant_shards.map(|(_k, v)| v))
5707 0 : .expect("Groups are always non-empty"),
5708 : );
5709 :
5710 : // Enforce `limit` parameter
5711 0 : if let Some(limit) = limit {
5712 0 : if result.len() >= limit {
5713 0 : break;
5714 0 : }
5715 0 : }
5716 : }
5717 :
5718 0 : result
5719 0 : }
5720 :
5721 : #[instrument(skip_all, fields(tenant_id=%op.tenant_id))]
5722 : async fn abort_tenant_shard_split(
5723 : &self,
5724 : op: &TenantShardSplitAbort,
5725 : ) -> Result<(), TenantShardSplitAbortError> {
5726 : // Cleaning up a split:
5727 : // - Parent shards are not destroyed during a split, just detached.
5728 : // - Failed pageserver split API calls can leave the remote node with just the parent attached,
5729 : // just the children attached, or both.
5730 : //
5731 : // Therefore our work to do is to:
5732 : // 1. Clean up storage controller's internal state to just refer to parents, no children
5733 : // 2. Call out to pageservers to ensure that children are detached
5734 : // 3. Call out to pageservers to ensure that parents are attached.
5735 : //
5736 : // Crash safety:
5737 : // - If the storage controller stops running during this cleanup *after* clearing the splitting state
5738 : // from our database, then [`Self::startup_reconcile`] will regard child attachments as garbage
5739 : // and detach them.
5740 : // - TODO: If the storage controller stops running during this cleanup *before* clearing the splitting state
5741 : // from our database, then we will re-enter this cleanup routine on startup.
5742 :
5743 : let TenantShardSplitAbort {
5744 : tenant_id,
5745 : new_shard_count,
5746 : new_stripe_size,
5747 : ..
5748 : } = op;
5749 :
5750 : // First abort persistent state, if any exists.
5751 : match self
5752 : .persistence
5753 : .abort_shard_split(*tenant_id, *new_shard_count)
5754 : .await?
5755 : {
5756 : AbortShardSplitStatus::Aborted => {
5757 : // Proceed to roll back any child shards created on pageservers
5758 : }
5759 : AbortShardSplitStatus::Complete => {
5760 : // The split completed (we might hit that path if e.g. our database transaction
5761 : // to write the completion landed in the database, but we dropped connection
5762 : // before seeing the result).
5763 : //
5764 : // We must update in-memory state to reflect the successful split.
5765 : self.tenant_shard_split_commit_inmem(
5766 : *tenant_id,
5767 : *new_shard_count,
5768 : *new_stripe_size,
5769 : );
5770 : return Ok(());
5771 : }
5772 : }
5773 :
5774 : // Clean up in-memory state, and accumulate the list of child locations that need detaching
5775 : let detach_locations: Vec<(Node, TenantShardId)> = {
5776 : let mut detach_locations = Vec::new();
5777 : let mut locked = self.inner.write().unwrap();
5778 : let (nodes, tenants, scheduler) = locked.parts_mut();
5779 :
5780 : for (tenant_shard_id, shard) in
5781 : tenants.range_mut(TenantShardId::tenant_range(op.tenant_id))
5782 : {
5783 : if shard.shard.count == op.new_shard_count {
5784 : // Surprising: the phase of [`Self::do_tenant_shard_split`] which inserts child shards in-memory
5785 : // is infallible, so if we got an error we shouldn't have got that far.
5786 : tracing::warn!(
5787 : "During split abort, child shard {tenant_shard_id} found in-memory"
5788 : );
5789 : continue;
5790 : }
5791 :
5792 : // Add the children of this shard to this list of things to detach
5793 : if let Some(node_id) = shard.intent.get_attached() {
5794 : for child_id in tenant_shard_id.split(*new_shard_count) {
5795 : detach_locations.push((
5796 : nodes
5797 : .get(node_id)
5798 : .expect("Intent references nonexistent node")
5799 : .clone(),
5800 : child_id,
5801 : ));
5802 : }
5803 : } else {
5804 : tracing::warn!(
5805 : "During split abort, shard {tenant_shard_id} has no attached location"
5806 : );
5807 : }
5808 :
5809 : tracing::info!("Restoring parent shard {tenant_shard_id}");
5810 :
5811 : // Drop any intents that refer to unavailable nodes, to enable this abort to proceed even
5812 : // if the original attachment location is offline.
5813 : if let Some(node_id) = shard.intent.get_attached() {
5814 : if !nodes.get(node_id).unwrap().is_available() {
5815 : tracing::info!(
5816 : "Demoting attached intent for {tenant_shard_id} on unavailable node {node_id}"
5817 : );
5818 : shard.intent.demote_attached(scheduler, *node_id);
5819 : }
5820 : }
5821 : for node_id in shard.intent.get_secondary().clone() {
5822 : if !nodes.get(&node_id).unwrap().is_available() {
5823 : tracing::info!(
5824 : "Dropping secondary intent for {tenant_shard_id} on unavailable node {node_id}"
5825 : );
5826 : shard.intent.remove_secondary(scheduler, node_id);
5827 : }
5828 : }
5829 :
5830 : shard.splitting = SplitState::Idle;
5831 : if let Err(e) = shard.schedule(scheduler, &mut ScheduleContext::default()) {
5832 : // If this shard can't be scheduled now (perhaps due to offline nodes or
5833 : // capacity issues), that must not prevent us rolling back a split. In this
5834 : // case it should be eventually scheduled in the background.
5835 : tracing::warn!("Failed to schedule {tenant_shard_id} during shard abort: {e}")
5836 : }
5837 :
5838 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
5839 : }
5840 :
5841 : // We don't expect any new_shard_count shards to exist here, but drop them just in case
5842 : tenants
5843 0 : .retain(|id, s| !(id.tenant_id == *tenant_id && s.shard.count == *new_shard_count));
5844 :
5845 : detach_locations
5846 : };
5847 :
5848 : for (node, child_id) in detach_locations {
5849 : if !node.is_available() {
5850 : // An unavailable node cannot be cleaned up now: to avoid blocking forever, we will permit this, and
5851 : // rely on the reconciliation that happens when a node transitions to Active to clean up. Since we have
5852 : // removed child shards from our in-memory state and database, the reconciliation will implicitly remove
5853 : // them from the node.
5854 : tracing::warn!(
5855 : "Node {node} unavailable, can't clean up during split abort. It will be cleaned up when it is reactivated."
5856 : );
5857 : continue;
5858 : }
5859 :
5860 : // Detach the remote child. If the pageserver split API call is still in progress, this call will get
5861 : // a 503 and retry, up to our limit.
5862 : tracing::info!("Detaching {child_id} on {node}...");
5863 : match node
5864 : .with_client_retries(
5865 0 : |client| async move {
5866 0 : let config = LocationConfig {
5867 0 : mode: LocationConfigMode::Detached,
5868 0 : generation: None,
5869 0 : secondary_conf: None,
5870 0 : shard_number: child_id.shard_number.0,
5871 0 : shard_count: child_id.shard_count.literal(),
5872 0 : // Stripe size and tenant config don't matter when detaching
5873 0 : shard_stripe_size: 0,
5874 0 : tenant_conf: TenantConfig::default(),
5875 0 : };
5876 :
5877 0 : client.location_config(child_id, config, None, false).await
5878 0 : },
5879 : &self.http_client,
5880 : &self.config.pageserver_jwt_token,
5881 : 1,
5882 : 10,
5883 : Duration::from_secs(5),
5884 : &self.reconcilers_cancel,
5885 : )
5886 : .await
5887 : {
5888 : Some(Ok(_)) => {}
5889 : Some(Err(e)) => {
5890 : // We failed to communicate with the remote node. This is problematic: we may be
5891 : // leaving it with a rogue child shard.
5892 : tracing::warn!(
5893 : "Failed to detach child {child_id} from node {node} during abort"
5894 : );
5895 : return Err(e.into());
5896 : }
5897 : None => {
5898 : // Cancellation: we were shutdown or the node went offline. Shutdown is fine, we'll
5899 : // clean up on restart. The node going offline requires a retry.
5900 : return Err(TenantShardSplitAbortError::Unavailable);
5901 : }
5902 : };
5903 : }
5904 :
5905 : tracing::info!("Successfully aborted split");
5906 : Ok(())
5907 : }
5908 :
5909 : /// Infallible final stage of [`Self::tenant_shard_split`]: update the contents
5910 : /// of the tenant map to reflect the child shards that exist after the split.
5911 0 : fn tenant_shard_split_commit_inmem(
5912 0 : &self,
5913 0 : tenant_id: TenantId,
5914 0 : new_shard_count: ShardCount,
5915 0 : new_stripe_size: Option<ShardStripeSize>,
5916 0 : ) -> (
5917 0 : TenantShardSplitResponse,
5918 0 : Vec<(TenantShardId, NodeId, ShardStripeSize)>,
5919 0 : Vec<ReconcilerWaiter>,
5920 0 : ) {
5921 0 : let mut response = TenantShardSplitResponse {
5922 0 : new_shards: Vec::new(),
5923 0 : };
5924 0 : let mut child_locations = Vec::new();
5925 0 : let mut waiters = Vec::new();
5926 :
5927 : {
5928 0 : let mut locked = self.inner.write().unwrap();
5929 :
5930 0 : let parent_ids = locked
5931 0 : .tenants
5932 0 : .range(TenantShardId::tenant_range(tenant_id))
5933 0 : .map(|(shard_id, _)| *shard_id)
5934 0 : .collect::<Vec<_>>();
5935 :
5936 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
5937 0 : for parent_id in parent_ids {
5938 0 : let child_ids = parent_id.split(new_shard_count);
5939 :
5940 : let (
5941 0 : pageserver,
5942 0 : generation,
5943 0 : policy,
5944 0 : parent_ident,
5945 0 : config,
5946 0 : preferred_az,
5947 0 : secondary_count,
5948 : ) = {
5949 0 : let mut old_state = tenants
5950 0 : .remove(&parent_id)
5951 0 : .expect("It was present, we just split it");
5952 :
5953 : // A non-splitting state is impossible, because [`Self::tenant_shard_split`] holds
5954 : // a TenantId lock and passes it through to [`TenantShardSplitAbort`] in case of cleanup:
5955 : // nothing else can clear this.
5956 0 : assert!(matches!(old_state.splitting, SplitState::Splitting));
5957 :
5958 0 : let old_attached = old_state.intent.get_attached().unwrap();
5959 0 : old_state.intent.clear(scheduler);
5960 0 : let generation = old_state.generation.expect("Shard must have been attached");
5961 0 : (
5962 0 : old_attached,
5963 0 : generation,
5964 0 : old_state.policy.clone(),
5965 0 : old_state.shard,
5966 0 : old_state.config.clone(),
5967 0 : old_state.preferred_az().cloned(),
5968 0 : old_state.intent.get_secondary().len(),
5969 0 : )
5970 : };
5971 :
5972 0 : let mut schedule_context = ScheduleContext::default();
5973 0 : for child in child_ids {
5974 0 : let mut child_shard = parent_ident;
5975 0 : child_shard.number = child.shard_number;
5976 0 : child_shard.count = child.shard_count;
5977 0 : if let Some(stripe_size) = new_stripe_size {
5978 0 : child_shard.stripe_size = stripe_size;
5979 0 : }
5980 :
5981 0 : let mut child_observed: HashMap<NodeId, ObservedStateLocation> = HashMap::new();
5982 0 : child_observed.insert(
5983 0 : pageserver,
5984 0 : ObservedStateLocation {
5985 0 : conf: Some(attached_location_conf(
5986 0 : generation,
5987 0 : &child_shard,
5988 0 : &config,
5989 0 : &policy,
5990 0 : secondary_count,
5991 0 : )),
5992 0 : },
5993 : );
5994 :
5995 0 : let mut child_state =
5996 0 : TenantShard::new(child, child_shard, policy.clone(), preferred_az.clone());
5997 0 : child_state.intent =
5998 0 : IntentState::single(scheduler, Some(pageserver), preferred_az.clone());
5999 0 : child_state.observed = ObservedState {
6000 0 : locations: child_observed,
6001 0 : };
6002 0 : child_state.generation = Some(generation);
6003 0 : child_state.config = config.clone();
6004 :
6005 : // The child's TenantShard::splitting is intentionally left at the default value of Idle,
6006 : // as at this point in the split process we have succeeded and this part is infallible:
6007 : // we will never need to do any special recovery from this state.
6008 :
6009 0 : child_locations.push((child, pageserver, child_shard.stripe_size));
6010 :
6011 0 : if let Err(e) = child_state.schedule(scheduler, &mut schedule_context) {
6012 : // This is not fatal, because we've implicitly already got an attached
6013 : // location for the child shard. Failure here just means we couldn't
6014 : // find a secondary (e.g. because cluster is overloaded).
6015 0 : tracing::warn!("Failed to schedule child shard {child}: {e}");
6016 0 : }
6017 : // In the background, attach secondary locations for the new shards
6018 0 : if let Some(waiter) = self.maybe_reconcile_shard(
6019 0 : &mut child_state,
6020 0 : nodes,
6021 0 : ReconcilerPriority::High,
6022 0 : ) {
6023 0 : waiters.push(waiter);
6024 0 : }
6025 :
6026 0 : tenants.insert(child, child_state);
6027 0 : response.new_shards.push(child);
6028 : }
6029 : }
6030 0 : (response, child_locations, waiters)
6031 : }
6032 0 : }
6033 :
6034 0 : async fn tenant_shard_split_start_secondaries(
6035 0 : &self,
6036 0 : tenant_id: TenantId,
6037 0 : waiters: Vec<ReconcilerWaiter>,
6038 0 : ) {
6039 : // Wait for initial reconcile of child shards, this creates the secondary locations
6040 0 : if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
6041 : // This is not a failure to split: it's some issue reconciling the new child shards, perhaps
6042 : // their secondaries couldn't be attached.
6043 0 : tracing::warn!("Failed to reconcile after split: {e}");
6044 0 : return;
6045 0 : }
6046 :
6047 : // Take the state lock to discover the attached & secondary intents for all shards
6048 0 : let (attached, secondary) = {
6049 0 : let locked = self.inner.read().unwrap();
6050 0 : let mut attached = Vec::new();
6051 0 : let mut secondary = Vec::new();
6052 :
6053 0 : for (tenant_shard_id, shard) in
6054 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
6055 : {
6056 0 : let Some(node_id) = shard.intent.get_attached() else {
6057 : // Unexpected. Race with a PlacementPolicy change?
6058 0 : tracing::warn!(
6059 0 : "No attached node on {tenant_shard_id} immediately after shard split!"
6060 : );
6061 0 : continue;
6062 : };
6063 :
6064 0 : let Some(secondary_node_id) = shard.intent.get_secondary().first() else {
6065 : // No secondary location. Nothing for us to do.
6066 0 : continue;
6067 : };
6068 :
6069 0 : let attached_node = locked
6070 0 : .nodes
6071 0 : .get(node_id)
6072 0 : .expect("Pageservers may not be deleted while referenced");
6073 :
6074 0 : let secondary_node = locked
6075 0 : .nodes
6076 0 : .get(secondary_node_id)
6077 0 : .expect("Pageservers may not be deleted while referenced");
6078 :
6079 0 : attached.push((*tenant_shard_id, attached_node.clone()));
6080 0 : secondary.push((*tenant_shard_id, secondary_node.clone()));
6081 : }
6082 0 : (attached, secondary)
6083 : };
6084 :
6085 0 : if secondary.is_empty() {
6086 : // No secondary locations; nothing for us to do
6087 0 : return;
6088 0 : }
6089 :
6090 0 : for (_, result) in self
6091 0 : .tenant_for_shards_api(
6092 0 : attached,
6093 0 : |tenant_shard_id, client| async move {
6094 0 : client.tenant_heatmap_upload(tenant_shard_id).await
6095 0 : },
6096 : 1,
6097 : 1,
6098 : SHORT_RECONCILE_TIMEOUT,
6099 0 : &self.cancel,
6100 : )
6101 0 : .await
6102 : {
6103 0 : if let Err(e) = result {
6104 0 : tracing::warn!("Error calling heatmap upload after shard split: {e}");
6105 0 : return;
6106 0 : }
6107 : }
6108 :
6109 0 : for (_, result) in self
6110 0 : .tenant_for_shards_api(
6111 0 : secondary,
6112 0 : |tenant_shard_id, client| async move {
6113 0 : client
6114 0 : .tenant_secondary_download(tenant_shard_id, Some(Duration::ZERO))
6115 0 : .await
6116 0 : },
6117 : 1,
6118 : 1,
6119 : SHORT_RECONCILE_TIMEOUT,
6120 0 : &self.cancel,
6121 : )
6122 0 : .await
6123 : {
6124 0 : if let Err(e) = result {
6125 0 : tracing::warn!("Error calling secondary download after shard split: {e}");
6126 0 : return;
6127 0 : }
6128 : }
6129 0 : }
6130 :
6131 0 : pub(crate) async fn tenant_shard_split(
6132 0 : &self,
6133 0 : tenant_id: TenantId,
6134 0 : split_req: TenantShardSplitRequest,
6135 0 : ) -> Result<TenantShardSplitResponse, ApiError> {
6136 : // TODO: return 503 if we get stuck waiting for this lock
6137 : // (issue https://github.com/neondatabase/neon/issues/7108)
6138 0 : let _tenant_lock = trace_exclusive_lock(
6139 0 : &self.tenant_op_locks,
6140 0 : tenant_id,
6141 0 : TenantOperations::ShardSplit,
6142 0 : )
6143 0 : .await;
6144 :
6145 0 : let _gate = self
6146 0 : .reconcilers_gate
6147 0 : .enter()
6148 0 : .map_err(|_| ApiError::ShuttingDown)?;
6149 :
6150 : // Timeline imports on the pageserver side can't handle shard-splits.
6151 : // If the tenant is importing a timeline, dont't shard split it.
6152 0 : match self
6153 0 : .persistence
6154 0 : .is_tenant_importing_timeline(tenant_id)
6155 0 : .await
6156 : {
6157 0 : Ok(importing) => {
6158 0 : if importing {
6159 0 : return Err(ApiError::Conflict(
6160 0 : "Cannot shard split during timeline import".to_string(),
6161 0 : ));
6162 0 : }
6163 : }
6164 0 : Err(err) => {
6165 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
6166 0 : "Failed to check for running imports: {err}"
6167 0 : )));
6168 : }
6169 : }
6170 :
6171 0 : let new_shard_count = ShardCount::new(split_req.new_shard_count);
6172 0 : let new_stripe_size = split_req.new_stripe_size;
6173 :
6174 : // Validate the request and construct parameters. This phase is fallible, but does not require
6175 : // rollback on errors, as it does no I/O and mutates no state.
6176 0 : let shard_split_params = match self.prepare_tenant_shard_split(tenant_id, split_req)? {
6177 0 : ShardSplitAction::NoOp(resp) => return Ok(resp),
6178 0 : ShardSplitAction::Split(params) => params,
6179 : };
6180 :
6181 : // Execute this split: this phase mutates state and does remote I/O on pageservers. If it fails,
6182 : // we must roll back.
6183 0 : let r = self
6184 0 : .do_tenant_shard_split(tenant_id, shard_split_params)
6185 0 : .await;
6186 :
6187 0 : let (response, waiters) = match r {
6188 0 : Ok(r) => r,
6189 0 : Err(e) => {
6190 : // Split might be part-done, we must do work to abort it.
6191 0 : tracing::warn!("Enqueuing background abort of split on {tenant_id}");
6192 0 : self.abort_tx
6193 0 : .send(TenantShardSplitAbort {
6194 0 : tenant_id,
6195 0 : new_shard_count,
6196 0 : new_stripe_size,
6197 0 : _tenant_lock,
6198 0 : _gate,
6199 0 : })
6200 : // Ignore error sending: that just means we're shutting down: aborts are ephemeral so it's fine to drop it.
6201 0 : .ok();
6202 0 : return Err(e);
6203 : }
6204 : };
6205 :
6206 : // The split is now complete. As an optimization, we will trigger all the child shards to upload
6207 : // a heatmap immediately, and all their secondary locations to start downloading: this avoids waiting
6208 : // for the background heatmap/download interval before secondaries get warm enough to migrate shards
6209 : // in [`Self::optimize_all`]
6210 0 : self.tenant_shard_split_start_secondaries(tenant_id, waiters)
6211 0 : .await;
6212 0 : Ok(response)
6213 0 : }
6214 :
6215 0 : fn prepare_tenant_shard_split(
6216 0 : &self,
6217 0 : tenant_id: TenantId,
6218 0 : split_req: TenantShardSplitRequest,
6219 0 : ) -> Result<ShardSplitAction, ApiError> {
6220 0 : fail::fail_point!("shard-split-validation", |_| Err(ApiError::BadRequest(
6221 0 : anyhow::anyhow!("failpoint")
6222 0 : )));
6223 :
6224 0 : let mut policy = None;
6225 0 : let mut config = None;
6226 0 : let mut shard_ident = None;
6227 0 : let mut preferred_az_id = None;
6228 : // Validate input, and calculate which shards we will create
6229 0 : let (old_shard_count, targets) =
6230 : {
6231 0 : let locked = self.inner.read().unwrap();
6232 :
6233 0 : let pageservers = locked.nodes.clone();
6234 :
6235 0 : let mut targets = Vec::new();
6236 :
6237 : // In case this is a retry, count how many already-split shards we found
6238 0 : let mut children_found = Vec::new();
6239 0 : let mut old_shard_count = None;
6240 :
6241 0 : for (tenant_shard_id, shard) in
6242 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
6243 : {
6244 0 : match shard.shard.count.count().cmp(&split_req.new_shard_count) {
6245 : Ordering::Equal => {
6246 : // Already split this
6247 0 : children_found.push(*tenant_shard_id);
6248 0 : continue;
6249 : }
6250 : Ordering::Greater => {
6251 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6252 0 : "Requested count {} but already have shards at count {}",
6253 0 : split_req.new_shard_count,
6254 0 : shard.shard.count.count()
6255 0 : )));
6256 : }
6257 0 : Ordering::Less => {
6258 0 : // Fall through: this shard has lower count than requested,
6259 0 : // is a candidate for splitting.
6260 0 : }
6261 : }
6262 :
6263 0 : match old_shard_count {
6264 0 : None => old_shard_count = Some(shard.shard.count),
6265 0 : Some(old_shard_count) => {
6266 0 : if old_shard_count != shard.shard.count {
6267 : // We may hit this case if a caller asked for two splits to
6268 : // different sizes, before the first one is complete.
6269 : // e.g. 1->2, 2->4, where the 4 call comes while we have a mixture
6270 : // of shard_count=1 and shard_count=2 shards in the map.
6271 0 : return Err(ApiError::Conflict(
6272 0 : "Cannot split, currently mid-split".to_string(),
6273 0 : ));
6274 0 : }
6275 : }
6276 : }
6277 0 : if policy.is_none() {
6278 0 : policy = Some(shard.policy.clone());
6279 0 : }
6280 0 : if shard_ident.is_none() {
6281 0 : shard_ident = Some(shard.shard);
6282 0 : }
6283 0 : if config.is_none() {
6284 0 : config = Some(shard.config.clone());
6285 0 : }
6286 0 : if preferred_az_id.is_none() {
6287 0 : preferred_az_id = shard.preferred_az().cloned();
6288 0 : }
6289 :
6290 0 : if tenant_shard_id.shard_count.count() == split_req.new_shard_count {
6291 0 : tracing::info!(
6292 0 : "Tenant shard {} already has shard count {}",
6293 : tenant_shard_id,
6294 : split_req.new_shard_count
6295 : );
6296 0 : continue;
6297 0 : }
6298 :
6299 0 : let node_id = shard.intent.get_attached().ok_or(ApiError::BadRequest(
6300 0 : anyhow::anyhow!("Cannot split a tenant that is not attached"),
6301 0 : ))?;
6302 :
6303 0 : let node = pageservers
6304 0 : .get(&node_id)
6305 0 : .expect("Pageservers may not be deleted while referenced");
6306 :
6307 0 : targets.push(ShardSplitTarget {
6308 0 : parent_id: *tenant_shard_id,
6309 0 : node: node.clone(),
6310 0 : child_ids: tenant_shard_id
6311 0 : .split(ShardCount::new(split_req.new_shard_count)),
6312 0 : });
6313 : }
6314 :
6315 0 : if targets.is_empty() {
6316 0 : if children_found.len() == split_req.new_shard_count as usize {
6317 0 : return Ok(ShardSplitAction::NoOp(TenantShardSplitResponse {
6318 0 : new_shards: children_found,
6319 0 : }));
6320 : } else {
6321 : // No shards found to split, and no existing children found: the
6322 : // tenant doesn't exist at all.
6323 0 : return Err(ApiError::NotFound(
6324 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
6325 0 : ));
6326 : }
6327 0 : }
6328 :
6329 0 : (old_shard_count, targets)
6330 : };
6331 :
6332 : // unwrap safety: we would have returned above if we didn't find at least one shard to split
6333 0 : let old_shard_count = old_shard_count.unwrap();
6334 0 : let shard_ident = if let Some(new_stripe_size) = split_req.new_stripe_size {
6335 : // This ShardIdentity will be used as the template for all children, so this implicitly
6336 : // applies the new stripe size to the children.
6337 0 : let mut shard_ident = shard_ident.unwrap();
6338 0 : if shard_ident.count.count() > 1 && shard_ident.stripe_size != new_stripe_size {
6339 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6340 0 : "Attempted to change stripe size ({:?}->{new_stripe_size:?}) on a tenant with multiple shards",
6341 0 : shard_ident.stripe_size
6342 0 : )));
6343 0 : }
6344 :
6345 0 : shard_ident.stripe_size = new_stripe_size;
6346 0 : tracing::info!("applied stripe size {}", shard_ident.stripe_size.0);
6347 0 : shard_ident
6348 : } else {
6349 0 : shard_ident.unwrap()
6350 : };
6351 0 : let policy = policy.unwrap();
6352 0 : let config = config.unwrap();
6353 :
6354 0 : Ok(ShardSplitAction::Split(Box::new(ShardSplitParams {
6355 0 : old_shard_count,
6356 0 : new_shard_count: ShardCount::new(split_req.new_shard_count),
6357 0 : new_stripe_size: split_req.new_stripe_size,
6358 0 : targets,
6359 0 : policy,
6360 0 : config,
6361 0 : shard_ident,
6362 0 : preferred_az_id,
6363 0 : })))
6364 0 : }
6365 :
6366 0 : async fn do_tenant_shard_split(
6367 0 : &self,
6368 0 : tenant_id: TenantId,
6369 0 : params: Box<ShardSplitParams>,
6370 0 : ) -> Result<(TenantShardSplitResponse, Vec<ReconcilerWaiter>), ApiError> {
6371 : // FIXME: we have dropped self.inner lock, and not yet written anything to the database: another
6372 : // request could occur here, deleting or mutating the tenant. begin_shard_split checks that the
6373 : // parent shards exist as expected, but it would be neater to do the above pre-checks within the
6374 : // same database transaction rather than pre-check in-memory and then maybe-fail the database write.
6375 : // (https://github.com/neondatabase/neon/issues/6676)
6376 :
6377 : let ShardSplitParams {
6378 0 : old_shard_count,
6379 0 : new_shard_count,
6380 0 : new_stripe_size,
6381 0 : mut targets,
6382 0 : policy,
6383 0 : config,
6384 0 : shard_ident,
6385 0 : preferred_az_id,
6386 0 : } = *params;
6387 :
6388 : // Drop any secondary locations: pageservers do not support splitting these, and in any case the
6389 : // end-state for a split tenant will usually be to have secondary locations on different nodes.
6390 : // The reconciliation calls in this block also implicitly cancel+barrier wrt any ongoing reconciliation
6391 : // at the time of split.
6392 0 : let waiters = {
6393 0 : let mut locked = self.inner.write().unwrap();
6394 0 : let mut waiters = Vec::new();
6395 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6396 0 : for target in &mut targets {
6397 0 : let Some(shard) = tenants.get_mut(&target.parent_id) else {
6398 : // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
6399 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
6400 0 : "Shard {} not found",
6401 0 : target.parent_id
6402 0 : )));
6403 : };
6404 :
6405 0 : if shard.intent.get_attached() != &Some(target.node.get_id()) {
6406 : // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
6407 0 : return Err(ApiError::Conflict(format!(
6408 0 : "Shard {} unexpectedly rescheduled during split",
6409 0 : target.parent_id
6410 0 : )));
6411 0 : }
6412 :
6413 : // Irrespective of PlacementPolicy, clear secondary locations from intent
6414 0 : shard.intent.clear_secondary(scheduler);
6415 :
6416 : // Run Reconciler to execute detach fo secondary locations.
6417 0 : if let Some(waiter) =
6418 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
6419 0 : {
6420 0 : waiters.push(waiter);
6421 0 : }
6422 : }
6423 0 : waiters
6424 : };
6425 0 : self.await_waiters(waiters, RECONCILE_TIMEOUT).await?;
6426 :
6427 : // Before creating any new child shards in memory or on the pageservers, persist them: this
6428 : // enables us to ensure that we will always be able to clean up if something goes wrong. This also
6429 : // acts as the protection against two concurrent attempts to split: one of them will get a database
6430 : // error trying to insert the child shards.
6431 0 : let mut child_tsps = Vec::new();
6432 0 : for target in &targets {
6433 0 : let mut this_child_tsps = Vec::new();
6434 0 : for child in &target.child_ids {
6435 0 : let mut child_shard = shard_ident;
6436 0 : child_shard.number = child.shard_number;
6437 0 : child_shard.count = child.shard_count;
6438 :
6439 0 : tracing::info!(
6440 0 : "Create child shard persistence with stripe size {}",
6441 : shard_ident.stripe_size.0
6442 : );
6443 :
6444 0 : this_child_tsps.push(TenantShardPersistence {
6445 0 : tenant_id: child.tenant_id.to_string(),
6446 0 : shard_number: child.shard_number.0 as i32,
6447 0 : shard_count: child.shard_count.literal() as i32,
6448 0 : shard_stripe_size: shard_ident.stripe_size.0 as i32,
6449 : // Note: this generation is a placeholder, [`Persistence::begin_shard_split`] will
6450 : // populate the correct generation as part of its transaction, to protect us
6451 : // against racing with changes in the state of the parent.
6452 0 : generation: None,
6453 0 : generation_pageserver: Some(target.node.get_id().0 as i64),
6454 0 : placement_policy: serde_json::to_string(&policy).unwrap(),
6455 0 : config: serde_json::to_string(&config).unwrap(),
6456 0 : splitting: SplitState::Splitting,
6457 :
6458 : // Scheduling policies and preferred AZ do not carry through to children
6459 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
6460 0 : .unwrap(),
6461 0 : preferred_az_id: preferred_az_id.as_ref().map(|az| az.0.clone()),
6462 : });
6463 : }
6464 :
6465 0 : child_tsps.push((target.parent_id, this_child_tsps));
6466 : }
6467 :
6468 0 : if let Err(e) = self
6469 0 : .persistence
6470 0 : .begin_shard_split(old_shard_count, tenant_id, child_tsps)
6471 0 : .await
6472 : {
6473 0 : match e {
6474 : DatabaseError::Query(diesel::result::Error::DatabaseError(
6475 : DatabaseErrorKind::UniqueViolation,
6476 : _,
6477 : )) => {
6478 : // Inserting a child shard violated a unique constraint: we raced with another call to
6479 : // this function
6480 0 : tracing::warn!("Conflicting attempt to split {tenant_id}: {e}");
6481 0 : return Err(ApiError::Conflict("Tenant is already splitting".into()));
6482 : }
6483 0 : _ => return Err(ApiError::InternalServerError(e.into())),
6484 : }
6485 0 : }
6486 0 : fail::fail_point!("shard-split-post-begin", |_| Err(
6487 0 : ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
6488 : ));
6489 :
6490 : // Now that I have persisted the splitting state, apply it in-memory. This is infallible, so
6491 : // callers may assume that if splitting is set in memory, then it was persisted, and if splitting
6492 : // is not set in memory, then it was not persisted.
6493 : {
6494 0 : let mut locked = self.inner.write().unwrap();
6495 0 : for target in &targets {
6496 0 : if let Some(parent_shard) = locked.tenants.get_mut(&target.parent_id) {
6497 0 : parent_shard.splitting = SplitState::Splitting;
6498 0 : // Put the observed state to None, to reflect that it is indeterminate once we start the
6499 0 : // split operation.
6500 0 : parent_shard
6501 0 : .observed
6502 0 : .locations
6503 0 : .insert(target.node.get_id(), ObservedStateLocation { conf: None });
6504 0 : }
6505 : }
6506 : }
6507 :
6508 : // TODO: issue split calls concurrently (this only matters once we're splitting
6509 : // N>1 shards into M shards -- initially we're usually splitting 1 shard into N).
6510 :
6511 : // HADRON: set a timeout for splitting individual shards on page servers.
6512 : // Currently we do not perform any retry because it's not clear if page server can handle
6513 : // partially split shards correctly.
6514 0 : let shard_split_timeout =
6515 0 : if let Some(env::DeploymentMode::Local) = env::get_deployment_mode() {
6516 0 : Duration::from_secs(30)
6517 : } else {
6518 0 : self.config.shard_split_request_timeout
6519 : };
6520 0 : let mut http_client_builder = reqwest::ClientBuilder::new()
6521 0 : .pool_max_idle_per_host(0)
6522 0 : .timeout(shard_split_timeout);
6523 :
6524 0 : for ssl_ca_cert in &self.config.ssl_ca_certs {
6525 0 : http_client_builder = http_client_builder.add_root_certificate(ssl_ca_cert.clone());
6526 0 : }
6527 0 : let http_client = http_client_builder
6528 0 : .build()
6529 0 : .expect("Failed to construct HTTP client");
6530 0 : for target in &targets {
6531 : let ShardSplitTarget {
6532 0 : parent_id,
6533 0 : node,
6534 0 : child_ids,
6535 0 : } = target;
6536 :
6537 0 : let client = PageserverClient::new(
6538 0 : node.get_id(),
6539 0 : http_client.clone(),
6540 0 : node.base_url(),
6541 0 : self.config.pageserver_jwt_token.as_deref(),
6542 : );
6543 :
6544 0 : let response = client
6545 0 : .tenant_shard_split(
6546 0 : *parent_id,
6547 0 : TenantShardSplitRequest {
6548 0 : new_shard_count: new_shard_count.literal(),
6549 0 : new_stripe_size,
6550 0 : },
6551 0 : )
6552 0 : .await
6553 0 : .map_err(|e| ApiError::Conflict(format!("Failed to split {parent_id}: {e}")))?;
6554 :
6555 0 : fail::fail_point!("shard-split-post-remote", |_| Err(ApiError::Conflict(
6556 0 : "failpoint".to_string()
6557 0 : )));
6558 :
6559 0 : failpoint_support::sleep_millis_async!(
6560 : "shard-split-post-remote-sleep",
6561 0 : &self.reconcilers_cancel
6562 : );
6563 :
6564 0 : tracing::info!(
6565 0 : "Split {} into {}",
6566 : parent_id,
6567 0 : response
6568 0 : .new_shards
6569 0 : .iter()
6570 0 : .map(|s| format!("{s:?}"))
6571 0 : .collect::<Vec<_>>()
6572 0 : .join(",")
6573 : );
6574 :
6575 0 : if &response.new_shards != child_ids {
6576 : // This should never happen: the pageserver should agree with us on how shard splits work.
6577 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
6578 0 : "Splitting shard {} resulted in unexpected IDs: {:?} (expected {:?})",
6579 0 : parent_id,
6580 0 : response.new_shards,
6581 0 : child_ids
6582 0 : )));
6583 0 : }
6584 : }
6585 :
6586 0 : fail::fail_point!("shard-split-pre-complete", |_| Err(ApiError::Conflict(
6587 0 : "failpoint".to_string()
6588 0 : )));
6589 :
6590 0 : pausable_failpoint!("shard-split-pre-complete-pause");
6591 :
6592 : // TODO: if the pageserver restarted concurrently with our split API call,
6593 : // the actual generation of the child shard might differ from the generation
6594 : // we expect it to have. In order for our in-database generation to end up
6595 : // correct, we should carry the child generation back in the response and apply it here
6596 : // in complete_shard_split (and apply the correct generation in memory)
6597 : // (or, we can carry generation in the request and reject the request if
6598 : // it doesn't match, but that requires more retry logic on this side)
6599 :
6600 0 : self.persistence
6601 0 : .complete_shard_split(tenant_id, old_shard_count, new_shard_count)
6602 0 : .await?;
6603 :
6604 0 : fail::fail_point!("shard-split-post-complete", |_| Err(
6605 0 : ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
6606 : ));
6607 :
6608 : // Replace all the shards we just split with their children: this phase is infallible.
6609 0 : let (response, child_locations, waiters) =
6610 0 : self.tenant_shard_split_commit_inmem(tenant_id, new_shard_count, new_stripe_size);
6611 :
6612 : // Notify all page servers to detach and clean up the old shards because they will no longer
6613 : // be needed. This is best-effort: if it fails, it will be cleaned up on a subsequent
6614 : // Pageserver re-attach/startup.
6615 0 : let shards_to_cleanup = targets
6616 0 : .iter()
6617 0 : .map(|target| (target.parent_id, target.node.get_id()))
6618 0 : .collect();
6619 0 : self.cleanup_locations(shards_to_cleanup).await;
6620 :
6621 : // Send compute notifications for all the new shards
6622 0 : let mut failed_notifications = Vec::new();
6623 0 : for (child_id, child_ps, stripe_size) in child_locations {
6624 0 : if let Err(e) = self
6625 0 : .compute_hook
6626 0 : .notify_attach(
6627 0 : compute_hook::ShardUpdate {
6628 0 : tenant_shard_id: child_id,
6629 0 : node_id: child_ps,
6630 0 : stripe_size,
6631 0 : preferred_az: preferred_az_id.as_ref().map(Cow::Borrowed),
6632 0 : },
6633 0 : &self.reconcilers_cancel,
6634 0 : )
6635 0 : .await
6636 : {
6637 0 : tracing::warn!(
6638 0 : "Failed to update compute of {}->{} during split, proceeding anyway to complete split ({e})",
6639 : child_id,
6640 : child_ps
6641 : );
6642 0 : failed_notifications.push(child_id);
6643 0 : }
6644 : }
6645 :
6646 : // If we failed any compute notifications, make a note to retry later.
6647 0 : if !failed_notifications.is_empty() {
6648 0 : let mut locked = self.inner.write().unwrap();
6649 0 : for failed in failed_notifications {
6650 0 : if let Some(shard) = locked.tenants.get_mut(&failed) {
6651 0 : shard.pending_compute_notification = true;
6652 0 : }
6653 : }
6654 0 : }
6655 :
6656 0 : Ok((response, waiters))
6657 0 : }
6658 :
6659 : /// A graceful migration: update the preferred node and let optimisation handle the migration
6660 : /// in the background (may take a long time as it will fully warm up a location before cutting over)
6661 : ///
6662 : /// Our external API calls this a 'prewarm=true' migration, but internally it isn't a special prewarm step: it's
6663 : /// just a migration that uses the same graceful procedure as our background scheduling optimisations would use.
6664 0 : fn tenant_shard_migrate_with_prewarm(
6665 0 : &self,
6666 0 : migrate_req: &TenantShardMigrateRequest,
6667 0 : shard: &mut TenantShard,
6668 0 : scheduler: &mut Scheduler,
6669 0 : schedule_context: ScheduleContext,
6670 0 : ) -> Result<Option<ScheduleOptimization>, ApiError> {
6671 0 : shard.set_preferred_node(Some(migrate_req.node_id));
6672 :
6673 : // Generate whatever the initial change to the intent is: this could be creation of a secondary, or
6674 : // cutting over to an existing secondary. Caller is responsible for validating this before applying it,
6675 : // e.g. by checking secondary is warm enough.
6676 0 : Ok(shard.optimize_attachment(scheduler, &schedule_context))
6677 0 : }
6678 :
6679 : /// Immediate migration: directly update the intent state and kick off a reconciler
6680 0 : fn tenant_shard_migrate_immediate(
6681 0 : &self,
6682 0 : migrate_req: &TenantShardMigrateRequest,
6683 0 : nodes: &Arc<HashMap<NodeId, Node>>,
6684 0 : shard: &mut TenantShard,
6685 0 : scheduler: &mut Scheduler,
6686 0 : ) -> Result<Option<ReconcilerWaiter>, ApiError> {
6687 : // Non-graceful migration: update the intent state immediately
6688 0 : let old_attached = *shard.intent.get_attached();
6689 0 : match shard.policy {
6690 0 : PlacementPolicy::Attached(n) => {
6691 : // If our new attached node was a secondary, it no longer should be.
6692 0 : shard
6693 0 : .intent
6694 0 : .remove_secondary(scheduler, migrate_req.node_id);
6695 :
6696 0 : shard
6697 0 : .intent
6698 0 : .set_attached(scheduler, Some(migrate_req.node_id));
6699 :
6700 : // If we were already attached to something, demote that to a secondary
6701 0 : if let Some(old_attached) = old_attached {
6702 0 : if n > 0 {
6703 : // Remove other secondaries to make room for the location we'll demote
6704 0 : while shard.intent.get_secondary().len() >= n {
6705 0 : shard.intent.pop_secondary(scheduler);
6706 0 : }
6707 :
6708 0 : shard.intent.push_secondary(scheduler, old_attached);
6709 0 : }
6710 0 : }
6711 : }
6712 0 : PlacementPolicy::Secondary => {
6713 0 : shard.intent.clear(scheduler);
6714 0 : shard.intent.push_secondary(scheduler, migrate_req.node_id);
6715 0 : }
6716 : PlacementPolicy::Detached => {
6717 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6718 0 : "Cannot migrate a tenant that is PlacementPolicy::Detached: configure it to an attached policy first"
6719 0 : )));
6720 : }
6721 : }
6722 :
6723 0 : tracing::info!("Migrating: new intent {:?}", shard.intent);
6724 0 : shard.sequence = shard.sequence.next();
6725 0 : shard.set_preferred_node(None); // Abort any in-flight graceful migration
6726 0 : Ok(self.maybe_configured_reconcile_shard(
6727 0 : shard,
6728 0 : nodes,
6729 0 : (&migrate_req.migration_config).into(),
6730 0 : ))
6731 0 : }
6732 :
6733 0 : pub(crate) async fn tenant_shard_migrate(
6734 0 : &self,
6735 0 : tenant_shard_id: TenantShardId,
6736 0 : migrate_req: TenantShardMigrateRequest,
6737 0 : ) -> Result<TenantShardMigrateResponse, ApiError> {
6738 : // Depending on whether the migration is a change and whether it's graceful or immediate, we might
6739 : // get a different outcome to handle
6740 : enum MigrationOutcome {
6741 : Optimization(Option<ScheduleOptimization>),
6742 : Reconcile(Option<ReconcilerWaiter>),
6743 : }
6744 :
6745 0 : let outcome = {
6746 0 : let mut locked = self.inner.write().unwrap();
6747 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6748 :
6749 0 : let Some(node) = nodes.get(&migrate_req.node_id) else {
6750 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6751 0 : "Node {} not found",
6752 0 : migrate_req.node_id
6753 0 : )));
6754 : };
6755 :
6756 : // Migration to unavavailable node requires force flag
6757 0 : if !node.is_available() {
6758 0 : if migrate_req.migration_config.override_scheduler {
6759 : // Warn but proceed: the caller may intend to manually adjust the placement of
6760 : // a shard even if the node is down, e.g. if intervening during an incident.
6761 0 : tracing::warn!("Forcibly migrating to unavailable node {node}");
6762 : } else {
6763 0 : tracing::warn!("Node {node} is unavailable, refusing migration");
6764 0 : return Err(ApiError::PreconditionFailed(
6765 0 : format!("Node {node} is unavailable").into_boxed_str(),
6766 0 : ));
6767 : }
6768 0 : }
6769 :
6770 : // Calculate the ScheduleContext for this tenant
6771 0 : let mut schedule_context = ScheduleContext::default();
6772 0 : for (_shard_id, shard) in
6773 0 : tenants.range(TenantShardId::tenant_range(tenant_shard_id.tenant_id))
6774 0 : {
6775 0 : schedule_context.avoid(&shard.intent.all_pageservers());
6776 0 : }
6777 :
6778 : // Look up the specific shard we will migrate
6779 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
6780 0 : return Err(ApiError::NotFound(
6781 0 : anyhow::anyhow!("Tenant shard not found").into(),
6782 0 : ));
6783 : };
6784 :
6785 : // Migration to a node with unfavorable scheduling score requires a force flag, because it might just
6786 : // be migrated back by the optimiser.
6787 0 : if let Some(better_node) = shard.find_better_location::<AttachedShardTag>(
6788 0 : scheduler,
6789 0 : &schedule_context,
6790 0 : migrate_req.node_id,
6791 0 : &[],
6792 0 : ) {
6793 0 : if !migrate_req.migration_config.override_scheduler {
6794 0 : return Err(ApiError::PreconditionFailed(
6795 0 : "Migration to a worse-scoring node".into(),
6796 0 : ));
6797 : } else {
6798 0 : tracing::info!(
6799 0 : "Migrating to a worse-scoring node {} (optimiser would prefer {better_node})",
6800 : migrate_req.node_id
6801 : );
6802 : }
6803 0 : }
6804 :
6805 0 : if let Some(origin_node_id) = migrate_req.origin_node_id {
6806 0 : if shard.intent.get_attached() != &Some(origin_node_id) {
6807 0 : return Err(ApiError::PreconditionFailed(
6808 0 : format!(
6809 0 : "Migration expected to originate from {} but shard is on {:?}",
6810 0 : origin_node_id,
6811 0 : shard.intent.get_attached()
6812 0 : )
6813 0 : .into(),
6814 0 : ));
6815 0 : }
6816 0 : }
6817 :
6818 0 : if shard.intent.get_attached() == &Some(migrate_req.node_id) {
6819 : // No-op case: we will still proceed to wait for reconciliation in case it is
6820 : // incomplete from an earlier update to the intent.
6821 0 : tracing::info!("Migrating: intent is unchanged {:?}", shard.intent);
6822 :
6823 : // An instruction to migrate to the currently attached node should
6824 : // cancel any pending graceful migration
6825 0 : shard.set_preferred_node(None);
6826 :
6827 0 : MigrationOutcome::Reconcile(self.maybe_configured_reconcile_shard(
6828 0 : shard,
6829 0 : nodes,
6830 0 : (&migrate_req.migration_config).into(),
6831 0 : ))
6832 0 : } else if migrate_req.migration_config.prewarm {
6833 0 : MigrationOutcome::Optimization(self.tenant_shard_migrate_with_prewarm(
6834 0 : &migrate_req,
6835 0 : shard,
6836 0 : scheduler,
6837 0 : schedule_context,
6838 0 : )?)
6839 : } else {
6840 0 : MigrationOutcome::Reconcile(self.tenant_shard_migrate_immediate(
6841 0 : &migrate_req,
6842 0 : nodes,
6843 0 : shard,
6844 0 : scheduler,
6845 0 : )?)
6846 : }
6847 : };
6848 :
6849 : // We may need to validate + apply an optimisation, or we may need to just retrive a reconcile waiter
6850 0 : let waiter = match outcome {
6851 0 : MigrationOutcome::Optimization(Some(optimization)) => {
6852 : // Validate and apply the optimization -- this would happen anyway in background reconcile loop, but
6853 : // we might as well do it more promptly as this is a direct external request.
6854 0 : let mut validated = self
6855 0 : .optimize_all_validate(vec![(tenant_shard_id, optimization)])
6856 0 : .await;
6857 0 : if let Some((_shard_id, optimization)) = validated.pop() {
6858 0 : let mut locked = self.inner.write().unwrap();
6859 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6860 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
6861 : // Rare but possible: tenant is removed between generating optimisation and validating it.
6862 0 : return Err(ApiError::NotFound(
6863 0 : anyhow::anyhow!("Tenant shard not found").into(),
6864 0 : ));
6865 : };
6866 :
6867 0 : if !shard.apply_optimization(scheduler, optimization) {
6868 : // This can happen but is unusual enough to warn on: something else changed in the shard that made the optimisation stale
6869 : // and therefore not applied.
6870 0 : tracing::warn!(
6871 0 : "Schedule optimisation generated during graceful migration was not applied, shard changed?"
6872 : );
6873 0 : }
6874 0 : self.maybe_configured_reconcile_shard(
6875 0 : shard,
6876 0 : nodes,
6877 0 : (&migrate_req.migration_config).into(),
6878 : )
6879 : } else {
6880 0 : None
6881 : }
6882 : }
6883 0 : MigrationOutcome::Optimization(None) => None,
6884 0 : MigrationOutcome::Reconcile(waiter) => waiter,
6885 : };
6886 :
6887 : // Finally, wait for any reconcile we started to complete. In the case of immediate-mode migrations to cold
6888 : // locations, this has a good chance of timing out.
6889 0 : if let Some(waiter) = waiter {
6890 0 : waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
6891 : } else {
6892 0 : tracing::info!("Migration is a no-op");
6893 : }
6894 :
6895 0 : Ok(TenantShardMigrateResponse {})
6896 0 : }
6897 :
6898 0 : pub(crate) async fn tenant_shard_migrate_secondary(
6899 0 : &self,
6900 0 : tenant_shard_id: TenantShardId,
6901 0 : migrate_req: TenantShardMigrateRequest,
6902 0 : ) -> Result<TenantShardMigrateResponse, ApiError> {
6903 0 : let waiter = {
6904 0 : let mut locked = self.inner.write().unwrap();
6905 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6906 :
6907 0 : let Some(node) = nodes.get(&migrate_req.node_id) else {
6908 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
6909 0 : "Node {} not found",
6910 0 : migrate_req.node_id
6911 0 : )));
6912 : };
6913 :
6914 0 : if !node.is_available() {
6915 : // Warn but proceed: the caller may intend to manually adjust the placement of
6916 : // a shard even if the node is down, e.g. if intervening during an incident.
6917 0 : tracing::warn!("Migrating to unavailable node {node}");
6918 0 : }
6919 :
6920 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
6921 0 : return Err(ApiError::NotFound(
6922 0 : anyhow::anyhow!("Tenant shard not found").into(),
6923 0 : ));
6924 : };
6925 :
6926 0 : if shard.intent.get_secondary().len() == 1
6927 0 : && shard.intent.get_secondary()[0] == migrate_req.node_id
6928 : {
6929 0 : tracing::info!(
6930 0 : "Migrating secondary to {node}: intent is unchanged {:?}",
6931 : shard.intent
6932 : );
6933 0 : } else if shard.intent.get_attached() == &Some(migrate_req.node_id) {
6934 0 : tracing::info!(
6935 0 : "Migrating secondary to {node}: already attached where we were asked to create a secondary"
6936 : );
6937 : } else {
6938 0 : let old_secondaries = shard.intent.get_secondary().clone();
6939 0 : for secondary in old_secondaries {
6940 0 : shard.intent.remove_secondary(scheduler, secondary);
6941 0 : }
6942 :
6943 0 : shard.intent.push_secondary(scheduler, migrate_req.node_id);
6944 0 : shard.sequence = shard.sequence.next();
6945 0 : tracing::info!(
6946 0 : "Migrating secondary to {node}: new intent {:?}",
6947 : shard.intent
6948 : );
6949 : }
6950 :
6951 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
6952 : };
6953 :
6954 0 : if let Some(waiter) = waiter {
6955 0 : waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
6956 : } else {
6957 0 : tracing::info!("Migration is a no-op");
6958 : }
6959 :
6960 0 : Ok(TenantShardMigrateResponse {})
6961 0 : }
6962 :
6963 : /// 'cancel' in this context means cancel any ongoing reconcile
6964 0 : pub(crate) async fn tenant_shard_cancel_reconcile(
6965 0 : &self,
6966 0 : tenant_shard_id: TenantShardId,
6967 0 : ) -> Result<(), ApiError> {
6968 : // Take state lock and fire the cancellation token, after which we drop lock and wait for any ongoing reconcile to complete
6969 0 : let waiter = {
6970 0 : let locked = self.inner.write().unwrap();
6971 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
6972 0 : return Err(ApiError::NotFound(
6973 0 : anyhow::anyhow!("Tenant shard not found").into(),
6974 0 : ));
6975 : };
6976 :
6977 0 : let waiter = shard.get_waiter();
6978 0 : match waiter {
6979 : None => {
6980 0 : tracing::info!("Shard does not have an ongoing Reconciler");
6981 0 : return Ok(());
6982 : }
6983 0 : Some(waiter) => {
6984 0 : tracing::info!("Cancelling Reconciler");
6985 0 : shard.cancel_reconciler();
6986 0 : waiter
6987 : }
6988 : }
6989 : };
6990 :
6991 : // Cancellation should be prompt. If this fails we have still done our job of firing the
6992 : // cancellation token, but by returning an ApiError we will indicate to the caller that
6993 : // the Reconciler is misbehaving and not respecting the cancellation token
6994 0 : self.await_waiters(vec![waiter], SHORT_RECONCILE_TIMEOUT)
6995 0 : .await?;
6996 :
6997 0 : Ok(())
6998 0 : }
6999 :
7000 : /// This is for debug/support only: we simply drop all state for a tenant, without
7001 : /// detaching or deleting it on pageservers.
7002 0 : pub(crate) async fn tenant_drop(&self, tenant_id: TenantId) -> Result<(), ApiError> {
7003 0 : self.persistence.delete_tenant(tenant_id).await?;
7004 :
7005 0 : let mut locked = self.inner.write().unwrap();
7006 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
7007 0 : let mut shards = Vec::new();
7008 0 : for (tenant_shard_id, _) in tenants.range(TenantShardId::tenant_range(tenant_id)) {
7009 0 : shards.push(*tenant_shard_id);
7010 0 : }
7011 :
7012 0 : for shard_id in shards {
7013 0 : if let Some(mut shard) = tenants.remove(&shard_id) {
7014 0 : shard.intent.clear(scheduler);
7015 0 : }
7016 : }
7017 :
7018 0 : Ok(())
7019 0 : }
7020 :
7021 : /// This is for debug/support only: assuming tenant data is already present in S3, we "create" a
7022 : /// tenant with a very high generation number so that it will see the existing data.
7023 : /// It does not create timelines on safekeepers, because they might already exist on some
7024 : /// safekeeper set. So, the timelines are not storcon-managed after the import.
7025 0 : pub(crate) async fn tenant_import(
7026 0 : &self,
7027 0 : tenant_id: TenantId,
7028 0 : ) -> Result<TenantCreateResponse, ApiError> {
7029 : // Pick an arbitrary available pageserver to use for scanning the tenant in remote storage
7030 0 : let maybe_node = {
7031 0 : self.inner
7032 0 : .read()
7033 0 : .unwrap()
7034 0 : .nodes
7035 0 : .values()
7036 0 : .find(|n| n.is_available())
7037 0 : .cloned()
7038 : };
7039 0 : let Some(node) = maybe_node else {
7040 0 : return Err(ApiError::BadRequest(anyhow::anyhow!("No nodes available")));
7041 : };
7042 :
7043 0 : let client = PageserverClient::new(
7044 0 : node.get_id(),
7045 0 : self.http_client.clone(),
7046 0 : node.base_url(),
7047 0 : self.config.pageserver_jwt_token.as_deref(),
7048 : );
7049 :
7050 0 : let scan_result = client
7051 0 : .tenant_scan_remote_storage(tenant_id)
7052 0 : .await
7053 0 : .map_err(|e| passthrough_api_error(&node, e))?;
7054 :
7055 : // A post-split tenant may contain a mixture of shard counts in remote storage: pick the highest count.
7056 0 : let Some(shard_count) = scan_result
7057 0 : .shards
7058 0 : .iter()
7059 0 : .map(|s| s.tenant_shard_id.shard_count)
7060 0 : .max()
7061 : else {
7062 0 : return Err(ApiError::NotFound(
7063 0 : anyhow::anyhow!("No shards found").into(),
7064 0 : ));
7065 : };
7066 :
7067 : // Ideally we would set each newly imported shard's generation independently, but for correctness it is sufficient
7068 : // to
7069 0 : let generation = scan_result
7070 0 : .shards
7071 0 : .iter()
7072 0 : .map(|s| s.generation)
7073 0 : .max()
7074 0 : .expect("We already validated >0 shards");
7075 :
7076 : // Find the tenant's stripe size. This wasn't always persisted in the tenant manifest, so
7077 : // fall back to the original default stripe size of 32768 (256 MB) if it's not specified.
7078 : const ORIGINAL_STRIPE_SIZE: ShardStripeSize = ShardStripeSize(32768);
7079 0 : let stripe_size = scan_result
7080 0 : .shards
7081 0 : .iter()
7082 0 : .find(|s| s.tenant_shard_id.shard_count == shard_count && s.generation == generation)
7083 0 : .expect("we validated >0 shards above")
7084 : .stripe_size
7085 0 : .unwrap_or_else(|| {
7086 0 : if shard_count.count() > 1 {
7087 0 : warn!("unknown stripe size, assuming {ORIGINAL_STRIPE_SIZE}");
7088 0 : }
7089 0 : ORIGINAL_STRIPE_SIZE
7090 0 : });
7091 :
7092 0 : let (response, waiters) = self
7093 0 : .do_tenant_create(TenantCreateRequest {
7094 0 : new_tenant_id: TenantShardId::unsharded(tenant_id),
7095 0 : generation,
7096 0 :
7097 0 : shard_parameters: ShardParameters {
7098 0 : count: shard_count,
7099 0 : stripe_size,
7100 0 : },
7101 0 : placement_policy: Some(PlacementPolicy::Attached(0)), // No secondaries, for convenient debug/hacking
7102 0 : config: TenantConfig::default(),
7103 0 : })
7104 0 : .await?;
7105 :
7106 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
7107 : // Since this is a debug/support operation, all kinds of weird issues are possible (e.g. this
7108 : // tenant doesn't exist in the control plane), so don't fail the request if it can't fully
7109 : // reconcile, as reconciliation includes notifying compute.
7110 0 : tracing::warn!(%tenant_id, "Reconcile not done yet while importing tenant ({e})");
7111 0 : }
7112 :
7113 0 : Ok(response)
7114 0 : }
7115 :
7116 : /// For debug/support: a full JSON dump of TenantShards. Returns a response so that
7117 : /// we don't have to make TenantShard clonable in the return path.
7118 0 : pub(crate) fn tenants_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
7119 0 : let serialized = {
7120 0 : let locked = self.inner.read().unwrap();
7121 0 : let result = locked.tenants.values().collect::<Vec<_>>();
7122 0 : serde_json::to_string(&result).map_err(|e| ApiError::InternalServerError(e.into()))?
7123 : };
7124 :
7125 0 : hyper::Response::builder()
7126 0 : .status(hyper::StatusCode::OK)
7127 0 : .header(hyper::header::CONTENT_TYPE, "application/json")
7128 0 : .body(hyper::Body::from(serialized))
7129 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
7130 0 : }
7131 :
7132 : /// Check the consistency of in-memory state vs. persistent state, and check that the
7133 : /// scheduler's statistics are up to date.
7134 : ///
7135 : /// These consistency checks expect an **idle** system. If changes are going on while
7136 : /// we run, then we can falsely indicate a consistency issue. This is sufficient for end-of-test
7137 : /// checks, but not suitable for running continuously in the background in the field.
7138 0 : pub(crate) async fn consistency_check(&self) -> Result<(), ApiError> {
7139 0 : let (mut expect_nodes, mut expect_shards) = {
7140 0 : let locked = self.inner.read().unwrap();
7141 :
7142 0 : locked
7143 0 : .scheduler
7144 0 : .consistency_check(locked.nodes.values(), locked.tenants.values())
7145 0 : .context("Scheduler checks")
7146 0 : .map_err(ApiError::InternalServerError)?;
7147 :
7148 0 : let expect_nodes = locked
7149 0 : .nodes
7150 0 : .values()
7151 0 : .map(|n| n.to_persistent())
7152 0 : .collect::<Vec<_>>();
7153 :
7154 0 : let expect_shards = locked
7155 0 : .tenants
7156 0 : .values()
7157 0 : .map(|t| t.to_persistent())
7158 0 : .collect::<Vec<_>>();
7159 :
7160 : // This method can only validate the state of an idle system: if a reconcile is in
7161 : // progress, fail out early to avoid giving false errors on state that won't match
7162 : // between database and memory under a ReconcileResult is processed.
7163 0 : for t in locked.tenants.values() {
7164 0 : if t.reconciler.is_some() {
7165 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
7166 0 : "Shard {} reconciliation in progress",
7167 0 : t.tenant_shard_id
7168 0 : )));
7169 0 : }
7170 : }
7171 :
7172 0 : (expect_nodes, expect_shards)
7173 : };
7174 :
7175 0 : let mut nodes = self.persistence.list_nodes().await?;
7176 0 : expect_nodes.sort_by_key(|n| n.node_id);
7177 0 : nodes.sort_by_key(|n| n.node_id);
7178 :
7179 : // Errors relating to nodes are deferred so that we don't skip the shard checks below if we have a node error
7180 0 : let node_result = if nodes != expect_nodes {
7181 0 : tracing::error!("Consistency check failed on nodes.");
7182 0 : tracing::error!(
7183 0 : "Nodes in memory: {}",
7184 0 : serde_json::to_string(&expect_nodes)
7185 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7186 : );
7187 0 : tracing::error!(
7188 0 : "Nodes in database: {}",
7189 0 : serde_json::to_string(&nodes)
7190 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7191 : );
7192 0 : Err(ApiError::InternalServerError(anyhow::anyhow!(
7193 0 : "Node consistency failure"
7194 0 : )))
7195 : } else {
7196 0 : Ok(())
7197 : };
7198 :
7199 0 : let mut persistent_shards = self.persistence.load_active_tenant_shards().await?;
7200 0 : persistent_shards
7201 0 : .sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
7202 :
7203 0 : expect_shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
7204 :
7205 : // Because JSON contents of persistent tenants might disagree with the fields in current `TenantConfig`
7206 : // definition, we will do an encode/decode cycle to ensure any legacy fields are dropped and any new
7207 : // fields are added, before doing a comparison.
7208 0 : for tsp in &mut persistent_shards {
7209 0 : let config: TenantConfig = serde_json::from_str(&tsp.config)
7210 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?;
7211 0 : tsp.config = serde_json::to_string(&config).expect("Encoding config is infallible");
7212 : }
7213 :
7214 0 : if persistent_shards != expect_shards {
7215 0 : tracing::error!("Consistency check failed on shards.");
7216 :
7217 0 : tracing::error!(
7218 0 : "Shards in memory: {}",
7219 0 : serde_json::to_string(&expect_shards)
7220 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7221 : );
7222 0 : tracing::error!(
7223 0 : "Shards in database: {}",
7224 0 : serde_json::to_string(&persistent_shards)
7225 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7226 : );
7227 :
7228 : // The total dump log lines above are useful in testing but in the field grafana will
7229 : // usually just drop them because they're so large. So we also do some explicit logging
7230 : // of just the diffs.
7231 0 : let persistent_shards = persistent_shards
7232 0 : .into_iter()
7233 0 : .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
7234 0 : .collect::<HashMap<_, _>>();
7235 0 : let expect_shards = expect_shards
7236 0 : .into_iter()
7237 0 : .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
7238 0 : .collect::<HashMap<_, _>>();
7239 0 : for (tenant_shard_id, persistent_tsp) in &persistent_shards {
7240 0 : match expect_shards.get(tenant_shard_id) {
7241 : None => {
7242 0 : tracing::error!(
7243 0 : "Shard {} found in database but not in memory",
7244 : tenant_shard_id
7245 : );
7246 : }
7247 0 : Some(expect_tsp) => {
7248 0 : if expect_tsp != persistent_tsp {
7249 0 : tracing::error!(
7250 0 : "Shard {} is inconsistent. In memory: {}, database has: {}",
7251 : tenant_shard_id,
7252 0 : serde_json::to_string(expect_tsp).unwrap(),
7253 0 : serde_json::to_string(&persistent_tsp).unwrap()
7254 : );
7255 0 : }
7256 : }
7257 : }
7258 : }
7259 :
7260 : // Having already logged any differences, log any shards that simply aren't present in the database
7261 0 : for (tenant_shard_id, memory_tsp) in &expect_shards {
7262 0 : if !persistent_shards.contains_key(tenant_shard_id) {
7263 0 : tracing::error!(
7264 0 : "Shard {} found in memory but not in database: {}",
7265 : tenant_shard_id,
7266 0 : serde_json::to_string(memory_tsp)
7267 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7268 : );
7269 0 : }
7270 : }
7271 :
7272 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
7273 0 : "Shard consistency failure"
7274 0 : )));
7275 0 : }
7276 :
7277 0 : node_result
7278 0 : }
7279 :
7280 : /// For debug/support: a JSON dump of the [`Scheduler`]. Returns a response so that
7281 : /// we don't have to make TenantShard clonable in the return path.
7282 0 : pub(crate) fn scheduler_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
7283 0 : let serialized = {
7284 0 : let locked = self.inner.read().unwrap();
7285 0 : serde_json::to_string(&locked.scheduler)
7286 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
7287 : };
7288 :
7289 0 : hyper::Response::builder()
7290 0 : .status(hyper::StatusCode::OK)
7291 0 : .header(hyper::header::CONTENT_TYPE, "application/json")
7292 0 : .body(hyper::Body::from(serialized))
7293 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
7294 0 : }
7295 :
7296 : /// This is for debug/support only: we simply drop all state for a tenant, without
7297 : /// detaching or deleting it on pageservers. We do not try and re-schedule any
7298 : /// tenants that were on this node.
7299 0 : pub(crate) async fn node_drop(&self, node_id: NodeId) -> Result<(), ApiError> {
7300 0 : self.persistence.set_tombstone(node_id).await?;
7301 :
7302 0 : let mut locked = self.inner.write().unwrap();
7303 :
7304 0 : for shard in locked.tenants.values_mut() {
7305 0 : shard.deref_node(node_id);
7306 0 : shard.observed.locations.remove(&node_id);
7307 0 : }
7308 :
7309 0 : let mut nodes = (*locked.nodes).clone();
7310 0 : nodes.remove(&node_id);
7311 0 : locked.nodes = Arc::new(nodes);
7312 0 : metrics::METRICS_REGISTRY
7313 0 : .metrics_group
7314 0 : .storage_controller_pageserver_nodes
7315 0 : .set(locked.nodes.len() as i64);
7316 0 : metrics::METRICS_REGISTRY
7317 0 : .metrics_group
7318 0 : .storage_controller_https_pageserver_nodes
7319 0 : .set(locked.nodes.values().filter(|n| n.has_https_port()).count() as i64);
7320 :
7321 0 : locked.scheduler.node_remove(node_id);
7322 :
7323 0 : Ok(())
7324 0 : }
7325 :
7326 : /// If a node has any work on it, it will be rescheduled: this is "clean" in the sense
7327 : /// that we don't leave any bad state behind in the storage controller, but unclean
7328 : /// in the sense that we are not carefully draining the node.
7329 0 : pub(crate) async fn node_delete_old(&self, node_id: NodeId) -> Result<(), ApiError> {
7330 0 : let _node_lock =
7331 0 : trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Delete).await;
7332 :
7333 : // 1. Atomically update in-memory state:
7334 : // - set the scheduling state to Pause to make subsequent scheduling ops skip it
7335 : // - update shards' intents to exclude the node, and reschedule any shards whose intents we modified.
7336 : // - drop the node from the main nodes map, so that when running reconciles complete they do not
7337 : // re-insert references to this node into the ObservedState of shards
7338 : // - drop the node from the scheduler
7339 : {
7340 0 : let mut locked = self.inner.write().unwrap();
7341 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
7342 :
7343 : {
7344 0 : let mut nodes_mut = (*nodes).deref().clone();
7345 0 : match nodes_mut.get_mut(&node_id) {
7346 0 : Some(node) => {
7347 0 : // We do not bother setting this in the database, because we're about to delete the row anyway, and
7348 0 : // if we crash it would not be desirable to leave the node paused after a restart.
7349 0 : node.set_scheduling(NodeSchedulingPolicy::Pause);
7350 0 : }
7351 : None => {
7352 0 : tracing::info!(
7353 0 : "Node not found: presuming this is a retry and returning success"
7354 : );
7355 0 : return Ok(());
7356 : }
7357 : }
7358 :
7359 0 : *nodes = Arc::new(nodes_mut);
7360 : }
7361 :
7362 0 : for (_tenant_id, mut schedule_context, shards) in
7363 0 : TenantShardExclusiveIterator::new(tenants, ScheduleMode::Normal)
7364 : {
7365 0 : for shard in shards {
7366 0 : if shard.deref_node(node_id) {
7367 0 : if let Err(e) = shard.schedule(scheduler, &mut schedule_context) {
7368 : // TODO: implement force flag to remove a node even if we can't reschedule
7369 : // a tenant
7370 0 : tracing::error!(
7371 0 : "Refusing to delete node, shard {} can't be rescheduled: {e}",
7372 : shard.tenant_shard_id
7373 : );
7374 0 : return Err(e.into());
7375 : } else {
7376 0 : tracing::info!(
7377 0 : "Rescheduled shard {} away from node during deletion",
7378 : shard.tenant_shard_id
7379 : )
7380 : }
7381 :
7382 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
7383 0 : }
7384 :
7385 : // Here we remove an existing observed location for the node we're removing, and it will
7386 : // not be re-added by a reconciler's completion because we filter out removed nodes in
7387 : // process_result.
7388 : //
7389 : // Note that we update the shard's observed state _after_ calling maybe_reconcile_shard: that
7390 : // means any reconciles we spawned will know about the node we're deleting, enabling them
7391 : // to do live migrations if it's still online.
7392 0 : shard.observed.locations.remove(&node_id);
7393 : }
7394 : }
7395 :
7396 0 : scheduler.node_remove(node_id);
7397 :
7398 : {
7399 0 : let mut nodes_mut = (**nodes).clone();
7400 0 : if let Some(mut removed_node) = nodes_mut.remove(&node_id) {
7401 0 : // Ensure that any reconciler holding an Arc<> to this node will
7402 0 : // drop out when trying to RPC to it (setting Offline state sets the
7403 0 : // cancellation token on the Node object).
7404 0 : removed_node.set_availability(NodeAvailability::Offline);
7405 0 : }
7406 0 : *nodes = Arc::new(nodes_mut);
7407 0 : metrics::METRICS_REGISTRY
7408 0 : .metrics_group
7409 0 : .storage_controller_pageserver_nodes
7410 0 : .set(nodes.len() as i64);
7411 0 : metrics::METRICS_REGISTRY
7412 0 : .metrics_group
7413 0 : .storage_controller_https_pageserver_nodes
7414 0 : .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
7415 : }
7416 : }
7417 :
7418 : // Note: some `generation_pageserver` columns on tenant shards in the database may still refer to
7419 : // the removed node, as this column means "The pageserver to which this generation was issued", and
7420 : // their generations won't get updated until the reconcilers moving them away from this node complete.
7421 : // That is safe because in Service::spawn we only use generation_pageserver if it refers to a node
7422 : // that exists.
7423 :
7424 : // 2. Actually delete the node from in-memory state and set tombstone to the database
7425 : // for preventing the node to register again.
7426 0 : tracing::info!("Deleting node from database");
7427 0 : self.persistence.set_tombstone(node_id).await?;
7428 :
7429 0 : Ok(())
7430 0 : }
7431 :
7432 0 : pub(crate) async fn delete_node(
7433 0 : self: &Arc<Self>,
7434 0 : node_id: NodeId,
7435 0 : policy_on_start: NodeSchedulingPolicy,
7436 0 : force: bool,
7437 0 : cancel: CancellationToken,
7438 0 : ) -> Result<(), OperationError> {
7439 0 : let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal).build();
7440 :
7441 0 : let mut waiters: Vec<ReconcilerWaiter> = Vec::new();
7442 0 : let mut tid_iter = create_shared_shard_iterator(self.clone());
7443 :
7444 0 : let reset_node_policy_on_cancel = || async {
7445 0 : match self
7446 0 : .node_configure(node_id, None, Some(policy_on_start))
7447 0 : .await
7448 : {
7449 0 : Ok(()) => OperationError::Cancelled,
7450 0 : Err(err) => {
7451 0 : OperationError::FinalizeError(
7452 0 : format!(
7453 0 : "Failed to finalise delete cancel of {} by setting scheduling policy to {}: {}",
7454 0 : node_id, String::from(policy_on_start), err
7455 0 : )
7456 0 : .into(),
7457 0 : )
7458 : }
7459 : }
7460 0 : };
7461 :
7462 0 : while !tid_iter.finished() {
7463 0 : if cancel.is_cancelled() {
7464 0 : return Err(reset_node_policy_on_cancel().await);
7465 0 : }
7466 :
7467 0 : operation_utils::validate_node_state(
7468 0 : &node_id,
7469 0 : self.inner.read().unwrap().nodes.clone(),
7470 0 : NodeSchedulingPolicy::Deleting,
7471 0 : )?;
7472 :
7473 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
7474 0 : let tid = match tid_iter.next() {
7475 0 : Some(tid) => tid,
7476 : None => {
7477 0 : break;
7478 : }
7479 : };
7480 :
7481 0 : let mut locked = self.inner.write().unwrap();
7482 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
7483 :
7484 : // Calculate a schedule context here to avoid borrow checker issues.
7485 0 : let mut schedule_context = ScheduleContext::default();
7486 0 : for (_, shard) in tenants.range(TenantShardId::tenant_range(tid.tenant_id)) {
7487 0 : schedule_context.avoid(&shard.intent.all_pageservers());
7488 0 : }
7489 :
7490 0 : let tenant_shard = match tenants.get_mut(&tid) {
7491 0 : Some(tenant_shard) => tenant_shard,
7492 : None => {
7493 : // Tenant shard was deleted by another operation. Skip it.
7494 0 : continue;
7495 : }
7496 : };
7497 :
7498 0 : match tenant_shard.get_scheduling_policy() {
7499 0 : ShardSchedulingPolicy::Active | ShardSchedulingPolicy::Essential => {
7500 0 : // A migration during delete is classed as 'essential' because it is required to
7501 0 : // uphold our availability goals for the tenant: this shard is elegible for migration.
7502 0 : }
7503 : ShardSchedulingPolicy::Pause | ShardSchedulingPolicy::Stop => {
7504 : // If we have been asked to avoid rescheduling this shard, then do not migrate it during a deletion
7505 0 : tracing::warn!(
7506 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
7507 0 : "Skip migration during deletion because shard scheduling policy {:?} disallows it",
7508 0 : tenant_shard.get_scheduling_policy(),
7509 : );
7510 0 : continue;
7511 : }
7512 : }
7513 :
7514 0 : if tenant_shard.deref_node(node_id) {
7515 0 : if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
7516 0 : tracing::error!(
7517 0 : "Refusing to delete node, shard {} can't be rescheduled: {e}",
7518 : tenant_shard.tenant_shard_id
7519 : );
7520 0 : return Err(OperationError::ImpossibleConstraint(e.to_string().into()));
7521 : } else {
7522 0 : tracing::info!(
7523 0 : "Rescheduled shard {} away from node during deletion",
7524 : tenant_shard.tenant_shard_id
7525 : )
7526 : }
7527 :
7528 0 : let waiter = self.maybe_configured_reconcile_shard(
7529 0 : tenant_shard,
7530 0 : nodes,
7531 0 : reconciler_config,
7532 0 : );
7533 :
7534 0 : if force {
7535 0 : // Here we remove an existing observed location for the node we're removing, and it will
7536 0 : // not be re-added by a reconciler's completion because we filter out removed nodes in
7537 0 : // process_result.
7538 0 : //
7539 0 : // Note that we update the shard's observed state _after_ calling maybe_configured_reconcile_shard:
7540 0 : // that means any reconciles we spawned will know about the node we're deleting,
7541 0 : // enabling them to do live migrations if it's still online.
7542 0 : tenant_shard.observed.locations.remove(&node_id);
7543 0 : } else if let Some(waiter) = waiter {
7544 0 : waiters.push(waiter);
7545 0 : }
7546 0 : }
7547 : }
7548 :
7549 0 : waiters = self
7550 0 : .await_waiters_remainder(waiters, WAITER_OPERATION_POLL_TIMEOUT)
7551 0 : .await;
7552 :
7553 0 : failpoint_support::sleep_millis_async!("sleepy-delete-loop", &cancel);
7554 : }
7555 :
7556 0 : while !waiters.is_empty() {
7557 0 : if cancel.is_cancelled() {
7558 0 : return Err(reset_node_policy_on_cancel().await);
7559 0 : }
7560 :
7561 0 : tracing::info!("Awaiting {} pending delete reconciliations", waiters.len());
7562 :
7563 0 : waiters = self
7564 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
7565 0 : .await;
7566 : }
7567 :
7568 0 : let pf = pausable_failpoint!("delete-node-after-reconciles-spawned", &cancel);
7569 0 : if pf.is_err() {
7570 : // An error from pausable_failpoint indicates the cancel token was triggered.
7571 0 : return Err(reset_node_policy_on_cancel().await);
7572 0 : }
7573 :
7574 0 : self.persistence
7575 0 : .set_tombstone(node_id)
7576 0 : .await
7577 0 : .map_err(|e| OperationError::FinalizeError(e.to_string().into()))?;
7578 :
7579 : {
7580 0 : let mut locked = self.inner.write().unwrap();
7581 0 : let (nodes, _, scheduler) = locked.parts_mut();
7582 :
7583 0 : scheduler.node_remove(node_id);
7584 :
7585 0 : let mut nodes_mut = (**nodes).clone();
7586 0 : if let Some(mut removed_node) = nodes_mut.remove(&node_id) {
7587 0 : // Ensure that any reconciler holding an Arc<> to this node will
7588 0 : // drop out when trying to RPC to it (setting Offline state sets the
7589 0 : // cancellation token on the Node object).
7590 0 : removed_node.set_availability(NodeAvailability::Offline);
7591 0 : }
7592 0 : *nodes = Arc::new(nodes_mut);
7593 :
7594 0 : metrics::METRICS_REGISTRY
7595 0 : .metrics_group
7596 0 : .storage_controller_pageserver_nodes
7597 0 : .set(nodes.len() as i64);
7598 0 : metrics::METRICS_REGISTRY
7599 0 : .metrics_group
7600 0 : .storage_controller_https_pageserver_nodes
7601 0 : .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
7602 : }
7603 :
7604 0 : Ok(())
7605 0 : }
7606 :
7607 0 : pub(crate) async fn node_list(&self) -> Result<Vec<Node>, ApiError> {
7608 0 : let nodes = {
7609 0 : self.inner
7610 0 : .read()
7611 0 : .unwrap()
7612 0 : .nodes
7613 0 : .values()
7614 0 : .cloned()
7615 0 : .collect::<Vec<_>>()
7616 : };
7617 :
7618 0 : Ok(nodes)
7619 0 : }
7620 :
7621 0 : pub(crate) async fn tombstone_list(&self) -> Result<Vec<Node>, ApiError> {
7622 0 : self.persistence
7623 0 : .list_tombstones()
7624 0 : .await?
7625 0 : .into_iter()
7626 0 : .map(|np| Node::from_persistent(np, false))
7627 0 : .collect::<Result<Vec<_>, _>>()
7628 0 : .map_err(ApiError::InternalServerError)
7629 0 : }
7630 :
7631 0 : pub(crate) async fn tombstone_delete(&self, node_id: NodeId) -> Result<(), ApiError> {
7632 0 : let _node_lock = trace_exclusive_lock(
7633 0 : &self.node_op_locks,
7634 0 : node_id,
7635 0 : NodeOperations::DeleteTombstone,
7636 0 : )
7637 0 : .await;
7638 :
7639 0 : if matches!(self.get_node(node_id).await, Err(ApiError::NotFound(_))) {
7640 0 : self.persistence.delete_node(node_id).await?;
7641 0 : Ok(())
7642 : } else {
7643 0 : Err(ApiError::Conflict(format!(
7644 0 : "Node {node_id} is in use, consider using tombstone API first"
7645 0 : )))
7646 : }
7647 0 : }
7648 :
7649 0 : pub(crate) async fn get_node(&self, node_id: NodeId) -> Result<Node, ApiError> {
7650 0 : self.inner
7651 0 : .read()
7652 0 : .unwrap()
7653 0 : .nodes
7654 0 : .get(&node_id)
7655 0 : .cloned()
7656 0 : .ok_or(ApiError::NotFound(
7657 0 : format!("Node {node_id} not registered").into(),
7658 0 : ))
7659 0 : }
7660 :
7661 0 : pub(crate) async fn get_node_shards(
7662 0 : &self,
7663 0 : node_id: NodeId,
7664 0 : ) -> Result<NodeShardResponse, ApiError> {
7665 0 : let locked = self.inner.read().unwrap();
7666 0 : let mut shards = Vec::new();
7667 0 : for (tid, tenant) in locked.tenants.iter() {
7668 0 : let is_intended_secondary = match (
7669 0 : tenant.intent.get_attached() == &Some(node_id),
7670 0 : tenant.intent.get_secondary().contains(&node_id),
7671 0 : ) {
7672 : (true, true) => {
7673 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
7674 0 : "{} attached as primary+secondary on the same node",
7675 0 : tid
7676 0 : )));
7677 : }
7678 0 : (true, false) => Some(false),
7679 0 : (false, true) => Some(true),
7680 0 : (false, false) => None,
7681 : };
7682 0 : let is_observed_secondary = if let Some(ObservedStateLocation { conf: Some(conf) }) =
7683 0 : tenant.observed.locations.get(&node_id)
7684 : {
7685 0 : Some(conf.secondary_conf.is_some())
7686 : } else {
7687 0 : None
7688 : };
7689 0 : if is_intended_secondary.is_some() || is_observed_secondary.is_some() {
7690 0 : shards.push(NodeShard {
7691 0 : tenant_shard_id: *tid,
7692 0 : is_intended_secondary,
7693 0 : is_observed_secondary,
7694 0 : });
7695 0 : }
7696 : }
7697 0 : Ok(NodeShardResponse { node_id, shards })
7698 0 : }
7699 :
7700 0 : pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
7701 0 : self.persistence.get_leader().await
7702 0 : }
7703 :
7704 0 : pub(crate) async fn node_register(
7705 0 : &self,
7706 0 : register_req: NodeRegisterRequest,
7707 0 : ) -> Result<(), ApiError> {
7708 0 : let _node_lock = trace_exclusive_lock(
7709 0 : &self.node_op_locks,
7710 0 : register_req.node_id,
7711 0 : NodeOperations::Register,
7712 0 : )
7713 0 : .await;
7714 :
7715 : #[derive(PartialEq)]
7716 : enum RegistrationStatus {
7717 : UpToDate,
7718 : NeedUpdate,
7719 : Mismatched,
7720 : New,
7721 : }
7722 :
7723 0 : let registration_status = {
7724 0 : let locked = self.inner.read().unwrap();
7725 0 : if let Some(node) = locked.nodes.get(®ister_req.node_id) {
7726 0 : if node.registration_match(®ister_req) {
7727 0 : if node.need_update(®ister_req) {
7728 0 : RegistrationStatus::NeedUpdate
7729 : } else {
7730 0 : RegistrationStatus::UpToDate
7731 : }
7732 : } else {
7733 0 : RegistrationStatus::Mismatched
7734 : }
7735 : } else {
7736 0 : RegistrationStatus::New
7737 : }
7738 : };
7739 :
7740 0 : match registration_status {
7741 : RegistrationStatus::UpToDate => {
7742 0 : tracing::info!(
7743 0 : "Node {} re-registered with matching address and is up to date",
7744 : register_req.node_id
7745 : );
7746 :
7747 0 : return Ok(());
7748 : }
7749 : RegistrationStatus::Mismatched => {
7750 : // TODO: decide if we want to allow modifying node addresses without removing and re-adding
7751 : // the node. Safest/simplest thing is to refuse it, and usually we deploy with
7752 : // a fixed address through the lifetime of a node.
7753 0 : tracing::warn!(
7754 0 : "Node {} tried to register with different address",
7755 : register_req.node_id
7756 : );
7757 0 : return Err(ApiError::Conflict(
7758 0 : "Node is already registered with different address".to_string(),
7759 0 : ));
7760 : }
7761 0 : RegistrationStatus::New | RegistrationStatus::NeedUpdate => {
7762 0 : // fallthrough
7763 0 : }
7764 : }
7765 :
7766 : // We do not require that a node is actually online when registered (it will start life
7767 : // with it's availability set to Offline), but we _do_ require that its DNS record exists. We're
7768 : // therefore not immune to asymmetric L3 connectivity issues, but we are protected against nodes
7769 : // that register themselves with a broken DNS config. We check only the HTTP hostname, because
7770 : // the postgres hostname might only be resolvable to clients (e.g. if we're on a different VPC than clients).
7771 0 : if tokio::net::lookup_host(format!(
7772 0 : "{}:{}",
7773 : register_req.listen_http_addr, register_req.listen_http_port
7774 : ))
7775 0 : .await
7776 0 : .is_err()
7777 : {
7778 : // If we have a transient DNS issue, it's up to the caller to retry their registration. Because
7779 : // we can't robustly distinguish between an intermittent issue and a totally bogus DNS situation,
7780 : // we return a soft 503 error, to encourage callers to retry past transient issues.
7781 0 : return Err(ApiError::ResourceUnavailable(
7782 0 : format!(
7783 0 : "Node {} tried to register with unknown DNS name '{}'",
7784 0 : register_req.node_id, register_req.listen_http_addr
7785 0 : )
7786 0 : .into(),
7787 0 : ));
7788 0 : }
7789 :
7790 0 : if self.config.use_https_pageserver_api && register_req.listen_https_port.is_none() {
7791 0 : return Err(ApiError::PreconditionFailed(
7792 0 : format!(
7793 0 : "Node {} has no https port, but use_https is enabled",
7794 0 : register_req.node_id
7795 0 : )
7796 0 : .into(),
7797 0 : ));
7798 0 : }
7799 :
7800 0 : if register_req.listen_grpc_addr.is_some() != register_req.listen_grpc_port.is_some() {
7801 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
7802 0 : "must specify both gRPC address and port"
7803 0 : )));
7804 0 : }
7805 :
7806 : // Ordering: we must persist the new node _before_ adding it to in-memory state.
7807 : // This ensures that before we use it for anything or expose it via any external
7808 : // API, it is guaranteed to be available after a restart.
7809 0 : let new_node = Node::new(
7810 0 : register_req.node_id,
7811 0 : register_req.listen_http_addr,
7812 0 : register_req.listen_http_port,
7813 0 : register_req.listen_https_port,
7814 0 : register_req.listen_pg_addr,
7815 0 : register_req.listen_pg_port,
7816 0 : register_req.listen_grpc_addr,
7817 0 : register_req.listen_grpc_port,
7818 0 : register_req.availability_zone_id.clone(),
7819 0 : self.config.use_https_pageserver_api,
7820 : );
7821 0 : let new_node = match new_node {
7822 0 : Ok(new_node) => new_node,
7823 0 : Err(error) => return Err(ApiError::InternalServerError(error)),
7824 : };
7825 :
7826 0 : match registration_status {
7827 : RegistrationStatus::New => {
7828 0 : self.persistence.insert_node(&new_node).await.map_err(|e| {
7829 0 : if matches!(
7830 0 : e,
7831 : crate::persistence::DatabaseError::Query(
7832 : diesel::result::Error::DatabaseError(
7833 : diesel::result::DatabaseErrorKind::UniqueViolation,
7834 : _,
7835 : )
7836 : )
7837 : ) {
7838 : // The node can be deleted by tombstone API, and not show up in the list of nodes.
7839 : // If you see this error, check tombstones first.
7840 0 : ApiError::Conflict(format!("Node {} is already exists", new_node.get_id()))
7841 : } else {
7842 0 : ApiError::from(e)
7843 : }
7844 0 : })?;
7845 : }
7846 : RegistrationStatus::NeedUpdate => {
7847 0 : self.persistence
7848 0 : .update_node_on_registration(
7849 0 : register_req.node_id,
7850 0 : register_req.listen_https_port,
7851 0 : )
7852 0 : .await?
7853 : }
7854 0 : _ => unreachable!("Other statuses have been processed earlier"),
7855 : }
7856 :
7857 0 : let mut locked = self.inner.write().unwrap();
7858 0 : let mut new_nodes = (*locked.nodes).clone();
7859 :
7860 0 : locked.scheduler.node_upsert(&new_node);
7861 0 : new_nodes.insert(register_req.node_id, new_node);
7862 :
7863 0 : locked.nodes = Arc::new(new_nodes);
7864 :
7865 0 : metrics::METRICS_REGISTRY
7866 0 : .metrics_group
7867 0 : .storage_controller_pageserver_nodes
7868 0 : .set(locked.nodes.len() as i64);
7869 0 : metrics::METRICS_REGISTRY
7870 0 : .metrics_group
7871 0 : .storage_controller_https_pageserver_nodes
7872 0 : .set(locked.nodes.values().filter(|n| n.has_https_port()).count() as i64);
7873 :
7874 0 : match registration_status {
7875 : RegistrationStatus::New => {
7876 0 : tracing::info!(
7877 0 : "Registered pageserver {} ({}), now have {} pageservers",
7878 : register_req.node_id,
7879 : register_req.availability_zone_id,
7880 0 : locked.nodes.len()
7881 : );
7882 : }
7883 : RegistrationStatus::NeedUpdate => {
7884 0 : tracing::info!(
7885 0 : "Re-registered and updated node {} ({})",
7886 : register_req.node_id,
7887 : register_req.availability_zone_id,
7888 : );
7889 : }
7890 0 : _ => unreachable!("Other statuses have been processed earlier"),
7891 : }
7892 0 : Ok(())
7893 0 : }
7894 :
7895 : /// Configure in-memory and persistent state of a node as requested
7896 : ///
7897 : /// Note that this function does not trigger any immediate side effects in response
7898 : /// to the changes. That part is handled by [`Self::handle_node_availability_transition`].
7899 0 : async fn node_state_configure(
7900 0 : &self,
7901 0 : node_id: NodeId,
7902 0 : availability: Option<NodeAvailability>,
7903 0 : scheduling: Option<NodeSchedulingPolicy>,
7904 0 : node_lock: &TracingExclusiveGuard<NodeOperations>,
7905 0 : ) -> Result<AvailabilityTransition, ApiError> {
7906 0 : if let Some(scheduling) = scheduling {
7907 : // Scheduling is a persistent part of Node: we must write updates to the database before
7908 : // applying them in memory
7909 0 : self.persistence
7910 0 : .update_node_scheduling_policy(node_id, scheduling)
7911 0 : .await?;
7912 0 : }
7913 :
7914 : // If we're activating a node, then before setting it active we must reconcile any shard locations
7915 : // on that node, in case it is out of sync, e.g. due to being unavailable during controller startup,
7916 : // by calling [`Self::node_activate_reconcile`]
7917 : //
7918 : // The transition we calculate here remains valid later in the function because we hold the op lock on the node:
7919 : // nothing else can mutate its availability while we run.
7920 0 : let availability_transition = if let Some(input_availability) = availability.as_ref() {
7921 0 : let (activate_node, availability_transition) = {
7922 0 : let locked = self.inner.read().unwrap();
7923 0 : let Some(node) = locked.nodes.get(&node_id) else {
7924 0 : return Err(ApiError::NotFound(
7925 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
7926 0 : ));
7927 : };
7928 :
7929 0 : (
7930 0 : node.clone(),
7931 0 : node.get_availability_transition(input_availability),
7932 0 : )
7933 : };
7934 :
7935 0 : if matches!(availability_transition, AvailabilityTransition::ToActive) {
7936 0 : self.node_activate_reconcile(activate_node, node_lock)
7937 0 : .await?;
7938 0 : }
7939 0 : availability_transition
7940 : } else {
7941 0 : AvailabilityTransition::Unchanged
7942 : };
7943 :
7944 : // Apply changes from the request to our in-memory state for the Node
7945 0 : let mut locked = self.inner.write().unwrap();
7946 0 : let (nodes, _tenants, scheduler) = locked.parts_mut();
7947 :
7948 0 : let mut new_nodes = (**nodes).clone();
7949 :
7950 0 : let Some(node) = new_nodes.get_mut(&node_id) else {
7951 0 : return Err(ApiError::NotFound(
7952 0 : anyhow::anyhow!("Node not registered").into(),
7953 0 : ));
7954 : };
7955 :
7956 0 : if let Some(availability) = availability {
7957 0 : node.set_availability(availability);
7958 0 : }
7959 :
7960 0 : if let Some(scheduling) = scheduling {
7961 0 : node.set_scheduling(scheduling);
7962 0 : }
7963 :
7964 : // Update the scheduler, in case the elegibility of the node for new shards has changed
7965 0 : scheduler.node_upsert(node);
7966 :
7967 0 : let new_nodes = Arc::new(new_nodes);
7968 0 : locked.nodes = new_nodes;
7969 :
7970 0 : Ok(availability_transition)
7971 0 : }
7972 :
7973 : /// Handle availability transition of one node
7974 : ///
7975 : /// Note that you should first call [`Self::node_state_configure`] to update
7976 : /// the in-memory state referencing that node. If you need to handle more than one transition
7977 : /// consider using [`Self::handle_node_availability_transitions`].
7978 0 : async fn handle_node_availability_transition(
7979 0 : &self,
7980 0 : node_id: NodeId,
7981 0 : transition: AvailabilityTransition,
7982 0 : _node_lock: &TracingExclusiveGuard<NodeOperations>,
7983 0 : ) -> Result<(), ApiError> {
7984 : // Modify scheduling state for any Tenants that are affected by a change in the node's availability state.
7985 0 : match transition {
7986 : AvailabilityTransition::ToOffline => {
7987 0 : tracing::info!("Node {} transition to offline", node_id);
7988 :
7989 0 : let mut locked = self.inner.write().unwrap();
7990 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
7991 :
7992 0 : let mut tenants_affected: usize = 0;
7993 :
7994 0 : for (_tenant_id, mut schedule_context, shards) in
7995 0 : TenantShardExclusiveIterator::new(tenants, ScheduleMode::Normal)
7996 : {
7997 0 : for tenant_shard in shards {
7998 0 : let tenant_shard_id = tenant_shard.tenant_shard_id;
7999 0 : if let Some(observed_loc) =
8000 0 : tenant_shard.observed.locations.get_mut(&node_id)
8001 0 : {
8002 0 : // When a node goes offline, we set its observed configuration to None, indicating unknown: we will
8003 0 : // not assume our knowledge of the node's configuration is accurate until it comes back online
8004 0 : observed_loc.conf = None;
8005 0 : }
8006 :
8007 0 : if nodes.len() == 1 {
8008 : // Special case for single-node cluster: there is no point trying to reschedule
8009 : // any tenant shards: avoid doing so, in order to avoid spewing warnings about
8010 : // failures to schedule them.
8011 0 : continue;
8012 0 : }
8013 :
8014 0 : if !nodes
8015 0 : .values()
8016 0 : .any(|n| matches!(n.may_schedule(), MaySchedule::Yes(_)))
8017 : {
8018 : // Special case for when all nodes are unavailable and/or unschedulable: there is no point
8019 : // trying to reschedule since there's nowhere else to go. Without this
8020 : // branch we incorrectly detach tenants in response to node unavailability.
8021 0 : continue;
8022 0 : }
8023 :
8024 0 : if tenant_shard.intent.demote_attached(scheduler, node_id) {
8025 0 : tenant_shard.sequence = tenant_shard.sequence.next();
8026 :
8027 0 : match tenant_shard.schedule(scheduler, &mut schedule_context) {
8028 0 : Err(e) => {
8029 : // It is possible that some tenants will become unschedulable when too many pageservers
8030 : // go offline: in this case there isn't much we can do other than make the issue observable.
8031 : // TODO: give TenantShard a scheduling error attribute to be queried later.
8032 0 : tracing::warn!(%tenant_shard_id, "Scheduling error when marking pageserver {} offline: {e}", node_id);
8033 : }
8034 : Ok(()) => {
8035 0 : if self
8036 0 : .maybe_reconcile_shard(
8037 0 : tenant_shard,
8038 0 : nodes,
8039 0 : ReconcilerPriority::Normal,
8040 0 : )
8041 0 : .is_some()
8042 0 : {
8043 0 : tenants_affected += 1;
8044 0 : };
8045 : }
8046 : }
8047 0 : }
8048 : }
8049 : }
8050 0 : tracing::info!(
8051 0 : "Launched {} reconciler tasks for tenants affected by node {} going offline",
8052 : tenants_affected,
8053 : node_id
8054 : )
8055 : }
8056 : AvailabilityTransition::ToActive => {
8057 0 : tracing::info!("Node {} transition to active", node_id);
8058 :
8059 0 : let mut locked = self.inner.write().unwrap();
8060 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
8061 :
8062 : // When a node comes back online, we must reconcile any tenant that has a None observed
8063 : // location on the node.
8064 0 : for tenant_shard in tenants.values_mut() {
8065 : // If a reconciliation is already in progress, rely on the previous scheduling
8066 : // decision and skip triggering a new reconciliation.
8067 0 : if tenant_shard.reconciler.is_some() {
8068 0 : continue;
8069 0 : }
8070 :
8071 0 : if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
8072 0 : if observed_loc.conf.is_none() {
8073 0 : self.maybe_reconcile_shard(
8074 0 : tenant_shard,
8075 0 : nodes,
8076 0 : ReconcilerPriority::Normal,
8077 0 : );
8078 0 : }
8079 0 : }
8080 : }
8081 :
8082 : // TODO: in the background, we should balance work back onto this pageserver
8083 : }
8084 : // No action required for the intermediate unavailable state.
8085 : // When we transition into active or offline from the unavailable state,
8086 : // the correct handling above will kick in.
8087 : AvailabilityTransition::ToWarmingUpFromActive => {
8088 0 : tracing::info!("Node {} transition to unavailable from active", node_id);
8089 : }
8090 : AvailabilityTransition::ToWarmingUpFromOffline => {
8091 0 : tracing::info!("Node {} transition to unavailable from offline", node_id);
8092 : }
8093 : AvailabilityTransition::Unchanged => {
8094 0 : tracing::debug!("Node {} no availability change during config", node_id);
8095 : }
8096 : }
8097 :
8098 0 : Ok(())
8099 0 : }
8100 :
8101 : /// Handle availability transition for multiple nodes
8102 : ///
8103 : /// Note that you should first call [`Self::node_state_configure`] for
8104 : /// all nodes being handled here for the handling to use fresh in-memory state.
8105 0 : async fn handle_node_availability_transitions(
8106 0 : &self,
8107 0 : transitions: Vec<(
8108 0 : NodeId,
8109 0 : TracingExclusiveGuard<NodeOperations>,
8110 0 : AvailabilityTransition,
8111 0 : )>,
8112 0 : ) -> Result<(), Vec<(NodeId, ApiError)>> {
8113 0 : let mut errors = Vec::default();
8114 0 : for (node_id, node_lock, transition) in transitions {
8115 0 : let res = self
8116 0 : .handle_node_availability_transition(node_id, transition, &node_lock)
8117 0 : .await;
8118 0 : if let Err(err) = res {
8119 0 : errors.push((node_id, err));
8120 0 : }
8121 : }
8122 :
8123 0 : if errors.is_empty() {
8124 0 : Ok(())
8125 : } else {
8126 0 : Err(errors)
8127 : }
8128 0 : }
8129 :
8130 0 : pub(crate) async fn node_configure(
8131 0 : &self,
8132 0 : node_id: NodeId,
8133 0 : availability: Option<NodeAvailability>,
8134 0 : scheduling: Option<NodeSchedulingPolicy>,
8135 0 : ) -> Result<(), ApiError> {
8136 0 : let node_lock =
8137 0 : trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Configure).await;
8138 :
8139 0 : let transition = self
8140 0 : .node_state_configure(node_id, availability, scheduling, &node_lock)
8141 0 : .await?;
8142 0 : self.handle_node_availability_transition(node_id, transition, &node_lock)
8143 0 : .await
8144 0 : }
8145 :
8146 : /// Wrapper around [`Self::node_configure`] which only allows changes while there is no ongoing
8147 : /// operation for HTTP api.
8148 0 : pub(crate) async fn external_node_configure(
8149 0 : &self,
8150 0 : node_id: NodeId,
8151 0 : availability: Option<NodeAvailability>,
8152 0 : scheduling: Option<NodeSchedulingPolicy>,
8153 0 : ) -> Result<(), ApiError> {
8154 : {
8155 0 : let locked = self.inner.read().unwrap();
8156 0 : if let Some(op) = locked.ongoing_operation.as_ref().map(|op| op.operation) {
8157 0 : return Err(ApiError::PreconditionFailed(
8158 0 : format!("Ongoing background operation forbids configuring: {op}").into(),
8159 0 : ));
8160 0 : }
8161 : }
8162 :
8163 0 : self.node_configure(node_id, availability, scheduling).await
8164 0 : }
8165 :
8166 0 : pub(crate) async fn start_node_delete(
8167 0 : self: &Arc<Self>,
8168 0 : node_id: NodeId,
8169 0 : force: bool,
8170 0 : ) -> Result<(), ApiError> {
8171 0 : let (ongoing_op, node_policy, schedulable_nodes_count) = {
8172 0 : let locked = self.inner.read().unwrap();
8173 0 : let nodes = &locked.nodes;
8174 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8175 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8176 0 : ))?;
8177 0 : let schedulable_nodes_count = nodes
8178 0 : .iter()
8179 0 : .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
8180 0 : .count();
8181 :
8182 : (
8183 0 : locked
8184 0 : .ongoing_operation
8185 0 : .as_ref()
8186 0 : .map(|ongoing| ongoing.operation),
8187 0 : node.get_scheduling(),
8188 0 : schedulable_nodes_count,
8189 : )
8190 : };
8191 :
8192 0 : if let Some(ongoing) = ongoing_op {
8193 0 : return Err(ApiError::PreconditionFailed(
8194 0 : format!("Background operation already ongoing for node: {ongoing}").into(),
8195 0 : ));
8196 0 : }
8197 :
8198 0 : if schedulable_nodes_count == 0 {
8199 0 : return Err(ApiError::PreconditionFailed(
8200 0 : "No other schedulable nodes to move shards".into(),
8201 0 : ));
8202 0 : }
8203 :
8204 0 : match node_policy {
8205 : NodeSchedulingPolicy::Active | NodeSchedulingPolicy::Pause => {
8206 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Deleting))
8207 0 : .await?;
8208 :
8209 0 : let cancel = self.cancel.child_token();
8210 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
8211 0 : let policy_on_start = node_policy;
8212 :
8213 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
8214 0 : operation: Operation::Delete(Delete { node_id }),
8215 0 : cancel: cancel.clone(),
8216 0 : });
8217 :
8218 0 : let span = tracing::info_span!(parent: None, "delete_node", %node_id);
8219 :
8220 0 : tokio::task::spawn(
8221 : {
8222 0 : let service = self.clone();
8223 0 : let cancel = cancel.clone();
8224 0 : async move {
8225 0 : let _gate_guard = gate_guard;
8226 :
8227 0 : scopeguard::defer! {
8228 : let prev = service.inner.write().unwrap().ongoing_operation.take();
8229 :
8230 : if let Some(Operation::Delete(removed_delete)) = prev.map(|h| h.operation) {
8231 : assert_eq!(removed_delete.node_id, node_id, "We always take the same operation");
8232 : } else {
8233 : panic!("We always remove the same operation")
8234 : }
8235 : }
8236 :
8237 0 : tracing::info!("Delete background operation starting");
8238 0 : let res = service
8239 0 : .delete_node(node_id, policy_on_start, force, cancel)
8240 0 : .await;
8241 0 : match res {
8242 : Ok(()) => {
8243 0 : tracing::info!(
8244 0 : "Delete background operation completed successfully"
8245 : );
8246 : }
8247 : Err(OperationError::Cancelled) => {
8248 0 : tracing::info!("Delete background operation was cancelled");
8249 : }
8250 0 : Err(err) => {
8251 0 : tracing::error!(
8252 0 : "Delete background operation encountered: {err}"
8253 : )
8254 : }
8255 : }
8256 0 : }
8257 : }
8258 0 : .instrument(span),
8259 : );
8260 : }
8261 : NodeSchedulingPolicy::Deleting => {
8262 0 : return Err(ApiError::Conflict(format!(
8263 0 : "Node {node_id} has delete in progress"
8264 0 : )));
8265 : }
8266 0 : policy => {
8267 0 : return Err(ApiError::PreconditionFailed(
8268 0 : format!("Node {node_id} cannot be deleted due to {policy:?} policy").into(),
8269 0 : ));
8270 : }
8271 : }
8272 :
8273 0 : Ok(())
8274 0 : }
8275 :
8276 0 : pub(crate) async fn cancel_node_delete(
8277 0 : self: &Arc<Self>,
8278 0 : node_id: NodeId,
8279 0 : ) -> Result<(), ApiError> {
8280 : {
8281 0 : let locked = self.inner.read().unwrap();
8282 0 : let nodes = &locked.nodes;
8283 0 : nodes.get(&node_id).ok_or(ApiError::NotFound(
8284 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8285 0 : ))?;
8286 : }
8287 :
8288 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
8289 0 : if let Operation::Delete(delete) = op_handler.operation {
8290 0 : if delete.node_id == node_id {
8291 0 : tracing::info!("Cancelling background delete operation for node {node_id}");
8292 0 : op_handler.cancel.cancel();
8293 0 : return Ok(());
8294 0 : }
8295 0 : }
8296 0 : }
8297 :
8298 0 : Err(ApiError::PreconditionFailed(
8299 0 : format!("Node {node_id} has no delete in progress").into(),
8300 0 : ))
8301 0 : }
8302 :
8303 0 : pub(crate) async fn start_node_drain(
8304 0 : self: &Arc<Self>,
8305 0 : node_id: NodeId,
8306 0 : ) -> Result<(), ApiError> {
8307 0 : let (ongoing_op, node_available, node_policy, schedulable_nodes_count) = {
8308 0 : let locked = self.inner.read().unwrap();
8309 0 : let nodes = &locked.nodes;
8310 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8311 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8312 0 : ))?;
8313 0 : let schedulable_nodes_count = nodes
8314 0 : .iter()
8315 0 : .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
8316 0 : .count();
8317 :
8318 : (
8319 0 : locked
8320 0 : .ongoing_operation
8321 0 : .as_ref()
8322 0 : .map(|ongoing| ongoing.operation),
8323 0 : node.is_available(),
8324 0 : node.get_scheduling(),
8325 0 : schedulable_nodes_count,
8326 : )
8327 : };
8328 :
8329 0 : if let Some(ongoing) = ongoing_op {
8330 0 : return Err(ApiError::PreconditionFailed(
8331 0 : format!("Background operation already ongoing for node: {ongoing}").into(),
8332 0 : ));
8333 0 : }
8334 :
8335 0 : if !node_available {
8336 0 : return Err(ApiError::ResourceUnavailable(
8337 0 : format!("Node {node_id} is currently unavailable").into(),
8338 0 : ));
8339 0 : }
8340 :
8341 0 : if schedulable_nodes_count == 0 {
8342 0 : return Err(ApiError::PreconditionFailed(
8343 0 : "No other schedulable nodes to drain to".into(),
8344 0 : ));
8345 0 : }
8346 :
8347 0 : match node_policy {
8348 : NodeSchedulingPolicy::Active => {
8349 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Draining))
8350 0 : .await?;
8351 :
8352 0 : let cancel = self.cancel.child_token();
8353 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
8354 :
8355 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
8356 0 : operation: Operation::Drain(Drain { node_id }),
8357 0 : cancel: cancel.clone(),
8358 0 : });
8359 :
8360 0 : let span = tracing::info_span!(parent: None, "drain_node", %node_id);
8361 :
8362 0 : tokio::task::spawn({
8363 0 : let service = self.clone();
8364 0 : let cancel = cancel.clone();
8365 0 : async move {
8366 0 : let _gate_guard = gate_guard;
8367 :
8368 0 : scopeguard::defer! {
8369 : let prev = service.inner.write().unwrap().ongoing_operation.take();
8370 :
8371 : if let Some(Operation::Drain(removed_drain)) = prev.map(|h| h.operation) {
8372 : assert_eq!(removed_drain.node_id, node_id, "We always take the same operation");
8373 : } else {
8374 : panic!("We always remove the same operation")
8375 : }
8376 : }
8377 :
8378 0 : tracing::info!("Drain background operation starting");
8379 0 : let res = service.drain_node(node_id, cancel).await;
8380 0 : match res {
8381 : Ok(()) => {
8382 0 : tracing::info!("Drain background operation completed successfully");
8383 : }
8384 : Err(OperationError::Cancelled) => {
8385 0 : tracing::info!("Drain background operation was cancelled");
8386 : }
8387 0 : Err(err) => {
8388 0 : tracing::error!("Drain background operation encountered: {err}")
8389 : }
8390 : }
8391 0 : }
8392 0 : }.instrument(span));
8393 : }
8394 : NodeSchedulingPolicy::Draining => {
8395 0 : return Err(ApiError::Conflict(format!(
8396 0 : "Node {node_id} has drain in progress"
8397 0 : )));
8398 : }
8399 0 : policy => {
8400 0 : return Err(ApiError::PreconditionFailed(
8401 0 : format!("Node {node_id} cannot be drained due to {policy:?} policy").into(),
8402 0 : ));
8403 : }
8404 : }
8405 :
8406 0 : Ok(())
8407 0 : }
8408 :
8409 0 : pub(crate) async fn cancel_node_drain(&self, node_id: NodeId) -> Result<(), ApiError> {
8410 0 : let node_available = {
8411 0 : let locked = self.inner.read().unwrap();
8412 0 : let nodes = &locked.nodes;
8413 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8414 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8415 0 : ))?;
8416 :
8417 0 : node.is_available()
8418 : };
8419 :
8420 0 : if !node_available {
8421 0 : return Err(ApiError::ResourceUnavailable(
8422 0 : format!("Node {node_id} is currently unavailable").into(),
8423 0 : ));
8424 0 : }
8425 :
8426 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
8427 0 : if let Operation::Drain(drain) = op_handler.operation {
8428 0 : if drain.node_id == node_id {
8429 0 : tracing::info!("Cancelling background drain operation for node {node_id}");
8430 0 : op_handler.cancel.cancel();
8431 0 : return Ok(());
8432 0 : }
8433 0 : }
8434 0 : }
8435 :
8436 0 : Err(ApiError::PreconditionFailed(
8437 0 : format!("Node {node_id} has no drain in progress").into(),
8438 0 : ))
8439 0 : }
8440 :
8441 0 : pub(crate) async fn start_node_fill(self: &Arc<Self>, node_id: NodeId) -> Result<(), ApiError> {
8442 0 : let (ongoing_op, node_available, node_policy, total_nodes_count) = {
8443 0 : let locked = self.inner.read().unwrap();
8444 0 : let nodes = &locked.nodes;
8445 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8446 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8447 0 : ))?;
8448 :
8449 : (
8450 0 : locked
8451 0 : .ongoing_operation
8452 0 : .as_ref()
8453 0 : .map(|ongoing| ongoing.operation),
8454 0 : node.is_available(),
8455 0 : node.get_scheduling(),
8456 0 : nodes.len(),
8457 : )
8458 : };
8459 :
8460 0 : if let Some(ongoing) = ongoing_op {
8461 0 : return Err(ApiError::PreconditionFailed(
8462 0 : format!("Background operation already ongoing for node: {ongoing}").into(),
8463 0 : ));
8464 0 : }
8465 :
8466 0 : if !node_available {
8467 0 : return Err(ApiError::ResourceUnavailable(
8468 0 : format!("Node {node_id} is currently unavailable").into(),
8469 0 : ));
8470 0 : }
8471 :
8472 0 : if total_nodes_count <= 1 {
8473 0 : return Err(ApiError::PreconditionFailed(
8474 0 : "No other nodes to fill from".into(),
8475 0 : ));
8476 0 : }
8477 :
8478 0 : match node_policy {
8479 : NodeSchedulingPolicy::Active => {
8480 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Filling))
8481 0 : .await?;
8482 :
8483 0 : let cancel = self.cancel.child_token();
8484 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
8485 :
8486 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
8487 0 : operation: Operation::Fill(Fill { node_id }),
8488 0 : cancel: cancel.clone(),
8489 0 : });
8490 :
8491 0 : let span = tracing::info_span!(parent: None, "fill_node", %node_id);
8492 :
8493 0 : tokio::task::spawn({
8494 0 : let service = self.clone();
8495 0 : let cancel = cancel.clone();
8496 0 : async move {
8497 0 : let _gate_guard = gate_guard;
8498 :
8499 0 : scopeguard::defer! {
8500 : let prev = service.inner.write().unwrap().ongoing_operation.take();
8501 :
8502 : if let Some(Operation::Fill(removed_fill)) = prev.map(|h| h.operation) {
8503 : assert_eq!(removed_fill.node_id, node_id, "We always take the same operation");
8504 : } else {
8505 : panic!("We always remove the same operation")
8506 : }
8507 : }
8508 :
8509 0 : tracing::info!("Fill background operation starting");
8510 0 : let res = service.fill_node(node_id, cancel).await;
8511 0 : match res {
8512 : Ok(()) => {
8513 0 : tracing::info!("Fill background operation completed successfully");
8514 : }
8515 : Err(OperationError::Cancelled) => {
8516 0 : tracing::info!("Fill background operation was cancelled");
8517 : }
8518 0 : Err(err) => {
8519 0 : tracing::error!("Fill background operation encountered: {err}")
8520 : }
8521 : }
8522 0 : }
8523 0 : }.instrument(span));
8524 : }
8525 : NodeSchedulingPolicy::Filling => {
8526 0 : return Err(ApiError::Conflict(format!(
8527 0 : "Node {node_id} has fill in progress"
8528 0 : )));
8529 : }
8530 0 : policy => {
8531 0 : return Err(ApiError::PreconditionFailed(
8532 0 : format!("Node {node_id} cannot be filled due to {policy:?} policy").into(),
8533 0 : ));
8534 : }
8535 : }
8536 :
8537 0 : Ok(())
8538 0 : }
8539 :
8540 0 : pub(crate) async fn cancel_node_fill(&self, node_id: NodeId) -> Result<(), ApiError> {
8541 0 : let node_available = {
8542 0 : let locked = self.inner.read().unwrap();
8543 0 : let nodes = &locked.nodes;
8544 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
8545 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
8546 0 : ))?;
8547 :
8548 0 : node.is_available()
8549 : };
8550 :
8551 0 : if !node_available {
8552 0 : return Err(ApiError::ResourceUnavailable(
8553 0 : format!("Node {node_id} is currently unavailable").into(),
8554 0 : ));
8555 0 : }
8556 :
8557 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
8558 0 : if let Operation::Fill(fill) = op_handler.operation {
8559 0 : if fill.node_id == node_id {
8560 0 : tracing::info!("Cancelling background drain operation for node {node_id}");
8561 0 : op_handler.cancel.cancel();
8562 0 : return Ok(());
8563 0 : }
8564 0 : }
8565 0 : }
8566 :
8567 0 : Err(ApiError::PreconditionFailed(
8568 0 : format!("Node {node_id} has no fill in progress").into(),
8569 0 : ))
8570 0 : }
8571 :
8572 : /// Like [`Self::maybe_configured_reconcile_shard`], but uses the default reconciler
8573 : /// configuration
8574 0 : fn maybe_reconcile_shard(
8575 0 : &self,
8576 0 : shard: &mut TenantShard,
8577 0 : nodes: &Arc<HashMap<NodeId, Node>>,
8578 0 : priority: ReconcilerPriority,
8579 0 : ) -> Option<ReconcilerWaiter> {
8580 0 : self.maybe_configured_reconcile_shard(shard, nodes, ReconcilerConfig::new(priority))
8581 0 : }
8582 :
8583 : /// Before constructing a Reconciler, acquire semaphore units from the appropriate concurrency limit (depends on priority)
8584 0 : fn get_reconciler_units(
8585 0 : &self,
8586 0 : priority: ReconcilerPriority,
8587 0 : ) -> Result<ReconcileUnits, TryAcquireError> {
8588 0 : let units = match priority {
8589 0 : ReconcilerPriority::Normal => self.reconciler_concurrency.clone().try_acquire_owned(),
8590 : ReconcilerPriority::High => {
8591 0 : match self
8592 0 : .priority_reconciler_concurrency
8593 0 : .clone()
8594 0 : .try_acquire_owned()
8595 : {
8596 0 : Ok(u) => Ok(u),
8597 : Err(TryAcquireError::NoPermits) => {
8598 : // If the high priority semaphore is exhausted, then high priority tasks may steal units from
8599 : // the normal priority semaphore.
8600 0 : self.reconciler_concurrency.clone().try_acquire_owned()
8601 : }
8602 0 : Err(e) => Err(e),
8603 : }
8604 : }
8605 : };
8606 :
8607 0 : units.map(ReconcileUnits::new)
8608 0 : }
8609 :
8610 : /// Wrap [`TenantShard`] reconciliation methods with acquisition of [`Gate`] and [`ReconcileUnits`],
8611 0 : fn maybe_configured_reconcile_shard(
8612 0 : &self,
8613 0 : shard: &mut TenantShard,
8614 0 : nodes: &Arc<HashMap<NodeId, Node>>,
8615 0 : reconciler_config: ReconcilerConfig,
8616 0 : ) -> Option<ReconcilerWaiter> {
8617 0 : let reconcile_needed = shard.get_reconcile_needed(nodes);
8618 :
8619 0 : let reconcile_reason = match reconcile_needed {
8620 0 : ReconcileNeeded::No => return None,
8621 0 : ReconcileNeeded::WaitExisting(waiter) => return Some(waiter),
8622 0 : ReconcileNeeded::Yes(reason) => {
8623 : // Fall through to try and acquire units for spawning reconciler
8624 0 : reason
8625 : }
8626 : };
8627 :
8628 0 : let units = match self.get_reconciler_units(reconciler_config.priority) {
8629 0 : Ok(u) => u,
8630 : Err(_) => {
8631 0 : tracing::info!(tenant_id=%shard.tenant_shard_id.tenant_id, shard_id=%shard.tenant_shard_id.shard_slug(),
8632 0 : "Concurrency limited: enqueued for reconcile later");
8633 0 : if !shard.delayed_reconcile {
8634 0 : match self.delayed_reconcile_tx.try_send(shard.tenant_shard_id) {
8635 0 : Err(TrySendError::Closed(_)) => {
8636 0 : // Weird mid-shutdown case?
8637 0 : }
8638 : Err(TrySendError::Full(_)) => {
8639 : // It is safe to skip sending our ID in the channel: we will eventually get retried by the background reconcile task.
8640 0 : tracing::warn!(
8641 0 : "Many shards are waiting to reconcile: delayed_reconcile queue is full"
8642 : );
8643 : }
8644 0 : Ok(()) => {
8645 0 : shard.delayed_reconcile = true;
8646 0 : }
8647 : }
8648 0 : }
8649 :
8650 : // We won't spawn a reconciler, but we will construct a waiter that waits for the shard's sequence
8651 : // number to advance. When this function is eventually called again and succeeds in getting units,
8652 : // it will spawn a reconciler that makes this waiter complete.
8653 0 : return Some(shard.future_reconcile_waiter());
8654 : }
8655 : };
8656 :
8657 0 : let Ok(gate_guard) = self.reconcilers_gate.enter() else {
8658 : // Gate closed: we're shutting down, drop out.
8659 0 : return None;
8660 : };
8661 :
8662 0 : shard.spawn_reconciler(
8663 0 : reconcile_reason,
8664 0 : &self.result_tx,
8665 0 : nodes,
8666 0 : &self.compute_hook,
8667 0 : reconciler_config,
8668 0 : &self.config,
8669 0 : &self.persistence,
8670 0 : units,
8671 0 : gate_guard,
8672 0 : &self.reconcilers_cancel,
8673 0 : self.http_client.clone(),
8674 : )
8675 0 : }
8676 :
8677 : /// Check all tenants for pending reconciliation work, and reconcile those in need.
8678 : /// Additionally, reschedule tenants that require it.
8679 : ///
8680 : /// Returns how many reconciliation tasks were started, or `1` if no reconciles were
8681 : /// spawned but some _would_ have been spawned if `reconciler_concurrency` units where
8682 : /// available. A return value of 0 indicates that everything is fully reconciled already.
8683 0 : fn reconcile_all(&self) -> ReconcileAllResult {
8684 0 : let mut locked = self.inner.write().unwrap();
8685 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
8686 0 : let pageservers = nodes.clone();
8687 :
8688 : // This function is an efficient place to update lazy statistics, since we are walking
8689 : // all tenants.
8690 0 : let mut pending_reconciles = 0;
8691 0 : let mut stuck_reconciles = 0;
8692 0 : let mut az_violations = 0;
8693 :
8694 : // If we find any tenants to drop from memory, stash them to offload after
8695 : // we're done traversing the map of tenants.
8696 0 : let mut drop_detached_tenants = Vec::new();
8697 :
8698 0 : let mut spawned_reconciles = 0;
8699 0 : let mut has_delayed_reconciles = false;
8700 :
8701 0 : for shard in tenants.values_mut() {
8702 : // Accumulate scheduling statistics
8703 0 : if let (Some(attached), Some(preferred)) =
8704 0 : (shard.intent.get_attached(), shard.preferred_az())
8705 : {
8706 0 : let node_az = nodes
8707 0 : .get(attached)
8708 0 : .expect("Nodes exist if referenced")
8709 0 : .get_availability_zone_id();
8710 0 : if node_az != preferred {
8711 0 : az_violations += 1;
8712 0 : }
8713 0 : }
8714 :
8715 : // Skip checking if this shard is already enqueued for reconciliation
8716 0 : if shard.delayed_reconcile && self.reconciler_concurrency.available_permits() == 0 {
8717 : // If there is something delayed, then return a nonzero count so that
8718 : // callers like reconcile_all_now do not incorrectly get the impression
8719 : // that the system is in a quiescent state.
8720 0 : has_delayed_reconciles = true;
8721 0 : pending_reconciles += 1;
8722 0 : continue;
8723 0 : }
8724 :
8725 : // Eventual consistency: if an earlier reconcile job failed, and the shard is still
8726 : // dirty, spawn another one
8727 0 : if self
8728 0 : .maybe_reconcile_shard(shard, &pageservers, ReconcilerPriority::Normal)
8729 0 : .is_some()
8730 : {
8731 0 : spawned_reconciles += 1;
8732 :
8733 0 : if shard.consecutive_reconciles_count >= MAX_CONSECUTIVE_RECONCILES {
8734 : // Count shards that are stuck, butwe still want to reconcile them.
8735 : // We don't want to consider them when deciding to run optimizations.
8736 0 : tracing::warn!(
8737 : tenant_id=%shard.tenant_shard_id.tenant_id,
8738 0 : shard_id=%shard.tenant_shard_id.shard_slug(),
8739 0 : "Shard reconciliation is stuck: {} consecutive launches",
8740 : shard.consecutive_reconciles_count
8741 : );
8742 0 : stuck_reconciles += 1;
8743 0 : }
8744 : } else {
8745 0 : if shard.delayed_reconcile {
8746 0 : // Shard wanted to reconcile but for some reason couldn't.
8747 0 : pending_reconciles += 1;
8748 0 : }
8749 :
8750 : // Reset the counter when we don't need to launch a reconcile.
8751 0 : shard.consecutive_reconciles_count = 0;
8752 : }
8753 : // If this tenant is detached, try dropping it from memory. This is usually done
8754 : // proactively in [`Self::process_results`], but we do it here to handle the edge
8755 : // case where a reconcile completes while someone else is holding an op lock for the tenant.
8756 0 : if shard.tenant_shard_id.shard_number == ShardNumber(0)
8757 0 : && shard.policy == PlacementPolicy::Detached
8758 : {
8759 0 : if let Some(guard) = self.tenant_op_locks.try_exclusive(
8760 0 : shard.tenant_shard_id.tenant_id,
8761 0 : TenantOperations::DropDetached,
8762 0 : ) {
8763 0 : drop_detached_tenants.push((shard.tenant_shard_id.tenant_id, guard));
8764 0 : }
8765 0 : }
8766 : }
8767 :
8768 : // Some metrics are calculated from SchedulerNode state, update these periodically
8769 0 : scheduler.update_metrics();
8770 :
8771 : // Process any deferred tenant drops
8772 0 : for (tenant_id, guard) in drop_detached_tenants {
8773 0 : self.maybe_drop_tenant(tenant_id, &mut locked, &guard);
8774 0 : }
8775 :
8776 0 : metrics::METRICS_REGISTRY
8777 0 : .metrics_group
8778 0 : .storage_controller_schedule_az_violation
8779 0 : .set(az_violations as i64);
8780 :
8781 0 : metrics::METRICS_REGISTRY
8782 0 : .metrics_group
8783 0 : .storage_controller_pending_reconciles
8784 0 : .set(pending_reconciles as i64);
8785 :
8786 0 : metrics::METRICS_REGISTRY
8787 0 : .metrics_group
8788 0 : .storage_controller_stuck_reconciles
8789 0 : .set(stuck_reconciles as i64);
8790 :
8791 0 : ReconcileAllResult::new(spawned_reconciles, stuck_reconciles, has_delayed_reconciles)
8792 0 : }
8793 :
8794 : /// `optimize` in this context means identifying shards which have valid scheduled locations, but
8795 : /// could be scheduled somewhere better:
8796 : /// - Cutting over to a secondary if the node with the secondary is more lightly loaded
8797 : /// * e.g. after a node fails then recovers, to move some work back to it
8798 : /// - Cutting over to a secondary if it improves the spread of shard attachments within a tenant
8799 : /// * e.g. after a shard split, the initial attached locations will all be on the node where
8800 : /// we did the split, but are probably better placed elsewhere.
8801 : /// - Creating new secondary locations if it improves the spreading of a sharded tenant
8802 : /// * e.g. after a shard split, some locations will be on the same node (where the split
8803 : /// happened), and will probably be better placed elsewhere.
8804 : ///
8805 : /// To put it more briefly: whereas the scheduler respects soft constraints in a ScheduleContext at
8806 : /// the time of scheduling, this function looks for cases where a better-scoring location is available
8807 : /// according to those same soft constraints.
8808 0 : async fn optimize_all(&self) -> usize {
8809 : // Limit on how many shards' optmizations each call to this function will execute. Combined
8810 : // with the frequency of background calls, this acts as an implicit rate limit that runs a small
8811 : // trickle of optimizations in the background, rather than executing a large number in parallel
8812 : // when a change occurs.
8813 : const MAX_OPTIMIZATIONS_EXEC_PER_PASS: usize = 16;
8814 :
8815 : // Synchronous prepare: scan shards for possible scheduling optimizations
8816 0 : let candidate_work = self.optimize_all_plan();
8817 0 : let candidate_work_len = candidate_work.len();
8818 :
8819 : // Asynchronous validate: I/O to pageservers to make sure shards are in a good state to apply validation
8820 0 : let validated_work = self.optimize_all_validate(candidate_work).await;
8821 :
8822 0 : let was_work_filtered = validated_work.len() != candidate_work_len;
8823 :
8824 : // Synchronous apply: update the shards' intent states according to validated optimisations
8825 0 : let mut reconciles_spawned = 0;
8826 0 : let mut optimizations_applied = 0;
8827 0 : let mut locked = self.inner.write().unwrap();
8828 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
8829 0 : for (tenant_shard_id, optimization) in validated_work {
8830 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
8831 : // Shard was dropped between planning and execution;
8832 0 : continue;
8833 : };
8834 0 : tracing::info!(tenant_shard_id=%tenant_shard_id, "Applying optimization: {optimization:?}");
8835 0 : if shard.apply_optimization(scheduler, optimization) {
8836 0 : optimizations_applied += 1;
8837 0 : if self
8838 0 : .maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal)
8839 0 : .is_some()
8840 0 : {
8841 0 : reconciles_spawned += 1;
8842 0 : }
8843 0 : }
8844 :
8845 0 : if optimizations_applied >= MAX_OPTIMIZATIONS_EXEC_PER_PASS {
8846 0 : break;
8847 0 : }
8848 : }
8849 :
8850 0 : if was_work_filtered {
8851 0 : // If we filtered any work out during validation, ensure we return a nonzero value to indicate
8852 0 : // to callers that the system is not in a truly quiet state, it's going to do some work as soon
8853 0 : // as these validations start passing.
8854 0 : reconciles_spawned = std::cmp::max(reconciles_spawned, 1);
8855 0 : }
8856 :
8857 0 : reconciles_spawned
8858 0 : }
8859 :
8860 0 : fn optimize_all_plan(&self) -> Vec<(TenantShardId, ScheduleOptimization)> {
8861 : // How many candidate optimizations we will generate, before evaluating them for readniess: setting
8862 : // this higher than the execution limit gives us a chance to execute some work even if the first
8863 : // few optimizations we find are not ready.
8864 : const MAX_OPTIMIZATIONS_PLAN_PER_PASS: usize = 64;
8865 :
8866 0 : let mut work = Vec::new();
8867 0 : let mut locked = self.inner.write().unwrap();
8868 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
8869 :
8870 : // We are going to plan a bunch of optimisations before applying any of them, so the
8871 : // utilisation stats on nodes will be effectively stale for the >1st optimisation we
8872 : // generate. To avoid this causing unstable migrations/flapping, it's important that the
8873 : // code in TenantShard for finding optimisations uses [`NodeAttachmentSchedulingScore::disregard_utilization`]
8874 : // to ignore the utilisation component of the score.
8875 :
8876 0 : for (_tenant_id, schedule_context, shards) in
8877 0 : TenantShardExclusiveIterator::new(tenants, ScheduleMode::Speculative)
8878 : {
8879 0 : for shard in shards {
8880 0 : if work.len() >= MAX_OPTIMIZATIONS_PLAN_PER_PASS {
8881 0 : break;
8882 0 : }
8883 0 : match shard.get_scheduling_policy() {
8884 0 : ShardSchedulingPolicy::Active => {
8885 0 : // Ok to do optimization
8886 0 : }
8887 0 : ShardSchedulingPolicy::Essential if shard.get_preferred_node().is_some() => {
8888 0 : // Ok to do optimization: we are executing a graceful migration that
8889 0 : // has set preferred_node
8890 0 : }
8891 : ShardSchedulingPolicy::Essential
8892 : | ShardSchedulingPolicy::Pause
8893 : | ShardSchedulingPolicy::Stop => {
8894 : // Policy prevents optimizing this shard.
8895 0 : continue;
8896 : }
8897 : }
8898 :
8899 0 : if !matches!(shard.splitting, SplitState::Idle)
8900 0 : || matches!(shard.policy, PlacementPolicy::Detached)
8901 0 : || shard.reconciler.is_some()
8902 : {
8903 : // Do not start any optimizations while another change to the tenant is ongoing: this
8904 : // is not necessary for correctness, but simplifies operations and implicitly throttles
8905 : // optimization changes to happen in a "trickle" over time.
8906 0 : continue;
8907 0 : }
8908 :
8909 : // Fast path: we may quickly identify shards that don't have any possible optimisations
8910 0 : if !shard.maybe_optimizable(scheduler, &schedule_context) {
8911 0 : if cfg!(feature = "testing") {
8912 : // Check that maybe_optimizable doesn't disagree with the actual optimization functions.
8913 : // Only do this in testing builds because it is not a correctness-critical check, so we shouldn't
8914 : // panic in prod if we hit this, or spend cycles on it in prod.
8915 0 : assert!(
8916 0 : shard
8917 0 : .optimize_attachment(scheduler, &schedule_context)
8918 0 : .is_none()
8919 : );
8920 0 : assert!(
8921 0 : shard
8922 0 : .optimize_secondary(scheduler, &schedule_context)
8923 0 : .is_none()
8924 : );
8925 0 : }
8926 0 : continue;
8927 0 : }
8928 :
8929 0 : if let Some(optimization) =
8930 : // If idle, maybe optimize attachments: if a shard has a secondary location that is preferable to
8931 : // its primary location based on soft constraints, cut it over.
8932 0 : shard.optimize_attachment(scheduler, &schedule_context)
8933 : {
8934 0 : tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for attachment: {optimization:?}");
8935 0 : work.push((shard.tenant_shard_id, optimization));
8936 0 : break;
8937 0 : } else if let Some(optimization) =
8938 : // If idle, maybe optimize secondary locations: if a shard has a secondary location that would be
8939 : // better placed on another node, based on ScheduleContext, then adjust it. This
8940 : // covers cases like after a shard split, where we might have too many shards
8941 : // in the same tenant with secondary locations on the node where they originally split.
8942 0 : shard.optimize_secondary(scheduler, &schedule_context)
8943 : {
8944 0 : tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for secondary: {optimization:?}");
8945 0 : work.push((shard.tenant_shard_id, optimization));
8946 0 : break;
8947 0 : }
8948 : }
8949 : }
8950 :
8951 0 : work
8952 0 : }
8953 :
8954 0 : async fn optimize_all_validate(
8955 0 : &self,
8956 0 : candidate_work: Vec<(TenantShardId, ScheduleOptimization)>,
8957 0 : ) -> Vec<(TenantShardId, ScheduleOptimization)> {
8958 : // Take a clone of the node map to use outside the lock in async validation phase
8959 0 : let validation_nodes = { self.inner.read().unwrap().nodes.clone() };
8960 :
8961 0 : let mut want_secondary_status = Vec::new();
8962 :
8963 : // Validate our plans: this is an async phase where we may do I/O to pageservers to
8964 : // check that the state of locations is acceptable to run the optimization, such as
8965 : // checking that a secondary location is sufficiently warmed-up to cleanly cut over
8966 : // in a live migration.
8967 0 : let mut validated_work = Vec::new();
8968 0 : for (tenant_shard_id, optimization) in candidate_work {
8969 0 : match optimization.action {
8970 : ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
8971 : old_attached_node_id: _,
8972 0 : new_attached_node_id,
8973 : }) => {
8974 0 : match validation_nodes.get(&new_attached_node_id) {
8975 0 : None => {
8976 0 : // Node was dropped between planning and validation
8977 0 : }
8978 0 : Some(node) => {
8979 0 : if !node.is_available() {
8980 0 : tracing::info!(
8981 0 : "Skipping optimization migration of {tenant_shard_id} to {new_attached_node_id} because node unavailable"
8982 : );
8983 0 : } else {
8984 0 : // Accumulate optimizations that require fetching secondary status, so that we can execute these
8985 0 : // remote API requests concurrently.
8986 0 : want_secondary_status.push((
8987 0 : tenant_shard_id,
8988 0 : node.clone(),
8989 0 : optimization,
8990 0 : ));
8991 0 : }
8992 : }
8993 : }
8994 : }
8995 : ScheduleOptimizationAction::ReplaceSecondary(_)
8996 : | ScheduleOptimizationAction::CreateSecondary(_)
8997 : | ScheduleOptimizationAction::RemoveSecondary(_) => {
8998 : // No extra checks needed to manage secondaries: this does not interrupt client access
8999 0 : validated_work.push((tenant_shard_id, optimization))
9000 : }
9001 : };
9002 : }
9003 :
9004 : // Call into pageserver API to find out if the destination secondary location is warm enough for a reasonably smooth migration: we
9005 : // do this so that we avoid spawning a Reconciler that would have to wait minutes/hours for a destination to warm up: that reconciler
9006 : // would hold a precious reconcile semaphore unit the whole time it was waiting for the destination to warm up.
9007 0 : let results = self
9008 0 : .tenant_for_shards_api(
9009 0 : want_secondary_status
9010 0 : .iter()
9011 0 : .map(|i| (i.0, i.1.clone()))
9012 0 : .collect(),
9013 0 : |tenant_shard_id, client| async move {
9014 0 : client.tenant_secondary_status(tenant_shard_id).await
9015 0 : },
9016 : 1,
9017 : 1,
9018 : SHORT_RECONCILE_TIMEOUT,
9019 0 : &self.cancel,
9020 : )
9021 0 : .await;
9022 :
9023 0 : for ((tenant_shard_id, node, optimization), (_, secondary_status)) in
9024 0 : want_secondary_status.into_iter().zip(results.into_iter())
9025 : {
9026 0 : match secondary_status {
9027 0 : Err(e) => {
9028 0 : tracing::info!(
9029 0 : "Skipping migration of {tenant_shard_id} to {node}, error querying secondary: {e}"
9030 : );
9031 : }
9032 0 : Ok(progress) => {
9033 : // We require secondary locations to have less than 10GiB of downloads pending before we will use
9034 : // them in an optimization
9035 : const DOWNLOAD_FRESHNESS_THRESHOLD: u64 = 10 * 1024 * 1024 * 1024;
9036 :
9037 0 : if progress.heatmap_mtime.is_none()
9038 0 : || progress.bytes_total < DOWNLOAD_FRESHNESS_THRESHOLD
9039 0 : && progress.bytes_downloaded != progress.bytes_total
9040 0 : || progress.bytes_total - progress.bytes_downloaded
9041 0 : > DOWNLOAD_FRESHNESS_THRESHOLD
9042 : {
9043 0 : tracing::info!(
9044 0 : "Skipping migration of {tenant_shard_id} to {node} because secondary isn't ready: {progress:?}"
9045 : );
9046 :
9047 0 : if progress.heatmap_mtime.is_none() {
9048 : // No heatmap might mean the attached location has never uploaded one, or that
9049 : // the secondary download hasn't happened yet. This is relatively unusual in the field,
9050 : // but fairly common in tests.
9051 0 : self.kick_secondary_download(tenant_shard_id).await;
9052 0 : }
9053 : } else {
9054 : // Location looks ready: proceed
9055 0 : tracing::info!(
9056 0 : "{tenant_shard_id} secondary on {node} is warm enough for migration: {progress:?}"
9057 : );
9058 0 : validated_work.push((tenant_shard_id, optimization))
9059 : }
9060 : }
9061 : }
9062 : }
9063 :
9064 0 : validated_work
9065 0 : }
9066 :
9067 : /// Some aspects of scheduling optimisation wait for secondary locations to be warm. This
9068 : /// happens on multi-minute timescales in the field, which is fine because optimisation is meant
9069 : /// to be a lazy background thing. However, when testing, it is not practical to wait around, so
9070 : /// we have this helper to move things along faster.
9071 0 : async fn kick_secondary_download(&self, tenant_shard_id: TenantShardId) {
9072 0 : if !self.config.kick_secondary_downloads {
9073 : // No-op if kick_secondary_downloads functionaliuty is not configured
9074 0 : return;
9075 0 : }
9076 :
9077 0 : let (attached_node, secondaries) = {
9078 0 : let locked = self.inner.read().unwrap();
9079 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
9080 0 : tracing::warn!(
9081 0 : "Skipping kick of secondary download for {tenant_shard_id}: not found"
9082 : );
9083 0 : return;
9084 : };
9085 :
9086 0 : let Some(attached) = shard.intent.get_attached() else {
9087 0 : tracing::warn!(
9088 0 : "Skipping kick of secondary download for {tenant_shard_id}: no attached"
9089 : );
9090 0 : return;
9091 : };
9092 :
9093 0 : let secondaries = shard
9094 0 : .intent
9095 0 : .get_secondary()
9096 0 : .iter()
9097 0 : .map(|n| locked.nodes.get(n).unwrap().clone())
9098 0 : .collect::<Vec<_>>();
9099 :
9100 0 : (locked.nodes.get(attached).unwrap().clone(), secondaries)
9101 : };
9102 :
9103 : // Make remote API calls to upload + download heatmaps: we ignore errors because this is just
9104 : // a 'kick' to let scheduling optimisation run more promptly.
9105 0 : match attached_node
9106 0 : .with_client_retries(
9107 0 : |client| async move { client.tenant_heatmap_upload(tenant_shard_id).await },
9108 0 : &self.http_client,
9109 0 : &self.config.pageserver_jwt_token,
9110 : 3,
9111 : 10,
9112 : SHORT_RECONCILE_TIMEOUT,
9113 0 : &self.cancel,
9114 : )
9115 0 : .await
9116 : {
9117 0 : Some(Err(e)) => {
9118 0 : tracing::info!(
9119 0 : "Failed to upload heatmap from {attached_node} for {tenant_shard_id}: {e}"
9120 : );
9121 : }
9122 : None => {
9123 0 : tracing::info!(
9124 0 : "Cancelled while uploading heatmap from {attached_node} for {tenant_shard_id}"
9125 : );
9126 : }
9127 : Some(Ok(_)) => {
9128 0 : tracing::info!(
9129 0 : "Successfully uploaded heatmap from {attached_node} for {tenant_shard_id}"
9130 : );
9131 : }
9132 : }
9133 :
9134 0 : for secondary_node in secondaries {
9135 0 : match secondary_node
9136 0 : .with_client_retries(
9137 0 : |client| async move {
9138 0 : client
9139 0 : .tenant_secondary_download(
9140 0 : tenant_shard_id,
9141 0 : Some(Duration::from_secs(1)),
9142 0 : )
9143 0 : .await
9144 0 : },
9145 0 : &self.http_client,
9146 0 : &self.config.pageserver_jwt_token,
9147 : 3,
9148 : 10,
9149 : SHORT_RECONCILE_TIMEOUT,
9150 0 : &self.cancel,
9151 : )
9152 0 : .await
9153 : {
9154 0 : Some(Err(e)) => {
9155 0 : tracing::info!(
9156 0 : "Failed to download heatmap from {secondary_node} for {tenant_shard_id}: {e}"
9157 : );
9158 : }
9159 : None => {
9160 0 : tracing::info!(
9161 0 : "Cancelled while downloading heatmap from {secondary_node} for {tenant_shard_id}"
9162 : );
9163 : }
9164 0 : Some(Ok(progress)) => {
9165 0 : tracing::info!(
9166 0 : "Successfully downloaded heatmap from {secondary_node} for {tenant_shard_id}: {progress:?}"
9167 : );
9168 : }
9169 : }
9170 : }
9171 0 : }
9172 :
9173 : /// Asynchronously split a tenant that's eligible for automatic splits. At most one tenant will
9174 : /// be split per call.
9175 : ///
9176 : /// Two sets of criteria are used: initial splits and size-based splits (in that order).
9177 : /// Initial splits are used to eagerly split unsharded tenants that may be performing initial
9178 : /// ingestion, since sharded tenants have significantly better ingestion throughput. Size-based
9179 : /// splits are used to bound the maximum shard size and balance out load.
9180 : ///
9181 : /// Splits are based on max_logical_size, i.e. the logical size of the largest timeline in a
9182 : /// tenant. We use this instead of the total logical size because branches will duplicate
9183 : /// logical size without actually using more storage. We could also use visible physical size,
9184 : /// but this might overestimate tenants that frequently churn branches.
9185 : ///
9186 : /// Initial splits (initial_split_threshold):
9187 : /// * Applies to tenants with 1 shard.
9188 : /// * The largest timeline (max_logical_size) exceeds initial_split_threshold.
9189 : /// * Splits into initial_split_shards.
9190 : ///
9191 : /// Size-based splits (split_threshold):
9192 : /// * Applies to all tenants.
9193 : /// * The largest timeline (max_logical_size) divided by shard count exceeds split_threshold.
9194 : /// * Splits such that max_logical_size / shard_count <= split_threshold, in powers of 2.
9195 : ///
9196 : /// Tenant shards are ordered by descending max_logical_size, first initial split candidates
9197 : /// then size-based split candidates. The first matching candidate is split.
9198 : ///
9199 : /// The shard count is clamped to max_split_shards. If a candidate is eligible for both initial
9200 : /// and size-based splits, the largest shard count will be used.
9201 : ///
9202 : /// An unsharded tenant will get DEFAULT_STRIPE_SIZE, regardless of what its ShardIdentity says.
9203 : /// A sharded tenant will retain its stripe size, as splits do not allow changing it.
9204 : ///
9205 : /// TODO: consider spawning multiple splits in parallel: this is only called once every 20
9206 : /// seconds, so a large backlog can take a long time, and if a tenant fails to split it will
9207 : /// block all other splits.
9208 0 : async fn autosplit_tenants(self: &Arc<Self>) {
9209 : // If max_split_shards is set to 0 or 1, we can't split.
9210 0 : let max_split_shards = self.config.max_split_shards;
9211 0 : if max_split_shards <= 1 {
9212 0 : return;
9213 0 : }
9214 :
9215 : // If initial_split_shards is set to 0 or 1, disable initial splits.
9216 0 : let mut initial_split_threshold = self.config.initial_split_threshold.unwrap_or(0);
9217 0 : let initial_split_shards = self.config.initial_split_shards;
9218 0 : if initial_split_shards <= 1 {
9219 0 : initial_split_threshold = 0;
9220 0 : }
9221 :
9222 : // If no split_threshold nor initial_split_threshold, disable autosplits.
9223 0 : let split_threshold = self.config.split_threshold.unwrap_or(0);
9224 0 : if split_threshold == 0 && initial_split_threshold == 0 {
9225 0 : return;
9226 0 : }
9227 :
9228 : // Fetch split candidates in prioritized order.
9229 : //
9230 : // If initial splits are enabled, fetch eligible tenants first. We prioritize initial splits
9231 : // over size-based splits, since these are often performing initial ingestion and rely on
9232 : // splits to improve ingest throughput.
9233 0 : let mut candidates = Vec::new();
9234 :
9235 0 : if initial_split_threshold > 0 {
9236 : // Initial splits: fetch tenants with 1 shard where the logical size of the largest
9237 : // timeline exceeds the initial split threshold.
9238 0 : let initial_candidates = self
9239 0 : .get_top_tenant_shards(&TopTenantShardsRequest {
9240 0 : order_by: TenantSorting::MaxLogicalSize,
9241 0 : limit: 10,
9242 0 : where_shards_lt: Some(ShardCount(2)),
9243 0 : where_gt: Some(initial_split_threshold),
9244 0 : })
9245 0 : .await;
9246 0 : candidates.extend(initial_candidates);
9247 0 : }
9248 :
9249 0 : if split_threshold > 0 {
9250 : // Size-based splits: fetch tenants where the logical size of the largest timeline
9251 : // divided by shard count exceeds the split threshold.
9252 : //
9253 : // max_logical_size is only tracked on shard 0, and contains the total logical size
9254 : // across all shards. We have to order and filter by MaxLogicalSizePerShard, i.e.
9255 : // max_logical_size / shard_count, such that we only receive tenants that are actually
9256 : // eligible for splits. But we still use max_logical_size for later split calculations.
9257 0 : let size_candidates = self
9258 0 : .get_top_tenant_shards(&TopTenantShardsRequest {
9259 0 : order_by: TenantSorting::MaxLogicalSizePerShard,
9260 0 : limit: 10,
9261 0 : where_shards_lt: Some(ShardCount(max_split_shards)),
9262 0 : where_gt: Some(split_threshold),
9263 0 : })
9264 0 : .await;
9265 : #[cfg(feature = "testing")]
9266 0 : assert!(
9267 0 : size_candidates.iter().all(|c| c.id.is_shard_zero()),
9268 0 : "MaxLogicalSizePerShard returned non-zero shard: {size_candidates:?}",
9269 : );
9270 0 : candidates.extend(size_candidates);
9271 0 : }
9272 :
9273 : // Filter out tenants in a prohibiting scheduling modes
9274 : // and tenants with an ongoing import.
9275 : //
9276 : // Note that the import check here is oportunistic. An import might start
9277 : // after the check before we actually update [`TenantShard::splitting`].
9278 : // [`Self::tenant_shard_split`] checks the database whilst holding the exclusive
9279 : // tenant lock. Imports might take a long time, so the check here allows us
9280 : // to split something else instead of trying the same shard over and over.
9281 : {
9282 0 : let state = self.inner.read().unwrap();
9283 0 : candidates.retain(|i| {
9284 0 : let shard = state.tenants.get(&i.id);
9285 0 : match shard {
9286 0 : Some(t) => {
9287 0 : t.get_scheduling_policy() == ShardSchedulingPolicy::Active
9288 0 : && t.importing == TimelineImportState::Idle
9289 : }
9290 0 : None => false,
9291 : }
9292 0 : });
9293 : }
9294 :
9295 : // Pick the first candidate to split. This will generally always be the first one in
9296 : // candidates, but we defensively skip candidates that end up not actually splitting.
9297 0 : let Some((candidate, new_shard_count)) = candidates
9298 0 : .into_iter()
9299 0 : .filter_map(|candidate| {
9300 0 : let new_shard_count = Self::compute_split_shards(ShardSplitInputs {
9301 0 : shard_count: candidate.id.shard_count,
9302 0 : max_logical_size: candidate.max_logical_size,
9303 0 : split_threshold,
9304 0 : max_split_shards,
9305 0 : initial_split_threshold,
9306 0 : initial_split_shards,
9307 0 : });
9308 0 : new_shard_count.map(|shards| (candidate, shards.count()))
9309 0 : })
9310 0 : .next()
9311 : else {
9312 0 : debug!("no split-eligible tenants found");
9313 0 : return;
9314 : };
9315 :
9316 : // Retain the stripe size of sharded tenants, as splits don't allow changing it. Otherwise,
9317 : // use DEFAULT_STRIPE_SIZE for unsharded tenants -- their stripe size doesn't really matter,
9318 : // and if we change the default stripe size we want to use the new default rather than an
9319 : // old, persisted stripe size.
9320 0 : let new_stripe_size = match candidate.id.shard_count.count() {
9321 0 : 0 => panic!("invalid shard count 0"),
9322 0 : 1 => Some(DEFAULT_STRIPE_SIZE),
9323 0 : 2.. => None,
9324 : };
9325 :
9326 : // We spawn a task to run this, so it's exactly like some external API client requesting
9327 : // it. We don't want to block the background reconcile loop on this.
9328 0 : let old_shard_count = candidate.id.shard_count.count();
9329 0 : info!(
9330 0 : "auto-splitting tenant {old_shard_count} → {new_shard_count} shards, \
9331 0 : current size {candidate:?} (split_threshold={split_threshold} \
9332 0 : initial_split_threshold={initial_split_threshold})"
9333 : );
9334 :
9335 0 : let this = self.clone();
9336 0 : tokio::spawn(
9337 0 : async move {
9338 0 : match this
9339 0 : .tenant_shard_split(
9340 0 : candidate.id.tenant_id,
9341 0 : TenantShardSplitRequest {
9342 0 : new_shard_count,
9343 0 : new_stripe_size,
9344 0 : },
9345 0 : )
9346 0 : .await
9347 : {
9348 : Ok(_) => {
9349 0 : info!("successful auto-split {old_shard_count} → {new_shard_count} shards")
9350 : }
9351 0 : Err(err) => error!("auto-split failed: {err}"),
9352 : }
9353 0 : }
9354 0 : .instrument(info_span!("auto_split", tenant_id=%candidate.id.tenant_id)),
9355 : );
9356 0 : }
9357 :
9358 : /// Returns the number of shards to split a tenant into, or None if the tenant shouldn't split,
9359 : /// based on the total logical size of the largest timeline summed across all shards. Uses the
9360 : /// larger of size-based and initial splits, clamped to max_split_shards.
9361 : ///
9362 : /// NB: the thresholds are exclusive, since TopTenantShardsRequest uses where_gt.
9363 25 : fn compute_split_shards(inputs: ShardSplitInputs) -> Option<ShardCount> {
9364 : let ShardSplitInputs {
9365 25 : shard_count,
9366 25 : max_logical_size,
9367 25 : split_threshold,
9368 25 : max_split_shards,
9369 25 : initial_split_threshold,
9370 25 : initial_split_shards,
9371 25 : } = inputs;
9372 :
9373 25 : let mut new_shard_count: u8 = shard_count.count();
9374 :
9375 : // Size-based splits. Ensures max_logical_size / new_shard_count <= split_threshold, using
9376 : // power-of-two shard counts.
9377 : //
9378 : // If the current shard count is not a power of two, and does not exceed split_threshold,
9379 : // then we leave it alone rather than forcing a power-of-two split.
9380 25 : if split_threshold > 0
9381 18 : && max_logical_size.div_ceil(split_threshold) > shard_count.count() as u64
9382 12 : {
9383 12 : new_shard_count = max_logical_size
9384 12 : .div_ceil(split_threshold)
9385 12 : .checked_next_power_of_two()
9386 12 : .unwrap_or(u8::MAX as u64)
9387 12 : .try_into()
9388 12 : .unwrap_or(u8::MAX);
9389 13 : }
9390 :
9391 : // Initial splits. Use the larger of size-based and initial split shard counts. This only
9392 : // applies to unsharded tenants, i.e. changes to initial_split_threshold or
9393 : // initial_split_shards are not retroactive for sharded tenants.
9394 25 : if initial_split_threshold > 0
9395 14 : && shard_count.count() <= 1
9396 11 : && max_logical_size > initial_split_threshold
9397 8 : {
9398 8 : new_shard_count = new_shard_count.max(initial_split_shards);
9399 17 : }
9400 :
9401 : // Clamp to max shards.
9402 25 : new_shard_count = new_shard_count.min(max_split_shards);
9403 :
9404 : // Don't split if we're not increasing the shard count.
9405 25 : if new_shard_count <= shard_count.count() {
9406 10 : return None;
9407 15 : }
9408 :
9409 15 : Some(ShardCount(new_shard_count))
9410 25 : }
9411 :
9412 : /// Fetches the top tenant shards from every available node, in descending order of
9413 : /// max logical size. Offline nodes are skipped, and any errors from available nodes
9414 : /// will be logged and ignored.
9415 0 : async fn get_top_tenant_shards(
9416 0 : &self,
9417 0 : request: &TopTenantShardsRequest,
9418 0 : ) -> Vec<TopTenantShardItem> {
9419 0 : let nodes = self
9420 0 : .inner
9421 0 : .read()
9422 0 : .unwrap()
9423 0 : .nodes
9424 0 : .values()
9425 0 : .filter(|node| node.is_available())
9426 0 : .cloned()
9427 0 : .collect_vec();
9428 :
9429 0 : let mut futures = FuturesUnordered::new();
9430 0 : for node in nodes {
9431 0 : futures.push(async move {
9432 0 : node.with_client_retries(
9433 0 : |client| async move { client.top_tenant_shards(request.clone()).await },
9434 0 : &self.http_client,
9435 0 : &self.config.pageserver_jwt_token,
9436 : 3,
9437 : 3,
9438 0 : Duration::from_secs(5),
9439 0 : &self.cancel,
9440 : )
9441 0 : .await
9442 0 : });
9443 : }
9444 :
9445 0 : let mut top = Vec::new();
9446 0 : while let Some(output) = futures.next().await {
9447 0 : match output {
9448 0 : Some(Ok(response)) => top.extend(response.shards),
9449 0 : Some(Err(mgmt_api::Error::Cancelled)) => {}
9450 0 : Some(Err(err)) => warn!("failed to fetch top tenants: {err}"),
9451 0 : None => {} // node is shutting down
9452 : }
9453 : }
9454 :
9455 0 : top.sort_by_key(|i| i.max_logical_size);
9456 0 : top.reverse();
9457 0 : top
9458 0 : }
9459 :
9460 : /// Useful for tests: run whatever work a background [`Self::reconcile_all`] would have done, but
9461 : /// also wait for any generated Reconcilers to complete. Calling this until it returns zero should
9462 : /// put the system into a quiescent state where future background reconciliations won't do anything.
9463 0 : pub(crate) async fn reconcile_all_now(&self) -> Result<usize, ReconcileWaitError> {
9464 0 : let reconcile_all_result = self.reconcile_all();
9465 0 : let mut spawned_reconciles = reconcile_all_result.spawned_reconciles;
9466 0 : if reconcile_all_result.can_run_optimizations() {
9467 : // Only optimize when we are otherwise idle
9468 0 : let optimization_reconciles = self.optimize_all().await;
9469 0 : spawned_reconciles += optimization_reconciles;
9470 0 : }
9471 :
9472 0 : let waiters = {
9473 0 : let mut waiters = Vec::new();
9474 0 : let locked = self.inner.read().unwrap();
9475 0 : for (_tenant_shard_id, shard) in locked.tenants.iter() {
9476 0 : if let Some(waiter) = shard.get_waiter() {
9477 0 : waiters.push(waiter);
9478 0 : }
9479 : }
9480 0 : waiters
9481 : };
9482 :
9483 0 : let waiter_count = waiters.len();
9484 0 : match self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
9485 0 : Ok(()) => {}
9486 0 : Err(e) => {
9487 0 : if let ReconcileWaitError::Failed(_, reconcile_error) = &e {
9488 0 : match **reconcile_error {
9489 : ReconcileError::Cancel
9490 0 : | ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
9491 0 : // Ignore reconciler cancel errors: this reconciler might have shut down
9492 0 : // because some other change superceded it. We will return a nonzero number,
9493 0 : // so the caller knows they might have to call again to quiesce the system.
9494 0 : }
9495 : _ => {
9496 0 : return Err(e);
9497 : }
9498 : }
9499 : } else {
9500 0 : return Err(e);
9501 : }
9502 : }
9503 : };
9504 :
9505 0 : tracing::info!(
9506 0 : "{} reconciles in reconcile_all, {} waiters",
9507 : spawned_reconciles,
9508 : waiter_count
9509 : );
9510 :
9511 0 : Ok(std::cmp::max(waiter_count, spawned_reconciles))
9512 0 : }
9513 :
9514 0 : async fn stop_reconciliations(&self, reason: StopReconciliationsReason) {
9515 : // Cancel all on-going reconciles and wait for them to exit the gate.
9516 0 : tracing::info!("{reason}: cancelling and waiting for in-flight reconciles");
9517 0 : self.reconcilers_cancel.cancel();
9518 0 : self.reconcilers_gate.close().await;
9519 :
9520 : // Signal the background loop in [`Service::process_results`] to exit once
9521 : // it has proccessed the results from all the reconciles we cancelled earlier.
9522 0 : tracing::info!("{reason}: processing results from previously in-flight reconciles");
9523 0 : self.result_tx.send(ReconcileResultRequest::Stop).ok();
9524 0 : self.result_tx.closed().await;
9525 0 : }
9526 :
9527 0 : pub async fn shutdown(&self) {
9528 0 : self.stop_reconciliations(StopReconciliationsReason::ShuttingDown)
9529 0 : .await;
9530 :
9531 : // Background tasks hold gate guards: this notifies them of the cancellation and
9532 : // waits for them all to complete.
9533 0 : tracing::info!("Shutting down: cancelling and waiting for background tasks to exit");
9534 0 : self.cancel.cancel();
9535 0 : self.gate.close().await;
9536 0 : }
9537 :
9538 : /// Spot check the download lag for a secondary location of a shard.
9539 : /// Should be used as a heuristic, since it's not always precise: the
9540 : /// secondary might have not downloaded the new heat map yet and, hence,
9541 : /// is not aware of the lag.
9542 : ///
9543 : /// Returns:
9544 : /// * Ok(None) if the lag could not be determined from the status,
9545 : /// * Ok(Some(_)) if the lag could be determind
9546 : /// * Err on failures to query the pageserver.
9547 0 : async fn secondary_lag(
9548 0 : &self,
9549 0 : secondary: &NodeId,
9550 0 : tenant_shard_id: TenantShardId,
9551 0 : ) -> Result<Option<u64>, mgmt_api::Error> {
9552 0 : let nodes = self.inner.read().unwrap().nodes.clone();
9553 0 : let node = nodes.get(secondary).ok_or(mgmt_api::Error::ApiError(
9554 0 : StatusCode::NOT_FOUND,
9555 0 : format!("Node with id {secondary} not found"),
9556 0 : ))?;
9557 :
9558 0 : match node
9559 0 : .with_client_retries(
9560 0 : |client| async move { client.tenant_secondary_status(tenant_shard_id).await },
9561 0 : &self.http_client,
9562 0 : &self.config.pageserver_jwt_token,
9563 : 1,
9564 : 3,
9565 0 : Duration::from_millis(250),
9566 0 : &self.cancel,
9567 : )
9568 0 : .await
9569 : {
9570 0 : Some(Ok(status)) => match status.heatmap_mtime {
9571 0 : Some(_) => Ok(Some(status.bytes_total - status.bytes_downloaded)),
9572 0 : None => Ok(None),
9573 : },
9574 0 : Some(Err(e)) => Err(e),
9575 0 : None => Err(mgmt_api::Error::Cancelled),
9576 : }
9577 0 : }
9578 :
9579 : /// Drain a node by moving the shards attached to it as primaries.
9580 : /// This is a long running operation and it should run as a separate Tokio task.
9581 0 : pub(crate) async fn drain_node(
9582 0 : self: &Arc<Self>,
9583 0 : node_id: NodeId,
9584 0 : cancel: CancellationToken,
9585 0 : ) -> Result<(), OperationError> {
9586 : const MAX_SECONDARY_LAG_BYTES_DEFAULT: u64 = 256 * 1024 * 1024;
9587 0 : let max_secondary_lag_bytes = self
9588 0 : .config
9589 0 : .max_secondary_lag_bytes
9590 0 : .unwrap_or(MAX_SECONDARY_LAG_BYTES_DEFAULT);
9591 :
9592 : // By default, live migrations are generous about the wait time for getting
9593 : // the secondary location up to speed. When draining, give up earlier in order
9594 : // to not stall the operation when a cold secondary is encountered.
9595 : const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(30);
9596 : const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
9597 0 : let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
9598 0 : .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
9599 0 : .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
9600 0 : .build();
9601 :
9602 0 : let mut waiters = Vec::new();
9603 :
9604 0 : let mut tid_iter = create_shared_shard_iterator(self.clone());
9605 :
9606 0 : while !tid_iter.finished() {
9607 0 : if cancel.is_cancelled() {
9608 0 : match self
9609 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
9610 0 : .await
9611 : {
9612 0 : Ok(()) => return Err(OperationError::Cancelled),
9613 0 : Err(err) => {
9614 0 : return Err(OperationError::FinalizeError(
9615 0 : format!(
9616 0 : "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
9617 0 : )
9618 0 : .into(),
9619 0 : ));
9620 : }
9621 : }
9622 0 : }
9623 :
9624 0 : operation_utils::validate_node_state(
9625 0 : &node_id,
9626 0 : self.inner.read().unwrap().nodes.clone(),
9627 0 : NodeSchedulingPolicy::Draining,
9628 0 : )?;
9629 :
9630 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
9631 0 : let tid = match tid_iter.next() {
9632 0 : Some(tid) => tid,
9633 : None => {
9634 0 : break;
9635 : }
9636 : };
9637 :
9638 0 : let tid_drain = TenantShardDrain {
9639 0 : drained_node: node_id,
9640 0 : tenant_shard_id: tid,
9641 0 : };
9642 :
9643 0 : let dest_node_id = {
9644 0 : let locked = self.inner.read().unwrap();
9645 :
9646 0 : match tid_drain
9647 0 : .tenant_shard_eligible_for_drain(&locked.tenants, &locked.scheduler)
9648 : {
9649 0 : Some(node_id) => node_id,
9650 : None => {
9651 0 : continue;
9652 : }
9653 : }
9654 : };
9655 :
9656 0 : match self.secondary_lag(&dest_node_id, tid).await {
9657 0 : Ok(Some(lag)) if lag <= max_secondary_lag_bytes => {
9658 0 : // The secondary is reasonably up to date.
9659 0 : // Migrate to it
9660 0 : }
9661 0 : Ok(Some(lag)) => {
9662 0 : tracing::info!(
9663 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9664 0 : "Secondary on node {dest_node_id} is lagging by {lag}. Skipping reconcile."
9665 : );
9666 0 : continue;
9667 : }
9668 : Ok(None) => {
9669 0 : tracing::info!(
9670 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9671 0 : "Could not determine lag for secondary on node {dest_node_id}. Skipping reconcile."
9672 : );
9673 0 : continue;
9674 : }
9675 0 : Err(err) => {
9676 0 : tracing::warn!(
9677 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9678 0 : "Failed to get secondary lag from node {dest_node_id}. Skipping reconcile: {err}"
9679 : );
9680 0 : continue;
9681 : }
9682 : }
9683 :
9684 : {
9685 0 : let mut locked = self.inner.write().unwrap();
9686 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
9687 0 : let rescheduled = tid_drain.reschedule_to_secondary(
9688 0 : dest_node_id,
9689 0 : tenants,
9690 0 : scheduler,
9691 0 : nodes,
9692 0 : )?;
9693 :
9694 0 : if let Some(tenant_shard) = rescheduled {
9695 0 : let waiter = self.maybe_configured_reconcile_shard(
9696 0 : tenant_shard,
9697 0 : nodes,
9698 0 : reconciler_config,
9699 0 : );
9700 0 : if let Some(some) = waiter {
9701 0 : waiters.push(some);
9702 0 : }
9703 0 : }
9704 : }
9705 : }
9706 :
9707 0 : waiters = self
9708 0 : .await_waiters_remainder(waiters, WAITER_OPERATION_POLL_TIMEOUT)
9709 0 : .await;
9710 :
9711 0 : failpoint_support::sleep_millis_async!("sleepy-drain-loop", &cancel);
9712 : }
9713 :
9714 0 : while !waiters.is_empty() {
9715 0 : if cancel.is_cancelled() {
9716 0 : match self
9717 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
9718 0 : .await
9719 : {
9720 0 : Ok(()) => return Err(OperationError::Cancelled),
9721 0 : Err(err) => {
9722 0 : return Err(OperationError::FinalizeError(
9723 0 : format!(
9724 0 : "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
9725 0 : )
9726 0 : .into(),
9727 0 : ));
9728 : }
9729 : }
9730 0 : }
9731 :
9732 0 : tracing::info!("Awaiting {} pending drain reconciliations", waiters.len());
9733 :
9734 0 : waiters = self
9735 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
9736 0 : .await;
9737 : }
9738 :
9739 : // At this point we have done the best we could to drain shards from this node.
9740 : // Set the node scheduling policy to `[NodeSchedulingPolicy::PauseForRestart]`
9741 : // to complete the drain.
9742 0 : if let Err(err) = self
9743 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::PauseForRestart))
9744 0 : .await
9745 : {
9746 : // This is not fatal. Anything that is polling the node scheduling policy to detect
9747 : // the end of the drain operations will hang, but all such places should enforce an
9748 : // overall timeout. The scheduling policy will be updated upon node re-attach and/or
9749 : // by the counterpart fill operation.
9750 0 : return Err(OperationError::FinalizeError(
9751 0 : format!(
9752 0 : "Failed to finalise drain of {node_id} by setting scheduling policy to PauseForRestart: {err}"
9753 0 : )
9754 0 : .into(),
9755 0 : ));
9756 0 : }
9757 :
9758 0 : Ok(())
9759 0 : }
9760 :
9761 : /// Create a node fill plan (pick secondaries to promote), based on:
9762 : /// 1. Shards which have a secondary on this node, and this node is in their home AZ, and are currently attached to a node
9763 : /// outside their home AZ, should be migrated back here.
9764 : /// 2. If after step 1 we have not migrated enough shards for this node to have its fair share of
9765 : /// attached shards, we will promote more shards from the nodes with the most attached shards, unless
9766 : /// those shards have a home AZ that doesn't match the node we're filling.
9767 0 : fn fill_node_plan(&self, node_id: NodeId) -> Vec<TenantShardId> {
9768 0 : let mut locked = self.inner.write().unwrap();
9769 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
9770 :
9771 0 : let node_az = nodes
9772 0 : .get(&node_id)
9773 0 : .expect("Node must exist")
9774 0 : .get_availability_zone_id()
9775 0 : .clone();
9776 :
9777 : // The tenant shard IDs that we plan to promote from secondary to attached on this node
9778 0 : let mut plan = Vec::new();
9779 :
9780 : // Collect shards which do not have a preferred AZ & are elegible for moving in stage 2
9781 0 : let mut free_tids_by_node: HashMap<NodeId, Vec<TenantShardId>> = HashMap::new();
9782 :
9783 : // Don't respect AZ preferences if there is only one AZ. This comes up in tests, but it could
9784 : // conceivably come up in real life if deploying a single-AZ region intentionally.
9785 0 : let respect_azs = nodes
9786 0 : .values()
9787 0 : .map(|n| n.get_availability_zone_id())
9788 0 : .unique()
9789 0 : .count()
9790 : > 1;
9791 :
9792 : // Step 1: collect all shards that we are required to migrate back to this node because their AZ preference
9793 : // requires it.
9794 0 : for (tsid, tenant_shard) in tenants {
9795 0 : if !tenant_shard.intent.get_secondary().contains(&node_id) {
9796 : // Shard doesn't have a secondary on this node, ignore it.
9797 0 : continue;
9798 0 : }
9799 :
9800 : // AZ check: when filling nodes after a restart, our intent is to move _back_ the
9801 : // shards which belong on this node, not to promote shards whose scheduling preference
9802 : // would be on their currently attached node. So will avoid promoting shards whose
9803 : // home AZ doesn't match the AZ of the node we're filling.
9804 0 : match tenant_shard.preferred_az() {
9805 0 : _ if !respect_azs => {
9806 0 : if let Some(primary) = tenant_shard.intent.get_attached() {
9807 0 : free_tids_by_node.entry(*primary).or_default().push(*tsid);
9808 0 : }
9809 : }
9810 : None => {
9811 : // Shard doesn't have an AZ preference: it is elegible to be moved, but we
9812 : // will only do so if our target shard count requires it.
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 0 : Some(az) if az == &node_az => {
9818 : // This shard's home AZ is equal to the node we're filling: it should
9819 : // be moved back to this node as part of filling, unless its currently
9820 : // attached location is also in its home AZ.
9821 0 : if let Some(primary) = tenant_shard.intent.get_attached() {
9822 0 : if nodes
9823 0 : .get(primary)
9824 0 : .expect("referenced node must exist")
9825 0 : .get_availability_zone_id()
9826 0 : != tenant_shard
9827 0 : .preferred_az()
9828 0 : .expect("tenant must have an AZ preference")
9829 : {
9830 0 : plan.push(*tsid)
9831 0 : }
9832 : } else {
9833 0 : plan.push(*tsid)
9834 : }
9835 : }
9836 0 : Some(_) => {
9837 0 : // This shard's home AZ is somewhere other than the node we're filling,
9838 0 : // it may not be moved back to this node as part of filling. Ignore it
9839 0 : }
9840 : }
9841 : }
9842 :
9843 : // Step 2: also promote any AZ-agnostic shards as required to achieve the target number of attachments
9844 0 : let fill_requirement = locked.scheduler.compute_fill_requirement(node_id);
9845 :
9846 0 : let expected_attached = locked.scheduler.expected_attached_shard_count();
9847 0 : let nodes_by_load = locked.scheduler.nodes_by_attached_shard_count();
9848 :
9849 0 : let mut promoted_per_tenant: HashMap<TenantId, usize> = HashMap::new();
9850 :
9851 0 : for (node_id, attached) in nodes_by_load {
9852 0 : let available = locked.nodes.get(&node_id).is_some_and(|n| n.is_available());
9853 0 : if !available {
9854 0 : continue;
9855 0 : }
9856 :
9857 0 : if plan.len() >= fill_requirement
9858 0 : || free_tids_by_node.is_empty()
9859 0 : || attached <= expected_attached
9860 : {
9861 0 : break;
9862 0 : }
9863 :
9864 0 : let can_take = attached - expected_attached;
9865 0 : let needed = fill_requirement - plan.len();
9866 0 : let mut take = std::cmp::min(can_take, needed);
9867 :
9868 0 : let mut remove_node = false;
9869 0 : while take > 0 {
9870 0 : match free_tids_by_node.get_mut(&node_id) {
9871 0 : Some(tids) => match tids.pop() {
9872 0 : Some(tid) => {
9873 0 : let max_promote_for_tenant = std::cmp::max(
9874 0 : tid.shard_count.count() as usize / locked.nodes.len(),
9875 : 1,
9876 : );
9877 0 : let promoted = promoted_per_tenant.entry(tid.tenant_id).or_default();
9878 0 : if *promoted < max_promote_for_tenant {
9879 0 : plan.push(tid);
9880 0 : *promoted += 1;
9881 0 : take -= 1;
9882 0 : }
9883 : }
9884 : None => {
9885 0 : remove_node = true;
9886 0 : break;
9887 : }
9888 : },
9889 : None => {
9890 0 : break;
9891 : }
9892 : }
9893 : }
9894 :
9895 0 : if remove_node {
9896 0 : free_tids_by_node.remove(&node_id);
9897 0 : }
9898 : }
9899 :
9900 0 : plan
9901 0 : }
9902 :
9903 : /// Fill a node by promoting its secondaries until the cluster is balanced
9904 : /// with regards to attached shard counts. Note that this operation only
9905 : /// makes sense as a counterpart to the drain implemented in [`Service::drain_node`].
9906 : /// This is a long running operation and it should run as a separate Tokio task.
9907 0 : pub(crate) async fn fill_node(
9908 0 : &self,
9909 0 : node_id: NodeId,
9910 0 : cancel: CancellationToken,
9911 0 : ) -> Result<(), OperationError> {
9912 : const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(30);
9913 : const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
9914 0 : let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
9915 0 : .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
9916 0 : .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
9917 0 : .build();
9918 :
9919 0 : let mut tids_to_promote = self.fill_node_plan(node_id);
9920 0 : let mut waiters = Vec::new();
9921 :
9922 : // Execute the plan we've composed above. Before aplying each move from the plan,
9923 : // we validate to ensure that it has not gone stale in the meantime.
9924 0 : while !tids_to_promote.is_empty() {
9925 0 : if cancel.is_cancelled() {
9926 0 : match self
9927 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
9928 0 : .await
9929 : {
9930 0 : Ok(()) => return Err(OperationError::Cancelled),
9931 0 : Err(err) => {
9932 0 : return Err(OperationError::FinalizeError(
9933 0 : format!(
9934 0 : "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
9935 0 : )
9936 0 : .into(),
9937 0 : ));
9938 : }
9939 : }
9940 0 : }
9941 :
9942 : {
9943 0 : let mut locked = self.inner.write().unwrap();
9944 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
9945 :
9946 0 : let node = nodes.get(&node_id).ok_or(OperationError::NodeStateChanged(
9947 0 : format!("node {node_id} was removed").into(),
9948 0 : ))?;
9949 :
9950 0 : let current_policy = node.get_scheduling();
9951 0 : if !matches!(current_policy, NodeSchedulingPolicy::Filling) {
9952 : // TODO(vlad): maybe cancel pending reconciles before erroring out. need to think
9953 : // about it
9954 0 : return Err(OperationError::NodeStateChanged(
9955 0 : format!("node {node_id} changed state to {current_policy:?}").into(),
9956 0 : ));
9957 0 : }
9958 :
9959 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
9960 0 : if let Some(tid) = tids_to_promote.pop() {
9961 0 : if let Some(tenant_shard) = tenants.get_mut(&tid) {
9962 : // If the node being filled is not a secondary anymore,
9963 : // skip the promotion.
9964 0 : if !tenant_shard.intent.get_secondary().contains(&node_id) {
9965 0 : continue;
9966 0 : }
9967 :
9968 0 : let previously_attached_to = *tenant_shard.intent.get_attached();
9969 0 : match tenant_shard.reschedule_to_secondary(Some(node_id), scheduler) {
9970 0 : Err(e) => {
9971 0 : tracing::warn!(
9972 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9973 0 : "Scheduling error when filling pageserver {} : {e}", node_id
9974 : );
9975 : }
9976 : Ok(()) => {
9977 0 : tracing::info!(
9978 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
9979 0 : "Rescheduled shard while filling node {}: {:?} -> {}",
9980 : node_id,
9981 : previously_attached_to,
9982 : node_id
9983 : );
9984 :
9985 0 : if let Some(waiter) = self.maybe_configured_reconcile_shard(
9986 0 : tenant_shard,
9987 0 : nodes,
9988 0 : reconciler_config,
9989 0 : ) {
9990 0 : waiters.push(waiter);
9991 0 : }
9992 : }
9993 : }
9994 0 : }
9995 : } else {
9996 0 : break;
9997 : }
9998 : }
9999 : }
10000 :
10001 0 : waiters = self
10002 0 : .await_waiters_remainder(waiters, WAITER_OPERATION_POLL_TIMEOUT)
10003 0 : .await;
10004 : }
10005 :
10006 0 : while !waiters.is_empty() {
10007 0 : if cancel.is_cancelled() {
10008 0 : match self
10009 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
10010 0 : .await
10011 : {
10012 0 : Ok(()) => return Err(OperationError::Cancelled),
10013 0 : Err(err) => {
10014 0 : return Err(OperationError::FinalizeError(
10015 0 : format!(
10016 0 : "Failed to finalise drain cancel of {node_id} by setting scheduling policy to Active: {err}"
10017 0 : )
10018 0 : .into(),
10019 0 : ));
10020 : }
10021 : }
10022 0 : }
10023 :
10024 0 : tracing::info!("Awaiting {} pending fill reconciliations", waiters.len());
10025 :
10026 0 : waiters = self
10027 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
10028 0 : .await;
10029 : }
10030 :
10031 0 : if let Err(err) = self
10032 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
10033 0 : .await
10034 : {
10035 : // This isn't a huge issue since the filling process starts upon request. However, it
10036 : // will prevent the next drain from starting. The only case in which this can fail
10037 : // is database unavailability. Such a case will require manual intervention.
10038 0 : return Err(OperationError::FinalizeError(
10039 0 : format!("Failed to finalise fill of {node_id} by setting scheduling policy to Active: {err}")
10040 0 : .into(),
10041 0 : ));
10042 0 : }
10043 :
10044 0 : Ok(())
10045 0 : }
10046 :
10047 : /// Updates scrubber metadata health check results.
10048 0 : pub(crate) async fn metadata_health_update(
10049 0 : &self,
10050 0 : update_req: MetadataHealthUpdateRequest,
10051 0 : ) -> Result<(), ApiError> {
10052 0 : let now = chrono::offset::Utc::now();
10053 0 : let (healthy_records, unhealthy_records) = {
10054 0 : let locked = self.inner.read().unwrap();
10055 0 : let healthy_records = update_req
10056 0 : .healthy_tenant_shards
10057 0 : .into_iter()
10058 : // Retain only health records associated with tenant shards managed by storage controller.
10059 0 : .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
10060 0 : .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, true, now))
10061 0 : .collect();
10062 0 : let unhealthy_records = update_req
10063 0 : .unhealthy_tenant_shards
10064 0 : .into_iter()
10065 0 : .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
10066 0 : .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, false, now))
10067 0 : .collect();
10068 :
10069 0 : (healthy_records, unhealthy_records)
10070 : };
10071 :
10072 0 : self.persistence
10073 0 : .update_metadata_health_records(healthy_records, unhealthy_records, now)
10074 0 : .await?;
10075 0 : Ok(())
10076 0 : }
10077 :
10078 : /// Lists the tenant shards that has unhealthy metadata status.
10079 0 : pub(crate) async fn metadata_health_list_unhealthy(
10080 0 : &self,
10081 0 : ) -> Result<Vec<TenantShardId>, ApiError> {
10082 0 : let result = self
10083 0 : .persistence
10084 0 : .list_unhealthy_metadata_health_records()
10085 0 : .await?
10086 0 : .iter()
10087 0 : .map(|p| p.get_tenant_shard_id().unwrap())
10088 0 : .collect();
10089 :
10090 0 : Ok(result)
10091 0 : }
10092 :
10093 : /// Lists the tenant shards that have not been scrubbed for some duration.
10094 0 : pub(crate) async fn metadata_health_list_outdated(
10095 0 : &self,
10096 0 : not_scrubbed_for: Duration,
10097 0 : ) -> Result<Vec<MetadataHealthRecord>, ApiError> {
10098 0 : let earlier = chrono::offset::Utc::now() - not_scrubbed_for;
10099 0 : let result = self
10100 0 : .persistence
10101 0 : .list_outdated_metadata_health_records(earlier)
10102 0 : .await?
10103 0 : .into_iter()
10104 0 : .map(|record| record.into())
10105 0 : .collect();
10106 0 : Ok(result)
10107 0 : }
10108 :
10109 0 : pub(crate) fn get_leadership_status(&self) -> LeadershipStatus {
10110 0 : self.inner.read().unwrap().get_leadership_status()
10111 0 : }
10112 :
10113 : /// Handler for step down requests
10114 : ///
10115 : /// Step down runs in separate task since once it's called it should
10116 : /// be driven to completion. Subsequent requests will wait on the same
10117 : /// step down task.
10118 0 : pub(crate) async fn step_down(self: &Arc<Self>) -> GlobalObservedState {
10119 0 : let handle = self.step_down_barrier.get_or_init(|| {
10120 0 : let step_down_self = self.clone();
10121 0 : let (tx, rx) = tokio::sync::watch::channel::<Option<GlobalObservedState>>(None);
10122 0 : tokio::spawn(async move {
10123 0 : let state = step_down_self.step_down_task().await;
10124 0 : tx.send(Some(state))
10125 0 : .expect("Task Arc<Service> keeps receiver alive");
10126 0 : });
10127 :
10128 0 : rx
10129 0 : });
10130 :
10131 0 : handle
10132 0 : .clone()
10133 0 : .wait_for(|observed_state| observed_state.is_some())
10134 0 : .await
10135 0 : .expect("Task Arc<Service> keeps sender alive")
10136 0 : .deref()
10137 0 : .clone()
10138 0 : .expect("Checked above")
10139 0 : }
10140 :
10141 0 : async fn step_down_task(&self) -> GlobalObservedState {
10142 0 : tracing::info!("Received step down request from peer");
10143 0 : failpoint_support::sleep_millis_async!("sleep-on-step-down-handling");
10144 :
10145 0 : self.inner.write().unwrap().step_down();
10146 :
10147 0 : let stop_reconciliations =
10148 0 : self.stop_reconciliations(StopReconciliationsReason::SteppingDown);
10149 0 : let mut stop_reconciliations = std::pin::pin!(stop_reconciliations);
10150 :
10151 0 : let started_at = Instant::now();
10152 :
10153 : // Wait for reconciliations to stop and warn if that's taking a long time
10154 : loop {
10155 0 : tokio::select! {
10156 0 : _ = &mut stop_reconciliations => {
10157 0 : tracing::info!("Reconciliations stopped, proceeding with step down");
10158 0 : break;
10159 : }
10160 0 : _ = tokio::time::sleep(Duration::from_secs(10)) => {
10161 0 : tracing::warn!(
10162 0 : elapsed_sec=%started_at.elapsed().as_secs(),
10163 0 : "Stopping reconciliations during step down is taking too long"
10164 : );
10165 : }
10166 : }
10167 : }
10168 :
10169 0 : let mut global_observed = GlobalObservedState::default();
10170 0 : let locked = self.inner.read().unwrap();
10171 0 : for (tid, tenant_shard) in locked.tenants.iter() {
10172 0 : global_observed
10173 0 : .0
10174 0 : .insert(*tid, tenant_shard.observed.clone());
10175 0 : }
10176 :
10177 0 : global_observed
10178 0 : }
10179 :
10180 0 : pub(crate) async fn update_shards_preferred_azs(
10181 0 : &self,
10182 0 : req: ShardsPreferredAzsRequest,
10183 0 : ) -> Result<ShardsPreferredAzsResponse, ApiError> {
10184 0 : let preferred_azs = req.preferred_az_ids.into_iter().collect::<Vec<_>>();
10185 0 : let updated = self
10186 0 : .persistence
10187 0 : .set_tenant_shard_preferred_azs(preferred_azs)
10188 0 : .await
10189 0 : .map_err(|err| {
10190 0 : ApiError::InternalServerError(anyhow::anyhow!(
10191 0 : "Failed to persist preferred AZs: {err}"
10192 0 : ))
10193 0 : })?;
10194 :
10195 0 : let mut updated_in_mem_and_db = Vec::default();
10196 :
10197 0 : let mut locked = self.inner.write().unwrap();
10198 0 : let state = locked.deref_mut();
10199 0 : for (tid, az_id) in updated {
10200 0 : let shard = state.tenants.get_mut(&tid);
10201 0 : if let Some(shard) = shard {
10202 0 : shard.set_preferred_az(&mut state.scheduler, az_id);
10203 0 : updated_in_mem_and_db.push(tid);
10204 0 : }
10205 : }
10206 :
10207 0 : Ok(ShardsPreferredAzsResponse {
10208 0 : updated: updated_in_mem_and_db,
10209 0 : })
10210 0 : }
10211 : }
10212 :
10213 : #[cfg(test)]
10214 : mod tests {
10215 : use super::*;
10216 :
10217 : /// Tests Service::compute_split_shards. For readability, this specifies sizes in GBs rather
10218 : /// than bytes. Note that max_logical_size is the total logical size of the largest timeline
10219 : /// summed across all shards.
10220 : #[test]
10221 1 : fn compute_split_shards() {
10222 : // Size-based split: two shards have a 500 GB timeline, which need to split into 8 shards
10223 : // that are <= 64 GB,
10224 1 : assert_eq!(
10225 1 : Service::compute_split_shards(ShardSplitInputs {
10226 1 : shard_count: ShardCount(2),
10227 1 : max_logical_size: 500,
10228 1 : split_threshold: 64,
10229 1 : max_split_shards: 16,
10230 1 : initial_split_threshold: 0,
10231 1 : initial_split_shards: 0,
10232 1 : }),
10233 : Some(ShardCount(8))
10234 : );
10235 :
10236 : // Size-based split: noop at or below threshold, fires above.
10237 1 : assert_eq!(
10238 1 : Service::compute_split_shards(ShardSplitInputs {
10239 1 : shard_count: ShardCount(2),
10240 1 : max_logical_size: 127,
10241 1 : split_threshold: 64,
10242 1 : max_split_shards: 16,
10243 1 : initial_split_threshold: 0,
10244 1 : initial_split_shards: 0,
10245 1 : }),
10246 : None,
10247 : );
10248 1 : assert_eq!(
10249 1 : Service::compute_split_shards(ShardSplitInputs {
10250 1 : shard_count: ShardCount(2),
10251 1 : max_logical_size: 128,
10252 1 : split_threshold: 64,
10253 1 : max_split_shards: 16,
10254 1 : initial_split_threshold: 0,
10255 1 : initial_split_shards: 0,
10256 1 : }),
10257 : None,
10258 : );
10259 1 : assert_eq!(
10260 1 : Service::compute_split_shards(ShardSplitInputs {
10261 1 : shard_count: ShardCount(2),
10262 1 : max_logical_size: 129,
10263 1 : split_threshold: 64,
10264 1 : max_split_shards: 16,
10265 1 : initial_split_threshold: 0,
10266 1 : initial_split_shards: 0,
10267 1 : }),
10268 : Some(ShardCount(4)),
10269 : );
10270 :
10271 : // Size-based split: clamped to max_split_shards.
10272 1 : assert_eq!(
10273 1 : Service::compute_split_shards(ShardSplitInputs {
10274 1 : shard_count: ShardCount(2),
10275 1 : max_logical_size: 10000,
10276 1 : split_threshold: 64,
10277 1 : max_split_shards: 16,
10278 1 : initial_split_threshold: 0,
10279 1 : initial_split_shards: 0,
10280 1 : }),
10281 : Some(ShardCount(16))
10282 : );
10283 :
10284 : // Size-based split: tenant already at or beyond max_split_shards is not split.
10285 1 : assert_eq!(
10286 1 : Service::compute_split_shards(ShardSplitInputs {
10287 1 : shard_count: ShardCount(16),
10288 1 : max_logical_size: 10000,
10289 1 : split_threshold: 64,
10290 1 : max_split_shards: 16,
10291 1 : initial_split_threshold: 0,
10292 1 : initial_split_shards: 0,
10293 1 : }),
10294 : None
10295 : );
10296 :
10297 1 : assert_eq!(
10298 1 : Service::compute_split_shards(ShardSplitInputs {
10299 1 : shard_count: ShardCount(32),
10300 1 : max_logical_size: 10000,
10301 1 : split_threshold: 64,
10302 1 : max_split_shards: 16,
10303 1 : initial_split_threshold: 0,
10304 1 : initial_split_shards: 0,
10305 1 : }),
10306 : None
10307 : );
10308 :
10309 : // Size-based split: a non-power-of-2 shard count is normalized to power-of-2 if it
10310 : // exceeds split_threshold (i.e. a 3-shard tenant splits into 8, not 6).
10311 1 : assert_eq!(
10312 1 : Service::compute_split_shards(ShardSplitInputs {
10313 1 : shard_count: ShardCount(3),
10314 1 : max_logical_size: 320,
10315 1 : split_threshold: 64,
10316 1 : max_split_shards: 16,
10317 1 : initial_split_threshold: 0,
10318 1 : initial_split_shards: 0,
10319 1 : }),
10320 : Some(ShardCount(8))
10321 : );
10322 :
10323 : // Size-based split: a non-power-of-2 shard count is not normalized to power-of-2 if the
10324 : // existing shards are below or at split_threshold, but splits into 4 if it exceeds it.
10325 1 : assert_eq!(
10326 1 : Service::compute_split_shards(ShardSplitInputs {
10327 1 : shard_count: ShardCount(3),
10328 1 : max_logical_size: 191,
10329 1 : split_threshold: 64,
10330 1 : max_split_shards: 16,
10331 1 : initial_split_threshold: 0,
10332 1 : initial_split_shards: 0,
10333 1 : }),
10334 : None
10335 : );
10336 1 : assert_eq!(
10337 1 : Service::compute_split_shards(ShardSplitInputs {
10338 1 : shard_count: ShardCount(3),
10339 1 : max_logical_size: 192,
10340 1 : split_threshold: 64,
10341 1 : max_split_shards: 16,
10342 1 : initial_split_threshold: 0,
10343 1 : initial_split_shards: 0,
10344 1 : }),
10345 : None
10346 : );
10347 1 : assert_eq!(
10348 1 : Service::compute_split_shards(ShardSplitInputs {
10349 1 : shard_count: ShardCount(3),
10350 1 : max_logical_size: 193,
10351 1 : split_threshold: 64,
10352 1 : max_split_shards: 16,
10353 1 : initial_split_threshold: 0,
10354 1 : initial_split_shards: 0,
10355 1 : }),
10356 : Some(ShardCount(4))
10357 : );
10358 :
10359 : // Initial split: tenant has a 10 GB timeline, split into 4 shards.
10360 1 : assert_eq!(
10361 1 : Service::compute_split_shards(ShardSplitInputs {
10362 1 : shard_count: ShardCount(1),
10363 1 : max_logical_size: 10,
10364 1 : split_threshold: 0,
10365 1 : max_split_shards: 16,
10366 1 : initial_split_threshold: 8,
10367 1 : initial_split_shards: 4,
10368 1 : }),
10369 : Some(ShardCount(4))
10370 : );
10371 :
10372 : // Initial split: 0 ShardCount is equivalent to 1.
10373 1 : assert_eq!(
10374 1 : Service::compute_split_shards(ShardSplitInputs {
10375 1 : shard_count: ShardCount(0),
10376 1 : max_logical_size: 10,
10377 1 : split_threshold: 0,
10378 1 : max_split_shards: 16,
10379 1 : initial_split_threshold: 8,
10380 1 : initial_split_shards: 4,
10381 1 : }),
10382 : Some(ShardCount(4))
10383 : );
10384 :
10385 : // Initial split: at or below threshold is noop.
10386 1 : assert_eq!(
10387 1 : Service::compute_split_shards(ShardSplitInputs {
10388 1 : shard_count: ShardCount(1),
10389 1 : max_logical_size: 7,
10390 1 : split_threshold: 0,
10391 1 : max_split_shards: 16,
10392 1 : initial_split_threshold: 8,
10393 1 : initial_split_shards: 4,
10394 1 : }),
10395 : None,
10396 : );
10397 1 : assert_eq!(
10398 1 : Service::compute_split_shards(ShardSplitInputs {
10399 1 : shard_count: ShardCount(1),
10400 1 : max_logical_size: 8,
10401 1 : split_threshold: 0,
10402 1 : max_split_shards: 16,
10403 1 : initial_split_threshold: 8,
10404 1 : initial_split_shards: 4,
10405 1 : }),
10406 : None,
10407 : );
10408 1 : assert_eq!(
10409 1 : Service::compute_split_shards(ShardSplitInputs {
10410 1 : shard_count: ShardCount(1),
10411 1 : max_logical_size: 9,
10412 1 : split_threshold: 0,
10413 1 : max_split_shards: 16,
10414 1 : initial_split_threshold: 8,
10415 1 : initial_split_shards: 4,
10416 1 : }),
10417 : Some(ShardCount(4))
10418 : );
10419 :
10420 : // Initial split: already sharded tenant is not affected, even if above threshold and below
10421 : // shard count.
10422 1 : assert_eq!(
10423 1 : Service::compute_split_shards(ShardSplitInputs {
10424 1 : shard_count: ShardCount(2),
10425 1 : max_logical_size: 20,
10426 1 : split_threshold: 0,
10427 1 : max_split_shards: 16,
10428 1 : initial_split_threshold: 8,
10429 1 : initial_split_shards: 4,
10430 1 : }),
10431 : None,
10432 : );
10433 :
10434 : // Initial split: clamped to max_shards.
10435 1 : assert_eq!(
10436 1 : Service::compute_split_shards(ShardSplitInputs {
10437 1 : shard_count: ShardCount(1),
10438 1 : max_logical_size: 10,
10439 1 : split_threshold: 0,
10440 1 : max_split_shards: 3,
10441 1 : initial_split_threshold: 8,
10442 1 : initial_split_shards: 4,
10443 1 : }),
10444 : Some(ShardCount(3)),
10445 : );
10446 :
10447 : // Initial+size split: tenant eligible for both will use the larger shard count.
10448 1 : assert_eq!(
10449 1 : Service::compute_split_shards(ShardSplitInputs {
10450 1 : shard_count: ShardCount(1),
10451 1 : max_logical_size: 10,
10452 1 : split_threshold: 64,
10453 1 : max_split_shards: 16,
10454 1 : initial_split_threshold: 8,
10455 1 : initial_split_shards: 4,
10456 1 : }),
10457 : Some(ShardCount(4)),
10458 : );
10459 1 : assert_eq!(
10460 1 : Service::compute_split_shards(ShardSplitInputs {
10461 1 : shard_count: ShardCount(1),
10462 1 : max_logical_size: 500,
10463 1 : split_threshold: 64,
10464 1 : max_split_shards: 16,
10465 1 : initial_split_threshold: 8,
10466 1 : initial_split_shards: 4,
10467 1 : }),
10468 : Some(ShardCount(8)),
10469 : );
10470 :
10471 : // Initial+size split: sharded tenant is only eligible for size-based split.
10472 1 : assert_eq!(
10473 1 : Service::compute_split_shards(ShardSplitInputs {
10474 1 : shard_count: ShardCount(2),
10475 1 : max_logical_size: 200,
10476 1 : split_threshold: 64,
10477 1 : max_split_shards: 16,
10478 1 : initial_split_threshold: 8,
10479 1 : initial_split_shards: 8,
10480 1 : }),
10481 : Some(ShardCount(4)),
10482 : );
10483 :
10484 : // Initial+size split: uses the larger shard count even with initial_split_threshold above
10485 : // split_threshold.
10486 1 : assert_eq!(
10487 1 : Service::compute_split_shards(ShardSplitInputs {
10488 1 : shard_count: ShardCount(1),
10489 1 : max_logical_size: 10,
10490 1 : split_threshold: 4,
10491 1 : max_split_shards: 16,
10492 1 : initial_split_threshold: 8,
10493 1 : initial_split_shards: 8,
10494 1 : }),
10495 : Some(ShardCount(8)),
10496 : );
10497 :
10498 : // Test backwards compatibility with production settings when initial/size-based splits were
10499 : // rolled out: a single split into 8 shards at 64 GB. Any already sharded tenants with <8
10500 : // shards will split according to split_threshold.
10501 1 : assert_eq!(
10502 1 : Service::compute_split_shards(ShardSplitInputs {
10503 1 : shard_count: ShardCount(1),
10504 1 : max_logical_size: 65,
10505 1 : split_threshold: 64,
10506 1 : max_split_shards: 8,
10507 1 : initial_split_threshold: 64,
10508 1 : initial_split_shards: 8,
10509 1 : }),
10510 : Some(ShardCount(8)),
10511 : );
10512 :
10513 1 : assert_eq!(
10514 1 : Service::compute_split_shards(ShardSplitInputs {
10515 1 : shard_count: ShardCount(1),
10516 1 : max_logical_size: 64,
10517 1 : split_threshold: 64,
10518 1 : max_split_shards: 8,
10519 1 : initial_split_threshold: 64,
10520 1 : initial_split_shards: 8,
10521 1 : }),
10522 : None,
10523 : );
10524 :
10525 1 : assert_eq!(
10526 1 : Service::compute_split_shards(ShardSplitInputs {
10527 1 : shard_count: ShardCount(2),
10528 1 : max_logical_size: 129,
10529 1 : split_threshold: 64,
10530 1 : max_split_shards: 8,
10531 1 : initial_split_threshold: 64,
10532 1 : initial_split_shards: 8,
10533 1 : }),
10534 : Some(ShardCount(4)),
10535 : );
10536 1 : }
10537 : }
|