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