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