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